Disable singnedness warnings with newer gcc.
[tinycc.git] / tcc.c
blobb364c2be421cd03f8cfc6176af90fb7275b1b552
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 <unistd.h>
37 #include <signal.h>
38 #include <fcntl.h>
39 #include <setjmp.h>
40 #include <time.h>
41 #ifdef _WIN32
42 #include <sys/timeb.h>
43 // #include <windows.h>
44 #endif
45 #ifndef _WIN32
46 #include <sys/time.h>
47 #include <sys/ucontext.h>
48 #include <sys/mman.h>
49 #endif
51 #endif /* !CONFIG_TCCBOOT */
53 #ifndef PAGESIZE
54 #define PAGESIZE 4096
55 #endif
57 #include "elf.h"
58 #include "stab.h"
60 #ifndef O_BINARY
61 #define O_BINARY 0
62 #endif
64 #include "libtcc.h"
66 /* parser debug */
67 //#define PARSE_DEBUG
68 /* preprocessor debug */
69 //#define PP_DEBUG
70 /* include file debug */
71 //#define INC_DEBUG
73 //#define MEM_DEBUG
75 /* assembler debug */
76 //#define ASM_DEBUG
78 /* target selection */
79 //#define TCC_TARGET_I386 /* i386 code generator */
80 //#define TCC_TARGET_ARM /* ARMv4 code generator */
81 //#define TCC_TARGET_C67 /* TMS320C67xx code generator */
83 /* default target is I386 */
84 #if !defined(TCC_TARGET_I386) && !defined(TCC_TARGET_ARM) && \
85 !defined(TCC_TARGET_C67)
86 #define TCC_TARGET_I386
87 #endif
89 #if !defined(_WIN32) && !defined(TCC_UCLIBC) && !defined(TCC_TARGET_ARM) && \
90 !defined(TCC_TARGET_C67)
91 #define CONFIG_TCC_BCHECK /* enable bound checking code */
92 #endif
94 #if defined(_WIN32) && !defined(TCC_TARGET_PE)
95 #define CONFIG_TCC_STATIC
96 #endif
98 /* define it to include assembler support */
99 #if !defined(TCC_TARGET_ARM) && !defined(TCC_TARGET_C67)
100 #define CONFIG_TCC_ASM
101 #endif
103 /* object format selection */
104 #if defined(TCC_TARGET_C67)
105 #define TCC_TARGET_COFF
106 #endif
108 #define FALSE 0
109 #define false 0
110 #define TRUE 1
111 #define true 1
112 typedef int BOOL;
114 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
115 executables or dlls */
116 #define CONFIG_TCC_CRT_PREFIX "/usr/lib"
118 #define INCLUDE_STACK_SIZE 32
119 #define IFDEF_STACK_SIZE 64
120 #define VSTACK_SIZE 256
121 #define STRING_MAX_SIZE 1024
122 #define PACK_STACK_SIZE 8
124 #define TOK_HASH_SIZE 8192 /* must be a power of two */
125 #define TOK_ALLOC_INCR 512 /* must be a power of two */
126 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
128 /* token symbol management */
129 typedef struct TokenSym {
130 struct TokenSym *hash_next;
131 struct Sym *sym_define; /* direct pointer to define */
132 struct Sym *sym_label; /* direct pointer to label */
133 struct Sym *sym_struct; /* direct pointer to structure */
134 struct Sym *sym_identifier; /* direct pointer to identifier */
135 int tok; /* token number */
136 int len;
137 char str[1];
138 } TokenSym;
140 #ifdef TCC_TARGET_PE
141 typedef unsigned short nwchar_t;
142 #else
143 typedef int nwchar_t;
144 #endif
146 typedef struct CString {
147 int size; /* size in bytes */
148 void *data; /* either 'char *' or 'nwchar_t *' */
149 int size_allocated;
150 void *data_allocated; /* if non NULL, data has been malloced */
151 } CString;
153 /* type definition */
154 typedef struct CType {
155 int t;
156 struct Sym *ref;
157 } CType;
159 /* constant value */
160 typedef union CValue {
161 long double ld;
162 double d;
163 float f;
164 int i;
165 unsigned int ui;
166 unsigned int ul; /* address (should be unsigned long on 64 bit cpu) */
167 long long ll;
168 unsigned long long ull;
169 struct CString *cstr;
170 void *ptr;
171 int tab[1];
172 } CValue;
174 /* value on stack */
175 typedef struct SValue {
176 CType type; /* type */
177 unsigned short r; /* register + flags */
178 unsigned short r2; /* second register, used for 'long long'
179 type. If not used, set to VT_CONST */
180 CValue c; /* constant, if VT_CONST */
181 struct Sym *sym; /* symbol, if (VT_SYM | VT_CONST) */
182 } SValue;
184 /* symbol management */
185 typedef struct Sym {
186 int v; /* symbol token */
187 int r; /* associated register */
188 int c; /* associated number */
189 CType type; /* associated type */
190 struct Sym *next; /* next related symbol */
191 struct Sym *prev; /* prev symbol in stack */
192 struct Sym *prev_tok; /* previous symbol for this token */
193 } Sym;
195 /* section definition */
196 /* XXX: use directly ELF structure for parameters ? */
197 /* special flag to indicate that the section should not be linked to
198 the other ones */
199 #define SHF_PRIVATE 0x80000000
201 typedef struct Section {
202 unsigned long data_offset; /* current data offset */
203 unsigned char *data; /* section data */
204 unsigned long data_allocated; /* used for realloc() handling */
205 int sh_name; /* elf section name (only used during output) */
206 int sh_num; /* elf section number */
207 int sh_type; /* elf section type */
208 int sh_flags; /* elf section flags */
209 int sh_info; /* elf section info */
210 int sh_addralign; /* elf section alignment */
211 int sh_entsize; /* elf entry size */
212 unsigned long sh_size; /* section size (only used during output) */
213 unsigned long sh_addr; /* address at which the section is relocated */
214 unsigned long sh_offset; /* file offset */
215 int nb_hashed_syms; /* used to resize the hash table */
216 struct Section *link; /* link to another section */
217 struct Section *reloc; /* corresponding section for relocation, if any */
218 struct Section *hash; /* hash table for symbols */
219 struct Section *next;
220 char name[1]; /* section name */
221 } Section;
223 typedef struct DLLReference {
224 int level;
225 char name[1];
226 } DLLReference;
228 /* GNUC attribute definition */
229 typedef struct AttributeDef {
230 int aligned;
231 int packed;
232 Section *section;
233 unsigned char func_call; /* FUNC_CDECL, FUNC_STDCALL, FUNC_FASTCALLx */
234 unsigned char dllexport;
235 } AttributeDef;
237 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
238 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
239 #define SYM_FIRST_ANOM 0x10000000 /* first anonymous sym */
241 /* stored in 'Sym.c' field */
242 #define FUNC_NEW 1 /* ansi function prototype */
243 #define FUNC_OLD 2 /* old function prototype */
244 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
246 /* stored in 'Sym.r' field */
247 #define FUNC_CDECL 0 /* standard c call */
248 #define FUNC_STDCALL 1 /* pascal c call */
249 #define FUNC_FASTCALL1 2 /* first param in %eax */
250 #define FUNC_FASTCALL2 3 /* first parameters in %eax, %edx */
251 #define FUNC_FASTCALL3 4 /* first parameter in %eax, %edx, %ecx */
252 #define FUNC_FASTCALLW 5 /* first parameter in %ecx, %edx */
254 /* field 'Sym.t' for macros */
255 #define MACRO_OBJ 0 /* object like macro */
256 #define MACRO_FUNC 1 /* function like macro */
258 /* field 'Sym.r' for C labels */
259 #define LABEL_DEFINED 0 /* label is defined */
260 #define LABEL_FORWARD 1 /* label is forward defined */
261 #define LABEL_DECLARED 2 /* label is declared but never used */
263 /* type_decl() types */
264 #define TYPE_ABSTRACT 1 /* type without variable */
265 #define TYPE_DIRECT 2 /* type with variable */
267 #define IO_BUF_SIZE 8192
269 typedef struct BufferedFile {
270 uint8_t *buf_ptr;
271 uint8_t *buf_end;
272 int fd;
273 int line_num; /* current line number - here to simplify code */
274 int ifndef_macro; /* #ifndef macro / #endif search */
275 int ifndef_macro_saved; /* saved ifndef_macro */
276 int *ifdef_stack_ptr; /* ifdef_stack value at the start of the file */
277 char inc_type; /* type of include */
278 char inc_filename[512]; /* filename specified by the user */
279 char filename[1024]; /* current filename - here to simplify code */
280 unsigned char buffer[IO_BUF_SIZE + 1]; /* extra size for CH_EOB char */
281 } BufferedFile;
283 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
284 #define CH_EOF (-1) /* end of file */
286 /* parsing state (used to save parser state to reparse part of the
287 source several times) */
288 typedef struct ParseState {
289 int *macro_ptr;
290 int line_num;
291 int tok;
292 CValue tokc;
293 } ParseState;
295 /* used to record tokens */
296 typedef struct TokenString {
297 int *str;
298 int len;
299 int allocated_len;
300 int last_line_num;
301 } TokenString;
303 /* include file cache, used to find files faster and also to eliminate
304 inclusion if the include file is protected by #ifndef ... #endif */
305 typedef struct CachedInclude {
306 int ifndef_macro;
307 int hash_next; /* -1 if none */
308 char type; /* '"' or '>' to give include type */
309 char filename[1]; /* path specified in #include */
310 } CachedInclude;
312 #define CACHED_INCLUDES_HASH_SIZE 512
314 /* parser */
315 static struct BufferedFile *file;
316 static int ch, tok;
317 static CValue tokc;
318 static CString tokcstr; /* current parsed string, if any */
319 /* additional informations about token */
320 static int tok_flags;
321 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
322 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
323 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
324 #define TOK_FLAG_EOF 0x0008 /* end of file */
326 static int *macro_ptr, *macro_ptr_allocated;
327 static int *unget_saved_macro_ptr;
328 static int unget_saved_buffer[TOK_MAX_SIZE + 1];
329 static int unget_buffer_enabled;
330 static int parse_flags;
331 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
332 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
333 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
334 token. line feed is also
335 returned at eof */
336 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
338 static Section *text_section, *data_section, *bss_section; /* predefined sections */
339 static Section *cur_text_section; /* current section where function code is
340 generated */
341 #ifdef CONFIG_TCC_ASM
342 static Section *last_text_section; /* to handle .previous asm directive */
343 #endif
344 /* bound check related sections */
345 static Section *bounds_section; /* contains global data bound description */
346 static Section *lbounds_section; /* contains local data bound description */
347 /* symbol sections */
348 static Section *symtab_section, *strtab_section;
350 /* debug sections */
351 static Section *stab_section, *stabstr_section;
353 /* loc : local variable index
354 ind : output code index
355 rsym: return symbol
356 anon_sym: anonymous symbol index
358 static int rsym, anon_sym, ind, loc;
359 /* expression generation modifiers */
360 static int const_wanted; /* true if constant wanted */
361 static int nocode_wanted; /* true if no code generation wanted for an expression */
362 static int global_expr; /* true if compound literals must be allocated
363 globally (used during initializers parsing */
364 static CType func_vt; /* current function return type (used by return
365 instruction) */
366 static int func_vc;
367 static int last_line_num, last_ind, func_ind; /* debug last line number and pc */
368 static int tok_ident;
369 static TokenSym **table_ident;
370 static TokenSym *hash_ident[TOK_HASH_SIZE];
371 static char token_buf[STRING_MAX_SIZE + 1];
372 static char *funcname;
373 static Sym *global_stack, *local_stack;
374 static Sym *define_stack;
375 static Sym *global_label_stack, *local_label_stack;
376 /* symbol allocator */
377 #define SYM_POOL_NB (8192 / sizeof(Sym))
378 static Sym *sym_free_first;
380 static SValue vstack[VSTACK_SIZE], *vtop;
381 /* some predefined types */
382 static CType char_pointer_type, func_old_type, int_type;
383 /* true if isid(c) || isnum(c) */
384 static unsigned char isidnum_table[256];
386 /* compile with debug symbol (and use them if error during execution) */
387 static int do_debug = 0;
389 /* compile with built-in memory and bounds checker */
390 static int do_bounds_check = 0;
392 /* display benchmark infos */
393 #if !defined(LIBTCC)
394 static int do_bench = 0;
395 #endif
396 static int total_lines;
397 static int total_bytes;
399 /* use GNU C extensions */
400 static int gnu_ext = 1;
402 /* use Tiny C extensions */
403 static int tcc_ext = 1;
405 /* max number of callers shown if error */
406 static int num_callers = 6;
407 static const char **rt_bound_error_msg;
409 /* XXX: get rid of this ASAP */
410 static struct TCCState *tcc_state;
412 /* give the path of the tcc libraries */
413 static const char *tcc_lib_path = CONFIG_TCCDIR;
415 struct TCCState {
416 int output_type;
418 BufferedFile **include_stack_ptr;
419 int *ifdef_stack_ptr;
421 /* include file handling */
422 char **include_paths;
423 int nb_include_paths;
424 char **sysinclude_paths;
425 int nb_sysinclude_paths;
426 CachedInclude **cached_includes;
427 int nb_cached_includes;
429 char **library_paths;
430 int nb_library_paths;
432 /* array of all loaded dlls (including those referenced by loaded
433 dlls) */
434 DLLReference **loaded_dlls;
435 int nb_loaded_dlls;
437 /* sections */
438 Section **sections;
439 int nb_sections; /* number of sections, including first dummy section */
441 /* got handling */
442 Section *got;
443 Section *plt;
444 unsigned long *got_offsets;
445 int nb_got_offsets;
446 /* give the correspondance from symtab indexes to dynsym indexes */
447 int *symtab_to_dynsym;
449 /* temporary dynamic symbol sections (for dll loading) */
450 Section *dynsymtab_section;
451 /* exported dynamic symbol section */
452 Section *dynsym;
454 int nostdinc; /* if true, no standard headers are added */
455 int nostdlib; /* if true, no standard libraries are added */
457 int nocommon; /* if true, do not use common symbols for .bss data */
459 /* if true, static linking is performed */
460 int static_link;
462 /* if true, all symbols are exported */
463 int rdynamic;
465 /* if true, only link in referenced objects from archive */
466 int alacarte_link;
468 /* address of text section */
469 unsigned long text_addr;
470 int has_text_addr;
472 /* output format, see TCC_OUTPUT_FORMAT_xxx */
473 int output_format;
475 /* C language options */
476 int char_is_unsigned;
477 int leading_underscore;
479 /* warning switches */
480 int warn_write_strings;
481 int warn_unsupported;
482 int warn_error;
483 int warn_none;
484 int warn_implicit_function_declaration;
486 /* error handling */
487 void *error_opaque;
488 void (*error_func)(void *opaque, const char *msg);
489 int error_set_jmp_enabled;
490 jmp_buf error_jmp_buf;
491 int nb_errors;
493 /* tiny assembler state */
494 Sym *asm_labels;
496 /* see include_stack_ptr */
497 BufferedFile *include_stack[INCLUDE_STACK_SIZE];
499 /* see ifdef_stack_ptr */
500 int ifdef_stack[IFDEF_STACK_SIZE];
502 /* see cached_includes */
503 int cached_includes_hash[CACHED_INCLUDES_HASH_SIZE];
505 /* pack stack */
506 int pack_stack[PACK_STACK_SIZE];
507 int *pack_stack_ptr;
509 /* output file for preprocessing */
510 FILE *outfile;
513 /* The current value can be: */
514 #define VT_VALMASK 0x00ff
515 #define VT_CONST 0x00f0 /* constant in vc
516 (must be first non register value) */
517 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
518 #define VT_LOCAL 0x00f2 /* offset on stack */
519 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
520 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
521 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
522 #define VT_LVAL 0x0100 /* var is an lvalue */
523 #define VT_SYM 0x0200 /* a symbol value is added */
524 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
525 char/short stored in integer registers) */
526 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
527 dereferencing value */
528 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
529 bounding function call point is in vc */
530 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
531 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
532 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
533 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
535 /* types */
536 #define VT_INT 0 /* integer type */
537 #define VT_BYTE 1 /* signed byte type */
538 #define VT_SHORT 2 /* short type */
539 #define VT_VOID 3 /* void type */
540 #define VT_PTR 4 /* pointer */
541 #define VT_ENUM 5 /* enum definition */
542 #define VT_FUNC 6 /* function type */
543 #define VT_STRUCT 7 /* struct/union definition */
544 #define VT_FLOAT 8 /* IEEE float */
545 #define VT_DOUBLE 9 /* IEEE double */
546 #define VT_LDOUBLE 10 /* IEEE long double */
547 #define VT_BOOL 11 /* ISOC99 boolean type */
548 #define VT_LLONG 12 /* 64 bit integer */
549 #define VT_LONG 13 /* long integer (NEVER USED as type, only
550 during parsing) */
551 #define VT_BTYPE 0x000f /* mask for basic type */
552 #define VT_UNSIGNED 0x0010 /* unsigned type */
553 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
554 #define VT_BITFIELD 0x0040 /* bitfield modifier */
555 #define VT_CONSTANT 0x0800 /* const modifier */
556 #define VT_VOLATILE 0x1000 /* volatile modifier */
557 #define VT_SIGNED 0x2000 /* signed type */
559 /* storage */
560 #define VT_EXTERN 0x00000080 /* extern definition */
561 #define VT_STATIC 0x00000100 /* static variable */
562 #define VT_TYPEDEF 0x00000200 /* typedef definition */
563 #define VT_INLINE 0x00000400 /* inline definition */
565 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
567 /* type mask (except storage) */
568 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
569 #define VT_TYPE (~(VT_STORAGE))
571 /* token values */
573 /* warning: the following compare tokens depend on i386 asm code */
574 #define TOK_ULT 0x92
575 #define TOK_UGE 0x93
576 #define TOK_EQ 0x94
577 #define TOK_NE 0x95
578 #define TOK_ULE 0x96
579 #define TOK_UGT 0x97
580 #define TOK_Nset 0x98
581 #define TOK_Nclear 0x99
582 #define TOK_LT 0x9c
583 #define TOK_GE 0x9d
584 #define TOK_LE 0x9e
585 #define TOK_GT 0x9f
587 #define TOK_LAND 0xa0
588 #define TOK_LOR 0xa1
590 #define TOK_DEC 0xa2
591 #define TOK_MID 0xa3 /* inc/dec, to void constant */
592 #define TOK_INC 0xa4
593 #define TOK_UDIV 0xb0 /* unsigned division */
594 #define TOK_UMOD 0xb1 /* unsigned modulo */
595 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
596 #define TOK_CINT 0xb3 /* number in tokc */
597 #define TOK_CCHAR 0xb4 /* char constant in tokc */
598 #define TOK_STR 0xb5 /* pointer to string in tokc */
599 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
600 #define TOK_LCHAR 0xb7
601 #define TOK_LSTR 0xb8
602 #define TOK_CFLOAT 0xb9 /* float constant */
603 #define TOK_LINENUM 0xba /* line number info */
604 #define TOK_CDOUBLE 0xc0 /* double constant */
605 #define TOK_CLDOUBLE 0xc1 /* long double constant */
606 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
607 #define TOK_ADDC1 0xc3 /* add with carry generation */
608 #define TOK_ADDC2 0xc4 /* add with carry use */
609 #define TOK_SUBC1 0xc5 /* add with carry generation */
610 #define TOK_SUBC2 0xc6 /* add with carry use */
611 #define TOK_CUINT 0xc8 /* unsigned int constant */
612 #define TOK_CLLONG 0xc9 /* long long constant */
613 #define TOK_CULLONG 0xca /* unsigned long long constant */
614 #define TOK_ARROW 0xcb
615 #define TOK_DOTS 0xcc /* three dots */
616 #define TOK_SHR 0xcd /* unsigned shift right */
617 #define TOK_PPNUM 0xce /* preprocessor number */
619 #define TOK_SHL 0x01 /* shift left */
620 #define TOK_SAR 0x02 /* signed shift right */
622 /* assignement operators : normal operator or 0x80 */
623 #define TOK_A_MOD 0xa5
624 #define TOK_A_AND 0xa6
625 #define TOK_A_MUL 0xaa
626 #define TOK_A_ADD 0xab
627 #define TOK_A_SUB 0xad
628 #define TOK_A_DIV 0xaf
629 #define TOK_A_XOR 0xde
630 #define TOK_A_OR 0xfc
631 #define TOK_A_SHL 0x81
632 #define TOK_A_SAR 0x82
634 #ifndef offsetof
635 #define offsetof(type, field) ((size_t) &((type *)0)->field)
636 #endif
638 #ifndef countof
639 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
640 #endif
642 /* WARNING: the content of this string encodes token numbers */
643 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";
645 #define TOK_EOF (-1) /* end of file */
646 #define TOK_LINEFEED 10 /* line feed */
648 /* all identificators and strings have token above that */
649 #define TOK_IDENT 256
651 /* only used for i386 asm opcodes definitions */
652 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
654 #define DEF_BWL(x) \
655 DEF(TOK_ASM_ ## x ## b, #x "b") \
656 DEF(TOK_ASM_ ## x ## w, #x "w") \
657 DEF(TOK_ASM_ ## x ## l, #x "l") \
658 DEF(TOK_ASM_ ## x, #x)
660 #define DEF_WL(x) \
661 DEF(TOK_ASM_ ## x ## w, #x "w") \
662 DEF(TOK_ASM_ ## x ## l, #x "l") \
663 DEF(TOK_ASM_ ## x, #x)
665 #define DEF_FP1(x) \
666 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
667 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
668 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
669 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
671 #define DEF_FP(x) \
672 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
673 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
674 DEF_FP1(x)
676 #define DEF_ASMTEST(x) \
677 DEF_ASM(x ## o) \
678 DEF_ASM(x ## no) \
679 DEF_ASM(x ## b) \
680 DEF_ASM(x ## c) \
681 DEF_ASM(x ## nae) \
682 DEF_ASM(x ## nb) \
683 DEF_ASM(x ## nc) \
684 DEF_ASM(x ## ae) \
685 DEF_ASM(x ## e) \
686 DEF_ASM(x ## z) \
687 DEF_ASM(x ## ne) \
688 DEF_ASM(x ## nz) \
689 DEF_ASM(x ## be) \
690 DEF_ASM(x ## na) \
691 DEF_ASM(x ## nbe) \
692 DEF_ASM(x ## a) \
693 DEF_ASM(x ## s) \
694 DEF_ASM(x ## ns) \
695 DEF_ASM(x ## p) \
696 DEF_ASM(x ## pe) \
697 DEF_ASM(x ## np) \
698 DEF_ASM(x ## po) \
699 DEF_ASM(x ## l) \
700 DEF_ASM(x ## nge) \
701 DEF_ASM(x ## nl) \
702 DEF_ASM(x ## ge) \
703 DEF_ASM(x ## le) \
704 DEF_ASM(x ## ng) \
705 DEF_ASM(x ## nle) \
706 DEF_ASM(x ## g)
708 #define TOK_ASM_int TOK_INT
710 enum tcc_token {
711 TOK_LAST = TOK_IDENT - 1,
712 #define DEF(id, str) id,
713 #include "tcctok.h"
714 #undef DEF
717 static const char tcc_keywords[] =
718 #define DEF(id, str) str "\0"
719 #include "tcctok.h"
720 #undef DEF
723 #define TOK_UIDENT TOK_DEFINE
725 #ifdef _WIN32
726 int __stdcall GetModuleFileNameA(void *, char *, int);
727 void *__stdcall GetProcAddress(void *, const char *);
728 void *__stdcall GetModuleHandleA(const char *);
729 void *__stdcall LoadLibraryA(const char *);
730 int __stdcall FreeConsole(void);
731 int __stdcall VirtualProtect(void*,unsigned long,unsigned long,unsigned long*);
732 #define PAGE_EXECUTE_READWRITE 0x0040
734 #define snprintf _snprintf
735 #define vsnprintf _vsnprintf
736 #ifndef __GNUC__
737 #define strtold (long double)strtod
738 #define strtof (float)strtod
739 #define strtoll (long long)strtol
740 #endif
741 #elif defined(TCC_UCLIBC) || defined(__FreeBSD__)
742 /* currently incorrect */
743 long double strtold(const char *nptr, char **endptr)
745 return (long double)strtod(nptr, endptr);
747 float strtof(const char *nptr, char **endptr)
749 return (float)strtod(nptr, endptr);
751 #else
752 /* XXX: need to define this to use them in non ISOC99 context */
753 extern float strtof (const char *__nptr, char **__endptr);
754 extern long double strtold (const char *__nptr, char **__endptr);
755 #endif
757 static char *pstrcpy(char *buf, int buf_size, const char *s);
758 static char *pstrcat(char *buf, int buf_size, const char *s);
759 static char *tcc_basename(const char *name);
761 static void next(void);
762 static void next_nomacro(void);
763 static void parse_expr_type(CType *type);
764 static void expr_type(CType *type);
765 static void unary_type(CType *type);
766 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
767 int case_reg, int is_expr);
768 static int expr_const(void);
769 static void expr_eq(void);
770 static void gexpr(void);
771 static void gen_inline_functions(void);
772 static void decl(int l);
773 static void decl_initializer(CType *type, Section *sec, unsigned long c,
774 int first, int size_only);
775 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
776 int has_init, int v, int scope);
777 int gv(int rc);
778 void gv2(int rc1, int rc2);
779 void move_reg(int r, int s);
780 void save_regs(int n);
781 void save_reg(int r);
782 void vpop(void);
783 void vswap(void);
784 void vdup(void);
785 int get_reg(int rc);
786 int get_reg_ex(int rc,int rc2);
788 struct macro_level {
789 struct macro_level *prev;
790 int *p;
793 static void macro_subst(TokenString *tok_str, Sym **nested_list,
794 const int *macro_str, struct macro_level **can_read_stream);
795 void gen_op(int op);
796 void force_charshort_cast(int t);
797 static void gen_cast(CType *type);
798 void vstore(void);
799 static Sym *sym_find(int v);
800 static Sym *sym_push(int v, CType *type, int r, int c);
802 /* type handling */
803 static int type_size(CType *type, int *a);
804 static inline CType *pointed_type(CType *type);
805 static int pointed_size(CType *type);
806 static int lvalue_type(int t);
807 static int parse_btype(CType *type, AttributeDef *ad);
808 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
809 static int compare_types(CType *type1, CType *type2, int unqualified);
810 static int is_compatible_types(CType *type1, CType *type2);
811 static int is_compatible_parameter_types(CType *type1, CType *type2);
813 int ieee_finite(double d);
814 void error(const char *fmt, ...);
815 void vpushi(int v);
816 void vrott(int n);
817 void vnrott(int n);
818 void lexpand_nr(void);
819 static void vpush_global_sym(CType *type, int v);
820 void vset(CType *type, int r, int v);
821 void type_to_str(char *buf, int buf_size,
822 CType *type, const char *varstr);
823 char *get_tok_str(int v, CValue *cv);
824 static Sym *get_sym_ref(CType *type, Section *sec,
825 unsigned long offset, unsigned long size);
826 static Sym *external_global_sym(int v, CType *type, int r);
828 /* section generation */
829 static void section_realloc(Section *sec, unsigned long new_size);
830 static void *section_ptr_add(Section *sec, unsigned long size);
831 static void put_extern_sym(Sym *sym, Section *section,
832 unsigned long value, unsigned long size);
833 static void greloc(Section *s, Sym *sym, unsigned long addr, int type);
834 static int put_elf_str(Section *s, const char *sym);
835 static int put_elf_sym(Section *s,
836 unsigned long value, unsigned long size,
837 int info, int other, int shndx, const char *name);
838 static int add_elf_sym(Section *s, unsigned long value, unsigned long size,
839 int info, int other, int sh_num, const char *name);
840 static void put_elf_reloc(Section *symtab, Section *s, unsigned long offset,
841 int type, int symbol);
842 static void put_stabs(const char *str, int type, int other, int desc,
843 unsigned long value);
844 static void put_stabs_r(const char *str, int type, int other, int desc,
845 unsigned long value, Section *sec, int sym_index);
846 static void put_stabn(int type, int other, int desc, int value);
847 static void put_stabd(int type, int other, int desc);
848 static int tcc_add_dll(TCCState *s, const char *filename, int flags);
850 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
851 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
852 #define AFF_PREPROCESS 0x0004 /* preprocess file */
853 static int tcc_add_file_internal(TCCState *s, const char *filename, int flags);
855 /* tcccoff.c */
856 int tcc_output_coff(TCCState *s1, FILE *f);
858 /* tccpe.c */
859 void *resolve_sym(TCCState *s1, const char *sym, int type);
860 int pe_load_def_file(struct TCCState *s1, FILE *fp);
861 void pe_setup_paths(struct TCCState *s1, int *p_output_type, const char **p_outfile, char *first_file);
862 unsigned long pe_add_runtime(struct TCCState *s1);
863 int tcc_output_pe(struct TCCState *s1, const char *filename);
865 /* tccasm.c */
867 #ifdef CONFIG_TCC_ASM
869 typedef struct ExprValue {
870 uint32_t v;
871 Sym *sym;
872 } ExprValue;
874 #define MAX_ASM_OPERANDS 30
876 typedef struct ASMOperand {
877 int id; /* GCC 3 optionnal identifier (0 if number only supported */
878 char *constraint;
879 char asm_str[16]; /* computed asm string for operand */
880 SValue *vt; /* C value of the expression */
881 int ref_index; /* if >= 0, gives reference to a output constraint */
882 int input_index; /* if >= 0, gives reference to an input constraint */
883 int priority; /* priority, used to assign registers */
884 int reg; /* if >= 0, register number used for this operand */
885 int is_llong; /* true if double register value */
886 int is_memory; /* true if memory operand */
887 int is_rw; /* for '+' modifier */
888 } ASMOperand;
890 static void asm_expr(TCCState *s1, ExprValue *pe);
891 static int asm_int_expr(TCCState *s1);
892 static int find_constraint(ASMOperand *operands, int nb_operands,
893 const char *name, const char **pp);
895 static int tcc_assemble(TCCState *s1, int do_preprocess);
897 #endif
899 static void asm_instr(void);
900 static void asm_global_instr(void);
902 /* true if float/double/long double type */
903 static inline int is_float(int t)
905 int bt;
906 bt = t & VT_BTYPE;
907 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT;
910 #ifdef TCC_TARGET_I386
911 #include "i386-gen.c"
912 #endif
914 #ifdef TCC_TARGET_ARM
915 #include "arm-gen.c"
916 #endif
918 #ifdef TCC_TARGET_C67
919 #include "c67-gen.c"
920 #endif
922 #ifdef CONFIG_TCC_STATIC
924 #define RTLD_LAZY 0x001
925 #define RTLD_NOW 0x002
926 #define RTLD_GLOBAL 0x100
927 #define RTLD_DEFAULT NULL
929 /* dummy function for profiling */
930 void *dlopen(const char *filename, int flag)
932 return NULL;
935 const char *dlerror(void)
937 return "error";
940 typedef struct TCCSyms {
941 char *str;
942 void *ptr;
943 } TCCSyms;
945 #define TCCSYM(a) { #a, &a, },
947 /* add the symbol you want here if no dynamic linking is done */
948 static TCCSyms tcc_syms[] = {
949 #if !defined(CONFIG_TCCBOOT)
950 TCCSYM(printf)
951 TCCSYM(fprintf)
952 TCCSYM(fopen)
953 TCCSYM(fclose)
954 #endif
955 { NULL, NULL },
958 void *resolve_sym(TCCState *s1, const char *symbol, int type)
960 TCCSyms *p;
961 p = tcc_syms;
962 while (p->str != NULL) {
963 if (!strcmp(p->str, symbol))
964 return p->ptr;
965 p++;
967 return NULL;
970 #elif !defined(_WIN32)
972 #include <dlfcn.h>
974 void *resolve_sym(TCCState *s1, const char *sym, int type)
976 return dlsym(RTLD_DEFAULT, sym);
979 #endif
981 /********************************************************/
983 /* we use our own 'finite' function to avoid potential problems with
984 non standard math libs */
985 /* XXX: endianness dependent */
986 int ieee_finite(double d)
988 int *p = (int *)&d;
989 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
992 /* copy a string and truncate it. */
993 static char *pstrcpy(char *buf, int buf_size, const char *s)
995 char *q, *q_end;
996 int c;
998 if (buf_size > 0) {
999 q = buf;
1000 q_end = buf + buf_size - 1;
1001 while (q < q_end) {
1002 c = *s++;
1003 if (c == '\0')
1004 break;
1005 *q++ = c;
1007 *q = '\0';
1009 return buf;
1012 /* strcat and truncate. */
1013 static char *pstrcat(char *buf, int buf_size, const char *s)
1015 int len;
1016 len = strlen(buf);
1017 if (len < buf_size)
1018 pstrcpy(buf + len, buf_size - len, s);
1019 return buf;
1022 static int strstart(const char *str, const char *val, const char **ptr)
1024 const char *p, *q;
1025 p = str;
1026 q = val;
1027 while (*q != '\0') {
1028 if (*p != *q)
1029 return 0;
1030 p++;
1031 q++;
1033 if (ptr)
1034 *ptr = p;
1035 return 1;
1038 #ifdef _WIN32
1039 char *normalize_slashes(char *path)
1041 char *p;
1042 for (p = path; *p; ++p)
1043 if (*p == '\\')
1044 *p = '/';
1045 return path;
1048 char *w32_tcc_lib_path(void)
1050 /* on win32, we suppose the lib and includes are at the location
1051 of 'tcc.exe' */
1052 char path[1024], *p;
1053 GetModuleFileNameA(NULL, path, sizeof path);
1054 p = tcc_basename(normalize_slashes(strlwr(path)));
1055 if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
1056 p -= 5;
1057 else if (p > path)
1058 p--;
1059 *p = 0;
1060 return strdup(path);
1062 #endif
1064 void set_pages_executable(void *ptr, unsigned long length)
1066 #ifdef _WIN32
1067 unsigned long old_protect;
1068 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
1069 #else
1070 unsigned long start, end;
1071 start = (unsigned long)ptr & ~(PAGESIZE - 1);
1072 end = (unsigned long)ptr + length;
1073 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
1074 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
1075 #endif
1078 /* memory management */
1079 #ifdef MEM_DEBUG
1080 int mem_cur_size;
1081 int mem_max_size;
1082 #endif
1084 static inline void tcc_free(void *ptr)
1086 #ifdef MEM_DEBUG
1087 mem_cur_size -= malloc_usable_size(ptr);
1088 #endif
1089 free(ptr);
1092 static void *tcc_malloc(unsigned long size)
1094 void *ptr;
1095 ptr = malloc(size);
1096 if (!ptr && size)
1097 error("memory full");
1098 #ifdef MEM_DEBUG
1099 mem_cur_size += malloc_usable_size(ptr);
1100 if (mem_cur_size > mem_max_size)
1101 mem_max_size = mem_cur_size;
1102 #endif
1103 return ptr;
1106 static void *tcc_mallocz(unsigned long size)
1108 void *ptr;
1109 ptr = tcc_malloc(size);
1110 memset(ptr, 0, size);
1111 return ptr;
1114 static inline void *tcc_realloc(void *ptr, unsigned long size)
1116 void *ptr1;
1117 #ifdef MEM_DEBUG
1118 mem_cur_size -= malloc_usable_size(ptr);
1119 #endif
1120 ptr1 = realloc(ptr, size);
1121 #ifdef MEM_DEBUG
1122 /* NOTE: count not correct if alloc error, but not critical */
1123 mem_cur_size += malloc_usable_size(ptr1);
1124 if (mem_cur_size > mem_max_size)
1125 mem_max_size = mem_cur_size;
1126 #endif
1127 return ptr1;
1130 static char *tcc_strdup(const char *str)
1132 char *ptr;
1133 ptr = tcc_malloc(strlen(str) + 1);
1134 strcpy(ptr, str);
1135 return ptr;
1138 #define free(p) use_tcc_free(p)
1139 #define malloc(s) use_tcc_malloc(s)
1140 #define realloc(p, s) use_tcc_realloc(p, s)
1142 static void dynarray_add(void ***ptab, int *nb_ptr, void *data)
1144 int nb, nb_alloc;
1145 void **pp;
1147 nb = *nb_ptr;
1148 pp = *ptab;
1149 /* every power of two we double array size */
1150 if ((nb & (nb - 1)) == 0) {
1151 if (!nb)
1152 nb_alloc = 1;
1153 else
1154 nb_alloc = nb * 2;
1155 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
1156 if (!pp)
1157 error("memory full");
1158 *ptab = pp;
1160 pp[nb++] = data;
1161 *nb_ptr = nb;
1164 /* symbol allocator */
1165 static Sym *__sym_malloc(void)
1167 Sym *sym_pool, *sym, *last_sym;
1168 int i;
1170 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
1172 last_sym = sym_free_first;
1173 sym = sym_pool;
1174 for(i = 0; i < SYM_POOL_NB; i++) {
1175 sym->next = last_sym;
1176 last_sym = sym;
1177 sym++;
1179 sym_free_first = last_sym;
1180 return last_sym;
1183 static inline Sym *sym_malloc(void)
1185 Sym *sym;
1186 sym = sym_free_first;
1187 if (!sym)
1188 sym = __sym_malloc();
1189 sym_free_first = sym->next;
1190 return sym;
1193 static inline void sym_free(Sym *sym)
1195 sym->next = sym_free_first;
1196 sym_free_first = sym;
1199 Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
1201 Section *sec;
1203 sec = tcc_mallocz(sizeof(Section) + strlen(name));
1204 strcpy(sec->name, name);
1205 sec->sh_type = sh_type;
1206 sec->sh_flags = sh_flags;
1207 switch(sh_type) {
1208 case SHT_HASH:
1209 case SHT_REL:
1210 case SHT_DYNSYM:
1211 case SHT_SYMTAB:
1212 case SHT_DYNAMIC:
1213 sec->sh_addralign = 4;
1214 break;
1215 case SHT_STRTAB:
1216 sec->sh_addralign = 1;
1217 break;
1218 default:
1219 sec->sh_addralign = 32; /* default conservative alignment */
1220 break;
1223 /* only add section if not private */
1224 if (!(sh_flags & SHF_PRIVATE)) {
1225 sec->sh_num = s1->nb_sections;
1226 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
1228 return sec;
1231 static void free_section(Section *s)
1233 tcc_free(s->data);
1234 tcc_free(s);
1237 /* realloc section and set its content to zero */
1238 static void section_realloc(Section *sec, unsigned long new_size)
1240 unsigned long size;
1241 unsigned char *data;
1243 size = sec->data_allocated;
1244 if (size == 0)
1245 size = 1;
1246 while (size < new_size)
1247 size = size * 2;
1248 data = tcc_realloc(sec->data, size);
1249 if (!data)
1250 error("memory full");
1251 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
1252 sec->data = data;
1253 sec->data_allocated = size;
1256 /* reserve at least 'size' bytes in section 'sec' from
1257 sec->data_offset. */
1258 static void *section_ptr_add(Section *sec, unsigned long size)
1260 unsigned long offset, offset1;
1262 offset = sec->data_offset;
1263 offset1 = offset + size;
1264 if (offset1 > sec->data_allocated)
1265 section_realloc(sec, offset1);
1266 sec->data_offset = offset1;
1267 return sec->data + offset;
1270 /* return a reference to a section, and create it if it does not
1271 exists */
1272 Section *find_section(TCCState *s1, const char *name)
1274 Section *sec;
1275 int i;
1276 for(i = 1; i < s1->nb_sections; i++) {
1277 sec = s1->sections[i];
1278 if (!strcmp(name, sec->name))
1279 return sec;
1281 /* sections are created as PROGBITS */
1282 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
1285 #define SECTION_ABS ((void *)1)
1287 /* update sym->c so that it points to an external symbol in section
1288 'section' with value 'value' */
1289 static void put_extern_sym2(Sym *sym, Section *section,
1290 unsigned long value, unsigned long size,
1291 int can_add_underscore)
1293 int sym_type, sym_bind, sh_num, info;
1294 Elf32_Sym *esym;
1295 const char *name;
1296 char buf1[256];
1298 if (section == NULL)
1299 sh_num = SHN_UNDEF;
1300 else if (section == SECTION_ABS)
1301 sh_num = SHN_ABS;
1302 else
1303 sh_num = section->sh_num;
1304 if (!sym->c) {
1305 if ((sym->type.t & VT_BTYPE) == VT_FUNC)
1306 sym_type = STT_FUNC;
1307 else
1308 sym_type = STT_OBJECT;
1309 if (sym->type.t & VT_STATIC)
1310 sym_bind = STB_LOCAL;
1311 else
1312 sym_bind = STB_GLOBAL;
1314 name = get_tok_str(sym->v, NULL);
1315 #ifdef CONFIG_TCC_BCHECK
1316 if (do_bounds_check) {
1317 char buf[32];
1319 /* XXX: avoid doing that for statics ? */
1320 /* if bound checking is activated, we change some function
1321 names by adding the "__bound" prefix */
1322 switch(sym->v) {
1323 #if 0
1324 /* XXX: we rely only on malloc hooks */
1325 case TOK_malloc:
1326 case TOK_free:
1327 case TOK_realloc:
1328 case TOK_memalign:
1329 case TOK_calloc:
1330 #endif
1331 case TOK_memcpy:
1332 case TOK_memmove:
1333 case TOK_memset:
1334 case TOK_strlen:
1335 case TOK_strcpy:
1336 case TOK__alloca:
1337 strcpy(buf, "__bound_");
1338 strcat(buf, name);
1339 name = buf;
1340 break;
1343 #endif
1344 if (tcc_state->leading_underscore && can_add_underscore) {
1345 buf1[0] = '_';
1346 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
1347 name = buf1;
1349 info = ELF32_ST_INFO(sym_bind, sym_type);
1350 sym->c = add_elf_sym(symtab_section, value, size, info, 0, sh_num, name);
1351 } else {
1352 esym = &((Elf32_Sym *)symtab_section->data)[sym->c];
1353 esym->st_value = value;
1354 esym->st_size = size;
1355 esym->st_shndx = sh_num;
1359 static void put_extern_sym(Sym *sym, Section *section,
1360 unsigned long value, unsigned long size)
1362 put_extern_sym2(sym, section, value, size, 1);
1365 /* add a new relocation entry to symbol 'sym' in section 's' */
1366 static void greloc(Section *s, Sym *sym, unsigned long offset, int type)
1368 if (!sym->c)
1369 put_extern_sym(sym, NULL, 0, 0);
1370 /* now we can add ELF relocation info */
1371 put_elf_reloc(symtab_section, s, offset, type, sym->c);
1374 static inline int isid(int c)
1376 return (c >= 'a' && c <= 'z') ||
1377 (c >= 'A' && c <= 'Z') ||
1378 c == '_';
1381 static inline int isnum(int c)
1383 return c >= '0' && c <= '9';
1386 static inline int isoct(int c)
1388 return c >= '0' && c <= '7';
1391 static inline int toup(int c)
1393 if (c >= 'a' && c <= 'z')
1394 return c - 'a' + 'A';
1395 else
1396 return c;
1399 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
1401 int len;
1402 len = strlen(buf);
1403 vsnprintf(buf + len, buf_size - len, fmt, ap);
1406 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
1408 va_list ap;
1409 va_start(ap, fmt);
1410 strcat_vprintf(buf, buf_size, fmt, ap);
1411 va_end(ap);
1414 void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
1416 char buf[2048];
1417 BufferedFile **f;
1419 buf[0] = '\0';
1420 if (file) {
1421 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
1422 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
1423 (*f)->filename, (*f)->line_num);
1424 if (file->line_num > 0) {
1425 strcat_printf(buf, sizeof(buf),
1426 "%s:%d: ", file->filename, file->line_num);
1427 } else {
1428 strcat_printf(buf, sizeof(buf),
1429 "%s: ", file->filename);
1431 } else {
1432 strcat_printf(buf, sizeof(buf),
1433 "tcc: ");
1435 if (is_warning)
1436 strcat_printf(buf, sizeof(buf), "warning: ");
1437 strcat_vprintf(buf, sizeof(buf), fmt, ap);
1439 if (!s1->error_func) {
1440 /* default case: stderr */
1441 fprintf(stderr, "%s\n", buf);
1442 } else {
1443 s1->error_func(s1->error_opaque, buf);
1445 if (!is_warning || s1->warn_error)
1446 s1->nb_errors++;
1449 #ifdef LIBTCC
1450 void tcc_set_error_func(TCCState *s, void *error_opaque,
1451 void (*error_func)(void *opaque, const char *msg))
1453 s->error_opaque = error_opaque;
1454 s->error_func = error_func;
1456 #endif
1458 /* error without aborting current compilation */
1459 void error_noabort(const char *fmt, ...)
1461 TCCState *s1 = tcc_state;
1462 va_list ap;
1464 va_start(ap, fmt);
1465 error1(s1, 0, fmt, ap);
1466 va_end(ap);
1469 void error(const char *fmt, ...)
1471 TCCState *s1 = tcc_state;
1472 va_list ap;
1474 va_start(ap, fmt);
1475 error1(s1, 0, fmt, ap);
1476 va_end(ap);
1477 /* better than nothing: in some cases, we accept to handle errors */
1478 if (s1->error_set_jmp_enabled) {
1479 longjmp(s1->error_jmp_buf, 1);
1480 } else {
1481 /* XXX: eliminate this someday */
1482 exit(1);
1486 void expect(const char *msg)
1488 error("%s expected", msg);
1491 void warning(const char *fmt, ...)
1493 TCCState *s1 = tcc_state;
1494 va_list ap;
1496 if (s1->warn_none)
1497 return;
1499 va_start(ap, fmt);
1500 error1(s1, 1, fmt, ap);
1501 va_end(ap);
1504 void skip(int c)
1506 if (tok != c)
1507 error("'%c' expected", c);
1508 next();
1511 static void test_lvalue(void)
1513 if (!(vtop->r & VT_LVAL))
1514 expect("lvalue");
1517 /* allocate a new token */
1518 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
1520 TokenSym *ts, **ptable;
1521 int i;
1523 if (tok_ident >= SYM_FIRST_ANOM)
1524 error("memory full");
1526 /* expand token table if needed */
1527 i = tok_ident - TOK_IDENT;
1528 if ((i % TOK_ALLOC_INCR) == 0) {
1529 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
1530 if (!ptable)
1531 error("memory full");
1532 table_ident = ptable;
1535 ts = tcc_malloc(sizeof(TokenSym) + len);
1536 table_ident[i] = ts;
1537 ts->tok = tok_ident++;
1538 ts->sym_define = NULL;
1539 ts->sym_label = NULL;
1540 ts->sym_struct = NULL;
1541 ts->sym_identifier = NULL;
1542 ts->len = len;
1543 ts->hash_next = NULL;
1544 memcpy(ts->str, str, len);
1545 ts->str[len] = '\0';
1546 *pts = ts;
1547 return ts;
1550 #define TOK_HASH_INIT 1
1551 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1553 /* find a token and add it if not found */
1554 static TokenSym *tok_alloc(const char *str, int len)
1556 TokenSym *ts, **pts;
1557 int i;
1558 unsigned int h;
1560 h = TOK_HASH_INIT;
1561 for(i=0;i<len;i++)
1562 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
1563 h &= (TOK_HASH_SIZE - 1);
1565 pts = &hash_ident[h];
1566 for(;;) {
1567 ts = *pts;
1568 if (!ts)
1569 break;
1570 if (ts->len == len && !memcmp(ts->str, str, len))
1571 return ts;
1572 pts = &(ts->hash_next);
1574 return tok_alloc_new(pts, str, len);
1577 /* CString handling */
1579 static void cstr_realloc(CString *cstr, int new_size)
1581 int size;
1582 void *data;
1584 size = cstr->size_allocated;
1585 if (size == 0)
1586 size = 8; /* no need to allocate a too small first string */
1587 while (size < new_size)
1588 size = size * 2;
1589 data = tcc_realloc(cstr->data_allocated, size);
1590 if (!data)
1591 error("memory full");
1592 cstr->data_allocated = data;
1593 cstr->size_allocated = size;
1594 cstr->data = data;
1597 /* add a byte */
1598 static inline void cstr_ccat(CString *cstr, int ch)
1600 int size;
1601 size = cstr->size + 1;
1602 if (size > cstr->size_allocated)
1603 cstr_realloc(cstr, size);
1604 ((unsigned char *)cstr->data)[size - 1] = ch;
1605 cstr->size = size;
1608 static void cstr_cat(CString *cstr, const char *str)
1610 int c;
1611 for(;;) {
1612 c = *str;
1613 if (c == '\0')
1614 break;
1615 cstr_ccat(cstr, c);
1616 str++;
1620 /* add a wide char */
1621 static void cstr_wccat(CString *cstr, int ch)
1623 int size;
1624 size = cstr->size + sizeof(nwchar_t);
1625 if (size > cstr->size_allocated)
1626 cstr_realloc(cstr, size);
1627 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
1628 cstr->size = size;
1631 static void cstr_new(CString *cstr)
1633 memset(cstr, 0, sizeof(CString));
1636 /* free string and reset it to NULL */
1637 static void cstr_free(CString *cstr)
1639 tcc_free(cstr->data_allocated);
1640 cstr_new(cstr);
1643 #define cstr_reset(cstr) cstr_free(cstr)
1645 /* XXX: unicode ? */
1646 static void add_char(CString *cstr, int c)
1648 if (c == '\'' || c == '\"' || c == '\\') {
1649 /* XXX: could be more precise if char or string */
1650 cstr_ccat(cstr, '\\');
1652 if (c >= 32 && c <= 126) {
1653 cstr_ccat(cstr, c);
1654 } else {
1655 cstr_ccat(cstr, '\\');
1656 if (c == '\n') {
1657 cstr_ccat(cstr, 'n');
1658 } else {
1659 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
1660 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
1661 cstr_ccat(cstr, '0' + (c & 7));
1666 /* XXX: buffer overflow */
1667 /* XXX: float tokens */
1668 char *get_tok_str(int v, CValue *cv)
1670 static char buf[STRING_MAX_SIZE + 1];
1671 static CString cstr_buf;
1672 CString *cstr;
1673 unsigned char *q;
1674 char *p;
1675 int i, len;
1677 /* NOTE: to go faster, we give a fixed buffer for small strings */
1678 cstr_reset(&cstr_buf);
1679 cstr_buf.data = buf;
1680 cstr_buf.size_allocated = sizeof(buf);
1681 p = buf;
1683 switch(v) {
1684 case TOK_CINT:
1685 case TOK_CUINT:
1686 /* XXX: not quite exact, but only useful for testing */
1687 sprintf(p, "%u", cv->ui);
1688 break;
1689 case TOK_CLLONG:
1690 case TOK_CULLONG:
1691 /* XXX: not quite exact, but only useful for testing */
1692 sprintf(p, "%Lu", cv->ull);
1693 break;
1694 case TOK_CCHAR:
1695 case TOK_LCHAR:
1696 cstr_ccat(&cstr_buf, '\'');
1697 add_char(&cstr_buf, cv->i);
1698 cstr_ccat(&cstr_buf, '\'');
1699 cstr_ccat(&cstr_buf, '\0');
1700 break;
1701 case TOK_PPNUM:
1702 cstr = cv->cstr;
1703 len = cstr->size - 1;
1704 for(i=0;i<len;i++)
1705 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
1706 cstr_ccat(&cstr_buf, '\0');
1707 break;
1708 case TOK_STR:
1709 case TOK_LSTR:
1710 cstr = cv->cstr;
1711 cstr_ccat(&cstr_buf, '\"');
1712 if (v == TOK_STR) {
1713 len = cstr->size - 1;
1714 for(i=0;i<len;i++)
1715 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
1716 } else {
1717 len = (cstr->size / sizeof(nwchar_t)) - 1;
1718 for(i=0;i<len;i++)
1719 add_char(&cstr_buf, ((nwchar_t *)cstr->data)[i]);
1721 cstr_ccat(&cstr_buf, '\"');
1722 cstr_ccat(&cstr_buf, '\0');
1723 break;
1724 case TOK_LT:
1725 v = '<';
1726 goto addv;
1727 case TOK_GT:
1728 v = '>';
1729 goto addv;
1730 case TOK_DOTS:
1731 return strcpy(p, "...");
1732 case TOK_A_SHL:
1733 return strcpy(p, "<<=");
1734 case TOK_A_SAR:
1735 return strcpy(p, ">>=");
1736 default:
1737 if (v < TOK_IDENT) {
1738 /* search in two bytes table */
1739 q = tok_two_chars;
1740 while (*q) {
1741 if (q[2] == v) {
1742 *p++ = q[0];
1743 *p++ = q[1];
1744 *p = '\0';
1745 return buf;
1747 q += 3;
1749 addv:
1750 *p++ = v;
1751 *p = '\0';
1752 } else if (v < tok_ident) {
1753 return table_ident[v - TOK_IDENT]->str;
1754 } else if (v >= SYM_FIRST_ANOM) {
1755 /* special name for anonymous symbol */
1756 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
1757 } else {
1758 /* should never happen */
1759 return NULL;
1761 break;
1763 return cstr_buf.data;
1766 /* push, without hashing */
1767 static Sym *sym_push2(Sym **ps, int v, int t, int c)
1769 Sym *s;
1770 s = sym_malloc();
1771 s->v = v;
1772 s->type.t = t;
1773 s->c = c;
1774 s->next = NULL;
1775 /* add in stack */
1776 s->prev = *ps;
1777 *ps = s;
1778 return s;
1781 /* find a symbol and return its associated structure. 's' is the top
1782 of the symbol stack */
1783 static Sym *sym_find2(Sym *s, int v)
1785 while (s) {
1786 if (s->v == v)
1787 return s;
1788 s = s->prev;
1790 return NULL;
1793 /* structure lookup */
1794 static inline Sym *struct_find(int v)
1796 v -= TOK_IDENT;
1797 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1798 return NULL;
1799 return table_ident[v]->sym_struct;
1802 /* find an identifier */
1803 static inline Sym *sym_find(int v)
1805 v -= TOK_IDENT;
1806 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1807 return NULL;
1808 return table_ident[v]->sym_identifier;
1811 /* push a given symbol on the symbol stack */
1812 static Sym *sym_push(int v, CType *type, int r, int c)
1814 Sym *s, **ps;
1815 TokenSym *ts;
1817 if (local_stack)
1818 ps = &local_stack;
1819 else
1820 ps = &global_stack;
1821 s = sym_push2(ps, v, type->t, c);
1822 s->type.ref = type->ref;
1823 s->r = r;
1824 /* don't record fields or anonymous symbols */
1825 /* XXX: simplify */
1826 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1827 /* record symbol in token array */
1828 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1829 if (v & SYM_STRUCT)
1830 ps = &ts->sym_struct;
1831 else
1832 ps = &ts->sym_identifier;
1833 s->prev_tok = *ps;
1834 *ps = s;
1836 return s;
1839 /* push a global identifier */
1840 static Sym *global_identifier_push(int v, int t, int c)
1842 Sym *s, **ps;
1843 s = sym_push2(&global_stack, v, t, c);
1844 /* don't record anonymous symbol */
1845 if (v < SYM_FIRST_ANOM) {
1846 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
1847 /* modify the top most local identifier, so that
1848 sym_identifier will point to 's' when popped */
1849 while (*ps != NULL)
1850 ps = &(*ps)->prev_tok;
1851 s->prev_tok = NULL;
1852 *ps = s;
1854 return s;
1857 /* pop symbols until top reaches 'b' */
1858 static void sym_pop(Sym **ptop, Sym *b)
1860 Sym *s, *ss, **ps;
1861 TokenSym *ts;
1862 int v;
1864 s = *ptop;
1865 while(s != b) {
1866 ss = s->prev;
1867 v = s->v;
1868 /* remove symbol in token array */
1869 /* XXX: simplify */
1870 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1871 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1872 if (v & SYM_STRUCT)
1873 ps = &ts->sym_struct;
1874 else
1875 ps = &ts->sym_identifier;
1876 *ps = s->prev_tok;
1878 sym_free(s);
1879 s = ss;
1881 *ptop = b;
1884 /* I/O layer */
1886 BufferedFile *tcc_open(TCCState *s1, const char *filename)
1888 int fd;
1889 BufferedFile *bf;
1891 fd = open(filename, O_RDONLY | O_BINARY);
1892 if (fd < 0)
1893 return NULL;
1894 bf = tcc_malloc(sizeof(BufferedFile));
1895 if (!bf) {
1896 close(fd);
1897 return NULL;
1899 bf->fd = fd;
1900 bf->buf_ptr = bf->buffer;
1901 bf->buf_end = bf->buffer;
1902 bf->buffer[0] = CH_EOB; /* put eob symbol */
1903 pstrcpy(bf->filename, sizeof(bf->filename), filename);
1904 #ifdef _WIN32
1905 normalize_slashes(bf->filename);
1906 #endif
1907 bf->line_num = 1;
1908 bf->ifndef_macro = 0;
1909 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
1910 // printf("opening '%s'\n", filename);
1911 return bf;
1914 void tcc_close(BufferedFile *bf)
1916 total_lines += bf->line_num;
1917 close(bf->fd);
1918 tcc_free(bf);
1921 /* fill input buffer and peek next char */
1922 static int tcc_peekc_slow(BufferedFile *bf)
1924 int len;
1925 /* only tries to read if really end of buffer */
1926 if (bf->buf_ptr >= bf->buf_end) {
1927 if (bf->fd != -1) {
1928 #if defined(PARSE_DEBUG)
1929 len = 8;
1930 #else
1931 len = IO_BUF_SIZE;
1932 #endif
1933 len = read(bf->fd, bf->buffer, len);
1934 if (len < 0)
1935 len = 0;
1936 } else {
1937 len = 0;
1939 total_bytes += len;
1940 bf->buf_ptr = bf->buffer;
1941 bf->buf_end = bf->buffer + len;
1942 *bf->buf_end = CH_EOB;
1944 if (bf->buf_ptr < bf->buf_end) {
1945 return bf->buf_ptr[0];
1946 } else {
1947 bf->buf_ptr = bf->buf_end;
1948 return CH_EOF;
1952 /* return the current character, handling end of block if necessary
1953 (but not stray) */
1954 static int handle_eob(void)
1956 return tcc_peekc_slow(file);
1959 /* read next char from current input file and handle end of input buffer */
1960 static inline void inp(void)
1962 ch = *(++(file->buf_ptr));
1963 /* end of buffer/file handling */
1964 if (ch == CH_EOB)
1965 ch = handle_eob();
1968 /* handle '\[\r]\n' */
1969 static void handle_stray(void)
1971 while (ch == '\\') {
1972 inp();
1973 if (ch == '\n') {
1974 file->line_num++;
1975 inp();
1976 } else if (ch == '\r') {
1977 inp();
1978 if (ch != '\n')
1979 goto fail;
1980 file->line_num++;
1981 inp();
1982 } else {
1983 fail:
1984 error("stray '\\' in program");
1989 /* skip the stray and handle the \\n case. Output an error if
1990 incorrect char after the stray */
1991 static int handle_stray1(uint8_t *p)
1993 int c;
1995 if (p >= file->buf_end) {
1996 file->buf_ptr = p;
1997 c = handle_eob();
1998 p = file->buf_ptr;
1999 if (c == '\\')
2000 goto parse_stray;
2001 } else {
2002 parse_stray:
2003 file->buf_ptr = p;
2004 ch = *p;
2005 handle_stray();
2006 p = file->buf_ptr;
2007 c = *p;
2009 return c;
2012 /* handle just the EOB case, but not stray */
2013 #define PEEKC_EOB(c, p)\
2015 p++;\
2016 c = *p;\
2017 if (c == '\\') {\
2018 file->buf_ptr = p;\
2019 c = handle_eob();\
2020 p = file->buf_ptr;\
2024 /* handle the complicated stray case */
2025 #define PEEKC(c, p)\
2027 p++;\
2028 c = *p;\
2029 if (c == '\\') {\
2030 c = handle_stray1(p);\
2031 p = file->buf_ptr;\
2035 /* input with '\[\r]\n' handling. Note that this function cannot
2036 handle other characters after '\', so you cannot call it inside
2037 strings or comments */
2038 static void minp(void)
2040 inp();
2041 if (ch == '\\')
2042 handle_stray();
2046 /* single line C++ comments */
2047 static uint8_t *parse_line_comment(uint8_t *p)
2049 int c;
2051 p++;
2052 for(;;) {
2053 c = *p;
2054 redo:
2055 if (c == '\n' || c == CH_EOF) {
2056 break;
2057 } else if (c == '\\') {
2058 file->buf_ptr = p;
2059 c = handle_eob();
2060 p = file->buf_ptr;
2061 if (c == '\\') {
2062 PEEKC_EOB(c, p);
2063 if (c == '\n') {
2064 file->line_num++;
2065 PEEKC_EOB(c, p);
2066 } else if (c == '\r') {
2067 PEEKC_EOB(c, p);
2068 if (c == '\n') {
2069 file->line_num++;
2070 PEEKC_EOB(c, p);
2073 } else {
2074 goto redo;
2076 } else {
2077 p++;
2080 return p;
2083 /* C comments */
2084 static uint8_t *parse_comment(uint8_t *p)
2086 int c;
2088 p++;
2089 for(;;) {
2090 /* fast skip loop */
2091 for(;;) {
2092 c = *p;
2093 if (c == '\n' || c == '*' || c == '\\')
2094 break;
2095 p++;
2096 c = *p;
2097 if (c == '\n' || c == '*' || c == '\\')
2098 break;
2099 p++;
2101 /* now we can handle all the cases */
2102 if (c == '\n') {
2103 file->line_num++;
2104 p++;
2105 } else if (c == '*') {
2106 p++;
2107 for(;;) {
2108 c = *p;
2109 if (c == '*') {
2110 p++;
2111 } else if (c == '/') {
2112 goto end_of_comment;
2113 } else if (c == '\\') {
2114 file->buf_ptr = p;
2115 c = handle_eob();
2116 p = file->buf_ptr;
2117 if (c == '\\') {
2118 /* skip '\[\r]\n', otherwise just skip the stray */
2119 while (c == '\\') {
2120 PEEKC_EOB(c, p);
2121 if (c == '\n') {
2122 file->line_num++;
2123 PEEKC_EOB(c, p);
2124 } else if (c == '\r') {
2125 PEEKC_EOB(c, p);
2126 if (c == '\n') {
2127 file->line_num++;
2128 PEEKC_EOB(c, p);
2130 } else {
2131 goto after_star;
2135 } else {
2136 break;
2139 after_star: ;
2140 } else {
2141 /* stray, eob or eof */
2142 file->buf_ptr = p;
2143 c = handle_eob();
2144 p = file->buf_ptr;
2145 if (c == CH_EOF) {
2146 error("unexpected end of file in comment");
2147 } else if (c == '\\') {
2148 p++;
2152 end_of_comment:
2153 p++;
2154 return p;
2157 #define cinp minp
2159 /* space exlcuding newline */
2160 static inline int is_space(int ch)
2162 return ch == ' ' || ch == '\t' || ch == '\v' || ch == '\f' || ch == '\r';
2165 static inline void skip_spaces(void)
2167 while (is_space(ch))
2168 cinp();
2171 /* parse a string without interpreting escapes */
2172 static uint8_t *parse_pp_string(uint8_t *p,
2173 int sep, CString *str)
2175 int c;
2176 p++;
2177 for(;;) {
2178 c = *p;
2179 if (c == sep) {
2180 break;
2181 } else if (c == '\\') {
2182 file->buf_ptr = p;
2183 c = handle_eob();
2184 p = file->buf_ptr;
2185 if (c == CH_EOF) {
2186 unterminated_string:
2187 /* XXX: indicate line number of start of string */
2188 error("missing terminating %c character", sep);
2189 } else if (c == '\\') {
2190 /* escape : just skip \[\r]\n */
2191 PEEKC_EOB(c, p);
2192 if (c == '\n') {
2193 file->line_num++;
2194 p++;
2195 } else if (c == '\r') {
2196 PEEKC_EOB(c, p);
2197 if (c != '\n')
2198 expect("'\n' after '\r'");
2199 file->line_num++;
2200 p++;
2201 } else if (c == CH_EOF) {
2202 goto unterminated_string;
2203 } else {
2204 if (str) {
2205 cstr_ccat(str, '\\');
2206 cstr_ccat(str, c);
2208 p++;
2211 } else if (c == '\n') {
2212 file->line_num++;
2213 goto add_char;
2214 } else if (c == '\r') {
2215 PEEKC_EOB(c, p);
2216 if (c != '\n') {
2217 if (str)
2218 cstr_ccat(str, '\r');
2219 } else {
2220 file->line_num++;
2221 goto add_char;
2223 } else {
2224 add_char:
2225 if (str)
2226 cstr_ccat(str, c);
2227 p++;
2230 p++;
2231 return p;
2234 /* skip block of text until #else, #elif or #endif. skip also pairs of
2235 #if/#endif */
2236 void preprocess_skip(void)
2238 int a, start_of_line, c;
2239 uint8_t *p;
2241 p = file->buf_ptr;
2242 start_of_line = 1;
2243 a = 0;
2244 for(;;) {
2245 redo_no_start:
2246 c = *p;
2247 switch(c) {
2248 case ' ':
2249 case '\t':
2250 case '\f':
2251 case '\v':
2252 case '\r':
2253 p++;
2254 goto redo_no_start;
2255 case '\n':
2256 start_of_line = 1;
2257 file->line_num++;
2258 p++;
2259 goto redo_no_start;
2260 case '\\':
2261 file->buf_ptr = p;
2262 c = handle_eob();
2263 if (c == CH_EOF) {
2264 expect("#endif");
2265 } else if (c == '\\') {
2266 /* XXX: incorrect: should not give an error */
2267 ch = file->buf_ptr[0];
2268 handle_stray();
2270 p = file->buf_ptr;
2271 goto redo_no_start;
2272 /* skip strings */
2273 case '\"':
2274 case '\'':
2275 p = parse_pp_string(p, c, NULL);
2276 break;
2277 /* skip comments */
2278 case '/':
2279 file->buf_ptr = p;
2280 ch = *p;
2281 minp();
2282 p = file->buf_ptr;
2283 if (ch == '*') {
2284 p = parse_comment(p);
2285 } else if (ch == '/') {
2286 p = parse_line_comment(p);
2288 break;
2290 case '#':
2291 p++;
2292 if (start_of_line) {
2293 file->buf_ptr = p;
2294 next_nomacro();
2295 p = file->buf_ptr;
2296 if (a == 0 &&
2297 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
2298 goto the_end;
2299 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
2300 a++;
2301 else if (tok == TOK_ENDIF)
2302 a--;
2304 break;
2305 default:
2306 p++;
2307 break;
2309 start_of_line = 0;
2311 the_end: ;
2312 file->buf_ptr = p;
2315 /* ParseState handling */
2317 /* XXX: currently, no include file info is stored. Thus, we cannot display
2318 accurate messages if the function or data definition spans multiple
2319 files */
2321 /* save current parse state in 's' */
2322 void save_parse_state(ParseState *s)
2324 s->line_num = file->line_num;
2325 s->macro_ptr = macro_ptr;
2326 s->tok = tok;
2327 s->tokc = tokc;
2330 /* restore parse state from 's' */
2331 void restore_parse_state(ParseState *s)
2333 file->line_num = s->line_num;
2334 macro_ptr = s->macro_ptr;
2335 tok = s->tok;
2336 tokc = s->tokc;
2339 /* return the number of additional 'ints' necessary to store the
2340 token */
2341 static inline int tok_ext_size(int t)
2343 switch(t) {
2344 /* 4 bytes */
2345 case TOK_CINT:
2346 case TOK_CUINT:
2347 case TOK_CCHAR:
2348 case TOK_LCHAR:
2349 case TOK_CFLOAT:
2350 case TOK_LINENUM:
2351 return 1;
2352 case TOK_STR:
2353 case TOK_LSTR:
2354 case TOK_PPNUM:
2355 error("unsupported token");
2356 return 1;
2357 case TOK_CDOUBLE:
2358 case TOK_CLLONG:
2359 case TOK_CULLONG:
2360 return 2;
2361 case TOK_CLDOUBLE:
2362 return LDOUBLE_SIZE / 4;
2363 default:
2364 return 0;
2368 /* token string handling */
2370 static inline void tok_str_new(TokenString *s)
2372 s->str = NULL;
2373 s->len = 0;
2374 s->allocated_len = 0;
2375 s->last_line_num = -1;
2378 static void tok_str_free(int *str)
2380 tcc_free(str);
2383 static int *tok_str_realloc(TokenString *s)
2385 int *str, len;
2387 if (s->allocated_len == 0) {
2388 len = 8;
2389 } else {
2390 len = s->allocated_len * 2;
2392 str = tcc_realloc(s->str, len * sizeof(int));
2393 if (!str)
2394 error("memory full");
2395 s->allocated_len = len;
2396 s->str = str;
2397 return str;
2400 static void tok_str_add(TokenString *s, int t)
2402 int len, *str;
2404 len = s->len;
2405 str = s->str;
2406 if (len >= s->allocated_len)
2407 str = tok_str_realloc(s);
2408 str[len++] = t;
2409 s->len = len;
2412 static void tok_str_add2(TokenString *s, int t, CValue *cv)
2414 int len, *str;
2416 len = s->len;
2417 str = s->str;
2419 /* allocate space for worst case */
2420 if (len + TOK_MAX_SIZE > s->allocated_len)
2421 str = tok_str_realloc(s);
2422 str[len++] = t;
2423 switch(t) {
2424 case TOK_CINT:
2425 case TOK_CUINT:
2426 case TOK_CCHAR:
2427 case TOK_LCHAR:
2428 case TOK_CFLOAT:
2429 case TOK_LINENUM:
2430 str[len++] = cv->tab[0];
2431 break;
2432 case TOK_PPNUM:
2433 case TOK_STR:
2434 case TOK_LSTR:
2436 int nb_words;
2437 CString *cstr;
2439 nb_words = (sizeof(CString) + cv->cstr->size + 3) >> 2;
2440 while ((len + nb_words) > s->allocated_len)
2441 str = tok_str_realloc(s);
2442 cstr = (CString *)(str + len);
2443 cstr->data = NULL;
2444 cstr->size = cv->cstr->size;
2445 cstr->data_allocated = NULL;
2446 cstr->size_allocated = cstr->size;
2447 memcpy((char *)cstr + sizeof(CString),
2448 cv->cstr->data, cstr->size);
2449 len += nb_words;
2451 break;
2452 case TOK_CDOUBLE:
2453 case TOK_CLLONG:
2454 case TOK_CULLONG:
2455 #if LDOUBLE_SIZE == 8
2456 case TOK_CLDOUBLE:
2457 #endif
2458 str[len++] = cv->tab[0];
2459 str[len++] = cv->tab[1];
2460 break;
2461 #if LDOUBLE_SIZE == 12
2462 case TOK_CLDOUBLE:
2463 str[len++] = cv->tab[0];
2464 str[len++] = cv->tab[1];
2465 str[len++] = cv->tab[2];
2466 #elif LDOUBLE_SIZE != 8
2467 #error add long double size support
2468 #endif
2469 break;
2470 default:
2471 break;
2473 s->len = len;
2476 /* add the current parse token in token string 's' */
2477 static void tok_str_add_tok(TokenString *s)
2479 CValue cval;
2481 /* save line number info */
2482 if (file->line_num != s->last_line_num) {
2483 s->last_line_num = file->line_num;
2484 cval.i = s->last_line_num;
2485 tok_str_add2(s, TOK_LINENUM, &cval);
2487 tok_str_add2(s, tok, &tokc);
2490 #if LDOUBLE_SIZE == 12
2491 #define LDOUBLE_GET(p, cv) \
2492 cv.tab[0] = p[0]; \
2493 cv.tab[1] = p[1]; \
2494 cv.tab[2] = p[2];
2495 #elif LDOUBLE_SIZE == 8
2496 #define LDOUBLE_GET(p, cv) \
2497 cv.tab[0] = p[0]; \
2498 cv.tab[1] = p[1];
2499 #else
2500 #error add long double size support
2501 #endif
2504 /* get a token from an integer array and increment pointer
2505 accordingly. we code it as a macro to avoid pointer aliasing. */
2506 #define TOK_GET(t, p, cv) \
2508 t = *p++; \
2509 switch(t) { \
2510 case TOK_CINT: \
2511 case TOK_CUINT: \
2512 case TOK_CCHAR: \
2513 case TOK_LCHAR: \
2514 case TOK_CFLOAT: \
2515 case TOK_LINENUM: \
2516 cv.tab[0] = *p++; \
2517 break; \
2518 case TOK_STR: \
2519 case TOK_LSTR: \
2520 case TOK_PPNUM: \
2521 cv.cstr = (CString *)p; \
2522 cv.cstr->data = (char *)p + sizeof(CString);\
2523 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
2524 break; \
2525 case TOK_CDOUBLE: \
2526 case TOK_CLLONG: \
2527 case TOK_CULLONG: \
2528 cv.tab[0] = p[0]; \
2529 cv.tab[1] = p[1]; \
2530 p += 2; \
2531 break; \
2532 case TOK_CLDOUBLE: \
2533 LDOUBLE_GET(p, cv); \
2534 p += LDOUBLE_SIZE / 4; \
2535 break; \
2536 default: \
2537 break; \
2541 /* defines handling */
2542 static inline void define_push(int v, int macro_type, int *str, Sym *first_arg)
2544 Sym *s;
2546 s = sym_push2(&define_stack, v, macro_type, (int)str);
2547 s->next = first_arg;
2548 table_ident[v - TOK_IDENT]->sym_define = s;
2551 /* undefined a define symbol. Its name is just set to zero */
2552 static void define_undef(Sym *s)
2554 int v;
2555 v = s->v;
2556 if (v >= TOK_IDENT && v < tok_ident)
2557 table_ident[v - TOK_IDENT]->sym_define = NULL;
2558 s->v = 0;
2561 static inline Sym *define_find(int v)
2563 v -= TOK_IDENT;
2564 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
2565 return NULL;
2566 return table_ident[v]->sym_define;
2569 /* free define stack until top reaches 'b' */
2570 static void free_defines(Sym *b)
2572 Sym *top, *top1;
2573 int v;
2575 top = define_stack;
2576 while (top != b) {
2577 top1 = top->prev;
2578 /* do not free args or predefined defines */
2579 if (top->c)
2580 tok_str_free((int *)top->c);
2581 v = top->v;
2582 if (v >= TOK_IDENT && v < tok_ident)
2583 table_ident[v - TOK_IDENT]->sym_define = NULL;
2584 sym_free(top);
2585 top = top1;
2587 define_stack = b;
2590 /* label lookup */
2591 static Sym *label_find(int v)
2593 v -= TOK_IDENT;
2594 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
2595 return NULL;
2596 return table_ident[v]->sym_label;
2599 static Sym *label_push(Sym **ptop, int v, int flags)
2601 Sym *s, **ps;
2602 s = sym_push2(ptop, v, 0, 0);
2603 s->r = flags;
2604 ps = &table_ident[v - TOK_IDENT]->sym_label;
2605 if (ptop == &global_label_stack) {
2606 /* modify the top most local identifier, so that
2607 sym_identifier will point to 's' when popped */
2608 while (*ps != NULL)
2609 ps = &(*ps)->prev_tok;
2611 s->prev_tok = *ps;
2612 *ps = s;
2613 return s;
2616 /* pop labels until element last is reached. Look if any labels are
2617 undefined. Define symbols if '&&label' was used. */
2618 static void label_pop(Sym **ptop, Sym *slast)
2620 Sym *s, *s1;
2621 for(s = *ptop; s != slast; s = s1) {
2622 s1 = s->prev;
2623 if (s->r == LABEL_DECLARED) {
2624 warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
2625 } else if (s->r == LABEL_FORWARD) {
2626 error("label '%s' used but not defined",
2627 get_tok_str(s->v, NULL));
2628 } else {
2629 if (s->c) {
2630 /* define corresponding symbol. A size of
2631 1 is put. */
2632 put_extern_sym(s, cur_text_section, (long)s->next, 1);
2635 /* remove label */
2636 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
2637 sym_free(s);
2639 *ptop = slast;
2642 /* eval an expression for #if/#elif */
2643 static int expr_preprocess(void)
2645 int c, t;
2646 TokenString str;
2648 tok_str_new(&str);
2649 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
2650 next(); /* do macro subst */
2651 if (tok == TOK_DEFINED) {
2652 next_nomacro();
2653 t = tok;
2654 if (t == '(')
2655 next_nomacro();
2656 c = define_find(tok) != 0;
2657 if (t == '(')
2658 next_nomacro();
2659 tok = TOK_CINT;
2660 tokc.i = c;
2661 } else if (tok >= TOK_IDENT) {
2662 /* if undefined macro */
2663 tok = TOK_CINT;
2664 tokc.i = 0;
2666 tok_str_add_tok(&str);
2668 tok_str_add(&str, -1); /* simulate end of file */
2669 tok_str_add(&str, 0);
2670 /* now evaluate C constant expression */
2671 macro_ptr = str.str;
2672 next();
2673 c = expr_const();
2674 macro_ptr = NULL;
2675 tok_str_free(str.str);
2676 return c != 0;
2679 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2680 static void tok_print(int *str)
2682 int t;
2683 CValue cval;
2685 while (1) {
2686 TOK_GET(t, str, cval);
2687 if (!t)
2688 break;
2689 printf(" %s", get_tok_str(t, &cval));
2691 printf("\n");
2693 #endif
2695 /* parse after #define */
2696 static void parse_define(void)
2698 Sym *s, *first, **ps;
2699 int v, t, varg, is_vaargs, c;
2700 TokenString str;
2702 v = tok;
2703 if (v < TOK_IDENT)
2704 error("invalid macro name '%s'", get_tok_str(tok, &tokc));
2705 /* XXX: should check if same macro (ANSI) */
2706 first = NULL;
2707 t = MACRO_OBJ;
2708 /* '(' must be just after macro definition for MACRO_FUNC */
2709 c = file->buf_ptr[0];
2710 if (c == '\\')
2711 c = handle_stray1(file->buf_ptr);
2712 if (c == '(') {
2713 next_nomacro();
2714 next_nomacro();
2715 ps = &first;
2716 while (tok != ')') {
2717 varg = tok;
2718 next_nomacro();
2719 is_vaargs = 0;
2720 if (varg == TOK_DOTS) {
2721 varg = TOK___VA_ARGS__;
2722 is_vaargs = 1;
2723 } else if (tok == TOK_DOTS && gnu_ext) {
2724 is_vaargs = 1;
2725 next_nomacro();
2727 if (varg < TOK_IDENT)
2728 error("badly punctuated parameter list");
2729 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
2730 *ps = s;
2731 ps = &s->next;
2732 if (tok != ',')
2733 break;
2734 next_nomacro();
2736 t = MACRO_FUNC;
2738 tok_str_new(&str);
2739 next_nomacro();
2740 /* EOF testing necessary for '-D' handling */
2741 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
2742 tok_str_add2(&str, tok, &tokc);
2743 next_nomacro();
2745 tok_str_add(&str, 0);
2746 #ifdef PP_DEBUG
2747 printf("define %s %d: ", get_tok_str(v, NULL), t);
2748 tok_print(str.str);
2749 #endif
2750 define_push(v, t, str.str, first);
2753 static inline int hash_cached_include(int type, const char *filename)
2755 const unsigned char *s;
2756 unsigned int h;
2758 h = TOK_HASH_INIT;
2759 h = TOK_HASH_FUNC(h, type);
2760 s = filename;
2761 while (*s) {
2762 h = TOK_HASH_FUNC(h, *s);
2763 s++;
2765 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
2766 return h;
2769 /* XXX: use a token or a hash table to accelerate matching ? */
2770 static CachedInclude *search_cached_include(TCCState *s1,
2771 int type, const char *filename)
2773 CachedInclude *e;
2774 int i, h;
2775 h = hash_cached_include(type, filename);
2776 i = s1->cached_includes_hash[h];
2777 for(;;) {
2778 if (i == 0)
2779 break;
2780 e = s1->cached_includes[i - 1];
2781 if (e->type == type && !strcmp(e->filename, filename))
2782 return e;
2783 i = e->hash_next;
2785 return NULL;
2788 static inline void add_cached_include(TCCState *s1, int type,
2789 const char *filename, int ifndef_macro)
2791 CachedInclude *e;
2792 int h;
2794 if (search_cached_include(s1, type, filename))
2795 return;
2796 #ifdef INC_DEBUG
2797 printf("adding cached '%s' %s\n", filename, get_tok_str(ifndef_macro, NULL));
2798 #endif
2799 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
2800 if (!e)
2801 return;
2802 e->type = type;
2803 strcpy(e->filename, filename);
2804 e->ifndef_macro = ifndef_macro;
2805 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
2806 /* add in hash table */
2807 h = hash_cached_include(type, filename);
2808 e->hash_next = s1->cached_includes_hash[h];
2809 s1->cached_includes_hash[h] = s1->nb_cached_includes;
2812 static void pragma_parse(TCCState *s1)
2814 int val;
2816 next();
2817 if (tok == TOK_pack) {
2819 This may be:
2820 #pragma pack(1) // set
2821 #pragma pack() // reset to default
2822 #pragma pack(push,1) // push & set
2823 #pragma pack(pop) // restore previous
2825 next();
2826 skip('(');
2827 if (tok == TOK_ASM_pop) {
2828 next();
2829 if (s1->pack_stack_ptr <= s1->pack_stack) {
2830 stk_error:
2831 error("out of pack stack");
2833 s1->pack_stack_ptr--;
2834 } else {
2835 val = 0;
2836 if (tok != ')') {
2837 if (tok == TOK_ASM_push) {
2838 next();
2839 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
2840 goto stk_error;
2841 s1->pack_stack_ptr++;
2842 skip(',');
2844 if (tok != TOK_CINT) {
2845 pack_error:
2846 error("invalid pack pragma");
2848 val = tokc.i;
2849 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
2850 goto pack_error;
2851 next();
2853 *s1->pack_stack_ptr = val;
2854 skip(')');
2859 /* is_bof is true if first non space token at beginning of file */
2860 static void preprocess(int is_bof)
2862 TCCState *s1 = tcc_state;
2863 int size, i, c, n, saved_parse_flags;
2864 char buf[1024], *q, *p;
2865 char buf1[1024];
2866 BufferedFile *f;
2867 Sym *s;
2868 CachedInclude *e;
2870 saved_parse_flags = parse_flags;
2871 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM |
2872 PARSE_FLAG_LINEFEED;
2873 next_nomacro();
2874 redo:
2875 switch(tok) {
2876 case TOK_DEFINE:
2877 next_nomacro();
2878 parse_define();
2879 break;
2880 case TOK_UNDEF:
2881 next_nomacro();
2882 s = define_find(tok);
2883 /* undefine symbol by putting an invalid name */
2884 if (s)
2885 define_undef(s);
2886 break;
2887 case TOK_INCLUDE:
2888 case TOK_INCLUDE_NEXT:
2889 ch = file->buf_ptr[0];
2890 /* XXX: incorrect if comments : use next_nomacro with a special mode */
2891 skip_spaces();
2892 if (ch == '<') {
2893 c = '>';
2894 goto read_name;
2895 } else if (ch == '\"') {
2896 c = ch;
2897 read_name:
2898 /* XXX: better stray handling */
2899 minp();
2900 q = buf;
2901 while (ch != c && ch != '\n' && ch != CH_EOF) {
2902 if ((q - buf) < sizeof(buf) - 1)
2903 *q++ = ch;
2904 minp();
2906 *q = '\0';
2907 minp();
2908 #if 0
2909 /* eat all spaces and comments after include */
2910 /* XXX: slightly incorrect */
2911 while (ch1 != '\n' && ch1 != CH_EOF)
2912 inp();
2913 #endif
2914 } else {
2915 /* computed #include : either we have only strings or
2916 we have anything enclosed in '<>' */
2917 next();
2918 buf[0] = '\0';
2919 if (tok == TOK_STR) {
2920 while (tok != TOK_LINEFEED) {
2921 if (tok != TOK_STR) {
2922 include_syntax:
2923 error("'#include' expects \"FILENAME\" or <FILENAME>");
2925 pstrcat(buf, sizeof(buf), (char *)tokc.cstr->data);
2926 next();
2928 c = '\"';
2929 } else {
2930 int len;
2931 while (tok != TOK_LINEFEED) {
2932 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
2933 next();
2935 len = strlen(buf);
2936 /* check syntax and remove '<>' */
2937 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
2938 goto include_syntax;
2939 memmove(buf, buf + 1, len - 2);
2940 buf[len - 2] = '\0';
2941 c = '>';
2945 e = search_cached_include(s1, c, buf);
2946 if (e && define_find(e->ifndef_macro)) {
2947 /* no need to parse the include because the 'ifndef macro'
2948 is defined */
2949 #ifdef INC_DEBUG
2950 printf("%s: skipping %s\n", file->filename, buf);
2951 #endif
2952 } else {
2953 if (c == '\"') {
2954 /* first search in current dir if "header.h" */
2955 size = 0;
2956 p = strrchr(file->filename, '/');
2957 if (p)
2958 size = p + 1 - file->filename;
2959 if (size > sizeof(buf1) - 1)
2960 size = sizeof(buf1) - 1;
2961 memcpy(buf1, file->filename, size);
2962 buf1[size] = '\0';
2963 pstrcat(buf1, sizeof(buf1), buf);
2964 f = tcc_open(s1, buf1);
2965 if (f) {
2966 if (tok == TOK_INCLUDE_NEXT)
2967 tok = TOK_INCLUDE;
2968 else
2969 goto found;
2972 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
2973 error("#include recursion too deep");
2974 /* now search in all the include paths */
2975 n = s1->nb_include_paths + s1->nb_sysinclude_paths;
2976 for(i = 0; i < n; i++) {
2977 const char *path;
2978 if (i < s1->nb_include_paths)
2979 path = s1->include_paths[i];
2980 else
2981 path = s1->sysinclude_paths[i - s1->nb_include_paths];
2982 pstrcpy(buf1, sizeof(buf1), path);
2983 pstrcat(buf1, sizeof(buf1), "/");
2984 pstrcat(buf1, sizeof(buf1), buf);
2985 f = tcc_open(s1, buf1);
2986 if (f) {
2987 if (tok == TOK_INCLUDE_NEXT)
2988 tok = TOK_INCLUDE;
2989 else
2990 goto found;
2993 error("include file '%s' not found", buf);
2994 f = NULL;
2995 found:
2996 #ifdef INC_DEBUG
2997 printf("%s: including %s\n", file->filename, buf1);
2998 #endif
2999 f->inc_type = c;
3000 pstrcpy(f->inc_filename, sizeof(f->inc_filename), buf);
3001 /* push current file in stack */
3002 /* XXX: fix current line init */
3003 *s1->include_stack_ptr++ = file;
3004 file = f;
3005 /* add include file debug info */
3006 if (do_debug) {
3007 put_stabs(file->filename, N_BINCL, 0, 0, 0);
3009 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
3010 ch = file->buf_ptr[0];
3011 goto the_end;
3013 break;
3014 case TOK_IFNDEF:
3015 c = 1;
3016 goto do_ifdef;
3017 case TOK_IF:
3018 c = expr_preprocess();
3019 goto do_if;
3020 case TOK_IFDEF:
3021 c = 0;
3022 do_ifdef:
3023 next_nomacro();
3024 if (tok < TOK_IDENT)
3025 error("invalid argument for '#if%sdef'", c ? "n" : "");
3026 if (is_bof) {
3027 if (c) {
3028 #ifdef INC_DEBUG
3029 printf("#ifndef %s\n", get_tok_str(tok, NULL));
3030 #endif
3031 file->ifndef_macro = tok;
3034 c = (define_find(tok) != 0) ^ c;
3035 do_if:
3036 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
3037 error("memory full");
3038 *s1->ifdef_stack_ptr++ = c;
3039 goto test_skip;
3040 case TOK_ELSE:
3041 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
3042 error("#else without matching #if");
3043 if (s1->ifdef_stack_ptr[-1] & 2)
3044 error("#else after #else");
3045 c = (s1->ifdef_stack_ptr[-1] ^= 3);
3046 goto test_skip;
3047 case TOK_ELIF:
3048 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
3049 error("#elif without matching #if");
3050 c = s1->ifdef_stack_ptr[-1];
3051 if (c > 1)
3052 error("#elif after #else");
3053 /* last #if/#elif expression was true: we skip */
3054 if (c == 1)
3055 goto skip;
3056 c = expr_preprocess();
3057 s1->ifdef_stack_ptr[-1] = c;
3058 test_skip:
3059 if (!(c & 1)) {
3060 skip:
3061 preprocess_skip();
3062 is_bof = 0;
3063 goto redo;
3065 break;
3066 case TOK_ENDIF:
3067 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
3068 error("#endif without matching #if");
3069 s1->ifdef_stack_ptr--;
3070 /* '#ifndef macro' was at the start of file. Now we check if
3071 an '#endif' is exactly at the end of file */
3072 if (file->ifndef_macro &&
3073 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
3074 file->ifndef_macro_saved = file->ifndef_macro;
3075 /* need to set to zero to avoid false matches if another
3076 #ifndef at middle of file */
3077 file->ifndef_macro = 0;
3078 while (tok != TOK_LINEFEED)
3079 next_nomacro();
3080 tok_flags |= TOK_FLAG_ENDIF;
3081 goto the_end;
3083 break;
3084 case TOK_LINE:
3085 next();
3086 if (tok != TOK_CINT)
3087 error("#line");
3088 file->line_num = tokc.i - 1; /* the line number will be incremented after */
3089 next();
3090 if (tok != TOK_LINEFEED) {
3091 if (tok != TOK_STR)
3092 error("#line");
3093 pstrcpy(file->filename, sizeof(file->filename),
3094 (char *)tokc.cstr->data);
3096 break;
3097 case TOK_ERROR:
3098 case TOK_WARNING:
3099 c = tok;
3100 ch = file->buf_ptr[0];
3101 skip_spaces();
3102 q = buf;
3103 while (ch != '\n' && ch != CH_EOF) {
3104 if ((q - buf) < sizeof(buf) - 1)
3105 *q++ = ch;
3106 minp();
3108 *q = '\0';
3109 if (c == TOK_ERROR)
3110 error("#error %s", buf);
3111 else
3112 warning("#warning %s", buf);
3113 break;
3114 case TOK_PRAGMA:
3115 pragma_parse(s1);
3116 break;
3117 default:
3118 if (tok == TOK_LINEFEED || tok == '!' || tok == TOK_CINT) {
3119 /* '!' is ignored to allow C scripts. numbers are ignored
3120 to emulate cpp behaviour */
3121 } else {
3122 if (!(saved_parse_flags & PARSE_FLAG_ASM_COMMENTS))
3123 error("invalid preprocessing directive #%s", get_tok_str(tok, &tokc));
3125 break;
3127 /* ignore other preprocess commands or #! for C scripts */
3128 while (tok != TOK_LINEFEED)
3129 next_nomacro();
3130 the_end:
3131 parse_flags = saved_parse_flags;
3134 /* evaluate escape codes in a string. */
3135 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
3137 int c, n;
3138 const uint8_t *p;
3140 p = buf;
3141 for(;;) {
3142 c = *p;
3143 if (c == '\0')
3144 break;
3145 if (c == '\\') {
3146 p++;
3147 /* escape */
3148 c = *p;
3149 switch(c) {
3150 case '0': case '1': case '2': case '3':
3151 case '4': case '5': case '6': case '7':
3152 /* at most three octal digits */
3153 n = c - '0';
3154 p++;
3155 c = *p;
3156 if (isoct(c)) {
3157 n = n * 8 + c - '0';
3158 p++;
3159 c = *p;
3160 if (isoct(c)) {
3161 n = n * 8 + c - '0';
3162 p++;
3165 c = n;
3166 goto add_char_nonext;
3167 case 'x':
3168 case 'u':
3169 case 'U':
3170 p++;
3171 n = 0;
3172 for(;;) {
3173 c = *p;
3174 if (c >= 'a' && c <= 'f')
3175 c = c - 'a' + 10;
3176 else if (c >= 'A' && c <= 'F')
3177 c = c - 'A' + 10;
3178 else if (isnum(c))
3179 c = c - '0';
3180 else
3181 break;
3182 n = n * 16 + c;
3183 p++;
3185 c = n;
3186 goto add_char_nonext;
3187 case 'a':
3188 c = '\a';
3189 break;
3190 case 'b':
3191 c = '\b';
3192 break;
3193 case 'f':
3194 c = '\f';
3195 break;
3196 case 'n':
3197 c = '\n';
3198 break;
3199 case 'r':
3200 c = '\r';
3201 break;
3202 case 't':
3203 c = '\t';
3204 break;
3205 case 'v':
3206 c = '\v';
3207 break;
3208 case 'e':
3209 if (!gnu_ext)
3210 goto invalid_escape;
3211 c = 27;
3212 break;
3213 case '\'':
3214 case '\"':
3215 case '\\':
3216 case '?':
3217 break;
3218 default:
3219 invalid_escape:
3220 if (c >= '!' && c <= '~')
3221 warning("unknown escape sequence: \'\\%c\'", c);
3222 else
3223 warning("unknown escape sequence: \'\\x%x\'", c);
3224 break;
3227 p++;
3228 add_char_nonext:
3229 if (!is_long)
3230 cstr_ccat(outstr, c);
3231 else
3232 cstr_wccat(outstr, c);
3234 /* add a trailing '\0' */
3235 if (!is_long)
3236 cstr_ccat(outstr, '\0');
3237 else
3238 cstr_wccat(outstr, '\0');
3241 /* we use 64 bit numbers */
3242 #define BN_SIZE 2
3244 /* bn = (bn << shift) | or_val */
3245 void bn_lshift(unsigned int *bn, int shift, int or_val)
3247 int i;
3248 unsigned int v;
3249 for(i=0;i<BN_SIZE;i++) {
3250 v = bn[i];
3251 bn[i] = (v << shift) | or_val;
3252 or_val = v >> (32 - shift);
3256 void bn_zero(unsigned int *bn)
3258 int i;
3259 for(i=0;i<BN_SIZE;i++) {
3260 bn[i] = 0;
3264 /* parse number in null terminated string 'p' and return it in the
3265 current token */
3266 void parse_number(const char *p)
3268 int b, t, shift, frac_bits, s, exp_val, ch;
3269 char *q;
3270 unsigned int bn[BN_SIZE];
3271 double d;
3273 /* number */
3274 q = token_buf;
3275 ch = *p++;
3276 t = ch;
3277 ch = *p++;
3278 *q++ = t;
3279 b = 10;
3280 if (t == '.') {
3281 goto float_frac_parse;
3282 } else if (t == '0') {
3283 if (ch == 'x' || ch == 'X') {
3284 q--;
3285 ch = *p++;
3286 b = 16;
3287 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
3288 q--;
3289 ch = *p++;
3290 b = 2;
3293 /* parse all digits. cannot check octal numbers at this stage
3294 because of floating point constants */
3295 while (1) {
3296 if (ch >= 'a' && ch <= 'f')
3297 t = ch - 'a' + 10;
3298 else if (ch >= 'A' && ch <= 'F')
3299 t = ch - 'A' + 10;
3300 else if (isnum(ch))
3301 t = ch - '0';
3302 else
3303 break;
3304 if (t >= b)
3305 break;
3306 if (q >= token_buf + STRING_MAX_SIZE) {
3307 num_too_long:
3308 error("number too long");
3310 *q++ = ch;
3311 ch = *p++;
3313 if (ch == '.' ||
3314 ((ch == 'e' || ch == 'E') && b == 10) ||
3315 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
3316 if (b != 10) {
3317 /* NOTE: strtox should support that for hexa numbers, but
3318 non ISOC99 libcs do not support it, so we prefer to do
3319 it by hand */
3320 /* hexadecimal or binary floats */
3321 /* XXX: handle overflows */
3322 *q = '\0';
3323 if (b == 16)
3324 shift = 4;
3325 else
3326 shift = 2;
3327 bn_zero(bn);
3328 q = token_buf;
3329 while (1) {
3330 t = *q++;
3331 if (t == '\0') {
3332 break;
3333 } else if (t >= 'a') {
3334 t = t - 'a' + 10;
3335 } else if (t >= 'A') {
3336 t = t - 'A' + 10;
3337 } else {
3338 t = t - '0';
3340 bn_lshift(bn, shift, t);
3342 frac_bits = 0;
3343 if (ch == '.') {
3344 ch = *p++;
3345 while (1) {
3346 t = ch;
3347 if (t >= 'a' && t <= 'f') {
3348 t = t - 'a' + 10;
3349 } else if (t >= 'A' && t <= 'F') {
3350 t = t - 'A' + 10;
3351 } else if (t >= '0' && t <= '9') {
3352 t = t - '0';
3353 } else {
3354 break;
3356 if (t >= b)
3357 error("invalid digit");
3358 bn_lshift(bn, shift, t);
3359 frac_bits += shift;
3360 ch = *p++;
3363 if (ch != 'p' && ch != 'P')
3364 expect("exponent");
3365 ch = *p++;
3366 s = 1;
3367 exp_val = 0;
3368 if (ch == '+') {
3369 ch = *p++;
3370 } else if (ch == '-') {
3371 s = -1;
3372 ch = *p++;
3374 if (ch < '0' || ch > '9')
3375 expect("exponent digits");
3376 while (ch >= '0' && ch <= '9') {
3377 exp_val = exp_val * 10 + ch - '0';
3378 ch = *p++;
3380 exp_val = exp_val * s;
3382 /* now we can generate the number */
3383 /* XXX: should patch directly float number */
3384 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
3385 d = ldexp(d, exp_val - frac_bits);
3386 t = toup(ch);
3387 if (t == 'F') {
3388 ch = *p++;
3389 tok = TOK_CFLOAT;
3390 /* float : should handle overflow */
3391 tokc.f = (float)d;
3392 } else if (t == 'L') {
3393 ch = *p++;
3394 tok = TOK_CLDOUBLE;
3395 /* XXX: not large enough */
3396 tokc.ld = (long double)d;
3397 } else {
3398 tok = TOK_CDOUBLE;
3399 tokc.d = d;
3401 } else {
3402 /* decimal floats */
3403 if (ch == '.') {
3404 if (q >= token_buf + STRING_MAX_SIZE)
3405 goto num_too_long;
3406 *q++ = ch;
3407 ch = *p++;
3408 float_frac_parse:
3409 while (ch >= '0' && ch <= '9') {
3410 if (q >= token_buf + STRING_MAX_SIZE)
3411 goto num_too_long;
3412 *q++ = ch;
3413 ch = *p++;
3416 if (ch == 'e' || ch == 'E') {
3417 if (q >= token_buf + STRING_MAX_SIZE)
3418 goto num_too_long;
3419 *q++ = ch;
3420 ch = *p++;
3421 if (ch == '-' || ch == '+') {
3422 if (q >= token_buf + STRING_MAX_SIZE)
3423 goto num_too_long;
3424 *q++ = ch;
3425 ch = *p++;
3427 if (ch < '0' || ch > '9')
3428 expect("exponent digits");
3429 while (ch >= '0' && ch <= '9') {
3430 if (q >= token_buf + STRING_MAX_SIZE)
3431 goto num_too_long;
3432 *q++ = ch;
3433 ch = *p++;
3436 *q = '\0';
3437 t = toup(ch);
3438 errno = 0;
3439 if (t == 'F') {
3440 ch = *p++;
3441 tok = TOK_CFLOAT;
3442 tokc.f = strtof(token_buf, NULL);
3443 } else if (t == 'L') {
3444 ch = *p++;
3445 tok = TOK_CLDOUBLE;
3446 tokc.ld = strtold(token_buf, NULL);
3447 } else {
3448 tok = TOK_CDOUBLE;
3449 tokc.d = strtod(token_buf, NULL);
3452 } else {
3453 unsigned long long n, n1;
3454 int lcount, ucount;
3456 /* integer number */
3457 *q = '\0';
3458 q = token_buf;
3459 if (b == 10 && *q == '0') {
3460 b = 8;
3461 q++;
3463 n = 0;
3464 while(1) {
3465 t = *q++;
3466 /* no need for checks except for base 10 / 8 errors */
3467 if (t == '\0') {
3468 break;
3469 } else if (t >= 'a') {
3470 t = t - 'a' + 10;
3471 } else if (t >= 'A') {
3472 t = t - 'A' + 10;
3473 } else {
3474 t = t - '0';
3475 if (t >= b)
3476 error("invalid digit");
3478 n1 = n;
3479 n = n * b + t;
3480 /* detect overflow */
3481 /* XXX: this test is not reliable */
3482 if (n < n1)
3483 error("integer constant overflow");
3486 /* XXX: not exactly ANSI compliant */
3487 if ((n & 0xffffffff00000000LL) != 0) {
3488 if ((n >> 63) != 0)
3489 tok = TOK_CULLONG;
3490 else
3491 tok = TOK_CLLONG;
3492 } else if (n > 0x7fffffff) {
3493 tok = TOK_CUINT;
3494 } else {
3495 tok = TOK_CINT;
3497 lcount = 0;
3498 ucount = 0;
3499 for(;;) {
3500 t = toup(ch);
3501 if (t == 'L') {
3502 if (lcount >= 2)
3503 error("three 'l's in integer constant");
3504 lcount++;
3505 if (lcount == 2) {
3506 if (tok == TOK_CINT)
3507 tok = TOK_CLLONG;
3508 else if (tok == TOK_CUINT)
3509 tok = TOK_CULLONG;
3511 ch = *p++;
3512 } else if (t == 'U') {
3513 if (ucount >= 1)
3514 error("two 'u's in integer constant");
3515 ucount++;
3516 if (tok == TOK_CINT)
3517 tok = TOK_CUINT;
3518 else if (tok == TOK_CLLONG)
3519 tok = TOK_CULLONG;
3520 ch = *p++;
3521 } else {
3522 break;
3525 if (tok == TOK_CINT || tok == TOK_CUINT)
3526 tokc.ui = n;
3527 else
3528 tokc.ull = n;
3533 #define PARSE2(c1, tok1, c2, tok2) \
3534 case c1: \
3535 PEEKC(c, p); \
3536 if (c == c2) { \
3537 p++; \
3538 tok = tok2; \
3539 } else { \
3540 tok = tok1; \
3542 break;
3544 /* return next token without macro substitution */
3545 static inline void next_nomacro1(void)
3547 int t, c, is_long;
3548 TokenSym *ts;
3549 uint8_t *p, *p1;
3550 unsigned int h;
3552 p = file->buf_ptr;
3553 redo_no_start:
3554 c = *p;
3555 switch(c) {
3556 case ' ':
3557 case '\t':
3558 case '\f':
3559 case '\v':
3560 case '\r':
3561 p++;
3562 goto redo_no_start;
3564 case '\\':
3565 /* first look if it is in fact an end of buffer */
3566 if (p >= file->buf_end) {
3567 file->buf_ptr = p;
3568 handle_eob();
3569 p = file->buf_ptr;
3570 if (p >= file->buf_end)
3571 goto parse_eof;
3572 else
3573 goto redo_no_start;
3574 } else {
3575 file->buf_ptr = p;
3576 ch = *p;
3577 handle_stray();
3578 p = file->buf_ptr;
3579 goto redo_no_start;
3581 parse_eof:
3583 TCCState *s1 = tcc_state;
3584 if ((parse_flags & PARSE_FLAG_LINEFEED)
3585 && !(tok_flags & TOK_FLAG_EOF)) {
3586 tok_flags |= TOK_FLAG_EOF;
3587 tok = TOK_LINEFEED;
3588 goto keep_tok_flags;
3589 } else if (s1->include_stack_ptr == s1->include_stack ||
3590 !(parse_flags & PARSE_FLAG_PREPROCESS)) {
3591 /* no include left : end of file. */
3592 tok = TOK_EOF;
3593 } else {
3594 tok_flags &= ~TOK_FLAG_EOF;
3595 /* pop include file */
3597 /* test if previous '#endif' was after a #ifdef at
3598 start of file */
3599 if (tok_flags & TOK_FLAG_ENDIF) {
3600 #ifdef INC_DEBUG
3601 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
3602 #endif
3603 add_cached_include(s1, file->inc_type, file->inc_filename,
3604 file->ifndef_macro_saved);
3607 /* add end of include file debug info */
3608 if (do_debug) {
3609 put_stabd(N_EINCL, 0, 0);
3611 /* pop include stack */
3612 tcc_close(file);
3613 s1->include_stack_ptr--;
3614 file = *s1->include_stack_ptr;
3615 p = file->buf_ptr;
3616 goto redo_no_start;
3619 break;
3621 case '\n':
3622 file->line_num++;
3623 tok_flags |= TOK_FLAG_BOL;
3624 p++;
3625 if (0 == (parse_flags & PARSE_FLAG_LINEFEED))
3626 goto redo_no_start;
3627 tok = TOK_LINEFEED;
3628 goto keep_tok_flags;
3630 case '#':
3631 /* XXX: simplify */
3632 PEEKC(c, p);
3633 if ((tok_flags & TOK_FLAG_BOL) &&
3634 (parse_flags & PARSE_FLAG_PREPROCESS)) {
3635 file->buf_ptr = p;
3636 preprocess(tok_flags & TOK_FLAG_BOF);
3637 p = file->buf_ptr;
3638 goto redo_no_start;
3639 } else {
3640 if (c == '#') {
3641 p++;
3642 tok = TOK_TWOSHARPS;
3643 } else {
3644 if (parse_flags & PARSE_FLAG_ASM_COMMENTS) {
3645 p = parse_line_comment(p - 1);
3646 goto redo_no_start;
3647 } else {
3648 tok = '#';
3652 break;
3654 case 'a': case 'b': case 'c': case 'd':
3655 case 'e': case 'f': case 'g': case 'h':
3656 case 'i': case 'j': case 'k': case 'l':
3657 case 'm': case 'n': case 'o': case 'p':
3658 case 'q': case 'r': case 's': case 't':
3659 case 'u': case 'v': case 'w': case 'x':
3660 case 'y': case 'z':
3661 case 'A': case 'B': case 'C': case 'D':
3662 case 'E': case 'F': case 'G': case 'H':
3663 case 'I': case 'J': case 'K':
3664 case 'M': case 'N': case 'O': case 'P':
3665 case 'Q': case 'R': case 'S': case 'T':
3666 case 'U': case 'V': case 'W': case 'X':
3667 case 'Y': case 'Z':
3668 case '_':
3669 parse_ident_fast:
3670 p1 = p;
3671 h = TOK_HASH_INIT;
3672 h = TOK_HASH_FUNC(h, c);
3673 p++;
3674 for(;;) {
3675 c = *p;
3676 if (!isidnum_table[c])
3677 break;
3678 h = TOK_HASH_FUNC(h, c);
3679 p++;
3681 if (c != '\\') {
3682 TokenSym **pts;
3683 int len;
3685 /* fast case : no stray found, so we have the full token
3686 and we have already hashed it */
3687 len = p - p1;
3688 h &= (TOK_HASH_SIZE - 1);
3689 pts = &hash_ident[h];
3690 for(;;) {
3691 ts = *pts;
3692 if (!ts)
3693 break;
3694 if (ts->len == len && !memcmp(ts->str, p1, len))
3695 goto token_found;
3696 pts = &(ts->hash_next);
3698 ts = tok_alloc_new(pts, p1, len);
3699 token_found: ;
3700 } else {
3701 /* slower case */
3702 cstr_reset(&tokcstr);
3704 while (p1 < p) {
3705 cstr_ccat(&tokcstr, *p1);
3706 p1++;
3708 p--;
3709 PEEKC(c, p);
3710 parse_ident_slow:
3711 while (isidnum_table[c]) {
3712 cstr_ccat(&tokcstr, c);
3713 PEEKC(c, p);
3715 ts = tok_alloc(tokcstr.data, tokcstr.size);
3717 tok = ts->tok;
3718 break;
3719 case 'L':
3720 t = p[1];
3721 if (t != '\\' && t != '\'' && t != '\"') {
3722 /* fast case */
3723 goto parse_ident_fast;
3724 } else {
3725 PEEKC(c, p);
3726 if (c == '\'' || c == '\"') {
3727 is_long = 1;
3728 goto str_const;
3729 } else {
3730 cstr_reset(&tokcstr);
3731 cstr_ccat(&tokcstr, 'L');
3732 goto parse_ident_slow;
3735 break;
3736 case '0': case '1': case '2': case '3':
3737 case '4': case '5': case '6': case '7':
3738 case '8': case '9':
3740 cstr_reset(&tokcstr);
3741 /* after the first digit, accept digits, alpha, '.' or sign if
3742 prefixed by 'eEpP' */
3743 parse_num:
3744 for(;;) {
3745 t = c;
3746 cstr_ccat(&tokcstr, c);
3747 PEEKC(c, p);
3748 if (!(isnum(c) || isid(c) || c == '.' ||
3749 ((c == '+' || c == '-') &&
3750 (t == 'e' || t == 'E' || t == 'p' || t == 'P'))))
3751 break;
3753 /* We add a trailing '\0' to ease parsing */
3754 cstr_ccat(&tokcstr, '\0');
3755 tokc.cstr = &tokcstr;
3756 tok = TOK_PPNUM;
3757 break;
3758 case '.':
3759 /* special dot handling because it can also start a number */
3760 PEEKC(c, p);
3761 if (isnum(c)) {
3762 cstr_reset(&tokcstr);
3763 cstr_ccat(&tokcstr, '.');
3764 goto parse_num;
3765 } else if (c == '.') {
3766 PEEKC(c, p);
3767 if (c != '.')
3768 expect("'.'");
3769 PEEKC(c, p);
3770 tok = TOK_DOTS;
3771 } else {
3772 tok = '.';
3774 break;
3775 case '\'':
3776 case '\"':
3777 is_long = 0;
3778 str_const:
3780 CString str;
3781 int sep;
3783 sep = c;
3785 /* parse the string */
3786 cstr_new(&str);
3787 p = parse_pp_string(p, sep, &str);
3788 cstr_ccat(&str, '\0');
3790 /* eval the escape (should be done as TOK_PPNUM) */
3791 cstr_reset(&tokcstr);
3792 parse_escape_string(&tokcstr, str.data, is_long);
3793 cstr_free(&str);
3795 if (sep == '\'') {
3796 int char_size;
3797 /* XXX: make it portable */
3798 if (!is_long)
3799 char_size = 1;
3800 else
3801 char_size = sizeof(nwchar_t);
3802 if (tokcstr.size <= char_size)
3803 error("empty character constant");
3804 if (tokcstr.size > 2 * char_size)
3805 warning("multi-character character constant");
3806 if (!is_long) {
3807 tokc.i = *(int8_t *)tokcstr.data;
3808 tok = TOK_CCHAR;
3809 } else {
3810 tokc.i = *(nwchar_t *)tokcstr.data;
3811 tok = TOK_LCHAR;
3813 } else {
3814 tokc.cstr = &tokcstr;
3815 if (!is_long)
3816 tok = TOK_STR;
3817 else
3818 tok = TOK_LSTR;
3821 break;
3823 case '<':
3824 PEEKC(c, p);
3825 if (c == '=') {
3826 p++;
3827 tok = TOK_LE;
3828 } else if (c == '<') {
3829 PEEKC(c, p);
3830 if (c == '=') {
3831 p++;
3832 tok = TOK_A_SHL;
3833 } else {
3834 tok = TOK_SHL;
3836 } else {
3837 tok = TOK_LT;
3839 break;
3841 case '>':
3842 PEEKC(c, p);
3843 if (c == '=') {
3844 p++;
3845 tok = TOK_GE;
3846 } else if (c == '>') {
3847 PEEKC(c, p);
3848 if (c == '=') {
3849 p++;
3850 tok = TOK_A_SAR;
3851 } else {
3852 tok = TOK_SAR;
3854 } else {
3855 tok = TOK_GT;
3857 break;
3859 case '&':
3860 PEEKC(c, p);
3861 if (c == '&') {
3862 p++;
3863 tok = TOK_LAND;
3864 } else if (c == '=') {
3865 p++;
3866 tok = TOK_A_AND;
3867 } else {
3868 tok = '&';
3870 break;
3872 case '|':
3873 PEEKC(c, p);
3874 if (c == '|') {
3875 p++;
3876 tok = TOK_LOR;
3877 } else if (c == '=') {
3878 p++;
3879 tok = TOK_A_OR;
3880 } else {
3881 tok = '|';
3883 break;
3885 case '+':
3886 PEEKC(c, p);
3887 if (c == '+') {
3888 p++;
3889 tok = TOK_INC;
3890 } else if (c == '=') {
3891 p++;
3892 tok = TOK_A_ADD;
3893 } else {
3894 tok = '+';
3896 break;
3898 case '-':
3899 PEEKC(c, p);
3900 if (c == '-') {
3901 p++;
3902 tok = TOK_DEC;
3903 } else if (c == '=') {
3904 p++;
3905 tok = TOK_A_SUB;
3906 } else if (c == '>') {
3907 p++;
3908 tok = TOK_ARROW;
3909 } else {
3910 tok = '-';
3912 break;
3914 PARSE2('!', '!', '=', TOK_NE)
3915 PARSE2('=', '=', '=', TOK_EQ)
3916 PARSE2('*', '*', '=', TOK_A_MUL)
3917 PARSE2('%', '%', '=', TOK_A_MOD)
3918 PARSE2('^', '^', '=', TOK_A_XOR)
3920 /* comments or operator */
3921 case '/':
3922 PEEKC(c, p);
3923 if (c == '*') {
3924 p = parse_comment(p);
3925 goto redo_no_start;
3926 } else if (c == '/') {
3927 p = parse_line_comment(p);
3928 goto redo_no_start;
3929 } else if (c == '=') {
3930 p++;
3931 tok = TOK_A_DIV;
3932 } else {
3933 tok = '/';
3935 break;
3937 /* simple tokens */
3938 case '(':
3939 case ')':
3940 case '[':
3941 case ']':
3942 case '{':
3943 case '}':
3944 case ',':
3945 case ';':
3946 case ':':
3947 case '?':
3948 case '~':
3949 case '$': /* only used in assembler */
3950 case '@': /* dito */
3951 tok = c;
3952 p++;
3953 break;
3954 default:
3955 error("unrecognized character \\x%02x", c);
3956 break;
3958 tok_flags = 0;
3959 keep_tok_flags:
3960 file->buf_ptr = p;
3961 #if defined(PARSE_DEBUG)
3962 printf("token = %s\n", get_tok_str(tok, &tokc));
3963 #endif
3966 /* return next token without macro substitution. Can read input from
3967 macro_ptr buffer */
3968 static void next_nomacro(void)
3970 if (macro_ptr) {
3971 redo:
3972 tok = *macro_ptr;
3973 if (tok) {
3974 TOK_GET(tok, macro_ptr, tokc);
3975 if (tok == TOK_LINENUM) {
3976 file->line_num = tokc.i;
3977 goto redo;
3980 } else {
3981 next_nomacro1();
3985 /* substitute args in macro_str and return allocated string */
3986 static int *macro_arg_subst(Sym **nested_list, int *macro_str, Sym *args)
3988 int *st, last_tok, t, notfirst;
3989 Sym *s;
3990 CValue cval;
3991 TokenString str;
3992 CString cstr;
3994 tok_str_new(&str);
3995 last_tok = 0;
3996 while(1) {
3997 TOK_GET(t, macro_str, cval);
3998 if (!t)
3999 break;
4000 if (t == '#') {
4001 /* stringize */
4002 TOK_GET(t, macro_str, cval);
4003 if (!t)
4004 break;
4005 s = sym_find2(args, t);
4006 if (s) {
4007 cstr_new(&cstr);
4008 st = (int *)s->c;
4009 notfirst = 0;
4010 while (*st) {
4011 if (notfirst)
4012 cstr_ccat(&cstr, ' ');
4013 TOK_GET(t, st, cval);
4014 cstr_cat(&cstr, get_tok_str(t, &cval));
4015 notfirst = 1;
4017 cstr_ccat(&cstr, '\0');
4018 #ifdef PP_DEBUG
4019 printf("stringize: %s\n", (char *)cstr.data);
4020 #endif
4021 /* add string */
4022 cval.cstr = &cstr;
4023 tok_str_add2(&str, TOK_STR, &cval);
4024 cstr_free(&cstr);
4025 } else {
4026 tok_str_add2(&str, t, &cval);
4028 } else if (t >= TOK_IDENT) {
4029 s = sym_find2(args, t);
4030 if (s) {
4031 st = (int *)s->c;
4032 /* if '##' is present before or after, no arg substitution */
4033 if (*macro_str == TOK_TWOSHARPS || last_tok == TOK_TWOSHARPS) {
4034 /* special case for var arg macros : ## eats the
4035 ',' if empty VA_ARGS variable. */
4036 /* XXX: test of the ',' is not 100%
4037 reliable. should fix it to avoid security
4038 problems */
4039 if (gnu_ext && s->type.t &&
4040 last_tok == TOK_TWOSHARPS &&
4041 str.len >= 2 && str.str[str.len - 2] == ',') {
4042 if (*st == 0) {
4043 /* suppress ',' '##' */
4044 str.len -= 2;
4045 } else {
4046 /* suppress '##' and add variable */
4047 str.len--;
4048 goto add_var;
4050 } else {
4051 int t1;
4052 add_var:
4053 for(;;) {
4054 TOK_GET(t1, st, cval);
4055 if (!t1)
4056 break;
4057 tok_str_add2(&str, t1, &cval);
4060 } else {
4061 /* NOTE: the stream cannot be read when macro
4062 substituing an argument */
4063 macro_subst(&str, nested_list, st, NULL);
4065 } else {
4066 tok_str_add(&str, t);
4068 } else {
4069 tok_str_add2(&str, t, &cval);
4071 last_tok = t;
4073 tok_str_add(&str, 0);
4074 return str.str;
4077 static char const ab_month_name[12][4] =
4079 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
4080 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
4083 /* do macro substitution of current token with macro 's' and add
4084 result to (tok_str,tok_len). 'nested_list' is the list of all
4085 macros we got inside to avoid recursing. Return non zero if no
4086 substitution needs to be done */
4087 static int macro_subst_tok(TokenString *tok_str,
4088 Sym **nested_list, Sym *s, struct macro_level **can_read_stream)
4090 Sym *args, *sa, *sa1;
4091 int mstr_allocated, parlevel, *mstr, t, t1;
4092 TokenString str;
4093 char *cstrval;
4094 CValue cval;
4095 CString cstr;
4096 char buf[32];
4098 /* if symbol is a macro, prepare substitution */
4099 /* special macros */
4100 if (tok == TOK___LINE__) {
4101 snprintf(buf, sizeof(buf), "%d", file->line_num);
4102 cstrval = buf;
4103 t1 = TOK_PPNUM;
4104 goto add_cstr1;
4105 } else if (tok == TOK___FILE__) {
4106 cstrval = file->filename;
4107 goto add_cstr;
4108 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
4109 time_t ti;
4110 struct tm *tm;
4112 time(&ti);
4113 tm = localtime(&ti);
4114 if (tok == TOK___DATE__) {
4115 snprintf(buf, sizeof(buf), "%s %2d %d",
4116 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
4117 } else {
4118 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
4119 tm->tm_hour, tm->tm_min, tm->tm_sec);
4121 cstrval = buf;
4122 add_cstr:
4123 t1 = TOK_STR;
4124 add_cstr1:
4125 cstr_new(&cstr);
4126 cstr_cat(&cstr, cstrval);
4127 cstr_ccat(&cstr, '\0');
4128 cval.cstr = &cstr;
4129 tok_str_add2(tok_str, t1, &cval);
4130 cstr_free(&cstr);
4131 } else {
4132 mstr = (int *)s->c;
4133 mstr_allocated = 0;
4134 if (s->type.t == MACRO_FUNC) {
4135 /* NOTE: we do not use next_nomacro to avoid eating the
4136 next token. XXX: find better solution */
4137 redo:
4138 if (macro_ptr) {
4139 t = *macro_ptr;
4140 if (t == 0 && can_read_stream) {
4141 /* end of macro stream: we must look at the token
4142 after in the file */
4143 struct macro_level *ml = *can_read_stream;
4144 macro_ptr = NULL;
4145 if (ml)
4147 macro_ptr = ml->p;
4148 ml->p = NULL;
4149 *can_read_stream = ml -> prev;
4151 goto redo;
4153 } else {
4154 /* XXX: incorrect with comments */
4155 ch = file->buf_ptr[0];
4156 while (is_space(ch) || ch == '\n')
4157 cinp();
4158 t = ch;
4160 if (t != '(') /* no macro subst */
4161 return -1;
4163 /* argument macro */
4164 next_nomacro();
4165 next_nomacro();
4166 args = NULL;
4167 sa = s->next;
4168 /* NOTE: empty args are allowed, except if no args */
4169 for(;;) {
4170 /* handle '()' case */
4171 if (!args && !sa && tok == ')')
4172 break;
4173 if (!sa)
4174 error("macro '%s' used with too many args",
4175 get_tok_str(s->v, 0));
4176 tok_str_new(&str);
4177 parlevel = 0;
4178 /* NOTE: non zero sa->t indicates VA_ARGS */
4179 while ((parlevel > 0 ||
4180 (tok != ')' &&
4181 (tok != ',' || sa->type.t))) &&
4182 tok != -1) {
4183 if (tok == '(')
4184 parlevel++;
4185 else if (tok == ')')
4186 parlevel--;
4187 if (tok != TOK_LINEFEED)
4188 tok_str_add2(&str, tok, &tokc);
4189 next_nomacro();
4191 tok_str_add(&str, 0);
4192 sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, (int)str.str);
4193 sa = sa->next;
4194 if (tok == ')') {
4195 /* special case for gcc var args: add an empty
4196 var arg argument if it is omitted */
4197 if (sa && sa->type.t && gnu_ext)
4198 continue;
4199 else
4200 break;
4202 if (tok != ',')
4203 expect(",");
4204 next_nomacro();
4206 if (sa) {
4207 error("macro '%s' used with too few args",
4208 get_tok_str(s->v, 0));
4211 /* now subst each arg */
4212 mstr = macro_arg_subst(nested_list, mstr, args);
4213 /* free memory */
4214 sa = args;
4215 while (sa) {
4216 sa1 = sa->prev;
4217 tok_str_free((int *)sa->c);
4218 sym_free(sa);
4219 sa = sa1;
4221 mstr_allocated = 1;
4223 sym_push2(nested_list, s->v, 0, 0);
4224 macro_subst(tok_str, nested_list, mstr, can_read_stream);
4225 /* pop nested defined symbol */
4226 sa1 = *nested_list;
4227 *nested_list = sa1->prev;
4228 sym_free(sa1);
4229 if (mstr_allocated)
4230 tok_str_free(mstr);
4232 return 0;
4235 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4236 return the resulting string (which must be freed). */
4237 static inline int *macro_twosharps(const int *macro_str)
4239 TokenSym *ts;
4240 const int *macro_ptr1, *start_macro_ptr, *ptr, *saved_macro_ptr;
4241 int t;
4242 const char *p1, *p2;
4243 CValue cval;
4244 TokenString macro_str1;
4245 CString cstr;
4247 start_macro_ptr = macro_str;
4248 /* we search the first '##' */
4249 for(;;) {
4250 macro_ptr1 = macro_str;
4251 TOK_GET(t, macro_str, cval);
4252 /* nothing more to do if end of string */
4253 if (t == 0)
4254 return NULL;
4255 if (*macro_str == TOK_TWOSHARPS)
4256 break;
4259 /* we saw '##', so we need more processing to handle it */
4260 cstr_new(&cstr);
4261 tok_str_new(&macro_str1);
4262 tok = t;
4263 tokc = cval;
4265 /* add all tokens seen so far */
4266 for(ptr = start_macro_ptr; ptr < macro_ptr1;) {
4267 TOK_GET(t, ptr, cval);
4268 tok_str_add2(&macro_str1, t, &cval);
4270 saved_macro_ptr = macro_ptr;
4271 /* XXX: get rid of the use of macro_ptr here */
4272 macro_ptr = (int *)macro_str;
4273 for(;;) {
4274 while (*macro_ptr == TOK_TWOSHARPS) {
4275 macro_ptr++;
4276 macro_ptr1 = macro_ptr;
4277 t = *macro_ptr;
4278 if (t) {
4279 TOK_GET(t, macro_ptr, cval);
4280 /* We concatenate the two tokens if we have an
4281 identifier or a preprocessing number */
4282 cstr_reset(&cstr);
4283 p1 = get_tok_str(tok, &tokc);
4284 cstr_cat(&cstr, p1);
4285 p2 = get_tok_str(t, &cval);
4286 cstr_cat(&cstr, p2);
4287 cstr_ccat(&cstr, '\0');
4289 if ((tok >= TOK_IDENT || tok == TOK_PPNUM) &&
4290 (t >= TOK_IDENT || t == TOK_PPNUM)) {
4291 if (tok == TOK_PPNUM) {
4292 /* if number, then create a number token */
4293 /* NOTE: no need to allocate because
4294 tok_str_add2() does it */
4295 cstr_reset(&tokcstr);
4296 tokcstr = cstr;
4297 cstr_new(&cstr);
4298 tokc.cstr = &tokcstr;
4299 } else {
4300 /* if identifier, we must do a test to
4301 validate we have a correct identifier */
4302 if (t == TOK_PPNUM) {
4303 const char *p;
4304 int c;
4306 p = p2;
4307 for(;;) {
4308 c = *p;
4309 if (c == '\0')
4310 break;
4311 p++;
4312 if (!isnum(c) && !isid(c))
4313 goto error_pasting;
4316 ts = tok_alloc(cstr.data, strlen(cstr.data));
4317 tok = ts->tok; /* modify current token */
4319 } else {
4320 const char *str = cstr.data;
4321 const unsigned char *q;
4323 /* we look for a valid token */
4324 /* XXX: do more extensive checks */
4325 if (!strcmp(str, ">>=")) {
4326 tok = TOK_A_SAR;
4327 } else if (!strcmp(str, "<<=")) {
4328 tok = TOK_A_SHL;
4329 } else if (strlen(str) == 2) {
4330 /* search in two bytes table */
4331 q = tok_two_chars;
4332 for(;;) {
4333 if (!*q)
4334 goto error_pasting;
4335 if (q[0] == str[0] && q[1] == str[1])
4336 break;
4337 q += 3;
4339 tok = q[2];
4340 } else {
4341 error_pasting:
4342 /* NOTE: because get_tok_str use a static buffer,
4343 we must save it */
4344 cstr_reset(&cstr);
4345 p1 = get_tok_str(tok, &tokc);
4346 cstr_cat(&cstr, p1);
4347 cstr_ccat(&cstr, '\0');
4348 p2 = get_tok_str(t, &cval);
4349 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr.data, p2);
4350 /* cannot merge tokens: just add them separately */
4351 tok_str_add2(&macro_str1, tok, &tokc);
4352 /* XXX: free associated memory ? */
4353 tok = t;
4354 tokc = cval;
4359 tok_str_add2(&macro_str1, tok, &tokc);
4360 next_nomacro();
4361 if (tok == 0)
4362 break;
4364 macro_ptr = (int *)saved_macro_ptr;
4365 cstr_free(&cstr);
4366 tok_str_add(&macro_str1, 0);
4367 return macro_str1.str;
4371 /* do macro substitution of macro_str and add result to
4372 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4373 inside to avoid recursing. */
4374 static void macro_subst(TokenString *tok_str, Sym **nested_list,
4375 const int *macro_str, struct macro_level ** can_read_stream)
4377 Sym *s;
4378 int *macro_str1;
4379 const int *ptr;
4380 int t, ret;
4381 CValue cval;
4382 struct macro_level ml;
4384 /* first scan for '##' operator handling */
4385 ptr = macro_str;
4386 macro_str1 = macro_twosharps(ptr);
4387 if (macro_str1)
4388 ptr = macro_str1;
4389 while (1) {
4390 /* NOTE: ptr == NULL can only happen if tokens are read from
4391 file stream due to a macro function call */
4392 if (ptr == NULL)
4393 break;
4394 TOK_GET(t, ptr, cval);
4395 if (t == 0)
4396 break;
4397 s = define_find(t);
4398 if (s != NULL) {
4399 /* if nested substitution, do nothing */
4400 if (sym_find2(*nested_list, t))
4401 goto no_subst;
4402 ml.p = macro_ptr;
4403 if (can_read_stream)
4404 ml.prev = *can_read_stream, *can_read_stream = &ml;
4405 macro_ptr = (int *)ptr;
4406 tok = t;
4407 ret = macro_subst_tok(tok_str, nested_list, s, can_read_stream);
4408 ptr = (int *)macro_ptr;
4409 macro_ptr = ml.p;
4410 if (can_read_stream && *can_read_stream == &ml)
4411 *can_read_stream = ml.prev;
4412 if (ret != 0)
4413 goto no_subst;
4414 } else {
4415 no_subst:
4416 tok_str_add2(tok_str, t, &cval);
4419 if (macro_str1)
4420 tok_str_free(macro_str1);
4423 /* return next token with macro substitution */
4424 static void next(void)
4426 Sym *nested_list, *s;
4427 TokenString str;
4428 struct macro_level *ml;
4430 redo:
4431 next_nomacro();
4432 if (!macro_ptr) {
4433 /* if not reading from macro substituted string, then try
4434 to substitute macros */
4435 if (tok >= TOK_IDENT &&
4436 (parse_flags & PARSE_FLAG_PREPROCESS)) {
4437 s = define_find(tok);
4438 if (s) {
4439 /* we have a macro: we try to substitute */
4440 tok_str_new(&str);
4441 nested_list = NULL;
4442 ml = NULL;
4443 if (macro_subst_tok(&str, &nested_list, s, &ml) == 0) {
4444 /* substitution done, NOTE: maybe empty */
4445 tok_str_add(&str, 0);
4446 macro_ptr = str.str;
4447 macro_ptr_allocated = str.str;
4448 goto redo;
4452 } else {
4453 if (tok == 0) {
4454 /* end of macro or end of unget buffer */
4455 if (unget_buffer_enabled) {
4456 macro_ptr = unget_saved_macro_ptr;
4457 unget_buffer_enabled = 0;
4458 } else {
4459 /* end of macro string: free it */
4460 tok_str_free(macro_ptr_allocated);
4461 macro_ptr = NULL;
4463 goto redo;
4467 /* convert preprocessor tokens into C tokens */
4468 if (tok == TOK_PPNUM &&
4469 (parse_flags & PARSE_FLAG_TOK_NUM)) {
4470 parse_number((char *)tokc.cstr->data);
4474 /* push back current token and set current token to 'last_tok'. Only
4475 identifier case handled for labels. */
4476 static inline void unget_tok(int last_tok)
4478 int i, n;
4479 int *q;
4480 unget_saved_macro_ptr = macro_ptr;
4481 unget_buffer_enabled = 1;
4482 q = unget_saved_buffer;
4483 macro_ptr = q;
4484 *q++ = tok;
4485 n = tok_ext_size(tok) - 1;
4486 for(i=0;i<n;i++)
4487 *q++ = tokc.tab[i];
4488 *q = 0; /* end of token string */
4489 tok = last_tok;
4493 void swap(int *p, int *q)
4495 int t;
4496 t = *p;
4497 *p = *q;
4498 *q = t;
4501 void vsetc(CType *type, int r, CValue *vc)
4503 int v;
4505 if (vtop >= vstack + (VSTACK_SIZE - 1))
4506 error("memory full");
4507 /* cannot let cpu flags if other instruction are generated. Also
4508 avoid leaving VT_JMP anywhere except on the top of the stack
4509 because it would complicate the code generator. */
4510 if (vtop >= vstack) {
4511 v = vtop->r & VT_VALMASK;
4512 if (v == VT_CMP || (v & ~1) == VT_JMP)
4513 gv(RC_INT);
4515 vtop++;
4516 vtop->type = *type;
4517 vtop->r = r;
4518 vtop->r2 = VT_CONST;
4519 vtop->c = *vc;
4522 /* push integer constant */
4523 void vpushi(int v)
4525 CValue cval;
4526 cval.i = v;
4527 vsetc(&int_type, VT_CONST, &cval);
4530 /* Return a static symbol pointing to a section */
4531 static Sym *get_sym_ref(CType *type, Section *sec,
4532 unsigned long offset, unsigned long size)
4534 int v;
4535 Sym *sym;
4537 v = anon_sym++;
4538 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
4539 sym->type.ref = type->ref;
4540 sym->r = VT_CONST | VT_SYM;
4541 put_extern_sym(sym, sec, offset, size);
4542 return sym;
4545 /* push a reference to a section offset by adding a dummy symbol */
4546 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
4548 CValue cval;
4550 cval.ul = 0;
4551 vsetc(type, VT_CONST | VT_SYM, &cval);
4552 vtop->sym = get_sym_ref(type, sec, offset, size);
4555 /* define a new external reference to a symbol 'v' of type 'u' */
4556 static Sym *external_global_sym(int v, CType *type, int r)
4558 Sym *s;
4560 s = sym_find(v);
4561 if (!s) {
4562 /* push forward reference */
4563 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
4564 s->type.ref = type->ref;
4565 s->r = r | VT_CONST | VT_SYM;
4567 return s;
4570 /* define a new external reference to a symbol 'v' of type 'u' */
4571 static Sym *external_sym(int v, CType *type, int r)
4573 Sym *s;
4575 s = sym_find(v);
4576 if (!s) {
4577 /* push forward reference */
4578 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
4579 s->type.t |= VT_EXTERN;
4580 } else {
4581 if (!is_compatible_types(&s->type, type))
4582 error("incompatible types for redefinition of '%s'",
4583 get_tok_str(v, NULL));
4585 return s;
4588 /* push a reference to global symbol v */
4589 static void vpush_global_sym(CType *type, int v)
4591 Sym *sym;
4592 CValue cval;
4594 sym = external_global_sym(v, type, 0);
4595 cval.ul = 0;
4596 vsetc(type, VT_CONST | VT_SYM, &cval);
4597 vtop->sym = sym;
4600 void vset(CType *type, int r, int v)
4602 CValue cval;
4604 cval.i = v;
4605 vsetc(type, r, &cval);
4608 void vseti(int r, int v)
4610 CType type;
4611 type.t = VT_INT;
4612 vset(&type, r, v);
4615 void vswap(void)
4617 SValue tmp;
4619 tmp = vtop[0];
4620 vtop[0] = vtop[-1];
4621 vtop[-1] = tmp;
4624 void vpushv(SValue *v)
4626 if (vtop >= vstack + (VSTACK_SIZE - 1))
4627 error("memory full");
4628 vtop++;
4629 *vtop = *v;
4632 void vdup(void)
4634 vpushv(vtop);
4637 /* save r to the memory stack, and mark it as being free */
4638 void save_reg(int r)
4640 int l, saved, size, align;
4641 SValue *p, sv;
4642 CType *type;
4644 /* modify all stack values */
4645 saved = 0;
4646 l = 0;
4647 for(p=vstack;p<=vtop;p++) {
4648 if ((p->r & VT_VALMASK) == r ||
4649 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
4650 /* must save value on stack if not already done */
4651 if (!saved) {
4652 /* NOTE: must reload 'r' because r might be equal to r2 */
4653 r = p->r & VT_VALMASK;
4654 /* store register in the stack */
4655 type = &p->type;
4656 if ((p->r & VT_LVAL) ||
4657 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
4658 type = &int_type;
4659 size = type_size(type, &align);
4660 loc = (loc - size) & -align;
4661 sv.type.t = type->t;
4662 sv.r = VT_LOCAL | VT_LVAL;
4663 sv.c.ul = loc;
4664 store(r, &sv);
4665 #ifdef TCC_TARGET_I386
4666 /* x86 specific: need to pop fp register ST0 if saved */
4667 if (r == TREG_ST0) {
4668 o(0xd9dd); /* fstp %st(1) */
4670 #endif
4671 /* special long long case */
4672 if ((type->t & VT_BTYPE) == VT_LLONG) {
4673 sv.c.ul += 4;
4674 store(p->r2, &sv);
4676 l = loc;
4677 saved = 1;
4679 /* mark that stack entry as being saved on the stack */
4680 if (p->r & VT_LVAL) {
4681 /* also clear the bounded flag because the
4682 relocation address of the function was stored in
4683 p->c.ul */
4684 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
4685 } else {
4686 p->r = lvalue_type(p->type.t) | VT_LOCAL;
4688 p->r2 = VT_CONST;
4689 p->c.ul = l;
4694 /* find a register of class 'rc2' with at most one reference on stack.
4695 * If none, call get_reg(rc) */
4696 int get_reg_ex(int rc, int rc2)
4698 int r;
4699 SValue *p;
4701 for(r=0;r<NB_REGS;r++) {
4702 if (reg_classes[r] & rc2) {
4703 int n;
4704 n=0;
4705 for(p = vstack; p <= vtop; p++) {
4706 if ((p->r & VT_VALMASK) == r ||
4707 (p->r2 & VT_VALMASK) == r)
4708 n++;
4710 if (n <= 1)
4711 return r;
4714 return get_reg(rc);
4717 /* find a free register of class 'rc'. If none, save one register */
4718 int get_reg(int rc)
4720 int r;
4721 SValue *p;
4723 /* find a free register */
4724 for(r=0;r<NB_REGS;r++) {
4725 if (reg_classes[r] & rc) {
4726 for(p=vstack;p<=vtop;p++) {
4727 if ((p->r & VT_VALMASK) == r ||
4728 (p->r2 & VT_VALMASK) == r)
4729 goto notfound;
4731 return r;
4733 notfound: ;
4736 /* no register left : free the first one on the stack (VERY
4737 IMPORTANT to start from the bottom to ensure that we don't
4738 spill registers used in gen_opi()) */
4739 for(p=vstack;p<=vtop;p++) {
4740 r = p->r & VT_VALMASK;
4741 if (r < VT_CONST && (reg_classes[r] & rc))
4742 goto save_found;
4743 /* also look at second register (if long long) */
4744 r = p->r2 & VT_VALMASK;
4745 if (r < VT_CONST && (reg_classes[r] & rc)) {
4746 save_found:
4747 save_reg(r);
4748 return r;
4751 /* Should never comes here */
4752 return -1;
4755 /* save registers up to (vtop - n) stack entry */
4756 void save_regs(int n)
4758 int r;
4759 SValue *p, *p1;
4760 p1 = vtop - n;
4761 for(p = vstack;p <= p1; p++) {
4762 r = p->r & VT_VALMASK;
4763 if (r < VT_CONST) {
4764 save_reg(r);
4769 /* move register 's' to 'r', and flush previous value of r to memory
4770 if needed */
4771 void move_reg(int r, int s)
4773 SValue sv;
4775 if (r != s) {
4776 save_reg(r);
4777 sv.type.t = VT_INT;
4778 sv.r = s;
4779 sv.c.ul = 0;
4780 load(r, &sv);
4784 /* get address of vtop (vtop MUST BE an lvalue) */
4785 void gaddrof(void)
4787 vtop->r &= ~VT_LVAL;
4788 /* tricky: if saved lvalue, then we can go back to lvalue */
4789 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
4790 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
4793 #ifdef CONFIG_TCC_BCHECK
4794 /* generate lvalue bound code */
4795 void gbound(void)
4797 int lval_type;
4798 CType type1;
4800 vtop->r &= ~VT_MUSTBOUND;
4801 /* if lvalue, then use checking code before dereferencing */
4802 if (vtop->r & VT_LVAL) {
4803 /* if not VT_BOUNDED value, then make one */
4804 if (!(vtop->r & VT_BOUNDED)) {
4805 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
4806 /* must save type because we must set it to int to get pointer */
4807 type1 = vtop->type;
4808 vtop->type.t = VT_INT;
4809 gaddrof();
4810 vpushi(0);
4811 gen_bounded_ptr_add();
4812 vtop->r |= lval_type;
4813 vtop->type = type1;
4815 /* then check for dereferencing */
4816 gen_bounded_ptr_deref();
4819 #endif
4821 /* store vtop a register belonging to class 'rc'. lvalues are
4822 converted to values. Cannot be used if cannot be converted to
4823 register value (such as structures). */
4824 int gv(int rc)
4826 int r, r2, rc2, bit_pos, bit_size, size, align, i;
4827 unsigned long long ll;
4829 /* NOTE: get_reg can modify vstack[] */
4830 if (vtop->type.t & VT_BITFIELD) {
4831 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
4832 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
4833 /* remove bit field info to avoid loops */
4834 vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
4835 /* generate shifts */
4836 vpushi(32 - (bit_pos + bit_size));
4837 gen_op(TOK_SHL);
4838 vpushi(32 - bit_size);
4839 /* NOTE: transformed to SHR if unsigned */
4840 gen_op(TOK_SAR);
4841 r = gv(rc);
4842 } else {
4843 if (is_float(vtop->type.t) &&
4844 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
4845 Sym *sym;
4846 int *ptr;
4847 unsigned long offset;
4848 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
4849 CValue check;
4850 #endif
4852 /* XXX: unify with initializers handling ? */
4853 /* CPUs usually cannot use float constants, so we store them
4854 generically in data segment */
4855 size = type_size(&vtop->type, &align);
4856 offset = (data_section->data_offset + align - 1) & -align;
4857 data_section->data_offset = offset;
4858 /* XXX: not portable yet */
4859 #ifdef __i386__
4860 /* Zero pad x87 tenbyte long doubles */
4861 if (size == 12)
4862 vtop->c.tab[2] &= 0xffff;
4863 #endif
4864 ptr = section_ptr_add(data_section, size);
4865 size = size >> 2;
4866 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
4867 check.d = 1;
4868 if(check.tab[0])
4869 for(i=0;i<size;i++)
4870 ptr[i] = vtop->c.tab[size-1-i];
4871 else
4872 #endif
4873 for(i=0;i<size;i++)
4874 ptr[i] = vtop->c.tab[i];
4875 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
4876 vtop->r |= VT_LVAL | VT_SYM;
4877 vtop->sym = sym;
4878 vtop->c.ul = 0;
4880 #ifdef CONFIG_TCC_BCHECK
4881 if (vtop->r & VT_MUSTBOUND)
4882 gbound();
4883 #endif
4885 r = vtop->r & VT_VALMASK;
4886 /* need to reload if:
4887 - constant
4888 - lvalue (need to dereference pointer)
4889 - already a register, but not in the right class */
4890 if (r >= VT_CONST ||
4891 (vtop->r & VT_LVAL) ||
4892 !(reg_classes[r] & rc) ||
4893 ((vtop->type.t & VT_BTYPE) == VT_LLONG &&
4894 !(reg_classes[vtop->r2] & rc))) {
4895 r = get_reg(rc);
4896 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
4897 /* two register type load : expand to two words
4898 temporarily */
4899 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
4900 /* load constant */
4901 ll = vtop->c.ull;
4902 vtop->c.ui = ll; /* first word */
4903 load(r, vtop);
4904 vtop->r = r; /* save register value */
4905 vpushi(ll >> 32); /* second word */
4906 } else if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
4907 (vtop->r & VT_LVAL)) {
4908 /* We do not want to modifier the long long
4909 pointer here, so the safest (and less
4910 efficient) is to save all the other registers
4911 in the stack. XXX: totally inefficient. */
4912 save_regs(1);
4913 /* load from memory */
4914 load(r, vtop);
4915 vdup();
4916 vtop[-1].r = r; /* save register value */
4917 /* increment pointer to get second word */
4918 vtop->type.t = VT_INT;
4919 gaddrof();
4920 vpushi(4);
4921 gen_op('+');
4922 vtop->r |= VT_LVAL;
4923 } else {
4924 /* move registers */
4925 load(r, vtop);
4926 vdup();
4927 vtop[-1].r = r; /* save register value */
4928 vtop->r = vtop[-1].r2;
4930 /* allocate second register */
4931 rc2 = RC_INT;
4932 if (rc == RC_IRET)
4933 rc2 = RC_LRET;
4934 r2 = get_reg(rc2);
4935 load(r2, vtop);
4936 vpop();
4937 /* write second register */
4938 vtop->r2 = r2;
4939 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
4940 int t1, t;
4941 /* lvalue of scalar type : need to use lvalue type
4942 because of possible cast */
4943 t = vtop->type.t;
4944 t1 = t;
4945 /* compute memory access type */
4946 if (vtop->r & VT_LVAL_BYTE)
4947 t = VT_BYTE;
4948 else if (vtop->r & VT_LVAL_SHORT)
4949 t = VT_SHORT;
4950 if (vtop->r & VT_LVAL_UNSIGNED)
4951 t |= VT_UNSIGNED;
4952 vtop->type.t = t;
4953 load(r, vtop);
4954 /* restore wanted type */
4955 vtop->type.t = t1;
4956 } else {
4957 /* one register type load */
4958 load(r, vtop);
4961 vtop->r = r;
4962 #ifdef TCC_TARGET_C67
4963 /* uses register pairs for doubles */
4964 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
4965 vtop->r2 = r+1;
4966 #endif
4968 return r;
4971 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
4972 void gv2(int rc1, int rc2)
4974 int v;
4976 /* generate more generic register first. But VT_JMP or VT_CMP
4977 values must be generated first in all cases to avoid possible
4978 reload errors */
4979 v = vtop[0].r & VT_VALMASK;
4980 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
4981 vswap();
4982 gv(rc1);
4983 vswap();
4984 gv(rc2);
4985 /* test if reload is needed for first register */
4986 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
4987 vswap();
4988 gv(rc1);
4989 vswap();
4991 } else {
4992 gv(rc2);
4993 vswap();
4994 gv(rc1);
4995 vswap();
4996 /* test if reload is needed for first register */
4997 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
4998 gv(rc2);
5003 /* expand long long on stack in two int registers */
5004 void lexpand(void)
5006 int u;
5008 u = vtop->type.t & VT_UNSIGNED;
5009 gv(RC_INT);
5010 vdup();
5011 vtop[0].r = vtop[-1].r2;
5012 vtop[0].r2 = VT_CONST;
5013 vtop[-1].r2 = VT_CONST;
5014 vtop[0].type.t = VT_INT | u;
5015 vtop[-1].type.t = VT_INT | u;
5018 #ifdef TCC_TARGET_ARM
5019 /* expand long long on stack */
5020 void lexpand_nr(void)
5022 int u,v;
5024 u = vtop->type.t & VT_UNSIGNED;
5025 vdup();
5026 vtop->r2 = VT_CONST;
5027 vtop->type.t = VT_INT | u;
5028 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
5029 if (v == VT_CONST) {
5030 vtop[-1].c.ui = vtop->c.ull;
5031 vtop->c.ui = vtop->c.ull >> 32;
5032 vtop->r = VT_CONST;
5033 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
5034 vtop->c.ui += 4;
5035 vtop->r = vtop[-1].r;
5036 } else if (v > VT_CONST) {
5037 vtop--;
5038 lexpand();
5039 } else
5040 vtop->r = vtop[-1].r2;
5041 vtop[-1].r2 = VT_CONST;
5042 vtop[-1].type.t = VT_INT | u;
5044 #endif
5046 /* build a long long from two ints */
5047 void lbuild(int t)
5049 gv2(RC_INT, RC_INT);
5050 vtop[-1].r2 = vtop[0].r;
5051 vtop[-1].type.t = t;
5052 vpop();
5055 /* rotate n first stack elements to the bottom
5056 I1 ... In -> I2 ... In I1 [top is right]
5058 void vrotb(int n)
5060 int i;
5061 SValue tmp;
5063 tmp = vtop[-n + 1];
5064 for(i=-n+1;i!=0;i++)
5065 vtop[i] = vtop[i+1];
5066 vtop[0] = tmp;
5069 /* rotate n first stack elements to the top
5070 I1 ... In -> In I1 ... I(n-1) [top is right]
5072 void vrott(int n)
5074 int i;
5075 SValue tmp;
5077 tmp = vtop[0];
5078 for(i = 0;i < n - 1; i++)
5079 vtop[-i] = vtop[-i - 1];
5080 vtop[-n + 1] = tmp;
5083 #ifdef TCC_TARGET_ARM
5084 /* like vrott but in other direction
5085 In ... I1 -> I(n-1) ... I1 In [top is right]
5087 void vnrott(int n)
5089 int i;
5090 SValue tmp;
5092 tmp = vtop[-n + 1];
5093 for(i = n - 1; i > 0; i--)
5094 vtop[-i] = vtop[-i + 1];
5095 vtop[0] = tmp;
5097 #endif
5099 /* pop stack value */
5100 void vpop(void)
5102 int v;
5103 v = vtop->r & VT_VALMASK;
5104 #ifdef TCC_TARGET_I386
5105 /* for x86, we need to pop the FP stack */
5106 if (v == TREG_ST0 && !nocode_wanted) {
5107 o(0xd9dd); /* fstp %st(1) */
5108 } else
5109 #endif
5110 if (v == VT_JMP || v == VT_JMPI) {
5111 /* need to put correct jump if && or || without test */
5112 gsym(vtop->c.ul);
5114 vtop--;
5117 /* convert stack entry to register and duplicate its value in another
5118 register */
5119 void gv_dup(void)
5121 int rc, t, r, r1;
5122 SValue sv;
5124 t = vtop->type.t;
5125 if ((t & VT_BTYPE) == VT_LLONG) {
5126 lexpand();
5127 gv_dup();
5128 vswap();
5129 vrotb(3);
5130 gv_dup();
5131 vrotb(4);
5132 /* stack: H L L1 H1 */
5133 lbuild(t);
5134 vrotb(3);
5135 vrotb(3);
5136 vswap();
5137 lbuild(t);
5138 vswap();
5139 } else {
5140 /* duplicate value */
5141 rc = RC_INT;
5142 sv.type.t = VT_INT;
5143 if (is_float(t)) {
5144 rc = RC_FLOAT;
5145 sv.type.t = t;
5147 r = gv(rc);
5148 r1 = get_reg(rc);
5149 sv.r = r;
5150 sv.c.ul = 0;
5151 load(r1, &sv); /* move r to r1 */
5152 vdup();
5153 /* duplicates value */
5154 vtop->r = r1;
5158 /* generate CPU independent (unsigned) long long operations */
5159 void gen_opl(int op)
5161 int t, a, b, op1, c, i;
5162 int func;
5163 SValue tmp;
5165 switch(op) {
5166 case '/':
5167 case TOK_PDIV:
5168 func = TOK___divdi3;
5169 goto gen_func;
5170 case TOK_UDIV:
5171 func = TOK___udivdi3;
5172 goto gen_func;
5173 case '%':
5174 func = TOK___moddi3;
5175 goto gen_func;
5176 case TOK_UMOD:
5177 func = TOK___umoddi3;
5178 gen_func:
5179 /* call generic long long function */
5180 vpush_global_sym(&func_old_type, func);
5181 vrott(3);
5182 gfunc_call(2);
5183 vpushi(0);
5184 vtop->r = REG_IRET;
5185 vtop->r2 = REG_LRET;
5186 break;
5187 case '^':
5188 case '&':
5189 case '|':
5190 case '*':
5191 case '+':
5192 case '-':
5193 t = vtop->type.t;
5194 vswap();
5195 lexpand();
5196 vrotb(3);
5197 lexpand();
5198 /* stack: L1 H1 L2 H2 */
5199 tmp = vtop[0];
5200 vtop[0] = vtop[-3];
5201 vtop[-3] = tmp;
5202 tmp = vtop[-2];
5203 vtop[-2] = vtop[-3];
5204 vtop[-3] = tmp;
5205 vswap();
5206 /* stack: H1 H2 L1 L2 */
5207 if (op == '*') {
5208 vpushv(vtop - 1);
5209 vpushv(vtop - 1);
5210 gen_op(TOK_UMULL);
5211 lexpand();
5212 /* stack: H1 H2 L1 L2 ML MH */
5213 for(i=0;i<4;i++)
5214 vrotb(6);
5215 /* stack: ML MH H1 H2 L1 L2 */
5216 tmp = vtop[0];
5217 vtop[0] = vtop[-2];
5218 vtop[-2] = tmp;
5219 /* stack: ML MH H1 L2 H2 L1 */
5220 gen_op('*');
5221 vrotb(3);
5222 vrotb(3);
5223 gen_op('*');
5224 /* stack: ML MH M1 M2 */
5225 gen_op('+');
5226 gen_op('+');
5227 } else if (op == '+' || op == '-') {
5228 /* XXX: add non carry method too (for MIPS or alpha) */
5229 if (op == '+')
5230 op1 = TOK_ADDC1;
5231 else
5232 op1 = TOK_SUBC1;
5233 gen_op(op1);
5234 /* stack: H1 H2 (L1 op L2) */
5235 vrotb(3);
5236 vrotb(3);
5237 gen_op(op1 + 1); /* TOK_xxxC2 */
5238 } else {
5239 gen_op(op);
5240 /* stack: H1 H2 (L1 op L2) */
5241 vrotb(3);
5242 vrotb(3);
5243 /* stack: (L1 op L2) H1 H2 */
5244 gen_op(op);
5245 /* stack: (L1 op L2) (H1 op H2) */
5247 /* stack: L H */
5248 lbuild(t);
5249 break;
5250 case TOK_SAR:
5251 case TOK_SHR:
5252 case TOK_SHL:
5253 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5254 t = vtop[-1].type.t;
5255 vswap();
5256 lexpand();
5257 vrotb(3);
5258 /* stack: L H shift */
5259 c = (int)vtop->c.i;
5260 /* constant: simpler */
5261 /* NOTE: all comments are for SHL. the other cases are
5262 done by swaping words */
5263 vpop();
5264 if (op != TOK_SHL)
5265 vswap();
5266 if (c >= 32) {
5267 /* stack: L H */
5268 vpop();
5269 if (c > 32) {
5270 vpushi(c - 32);
5271 gen_op(op);
5273 if (op != TOK_SAR) {
5274 vpushi(0);
5275 } else {
5276 gv_dup();
5277 vpushi(31);
5278 gen_op(TOK_SAR);
5280 vswap();
5281 } else {
5282 vswap();
5283 gv_dup();
5284 /* stack: H L L */
5285 vpushi(c);
5286 gen_op(op);
5287 vswap();
5288 vpushi(32 - c);
5289 if (op == TOK_SHL)
5290 gen_op(TOK_SHR);
5291 else
5292 gen_op(TOK_SHL);
5293 vrotb(3);
5294 /* stack: L L H */
5295 vpushi(c);
5296 if (op == TOK_SHL)
5297 gen_op(TOK_SHL);
5298 else
5299 gen_op(TOK_SHR);
5300 gen_op('|');
5302 if (op != TOK_SHL)
5303 vswap();
5304 lbuild(t);
5305 } else {
5306 /* XXX: should provide a faster fallback on x86 ? */
5307 switch(op) {
5308 case TOK_SAR:
5309 func = TOK___sardi3;
5310 goto gen_func;
5311 case TOK_SHR:
5312 func = TOK___shrdi3;
5313 goto gen_func;
5314 case TOK_SHL:
5315 func = TOK___shldi3;
5316 goto gen_func;
5319 break;
5320 default:
5321 /* compare operations */
5322 t = vtop->type.t;
5323 vswap();
5324 lexpand();
5325 vrotb(3);
5326 lexpand();
5327 /* stack: L1 H1 L2 H2 */
5328 tmp = vtop[-1];
5329 vtop[-1] = vtop[-2];
5330 vtop[-2] = tmp;
5331 /* stack: L1 L2 H1 H2 */
5332 /* compare high */
5333 op1 = op;
5334 /* when values are equal, we need to compare low words. since
5335 the jump is inverted, we invert the test too. */
5336 if (op1 == TOK_LT)
5337 op1 = TOK_LE;
5338 else if (op1 == TOK_GT)
5339 op1 = TOK_GE;
5340 else if (op1 == TOK_ULT)
5341 op1 = TOK_ULE;
5342 else if (op1 == TOK_UGT)
5343 op1 = TOK_UGE;
5344 a = 0;
5345 b = 0;
5346 gen_op(op1);
5347 if (op1 != TOK_NE) {
5348 a = gtst(1, 0);
5350 if (op != TOK_EQ) {
5351 /* generate non equal test */
5352 /* XXX: NOT PORTABLE yet */
5353 if (a == 0) {
5354 b = gtst(0, 0);
5355 } else {
5356 #if defined(TCC_TARGET_I386)
5357 b = psym(0x850f, 0);
5358 #elif defined(TCC_TARGET_ARM)
5359 b = ind;
5360 o(0x1A000000 | encbranch(ind, 0, 1));
5361 #elif defined(TCC_TARGET_C67)
5362 error("not implemented");
5363 #else
5364 #error not supported
5365 #endif
5368 /* compare low. Always unsigned */
5369 op1 = op;
5370 if (op1 == TOK_LT)
5371 op1 = TOK_ULT;
5372 else if (op1 == TOK_LE)
5373 op1 = TOK_ULE;
5374 else if (op1 == TOK_GT)
5375 op1 = TOK_UGT;
5376 else if (op1 == TOK_GE)
5377 op1 = TOK_UGE;
5378 gen_op(op1);
5379 a = gtst(1, a);
5380 gsym(b);
5381 vseti(VT_JMPI, a);
5382 break;
5386 /* handle integer constant optimizations and various machine
5387 independent opt */
5388 void gen_opic(int op)
5390 int c1, c2, t1, t2, n, c;
5391 SValue *v1, *v2;
5392 long long l1, l2, l;
5393 typedef unsigned long long U;
5395 v1 = vtop - 1;
5396 v2 = vtop;
5397 t1 = v1->type.t & VT_BTYPE;
5398 t2 = v2->type.t & VT_BTYPE;
5399 l1 = (t1 == VT_LLONG) ? v1->c.ll : v1->c.i;
5400 l2 = (t2 == VT_LLONG) ? v2->c.ll : v2->c.i;
5402 /* currently, we cannot do computations with forward symbols */
5403 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5404 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5405 if (c1 && c2) {
5406 switch(op) {
5407 case '+': l1 += l2; break;
5408 case '-': l1 -= l2; break;
5409 case '&': l1 &= l2; break;
5410 case '^': l1 ^= l2; break;
5411 case '|': l1 |= l2; break;
5412 case '*': l1 *= l2; break;
5414 case TOK_PDIV:
5415 case '/':
5416 case '%':
5417 case TOK_UDIV:
5418 case TOK_UMOD:
5419 /* if division by zero, generate explicit division */
5420 if (l2 == 0) {
5421 if (const_wanted)
5422 error("division by zero in constant");
5423 goto general_case;
5425 switch(op) {
5426 default: l1 /= l2; break;
5427 case '%': l1 %= l2; break;
5428 case TOK_UDIV: l1 = (U)l1 / l2; break;
5429 case TOK_UMOD: l1 = (U)l1 % l2; break;
5431 break;
5432 case TOK_SHL: l1 <<= l2; break;
5433 case TOK_SHR: l1 = (U)l1 >> l2; break;
5434 case TOK_SAR: l1 >>= l2; break;
5435 /* tests */
5436 case TOK_ULT: l1 = (U)l1 < (U)l2; break;
5437 case TOK_UGE: l1 = (U)l1 >= (U)l2; break;
5438 case TOK_EQ: l1 = l1 == l2; break;
5439 case TOK_NE: l1 = l1 != l2; break;
5440 case TOK_ULE: l1 = (U)l1 <= (U)l2; break;
5441 case TOK_UGT: l1 = (U)l1 > (U)l2; break;
5442 case TOK_LT: l1 = l1 < l2; break;
5443 case TOK_GE: l1 = l1 >= l2; break;
5444 case TOK_LE: l1 = l1 <= l2; break;
5445 case TOK_GT: l1 = l1 > l2; break;
5446 /* logical */
5447 case TOK_LAND: l1 = l1 && l2; break;
5448 case TOK_LOR: l1 = l1 || l2; break;
5449 default:
5450 goto general_case;
5452 v1->c.ll = l1;
5453 vtop--;
5454 } else {
5455 /* if commutative ops, put c2 as constant */
5456 if (c1 && (op == '+' || op == '&' || op == '^' ||
5457 op == '|' || op == '*')) {
5458 vswap();
5459 c = c1, c1 = c2, c2 = c;
5460 l = l1, l1 = l2, l2 = l;
5462 /* Filter out NOP operations like x*1, x-0, x&-1... */
5463 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
5464 op == TOK_PDIV) &&
5465 l2 == 1) ||
5466 ((op == '+' || op == '-' || op == '|' || op == '^' ||
5467 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
5468 l2 == 0) ||
5469 (op == '&' &&
5470 l2 == -1))) {
5471 /* nothing to do */
5472 vtop--;
5473 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
5474 /* try to use shifts instead of muls or divs */
5475 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
5476 n = -1;
5477 while (l2) {
5478 l2 >>= 1;
5479 n++;
5481 vtop->c.ll = n;
5482 if (op == '*')
5483 op = TOK_SHL;
5484 else if (op == TOK_PDIV)
5485 op = TOK_SAR;
5486 else
5487 op = TOK_SHR;
5489 goto general_case;
5490 } else if (c2 && (op == '+' || op == '-') &&
5491 (vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) ==
5492 (VT_CONST | VT_SYM)) {
5493 /* symbol + constant case */
5494 if (op == '-')
5495 l2 = -l2;
5496 vtop--;
5497 vtop->c.ll += l2;
5498 } else {
5499 general_case:
5500 if (!nocode_wanted) {
5501 /* call low level op generator */
5502 if (t1 == VT_LLONG || t2 == VT_LLONG)
5503 gen_opl(op);
5504 else
5505 gen_opi(op);
5506 } else {
5507 vtop--;
5513 /* generate a floating point operation with constant propagation */
5514 void gen_opif(int op)
5516 int c1, c2;
5517 SValue *v1, *v2;
5518 long double f1, f2;
5520 v1 = vtop - 1;
5521 v2 = vtop;
5522 /* currently, we cannot do computations with forward symbols */
5523 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5524 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5525 if (c1 && c2) {
5526 if (v1->type.t == VT_FLOAT) {
5527 f1 = v1->c.f;
5528 f2 = v2->c.f;
5529 } else if (v1->type.t == VT_DOUBLE) {
5530 f1 = v1->c.d;
5531 f2 = v2->c.d;
5532 } else {
5533 f1 = v1->c.ld;
5534 f2 = v2->c.ld;
5537 /* NOTE: we only do constant propagation if finite number (not
5538 NaN or infinity) (ANSI spec) */
5539 if (!ieee_finite(f1) || !ieee_finite(f2))
5540 goto general_case;
5542 switch(op) {
5543 case '+': f1 += f2; break;
5544 case '-': f1 -= f2; break;
5545 case '*': f1 *= f2; break;
5546 case '/':
5547 if (f2 == 0.0) {
5548 if (const_wanted)
5549 error("division by zero in constant");
5550 goto general_case;
5552 f1 /= f2;
5553 break;
5554 /* XXX: also handles tests ? */
5555 default:
5556 goto general_case;
5558 /* XXX: overflow test ? */
5559 if (v1->type.t == VT_FLOAT) {
5560 v1->c.f = f1;
5561 } else if (v1->type.t == VT_DOUBLE) {
5562 v1->c.d = f1;
5563 } else {
5564 v1->c.ld = f1;
5566 vtop--;
5567 } else {
5568 general_case:
5569 if (!nocode_wanted) {
5570 gen_opf(op);
5571 } else {
5572 vtop--;
5577 static int pointed_size(CType *type)
5579 int align;
5580 return type_size(pointed_type(type), &align);
5583 static inline int is_null_pointer(SValue *p)
5585 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
5586 return 0;
5587 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
5588 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0);
5591 static inline int is_integer_btype(int bt)
5593 return (bt == VT_BYTE || bt == VT_SHORT ||
5594 bt == VT_INT || bt == VT_LLONG);
5597 /* check types for comparison or substraction of pointers */
5598 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
5600 CType *type1, *type2, tmp_type1, tmp_type2;
5601 int bt1, bt2;
5603 /* null pointers are accepted for all comparisons as gcc */
5604 if (is_null_pointer(p1) || is_null_pointer(p2))
5605 return;
5606 type1 = &p1->type;
5607 type2 = &p2->type;
5608 bt1 = type1->t & VT_BTYPE;
5609 bt2 = type2->t & VT_BTYPE;
5610 /* accept comparison between pointer and integer with a warning */
5611 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
5612 if (op != TOK_LOR && op != TOK_LAND )
5613 warning("comparison between pointer and integer");
5614 return;
5617 /* both must be pointers or implicit function pointers */
5618 if (bt1 == VT_PTR) {
5619 type1 = pointed_type(type1);
5620 } else if (bt1 != VT_FUNC)
5621 goto invalid_operands;
5623 if (bt2 == VT_PTR) {
5624 type2 = pointed_type(type2);
5625 } else if (bt2 != VT_FUNC) {
5626 invalid_operands:
5627 error("invalid operands to binary %s", get_tok_str(op, NULL));
5629 if ((type1->t & VT_BTYPE) == VT_VOID ||
5630 (type2->t & VT_BTYPE) == VT_VOID)
5631 return;
5632 tmp_type1 = *type1;
5633 tmp_type2 = *type2;
5634 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
5635 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
5636 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
5637 /* gcc-like error if '-' is used */
5638 if (op == '-')
5639 goto invalid_operands;
5640 else
5641 warning("comparison of distinct pointer types lacks a cast");
5645 /* generic gen_op: handles types problems */
5646 void gen_op(int op)
5648 int u, t1, t2, bt1, bt2, t;
5649 CType type1;
5651 t1 = vtop[-1].type.t;
5652 t2 = vtop[0].type.t;
5653 bt1 = t1 & VT_BTYPE;
5654 bt2 = t2 & VT_BTYPE;
5656 if (bt1 == VT_PTR || bt2 == VT_PTR) {
5657 /* at least one operand is a pointer */
5658 /* relationnal op: must be both pointers */
5659 if (op >= TOK_ULT && op <= TOK_LOR) {
5660 check_comparison_pointer_types(vtop - 1, vtop, op);
5661 /* pointers are handled are unsigned */
5662 t = VT_INT | VT_UNSIGNED;
5663 goto std_op;
5665 /* if both pointers, then it must be the '-' op */
5666 if (bt1 == VT_PTR && bt2 == VT_PTR) {
5667 if (op != '-')
5668 error("cannot use pointers here");
5669 check_comparison_pointer_types(vtop - 1, vtop, op);
5670 /* XXX: check that types are compatible */
5671 u = pointed_size(&vtop[-1].type);
5672 gen_opic(op);
5673 /* set to integer type */
5674 vtop->type.t = VT_INT;
5675 vpushi(u);
5676 gen_op(TOK_PDIV);
5677 } else {
5678 /* exactly one pointer : must be '+' or '-'. */
5679 if (op != '-' && op != '+')
5680 error("cannot use pointers here");
5681 /* Put pointer as first operand */
5682 if (bt2 == VT_PTR) {
5683 vswap();
5684 swap(&t1, &t2);
5686 type1 = vtop[-1].type;
5687 /* XXX: cast to int ? (long long case) */
5688 vpushi(pointed_size(&vtop[-1].type));
5689 gen_op('*');
5690 #ifdef CONFIG_TCC_BCHECK
5691 /* if evaluating constant expression, no code should be
5692 generated, so no bound check */
5693 if (do_bounds_check && !const_wanted) {
5694 /* if bounded pointers, we generate a special code to
5695 test bounds */
5696 if (op == '-') {
5697 vpushi(0);
5698 vswap();
5699 gen_op('-');
5701 gen_bounded_ptr_add();
5702 } else
5703 #endif
5705 gen_opic(op);
5707 /* put again type if gen_opic() swaped operands */
5708 vtop->type = type1;
5710 } else if (is_float(bt1) || is_float(bt2)) {
5711 /* compute bigger type and do implicit casts */
5712 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
5713 t = VT_LDOUBLE;
5714 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
5715 t = VT_DOUBLE;
5716 } else {
5717 t = VT_FLOAT;
5719 /* floats can only be used for a few operations */
5720 if (op != '+' && op != '-' && op != '*' && op != '/' &&
5721 (op < TOK_ULT || op > TOK_GT))
5722 error("invalid operands for binary operation");
5723 goto std_op;
5724 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
5725 /* cast to biggest op */
5726 t = VT_LLONG;
5727 /* convert to unsigned if it does not fit in a long long */
5728 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
5729 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
5730 t |= VT_UNSIGNED;
5731 goto std_op;
5732 } else {
5733 /* integer operations */
5734 t = VT_INT;
5735 /* convert to unsigned if it does not fit in an integer */
5736 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
5737 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
5738 t |= VT_UNSIGNED;
5739 std_op:
5740 /* XXX: currently, some unsigned operations are explicit, so
5741 we modify them here */
5742 if (t & VT_UNSIGNED) {
5743 if (op == TOK_SAR)
5744 op = TOK_SHR;
5745 else if (op == '/')
5746 op = TOK_UDIV;
5747 else if (op == '%')
5748 op = TOK_UMOD;
5749 else if (op == TOK_LT)
5750 op = TOK_ULT;
5751 else if (op == TOK_GT)
5752 op = TOK_UGT;
5753 else if (op == TOK_LE)
5754 op = TOK_ULE;
5755 else if (op == TOK_GE)
5756 op = TOK_UGE;
5758 vswap();
5759 type1.t = t;
5760 gen_cast(&type1);
5761 vswap();
5762 /* special case for shifts and long long: we keep the shift as
5763 an integer */
5764 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
5765 type1.t = VT_INT;
5766 gen_cast(&type1);
5767 if (is_float(t))
5768 gen_opif(op);
5769 else
5770 gen_opic(op);
5771 if (op >= TOK_ULT && op <= TOK_GT) {
5772 /* relationnal op: the result is an int */
5773 vtop->type.t = VT_INT;
5774 } else {
5775 vtop->type.t = t;
5780 /* generic itof for unsigned long long case */
5781 void gen_cvt_itof1(int t)
5783 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
5784 (VT_LLONG | VT_UNSIGNED)) {
5786 if (t == VT_FLOAT)
5787 vpush_global_sym(&func_old_type, TOK___ulltof);
5788 else if (t == VT_DOUBLE)
5789 vpush_global_sym(&func_old_type, TOK___ulltod);
5790 else
5791 vpush_global_sym(&func_old_type, TOK___ulltold);
5792 vrott(2);
5793 gfunc_call(1);
5794 vpushi(0);
5795 vtop->r = REG_FRET;
5796 } else {
5797 gen_cvt_itof(t);
5801 /* generic ftoi for unsigned long long case */
5802 void gen_cvt_ftoi1(int t)
5804 int st;
5806 if (t == (VT_LLONG | VT_UNSIGNED)) {
5807 /* not handled natively */
5808 st = vtop->type.t & VT_BTYPE;
5809 if (st == VT_FLOAT)
5810 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
5811 else if (st == VT_DOUBLE)
5812 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
5813 else
5814 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
5815 vrott(2);
5816 gfunc_call(1);
5817 vpushi(0);
5818 vtop->r = REG_IRET;
5819 vtop->r2 = REG_LRET;
5820 } else {
5821 gen_cvt_ftoi(t);
5825 /* force char or short cast */
5826 void force_charshort_cast(int t)
5828 int bits, dbt;
5829 dbt = t & VT_BTYPE;
5830 /* XXX: add optimization if lvalue : just change type and offset */
5831 if (dbt == VT_BYTE)
5832 bits = 8;
5833 else
5834 bits = 16;
5835 if (t & VT_UNSIGNED) {
5836 vpushi((1 << bits) - 1);
5837 gen_op('&');
5838 } else {
5839 bits = 32 - bits;
5840 vpushi(bits);
5841 gen_op(TOK_SHL);
5842 /* result must be signed or the SAR is converted to an SHL
5843 This was not the case when "t" was a signed short
5844 and the last value on the stack was an unsigned int */
5845 vtop->type.t &= ~VT_UNSIGNED;
5846 vpushi(bits);
5847 gen_op(TOK_SAR);
5851 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
5852 static void gen_cast(CType *type)
5854 int sbt, dbt, sf, df, c;
5856 /* special delayed cast for char/short */
5857 /* XXX: in some cases (multiple cascaded casts), it may still
5858 be incorrect */
5859 if (vtop->r & VT_MUSTCAST) {
5860 vtop->r &= ~VT_MUSTCAST;
5861 force_charshort_cast(vtop->type.t);
5864 /* bitfields first get cast to ints */
5865 if (vtop->type.t & VT_BITFIELD) {
5866 gv(RC_INT);
5869 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
5870 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
5872 if (sbt != dbt && !nocode_wanted) {
5873 sf = is_float(sbt);
5874 df = is_float(dbt);
5875 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5876 if (sf && df) {
5877 /* convert from fp to fp */
5878 if (c) {
5879 /* constant case: we can do it now */
5880 /* XXX: in ISOC, cannot do it if error in convert */
5881 if (dbt == VT_FLOAT && sbt == VT_DOUBLE)
5882 vtop->c.f = (float)vtop->c.d;
5883 else if (dbt == VT_FLOAT && sbt == VT_LDOUBLE)
5884 vtop->c.f = (float)vtop->c.ld;
5885 else if (dbt == VT_DOUBLE && sbt == VT_FLOAT)
5886 vtop->c.d = (double)vtop->c.f;
5887 else if (dbt == VT_DOUBLE && sbt == VT_LDOUBLE)
5888 vtop->c.d = (double)vtop->c.ld;
5889 else if (dbt == VT_LDOUBLE && sbt == VT_FLOAT)
5890 vtop->c.ld = (long double)vtop->c.f;
5891 else if (dbt == VT_LDOUBLE && sbt == VT_DOUBLE)
5892 vtop->c.ld = (long double)vtop->c.d;
5893 } else {
5894 /* non constant case: generate code */
5895 gen_cvt_ftof(dbt);
5897 } else if (df) {
5898 /* convert int to fp */
5899 if (c) {
5900 switch(sbt) {
5901 case VT_LLONG | VT_UNSIGNED:
5902 case VT_LLONG:
5903 /* XXX: add const cases for long long */
5904 goto do_itof;
5905 case VT_INT | VT_UNSIGNED:
5906 switch(dbt) {
5907 case VT_FLOAT: vtop->c.f = (float)vtop->c.ui; break;
5908 case VT_DOUBLE: vtop->c.d = (double)vtop->c.ui; break;
5909 case VT_LDOUBLE: vtop->c.ld = (long double)vtop->c.ui; break;
5911 break;
5912 default:
5913 switch(dbt) {
5914 case VT_FLOAT: vtop->c.f = (float)vtop->c.i; break;
5915 case VT_DOUBLE: vtop->c.d = (double)vtop->c.i; break;
5916 case VT_LDOUBLE: vtop->c.ld = (long double)vtop->c.i; break;
5918 break;
5920 } else {
5921 do_itof:
5922 #if !defined(TCC_TARGET_ARM)
5923 gen_cvt_itof1(dbt);
5924 #else
5925 gen_cvt_itof(dbt);
5926 #endif
5928 } else if (sf) {
5929 /* convert fp to int */
5930 if (dbt == VT_BOOL) {
5931 vpushi(0);
5932 gen_op(TOK_NE);
5933 } else {
5934 /* we handle char/short/etc... with generic code */
5935 if (dbt != (VT_INT | VT_UNSIGNED) &&
5936 dbt != (VT_LLONG | VT_UNSIGNED) &&
5937 dbt != VT_LLONG)
5938 dbt = VT_INT;
5939 if (c) {
5940 switch(dbt) {
5941 case VT_LLONG | VT_UNSIGNED:
5942 case VT_LLONG:
5943 /* XXX: add const cases for long long */
5944 goto do_ftoi;
5945 case VT_INT | VT_UNSIGNED:
5946 switch(sbt) {
5947 case VT_FLOAT: vtop->c.ui = (unsigned int)vtop->c.d; break;
5948 case VT_DOUBLE: vtop->c.ui = (unsigned int)vtop->c.d; break;
5949 case VT_LDOUBLE: vtop->c.ui = (unsigned int)vtop->c.d; break;
5951 break;
5952 default:
5953 /* int case */
5954 switch(sbt) {
5955 case VT_FLOAT: vtop->c.i = (int)vtop->c.d; break;
5956 case VT_DOUBLE: vtop->c.i = (int)vtop->c.d; break;
5957 case VT_LDOUBLE: vtop->c.i = (int)vtop->c.d; break;
5959 break;
5961 } else {
5962 do_ftoi:
5963 gen_cvt_ftoi1(dbt);
5965 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
5966 /* additional cast for char/short... */
5967 vtop->type.t = dbt;
5968 gen_cast(type);
5971 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
5972 if ((sbt & VT_BTYPE) != VT_LLONG) {
5973 /* scalar to long long */
5974 if (c) {
5975 if (sbt == (VT_INT | VT_UNSIGNED))
5976 vtop->c.ll = vtop->c.ui;
5977 else
5978 vtop->c.ll = vtop->c.i;
5979 } else {
5980 /* machine independent conversion */
5981 gv(RC_INT);
5982 /* generate high word */
5983 if (sbt == (VT_INT | VT_UNSIGNED)) {
5984 vpushi(0);
5985 gv(RC_INT);
5986 } else {
5987 gv_dup();
5988 vpushi(31);
5989 gen_op(TOK_SAR);
5991 /* patch second register */
5992 vtop[-1].r2 = vtop->r;
5993 vpop();
5996 } else if (dbt == VT_BOOL) {
5997 /* scalar to bool */
5998 vpushi(0);
5999 gen_op(TOK_NE);
6000 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
6001 (dbt & VT_BTYPE) == VT_SHORT) {
6002 if (sbt == VT_PTR) {
6003 vtop->type.t = VT_INT;
6004 warning("nonportable conversion from pointer to char/short");
6006 force_charshort_cast(dbt);
6007 } else if ((dbt & VT_BTYPE) == VT_INT) {
6008 /* scalar to int */
6009 if (sbt == VT_LLONG) {
6010 /* from long long: just take low order word */
6011 lexpand();
6012 vpop();
6014 /* if lvalue and single word type, nothing to do because
6015 the lvalue already contains the real type size (see
6016 VT_LVAL_xxx constants) */
6018 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
6019 /* if we are casting between pointer types,
6020 we must update the VT_LVAL_xxx size */
6021 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
6022 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
6024 vtop->type = *type;
6027 /* return type size. Put alignment at 'a' */
6028 static int type_size(CType *type, int *a)
6030 Sym *s;
6031 int bt;
6033 bt = type->t & VT_BTYPE;
6034 if (bt == VT_STRUCT) {
6035 /* struct/union */
6036 s = type->ref;
6037 *a = s->r;
6038 return s->c;
6039 } else if (bt == VT_PTR) {
6040 if (type->t & VT_ARRAY) {
6041 s = type->ref;
6042 return type_size(&s->type, a) * s->c;
6043 } else {
6044 *a = PTR_SIZE;
6045 return PTR_SIZE;
6047 } else if (bt == VT_LDOUBLE) {
6048 *a = LDOUBLE_ALIGN;
6049 return LDOUBLE_SIZE;
6050 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
6051 #ifdef TCC_TARGET_I386
6052 *a = 4;
6053 #elif defined(TCC_TARGET_ARM)
6054 #ifdef TCC_ARM_EABI
6055 *a = 8;
6056 #else
6057 *a = 4;
6058 #endif
6059 #else
6060 *a = 8;
6061 #endif
6062 return 8;
6063 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
6064 *a = 4;
6065 return 4;
6066 } else if (bt == VT_SHORT) {
6067 *a = 2;
6068 return 2;
6069 } else {
6070 /* char, void, function, _Bool */
6071 *a = 1;
6072 return 1;
6076 /* return the pointed type of t */
6077 static inline CType *pointed_type(CType *type)
6079 return &type->ref->type;
6082 /* modify type so that its it is a pointer to type. */
6083 static void mk_pointer(CType *type)
6085 Sym *s;
6086 s = sym_push(SYM_FIELD, type, 0, -1);
6087 type->t = VT_PTR | (type->t & ~VT_TYPE);
6088 type->ref = s;
6091 /* compare function types. OLD functions match any new functions */
6092 static int is_compatible_func(CType *type1, CType *type2)
6094 Sym *s1, *s2;
6096 s1 = type1->ref;
6097 s2 = type2->ref;
6098 if (!is_compatible_types(&s1->type, &s2->type))
6099 return 0;
6100 /* check func_call */
6101 if (s1->r != s2->r)
6102 return 0;
6103 /* XXX: not complete */
6104 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
6105 return 1;
6106 if (s1->c != s2->c)
6107 return 0;
6108 while (s1 != NULL) {
6109 if (s2 == NULL)
6110 return 0;
6111 if (!is_compatible_parameter_types(&s1->type, &s2->type))
6112 return 0;
6113 s1 = s1->next;
6114 s2 = s2->next;
6116 if (s2)
6117 return 0;
6118 return 1;
6121 /* return true if type1 and type2 are the same. If unqualified is
6122 true, qualifiers on the types are ignored.
6124 - enums are not checked as gcc __builtin_types_compatible_p ()
6126 static int compare_types(CType *type1, CType *type2, int unqualified)
6128 int bt1, t1, t2;
6130 t1 = type1->t & VT_TYPE;
6131 t2 = type2->t & VT_TYPE;
6132 if (unqualified) {
6133 /* strip qualifiers before comparing */
6134 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
6135 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
6137 /* XXX: bitfields ? */
6138 if (t1 != t2)
6139 return 0;
6140 /* test more complicated cases */
6141 bt1 = t1 & VT_BTYPE;
6142 if (bt1 == VT_PTR) {
6143 type1 = pointed_type(type1);
6144 type2 = pointed_type(type2);
6145 return is_compatible_types(type1, type2);
6146 } else if (bt1 == VT_STRUCT) {
6147 return (type1->ref == type2->ref);
6148 } else if (bt1 == VT_FUNC) {
6149 return is_compatible_func(type1, type2);
6150 } else {
6151 return 1;
6155 /* return true if type1 and type2 are exactly the same (including
6156 qualifiers).
6158 static int is_compatible_types(CType *type1, CType *type2)
6160 return compare_types(type1,type2,0);
6163 /* return true if type1 and type2 are the same (ignoring qualifiers).
6165 static int is_compatible_parameter_types(CType *type1, CType *type2)
6167 return compare_types(type1,type2,1);
6170 /* print a type. If 'varstr' is not NULL, then the variable is also
6171 printed in the type */
6172 /* XXX: union */
6173 /* XXX: add array and function pointers */
6174 void type_to_str(char *buf, int buf_size,
6175 CType *type, const char *varstr)
6177 int bt, v, t;
6178 Sym *s, *sa;
6179 char buf1[256];
6180 const char *tstr;
6182 t = type->t & VT_TYPE;
6183 bt = t & VT_BTYPE;
6184 buf[0] = '\0';
6185 if (t & VT_CONSTANT)
6186 pstrcat(buf, buf_size, "const ");
6187 if (t & VT_VOLATILE)
6188 pstrcat(buf, buf_size, "volatile ");
6189 if (t & VT_UNSIGNED)
6190 pstrcat(buf, buf_size, "unsigned ");
6191 switch(bt) {
6192 case VT_VOID:
6193 tstr = "void";
6194 goto add_tstr;
6195 case VT_BOOL:
6196 tstr = "_Bool";
6197 goto add_tstr;
6198 case VT_BYTE:
6199 tstr = "char";
6200 goto add_tstr;
6201 case VT_SHORT:
6202 tstr = "short";
6203 goto add_tstr;
6204 case VT_INT:
6205 tstr = "int";
6206 goto add_tstr;
6207 case VT_LONG:
6208 tstr = "long";
6209 goto add_tstr;
6210 case VT_LLONG:
6211 tstr = "long long";
6212 goto add_tstr;
6213 case VT_FLOAT:
6214 tstr = "float";
6215 goto add_tstr;
6216 case VT_DOUBLE:
6217 tstr = "double";
6218 goto add_tstr;
6219 case VT_LDOUBLE:
6220 tstr = "long double";
6221 add_tstr:
6222 pstrcat(buf, buf_size, tstr);
6223 break;
6224 case VT_ENUM:
6225 case VT_STRUCT:
6226 if (bt == VT_STRUCT)
6227 tstr = "struct ";
6228 else
6229 tstr = "enum ";
6230 pstrcat(buf, buf_size, tstr);
6231 v = type->ref->v & ~SYM_STRUCT;
6232 if (v >= SYM_FIRST_ANOM)
6233 pstrcat(buf, buf_size, "<anonymous>");
6234 else
6235 pstrcat(buf, buf_size, get_tok_str(v, NULL));
6236 break;
6237 case VT_FUNC:
6238 s = type->ref;
6239 type_to_str(buf, buf_size, &s->type, varstr);
6240 pstrcat(buf, buf_size, "(");
6241 sa = s->next;
6242 while (sa != NULL) {
6243 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
6244 pstrcat(buf, buf_size, buf1);
6245 sa = sa->next;
6246 if (sa)
6247 pstrcat(buf, buf_size, ", ");
6249 pstrcat(buf, buf_size, ")");
6250 goto no_var;
6251 case VT_PTR:
6252 s = type->ref;
6253 pstrcpy(buf1, sizeof(buf1), "*");
6254 if (varstr)
6255 pstrcat(buf1, sizeof(buf1), varstr);
6256 type_to_str(buf, buf_size, &s->type, buf1);
6257 goto no_var;
6259 if (varstr) {
6260 pstrcat(buf, buf_size, " ");
6261 pstrcat(buf, buf_size, varstr);
6263 no_var: ;
6266 /* verify type compatibility to store vtop in 'dt' type, and generate
6267 casts if needed. */
6268 static void gen_assign_cast(CType *dt)
6270 CType *st, *type1, *type2, tmp_type1, tmp_type2;
6271 char buf1[256], buf2[256];
6272 int dbt, sbt;
6274 st = &vtop->type; /* source type */
6275 dbt = dt->t & VT_BTYPE;
6276 sbt = st->t & VT_BTYPE;
6277 if (dt->t & VT_CONSTANT)
6278 warning("assignment of read-only location");
6279 switch(dbt) {
6280 case VT_PTR:
6281 /* special cases for pointers */
6282 /* '0' can also be a pointer */
6283 if (is_null_pointer(vtop))
6284 goto type_ok;
6285 /* accept implicit pointer to integer cast with warning */
6286 if (is_integer_btype(sbt)) {
6287 warning("assignment makes pointer from integer without a cast");
6288 goto type_ok;
6290 type1 = pointed_type(dt);
6291 /* a function is implicitely a function pointer */
6292 if (sbt == VT_FUNC) {
6293 if ((type1->t & VT_BTYPE) != VT_VOID &&
6294 !is_compatible_types(pointed_type(dt), st))
6295 goto error;
6296 else
6297 goto type_ok;
6299 if (sbt != VT_PTR)
6300 goto error;
6301 type2 = pointed_type(st);
6302 if ((type1->t & VT_BTYPE) == VT_VOID ||
6303 (type2->t & VT_BTYPE) == VT_VOID) {
6304 /* void * can match anything */
6305 } else {
6306 /* exact type match, except for unsigned */
6307 tmp_type1 = *type1;
6308 tmp_type2 = *type2;
6309 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
6310 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
6311 if (!is_compatible_types(&tmp_type1, &tmp_type2))
6312 warning("assignment from incompatible pointer type");
6314 /* check const and volatile */
6315 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
6316 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
6317 warning("assignment discards qualifiers from pointer target type");
6318 break;
6319 case VT_BYTE:
6320 case VT_SHORT:
6321 case VT_INT:
6322 case VT_LLONG:
6323 if (sbt == VT_PTR || sbt == VT_FUNC) {
6324 warning("assignment makes integer from pointer without a cast");
6326 /* XXX: more tests */
6327 break;
6328 case VT_STRUCT:
6329 tmp_type1 = *dt;
6330 tmp_type2 = *st;
6331 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
6332 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
6333 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
6334 error:
6335 type_to_str(buf1, sizeof(buf1), st, NULL);
6336 type_to_str(buf2, sizeof(buf2), dt, NULL);
6337 error("cannot cast '%s' to '%s'", buf1, buf2);
6339 break;
6341 type_ok:
6342 gen_cast(dt);
6345 /* store vtop in lvalue pushed on stack */
6346 void vstore(void)
6348 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
6350 ft = vtop[-1].type.t;
6351 sbt = vtop->type.t & VT_BTYPE;
6352 dbt = ft & VT_BTYPE;
6353 if (((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
6354 (sbt == VT_INT && dbt == VT_SHORT)) {
6355 /* optimize char/short casts */
6356 delayed_cast = VT_MUSTCAST;
6357 vtop->type.t = ft & VT_TYPE;
6358 /* XXX: factorize */
6359 if (ft & VT_CONSTANT)
6360 warning("assignment of read-only location");
6361 } else {
6362 delayed_cast = 0;
6363 if (!(ft & VT_BITFIELD))
6364 gen_assign_cast(&vtop[-1].type);
6367 if (sbt == VT_STRUCT) {
6368 /* if structure, only generate pointer */
6369 /* structure assignment : generate memcpy */
6370 /* XXX: optimize if small size */
6371 if (!nocode_wanted) {
6372 size = type_size(&vtop->type, &align);
6374 #ifdef TCC_ARM_EABI
6375 if(!(align & 7))
6376 vpush_global_sym(&func_old_type, TOK_memcpy8);
6377 else if(!(align & 3))
6378 vpush_global_sym(&func_old_type, TOK_memcpy4);
6379 else
6380 #endif
6381 vpush_global_sym(&func_old_type, TOK_memcpy);
6383 /* destination */
6384 vpushv(vtop - 2);
6385 vtop->type.t = VT_INT;
6386 gaddrof();
6387 /* source */
6388 vpushv(vtop - 2);
6389 vtop->type.t = VT_INT;
6390 gaddrof();
6391 /* type size */
6392 vpushi(size);
6393 gfunc_call(3);
6395 vswap();
6396 vpop();
6397 } else {
6398 vswap();
6399 vpop();
6401 /* leave source on stack */
6402 } else if (ft & VT_BITFIELD) {
6403 /* bitfield store handling */
6404 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
6405 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
6406 /* remove bit field info to avoid loops */
6407 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
6409 /* duplicate source into other register */
6410 gv_dup();
6411 vswap();
6412 vrott(3);
6414 /* duplicate destination */
6415 vdup();
6416 vtop[-1] = vtop[-2];
6418 /* mask and shift source */
6419 vpushi((1 << bit_size) - 1);
6420 gen_op('&');
6421 vpushi(bit_pos);
6422 gen_op(TOK_SHL);
6423 /* load destination, mask and or with source */
6424 vswap();
6425 vpushi(~(((1 << bit_size) - 1) << bit_pos));
6426 gen_op('&');
6427 gen_op('|');
6428 /* store result */
6429 vstore();
6431 /* pop off shifted source from "duplicate source..." above */
6432 vpop();
6434 } else {
6435 #ifdef CONFIG_TCC_BCHECK
6436 /* bound check case */
6437 if (vtop[-1].r & VT_MUSTBOUND) {
6438 vswap();
6439 gbound();
6440 vswap();
6442 #endif
6443 if (!nocode_wanted) {
6444 rc = RC_INT;
6445 if (is_float(ft))
6446 rc = RC_FLOAT;
6447 r = gv(rc); /* generate value */
6448 /* if lvalue was saved on stack, must read it */
6449 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
6450 SValue sv;
6451 t = get_reg(RC_INT);
6452 sv.type.t = VT_INT;
6453 sv.r = VT_LOCAL | VT_LVAL;
6454 sv.c.ul = vtop[-1].c.ul;
6455 load(t, &sv);
6456 vtop[-1].r = t | VT_LVAL;
6458 store(r, vtop - 1);
6459 /* two word case handling : store second register at word + 4 */
6460 if ((ft & VT_BTYPE) == VT_LLONG) {
6461 vswap();
6462 /* convert to int to increment easily */
6463 vtop->type.t = VT_INT;
6464 gaddrof();
6465 vpushi(4);
6466 gen_op('+');
6467 vtop->r |= VT_LVAL;
6468 vswap();
6469 /* XXX: it works because r2 is spilled last ! */
6470 store(vtop->r2, vtop - 1);
6473 vswap();
6474 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
6475 vtop->r |= delayed_cast;
6479 /* post defines POST/PRE add. c is the token ++ or -- */
6480 void inc(int post, int c)
6482 test_lvalue();
6483 vdup(); /* save lvalue */
6484 if (post) {
6485 gv_dup(); /* duplicate value */
6486 vrotb(3);
6487 vrotb(3);
6489 /* add constant */
6490 vpushi(c - TOK_MID);
6491 gen_op('+');
6492 vstore(); /* store value */
6493 if (post)
6494 vpop(); /* if post op, return saved value */
6497 /* Parse GNUC __attribute__ extension. Currently, the following
6498 extensions are recognized:
6499 - aligned(n) : set data/function alignment.
6500 - packed : force data alignment to 1
6501 - section(x) : generate data/code in this section.
6502 - unused : currently ignored, but may be used someday.
6503 - regparm(n) : pass function parameters in registers (i386 only)
6505 static void parse_attribute(AttributeDef *ad)
6507 int t, n;
6509 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
6510 next();
6511 skip('(');
6512 skip('(');
6513 while (tok != ')') {
6514 if (tok < TOK_IDENT)
6515 expect("attribute name");
6516 t = tok;
6517 next();
6518 switch(t) {
6519 case TOK_SECTION1:
6520 case TOK_SECTION2:
6521 skip('(');
6522 if (tok != TOK_STR)
6523 expect("section name");
6524 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
6525 next();
6526 skip(')');
6527 break;
6528 case TOK_ALIGNED1:
6529 case TOK_ALIGNED2:
6530 if (tok == '(') {
6531 next();
6532 n = expr_const();
6533 if (n <= 0 || (n & (n - 1)) != 0)
6534 error("alignment must be a positive power of two");
6535 skip(')');
6536 } else {
6537 n = MAX_ALIGN;
6539 ad->aligned = n;
6540 break;
6541 case TOK_PACKED1:
6542 case TOK_PACKED2:
6543 ad->packed = 1;
6544 break;
6545 case TOK_UNUSED1:
6546 case TOK_UNUSED2:
6547 /* currently, no need to handle it because tcc does not
6548 track unused objects */
6549 break;
6550 case TOK_NORETURN1:
6551 case TOK_NORETURN2:
6552 /* currently, no need to handle it because tcc does not
6553 track unused objects */
6554 break;
6555 case TOK_CDECL1:
6556 case TOK_CDECL2:
6557 case TOK_CDECL3:
6558 ad->func_call = FUNC_CDECL;
6559 break;
6560 case TOK_STDCALL1:
6561 case TOK_STDCALL2:
6562 case TOK_STDCALL3:
6563 ad->func_call = FUNC_STDCALL;
6564 break;
6565 #ifdef TCC_TARGET_I386
6566 case TOK_REGPARM1:
6567 case TOK_REGPARM2:
6568 skip('(');
6569 n = expr_const();
6570 if (n > 3)
6571 n = 3;
6572 else if (n < 0)
6573 n = 0;
6574 if (n > 0)
6575 ad->func_call = FUNC_FASTCALL1 + n - 1;
6576 skip(')');
6577 break;
6578 case TOK_FASTCALL1:
6579 case TOK_FASTCALL2:
6580 case TOK_FASTCALL3:
6581 ad->func_call = FUNC_FASTCALLW;
6582 break;
6583 #endif
6584 case TOK_DLLEXPORT:
6585 ad->dllexport = 1;
6586 break;
6587 default:
6588 if (tcc_state->warn_unsupported)
6589 warning("'%s' attribute ignored", get_tok_str(t, NULL));
6590 /* skip parameters */
6591 if (tok == '(') {
6592 int parenthesis = 0;
6593 do {
6594 if (tok == '(')
6595 parenthesis++;
6596 else if (tok == ')')
6597 parenthesis--;
6598 next();
6599 } while (parenthesis && tok != -1);
6601 break;
6603 if (tok != ',')
6604 break;
6605 next();
6607 skip(')');
6608 skip(')');
6612 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6613 static void struct_decl(CType *type, int u)
6615 int a, v, size, align, maxalign, c, offset;
6616 int bit_size, bit_pos, bsize, bt, lbit_pos;
6617 Sym *s, *ss, *ass, **ps;
6618 AttributeDef ad;
6619 CType type1, btype;
6621 a = tok; /* save decl type */
6622 next();
6623 if (tok != '{') {
6624 v = tok;
6625 next();
6626 /* struct already defined ? return it */
6627 if (v < TOK_IDENT)
6628 expect("struct/union/enum name");
6629 s = struct_find(v);
6630 if (s) {
6631 if (s->type.t != a)
6632 error("invalid type");
6633 goto do_decl;
6635 } else {
6636 v = anon_sym++;
6638 type1.t = a;
6639 /* we put an undefined size for struct/union */
6640 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
6641 s->r = 0; /* default alignment is zero as gcc */
6642 /* put struct/union/enum name in type */
6643 do_decl:
6644 type->t = u;
6645 type->ref = s;
6647 if (tok == '{') {
6648 next();
6649 if (s->c != -1)
6650 error("struct/union/enum already defined");
6651 /* cannot be empty */
6652 c = 0;
6653 /* non empty enums are not allowed */
6654 if (a == TOK_ENUM) {
6655 for(;;) {
6656 v = tok;
6657 if (v < TOK_UIDENT)
6658 expect("identifier");
6659 next();
6660 if (tok == '=') {
6661 next();
6662 c = expr_const();
6664 /* enum symbols have static storage */
6665 ss = sym_push(v, &int_type, VT_CONST, c);
6666 ss->type.t |= VT_STATIC;
6667 if (tok != ',')
6668 break;
6669 next();
6670 c++;
6671 /* NOTE: we accept a trailing comma */
6672 if (tok == '}')
6673 break;
6675 skip('}');
6676 } else {
6677 maxalign = 1;
6678 ps = &s->next;
6679 bit_pos = 0;
6680 offset = 0;
6681 while (tok != '}') {
6682 parse_btype(&btype, &ad);
6683 while (1) {
6684 bit_size = -1;
6685 v = 0;
6686 type1 = btype;
6687 if (tok != ':') {
6688 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
6689 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
6690 expect("identifier");
6691 if ((type1.t & VT_BTYPE) == VT_FUNC ||
6692 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
6693 error("invalid type for '%s'",
6694 get_tok_str(v, NULL));
6696 if (tok == ':') {
6697 next();
6698 bit_size = expr_const();
6699 /* XXX: handle v = 0 case for messages */
6700 if (bit_size < 0)
6701 error("negative width in bit-field '%s'",
6702 get_tok_str(v, NULL));
6703 if (v && bit_size == 0)
6704 error("zero width for bit-field '%s'",
6705 get_tok_str(v, NULL));
6707 size = type_size(&type1, &align);
6708 if (ad.aligned) {
6709 if (align < ad.aligned)
6710 align = ad.aligned;
6711 } else if (ad.packed) {
6712 align = 1;
6713 } else if (*tcc_state->pack_stack_ptr) {
6714 if (align > *tcc_state->pack_stack_ptr)
6715 align = *tcc_state->pack_stack_ptr;
6717 lbit_pos = 0;
6718 if (bit_size >= 0) {
6719 bt = type1.t & VT_BTYPE;
6720 if (bt != VT_INT &&
6721 bt != VT_BYTE &&
6722 bt != VT_SHORT &&
6723 bt != VT_BOOL &&
6724 bt != VT_ENUM)
6725 error("bitfields must have scalar type");
6726 bsize = size * 8;
6727 if (bit_size > bsize) {
6728 error("width of '%s' exceeds its type",
6729 get_tok_str(v, NULL));
6730 } else if (bit_size == bsize) {
6731 /* no need for bit fields */
6732 bit_pos = 0;
6733 } else if (bit_size == 0) {
6734 /* XXX: what to do if only padding in a
6735 structure ? */
6736 /* zero size: means to pad */
6737 if (bit_pos > 0)
6738 bit_pos = bsize;
6739 } else {
6740 /* we do not have enough room ? */
6741 if ((bit_pos + bit_size) > bsize)
6742 bit_pos = 0;
6743 lbit_pos = bit_pos;
6744 /* XXX: handle LSB first */
6745 type1.t |= VT_BITFIELD |
6746 (bit_pos << VT_STRUCT_SHIFT) |
6747 (bit_size << (VT_STRUCT_SHIFT + 6));
6748 bit_pos += bit_size;
6750 } else {
6751 bit_pos = 0;
6753 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
6754 /* add new memory data only if starting
6755 bit field */
6756 if (lbit_pos == 0) {
6757 if (a == TOK_STRUCT) {
6758 c = (c + align - 1) & -align;
6759 offset = c;
6760 if (size > 0)
6761 c += size;
6762 } else {
6763 offset = 0;
6764 if (size > c)
6765 c = size;
6767 if (align > maxalign)
6768 maxalign = align;
6770 #if 0
6771 printf("add field %s offset=%d",
6772 get_tok_str(v, NULL), offset);
6773 if (type1.t & VT_BITFIELD) {
6774 printf(" pos=%d size=%d",
6775 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
6776 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
6778 printf("\n");
6779 #endif
6781 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
6782 ass = type1.ref;
6783 while ((ass = ass->next) != NULL) {
6784 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
6785 *ps = ss;
6786 ps = &ss->next;
6788 } else if (v) {
6789 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
6790 *ps = ss;
6791 ps = &ss->next;
6793 if (tok == ';' || tok == TOK_EOF)
6794 break;
6795 skip(',');
6797 skip(';');
6799 skip('}');
6800 /* store size and alignment */
6801 s->c = (c + maxalign - 1) & -maxalign;
6802 s->r = maxalign;
6807 /* return 0 if no type declaration. otherwise, return the basic type
6808 and skip it.
6810 static int parse_btype(CType *type, AttributeDef *ad)
6812 int t, u, type_found, typespec_found, typedef_found;
6813 Sym *s;
6814 CType type1;
6816 memset(ad, 0, sizeof(AttributeDef));
6817 type_found = 0;
6818 typespec_found = 0;
6819 typedef_found = 0;
6820 t = 0;
6821 while(1) {
6822 switch(tok) {
6823 case TOK_EXTENSION:
6824 /* currently, we really ignore extension */
6825 next();
6826 continue;
6828 /* basic types */
6829 case TOK_CHAR:
6830 u = VT_BYTE;
6831 basic_type:
6832 next();
6833 basic_type1:
6834 if ((t & VT_BTYPE) != 0)
6835 error("too many basic types");
6836 t |= u;
6837 typespec_found = 1;
6838 break;
6839 case TOK_VOID:
6840 u = VT_VOID;
6841 goto basic_type;
6842 case TOK_SHORT:
6843 u = VT_SHORT;
6844 goto basic_type;
6845 case TOK_INT:
6846 next();
6847 typespec_found = 1;
6848 break;
6849 case TOK_LONG:
6850 next();
6851 if ((t & VT_BTYPE) == VT_DOUBLE) {
6852 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
6853 } else if ((t & VT_BTYPE) == VT_LONG) {
6854 t = (t & ~VT_BTYPE) | VT_LLONG;
6855 } else {
6856 u = VT_LONG;
6857 goto basic_type1;
6859 break;
6860 case TOK_BOOL:
6861 u = VT_BOOL;
6862 goto basic_type;
6863 case TOK_FLOAT:
6864 u = VT_FLOAT;
6865 goto basic_type;
6866 case TOK_DOUBLE:
6867 next();
6868 if ((t & VT_BTYPE) == VT_LONG) {
6869 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
6870 } else {
6871 u = VT_DOUBLE;
6872 goto basic_type1;
6874 break;
6875 case TOK_ENUM:
6876 struct_decl(&type1, VT_ENUM);
6877 basic_type2:
6878 u = type1.t;
6879 type->ref = type1.ref;
6880 goto basic_type1;
6881 case TOK_STRUCT:
6882 case TOK_UNION:
6883 struct_decl(&type1, VT_STRUCT);
6884 goto basic_type2;
6886 /* type modifiers */
6887 case TOK_CONST1:
6888 case TOK_CONST2:
6889 case TOK_CONST3:
6890 t |= VT_CONSTANT;
6891 next();
6892 break;
6893 case TOK_VOLATILE1:
6894 case TOK_VOLATILE2:
6895 case TOK_VOLATILE3:
6896 t |= VT_VOLATILE;
6897 next();
6898 break;
6899 case TOK_SIGNED1:
6900 case TOK_SIGNED2:
6901 case TOK_SIGNED3:
6902 typespec_found = 1;
6903 t |= VT_SIGNED;
6904 next();
6905 break;
6906 case TOK_REGISTER:
6907 case TOK_AUTO:
6908 case TOK_RESTRICT1:
6909 case TOK_RESTRICT2:
6910 case TOK_RESTRICT3:
6911 next();
6912 break;
6913 case TOK_UNSIGNED:
6914 t |= VT_UNSIGNED;
6915 next();
6916 typespec_found = 1;
6917 break;
6919 /* storage */
6920 case TOK_EXTERN:
6921 t |= VT_EXTERN;
6922 next();
6923 break;
6924 case TOK_STATIC:
6925 t |= VT_STATIC;
6926 next();
6927 break;
6928 case TOK_TYPEDEF:
6929 t |= VT_TYPEDEF;
6930 next();
6931 break;
6932 case TOK_INLINE1:
6933 case TOK_INLINE2:
6934 case TOK_INLINE3:
6935 t |= VT_INLINE;
6936 next();
6937 break;
6939 /* GNUC attribute */
6940 case TOK_ATTRIBUTE1:
6941 case TOK_ATTRIBUTE2:
6942 parse_attribute(ad);
6943 break;
6944 /* GNUC typeof */
6945 case TOK_TYPEOF1:
6946 case TOK_TYPEOF2:
6947 case TOK_TYPEOF3:
6948 next();
6949 parse_expr_type(&type1);
6950 goto basic_type2;
6951 default:
6952 if (typespec_found || typedef_found)
6953 goto the_end;
6954 s = sym_find(tok);
6955 if (!s || !(s->type.t & VT_TYPEDEF))
6956 goto the_end;
6957 typedef_found = 1;
6958 t |= (s->type.t & ~VT_TYPEDEF);
6959 type->ref = s->type.ref;
6960 next();
6961 typespec_found = 1;
6962 break;
6964 type_found = 1;
6966 the_end:
6967 if ((t & (VT_SIGNED|VT_UNSIGNED)) == (VT_SIGNED|VT_UNSIGNED))
6968 error("signed and unsigned modifier");
6969 if (tcc_state->char_is_unsigned) {
6970 if ((t & (VT_SIGNED|VT_UNSIGNED|VT_BTYPE)) == VT_BYTE)
6971 t |= VT_UNSIGNED;
6973 t &= ~VT_SIGNED;
6975 /* long is never used as type */
6976 if ((t & VT_BTYPE) == VT_LONG)
6977 t = (t & ~VT_BTYPE) | VT_INT;
6978 type->t = t;
6979 return type_found;
6982 /* convert a function parameter type (array to pointer and function to
6983 function pointer) */
6984 static inline void convert_parameter_type(CType *pt)
6986 /* remove const and volatile qualifiers (XXX: const could be used
6987 to indicate a const function parameter */
6988 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
6989 /* array must be transformed to pointer according to ANSI C */
6990 pt->t &= ~VT_ARRAY;
6991 if ((pt->t & VT_BTYPE) == VT_FUNC) {
6992 mk_pointer(pt);
6996 static void post_type(CType *type, AttributeDef *ad)
6998 int n, l, t1;
6999 Sym **plast, *s, *first;
7000 AttributeDef ad1;
7001 CType pt;
7003 if (tok == '(') {
7004 /* function declaration */
7005 next();
7006 l = 0;
7007 first = NULL;
7008 plast = &first;
7009 if (tok != ')') {
7010 for(;;) {
7011 /* read param name and compute offset */
7012 if (l != FUNC_OLD) {
7013 if (!parse_btype(&pt, &ad1)) {
7014 if (l) {
7015 error("invalid type");
7016 } else {
7017 l = FUNC_OLD;
7018 goto old_proto;
7021 l = FUNC_NEW;
7022 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
7023 break;
7024 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
7025 if ((pt.t & VT_BTYPE) == VT_VOID)
7026 error("parameter declared as void");
7027 } else {
7028 old_proto:
7029 n = tok;
7030 if (n < TOK_UIDENT)
7031 expect("identifier");
7032 pt.t = VT_INT;
7033 next();
7035 convert_parameter_type(&pt);
7036 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
7037 *plast = s;
7038 plast = &s->next;
7039 if (tok == ')')
7040 break;
7041 skip(',');
7042 if (l == FUNC_NEW && tok == TOK_DOTS) {
7043 l = FUNC_ELLIPSIS;
7044 next();
7045 break;
7049 /* if no parameters, then old type prototype */
7050 if (l == 0)
7051 l = FUNC_OLD;
7052 skip(')');
7053 t1 = type->t & VT_STORAGE;
7054 /* NOTE: const is ignored in returned type as it has a special
7055 meaning in gcc / C++ */
7056 type->t &= ~(VT_STORAGE | VT_CONSTANT);
7057 post_type(type, ad);
7058 /* we push a anonymous symbol which will contain the function prototype */
7059 s = sym_push(SYM_FIELD, type, ad->func_call, l);
7060 s->next = first;
7061 type->t = t1 | VT_FUNC;
7062 type->ref = s;
7063 } else if (tok == '[') {
7064 /* array definition */
7065 next();
7066 n = -1;
7067 if (tok != ']') {
7068 n = expr_const();
7069 if (n < 0)
7070 error("invalid array size");
7072 skip(']');
7073 /* parse next post type */
7074 t1 = type->t & VT_STORAGE;
7075 type->t &= ~VT_STORAGE;
7076 post_type(type, ad);
7078 /* we push a anonymous symbol which will contain the array
7079 element type */
7080 s = sym_push(SYM_FIELD, type, 0, n);
7081 type->t = t1 | VT_ARRAY | VT_PTR;
7082 type->ref = s;
7086 /* Parse a type declaration (except basic type), and return the type
7087 in 'type'. 'td' is a bitmask indicating which kind of type decl is
7088 expected. 'type' should contain the basic type. 'ad' is the
7089 attribute definition of the basic type. It can be modified by
7090 type_decl().
7092 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
7094 Sym *s;
7095 CType type1, *type2;
7096 int qualifiers;
7098 while (tok == '*') {
7099 qualifiers = 0;
7100 redo:
7101 next();
7102 switch(tok) {
7103 case TOK_CONST1:
7104 case TOK_CONST2:
7105 case TOK_CONST3:
7106 qualifiers |= VT_CONSTANT;
7107 goto redo;
7108 case TOK_VOLATILE1:
7109 case TOK_VOLATILE2:
7110 case TOK_VOLATILE3:
7111 qualifiers |= VT_VOLATILE;
7112 goto redo;
7113 case TOK_RESTRICT1:
7114 case TOK_RESTRICT2:
7115 case TOK_RESTRICT3:
7116 goto redo;
7118 mk_pointer(type);
7119 type->t |= qualifiers;
7122 /* XXX: clarify attribute handling */
7123 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7124 parse_attribute(ad);
7126 /* recursive type */
7127 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
7128 type1.t = 0; /* XXX: same as int */
7129 if (tok == '(') {
7130 next();
7131 /* XXX: this is not correct to modify 'ad' at this point, but
7132 the syntax is not clear */
7133 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7134 parse_attribute(ad);
7135 type_decl(&type1, ad, v, td);
7136 skip(')');
7137 } else {
7138 /* type identifier */
7139 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
7140 *v = tok;
7141 next();
7142 } else {
7143 if (!(td & TYPE_ABSTRACT))
7144 expect("identifier");
7145 *v = 0;
7148 post_type(type, ad);
7149 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7150 parse_attribute(ad);
7151 if (!type1.t)
7152 return;
7153 /* append type at the end of type1 */
7154 type2 = &type1;
7155 for(;;) {
7156 s = type2->ref;
7157 type2 = &s->type;
7158 if (!type2->t) {
7159 *type2 = *type;
7160 break;
7163 *type = type1;
7166 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
7167 static int lvalue_type(int t)
7169 int bt, r;
7170 r = VT_LVAL;
7171 bt = t & VT_BTYPE;
7172 if (bt == VT_BYTE || bt == VT_BOOL)
7173 r |= VT_LVAL_BYTE;
7174 else if (bt == VT_SHORT)
7175 r |= VT_LVAL_SHORT;
7176 else
7177 return r;
7178 if (t & VT_UNSIGNED)
7179 r |= VT_LVAL_UNSIGNED;
7180 return r;
7183 /* indirection with full error checking and bound check */
7184 static void indir(void)
7186 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
7187 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
7188 return;
7189 expect("pointer");
7191 if ((vtop->r & VT_LVAL) && !nocode_wanted)
7192 gv(RC_INT);
7193 vtop->type = *pointed_type(&vtop->type);
7194 /* Arrays and functions are never lvalues */
7195 if (!(vtop->type.t & VT_ARRAY)
7196 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
7197 vtop->r |= lvalue_type(vtop->type.t);
7198 /* if bound checking, the referenced pointer must be checked */
7199 if (do_bounds_check)
7200 vtop->r |= VT_MUSTBOUND;
7204 /* pass a parameter to a function and do type checking and casting */
7205 static void gfunc_param_typed(Sym *func, Sym *arg)
7207 int func_type;
7208 CType type;
7210 func_type = func->c;
7211 if (func_type == FUNC_OLD ||
7212 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
7213 /* default casting : only need to convert float to double */
7214 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
7215 type.t = VT_DOUBLE;
7216 gen_cast(&type);
7218 } else if (arg == NULL) {
7219 error("too many arguments to function");
7220 } else {
7221 type = arg->type;
7222 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
7223 gen_assign_cast(&type);
7227 /* parse an expression of the form '(type)' or '(expr)' and return its
7228 type */
7229 static void parse_expr_type(CType *type)
7231 int n;
7232 AttributeDef ad;
7234 skip('(');
7235 if (parse_btype(type, &ad)) {
7236 type_decl(type, &ad, &n, TYPE_ABSTRACT);
7237 } else {
7238 expr_type(type);
7240 skip(')');
7243 static void parse_type(CType *type)
7245 AttributeDef ad;
7246 int n;
7248 if (!parse_btype(type, &ad)) {
7249 expect("type");
7251 type_decl(type, &ad, &n, TYPE_ABSTRACT);
7254 static void vpush_tokc(int t)
7256 CType type;
7257 type.t = t;
7258 vsetc(&type, VT_CONST, &tokc);
7261 static void unary(void)
7263 int n, t, align, size, r;
7264 CType type;
7265 Sym *s;
7266 AttributeDef ad;
7268 /* XXX: GCC 2.95.3 does not generate a table although it should be
7269 better here */
7270 tok_next:
7271 switch(tok) {
7272 case TOK_EXTENSION:
7273 next();
7274 goto tok_next;
7275 case TOK_CINT:
7276 case TOK_CCHAR:
7277 case TOK_LCHAR:
7278 vpushi(tokc.i);
7279 next();
7280 break;
7281 case TOK_CUINT:
7282 vpush_tokc(VT_INT | VT_UNSIGNED);
7283 next();
7284 break;
7285 case TOK_CLLONG:
7286 vpush_tokc(VT_LLONG);
7287 next();
7288 break;
7289 case TOK_CULLONG:
7290 vpush_tokc(VT_LLONG | VT_UNSIGNED);
7291 next();
7292 break;
7293 case TOK_CFLOAT:
7294 vpush_tokc(VT_FLOAT);
7295 next();
7296 break;
7297 case TOK_CDOUBLE:
7298 vpush_tokc(VT_DOUBLE);
7299 next();
7300 break;
7301 case TOK_CLDOUBLE:
7302 vpush_tokc(VT_LDOUBLE);
7303 next();
7304 break;
7305 case TOK___FUNCTION__:
7306 if (!gnu_ext)
7307 goto tok_identifier;
7308 /* fall thru */
7309 case TOK___FUNC__:
7311 void *ptr;
7312 int len;
7313 /* special function name identifier */
7314 len = strlen(funcname) + 1;
7315 /* generate char[len] type */
7316 type.t = VT_BYTE;
7317 mk_pointer(&type);
7318 type.t |= VT_ARRAY;
7319 type.ref->c = len;
7320 vpush_ref(&type, data_section, data_section->data_offset, len);
7321 ptr = section_ptr_add(data_section, len);
7322 memcpy(ptr, funcname, len);
7323 next();
7325 break;
7326 case TOK_LSTR:
7327 #ifdef TCC_TARGET_PE
7328 t = VT_SHORT | VT_UNSIGNED;
7329 #else
7330 t = VT_INT;
7331 #endif
7332 goto str_init;
7333 case TOK_STR:
7334 /* string parsing */
7335 t = VT_BYTE;
7336 str_init:
7337 if (tcc_state->warn_write_strings)
7338 t |= VT_CONSTANT;
7339 type.t = t;
7340 mk_pointer(&type);
7341 type.t |= VT_ARRAY;
7342 memset(&ad, 0, sizeof(AttributeDef));
7343 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
7344 break;
7345 case '(':
7346 next();
7347 /* cast ? */
7348 if (parse_btype(&type, &ad)) {
7349 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
7350 skip(')');
7351 /* check ISOC99 compound literal */
7352 if (tok == '{') {
7353 /* data is allocated locally by default */
7354 if (global_expr)
7355 r = VT_CONST;
7356 else
7357 r = VT_LOCAL;
7358 /* all except arrays are lvalues */
7359 if (!(type.t & VT_ARRAY))
7360 r |= lvalue_type(type.t);
7361 memset(&ad, 0, sizeof(AttributeDef));
7362 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
7363 } else {
7364 unary();
7365 gen_cast(&type);
7367 } else if (tok == '{') {
7368 /* save all registers */
7369 save_regs(0);
7370 /* statement expression : we do not accept break/continue
7371 inside as GCC does */
7372 block(NULL, NULL, NULL, NULL, 0, 1);
7373 skip(')');
7374 } else {
7375 gexpr();
7376 skip(')');
7378 break;
7379 case '*':
7380 next();
7381 unary();
7382 indir();
7383 break;
7384 case '&':
7385 next();
7386 unary();
7387 /* functions names must be treated as function pointers,
7388 except for unary '&' and sizeof. Since we consider that
7389 functions are not lvalues, we only have to handle it
7390 there and in function calls. */
7391 /* arrays can also be used although they are not lvalues */
7392 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
7393 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
7394 test_lvalue();
7395 mk_pointer(&vtop->type);
7396 gaddrof();
7397 break;
7398 case '!':
7399 next();
7400 unary();
7401 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST)
7402 vtop->c.i = !vtop->c.i;
7403 else if ((vtop->r & VT_VALMASK) == VT_CMP)
7404 vtop->c.i = vtop->c.i ^ 1;
7405 else {
7406 save_regs(1);
7407 vseti(VT_JMP, gtst(1, 0));
7409 break;
7410 case '~':
7411 next();
7412 unary();
7413 vpushi(-1);
7414 gen_op('^');
7415 break;
7416 case '+':
7417 next();
7418 /* in order to force cast, we add zero */
7419 unary();
7420 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
7421 error("pointer not accepted for unary plus");
7422 vpushi(0);
7423 gen_op('+');
7424 break;
7425 case TOK_SIZEOF:
7426 case TOK_ALIGNOF1:
7427 case TOK_ALIGNOF2:
7428 t = tok;
7429 next();
7430 if (tok == '(') {
7431 parse_expr_type(&type);
7432 } else {
7433 unary_type(&type);
7435 size = type_size(&type, &align);
7436 if (t == TOK_SIZEOF) {
7437 if (size < 0)
7438 error("sizeof applied to an incomplete type");
7439 vpushi(size);
7440 } else {
7441 vpushi(align);
7443 vtop->type.t |= VT_UNSIGNED;
7444 break;
7446 case TOK_builtin_types_compatible_p:
7448 CType type1, type2;
7449 next();
7450 skip('(');
7451 parse_type(&type1);
7452 skip(',');
7453 parse_type(&type2);
7454 skip(')');
7455 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
7456 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
7457 vpushi(is_compatible_types(&type1, &type2));
7459 break;
7460 case TOK_builtin_constant_p:
7462 int saved_nocode_wanted, res;
7463 next();
7464 skip('(');
7465 saved_nocode_wanted = nocode_wanted;
7466 nocode_wanted = 1;
7467 gexpr();
7468 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
7469 vpop();
7470 nocode_wanted = saved_nocode_wanted;
7471 skip(')');
7472 vpushi(res);
7474 break;
7475 case TOK_INC:
7476 case TOK_DEC:
7477 t = tok;
7478 next();
7479 unary();
7480 inc(0, t);
7481 break;
7482 case '-':
7483 next();
7484 vpushi(0);
7485 unary();
7486 gen_op('-');
7487 break;
7488 case TOK_LAND:
7489 if (!gnu_ext)
7490 goto tok_identifier;
7491 next();
7492 /* allow to take the address of a label */
7493 if (tok < TOK_UIDENT)
7494 expect("label identifier");
7495 s = label_find(tok);
7496 if (!s) {
7497 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
7498 } else {
7499 if (s->r == LABEL_DECLARED)
7500 s->r = LABEL_FORWARD;
7502 if (!s->type.t) {
7503 s->type.t = VT_VOID;
7504 mk_pointer(&s->type);
7505 s->type.t |= VT_STATIC;
7507 vset(&s->type, VT_CONST | VT_SYM, 0);
7508 vtop->sym = s;
7509 next();
7510 break;
7511 default:
7512 tok_identifier:
7513 t = tok;
7514 next();
7515 if (t < TOK_UIDENT)
7516 expect("identifier");
7517 s = sym_find(t);
7518 if (!s) {
7519 if (tok != '(')
7520 error("'%s' undeclared", get_tok_str(t, NULL));
7521 /* for simple function calls, we tolerate undeclared
7522 external reference to int() function */
7523 if (tcc_state->warn_implicit_function_declaration)
7524 warning("implicit declaration of function '%s'",
7525 get_tok_str(t, NULL));
7526 s = external_global_sym(t, &func_old_type, 0);
7528 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
7529 (VT_STATIC | VT_INLINE | VT_FUNC)) {
7530 /* if referencing an inline function, then we generate a
7531 symbol to it if not already done. It will have the
7532 effect to generate code for it at the end of the
7533 compilation unit. Inline function as always
7534 generated in the text section. */
7535 if (!s->c)
7536 put_extern_sym(s, text_section, 0, 0);
7537 r = VT_SYM | VT_CONST;
7538 } else {
7539 r = s->r;
7541 vset(&s->type, r, s->c);
7542 /* if forward reference, we must point to s */
7543 if (vtop->r & VT_SYM) {
7544 vtop->sym = s;
7545 vtop->c.ul = 0;
7547 break;
7550 /* post operations */
7551 while (1) {
7552 if (tok == TOK_INC || tok == TOK_DEC) {
7553 inc(1, tok);
7554 next();
7555 } else if (tok == '.' || tok == TOK_ARROW) {
7556 /* field */
7557 if (tok == TOK_ARROW)
7558 indir();
7559 test_lvalue();
7560 gaddrof();
7561 next();
7562 /* expect pointer on structure */
7563 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
7564 expect("struct or union");
7565 s = vtop->type.ref;
7566 /* find field */
7567 tok |= SYM_FIELD;
7568 while ((s = s->next) != NULL) {
7569 if (s->v == tok)
7570 break;
7572 if (!s)
7573 error("field not found");
7574 /* add field offset to pointer */
7575 vtop->type = char_pointer_type; /* change type to 'char *' */
7576 vpushi(s->c);
7577 gen_op('+');
7578 /* change type to field type, and set to lvalue */
7579 vtop->type = s->type;
7580 /* an array is never an lvalue */
7581 if (!(vtop->type.t & VT_ARRAY)) {
7582 vtop->r |= lvalue_type(vtop->type.t);
7583 /* if bound checking, the referenced pointer must be checked */
7584 if (do_bounds_check)
7585 vtop->r |= VT_MUSTBOUND;
7587 next();
7588 } else if (tok == '[') {
7589 next();
7590 gexpr();
7591 gen_op('+');
7592 indir();
7593 skip(']');
7594 } else if (tok == '(') {
7595 SValue ret;
7596 Sym *sa;
7597 int nb_args;
7599 /* function call */
7600 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
7601 /* pointer test (no array accepted) */
7602 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
7603 vtop->type = *pointed_type(&vtop->type);
7604 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
7605 goto error_func;
7606 } else {
7607 error_func:
7608 expect("function pointer");
7610 } else {
7611 vtop->r &= ~VT_LVAL; /* no lvalue */
7613 /* get return type */
7614 s = vtop->type.ref;
7615 next();
7616 sa = s->next; /* first parameter */
7617 nb_args = 0;
7618 /* compute first implicit argument if a structure is returned */
7619 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
7620 /* get some space for the returned structure */
7621 size = type_size(&s->type, &align);
7622 loc = (loc - size) & -align;
7623 ret.type = s->type;
7624 ret.r = VT_LOCAL | VT_LVAL;
7625 /* pass it as 'int' to avoid structure arg passing
7626 problems */
7627 vseti(VT_LOCAL, loc);
7628 ret.c = vtop->c;
7629 nb_args++;
7630 } else {
7631 ret.type = s->type;
7632 ret.r2 = VT_CONST;
7633 /* return in register */
7634 if (is_float(ret.type.t)) {
7635 ret.r = REG_FRET;
7636 } else {
7637 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
7638 ret.r2 = REG_LRET;
7639 ret.r = REG_IRET;
7641 ret.c.i = 0;
7643 if (tok != ')') {
7644 for(;;) {
7645 expr_eq();
7646 gfunc_param_typed(s, sa);
7647 nb_args++;
7648 if (sa)
7649 sa = sa->next;
7650 if (tok == ')')
7651 break;
7652 skip(',');
7655 if (sa)
7656 error("too few arguments to function");
7657 skip(')');
7658 if (!nocode_wanted) {
7659 gfunc_call(nb_args);
7660 } else {
7661 vtop -= (nb_args + 1);
7663 /* return value */
7664 vsetc(&ret.type, ret.r, &ret.c);
7665 vtop->r2 = ret.r2;
7666 } else {
7667 break;
7672 static void uneq(void)
7674 int t;
7676 unary();
7677 if (tok == '=' ||
7678 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
7679 tok == TOK_A_XOR || tok == TOK_A_OR ||
7680 tok == TOK_A_SHL || tok == TOK_A_SAR) {
7681 test_lvalue();
7682 t = tok;
7683 next();
7684 if (t == '=') {
7685 expr_eq();
7686 } else {
7687 vdup();
7688 expr_eq();
7689 gen_op(t & 0x7f);
7691 vstore();
7695 static void expr_prod(void)
7697 int t;
7699 uneq();
7700 while (tok == '*' || tok == '/' || tok == '%') {
7701 t = tok;
7702 next();
7703 uneq();
7704 gen_op(t);
7708 static void expr_sum(void)
7710 int t;
7712 expr_prod();
7713 while (tok == '+' || tok == '-') {
7714 t = tok;
7715 next();
7716 expr_prod();
7717 gen_op(t);
7721 static void expr_shift(void)
7723 int t;
7725 expr_sum();
7726 while (tok == TOK_SHL || tok == TOK_SAR) {
7727 t = tok;
7728 next();
7729 expr_sum();
7730 gen_op(t);
7734 static void expr_cmp(void)
7736 int t;
7738 expr_shift();
7739 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
7740 tok == TOK_ULT || tok == TOK_UGE) {
7741 t = tok;
7742 next();
7743 expr_shift();
7744 gen_op(t);
7748 static void expr_cmpeq(void)
7750 int t;
7752 expr_cmp();
7753 while (tok == TOK_EQ || tok == TOK_NE) {
7754 t = tok;
7755 next();
7756 expr_cmp();
7757 gen_op(t);
7761 static void expr_and(void)
7763 expr_cmpeq();
7764 while (tok == '&') {
7765 next();
7766 expr_cmpeq();
7767 gen_op('&');
7771 static void expr_xor(void)
7773 expr_and();
7774 while (tok == '^') {
7775 next();
7776 expr_and();
7777 gen_op('^');
7781 static void expr_or(void)
7783 expr_xor();
7784 while (tok == '|') {
7785 next();
7786 expr_xor();
7787 gen_op('|');
7791 /* XXX: fix this mess */
7792 static void expr_land_const(void)
7794 expr_or();
7795 while (tok == TOK_LAND) {
7796 next();
7797 expr_or();
7798 gen_op(TOK_LAND);
7802 /* XXX: fix this mess */
7803 static void expr_lor_const(void)
7805 expr_land_const();
7806 while (tok == TOK_LOR) {
7807 next();
7808 expr_land_const();
7809 gen_op(TOK_LOR);
7813 /* only used if non constant */
7814 static void expr_land(void)
7816 int t;
7818 expr_or();
7819 if (tok == TOK_LAND) {
7820 t = 0;
7821 save_regs(1);
7822 for(;;) {
7823 t = gtst(1, t);
7824 if (tok != TOK_LAND) {
7825 vseti(VT_JMPI, t);
7826 break;
7828 next();
7829 expr_or();
7834 static void expr_lor(void)
7836 int t;
7838 expr_land();
7839 if (tok == TOK_LOR) {
7840 t = 0;
7841 save_regs(1);
7842 for(;;) {
7843 t = gtst(0, t);
7844 if (tok != TOK_LOR) {
7845 vseti(VT_JMP, t);
7846 break;
7848 next();
7849 expr_land();
7854 /* XXX: better constant handling */
7855 static void expr_eq(void)
7857 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
7858 SValue sv;
7859 CType type, type1, type2;
7861 if (const_wanted) {
7862 int c1, c;
7863 expr_lor_const();
7864 if (tok == '?') {
7865 c = vtop->c.i;
7866 vpop();
7867 next();
7868 if (tok == ':' && gnu_ext) {
7869 c1 = c;
7870 } else {
7871 gexpr();
7872 c1 = vtop->c.i;
7873 vpop();
7875 skip(':');
7876 expr_eq();
7877 if (c)
7878 vtop->c.i = c1;
7880 } else {
7881 expr_lor();
7882 if (tok == '?') {
7883 next();
7884 if (vtop != vstack) {
7885 /* needed to avoid having different registers saved in
7886 each branch */
7887 if (is_float(vtop->type.t))
7888 rc = RC_FLOAT;
7889 else
7890 rc = RC_INT;
7891 gv(rc);
7892 save_regs(1);
7894 if (tok == ':' && gnu_ext) {
7895 gv_dup();
7896 tt = gtst(1, 0);
7897 } else {
7898 tt = gtst(1, 0);
7899 gexpr();
7901 type1 = vtop->type;
7902 sv = *vtop; /* save value to handle it later */
7903 vtop--; /* no vpop so that FP stack is not flushed */
7904 skip(':');
7905 u = gjmp(0);
7906 gsym(tt);
7907 expr_eq();
7908 type2 = vtop->type;
7910 t1 = type1.t;
7911 bt1 = t1 & VT_BTYPE;
7912 t2 = type2.t;
7913 bt2 = t2 & VT_BTYPE;
7914 /* cast operands to correct type according to ISOC rules */
7915 if (is_float(bt1) || is_float(bt2)) {
7916 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
7917 type.t = VT_LDOUBLE;
7918 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
7919 type.t = VT_DOUBLE;
7920 } else {
7921 type.t = VT_FLOAT;
7923 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
7924 /* cast to biggest op */
7925 type.t = VT_LLONG;
7926 /* convert to unsigned if it does not fit in a long long */
7927 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
7928 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
7929 type.t |= VT_UNSIGNED;
7930 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
7931 /* XXX: test pointer compatibility */
7932 type = type1;
7933 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
7934 /* XXX: test function pointer compatibility */
7935 type = type1;
7936 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
7937 /* XXX: test structure compatibility */
7938 type = type1;
7939 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
7940 /* NOTE: as an extension, we accept void on only one side */
7941 type.t = VT_VOID;
7942 } else {
7943 /* integer operations */
7944 type.t = VT_INT;
7945 /* convert to unsigned if it does not fit in an integer */
7946 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
7947 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
7948 type.t |= VT_UNSIGNED;
7951 /* now we convert second operand */
7952 gen_cast(&type);
7953 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
7954 gaddrof();
7955 rc = RC_INT;
7956 if (is_float(type.t)) {
7957 rc = RC_FLOAT;
7958 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
7959 /* for long longs, we use fixed registers to avoid having
7960 to handle a complicated move */
7961 rc = RC_IRET;
7964 r2 = gv(rc);
7965 /* this is horrible, but we must also convert first
7966 operand */
7967 tt = gjmp(0);
7968 gsym(u);
7969 /* put again first value and cast it */
7970 *vtop = sv;
7971 gen_cast(&type);
7972 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
7973 gaddrof();
7974 r1 = gv(rc);
7975 move_reg(r2, r1);
7976 vtop->r = r2;
7977 gsym(tt);
7982 static void gexpr(void)
7984 while (1) {
7985 expr_eq();
7986 if (tok != ',')
7987 break;
7988 vpop();
7989 next();
7993 /* parse an expression and return its type without any side effect. */
7994 static void expr_type(CType *type)
7996 int saved_nocode_wanted;
7998 saved_nocode_wanted = nocode_wanted;
7999 nocode_wanted = 1;
8000 gexpr();
8001 *type = vtop->type;
8002 vpop();
8003 nocode_wanted = saved_nocode_wanted;
8006 /* parse a unary expression and return its type without any side
8007 effect. */
8008 static void unary_type(CType *type)
8010 int a;
8012 a = nocode_wanted;
8013 nocode_wanted = 1;
8014 unary();
8015 *type = vtop->type;
8016 vpop();
8017 nocode_wanted = a;
8020 /* parse a constant expression and return value in vtop. */
8021 static void expr_const1(void)
8023 int a;
8024 a = const_wanted;
8025 const_wanted = 1;
8026 expr_eq();
8027 const_wanted = a;
8030 /* parse an integer constant and return its value. */
8031 static int expr_const(void)
8033 int c;
8034 expr_const1();
8035 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
8036 expect("constant expression");
8037 c = vtop->c.i;
8038 vpop();
8039 return c;
8042 /* return the label token if current token is a label, otherwise
8043 return zero */
8044 static int is_label(void)
8046 int last_tok;
8048 /* fast test first */
8049 if (tok < TOK_UIDENT)
8050 return 0;
8051 /* no need to save tokc because tok is an identifier */
8052 last_tok = tok;
8053 next();
8054 if (tok == ':') {
8055 next();
8056 return last_tok;
8057 } else {
8058 unget_tok(last_tok);
8059 return 0;
8063 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
8064 int case_reg, int is_expr)
8066 int a, b, c, d;
8067 Sym *s;
8069 /* generate line number info */
8070 if (do_debug &&
8071 (last_line_num != file->line_num || last_ind != ind)) {
8072 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
8073 last_ind = ind;
8074 last_line_num = file->line_num;
8077 if (is_expr) {
8078 /* default return value is (void) */
8079 vpushi(0);
8080 vtop->type.t = VT_VOID;
8083 if (tok == TOK_IF) {
8084 /* if test */
8085 next();
8086 skip('(');
8087 gexpr();
8088 skip(')');
8089 a = gtst(1, 0);
8090 block(bsym, csym, case_sym, def_sym, case_reg, 0);
8091 c = tok;
8092 if (c == TOK_ELSE) {
8093 next();
8094 d = gjmp(0);
8095 gsym(a);
8096 block(bsym, csym, case_sym, def_sym, case_reg, 0);
8097 gsym(d); /* patch else jmp */
8098 } else
8099 gsym(a);
8100 } else if (tok == TOK_WHILE) {
8101 next();
8102 d = ind;
8103 skip('(');
8104 gexpr();
8105 skip(')');
8106 a = gtst(1, 0);
8107 b = 0;
8108 block(&a, &b, case_sym, def_sym, case_reg, 0);
8109 gjmp_addr(d);
8110 gsym(a);
8111 gsym_addr(b, d);
8112 } else if (tok == '{') {
8113 Sym *llabel;
8115 next();
8116 /* record local declaration stack position */
8117 s = local_stack;
8118 llabel = local_label_stack;
8119 /* handle local labels declarations */
8120 if (tok == TOK_LABEL) {
8121 next();
8122 for(;;) {
8123 if (tok < TOK_UIDENT)
8124 expect("label identifier");
8125 label_push(&local_label_stack, tok, LABEL_DECLARED);
8126 next();
8127 if (tok == ',') {
8128 next();
8129 } else {
8130 skip(';');
8131 break;
8135 while (tok != '}') {
8136 decl(VT_LOCAL);
8137 if (tok != '}') {
8138 if (is_expr)
8139 vpop();
8140 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
8143 /* pop locally defined labels */
8144 label_pop(&local_label_stack, llabel);
8145 /* pop locally defined symbols */
8146 sym_pop(&local_stack, s);
8147 next();
8148 } else if (tok == TOK_RETURN) {
8149 next();
8150 if (tok != ';') {
8151 gexpr();
8152 gen_assign_cast(&func_vt);
8153 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
8154 CType type;
8155 /* if returning structure, must copy it to implicit
8156 first pointer arg location */
8157 #ifdef TCC_ARM_EABI
8158 int align, size;
8159 size = type_size(&func_vt,&align);
8160 if(size <= 4)
8162 if((vtop->r != (VT_LOCAL | VT_LVAL) || (vtop->c.i & 3))
8163 && (align & 3))
8165 int addr;
8166 loc = (loc - size) & -4;
8167 addr = loc;
8168 type = func_vt;
8169 vset(&type, VT_LOCAL | VT_LVAL, addr);
8170 vswap();
8171 vstore();
8172 vset(&int_type, VT_LOCAL | VT_LVAL, addr);
8174 vtop->type = int_type;
8175 gv(RC_IRET);
8176 } else {
8177 #endif
8178 type = func_vt;
8179 mk_pointer(&type);
8180 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
8181 indir();
8182 vswap();
8183 /* copy structure value to pointer */
8184 vstore();
8185 #ifdef TCC_ARM_EABI
8187 #endif
8188 } else if (is_float(func_vt.t)) {
8189 gv(RC_FRET);
8190 } else {
8191 gv(RC_IRET);
8193 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
8195 skip(';');
8196 rsym = gjmp(rsym); /* jmp */
8197 } else if (tok == TOK_BREAK) {
8198 /* compute jump */
8199 if (!bsym)
8200 error("cannot break");
8201 *bsym = gjmp(*bsym);
8202 next();
8203 skip(';');
8204 } else if (tok == TOK_CONTINUE) {
8205 /* compute jump */
8206 if (!csym)
8207 error("cannot continue");
8208 *csym = gjmp(*csym);
8209 next();
8210 skip(';');
8211 } else if (tok == TOK_FOR) {
8212 int e;
8213 next();
8214 skip('(');
8215 if (tok != ';') {
8216 gexpr();
8217 vpop();
8219 skip(';');
8220 d = ind;
8221 c = ind;
8222 a = 0;
8223 b = 0;
8224 if (tok != ';') {
8225 gexpr();
8226 a = gtst(1, 0);
8228 skip(';');
8229 if (tok != ')') {
8230 e = gjmp(0);
8231 c = ind;
8232 gexpr();
8233 vpop();
8234 gjmp_addr(d);
8235 gsym(e);
8237 skip(')');
8238 block(&a, &b, case_sym, def_sym, case_reg, 0);
8239 gjmp_addr(c);
8240 gsym(a);
8241 gsym_addr(b, c);
8242 } else
8243 if (tok == TOK_DO) {
8244 next();
8245 a = 0;
8246 b = 0;
8247 d = ind;
8248 block(&a, &b, case_sym, def_sym, case_reg, 0);
8249 skip(TOK_WHILE);
8250 skip('(');
8251 gsym(b);
8252 gexpr();
8253 c = gtst(0, 0);
8254 gsym_addr(c, d);
8255 skip(')');
8256 gsym(a);
8257 skip(';');
8258 } else
8259 if (tok == TOK_SWITCH) {
8260 next();
8261 skip('(');
8262 gexpr();
8263 /* XXX: other types than integer */
8264 case_reg = gv(RC_INT);
8265 vpop();
8266 skip(')');
8267 a = 0;
8268 b = gjmp(0); /* jump to first case */
8269 c = 0;
8270 block(&a, csym, &b, &c, case_reg, 0);
8271 /* if no default, jmp after switch */
8272 if (c == 0)
8273 c = ind;
8274 /* default label */
8275 gsym_addr(b, c);
8276 /* break label */
8277 gsym(a);
8278 } else
8279 if (tok == TOK_CASE) {
8280 int v1, v2;
8281 if (!case_sym)
8282 expect("switch");
8283 next();
8284 v1 = expr_const();
8285 v2 = v1;
8286 if (gnu_ext && tok == TOK_DOTS) {
8287 next();
8288 v2 = expr_const();
8289 if (v2 < v1)
8290 warning("empty case range");
8292 /* since a case is like a label, we must skip it with a jmp */
8293 b = gjmp(0);
8294 gsym(*case_sym);
8295 vseti(case_reg, 0);
8296 vpushi(v1);
8297 if (v1 == v2) {
8298 gen_op(TOK_EQ);
8299 *case_sym = gtst(1, 0);
8300 } else {
8301 gen_op(TOK_GE);
8302 *case_sym = gtst(1, 0);
8303 vseti(case_reg, 0);
8304 vpushi(v2);
8305 gen_op(TOK_LE);
8306 *case_sym = gtst(1, *case_sym);
8308 gsym(b);
8309 skip(':');
8310 is_expr = 0;
8311 goto block_after_label;
8312 } else
8313 if (tok == TOK_DEFAULT) {
8314 next();
8315 skip(':');
8316 if (!def_sym)
8317 expect("switch");
8318 if (*def_sym)
8319 error("too many 'default'");
8320 *def_sym = ind;
8321 is_expr = 0;
8322 goto block_after_label;
8323 } else
8324 if (tok == TOK_GOTO) {
8325 next();
8326 if (tok == '*' && gnu_ext) {
8327 /* computed goto */
8328 next();
8329 gexpr();
8330 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
8331 expect("pointer");
8332 ggoto();
8333 } else if (tok >= TOK_UIDENT) {
8334 s = label_find(tok);
8335 /* put forward definition if needed */
8336 if (!s) {
8337 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
8338 } else {
8339 if (s->r == LABEL_DECLARED)
8340 s->r = LABEL_FORWARD;
8342 /* label already defined */
8343 if (s->r & LABEL_FORWARD)
8344 s->next = (void *)gjmp((long)s->next);
8345 else
8346 gjmp_addr((long)s->next);
8347 next();
8348 } else {
8349 expect("label identifier");
8351 skip(';');
8352 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
8353 asm_instr();
8354 } else {
8355 b = is_label();
8356 if (b) {
8357 /* label case */
8358 s = label_find(b);
8359 if (s) {
8360 if (s->r == LABEL_DEFINED)
8361 error("duplicate label '%s'", get_tok_str(s->v, NULL));
8362 gsym((long)s->next);
8363 s->r = LABEL_DEFINED;
8364 } else {
8365 s = label_push(&global_label_stack, b, LABEL_DEFINED);
8367 s->next = (void *)ind;
8368 /* we accept this, but it is a mistake */
8369 block_after_label:
8370 if (tok == '}') {
8371 warning("deprecated use of label at end of compound statement");
8372 } else {
8373 if (is_expr)
8374 vpop();
8375 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
8377 } else {
8378 /* expression case */
8379 if (tok != ';') {
8380 if (is_expr) {
8381 vpop();
8382 gexpr();
8383 } else {
8384 gexpr();
8385 vpop();
8388 skip(';');
8393 /* t is the array or struct type. c is the array or struct
8394 address. cur_index/cur_field is the pointer to the current
8395 value. 'size_only' is true if only size info is needed (only used
8396 in arrays) */
8397 static void decl_designator(CType *type, Section *sec, unsigned long c,
8398 int *cur_index, Sym **cur_field,
8399 int size_only)
8401 Sym *s, *f;
8402 int notfirst, index, index_last, align, l, nb_elems, elem_size;
8403 CType type1;
8405 notfirst = 0;
8406 elem_size = 0;
8407 nb_elems = 1;
8408 if (gnu_ext && (l = is_label()) != 0)
8409 goto struct_field;
8410 while (tok == '[' || tok == '.') {
8411 if (tok == '[') {
8412 if (!(type->t & VT_ARRAY))
8413 expect("array type");
8414 s = type->ref;
8415 next();
8416 index = expr_const();
8417 if (index < 0 || (s->c >= 0 && index >= s->c))
8418 expect("invalid index");
8419 if (tok == TOK_DOTS && gnu_ext) {
8420 next();
8421 index_last = expr_const();
8422 if (index_last < 0 ||
8423 (s->c >= 0 && index_last >= s->c) ||
8424 index_last < index)
8425 expect("invalid index");
8426 } else {
8427 index_last = index;
8429 skip(']');
8430 if (!notfirst)
8431 *cur_index = index_last;
8432 type = pointed_type(type);
8433 elem_size = type_size(type, &align);
8434 c += index * elem_size;
8435 /* NOTE: we only support ranges for last designator */
8436 nb_elems = index_last - index + 1;
8437 if (nb_elems != 1) {
8438 notfirst = 1;
8439 break;
8441 } else {
8442 next();
8443 l = tok;
8444 next();
8445 struct_field:
8446 if ((type->t & VT_BTYPE) != VT_STRUCT)
8447 expect("struct/union type");
8448 s = type->ref;
8449 l |= SYM_FIELD;
8450 f = s->next;
8451 while (f) {
8452 if (f->v == l)
8453 break;
8454 f = f->next;
8456 if (!f)
8457 expect("field");
8458 if (!notfirst)
8459 *cur_field = f;
8460 /* XXX: fix this mess by using explicit storage field */
8461 type1 = f->type;
8462 type1.t |= (type->t & ~VT_TYPE);
8463 type = &type1;
8464 c += f->c;
8466 notfirst = 1;
8468 if (notfirst) {
8469 if (tok == '=') {
8470 next();
8471 } else {
8472 if (!gnu_ext)
8473 expect("=");
8475 } else {
8476 if (type->t & VT_ARRAY) {
8477 index = *cur_index;
8478 type = pointed_type(type);
8479 c += index * type_size(type, &align);
8480 } else {
8481 f = *cur_field;
8482 if (!f)
8483 error("too many field init");
8484 /* XXX: fix this mess by using explicit storage field */
8485 type1 = f->type;
8486 type1.t |= (type->t & ~VT_TYPE);
8487 type = &type1;
8488 c += f->c;
8491 decl_initializer(type, sec, c, 0, size_only);
8493 /* XXX: make it more general */
8494 if (!size_only && nb_elems > 1) {
8495 unsigned long c_end;
8496 uint8_t *src, *dst;
8497 int i;
8499 if (!sec)
8500 error("range init not supported yet for dynamic storage");
8501 c_end = c + nb_elems * elem_size;
8502 if (c_end > sec->data_allocated)
8503 section_realloc(sec, c_end);
8504 src = sec->data + c;
8505 dst = src;
8506 for(i = 1; i < nb_elems; i++) {
8507 dst += elem_size;
8508 memcpy(dst, src, elem_size);
8513 #define EXPR_VAL 0
8514 #define EXPR_CONST 1
8515 #define EXPR_ANY 2
8517 /* store a value or an expression directly in global data or in local array */
8518 static void init_putv(CType *type, Section *sec, unsigned long c,
8519 int v, int expr_type)
8521 int saved_global_expr, bt, bit_pos, bit_size;
8522 void *ptr;
8523 unsigned long long bit_mask;
8524 CType dtype;
8526 switch(expr_type) {
8527 case EXPR_VAL:
8528 vpushi(v);
8529 break;
8530 case EXPR_CONST:
8531 /* compound literals must be allocated globally in this case */
8532 saved_global_expr = global_expr;
8533 global_expr = 1;
8534 expr_const1();
8535 global_expr = saved_global_expr;
8536 /* NOTE: symbols are accepted */
8537 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
8538 error("initializer element is not constant");
8539 break;
8540 case EXPR_ANY:
8541 expr_eq();
8542 break;
8545 dtype = *type;
8546 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
8548 if (sec) {
8549 /* XXX: not portable */
8550 /* XXX: generate error if incorrect relocation */
8551 gen_assign_cast(&dtype);
8552 bt = type->t & VT_BTYPE;
8553 ptr = sec->data + c;
8554 /* XXX: make code faster ? */
8555 if (!(type->t & VT_BITFIELD)) {
8556 bit_pos = 0;
8557 bit_size = 32;
8558 bit_mask = -1LL;
8559 } else {
8560 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
8561 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
8562 bit_mask = (1LL << bit_size) - 1;
8564 if ((vtop->r & VT_SYM) &&
8565 (bt == VT_BYTE ||
8566 bt == VT_SHORT ||
8567 bt == VT_DOUBLE ||
8568 bt == VT_LDOUBLE ||
8569 bt == VT_LLONG ||
8570 (bt == VT_INT && bit_size != 32)))
8571 error("initializer element is not computable at load time");
8572 switch(bt) {
8573 case VT_BYTE:
8574 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8575 break;
8576 case VT_SHORT:
8577 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8578 break;
8579 case VT_DOUBLE:
8580 *(double *)ptr = vtop->c.d;
8581 break;
8582 case VT_LDOUBLE:
8583 *(long double *)ptr = vtop->c.ld;
8584 break;
8585 case VT_LLONG:
8586 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
8587 break;
8588 default:
8589 if (vtop->r & VT_SYM) {
8590 greloc(sec, vtop->sym, c, R_DATA_32);
8592 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8593 break;
8595 vtop--;
8596 } else {
8597 vset(&dtype, VT_LOCAL|VT_LVAL, c);
8598 vswap();
8599 vstore();
8600 vpop();
8604 /* put zeros for variable based init */
8605 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
8607 if (sec) {
8608 /* nothing to do because globals are already set to zero */
8609 } else {
8610 vpush_global_sym(&func_old_type, TOK_memset);
8611 vseti(VT_LOCAL, c);
8612 vpushi(0);
8613 vpushi(size);
8614 gfunc_call(3);
8618 /* 't' contains the type and storage info. 'c' is the offset of the
8619 object in section 'sec'. If 'sec' is NULL, it means stack based
8620 allocation. 'first' is true if array '{' must be read (multi
8621 dimension implicit array init handling). 'size_only' is true if
8622 size only evaluation is wanted (only for arrays). */
8623 static void decl_initializer(CType *type, Section *sec, unsigned long c,
8624 int first, int size_only)
8626 int index, array_length, n, no_oblock, nb, parlevel, i;
8627 int size1, align1, expr_type;
8628 Sym *s, *f;
8629 CType *t1;
8631 if (type->t & VT_ARRAY) {
8632 s = type->ref;
8633 n = s->c;
8634 array_length = 0;
8635 t1 = pointed_type(type);
8636 size1 = type_size(t1, &align1);
8638 no_oblock = 1;
8639 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
8640 tok == '{') {
8641 skip('{');
8642 no_oblock = 0;
8645 /* only parse strings here if correct type (otherwise: handle
8646 them as ((w)char *) expressions */
8647 if ((tok == TOK_LSTR &&
8648 #ifdef TCC_TARGET_PE
8649 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)) ||
8650 #else
8651 (t1->t & VT_BTYPE) == VT_INT) ||
8652 #endif
8653 (tok == TOK_STR &&
8654 (t1->t & VT_BTYPE) == VT_BYTE)) {
8655 while (tok == TOK_STR || tok == TOK_LSTR) {
8656 int cstr_len, ch;
8657 CString *cstr;
8659 cstr = tokc.cstr;
8660 /* compute maximum number of chars wanted */
8661 if (tok == TOK_STR)
8662 cstr_len = cstr->size;
8663 else
8664 cstr_len = cstr->size / sizeof(nwchar_t);
8665 cstr_len--;
8666 nb = cstr_len;
8667 if (n >= 0 && nb > (n - array_length))
8668 nb = n - array_length;
8669 if (!size_only) {
8670 if (cstr_len > nb)
8671 warning("initializer-string for array is too long");
8672 /* in order to go faster for common case (char
8673 string in global variable, we handle it
8674 specifically */
8675 if (sec && tok == TOK_STR && size1 == 1) {
8676 memcpy(sec->data + c + array_length, cstr->data, nb);
8677 } else {
8678 for(i=0;i<nb;i++) {
8679 if (tok == TOK_STR)
8680 ch = ((unsigned char *)cstr->data)[i];
8681 else
8682 ch = ((nwchar_t *)cstr->data)[i];
8683 init_putv(t1, sec, c + (array_length + i) * size1,
8684 ch, EXPR_VAL);
8688 array_length += nb;
8689 next();
8691 /* only add trailing zero if enough storage (no
8692 warning in this case since it is standard) */
8693 if (n < 0 || array_length < n) {
8694 if (!size_only) {
8695 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
8697 array_length++;
8699 } else {
8700 index = 0;
8701 while (tok != '}') {
8702 decl_designator(type, sec, c, &index, NULL, size_only);
8703 if (n >= 0 && index >= n)
8704 error("index too large");
8705 /* must put zero in holes (note that doing it that way
8706 ensures that it even works with designators) */
8707 if (!size_only && array_length < index) {
8708 init_putz(t1, sec, c + array_length * size1,
8709 (index - array_length) * size1);
8711 index++;
8712 if (index > array_length)
8713 array_length = index;
8714 /* special test for multi dimensional arrays (may not
8715 be strictly correct if designators are used at the
8716 same time) */
8717 if (index >= n && no_oblock)
8718 break;
8719 if (tok == '}')
8720 break;
8721 skip(',');
8724 if (!no_oblock)
8725 skip('}');
8726 /* put zeros at the end */
8727 if (!size_only && n >= 0 && array_length < n) {
8728 init_putz(t1, sec, c + array_length * size1,
8729 (n - array_length) * size1);
8731 /* patch type size if needed */
8732 if (n < 0)
8733 s->c = array_length;
8734 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
8735 (sec || !first || tok == '{')) {
8736 int par_count;
8738 /* NOTE: the previous test is a specific case for automatic
8739 struct/union init */
8740 /* XXX: union needs only one init */
8742 /* XXX: this test is incorrect for local initializers
8743 beginning with ( without {. It would be much more difficult
8744 to do it correctly (ideally, the expression parser should
8745 be used in all cases) */
8746 par_count = 0;
8747 if (tok == '(') {
8748 AttributeDef ad1;
8749 CType type1;
8750 next();
8751 while (tok == '(') {
8752 par_count++;
8753 next();
8755 if (!parse_btype(&type1, &ad1))
8756 expect("cast");
8757 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
8758 #if 0
8759 if (!is_assignable_types(type, &type1))
8760 error("invalid type for cast");
8761 #endif
8762 skip(')');
8764 no_oblock = 1;
8765 if (first || tok == '{') {
8766 skip('{');
8767 no_oblock = 0;
8769 s = type->ref;
8770 f = s->next;
8771 array_length = 0;
8772 index = 0;
8773 n = s->c;
8774 while (tok != '}') {
8775 decl_designator(type, sec, c, NULL, &f, size_only);
8776 index = f->c;
8777 if (!size_only && array_length < index) {
8778 init_putz(type, sec, c + array_length,
8779 index - array_length);
8781 index = index + type_size(&f->type, &align1);
8782 if (index > array_length)
8783 array_length = index;
8784 f = f->next;
8785 if (no_oblock && f == NULL)
8786 break;
8787 if (tok == '}')
8788 break;
8789 skip(',');
8791 /* put zeros at the end */
8792 if (!size_only && array_length < n) {
8793 init_putz(type, sec, c + array_length,
8794 n - array_length);
8796 if (!no_oblock)
8797 skip('}');
8798 while (par_count) {
8799 skip(')');
8800 par_count--;
8802 } else if (tok == '{') {
8803 next();
8804 decl_initializer(type, sec, c, first, size_only);
8805 skip('}');
8806 } else if (size_only) {
8807 /* just skip expression */
8808 parlevel = 0;
8809 while ((parlevel > 0 || (tok != '}' && tok != ',')) &&
8810 tok != -1) {
8811 if (tok == '(')
8812 parlevel++;
8813 else if (tok == ')')
8814 parlevel--;
8815 next();
8817 } else {
8818 /* currently, we always use constant expression for globals
8819 (may change for scripting case) */
8820 expr_type = EXPR_CONST;
8821 if (!sec)
8822 expr_type = EXPR_ANY;
8823 init_putv(type, sec, c, 0, expr_type);
8827 /* parse an initializer for type 't' if 'has_init' is non zero, and
8828 allocate space in local or global data space ('r' is either
8829 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
8830 variable 'v' of scope 'scope' is declared before initializers are
8831 parsed. If 'v' is zero, then a reference to the new object is put
8832 in the value stack. If 'has_init' is 2, a special parsing is done
8833 to handle string constants. */
8834 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
8835 int has_init, int v, int scope)
8837 int size, align, addr, data_offset;
8838 int level;
8839 ParseState saved_parse_state;
8840 TokenString init_str;
8841 Section *sec;
8843 size = type_size(type, &align);
8844 /* If unknown size, we must evaluate it before
8845 evaluating initializers because
8846 initializers can generate global data too
8847 (e.g. string pointers or ISOC99 compound
8848 literals). It also simplifies local
8849 initializers handling */
8850 tok_str_new(&init_str);
8851 if (size < 0) {
8852 if (!has_init)
8853 error("unknown type size");
8854 /* get all init string */
8855 if (has_init == 2) {
8856 /* only get strings */
8857 while (tok == TOK_STR || tok == TOK_LSTR) {
8858 tok_str_add_tok(&init_str);
8859 next();
8861 } else {
8862 level = 0;
8863 while (level > 0 || (tok != ',' && tok != ';')) {
8864 if (tok < 0)
8865 error("unexpected end of file in initializer");
8866 tok_str_add_tok(&init_str);
8867 if (tok == '{')
8868 level++;
8869 else if (tok == '}') {
8870 if (level == 0)
8871 break;
8872 level--;
8874 next();
8877 tok_str_add(&init_str, -1);
8878 tok_str_add(&init_str, 0);
8880 /* compute size */
8881 save_parse_state(&saved_parse_state);
8883 macro_ptr = init_str.str;
8884 next();
8885 decl_initializer(type, NULL, 0, 1, 1);
8886 /* prepare second initializer parsing */
8887 macro_ptr = init_str.str;
8888 next();
8890 /* if still unknown size, error */
8891 size = type_size(type, &align);
8892 if (size < 0)
8893 error("unknown type size");
8895 /* take into account specified alignment if bigger */
8896 if (ad->aligned) {
8897 if (ad->aligned > align)
8898 align = ad->aligned;
8899 } else if (ad->packed) {
8900 align = 1;
8902 if ((r & VT_VALMASK) == VT_LOCAL) {
8903 sec = NULL;
8904 if (do_bounds_check && (type->t & VT_ARRAY))
8905 loc--;
8906 loc = (loc - size) & -align;
8907 addr = loc;
8908 /* handles bounds */
8909 /* XXX: currently, since we do only one pass, we cannot track
8910 '&' operators, so we add only arrays */
8911 if (do_bounds_check && (type->t & VT_ARRAY)) {
8912 unsigned long *bounds_ptr;
8913 /* add padding between regions */
8914 loc--;
8915 /* then add local bound info */
8916 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
8917 bounds_ptr[0] = addr;
8918 bounds_ptr[1] = size;
8920 if (v) {
8921 /* local variable */
8922 sym_push(v, type, r, addr);
8923 } else {
8924 /* push local reference */
8925 vset(type, r, addr);
8927 } else {
8928 Sym *sym;
8930 sym = NULL;
8931 if (v && scope == VT_CONST) {
8932 /* see if the symbol was already defined */
8933 sym = sym_find(v);
8934 if (sym) {
8935 if (!is_compatible_types(&sym->type, type))
8936 error("incompatible types for redefinition of '%s'",
8937 get_tok_str(v, NULL));
8938 if (sym->type.t & VT_EXTERN) {
8939 /* if the variable is extern, it was not allocated */
8940 sym->type.t &= ~VT_EXTERN;
8941 /* set array size if it was ommited in extern
8942 declaration */
8943 if ((sym->type.t & VT_ARRAY) &&
8944 sym->type.ref->c < 0 &&
8945 type->ref->c >= 0)
8946 sym->type.ref->c = type->ref->c;
8947 } else {
8948 /* we accept several definitions of the same
8949 global variable. this is tricky, because we
8950 must play with the SHN_COMMON type of the symbol */
8951 /* XXX: should check if the variable was already
8952 initialized. It is incorrect to initialized it
8953 twice */
8954 /* no init data, we won't add more to the symbol */
8955 if (!has_init)
8956 goto no_alloc;
8961 /* allocate symbol in corresponding section */
8962 sec = ad->section;
8963 if (!sec) {
8964 if (has_init)
8965 sec = data_section;
8966 else if (tcc_state->nocommon)
8967 sec = bss_section;
8969 if (sec) {
8970 data_offset = sec->data_offset;
8971 data_offset = (data_offset + align - 1) & -align;
8972 addr = data_offset;
8973 /* very important to increment global pointer at this time
8974 because initializers themselves can create new initializers */
8975 data_offset += size;
8976 /* add padding if bound check */
8977 if (do_bounds_check)
8978 data_offset++;
8979 sec->data_offset = data_offset;
8980 /* allocate section space to put the data */
8981 if (sec->sh_type != SHT_NOBITS &&
8982 data_offset > sec->data_allocated)
8983 section_realloc(sec, data_offset);
8984 /* align section if needed */
8985 if (align > sec->sh_addralign)
8986 sec->sh_addralign = align;
8987 } else {
8988 addr = 0; /* avoid warning */
8991 if (v) {
8992 if (scope != VT_CONST || !sym) {
8993 sym = sym_push(v, type, r | VT_SYM, 0);
8995 /* update symbol definition */
8996 if (sec) {
8997 put_extern_sym(sym, sec, addr, size);
8998 } else {
8999 Elf32_Sym *esym;
9000 /* put a common area */
9001 put_extern_sym(sym, NULL, align, size);
9002 /* XXX: find a nicer way */
9003 esym = &((Elf32_Sym *)symtab_section->data)[sym->c];
9004 esym->st_shndx = SHN_COMMON;
9006 } else {
9007 CValue cval;
9009 /* push global reference */
9010 sym = get_sym_ref(type, sec, addr, size);
9011 cval.ul = 0;
9012 vsetc(type, VT_CONST | VT_SYM, &cval);
9013 vtop->sym = sym;
9016 /* handles bounds now because the symbol must be defined
9017 before for the relocation */
9018 if (do_bounds_check) {
9019 unsigned long *bounds_ptr;
9021 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_32);
9022 /* then add global bound info */
9023 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
9024 bounds_ptr[0] = 0; /* relocated */
9025 bounds_ptr[1] = size;
9028 if (has_init) {
9029 decl_initializer(type, sec, addr, 1, 0);
9030 /* restore parse state if needed */
9031 if (init_str.str) {
9032 tok_str_free(init_str.str);
9033 restore_parse_state(&saved_parse_state);
9036 no_alloc: ;
9039 void put_func_debug(Sym *sym)
9041 char buf[512];
9043 /* stabs info */
9044 /* XXX: we put here a dummy type */
9045 snprintf(buf, sizeof(buf), "%s:%c1",
9046 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
9047 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
9048 cur_text_section, sym->c);
9049 last_ind = 0;
9050 last_line_num = 0;
9053 /* parse an old style function declaration list */
9054 /* XXX: check multiple parameter */
9055 static void func_decl_list(Sym *func_sym)
9057 AttributeDef ad;
9058 int v;
9059 Sym *s;
9060 CType btype, type;
9062 /* parse each declaration */
9063 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF) {
9064 if (!parse_btype(&btype, &ad))
9065 expect("declaration list");
9066 if (((btype.t & VT_BTYPE) == VT_ENUM ||
9067 (btype.t & VT_BTYPE) == VT_STRUCT) &&
9068 tok == ';') {
9069 /* we accept no variable after */
9070 } else {
9071 for(;;) {
9072 type = btype;
9073 type_decl(&type, &ad, &v, TYPE_DIRECT);
9074 /* find parameter in function parameter list */
9075 s = func_sym->next;
9076 while (s != NULL) {
9077 if ((s->v & ~SYM_FIELD) == v)
9078 goto found;
9079 s = s->next;
9081 error("declaration for parameter '%s' but no such parameter",
9082 get_tok_str(v, NULL));
9083 found:
9084 /* check that no storage specifier except 'register' was given */
9085 if (type.t & VT_STORAGE)
9086 error("storage class specified for '%s'", get_tok_str(v, NULL));
9087 convert_parameter_type(&type);
9088 /* we can add the type (NOTE: it could be local to the function) */
9089 s->type = type;
9090 /* accept other parameters */
9091 if (tok == ',')
9092 next();
9093 else
9094 break;
9097 skip(';');
9101 /* parse a function defined by symbol 'sym' and generate its code in
9102 'cur_text_section' */
9103 static void gen_function(Sym *sym)
9105 int saved_nocode_wanted = nocode_wanted;
9106 nocode_wanted = 0;
9107 ind = cur_text_section->data_offset;
9108 /* NOTE: we patch the symbol size later */
9109 put_extern_sym(sym, cur_text_section, ind, 0);
9110 funcname = get_tok_str(sym->v, NULL);
9111 func_ind = ind;
9112 /* put debug symbol */
9113 if (do_debug)
9114 put_func_debug(sym);
9115 /* push a dummy symbol to enable local sym storage */
9116 sym_push2(&local_stack, SYM_FIELD, 0, 0);
9117 gfunc_prolog(&sym->type);
9118 rsym = 0;
9119 block(NULL, NULL, NULL, NULL, 0, 0);
9120 gsym(rsym);
9121 gfunc_epilog();
9122 cur_text_section->data_offset = ind;
9123 label_pop(&global_label_stack, NULL);
9124 sym_pop(&local_stack, NULL); /* reset local stack */
9125 /* end of function */
9126 /* patch symbol size */
9127 ((Elf32_Sym *)symtab_section->data)[sym->c].st_size =
9128 ind - func_ind;
9129 if (do_debug) {
9130 put_stabn(N_FUN, 0, 0, ind - func_ind);
9132 funcname = ""; /* for safety */
9133 func_vt.t = VT_VOID; /* for safety */
9134 ind = 0; /* for safety */
9135 nocode_wanted = saved_nocode_wanted;
9138 static void gen_inline_functions(void)
9140 Sym *sym;
9141 CType *type;
9142 int *str, inline_generated;
9144 /* iterate while inline function are referenced */
9145 for(;;) {
9146 inline_generated = 0;
9147 for(sym = global_stack; sym != NULL; sym = sym->prev) {
9148 type = &sym->type;
9149 if (((type->t & VT_BTYPE) == VT_FUNC) &&
9150 (type->t & (VT_STATIC | VT_INLINE)) ==
9151 (VT_STATIC | VT_INLINE) &&
9152 sym->c != 0) {
9153 /* the function was used: generate its code and
9154 convert it to a normal function */
9155 str = (int *)sym->r;
9156 sym->r = VT_SYM | VT_CONST;
9157 type->t &= ~VT_INLINE;
9159 macro_ptr = str;
9160 next();
9161 cur_text_section = text_section;
9162 gen_function(sym);
9163 macro_ptr = NULL; /* fail safe */
9165 tok_str_free(str);
9166 inline_generated = 1;
9169 if (!inline_generated)
9170 break;
9173 /* free all remaining inline function tokens */
9174 for(sym = global_stack; sym != NULL; sym = sym->prev) {
9175 type = &sym->type;
9176 if (((type->t & VT_BTYPE) == VT_FUNC) &&
9177 (type->t & (VT_STATIC | VT_INLINE)) ==
9178 (VT_STATIC | VT_INLINE)) {
9179 str = (int *)sym->r;
9180 tok_str_free(str);
9181 sym->r = 0; /* fail safe */
9186 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
9187 static void decl(int l)
9189 int v, has_init, r;
9190 CType type, btype;
9191 Sym *sym;
9192 AttributeDef ad;
9194 while (1) {
9195 if (!parse_btype(&btype, &ad)) {
9196 /* skip redundant ';' */
9197 /* XXX: find more elegant solution */
9198 if (tok == ';') {
9199 next();
9200 continue;
9202 if (l == VT_CONST &&
9203 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
9204 /* global asm block */
9205 asm_global_instr();
9206 continue;
9208 /* special test for old K&R protos without explicit int
9209 type. Only accepted when defining global data */
9210 if (l == VT_LOCAL || tok < TOK_DEFINE)
9211 break;
9212 btype.t = VT_INT;
9214 if (((btype.t & VT_BTYPE) == VT_ENUM ||
9215 (btype.t & VT_BTYPE) == VT_STRUCT) &&
9216 tok == ';') {
9217 /* we accept no variable after */
9218 next();
9219 continue;
9221 while (1) { /* iterate thru each declaration */
9222 type = btype;
9223 type_decl(&type, &ad, &v, TYPE_DIRECT);
9224 #if 0
9226 char buf[500];
9227 type_to_str(buf, sizeof(buf), &type, get_tok_str(v, NULL));
9228 printf("type = '%s'\n", buf);
9230 #endif
9231 if ((type.t & VT_BTYPE) == VT_FUNC) {
9232 /* if old style function prototype, we accept a
9233 declaration list */
9234 sym = type.ref;
9235 if (sym->c == FUNC_OLD)
9236 func_decl_list(sym);
9239 if (tok == '{') {
9240 if (l == VT_LOCAL)
9241 error("cannot use local functions");
9242 if ((type.t & VT_BTYPE) != VT_FUNC)
9243 expect("function definition");
9245 /* reject abstract declarators in function definition */
9246 sym = type.ref;
9247 while ((sym = sym->next) != NULL)
9248 if (!(sym->v & ~SYM_FIELD))
9249 expect("identifier");
9251 /* XXX: cannot do better now: convert extern line to static inline */
9252 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
9253 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
9255 sym = sym_find(v);
9256 if (sym) {
9257 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
9258 goto func_error1;
9259 /* specific case: if not func_call defined, we put
9260 the one of the prototype */
9261 /* XXX: should have default value */
9262 if (sym->type.ref->r != FUNC_CDECL &&
9263 type.ref->r == FUNC_CDECL)
9264 type.ref->r = sym->type.ref->r;
9265 if (!is_compatible_types(&sym->type, &type)) {
9266 func_error1:
9267 error("incompatible types for redefinition of '%s'",
9268 get_tok_str(v, NULL));
9270 /* if symbol is already defined, then put complete type */
9271 sym->type = type;
9272 } else {
9273 /* put function symbol */
9274 sym = global_identifier_push(v, type.t, 0);
9275 sym->type.ref = type.ref;
9278 /* static inline functions are just recorded as a kind
9279 of macro. Their code will be emitted at the end of
9280 the compilation unit only if they are used */
9281 if ((type.t & (VT_INLINE | VT_STATIC)) ==
9282 (VT_INLINE | VT_STATIC)) {
9283 TokenString func_str;
9284 int block_level;
9286 tok_str_new(&func_str);
9288 block_level = 0;
9289 for(;;) {
9290 int t;
9291 if (tok == TOK_EOF)
9292 error("unexpected end of file");
9293 tok_str_add_tok(&func_str);
9294 t = tok;
9295 next();
9296 if (t == '{') {
9297 block_level++;
9298 } else if (t == '}') {
9299 block_level--;
9300 if (block_level == 0)
9301 break;
9304 tok_str_add(&func_str, -1);
9305 tok_str_add(&func_str, 0);
9306 sym->r = (int)func_str.str;
9307 } else {
9308 /* compute text section */
9309 cur_text_section = ad.section;
9310 if (!cur_text_section)
9311 cur_text_section = text_section;
9312 sym->r = VT_SYM | VT_CONST;
9313 gen_function(sym);
9314 #ifdef TCC_TARGET_PE
9315 if (ad.dllexport) {
9316 ((Elf32_Sym *)symtab_section->data)[sym->c].st_other |= 1;
9318 #endif
9320 break;
9321 } else {
9322 if (btype.t & VT_TYPEDEF) {
9323 /* save typedefed type */
9324 /* XXX: test storage specifiers ? */
9325 sym = sym_push(v, &type, 0, 0);
9326 sym->type.t |= VT_TYPEDEF;
9327 } else if ((type.t & VT_BTYPE) == VT_FUNC) {
9328 /* external function definition */
9329 /* specific case for func_call attribute */
9330 if (ad.func_call)
9331 type.ref->r = ad.func_call;
9332 external_sym(v, &type, 0);
9333 } else {
9334 /* not lvalue if array */
9335 r = 0;
9336 if (!(type.t & VT_ARRAY))
9337 r |= lvalue_type(type.t);
9338 has_init = (tok == '=');
9339 if ((btype.t & VT_EXTERN) ||
9340 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
9341 !has_init && l == VT_CONST && type.ref->c < 0)) {
9342 /* external variable */
9343 /* NOTE: as GCC, uninitialized global static
9344 arrays of null size are considered as
9345 extern */
9346 external_sym(v, &type, r);
9347 } else {
9348 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
9349 if (type.t & VT_STATIC)
9350 r |= VT_CONST;
9351 else
9352 r |= l;
9353 if (has_init)
9354 next();
9355 decl_initializer_alloc(&type, &ad, r,
9356 has_init, v, l);
9359 if (tok != ',') {
9360 skip(';');
9361 break;
9363 next();
9369 /* better than nothing, but needs extension to handle '-E' option
9370 correctly too */
9371 static void preprocess_init(TCCState *s1)
9373 s1->include_stack_ptr = s1->include_stack;
9374 /* XXX: move that before to avoid having to initialize
9375 file->ifdef_stack_ptr ? */
9376 s1->ifdef_stack_ptr = s1->ifdef_stack;
9377 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
9379 /* XXX: not ANSI compliant: bound checking says error */
9380 vtop = vstack - 1;
9381 s1->pack_stack[0] = 0;
9382 s1->pack_stack_ptr = s1->pack_stack;
9385 /* compile the C file opened in 'file'. Return non zero if errors. */
9386 static int tcc_compile(TCCState *s1)
9388 Sym *define_start;
9389 char buf[512];
9390 volatile int section_sym;
9392 #ifdef INC_DEBUG
9393 printf("%s: **** new file\n", file->filename);
9394 #endif
9395 preprocess_init(s1);
9397 funcname = "";
9398 anon_sym = SYM_FIRST_ANOM;
9400 /* file info: full path + filename */
9401 section_sym = 0; /* avoid warning */
9402 if (do_debug) {
9403 section_sym = put_elf_sym(symtab_section, 0, 0,
9404 ELF32_ST_INFO(STB_LOCAL, STT_SECTION), 0,
9405 text_section->sh_num, NULL);
9406 getcwd(buf, sizeof(buf));
9407 #ifdef _WIN32
9408 normalize_slashes(buf);
9409 #endif
9410 pstrcat(buf, sizeof(buf), "/");
9411 put_stabs_r(buf, N_SO, 0, 0,
9412 text_section->data_offset, text_section, section_sym);
9413 put_stabs_r(file->filename, N_SO, 0, 0,
9414 text_section->data_offset, text_section, section_sym);
9416 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
9417 symbols can be safely used */
9418 put_elf_sym(symtab_section, 0, 0,
9419 ELF32_ST_INFO(STB_LOCAL, STT_FILE), 0,
9420 SHN_ABS, file->filename);
9422 /* define some often used types */
9423 int_type.t = VT_INT;
9425 char_pointer_type.t = VT_BYTE;
9426 mk_pointer(&char_pointer_type);
9428 func_old_type.t = VT_FUNC;
9429 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
9431 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
9432 float_type.t = VT_FLOAT;
9433 double_type.t = VT_DOUBLE;
9435 func_float_type.t = VT_FUNC;
9436 func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
9437 func_double_type.t = VT_FUNC;
9438 func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
9439 #endif
9441 #if 0
9442 /* define 'void *alloca(unsigned int)' builtin function */
9444 Sym *s1;
9446 p = anon_sym++;
9447 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
9448 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
9449 s1->next = NULL;
9450 sym->next = s1;
9451 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
9453 #endif
9455 define_start = define_stack;
9456 nocode_wanted = 1;
9458 if (setjmp(s1->error_jmp_buf) == 0) {
9459 s1->nb_errors = 0;
9460 s1->error_set_jmp_enabled = 1;
9462 ch = file->buf_ptr[0];
9463 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
9464 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
9465 next();
9466 decl(VT_CONST);
9467 if (tok != TOK_EOF)
9468 expect("declaration");
9470 /* end of translation unit info */
9471 if (do_debug) {
9472 put_stabs_r(NULL, N_SO, 0, 0,
9473 text_section->data_offset, text_section, section_sym);
9476 s1->error_set_jmp_enabled = 0;
9478 /* reset define stack, but leave -Dsymbols (may be incorrect if
9479 they are undefined) */
9480 free_defines(define_start);
9482 gen_inline_functions();
9484 sym_pop(&global_stack, NULL);
9486 return s1->nb_errors != 0 ? -1 : 0;
9489 /* Preprocess the current file */
9490 /* XXX: add line and file infos, add options to preserve spaces */
9491 static int tcc_preprocess(TCCState *s1)
9493 Sym *define_start;
9494 int last_is_space;
9496 preprocess_init(s1);
9498 define_start = define_stack;
9500 ch = file->buf_ptr[0];
9501 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
9502 parse_flags = PARSE_FLAG_ASM_COMMENTS | PARSE_FLAG_PREPROCESS |
9503 PARSE_FLAG_LINEFEED;
9504 last_is_space = 1;
9505 next();
9506 for(;;) {
9507 if (tok == TOK_EOF) {
9508 break;
9509 } else if (tok == TOK_LINEFEED) {
9510 last_is_space = 1;
9511 } else {
9512 if (!last_is_space)
9513 fputc(' ', s1->outfile);
9514 last_is_space = 0;
9516 fputs(get_tok_str(tok, &tokc), s1->outfile);
9517 next();
9519 free_defines(define_start);
9520 return 0;
9523 #ifdef LIBTCC
9524 int tcc_compile_string(TCCState *s, const char *str)
9526 BufferedFile bf1, *bf = &bf1;
9527 int ret, len;
9528 char *buf;
9530 /* init file structure */
9531 bf->fd = -1;
9532 /* XXX: avoid copying */
9533 len = strlen(str);
9534 buf = tcc_malloc(len + 1);
9535 if (!buf)
9536 return -1;
9537 memcpy(buf, str, len);
9538 buf[len] = CH_EOB;
9539 bf->buf_ptr = buf;
9540 bf->buf_end = buf + len;
9541 pstrcpy(bf->filename, sizeof(bf->filename), "<string>");
9542 bf->line_num = 1;
9543 file = bf;
9545 ret = tcc_compile(s);
9547 tcc_free(buf);
9549 /* currently, no need to close */
9550 return ret;
9552 #endif
9554 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9555 void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
9557 BufferedFile bf1, *bf = &bf1;
9559 pstrcpy(bf->buffer, IO_BUF_SIZE, sym);
9560 pstrcat(bf->buffer, IO_BUF_SIZE, " ");
9561 /* default value */
9562 if (!value)
9563 value = "1";
9564 pstrcat(bf->buffer, IO_BUF_SIZE, value);
9566 /* init file structure */
9567 bf->fd = -1;
9568 bf->buf_ptr = bf->buffer;
9569 bf->buf_end = bf->buffer + strlen(bf->buffer);
9570 *bf->buf_end = CH_EOB;
9571 bf->filename[0] = '\0';
9572 bf->line_num = 1;
9573 file = bf;
9575 s1->include_stack_ptr = s1->include_stack;
9577 /* parse with define parser */
9578 ch = file->buf_ptr[0];
9579 next_nomacro();
9580 parse_define();
9581 file = NULL;
9584 /* undefine a preprocessor symbol */
9585 void tcc_undefine_symbol(TCCState *s1, const char *sym)
9587 TokenSym *ts;
9588 Sym *s;
9589 ts = tok_alloc(sym, strlen(sym));
9590 s = define_find(ts->tok);
9591 /* undefine symbol by putting an invalid name */
9592 if (s)
9593 define_undef(s);
9596 #ifdef CONFIG_TCC_ASM
9598 #ifdef TCC_TARGET_I386
9599 #include "i386-asm.c"
9600 #endif
9601 #include "tccasm.c"
9603 #else
9604 static void asm_instr(void)
9606 error("inline asm() not supported");
9608 static void asm_global_instr(void)
9610 error("inline asm() not supported");
9612 #endif
9614 #include "tccelf.c"
9616 #ifdef TCC_TARGET_COFF
9617 #include "tcccoff.c"
9618 #endif
9620 #ifdef TCC_TARGET_PE
9621 #include "tccpe.c"
9622 #endif
9624 /* print the position in the source file of PC value 'pc' by reading
9625 the stabs debug information */
9626 static void rt_printline(unsigned long wanted_pc)
9628 Stab_Sym *sym, *sym_end;
9629 char func_name[128], last_func_name[128];
9630 unsigned long func_addr, last_pc, pc;
9631 const char *incl_files[INCLUDE_STACK_SIZE];
9632 int incl_index, len, last_line_num, i;
9633 const char *str, *p;
9635 fprintf(stderr, "0x%08lx:", wanted_pc);
9637 func_name[0] = '\0';
9638 func_addr = 0;
9639 incl_index = 0;
9640 last_func_name[0] = '\0';
9641 last_pc = 0xffffffff;
9642 last_line_num = 1;
9643 sym = (Stab_Sym *)stab_section->data + 1;
9644 sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
9645 while (sym < sym_end) {
9646 switch(sym->n_type) {
9647 /* function start or end */
9648 case N_FUN:
9649 if (sym->n_strx == 0) {
9650 /* we test if between last line and end of function */
9651 pc = sym->n_value + func_addr;
9652 if (wanted_pc >= last_pc && wanted_pc < pc)
9653 goto found;
9654 func_name[0] = '\0';
9655 func_addr = 0;
9656 } else {
9657 str = stabstr_section->data + sym->n_strx;
9658 p = strchr(str, ':');
9659 if (!p) {
9660 pstrcpy(func_name, sizeof(func_name), str);
9661 } else {
9662 len = p - str;
9663 if (len > sizeof(func_name) - 1)
9664 len = sizeof(func_name) - 1;
9665 memcpy(func_name, str, len);
9666 func_name[len] = '\0';
9668 func_addr = sym->n_value;
9670 break;
9671 /* line number info */
9672 case N_SLINE:
9673 pc = sym->n_value + func_addr;
9674 if (wanted_pc >= last_pc && wanted_pc < pc)
9675 goto found;
9676 last_pc = pc;
9677 last_line_num = sym->n_desc;
9678 /* XXX: slow! */
9679 strcpy(last_func_name, func_name);
9680 break;
9681 /* include files */
9682 case N_BINCL:
9683 str = stabstr_section->data + sym->n_strx;
9684 add_incl:
9685 if (incl_index < INCLUDE_STACK_SIZE) {
9686 incl_files[incl_index++] = str;
9688 break;
9689 case N_EINCL:
9690 if (incl_index > 1)
9691 incl_index--;
9692 break;
9693 case N_SO:
9694 if (sym->n_strx == 0) {
9695 incl_index = 0; /* end of translation unit */
9696 } else {
9697 str = stabstr_section->data + sym->n_strx;
9698 /* do not add path */
9699 len = strlen(str);
9700 if (len > 0 && str[len - 1] != '/')
9701 goto add_incl;
9703 break;
9705 sym++;
9708 /* second pass: we try symtab symbols (no line number info) */
9709 incl_index = 0;
9711 Elf32_Sym *sym, *sym_end;
9712 int type;
9714 sym_end = (Elf32_Sym *)(symtab_section->data + symtab_section->data_offset);
9715 for(sym = (Elf32_Sym *)symtab_section->data + 1;
9716 sym < sym_end;
9717 sym++) {
9718 type = ELF32_ST_TYPE(sym->st_info);
9719 if (type == STT_FUNC) {
9720 if (wanted_pc >= sym->st_value &&
9721 wanted_pc < sym->st_value + sym->st_size) {
9722 pstrcpy(last_func_name, sizeof(last_func_name),
9723 strtab_section->data + sym->st_name);
9724 goto found;
9729 /* did not find any info: */
9730 fprintf(stderr, " ???\n");
9731 return;
9732 found:
9733 if (last_func_name[0] != '\0') {
9734 fprintf(stderr, " %s()", last_func_name);
9736 if (incl_index > 0) {
9737 fprintf(stderr, " (%s:%d",
9738 incl_files[incl_index - 1], last_line_num);
9739 for(i = incl_index - 2; i >= 0; i--)
9740 fprintf(stderr, ", included from %s", incl_files[i]);
9741 fprintf(stderr, ")");
9743 fprintf(stderr, "\n");
9746 #if !defined(_WIN32) && !defined(CONFIG_TCCBOOT)
9748 #ifdef __i386__
9750 /* fix for glibc 2.1 */
9751 #ifndef REG_EIP
9752 #define REG_EIP EIP
9753 #define REG_EBP EBP
9754 #endif
9756 /* return the PC at frame level 'level'. Return non zero if not found */
9757 static int rt_get_caller_pc(unsigned long *paddr,
9758 ucontext_t *uc, int level)
9760 unsigned long fp;
9761 int i;
9763 if (level == 0) {
9764 #if defined(__FreeBSD__)
9765 *paddr = uc->uc_mcontext.mc_eip;
9766 #elif defined(__dietlibc__)
9767 *paddr = uc->uc_mcontext.eip;
9768 #else
9769 *paddr = uc->uc_mcontext.gregs[REG_EIP];
9770 #endif
9771 return 0;
9772 } else {
9773 #if defined(__FreeBSD__)
9774 fp = uc->uc_mcontext.mc_ebp;
9775 #elif defined(__dietlibc__)
9776 fp = uc->uc_mcontext.ebp;
9777 #else
9778 fp = uc->uc_mcontext.gregs[REG_EBP];
9779 #endif
9780 for(i=1;i<level;i++) {
9781 /* XXX: check address validity with program info */
9782 if (fp <= 0x1000 || fp >= 0xc0000000)
9783 return -1;
9784 fp = ((unsigned long *)fp)[0];
9786 *paddr = ((unsigned long *)fp)[1];
9787 return 0;
9790 #else
9792 #warning add arch specific rt_get_caller_pc()
9794 static int rt_get_caller_pc(unsigned long *paddr,
9795 ucontext_t *uc, int level)
9797 return -1;
9799 #endif
9801 /* emit a run time error at position 'pc' */
9802 void rt_error(ucontext_t *uc, const char *fmt, ...)
9804 va_list ap;
9805 unsigned long pc;
9806 int i;
9808 va_start(ap, fmt);
9809 fprintf(stderr, "Runtime error: ");
9810 vfprintf(stderr, fmt, ap);
9811 fprintf(stderr, "\n");
9812 for(i=0;i<num_callers;i++) {
9813 if (rt_get_caller_pc(&pc, uc, i) < 0)
9814 break;
9815 if (i == 0)
9816 fprintf(stderr, "at ");
9817 else
9818 fprintf(stderr, "by ");
9819 rt_printline(pc);
9821 exit(255);
9822 va_end(ap);
9825 /* signal handler for fatal errors */
9826 static void sig_error(int signum, siginfo_t *siginf, void *puc)
9828 ucontext_t *uc = puc;
9830 switch(signum) {
9831 case SIGFPE:
9832 switch(siginf->si_code) {
9833 case FPE_INTDIV:
9834 case FPE_FLTDIV:
9835 rt_error(uc, "division by zero");
9836 break;
9837 default:
9838 rt_error(uc, "floating point exception");
9839 break;
9841 break;
9842 case SIGBUS:
9843 case SIGSEGV:
9844 if (rt_bound_error_msg && *rt_bound_error_msg)
9845 rt_error(uc, *rt_bound_error_msg);
9846 else
9847 rt_error(uc, "dereferencing invalid pointer");
9848 break;
9849 case SIGILL:
9850 rt_error(uc, "illegal instruction");
9851 break;
9852 case SIGABRT:
9853 rt_error(uc, "abort() called");
9854 break;
9855 default:
9856 rt_error(uc, "caught signal %d", signum);
9857 break;
9859 exit(255);
9861 #endif
9863 /* do all relocations (needed before using tcc_get_symbol()) */
9864 int tcc_relocate(TCCState *s1)
9866 Section *s;
9867 int i;
9869 s1->nb_errors = 0;
9871 #ifdef TCC_TARGET_PE
9872 pe_add_runtime(s1);
9873 #else
9874 tcc_add_runtime(s1);
9875 #endif
9877 relocate_common_syms();
9879 tcc_add_linker_symbols(s1);
9881 build_got_entries(s1);
9883 /* compute relocation address : section are relocated in place. We
9884 also alloc the bss space */
9885 for(i = 1; i < s1->nb_sections; i++) {
9886 s = s1->sections[i];
9887 if (s->sh_flags & SHF_ALLOC) {
9888 if (s->sh_type == SHT_NOBITS)
9889 s->data = tcc_mallocz(s->data_offset);
9890 s->sh_addr = (unsigned long)s->data;
9894 relocate_syms(s1, 1);
9896 if (s1->nb_errors != 0)
9897 return -1;
9899 /* relocate each section */
9900 for(i = 1; i < s1->nb_sections; i++) {
9901 s = s1->sections[i];
9902 if (s->reloc)
9903 relocate_section(s1, s);
9906 /* mark executable sections as executable in memory */
9907 for(i = 1; i < s1->nb_sections; i++) {
9908 s = s1->sections[i];
9909 if ((s->sh_flags & (SHF_ALLOC | SHF_EXECINSTR)) ==
9910 (SHF_ALLOC | SHF_EXECINSTR))
9911 set_pages_executable(s->data, s->data_offset);
9913 return 0;
9916 /* launch the compiled program with the given arguments */
9917 int tcc_run(TCCState *s1, int argc, char **argv)
9919 int (*prog_main)(int, char **);
9921 if (tcc_relocate(s1) < 0)
9922 return -1;
9924 prog_main = tcc_get_symbol_err(s1, "main");
9926 if (do_debug) {
9927 #if defined(_WIN32) || defined(CONFIG_TCCBOOT)
9928 error("debug mode currently not available for Windows");
9929 #else
9930 struct sigaction sigact;
9931 /* install TCC signal handlers to print debug info on fatal
9932 runtime errors */
9933 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
9934 sigact.sa_sigaction = sig_error;
9935 sigemptyset(&sigact.sa_mask);
9936 sigaction(SIGFPE, &sigact, NULL);
9937 sigaction(SIGILL, &sigact, NULL);
9938 sigaction(SIGSEGV, &sigact, NULL);
9939 sigaction(SIGBUS, &sigact, NULL);
9940 sigaction(SIGABRT, &sigact, NULL);
9941 #endif
9944 #ifdef CONFIG_TCC_BCHECK
9945 if (do_bounds_check) {
9946 void (*bound_init)(void);
9948 /* set error function */
9949 rt_bound_error_msg = (void *)tcc_get_symbol_err(s1,
9950 "__bound_error_msg");
9952 /* XXX: use .init section so that it also work in binary ? */
9953 bound_init = (void *)tcc_get_symbol_err(s1, "__bound_init");
9954 bound_init();
9956 #endif
9957 return (*prog_main)(argc, argv);
9960 TCCState *tcc_new(void)
9962 const char *p, *r;
9963 TCCState *s;
9964 TokenSym *ts;
9965 int i, c;
9967 s = tcc_mallocz(sizeof(TCCState));
9968 if (!s)
9969 return NULL;
9970 tcc_state = s;
9971 s->output_type = TCC_OUTPUT_MEMORY;
9973 /* init isid table */
9974 for(i=0;i<256;i++)
9975 isidnum_table[i] = isid(i) || isnum(i);
9977 /* add all tokens */
9978 table_ident = NULL;
9979 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
9981 tok_ident = TOK_IDENT;
9982 p = tcc_keywords;
9983 while (*p) {
9984 r = p;
9985 for(;;) {
9986 c = *r++;
9987 if (c == '\0')
9988 break;
9990 ts = tok_alloc(p, r - p - 1);
9991 p = r;
9994 /* we add dummy defines for some special macros to speed up tests
9995 and to have working defined() */
9996 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
9997 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
9998 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
9999 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
10001 /* standard defines */
10002 tcc_define_symbol(s, "__STDC__", NULL);
10003 #if defined(TCC_TARGET_I386)
10004 tcc_define_symbol(s, "__i386__", NULL);
10005 #endif
10006 #if defined(TCC_TARGET_ARM)
10007 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
10008 tcc_define_symbol(s, "__arm_elf__", NULL);
10009 tcc_define_symbol(s, "__arm_elf", NULL);
10010 tcc_define_symbol(s, "arm_elf", NULL);
10011 tcc_define_symbol(s, "__arm__", NULL);
10012 tcc_define_symbol(s, "__arm", NULL);
10013 tcc_define_symbol(s, "arm", NULL);
10014 tcc_define_symbol(s, "__APCS_32__", NULL);
10015 #endif
10016 #if defined(linux)
10017 tcc_define_symbol(s, "__linux__", NULL);
10018 tcc_define_symbol(s, "linux", NULL);
10019 #endif
10020 /* tiny C specific defines */
10021 tcc_define_symbol(s, "__TINYC__", NULL);
10023 /* tiny C & gcc defines */
10024 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned int");
10025 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "int");
10026 #ifdef TCC_TARGET_PE
10027 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
10028 tcc_define_symbol(s, "_WIN32", NULL);
10029 #else
10030 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
10031 #endif
10033 /* default library paths */
10034 #ifdef TCC_TARGET_PE
10036 char buf[1024];
10037 snprintf(buf, sizeof(buf), "%s/lib", tcc_lib_path);
10038 tcc_add_library_path(s, buf);
10040 #else
10041 tcc_add_library_path(s, "/usr/local/lib");
10042 tcc_add_library_path(s, "/usr/lib");
10043 tcc_add_library_path(s, "/lib");
10044 #endif
10046 /* no section zero */
10047 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
10049 /* create standard sections */
10050 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
10051 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
10052 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
10054 /* symbols are always generated for linking stage */
10055 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
10056 ".strtab",
10057 ".hashtab", SHF_PRIVATE);
10058 strtab_section = symtab_section->link;
10060 /* private symbol table for dynamic symbols */
10061 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
10062 ".dynstrtab",
10063 ".dynhashtab", SHF_PRIVATE);
10064 s->alacarte_link = 1;
10066 #ifdef CHAR_IS_UNSIGNED
10067 s->char_is_unsigned = 1;
10068 #endif
10069 #if defined(TCC_TARGET_PE) && 0
10070 /* XXX: currently the PE linker is not ready to support that */
10071 s->leading_underscore = 1;
10072 #endif
10073 return s;
10076 void tcc_delete(TCCState *s1)
10078 int i, n;
10080 /* free -D defines */
10081 free_defines(NULL);
10083 /* free tokens */
10084 n = tok_ident - TOK_IDENT;
10085 for(i = 0; i < n; i++)
10086 tcc_free(table_ident[i]);
10087 tcc_free(table_ident);
10089 /* free all sections */
10091 free_section(symtab_section->hash);
10093 free_section(s1->dynsymtab_section->hash);
10094 free_section(s1->dynsymtab_section->link);
10095 free_section(s1->dynsymtab_section);
10097 for(i = 1; i < s1->nb_sections; i++)
10098 free_section(s1->sections[i]);
10099 tcc_free(s1->sections);
10101 /* free loaded dlls array */
10102 for(i = 0; i < s1->nb_loaded_dlls; i++)
10103 tcc_free(s1->loaded_dlls[i]);
10104 tcc_free(s1->loaded_dlls);
10106 /* library paths */
10107 for(i = 0; i < s1->nb_library_paths; i++)
10108 tcc_free(s1->library_paths[i]);
10109 tcc_free(s1->library_paths);
10111 /* cached includes */
10112 for(i = 0; i < s1->nb_cached_includes; i++)
10113 tcc_free(s1->cached_includes[i]);
10114 tcc_free(s1->cached_includes);
10116 for(i = 0; i < s1->nb_include_paths; i++)
10117 tcc_free(s1->include_paths[i]);
10118 tcc_free(s1->include_paths);
10120 for(i = 0; i < s1->nb_sysinclude_paths; i++)
10121 tcc_free(s1->sysinclude_paths[i]);
10122 tcc_free(s1->sysinclude_paths);
10124 tcc_free(s1);
10127 int tcc_add_include_path(TCCState *s1, const char *pathname)
10129 char *pathname1;
10131 pathname1 = tcc_strdup(pathname);
10132 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
10133 return 0;
10136 int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
10138 char *pathname1;
10140 pathname1 = tcc_strdup(pathname);
10141 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
10142 return 0;
10145 static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
10147 const char *ext, *filename1;
10148 Elf32_Ehdr ehdr;
10149 int fd, ret;
10150 BufferedFile *saved_file;
10152 /* find source file type with extension */
10153 filename1 = strrchr(filename, '/');
10154 if (filename1)
10155 filename1++;
10156 else
10157 filename1 = filename;
10158 ext = strrchr(filename1, '.');
10159 if (ext)
10160 ext++;
10162 /* open the file */
10163 saved_file = file;
10164 file = tcc_open(s1, filename);
10165 if (!file) {
10166 if (flags & AFF_PRINT_ERROR) {
10167 error_noabort("file '%s' not found", filename);
10169 ret = -1;
10170 goto fail1;
10173 if (flags & AFF_PREPROCESS) {
10174 ret = tcc_preprocess(s1);
10175 } else if (!ext || !strcmp(ext, "c")) {
10176 /* C file assumed */
10177 ret = tcc_compile(s1);
10178 } else
10179 #ifdef CONFIG_TCC_ASM
10180 if (!strcmp(ext, "S")) {
10181 /* preprocessed assembler */
10182 ret = tcc_assemble(s1, 1);
10183 } else if (!strcmp(ext, "s")) {
10184 /* non preprocessed assembler */
10185 ret = tcc_assemble(s1, 0);
10186 } else
10187 #endif
10188 #ifdef TCC_TARGET_PE
10189 if (!strcmp(ext, "def")) {
10190 ret = pe_load_def_file(s1, fdopen(file->fd, "rb"));
10191 } else
10192 #endif
10194 fd = file->fd;
10195 /* assume executable format: auto guess file type */
10196 ret = read(fd, &ehdr, sizeof(ehdr));
10197 lseek(fd, 0, SEEK_SET);
10198 if (ret <= 0) {
10199 error_noabort("could not read header");
10200 goto fail;
10201 } else if (ret != sizeof(ehdr)) {
10202 goto try_load_script;
10205 if (ehdr.e_ident[0] == ELFMAG0 &&
10206 ehdr.e_ident[1] == ELFMAG1 &&
10207 ehdr.e_ident[2] == ELFMAG2 &&
10208 ehdr.e_ident[3] == ELFMAG3) {
10209 file->line_num = 0; /* do not display line number if error */
10210 if (ehdr.e_type == ET_REL) {
10211 ret = tcc_load_object_file(s1, fd, 0);
10212 } else if (ehdr.e_type == ET_DYN) {
10213 if (s1->output_type == TCC_OUTPUT_MEMORY) {
10214 #ifdef TCC_TARGET_PE
10215 ret = -1;
10216 #else
10217 void *h;
10218 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
10219 if (h)
10220 ret = 0;
10221 else
10222 ret = -1;
10223 #endif
10224 } else {
10225 ret = tcc_load_dll(s1, fd, filename,
10226 (flags & AFF_REFERENCED_DLL) != 0);
10228 } else {
10229 error_noabort("unrecognized ELF file");
10230 goto fail;
10232 } else if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
10233 file->line_num = 0; /* do not display line number if error */
10234 ret = tcc_load_archive(s1, fd);
10235 } else
10236 #ifdef TCC_TARGET_COFF
10237 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
10238 ret = tcc_load_coff(s1, fd);
10239 } else
10240 #endif
10242 /* as GNU ld, consider it is an ld script if not recognized */
10243 try_load_script:
10244 ret = tcc_load_ldscript(s1);
10245 if (ret < 0) {
10246 error_noabort("unrecognized file type");
10247 goto fail;
10251 the_end:
10252 tcc_close(file);
10253 fail1:
10254 file = saved_file;
10255 return ret;
10256 fail:
10257 ret = -1;
10258 goto the_end;
10261 int tcc_add_file(TCCState *s, const char *filename)
10263 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
10266 int tcc_add_library_path(TCCState *s, const char *pathname)
10268 char *pathname1;
10270 pathname1 = tcc_strdup(pathname);
10271 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
10272 return 0;
10275 /* find and load a dll. Return non zero if not found */
10276 /* XXX: add '-rpath' option support ? */
10277 static int tcc_add_dll(TCCState *s, const char *filename, int flags)
10279 char buf[1024];
10280 int i;
10282 for(i = 0; i < s->nb_library_paths; i++) {
10283 snprintf(buf, sizeof(buf), "%s/%s",
10284 s->library_paths[i], filename);
10285 if (tcc_add_file_internal(s, buf, flags) == 0)
10286 return 0;
10288 return -1;
10291 /* the library name is the same as the argument of the '-l' option */
10292 int tcc_add_library(TCCState *s, const char *libraryname)
10294 char buf[1024];
10295 int i;
10297 /* first we look for the dynamic library if not static linking */
10298 if (!s->static_link) {
10299 #ifdef TCC_TARGET_PE
10300 snprintf(buf, sizeof(buf), "%s.def", libraryname);
10301 #else
10302 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
10303 #endif
10304 if (tcc_add_dll(s, buf, 0) == 0)
10305 return 0;
10308 /* then we look for the static library */
10309 for(i = 0; i < s->nb_library_paths; i++) {
10310 snprintf(buf, sizeof(buf), "%s/lib%s.a",
10311 s->library_paths[i], libraryname);
10312 if (tcc_add_file_internal(s, buf, 0) == 0)
10313 return 0;
10315 return -1;
10318 int tcc_add_symbol(TCCState *s, const char *name, unsigned long val)
10320 add_elf_sym(symtab_section, val, 0,
10321 ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
10322 SHN_ABS, name);
10323 return 0;
10326 int tcc_set_output_type(TCCState *s, int output_type)
10328 s->output_type = output_type;
10330 if (!s->nostdinc) {
10331 char buf[1024];
10333 /* default include paths */
10334 /* XXX: reverse order needed if -isystem support */
10335 #ifndef TCC_TARGET_PE
10336 tcc_add_sysinclude_path(s, "/usr/local/include");
10337 tcc_add_sysinclude_path(s, "/usr/include");
10338 #endif
10339 snprintf(buf, sizeof(buf), "%s/include", tcc_lib_path);
10340 tcc_add_sysinclude_path(s, buf);
10341 #ifdef TCC_TARGET_PE
10342 snprintf(buf, sizeof(buf), "%s/include/winapi", tcc_lib_path);
10343 tcc_add_sysinclude_path(s, buf);
10344 #endif
10347 /* if bound checking, then add corresponding sections */
10348 #ifdef CONFIG_TCC_BCHECK
10349 if (do_bounds_check) {
10350 /* define symbol */
10351 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
10352 /* create bounds sections */
10353 bounds_section = new_section(s, ".bounds",
10354 SHT_PROGBITS, SHF_ALLOC);
10355 lbounds_section = new_section(s, ".lbounds",
10356 SHT_PROGBITS, SHF_ALLOC);
10358 #endif
10360 if (s->char_is_unsigned) {
10361 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
10364 /* add debug sections */
10365 if (do_debug) {
10366 /* stab symbols */
10367 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
10368 stab_section->sh_entsize = sizeof(Stab_Sym);
10369 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
10370 put_elf_str(stabstr_section, "");
10371 stab_section->link = stabstr_section;
10372 /* put first entry */
10373 put_stabs("", 0, 0, 0, 0);
10376 /* add libc crt1/crti objects */
10377 #ifndef TCC_TARGET_PE
10378 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
10379 !s->nostdlib) {
10380 if (output_type != TCC_OUTPUT_DLL)
10381 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
10382 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
10384 #endif
10385 return 0;
10388 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
10389 #define FD_INVERT 0x0002 /* invert value before storing */
10391 typedef struct FlagDef {
10392 uint16_t offset;
10393 uint16_t flags;
10394 const char *name;
10395 } FlagDef;
10397 static const FlagDef warning_defs[] = {
10398 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
10399 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
10400 { offsetof(TCCState, warn_error), 0, "error" },
10401 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
10402 "implicit-function-declaration" },
10405 static int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
10406 const char *name, int value)
10408 int i;
10409 const FlagDef *p;
10410 const char *r;
10412 r = name;
10413 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
10414 r += 3;
10415 value = !value;
10417 for(i = 0, p = flags; i < nb_flags; i++, p++) {
10418 if (!strcmp(r, p->name))
10419 goto found;
10421 return -1;
10422 found:
10423 if (p->flags & FD_INVERT)
10424 value = !value;
10425 *(int *)((uint8_t *)s + p->offset) = value;
10426 return 0;
10430 /* set/reset a warning */
10431 int tcc_set_warning(TCCState *s, const char *warning_name, int value)
10433 int i;
10434 const FlagDef *p;
10436 if (!strcmp(warning_name, "all")) {
10437 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
10438 if (p->flags & WD_ALL)
10439 *(int *)((uint8_t *)s + p->offset) = 1;
10441 return 0;
10442 } else {
10443 return set_flag(s, warning_defs, countof(warning_defs),
10444 warning_name, value);
10448 static const FlagDef flag_defs[] = {
10449 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
10450 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
10451 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
10452 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
10455 /* set/reset a flag */
10456 int tcc_set_flag(TCCState *s, const char *flag_name, int value)
10458 return set_flag(s, flag_defs, countof(flag_defs),
10459 flag_name, value);
10462 /* extract the basename of a file */
10463 static char *tcc_basename(const char *name)
10465 char *p = strchr(name, 0);
10466 while (p > name
10467 && p[-1] != '/'
10468 #ifdef _WIN32
10469 && p[-1] != '\\'
10470 #endif
10472 --p;
10473 return p;
10476 #if !defined(LIBTCC)
10478 static int64_t getclock_us(void)
10480 #ifdef _WIN32
10481 struct _timeb tb;
10482 _ftime(&tb);
10483 return (tb.time * 1000LL + tb.millitm) * 1000LL;
10484 #else
10485 struct timeval tv;
10486 gettimeofday(&tv, NULL);
10487 return tv.tv_sec * 1000000LL + tv.tv_usec;
10488 #endif
10491 void help(void)
10493 printf("tcc version " TCC_VERSION " - Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard\n"
10494 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
10495 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]\n"
10496 " [infile1 infile2...] [-run infile args...]\n"
10497 "\n"
10498 "General options:\n"
10499 " -v display current version\n"
10500 " -c compile only - generate an object file\n"
10501 " -o outfile set output filename\n"
10502 " -Bdir set tcc internal library path\n"
10503 " -bench output compilation statistics\n"
10504 " -run run compiled source\n"
10505 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
10506 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
10507 " -w disable all warnings\n"
10508 "Preprocessor options:\n"
10509 " -E preprocess only\n"
10510 " -Idir add include path 'dir'\n"
10511 " -Dsym[=val] define 'sym' with value 'val'\n"
10512 " -Usym undefine 'sym'\n"
10513 "Linker options:\n"
10514 " -Ldir add library path 'dir'\n"
10515 " -llib link with dynamic or static library 'lib'\n"
10516 " -shared generate a shared library\n"
10517 " -static static linking\n"
10518 " -rdynamic export all global symbols to dynamic linker\n"
10519 " -r relocatable output\n"
10520 "Debugger options:\n"
10521 " -g generate runtime debug info\n"
10522 #ifdef CONFIG_TCC_BCHECK
10523 " -b compile with built-in memory and bounds checker (implies -g)\n"
10524 #endif
10525 " -bt N show N callers in stack traces\n"
10529 #define TCC_OPTION_HAS_ARG 0x0001
10530 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
10532 typedef struct TCCOption {
10533 const char *name;
10534 uint16_t index;
10535 uint16_t flags;
10536 } TCCOption;
10538 enum {
10539 TCC_OPTION_HELP,
10540 TCC_OPTION_I,
10541 TCC_OPTION_D,
10542 TCC_OPTION_U,
10543 TCC_OPTION_L,
10544 TCC_OPTION_B,
10545 TCC_OPTION_l,
10546 TCC_OPTION_bench,
10547 TCC_OPTION_bt,
10548 TCC_OPTION_b,
10549 TCC_OPTION_g,
10550 TCC_OPTION_c,
10551 TCC_OPTION_static,
10552 TCC_OPTION_shared,
10553 TCC_OPTION_o,
10554 TCC_OPTION_r,
10555 TCC_OPTION_Wl,
10556 TCC_OPTION_W,
10557 TCC_OPTION_O,
10558 TCC_OPTION_m,
10559 TCC_OPTION_f,
10560 TCC_OPTION_nostdinc,
10561 TCC_OPTION_nostdlib,
10562 TCC_OPTION_print_search_dirs,
10563 TCC_OPTION_rdynamic,
10564 TCC_OPTION_run,
10565 TCC_OPTION_v,
10566 TCC_OPTION_w,
10567 TCC_OPTION_pipe,
10568 TCC_OPTION_E,
10571 static const TCCOption tcc_options[] = {
10572 { "h", TCC_OPTION_HELP, 0 },
10573 { "?", TCC_OPTION_HELP, 0 },
10574 { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
10575 { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
10576 { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
10577 { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
10578 { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
10579 { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
10580 { "bench", TCC_OPTION_bench, 0 },
10581 { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG },
10582 #ifdef CONFIG_TCC_BCHECK
10583 { "b", TCC_OPTION_b, 0 },
10584 #endif
10585 { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
10586 { "c", TCC_OPTION_c, 0 },
10587 { "static", TCC_OPTION_static, 0 },
10588 { "shared", TCC_OPTION_shared, 0 },
10589 { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
10590 { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
10591 { "rdynamic", TCC_OPTION_rdynamic, 0 },
10592 { "r", TCC_OPTION_r, 0 },
10593 { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
10594 { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
10595 { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
10596 { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG },
10597 { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
10598 { "nostdinc", TCC_OPTION_nostdinc, 0 },
10599 { "nostdlib", TCC_OPTION_nostdlib, 0 },
10600 { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
10601 { "v", TCC_OPTION_v, 0 },
10602 { "w", TCC_OPTION_w, 0 },
10603 { "pipe", TCC_OPTION_pipe, 0},
10604 { "E", TCC_OPTION_E, 0},
10605 { NULL },
10608 /* convert 'str' into an array of space separated strings */
10609 static int expand_args(char ***pargv, const char *str)
10611 const char *s1;
10612 char **argv, *arg;
10613 int argc, len;
10615 argc = 0;
10616 argv = NULL;
10617 for(;;) {
10618 while (is_space(*str))
10619 str++;
10620 if (*str == '\0')
10621 break;
10622 s1 = str;
10623 while (*str != '\0' && !is_space(*str))
10624 str++;
10625 len = str - s1;
10626 arg = tcc_malloc(len + 1);
10627 memcpy(arg, s1, len);
10628 arg[len] = '\0';
10629 dynarray_add((void ***)&argv, &argc, arg);
10631 *pargv = argv;
10632 return argc;
10635 static char **files;
10636 static int nb_files, nb_libraries;
10637 static int multiple_files;
10638 static int print_search_dirs;
10639 static int output_type;
10640 static int reloc_output;
10641 static const char *outfile;
10643 int parse_args(TCCState *s, int argc, char **argv)
10645 int optind;
10646 const TCCOption *popt;
10647 const char *optarg, *p1, *r1;
10648 char *r;
10650 optind = 0;
10651 while (1) {
10652 if (optind >= argc) {
10653 if (nb_files == 0 && !print_search_dirs)
10654 goto show_help;
10655 else
10656 break;
10658 r = argv[optind++];
10659 if (r[0] != '-') {
10660 /* add a new file */
10661 dynarray_add((void ***)&files, &nb_files, r);
10662 if (!multiple_files) {
10663 optind--;
10664 /* argv[0] will be this file */
10665 break;
10667 } else {
10668 /* find option in table (match only the first chars */
10669 popt = tcc_options;
10670 for(;;) {
10671 p1 = popt->name;
10672 if (p1 == NULL)
10673 error("invalid option -- '%s'", r);
10674 r1 = r + 1;
10675 for(;;) {
10676 if (*p1 == '\0')
10677 goto option_found;
10678 if (*r1 != *p1)
10679 break;
10680 p1++;
10681 r1++;
10683 popt++;
10685 option_found:
10686 if (popt->flags & TCC_OPTION_HAS_ARG) {
10687 if (*r1 != '\0' || (popt->flags & TCC_OPTION_NOSEP)) {
10688 optarg = r1;
10689 } else {
10690 if (optind >= argc)
10691 error("argument to '%s' is missing", r);
10692 optarg = argv[optind++];
10694 } else {
10695 if (*r1 != '\0')
10696 goto show_help;
10697 optarg = NULL;
10700 switch(popt->index) {
10701 case TCC_OPTION_HELP:
10702 show_help:
10703 help();
10704 exit(1);
10705 case TCC_OPTION_I:
10706 if (tcc_add_include_path(s, optarg) < 0)
10707 error("too many include paths");
10708 break;
10709 case TCC_OPTION_D:
10711 char *sym, *value;
10712 sym = (char *)optarg;
10713 value = strchr(sym, '=');
10714 if (value) {
10715 *value = '\0';
10716 value++;
10718 tcc_define_symbol(s, sym, value);
10720 break;
10721 case TCC_OPTION_U:
10722 tcc_undefine_symbol(s, optarg);
10723 break;
10724 case TCC_OPTION_L:
10725 tcc_add_library_path(s, optarg);
10726 break;
10727 case TCC_OPTION_B:
10728 /* set tcc utilities path (mainly for tcc development) */
10729 tcc_lib_path = optarg;
10730 break;
10731 case TCC_OPTION_l:
10732 dynarray_add((void ***)&files, &nb_files, r);
10733 nb_libraries++;
10734 break;
10735 case TCC_OPTION_bench:
10736 do_bench = 1;
10737 break;
10738 case TCC_OPTION_bt:
10739 num_callers = atoi(optarg);
10740 break;
10741 #ifdef CONFIG_TCC_BCHECK
10742 case TCC_OPTION_b:
10743 do_bounds_check = 1;
10744 do_debug = 1;
10745 break;
10746 #endif
10747 case TCC_OPTION_g:
10748 do_debug = 1;
10749 break;
10750 case TCC_OPTION_c:
10751 multiple_files = 1;
10752 output_type = TCC_OUTPUT_OBJ;
10753 break;
10754 case TCC_OPTION_static:
10755 s->static_link = 1;
10756 break;
10757 case TCC_OPTION_shared:
10758 output_type = TCC_OUTPUT_DLL;
10759 break;
10760 case TCC_OPTION_o:
10761 multiple_files = 1;
10762 outfile = optarg;
10763 break;
10764 case TCC_OPTION_r:
10765 /* generate a .o merging several output files */
10766 reloc_output = 1;
10767 output_type = TCC_OUTPUT_OBJ;
10768 break;
10769 case TCC_OPTION_nostdinc:
10770 s->nostdinc = 1;
10771 break;
10772 case TCC_OPTION_nostdlib:
10773 s->nostdlib = 1;
10774 break;
10775 case TCC_OPTION_print_search_dirs:
10776 print_search_dirs = 1;
10777 break;
10778 case TCC_OPTION_run:
10780 int argc1;
10781 char **argv1;
10782 argc1 = expand_args(&argv1, optarg);
10783 if (argc1 > 0) {
10784 parse_args(s, argc1, argv1);
10786 multiple_files = 0;
10787 output_type = TCC_OUTPUT_MEMORY;
10789 break;
10790 case TCC_OPTION_v:
10791 printf("tcc version %s\n", TCC_VERSION);
10792 exit(0);
10793 case TCC_OPTION_f:
10794 if (tcc_set_flag(s, optarg, 1) < 0 && s->warn_unsupported)
10795 goto unsupported_option;
10796 break;
10797 case TCC_OPTION_W:
10798 if (tcc_set_warning(s, optarg, 1) < 0 &&
10799 s->warn_unsupported)
10800 goto unsupported_option;
10801 break;
10802 case TCC_OPTION_w:
10803 s->warn_none = 1;
10804 break;
10805 case TCC_OPTION_rdynamic:
10806 s->rdynamic = 1;
10807 break;
10808 case TCC_OPTION_Wl:
10810 const char *p;
10811 if (strstart(optarg, "-Ttext,", &p)) {
10812 s->text_addr = strtoul(p, NULL, 16);
10813 s->has_text_addr = 1;
10814 } else if (strstart(optarg, "--oformat,", &p)) {
10815 if (strstart(p, "elf32-", NULL)) {
10816 s->output_format = TCC_OUTPUT_FORMAT_ELF;
10817 } else if (!strcmp(p, "binary")) {
10818 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
10819 } else
10820 #ifdef TCC_TARGET_COFF
10821 if (!strcmp(p, "coff")) {
10822 s->output_format = TCC_OUTPUT_FORMAT_COFF;
10823 } else
10824 #endif
10826 error("target %s not found", p);
10828 } else {
10829 error("unsupported linker option '%s'", optarg);
10832 break;
10833 case TCC_OPTION_E:
10834 output_type = TCC_OUTPUT_PREPROCESS;
10835 break;
10836 default:
10837 if (s->warn_unsupported) {
10838 unsupported_option:
10839 warning("unsupported option '%s'", r);
10841 break;
10845 return optind;
10848 int main(int argc, char **argv)
10850 int i;
10851 TCCState *s;
10852 int nb_objfiles, ret, optind;
10853 char objfilename[1024];
10854 int64_t start_time = 0;
10856 #ifdef _WIN32
10857 tcc_lib_path = w32_tcc_lib_path();
10858 #endif
10860 s = tcc_new();
10861 output_type = TCC_OUTPUT_EXE;
10862 outfile = NULL;
10863 multiple_files = 1;
10864 files = NULL;
10865 nb_files = 0;
10866 nb_libraries = 0;
10867 reloc_output = 0;
10868 print_search_dirs = 0;
10870 optind = parse_args(s, argc - 1, argv + 1) + 1;
10872 if (print_search_dirs) {
10873 /* enough for Linux kernel */
10874 printf("install: %s/\n", tcc_lib_path);
10875 return 0;
10878 nb_objfiles = nb_files - nb_libraries;
10880 /* if outfile provided without other options, we output an
10881 executable */
10882 if (outfile && output_type == TCC_OUTPUT_MEMORY)
10883 output_type = TCC_OUTPUT_EXE;
10885 /* check -c consistency : only single file handled. XXX: checks file type */
10886 if (output_type == TCC_OUTPUT_OBJ && !reloc_output) {
10887 /* accepts only a single input file */
10888 if (nb_objfiles != 1)
10889 error("cannot specify multiple files with -c");
10890 if (nb_libraries != 0)
10891 error("cannot specify libraries with -c");
10895 if (output_type == TCC_OUTPUT_PREPROCESS) {
10896 if (!outfile) {
10897 s->outfile = stdout;
10898 } else {
10899 s->outfile = fopen(outfile, "wb");
10900 if (!s->outfile)
10901 error("could not open '%s", outfile);
10903 } else if (output_type != TCC_OUTPUT_MEMORY) {
10904 if (!outfile) {
10905 /* compute default outfile name */
10906 pstrcpy(objfilename, sizeof(objfilename) - 1,
10907 /* strip path */
10908 tcc_basename(files[0]));
10909 #ifdef TCC_TARGET_PE
10910 pe_guess_outfile(objfilename, output_type);
10911 #else
10912 if (output_type == TCC_OUTPUT_OBJ && !reloc_output) {
10913 char *ext = strrchr(objfilename, '.');
10914 if (!ext)
10915 goto default_outfile;
10916 /* add .o extension */
10917 strcpy(ext + 1, "o");
10918 } else {
10919 default_outfile:
10920 pstrcpy(objfilename, sizeof(objfilename), "a.out");
10922 #endif
10923 outfile = objfilename;
10927 if (do_bench) {
10928 start_time = getclock_us();
10931 tcc_set_output_type(s, output_type);
10933 /* compile or add each files or library */
10934 for(i = 0;i < nb_files; i++) {
10935 const char *filename;
10937 filename = files[i];
10938 if (output_type == TCC_OUTPUT_PREPROCESS) {
10939 tcc_add_file_internal(s, filename,
10940 AFF_PRINT_ERROR | AFF_PREPROCESS);
10941 } else {
10942 if (filename[0] == '-') {
10943 if (tcc_add_library(s, filename + 2) < 0)
10944 error("cannot find %s", filename);
10945 } else {
10946 if (tcc_add_file(s, filename) < 0) {
10947 ret = 1;
10948 goto the_end;
10954 /* free all files */
10955 tcc_free(files);
10957 if (do_bench) {
10958 double total_time;
10959 total_time = (double)(getclock_us() - start_time) / 1000000.0;
10960 if (total_time < 0.001)
10961 total_time = 0.001;
10962 if (total_bytes < 1)
10963 total_bytes = 1;
10964 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
10965 tok_ident - TOK_IDENT, total_lines, total_bytes,
10966 total_time, (int)(total_lines / total_time),
10967 total_bytes / total_time / 1000000.0);
10970 if (s->output_type == TCC_OUTPUT_PREPROCESS) {
10971 if (outfile)
10972 fclose(s->outfile);
10973 ret = 0;
10974 } else if (s->output_type == TCC_OUTPUT_MEMORY) {
10975 ret = tcc_run(s, argc - optind, argv + optind);
10976 } else
10977 #ifdef TCC_TARGET_PE
10978 if (s->output_type != TCC_OUTPUT_OBJ) {
10979 ret = tcc_output_pe(s, outfile);
10980 } else
10981 #endif
10983 ret = tcc_output_file(s, outfile) ? 1 : 0;
10985 the_end:
10986 /* XXX: cannot do it with bound checking because of the malloc hooks */
10987 if (!do_bounds_check)
10988 tcc_delete(s);
10990 #ifdef MEM_DEBUG
10991 if (do_bench) {
10992 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size, mem_max_size);
10994 #endif
10995 return ret;
10998 #endif