Import some changesets from Rob Landley's fork (part 1)
[tinycc/miki.git] / tcc.c
blobd8a02308cc23db7a40dd3ed227ff3e738d23df38
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 */
325 static int *macro_ptr, *macro_ptr_allocated;
326 static int *unget_saved_macro_ptr;
327 static int unget_saved_buffer[TOK_MAX_SIZE + 1];
328 static int unget_buffer_enabled;
329 static int parse_flags;
330 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
331 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
332 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
333 token. line feed is also
334 returned at eof */
335 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
337 static Section *text_section, *data_section, *bss_section; /* predefined sections */
338 static Section *cur_text_section; /* current section where function code is
339 generated */
340 #ifdef CONFIG_TCC_ASM
341 static Section *last_text_section; /* to handle .previous asm directive */
342 #endif
343 /* bound check related sections */
344 static Section *bounds_section; /* contains global data bound description */
345 static Section *lbounds_section; /* contains local data bound description */
346 /* symbol sections */
347 static Section *symtab_section, *strtab_section;
349 /* debug sections */
350 static Section *stab_section, *stabstr_section;
352 /* loc : local variable index
353 ind : output code index
354 rsym: return symbol
355 anon_sym: anonymous symbol index
357 static int rsym, anon_sym, ind, loc;
358 /* expression generation modifiers */
359 static int const_wanted; /* true if constant wanted */
360 static int nocode_wanted; /* true if no code generation wanted for an expression */
361 static int global_expr; /* true if compound literals must be allocated
362 globally (used during initializers parsing */
363 static CType func_vt; /* current function return type (used by return
364 instruction) */
365 static int func_vc;
366 static int last_line_num, last_ind, func_ind; /* debug last line number and pc */
367 static int tok_ident;
368 static TokenSym **table_ident;
369 static TokenSym *hash_ident[TOK_HASH_SIZE];
370 static char token_buf[STRING_MAX_SIZE + 1];
371 static char *funcname;
372 static Sym *global_stack, *local_stack;
373 static Sym *define_stack;
374 static Sym *global_label_stack, *local_label_stack;
375 /* symbol allocator */
376 #define SYM_POOL_NB (8192 / sizeof(Sym))
377 static Sym *sym_free_first;
379 static SValue vstack[VSTACK_SIZE], *vtop;
380 /* some predefined types */
381 static CType char_pointer_type, func_old_type, int_type;
382 /* true if isid(c) || isnum(c) */
383 static unsigned char isidnum_table[256];
385 /* compile with debug symbol (and use them if error during execution) */
386 static int do_debug = 0;
388 /* compile with built-in memory and bounds checker */
389 static int do_bounds_check = 0;
391 /* display benchmark infos */
392 #if !defined(LIBTCC)
393 static int do_bench = 0;
394 #endif
395 static int total_lines;
396 static int total_bytes;
398 /* use GNU C extensions */
399 static int gnu_ext = 1;
401 /* use Tiny C extensions */
402 static int tcc_ext = 1;
404 /* max number of callers shown if error */
405 static int num_callers = 6;
406 static const char **rt_bound_error_msg;
408 /* XXX: get rid of this ASAP */
409 static struct TCCState *tcc_state;
411 /* give the path of the tcc libraries */
412 static const char *tcc_lib_path = CONFIG_TCCDIR;
414 struct TCCState {
415 int output_type;
417 BufferedFile **include_stack_ptr;
418 int *ifdef_stack_ptr;
420 /* include file handling */
421 char **include_paths;
422 int nb_include_paths;
423 char **sysinclude_paths;
424 int nb_sysinclude_paths;
425 CachedInclude **cached_includes;
426 int nb_cached_includes;
428 char **library_paths;
429 int nb_library_paths;
431 /* array of all loaded dlls (including those referenced by loaded
432 dlls) */
433 DLLReference **loaded_dlls;
434 int nb_loaded_dlls;
436 /* sections */
437 Section **sections;
438 int nb_sections; /* number of sections, including first dummy section */
440 /* got handling */
441 Section *got;
442 Section *plt;
443 unsigned long *got_offsets;
444 int nb_got_offsets;
445 /* give the correspondance from symtab indexes to dynsym indexes */
446 int *symtab_to_dynsym;
448 /* temporary dynamic symbol sections (for dll loading) */
449 Section *dynsymtab_section;
450 /* exported dynamic symbol section */
451 Section *dynsym;
453 int nostdinc; /* if true, no standard headers are added */
454 int nostdlib; /* if true, no standard libraries are added */
456 int nocommon; /* if true, do not use common symbols for .bss data */
458 /* if true, static linking is performed */
459 int static_link;
461 /* if true, all symbols are exported */
462 int rdynamic;
464 /* if true, only link in referenced objects from archive */
465 int alacarte_link;
467 /* address of text section */
468 unsigned long text_addr;
469 int has_text_addr;
471 /* output format, see TCC_OUTPUT_FORMAT_xxx */
472 int output_format;
474 /* C language options */
475 int char_is_unsigned;
476 int leading_underscore;
478 /* warning switches */
479 int warn_write_strings;
480 int warn_unsupported;
481 int warn_error;
482 int warn_none;
483 int warn_implicit_function_declaration;
485 /* error handling */
486 void *error_opaque;
487 void (*error_func)(void *opaque, const char *msg);
488 int error_set_jmp_enabled;
489 jmp_buf error_jmp_buf;
490 int nb_errors;
492 /* tiny assembler state */
493 Sym *asm_labels;
495 /* see include_stack_ptr */
496 BufferedFile *include_stack[INCLUDE_STACK_SIZE];
498 /* see ifdef_stack_ptr */
499 int ifdef_stack[IFDEF_STACK_SIZE];
501 /* see cached_includes */
502 int cached_includes_hash[CACHED_INCLUDES_HASH_SIZE];
504 /* pack stack */
505 int pack_stack[PACK_STACK_SIZE];
506 int *pack_stack_ptr;
508 /* output file for preprocessing */
509 FILE *outfile;
512 /* The current value can be: */
513 #define VT_VALMASK 0x00ff
514 #define VT_CONST 0x00f0 /* constant in vc
515 (must be first non register value) */
516 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
517 #define VT_LOCAL 0x00f2 /* offset on stack */
518 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
519 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
520 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
521 #define VT_LVAL 0x0100 /* var is an lvalue */
522 #define VT_SYM 0x0200 /* a symbol value is added */
523 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
524 char/short stored in integer registers) */
525 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
526 dereferencing value */
527 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
528 bounding function call point is in vc */
529 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
530 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
531 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
532 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
534 /* types */
535 #define VT_INT 0 /* integer type */
536 #define VT_BYTE 1 /* signed byte type */
537 #define VT_SHORT 2 /* short type */
538 #define VT_VOID 3 /* void type */
539 #define VT_PTR 4 /* pointer */
540 #define VT_ENUM 5 /* enum definition */
541 #define VT_FUNC 6 /* function type */
542 #define VT_STRUCT 7 /* struct/union definition */
543 #define VT_FLOAT 8 /* IEEE float */
544 #define VT_DOUBLE 9 /* IEEE double */
545 #define VT_LDOUBLE 10 /* IEEE long double */
546 #define VT_BOOL 11 /* ISOC99 boolean type */
547 #define VT_LLONG 12 /* 64 bit integer */
548 #define VT_LONG 13 /* long integer (NEVER USED as type, only
549 during parsing) */
550 #define VT_BTYPE 0x000f /* mask for basic type */
551 #define VT_UNSIGNED 0x0010 /* unsigned type */
552 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
553 #define VT_BITFIELD 0x0040 /* bitfield modifier */
554 #define VT_CONSTANT 0x0800 /* const modifier */
555 #define VT_VOLATILE 0x1000 /* volatile modifier */
556 #define VT_SIGNED 0x2000 /* signed type */
558 /* storage */
559 #define VT_EXTERN 0x00000080 /* extern definition */
560 #define VT_STATIC 0x00000100 /* static variable */
561 #define VT_TYPEDEF 0x00000200 /* typedef definition */
562 #define VT_INLINE 0x00000400 /* inline definition */
564 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
566 /* type mask (except storage) */
567 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
568 #define VT_TYPE (~(VT_STORAGE))
570 /* token values */
572 /* warning: the following compare tokens depend on i386 asm code */
573 #define TOK_ULT 0x92
574 #define TOK_UGE 0x93
575 #define TOK_EQ 0x94
576 #define TOK_NE 0x95
577 #define TOK_ULE 0x96
578 #define TOK_UGT 0x97
579 #define TOK_LT 0x9c
580 #define TOK_GE 0x9d
581 #define TOK_LE 0x9e
582 #define TOK_GT 0x9f
584 #define TOK_LAND 0xa0
585 #define TOK_LOR 0xa1
587 #define TOK_DEC 0xa2
588 #define TOK_MID 0xa3 /* inc/dec, to void constant */
589 #define TOK_INC 0xa4
590 #define TOK_UDIV 0xb0 /* unsigned division */
591 #define TOK_UMOD 0xb1 /* unsigned modulo */
592 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
593 #define TOK_CINT 0xb3 /* number in tokc */
594 #define TOK_CCHAR 0xb4 /* char constant in tokc */
595 #define TOK_STR 0xb5 /* pointer to string in tokc */
596 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
597 #define TOK_LCHAR 0xb7
598 #define TOK_LSTR 0xb8
599 #define TOK_CFLOAT 0xb9 /* float constant */
600 #define TOK_LINENUM 0xba /* line number info */
601 #define TOK_CDOUBLE 0xc0 /* double constant */
602 #define TOK_CLDOUBLE 0xc1 /* long double constant */
603 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
604 #define TOK_ADDC1 0xc3 /* add with carry generation */
605 #define TOK_ADDC2 0xc4 /* add with carry use */
606 #define TOK_SUBC1 0xc5 /* add with carry generation */
607 #define TOK_SUBC2 0xc6 /* add with carry use */
608 #define TOK_CUINT 0xc8 /* unsigned int constant */
609 #define TOK_CLLONG 0xc9 /* long long constant */
610 #define TOK_CULLONG 0xca /* unsigned long long constant */
611 #define TOK_ARROW 0xcb
612 #define TOK_DOTS 0xcc /* three dots */
613 #define TOK_SHR 0xcd /* unsigned shift right */
614 #define TOK_PPNUM 0xce /* preprocessor number */
616 #define TOK_SHL 0x01 /* shift left */
617 #define TOK_SAR 0x02 /* signed shift right */
619 /* assignement operators : normal operator or 0x80 */
620 #define TOK_A_MOD 0xa5
621 #define TOK_A_AND 0xa6
622 #define TOK_A_MUL 0xaa
623 #define TOK_A_ADD 0xab
624 #define TOK_A_SUB 0xad
625 #define TOK_A_DIV 0xaf
626 #define TOK_A_XOR 0xde
627 #define TOK_A_OR 0xfc
628 #define TOK_A_SHL 0x81
629 #define TOK_A_SAR 0x82
631 #ifndef offsetof
632 #define offsetof(type, field) ((size_t) &((type *)0)->field)
633 #endif
635 #ifndef countof
636 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
637 #endif
639 /* WARNING: the content of this string encodes token numbers */
640 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";
642 #define TOK_EOF (-1) /* end of file */
643 #define TOK_LINEFEED 10 /* line feed */
645 /* all identificators and strings have token above that */
646 #define TOK_IDENT 256
648 /* only used for i386 asm opcodes definitions */
649 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
651 #define DEF_BWL(x) \
652 DEF(TOK_ASM_ ## x ## b, #x "b") \
653 DEF(TOK_ASM_ ## x ## w, #x "w") \
654 DEF(TOK_ASM_ ## x ## l, #x "l") \
655 DEF(TOK_ASM_ ## x, #x)
657 #define DEF_WL(x) \
658 DEF(TOK_ASM_ ## x ## w, #x "w") \
659 DEF(TOK_ASM_ ## x ## l, #x "l") \
660 DEF(TOK_ASM_ ## x, #x)
662 #define DEF_FP1(x) \
663 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
664 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
665 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
666 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
668 #define DEF_FP(x) \
669 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
670 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
671 DEF_FP1(x)
673 #define DEF_ASMTEST(x) \
674 DEF_ASM(x ## o) \
675 DEF_ASM(x ## no) \
676 DEF_ASM(x ## b) \
677 DEF_ASM(x ## c) \
678 DEF_ASM(x ## nae) \
679 DEF_ASM(x ## nb) \
680 DEF_ASM(x ## nc) \
681 DEF_ASM(x ## ae) \
682 DEF_ASM(x ## e) \
683 DEF_ASM(x ## z) \
684 DEF_ASM(x ## ne) \
685 DEF_ASM(x ## nz) \
686 DEF_ASM(x ## be) \
687 DEF_ASM(x ## na) \
688 DEF_ASM(x ## nbe) \
689 DEF_ASM(x ## a) \
690 DEF_ASM(x ## s) \
691 DEF_ASM(x ## ns) \
692 DEF_ASM(x ## p) \
693 DEF_ASM(x ## pe) \
694 DEF_ASM(x ## np) \
695 DEF_ASM(x ## po) \
696 DEF_ASM(x ## l) \
697 DEF_ASM(x ## nge) \
698 DEF_ASM(x ## nl) \
699 DEF_ASM(x ## ge) \
700 DEF_ASM(x ## le) \
701 DEF_ASM(x ## ng) \
702 DEF_ASM(x ## nle) \
703 DEF_ASM(x ## g)
705 #define TOK_ASM_int TOK_INT
707 enum tcc_token {
708 TOK_LAST = TOK_IDENT - 1,
709 #define DEF(id, str) id,
710 #include "tcctok.h"
711 #undef DEF
714 static const char tcc_keywords[] =
715 #define DEF(id, str) str "\0"
716 #include "tcctok.h"
717 #undef DEF
720 #define TOK_UIDENT TOK_DEFINE
722 #ifdef WIN32
723 int __stdcall GetModuleFileNameA(void *, char *, int);
724 void *__stdcall GetProcAddress(void *, const char *);
725 void *__stdcall GetModuleHandleA(const char *);
726 void *__stdcall LoadLibraryA(const char *);
727 int __stdcall FreeConsole(void);
728 int __stdcall VirtualProtect(void*,unsigned long,unsigned long,unsigned long*);
729 #define PAGE_EXECUTE_READWRITE 0x0040
731 #define snprintf _snprintf
732 #define vsnprintf _vsnprintf
733 #ifndef __GNUC__
734 #define strtold (long double)strtod
735 #define strtof (float)strtod
736 #define strtoll (long long)strtol
737 #endif
738 #elif defined(TCC_UCLIBC) || defined(__FreeBSD__)
739 /* currently incorrect */
740 long double strtold(const char *nptr, char **endptr)
742 return (long double)strtod(nptr, endptr);
744 float strtof(const char *nptr, char **endptr)
746 return (float)strtod(nptr, endptr);
748 #else
749 /* XXX: need to define this to use them in non ISOC99 context */
750 extern float strtof (const char *__nptr, char **__endptr);
751 extern long double strtold (const char *__nptr, char **__endptr);
752 #endif
754 static char *pstrcpy(char *buf, int buf_size, const char *s);
755 static char *pstrcat(char *buf, int buf_size, const char *s);
756 static char *tcc_basename(const char *name);
758 static void next(void);
759 static void next_nomacro(void);
760 static void parse_expr_type(CType *type);
761 static void expr_type(CType *type);
762 static void unary_type(CType *type);
763 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
764 int case_reg, int is_expr);
765 static int expr_const(void);
766 static void expr_eq(void);
767 static void gexpr(void);
768 static void gen_inline_functions(void);
769 static void decl(int l);
770 static void decl_initializer(CType *type, Section *sec, unsigned long c,
771 int first, int size_only);
772 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
773 int has_init, int v, int scope);
774 int gv(int rc);
775 void gv2(int rc1, int rc2);
776 void move_reg(int r, int s);
777 void save_regs(int n);
778 void save_reg(int r);
779 void vpop(void);
780 void vswap(void);
781 void vdup(void);
782 int get_reg(int rc);
783 int get_reg_ex(int rc,int rc2);
785 struct macro_level {
786 struct macro_level *prev;
787 int *p;
790 static void macro_subst(TokenString *tok_str, Sym **nested_list,
791 const int *macro_str, struct macro_level **can_read_stream);
792 void gen_op(int op);
793 void force_charshort_cast(int t);
794 static void gen_cast(CType *type);
795 void vstore(void);
796 static Sym *sym_find(int v);
797 static Sym *sym_push(int v, CType *type, int r, int c);
799 /* type handling */
800 static int type_size(CType *type, int *a);
801 static inline CType *pointed_type(CType *type);
802 static int pointed_size(CType *type);
803 static int lvalue_type(int t);
804 static int parse_btype(CType *type, AttributeDef *ad);
805 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
806 static int compare_types(CType *type1, CType *type2, int unqualified);
807 static int is_compatible_types(CType *type1, CType *type2);
808 static int is_compatible_parameter_types(CType *type1, CType *type2);
810 int ieee_finite(double d);
811 void error(const char *fmt, ...);
812 void vpushi(int v);
813 void vrott(int n);
814 void vnrott(int n);
815 void lexpand_nr(void);
816 static void vpush_global_sym(CType *type, int v);
817 void vset(CType *type, int r, int v);
818 void type_to_str(char *buf, int buf_size,
819 CType *type, const char *varstr);
820 char *get_tok_str(int v, CValue *cv);
821 static Sym *get_sym_ref(CType *type, Section *sec,
822 unsigned long offset, unsigned long size);
823 static Sym *external_global_sym(int v, CType *type, int r);
825 /* section generation */
826 static void section_realloc(Section *sec, unsigned long new_size);
827 static void *section_ptr_add(Section *sec, unsigned long size);
828 static void put_extern_sym(Sym *sym, Section *section,
829 unsigned long value, unsigned long size);
830 static void greloc(Section *s, Sym *sym, unsigned long addr, int type);
831 static int put_elf_str(Section *s, const char *sym);
832 static int put_elf_sym(Section *s,
833 unsigned long value, unsigned long size,
834 int info, int other, int shndx, const char *name);
835 static int add_elf_sym(Section *s, unsigned long value, unsigned long size,
836 int info, int other, int sh_num, const char *name);
837 static void put_elf_reloc(Section *symtab, Section *s, unsigned long offset,
838 int type, int symbol);
839 static void put_stabs(const char *str, int type, int other, int desc,
840 unsigned long value);
841 static void put_stabs_r(const char *str, int type, int other, int desc,
842 unsigned long value, Section *sec, int sym_index);
843 static void put_stabn(int type, int other, int desc, int value);
844 static void put_stabd(int type, int other, int desc);
845 static int tcc_add_dll(TCCState *s, const char *filename, int flags);
847 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
848 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
849 #define AFF_PREPROCESS 0x0004 /* preprocess file */
850 static int tcc_add_file_internal(TCCState *s, const char *filename, int flags);
852 /* tcccoff.c */
853 int tcc_output_coff(TCCState *s1, FILE *f);
855 /* tccpe.c */
856 void *resolve_sym(TCCState *s1, const char *sym, int type);
857 int pe_load_def_file(struct TCCState *s1, FILE *fp);
858 void pe_setup_paths(struct TCCState *s1, int *p_output_type, const char **p_outfile, char *first_file);
859 unsigned long pe_add_runtime(struct TCCState *s1);
860 int tcc_output_pe(struct TCCState *s1, const char *filename);
862 /* tccasm.c */
864 #ifdef CONFIG_TCC_ASM
866 typedef struct ExprValue {
867 uint32_t v;
868 Sym *sym;
869 } ExprValue;
871 #define MAX_ASM_OPERANDS 30
873 typedef struct ASMOperand {
874 int id; /* GCC 3 optionnal identifier (0 if number only supported */
875 char *constraint;
876 char asm_str[16]; /* computed asm string for operand */
877 SValue *vt; /* C value of the expression */
878 int ref_index; /* if >= 0, gives reference to a output constraint */
879 int input_index; /* if >= 0, gives reference to an input constraint */
880 int priority; /* priority, used to assign registers */
881 int reg; /* if >= 0, register number used for this operand */
882 int is_llong; /* true if double register value */
883 int is_memory; /* true if memory operand */
884 int is_rw; /* for '+' modifier */
885 } ASMOperand;
887 static void asm_expr(TCCState *s1, ExprValue *pe);
888 static int asm_int_expr(TCCState *s1);
889 static int find_constraint(ASMOperand *operands, int nb_operands,
890 const char *name, const char **pp);
892 static int tcc_assemble(TCCState *s1, int do_preprocess);
894 #endif
896 static void asm_instr(void);
897 static void asm_global_instr(void);
899 /* true if float/double/long double type */
900 static inline int is_float(int t)
902 int bt;
903 bt = t & VT_BTYPE;
904 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT;
907 #ifdef TCC_TARGET_I386
908 #include "i386-gen.c"
909 #endif
911 #ifdef TCC_TARGET_ARM
912 #include "arm-gen.c"
913 #endif
915 #ifdef TCC_TARGET_C67
916 #include "c67-gen.c"
917 #endif
919 #ifdef CONFIG_TCC_STATIC
921 #define RTLD_LAZY 0x001
922 #define RTLD_NOW 0x002
923 #define RTLD_GLOBAL 0x100
924 #define RTLD_DEFAULT NULL
926 /* dummy function for profiling */
927 void *dlopen(const char *filename, int flag)
929 return NULL;
932 const char *dlerror(void)
934 return "error";
937 typedef struct TCCSyms {
938 char *str;
939 void *ptr;
940 } TCCSyms;
942 #define TCCSYM(a) { #a, &a, },
944 /* add the symbol you want here if no dynamic linking is done */
945 static TCCSyms tcc_syms[] = {
946 #if !defined(CONFIG_TCCBOOT)
947 TCCSYM(printf)
948 TCCSYM(fprintf)
949 TCCSYM(fopen)
950 TCCSYM(fclose)
951 #endif
952 { NULL, NULL },
955 void *resolve_sym(TCCState *s1, const char *symbol, int type)
957 TCCSyms *p;
958 p = tcc_syms;
959 while (p->str != NULL) {
960 if (!strcmp(p->str, symbol))
961 return p->ptr;
962 p++;
964 return NULL;
967 #elif !defined(WIN32)
969 #include <dlfcn.h>
971 void *resolve_sym(TCCState *s1, const char *sym, int type)
973 return dlsym(RTLD_DEFAULT, sym);
976 #endif
978 /********************************************************/
980 /* we use our own 'finite' function to avoid potential problems with
981 non standard math libs */
982 /* XXX: endianness dependent */
983 int ieee_finite(double d)
985 int *p = (int *)&d;
986 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
989 /* copy a string and truncate it. */
990 static char *pstrcpy(char *buf, int buf_size, const char *s)
992 char *q, *q_end;
993 int c;
995 if (buf_size > 0) {
996 q = buf;
997 q_end = buf + buf_size - 1;
998 while (q < q_end) {
999 c = *s++;
1000 if (c == '\0')
1001 break;
1002 *q++ = c;
1004 *q = '\0';
1006 return buf;
1009 /* strcat and truncate. */
1010 static char *pstrcat(char *buf, int buf_size, const char *s)
1012 int len;
1013 len = strlen(buf);
1014 if (len < buf_size)
1015 pstrcpy(buf + len, buf_size - len, s);
1016 return buf;
1019 static int strstart(const char *str, const char *val, const char **ptr)
1021 const char *p, *q;
1022 p = str;
1023 q = val;
1024 while (*q != '\0') {
1025 if (*p != *q)
1026 return 0;
1027 p++;
1028 q++;
1030 if (ptr)
1031 *ptr = p;
1032 return 1;
1035 /* memory management */
1036 #ifdef MEM_DEBUG
1037 int mem_cur_size;
1038 int mem_max_size;
1039 #endif
1041 static inline void tcc_free(void *ptr)
1043 #ifdef MEM_DEBUG
1044 mem_cur_size -= malloc_usable_size(ptr);
1045 #endif
1046 free(ptr);
1049 static void *tcc_malloc(unsigned long size)
1051 void *ptr;
1052 ptr = malloc(size);
1053 if (!ptr && size)
1054 error("memory full");
1055 #ifdef MEM_DEBUG
1056 mem_cur_size += malloc_usable_size(ptr);
1057 if (mem_cur_size > mem_max_size)
1058 mem_max_size = mem_cur_size;
1059 #endif
1060 return ptr;
1063 static void *tcc_mallocz(unsigned long size)
1065 void *ptr;
1066 ptr = tcc_malloc(size);
1067 memset(ptr, 0, size);
1068 return ptr;
1071 static inline void *tcc_realloc(void *ptr, unsigned long size)
1073 void *ptr1;
1074 #ifdef MEM_DEBUG
1075 mem_cur_size -= malloc_usable_size(ptr);
1076 #endif
1077 ptr1 = realloc(ptr, size);
1078 #ifdef MEM_DEBUG
1079 /* NOTE: count not correct if alloc error, but not critical */
1080 mem_cur_size += malloc_usable_size(ptr1);
1081 if (mem_cur_size > mem_max_size)
1082 mem_max_size = mem_cur_size;
1083 #endif
1084 return ptr1;
1087 static char *tcc_strdup(const char *str)
1089 char *ptr;
1090 ptr = tcc_malloc(strlen(str) + 1);
1091 strcpy(ptr, str);
1092 return ptr;
1095 #define free(p) use_tcc_free(p)
1096 #define malloc(s) use_tcc_malloc(s)
1097 #define realloc(p, s) use_tcc_realloc(p, s)
1099 static void dynarray_add(void ***ptab, int *nb_ptr, void *data)
1101 int nb, nb_alloc;
1102 void **pp;
1104 nb = *nb_ptr;
1105 pp = *ptab;
1106 /* every power of two we double array size */
1107 if ((nb & (nb - 1)) == 0) {
1108 if (!nb)
1109 nb_alloc = 1;
1110 else
1111 nb_alloc = nb * 2;
1112 pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
1113 if (!pp)
1114 error("memory full");
1115 *ptab = pp;
1117 pp[nb++] = data;
1118 *nb_ptr = nb;
1121 /* symbol allocator */
1122 static Sym *__sym_malloc(void)
1124 Sym *sym_pool, *sym, *last_sym;
1125 int i;
1127 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
1129 last_sym = sym_free_first;
1130 sym = sym_pool;
1131 for(i = 0; i < SYM_POOL_NB; i++) {
1132 sym->next = last_sym;
1133 last_sym = sym;
1134 sym++;
1136 sym_free_first = last_sym;
1137 return last_sym;
1140 static inline Sym *sym_malloc(void)
1142 Sym *sym;
1143 sym = sym_free_first;
1144 if (!sym)
1145 sym = __sym_malloc();
1146 sym_free_first = sym->next;
1147 return sym;
1150 static inline void sym_free(Sym *sym)
1152 sym->next = sym_free_first;
1153 sym_free_first = sym;
1156 Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
1158 Section *sec;
1160 sec = tcc_mallocz(sizeof(Section) + strlen(name));
1161 strcpy(sec->name, name);
1162 sec->sh_type = sh_type;
1163 sec->sh_flags = sh_flags;
1164 switch(sh_type) {
1165 case SHT_HASH:
1166 case SHT_REL:
1167 case SHT_DYNSYM:
1168 case SHT_SYMTAB:
1169 case SHT_DYNAMIC:
1170 sec->sh_addralign = 4;
1171 break;
1172 case SHT_STRTAB:
1173 sec->sh_addralign = 1;
1174 break;
1175 default:
1176 sec->sh_addralign = 32; /* default conservative alignment */
1177 break;
1180 /* only add section if not private */
1181 if (!(sh_flags & SHF_PRIVATE)) {
1182 sec->sh_num = s1->nb_sections;
1183 dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
1185 return sec;
1188 static void free_section(Section *s)
1190 tcc_free(s->data);
1191 tcc_free(s);
1194 /* realloc section and set its content to zero */
1195 static void section_realloc(Section *sec, unsigned long new_size)
1197 unsigned long size;
1198 unsigned char *data;
1200 size = sec->data_allocated;
1201 if (size == 0)
1202 size = 1;
1203 while (size < new_size)
1204 size = size * 2;
1205 data = tcc_realloc(sec->data, size);
1206 if (!data)
1207 error("memory full");
1208 memset(data + sec->data_allocated, 0, size - sec->data_allocated);
1209 sec->data = data;
1210 sec->data_allocated = size;
1213 /* reserve at least 'size' bytes in section 'sec' from
1214 sec->data_offset. */
1215 static void *section_ptr_add(Section *sec, unsigned long size)
1217 unsigned long offset, offset1;
1219 offset = sec->data_offset;
1220 offset1 = offset + size;
1221 if (offset1 > sec->data_allocated)
1222 section_realloc(sec, offset1);
1223 sec->data_offset = offset1;
1224 return sec->data + offset;
1227 /* return a reference to a section, and create it if it does not
1228 exists */
1229 Section *find_section(TCCState *s1, const char *name)
1231 Section *sec;
1232 int i;
1233 for(i = 1; i < s1->nb_sections; i++) {
1234 sec = s1->sections[i];
1235 if (!strcmp(name, sec->name))
1236 return sec;
1238 /* sections are created as PROGBITS */
1239 return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
1242 #define SECTION_ABS ((void *)1)
1244 /* update sym->c so that it points to an external symbol in section
1245 'section' with value 'value' */
1246 static void put_extern_sym2(Sym *sym, Section *section,
1247 unsigned long value, unsigned long size,
1248 int can_add_underscore)
1250 int sym_type, sym_bind, sh_num, info;
1251 Elf32_Sym *esym;
1252 const char *name;
1253 char buf1[256];
1255 if (section == NULL)
1256 sh_num = SHN_UNDEF;
1257 else if (section == SECTION_ABS)
1258 sh_num = SHN_ABS;
1259 else
1260 sh_num = section->sh_num;
1261 if (!sym->c) {
1262 if ((sym->type.t & VT_BTYPE) == VT_FUNC)
1263 sym_type = STT_FUNC;
1264 else
1265 sym_type = STT_OBJECT;
1266 if (sym->type.t & VT_STATIC)
1267 sym_bind = STB_LOCAL;
1268 else
1269 sym_bind = STB_GLOBAL;
1271 name = get_tok_str(sym->v, NULL);
1272 #ifdef CONFIG_TCC_BCHECK
1273 if (do_bounds_check) {
1274 char buf[32];
1276 /* XXX: avoid doing that for statics ? */
1277 /* if bound checking is activated, we change some function
1278 names by adding the "__bound" prefix */
1279 switch(sym->v) {
1280 #if 0
1281 /* XXX: we rely only on malloc hooks */
1282 case TOK_malloc:
1283 case TOK_free:
1284 case TOK_realloc:
1285 case TOK_memalign:
1286 case TOK_calloc:
1287 #endif
1288 case TOK_memcpy:
1289 case TOK_memmove:
1290 case TOK_memset:
1291 case TOK_strlen:
1292 case TOK_strcpy:
1293 strcpy(buf, "__bound_");
1294 strcat(buf, name);
1295 name = buf;
1296 break;
1299 #endif
1300 if (tcc_state->leading_underscore && can_add_underscore) {
1301 buf1[0] = '_';
1302 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
1303 name = buf1;
1305 info = ELF32_ST_INFO(sym_bind, sym_type);
1306 sym->c = add_elf_sym(symtab_section, value, size, info, 0, sh_num, name);
1307 } else {
1308 esym = &((Elf32_Sym *)symtab_section->data)[sym->c];
1309 esym->st_value = value;
1310 esym->st_size = size;
1311 esym->st_shndx = sh_num;
1315 static void put_extern_sym(Sym *sym, Section *section,
1316 unsigned long value, unsigned long size)
1318 put_extern_sym2(sym, section, value, size, 1);
1321 /* add a new relocation entry to symbol 'sym' in section 's' */
1322 static void greloc(Section *s, Sym *sym, unsigned long offset, int type)
1324 if (!sym->c)
1325 put_extern_sym(sym, NULL, 0, 0);
1326 /* now we can add ELF relocation info */
1327 put_elf_reloc(symtab_section, s, offset, type, sym->c);
1330 static inline int isid(int c)
1332 return (c >= 'a' && c <= 'z') ||
1333 (c >= 'A' && c <= 'Z') ||
1334 c == '_';
1337 static inline int isnum(int c)
1339 return c >= '0' && c <= '9';
1342 static inline int isoct(int c)
1344 return c >= '0' && c <= '7';
1347 static inline int toup(int c)
1349 if (c >= 'a' && c <= 'z')
1350 return c - 'a' + 'A';
1351 else
1352 return c;
1355 static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
1357 int len;
1358 len = strlen(buf);
1359 vsnprintf(buf + len, buf_size - len, fmt, ap);
1362 static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
1364 va_list ap;
1365 va_start(ap, fmt);
1366 strcat_vprintf(buf, buf_size, fmt, ap);
1367 va_end(ap);
1370 void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
1372 char buf[2048];
1373 BufferedFile **f;
1375 buf[0] = '\0';
1376 if (file) {
1377 for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
1378 strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
1379 (*f)->filename, (*f)->line_num);
1380 if (file->line_num > 0) {
1381 strcat_printf(buf, sizeof(buf),
1382 "%s:%d: ", file->filename, file->line_num);
1383 } else {
1384 strcat_printf(buf, sizeof(buf),
1385 "%s: ", file->filename);
1387 } else {
1388 strcat_printf(buf, sizeof(buf),
1389 "tcc: ");
1391 if (is_warning)
1392 strcat_printf(buf, sizeof(buf), "warning: ");
1393 strcat_vprintf(buf, sizeof(buf), fmt, ap);
1395 if (!s1->error_func) {
1396 /* default case: stderr */
1397 fprintf(stderr, "%s\n", buf);
1398 } else {
1399 s1->error_func(s1->error_opaque, buf);
1401 if (!is_warning || s1->warn_error)
1402 s1->nb_errors++;
1405 #ifdef LIBTCC
1406 void tcc_set_error_func(TCCState *s, void *error_opaque,
1407 void (*error_func)(void *opaque, const char *msg))
1409 s->error_opaque = error_opaque;
1410 s->error_func = error_func;
1412 #endif
1414 /* error without aborting current compilation */
1415 void error_noabort(const char *fmt, ...)
1417 TCCState *s1 = tcc_state;
1418 va_list ap;
1420 va_start(ap, fmt);
1421 error1(s1, 0, fmt, ap);
1422 va_end(ap);
1425 void error(const char *fmt, ...)
1427 TCCState *s1 = tcc_state;
1428 va_list ap;
1430 va_start(ap, fmt);
1431 error1(s1, 0, fmt, ap);
1432 va_end(ap);
1433 /* better than nothing: in some cases, we accept to handle errors */
1434 if (s1->error_set_jmp_enabled) {
1435 longjmp(s1->error_jmp_buf, 1);
1436 } else {
1437 /* XXX: eliminate this someday */
1438 exit(1);
1442 void expect(const char *msg)
1444 error("%s expected", msg);
1447 void warning(const char *fmt, ...)
1449 TCCState *s1 = tcc_state;
1450 va_list ap;
1452 if (s1->warn_none)
1453 return;
1455 va_start(ap, fmt);
1456 error1(s1, 1, fmt, ap);
1457 va_end(ap);
1460 void skip(int c)
1462 if (tok != c)
1463 error("'%c' expected", c);
1464 next();
1467 static void test_lvalue(void)
1469 if (!(vtop->r & VT_LVAL))
1470 expect("lvalue");
1473 /* allocate a new token */
1474 static TokenSym *tok_alloc_new(TokenSym **pts, const char *str, int len)
1476 TokenSym *ts, **ptable;
1477 int i;
1479 if (tok_ident >= SYM_FIRST_ANOM)
1480 error("memory full");
1482 /* expand token table if needed */
1483 i = tok_ident - TOK_IDENT;
1484 if ((i % TOK_ALLOC_INCR) == 0) {
1485 ptable = tcc_realloc(table_ident, (i + TOK_ALLOC_INCR) * sizeof(TokenSym *));
1486 if (!ptable)
1487 error("memory full");
1488 table_ident = ptable;
1491 ts = tcc_malloc(sizeof(TokenSym) + len);
1492 table_ident[i] = ts;
1493 ts->tok = tok_ident++;
1494 ts->sym_define = NULL;
1495 ts->sym_label = NULL;
1496 ts->sym_struct = NULL;
1497 ts->sym_identifier = NULL;
1498 ts->len = len;
1499 ts->hash_next = NULL;
1500 memcpy(ts->str, str, len);
1501 ts->str[len] = '\0';
1502 *pts = ts;
1503 return ts;
1506 #define TOK_HASH_INIT 1
1507 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1509 /* find a token and add it if not found */
1510 static TokenSym *tok_alloc(const char *str, int len)
1512 TokenSym *ts, **pts;
1513 int i;
1514 unsigned int h;
1516 h = TOK_HASH_INIT;
1517 for(i=0;i<len;i++)
1518 h = TOK_HASH_FUNC(h, ((unsigned char *)str)[i]);
1519 h &= (TOK_HASH_SIZE - 1);
1521 pts = &hash_ident[h];
1522 for(;;) {
1523 ts = *pts;
1524 if (!ts)
1525 break;
1526 if (ts->len == len && !memcmp(ts->str, str, len))
1527 return ts;
1528 pts = &(ts->hash_next);
1530 return tok_alloc_new(pts, str, len);
1533 /* CString handling */
1535 static void cstr_realloc(CString *cstr, int new_size)
1537 int size;
1538 void *data;
1540 size = cstr->size_allocated;
1541 if (size == 0)
1542 size = 8; /* no need to allocate a too small first string */
1543 while (size < new_size)
1544 size = size * 2;
1545 data = tcc_realloc(cstr->data_allocated, size);
1546 if (!data)
1547 error("memory full");
1548 cstr->data_allocated = data;
1549 cstr->size_allocated = size;
1550 cstr->data = data;
1553 /* add a byte */
1554 static inline void cstr_ccat(CString *cstr, int ch)
1556 int size;
1557 size = cstr->size + 1;
1558 if (size > cstr->size_allocated)
1559 cstr_realloc(cstr, size);
1560 ((unsigned char *)cstr->data)[size - 1] = ch;
1561 cstr->size = size;
1564 static void cstr_cat(CString *cstr, const char *str)
1566 int c;
1567 for(;;) {
1568 c = *str;
1569 if (c == '\0')
1570 break;
1571 cstr_ccat(cstr, c);
1572 str++;
1576 /* add a wide char */
1577 static void cstr_wccat(CString *cstr, int ch)
1579 int size;
1580 size = cstr->size + sizeof(nwchar_t);
1581 if (size > cstr->size_allocated)
1582 cstr_realloc(cstr, size);
1583 *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
1584 cstr->size = size;
1587 static void cstr_new(CString *cstr)
1589 memset(cstr, 0, sizeof(CString));
1592 /* free string and reset it to NULL */
1593 static void cstr_free(CString *cstr)
1595 tcc_free(cstr->data_allocated);
1596 cstr_new(cstr);
1599 #define cstr_reset(cstr) cstr_free(cstr)
1601 /* XXX: unicode ? */
1602 static void add_char(CString *cstr, int c)
1604 if (c == '\'' || c == '\"' || c == '\\') {
1605 /* XXX: could be more precise if char or string */
1606 cstr_ccat(cstr, '\\');
1608 if (c >= 32 && c <= 126) {
1609 cstr_ccat(cstr, c);
1610 } else {
1611 cstr_ccat(cstr, '\\');
1612 if (c == '\n') {
1613 cstr_ccat(cstr, 'n');
1614 } else {
1615 cstr_ccat(cstr, '0' + ((c >> 6) & 7));
1616 cstr_ccat(cstr, '0' + ((c >> 3) & 7));
1617 cstr_ccat(cstr, '0' + (c & 7));
1622 /* XXX: buffer overflow */
1623 /* XXX: float tokens */
1624 char *get_tok_str(int v, CValue *cv)
1626 static char buf[STRING_MAX_SIZE + 1];
1627 static CString cstr_buf;
1628 CString *cstr;
1629 unsigned char *q;
1630 char *p;
1631 int i, len;
1633 /* NOTE: to go faster, we give a fixed buffer for small strings */
1634 cstr_reset(&cstr_buf);
1635 cstr_buf.data = buf;
1636 cstr_buf.size_allocated = sizeof(buf);
1637 p = buf;
1639 switch(v) {
1640 case TOK_CINT:
1641 case TOK_CUINT:
1642 /* XXX: not quite exact, but only useful for testing */
1643 sprintf(p, "%u", cv->ui);
1644 break;
1645 case TOK_CLLONG:
1646 case TOK_CULLONG:
1647 /* XXX: not quite exact, but only useful for testing */
1648 sprintf(p, "%Lu", cv->ull);
1649 break;
1650 case TOK_CCHAR:
1651 case TOK_LCHAR:
1652 cstr_ccat(&cstr_buf, '\'');
1653 add_char(&cstr_buf, cv->i);
1654 cstr_ccat(&cstr_buf, '\'');
1655 cstr_ccat(&cstr_buf, '\0');
1656 break;
1657 case TOK_PPNUM:
1658 cstr = cv->cstr;
1659 len = cstr->size - 1;
1660 for(i=0;i<len;i++)
1661 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
1662 cstr_ccat(&cstr_buf, '\0');
1663 break;
1664 case TOK_STR:
1665 case TOK_LSTR:
1666 cstr = cv->cstr;
1667 cstr_ccat(&cstr_buf, '\"');
1668 if (v == TOK_STR) {
1669 len = cstr->size - 1;
1670 for(i=0;i<len;i++)
1671 add_char(&cstr_buf, ((unsigned char *)cstr->data)[i]);
1672 } else {
1673 len = (cstr->size / sizeof(nwchar_t)) - 1;
1674 for(i=0;i<len;i++)
1675 add_char(&cstr_buf, ((nwchar_t *)cstr->data)[i]);
1677 cstr_ccat(&cstr_buf, '\"');
1678 cstr_ccat(&cstr_buf, '\0');
1679 break;
1680 case TOK_LT:
1681 v = '<';
1682 goto addv;
1683 case TOK_GT:
1684 v = '>';
1685 goto addv;
1686 case TOK_DOTS:
1687 return strcpy(p, "...");
1688 case TOK_A_SHL:
1689 return strcpy(p, "<<=");
1690 case TOK_A_SAR:
1691 return strcpy(p, ">>=");
1692 default:
1693 if (v < TOK_IDENT) {
1694 /* search in two bytes table */
1695 q = tok_two_chars;
1696 while (*q) {
1697 if (q[2] == v) {
1698 *p++ = q[0];
1699 *p++ = q[1];
1700 *p = '\0';
1701 return buf;
1703 q += 3;
1705 addv:
1706 *p++ = v;
1707 *p = '\0';
1708 } else if (v < tok_ident) {
1709 return table_ident[v - TOK_IDENT]->str;
1710 } else if (v >= SYM_FIRST_ANOM) {
1711 /* special name for anonymous symbol */
1712 sprintf(p, "L.%u", v - SYM_FIRST_ANOM);
1713 } else {
1714 /* should never happen */
1715 return NULL;
1717 break;
1719 return cstr_buf.data;
1722 /* push, without hashing */
1723 static Sym *sym_push2(Sym **ps, int v, int t, int c)
1725 Sym *s;
1726 s = sym_malloc();
1727 s->v = v;
1728 s->type.t = t;
1729 s->c = c;
1730 s->next = NULL;
1731 /* add in stack */
1732 s->prev = *ps;
1733 *ps = s;
1734 return s;
1737 /* find a symbol and return its associated structure. 's' is the top
1738 of the symbol stack */
1739 static Sym *sym_find2(Sym *s, int v)
1741 while (s) {
1742 if (s->v == v)
1743 return s;
1744 s = s->prev;
1746 return NULL;
1749 /* structure lookup */
1750 static inline Sym *struct_find(int v)
1752 v -= TOK_IDENT;
1753 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1754 return NULL;
1755 return table_ident[v]->sym_struct;
1758 /* find an identifier */
1759 static inline Sym *sym_find(int v)
1761 v -= TOK_IDENT;
1762 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
1763 return NULL;
1764 return table_ident[v]->sym_identifier;
1767 /* push a given symbol on the symbol stack */
1768 static Sym *sym_push(int v, CType *type, int r, int c)
1770 Sym *s, **ps;
1771 TokenSym *ts;
1773 if (local_stack)
1774 ps = &local_stack;
1775 else
1776 ps = &global_stack;
1777 s = sym_push2(ps, v, type->t, c);
1778 s->type.ref = type->ref;
1779 s->r = r;
1780 /* don't record fields or anonymous symbols */
1781 /* XXX: simplify */
1782 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1783 /* record symbol in token array */
1784 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1785 if (v & SYM_STRUCT)
1786 ps = &ts->sym_struct;
1787 else
1788 ps = &ts->sym_identifier;
1789 s->prev_tok = *ps;
1790 *ps = s;
1792 return s;
1795 /* push a global identifier */
1796 static Sym *global_identifier_push(int v, int t, int c)
1798 Sym *s, **ps;
1799 s = sym_push2(&global_stack, v, t, c);
1800 /* don't record anonymous symbol */
1801 if (v < SYM_FIRST_ANOM) {
1802 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
1803 /* modify the top most local identifier, so that
1804 sym_identifier will point to 's' when popped */
1805 while (*ps != NULL)
1806 ps = &(*ps)->prev_tok;
1807 s->prev_tok = NULL;
1808 *ps = s;
1810 return s;
1813 /* pop symbols until top reaches 'b' */
1814 static void sym_pop(Sym **ptop, Sym *b)
1816 Sym *s, *ss, **ps;
1817 TokenSym *ts;
1818 int v;
1820 s = *ptop;
1821 while(s != b) {
1822 ss = s->prev;
1823 v = s->v;
1824 /* remove symbol in token array */
1825 /* XXX: simplify */
1826 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
1827 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
1828 if (v & SYM_STRUCT)
1829 ps = &ts->sym_struct;
1830 else
1831 ps = &ts->sym_identifier;
1832 *ps = s->prev_tok;
1834 sym_free(s);
1835 s = ss;
1837 *ptop = b;
1840 /* I/O layer */
1842 BufferedFile *tcc_open(TCCState *s1, const char *filename)
1844 int fd;
1845 BufferedFile *bf;
1846 int i, len;
1848 fd = open(filename, O_RDONLY | O_BINARY);
1849 if (fd < 0)
1850 return NULL;
1851 bf = tcc_malloc(sizeof(BufferedFile));
1852 if (!bf) {
1853 close(fd);
1854 return NULL;
1856 bf->fd = fd;
1857 bf->buf_ptr = bf->buffer;
1858 bf->buf_end = bf->buffer;
1859 bf->buffer[0] = CH_EOB; /* put eob symbol */
1860 pstrcpy(bf->filename, sizeof(bf->filename), filename);
1861 len = strlen(bf->filename);
1862 for (i = 0; i < len; i++)
1863 if (bf->filename[i] == '\\')
1864 bf->filename[i] = '/';
1865 bf->line_num = 1;
1866 bf->ifndef_macro = 0;
1867 bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
1868 // printf("opening '%s'\n", filename);
1869 return bf;
1872 void tcc_close(BufferedFile *bf)
1874 total_lines += bf->line_num;
1875 close(bf->fd);
1876 tcc_free(bf);
1879 /* fill input buffer and peek next char */
1880 static int tcc_peekc_slow(BufferedFile *bf)
1882 int len;
1883 /* only tries to read if really end of buffer */
1884 if (bf->buf_ptr >= bf->buf_end) {
1885 if (bf->fd != -1) {
1886 #if defined(PARSE_DEBUG)
1887 len = 8;
1888 #else
1889 len = IO_BUF_SIZE;
1890 #endif
1891 len = read(bf->fd, bf->buffer, len);
1892 if (len < 0)
1893 len = 0;
1894 } else {
1895 len = 0;
1897 total_bytes += len;
1898 bf->buf_ptr = bf->buffer;
1899 bf->buf_end = bf->buffer + len;
1900 *bf->buf_end = CH_EOB;
1902 if (bf->buf_ptr < bf->buf_end) {
1903 return bf->buf_ptr[0];
1904 } else {
1905 bf->buf_ptr = bf->buf_end;
1906 return CH_EOF;
1910 /* return the current character, handling end of block if necessary
1911 (but not stray) */
1912 static int handle_eob(void)
1914 return tcc_peekc_slow(file);
1917 /* read next char from current input file and handle end of input buffer */
1918 static inline void inp(void)
1920 ch = *(++(file->buf_ptr));
1921 /* end of buffer/file handling */
1922 if (ch == CH_EOB)
1923 ch = handle_eob();
1926 /* handle '\[\r]\n' */
1927 static void handle_stray(void)
1929 while (ch == '\\') {
1930 inp();
1931 if (ch == '\n') {
1932 file->line_num++;
1933 inp();
1934 } else if (ch == '\r') {
1935 inp();
1936 if (ch != '\n')
1937 goto fail;
1938 file->line_num++;
1939 inp();
1940 } else {
1941 fail:
1942 error("stray '\\' in program");
1947 /* skip the stray and handle the \\n case. Output an error if
1948 incorrect char after the stray */
1949 static int handle_stray1(uint8_t *p)
1951 int c;
1953 if (p >= file->buf_end) {
1954 file->buf_ptr = p;
1955 c = handle_eob();
1956 p = file->buf_ptr;
1957 if (c == '\\')
1958 goto parse_stray;
1959 } else {
1960 parse_stray:
1961 file->buf_ptr = p;
1962 ch = *p;
1963 handle_stray();
1964 p = file->buf_ptr;
1965 c = *p;
1967 return c;
1970 /* handle just the EOB case, but not stray */
1971 #define PEEKC_EOB(c, p)\
1973 p++;\
1974 c = *p;\
1975 if (c == '\\') {\
1976 file->buf_ptr = p;\
1977 c = handle_eob();\
1978 p = file->buf_ptr;\
1982 /* handle the complicated stray case */
1983 #define PEEKC(c, p)\
1985 p++;\
1986 c = *p;\
1987 if (c == '\\') {\
1988 c = handle_stray1(p);\
1989 p = file->buf_ptr;\
1993 /* input with '\[\r]\n' handling. Note that this function cannot
1994 handle other characters after '\', so you cannot call it inside
1995 strings or comments */
1996 static void minp(void)
1998 inp();
1999 if (ch == '\\')
2000 handle_stray();
2004 /* single line C++ comments */
2005 static uint8_t *parse_line_comment(uint8_t *p)
2007 int c;
2009 p++;
2010 for(;;) {
2011 c = *p;
2012 redo:
2013 if (c == '\n' || c == CH_EOF) {
2014 break;
2015 } else if (c == '\\') {
2016 file->buf_ptr = p;
2017 c = handle_eob();
2018 p = file->buf_ptr;
2019 if (c == '\\') {
2020 PEEKC_EOB(c, p);
2021 if (c == '\n') {
2022 file->line_num++;
2023 PEEKC_EOB(c, p);
2024 } else if (c == '\r') {
2025 PEEKC_EOB(c, p);
2026 if (c == '\n') {
2027 file->line_num++;
2028 PEEKC_EOB(c, p);
2031 } else {
2032 goto redo;
2034 } else {
2035 p++;
2038 return p;
2041 /* C comments */
2042 static uint8_t *parse_comment(uint8_t *p)
2044 int c;
2046 p++;
2047 for(;;) {
2048 /* fast skip loop */
2049 for(;;) {
2050 c = *p;
2051 if (c == '\n' || c == '*' || c == '\\')
2052 break;
2053 p++;
2054 c = *p;
2055 if (c == '\n' || c == '*' || c == '\\')
2056 break;
2057 p++;
2059 /* now we can handle all the cases */
2060 if (c == '\n') {
2061 file->line_num++;
2062 p++;
2063 } else if (c == '*') {
2064 p++;
2065 for(;;) {
2066 c = *p;
2067 if (c == '*') {
2068 p++;
2069 } else if (c == '/') {
2070 goto end_of_comment;
2071 } else if (c == '\\') {
2072 file->buf_ptr = p;
2073 c = handle_eob();
2074 p = file->buf_ptr;
2075 if (c == '\\') {
2076 /* skip '\[\r]\n', otherwise just skip the stray */
2077 while (c == '\\') {
2078 PEEKC_EOB(c, p);
2079 if (c == '\n') {
2080 file->line_num++;
2081 PEEKC_EOB(c, p);
2082 } else if (c == '\r') {
2083 PEEKC_EOB(c, p);
2084 if (c == '\n') {
2085 file->line_num++;
2086 PEEKC_EOB(c, p);
2088 } else {
2089 goto after_star;
2093 } else {
2094 break;
2097 after_star: ;
2098 } else {
2099 /* stray, eob or eof */
2100 file->buf_ptr = p;
2101 c = handle_eob();
2102 p = file->buf_ptr;
2103 if (c == CH_EOF) {
2104 error("unexpected end of file in comment");
2105 } else if (c == '\\') {
2106 p++;
2110 end_of_comment:
2111 p++;
2112 return p;
2115 #define cinp minp
2117 /* space exlcuding newline */
2118 static inline int is_space(int ch)
2120 return ch == ' ' || ch == '\t' || ch == '\v' || ch == '\f' || ch == '\r';
2123 static inline void skip_spaces(void)
2125 while (is_space(ch))
2126 cinp();
2129 /* parse a string without interpreting escapes */
2130 static uint8_t *parse_pp_string(uint8_t *p,
2131 int sep, CString *str)
2133 int c;
2134 p++;
2135 for(;;) {
2136 c = *p;
2137 if (c == sep) {
2138 break;
2139 } else if (c == '\\') {
2140 file->buf_ptr = p;
2141 c = handle_eob();
2142 p = file->buf_ptr;
2143 if (c == CH_EOF) {
2144 unterminated_string:
2145 /* XXX: indicate line number of start of string */
2146 error("missing terminating %c character", sep);
2147 } else if (c == '\\') {
2148 /* escape : just skip \[\r]\n */
2149 PEEKC_EOB(c, p);
2150 if (c == '\n') {
2151 file->line_num++;
2152 p++;
2153 } else if (c == '\r') {
2154 PEEKC_EOB(c, p);
2155 if (c != '\n')
2156 expect("'\n' after '\r'");
2157 file->line_num++;
2158 p++;
2159 } else if (c == CH_EOF) {
2160 goto unterminated_string;
2161 } else {
2162 if (str) {
2163 cstr_ccat(str, '\\');
2164 cstr_ccat(str, c);
2166 p++;
2169 } else if (c == '\n') {
2170 file->line_num++;
2171 goto add_char;
2172 } else if (c == '\r') {
2173 PEEKC_EOB(c, p);
2174 if (c != '\n') {
2175 if (str)
2176 cstr_ccat(str, '\r');
2177 } else {
2178 file->line_num++;
2179 goto add_char;
2181 } else {
2182 add_char:
2183 if (str)
2184 cstr_ccat(str, c);
2185 p++;
2188 p++;
2189 return p;
2192 /* skip block of text until #else, #elif or #endif. skip also pairs of
2193 #if/#endif */
2194 void preprocess_skip(void)
2196 int a, start_of_line, c;
2197 uint8_t *p;
2199 p = file->buf_ptr;
2200 start_of_line = 1;
2201 a = 0;
2202 for(;;) {
2203 redo_no_start:
2204 c = *p;
2205 switch(c) {
2206 case ' ':
2207 case '\t':
2208 case '\f':
2209 case '\v':
2210 case '\r':
2211 p++;
2212 goto redo_no_start;
2213 case '\n':
2214 start_of_line = 1;
2215 file->line_num++;
2216 p++;
2217 goto redo_no_start;
2218 case '\\':
2219 file->buf_ptr = p;
2220 c = handle_eob();
2221 if (c == CH_EOF) {
2222 expect("#endif");
2223 } else if (c == '\\') {
2224 /* XXX: incorrect: should not give an error */
2225 ch = file->buf_ptr[0];
2226 handle_stray();
2228 p = file->buf_ptr;
2229 goto redo_no_start;
2230 /* skip strings */
2231 case '\"':
2232 case '\'':
2233 p = parse_pp_string(p, c, NULL);
2234 break;
2235 /* skip comments */
2236 case '/':
2237 file->buf_ptr = p;
2238 ch = *p;
2239 minp();
2240 p = file->buf_ptr;
2241 if (ch == '*') {
2242 p = parse_comment(p);
2243 } else if (ch == '/') {
2244 p = parse_line_comment(p);
2246 break;
2248 case '#':
2249 p++;
2250 if (start_of_line) {
2251 file->buf_ptr = p;
2252 next_nomacro();
2253 p = file->buf_ptr;
2254 if (a == 0 &&
2255 (tok == TOK_ELSE || tok == TOK_ELIF || tok == TOK_ENDIF))
2256 goto the_end;
2257 if (tok == TOK_IF || tok == TOK_IFDEF || tok == TOK_IFNDEF)
2258 a++;
2259 else if (tok == TOK_ENDIF)
2260 a--;
2262 break;
2263 default:
2264 p++;
2265 break;
2267 start_of_line = 0;
2269 the_end: ;
2270 file->buf_ptr = p;
2273 /* ParseState handling */
2275 /* XXX: currently, no include file info is stored. Thus, we cannot display
2276 accurate messages if the function or data definition spans multiple
2277 files */
2279 /* save current parse state in 's' */
2280 void save_parse_state(ParseState *s)
2282 s->line_num = file->line_num;
2283 s->macro_ptr = macro_ptr;
2284 s->tok = tok;
2285 s->tokc = tokc;
2288 /* restore parse state from 's' */
2289 void restore_parse_state(ParseState *s)
2291 file->line_num = s->line_num;
2292 macro_ptr = s->macro_ptr;
2293 tok = s->tok;
2294 tokc = s->tokc;
2297 /* return the number of additional 'ints' necessary to store the
2298 token */
2299 static inline int tok_ext_size(int t)
2301 switch(t) {
2302 /* 4 bytes */
2303 case TOK_CINT:
2304 case TOK_CUINT:
2305 case TOK_CCHAR:
2306 case TOK_LCHAR:
2307 case TOK_CFLOAT:
2308 case TOK_LINENUM:
2309 return 1;
2310 case TOK_STR:
2311 case TOK_LSTR:
2312 case TOK_PPNUM:
2313 error("unsupported token");
2314 return 1;
2315 case TOK_CDOUBLE:
2316 case TOK_CLLONG:
2317 case TOK_CULLONG:
2318 return 2;
2319 case TOK_CLDOUBLE:
2320 return LDOUBLE_SIZE / 4;
2321 default:
2322 return 0;
2326 /* token string handling */
2328 static inline void tok_str_new(TokenString *s)
2330 s->str = NULL;
2331 s->len = 0;
2332 s->allocated_len = 0;
2333 s->last_line_num = -1;
2336 static void tok_str_free(int *str)
2338 tcc_free(str);
2341 static int *tok_str_realloc(TokenString *s)
2343 int *str, len;
2345 if (s->allocated_len == 0) {
2346 len = 8;
2347 } else {
2348 len = s->allocated_len * 2;
2350 str = tcc_realloc(s->str, len * sizeof(int));
2351 if (!str)
2352 error("memory full");
2353 s->allocated_len = len;
2354 s->str = str;
2355 return str;
2358 static void tok_str_add(TokenString *s, int t)
2360 int len, *str;
2362 len = s->len;
2363 str = s->str;
2364 if (len >= s->allocated_len)
2365 str = tok_str_realloc(s);
2366 str[len++] = t;
2367 s->len = len;
2370 static void tok_str_add2(TokenString *s, int t, CValue *cv)
2372 int len, *str;
2374 len = s->len;
2375 str = s->str;
2377 /* allocate space for worst case */
2378 if (len + TOK_MAX_SIZE > s->allocated_len)
2379 str = tok_str_realloc(s);
2380 str[len++] = t;
2381 switch(t) {
2382 case TOK_CINT:
2383 case TOK_CUINT:
2384 case TOK_CCHAR:
2385 case TOK_LCHAR:
2386 case TOK_CFLOAT:
2387 case TOK_LINENUM:
2388 str[len++] = cv->tab[0];
2389 break;
2390 case TOK_PPNUM:
2391 case TOK_STR:
2392 case TOK_LSTR:
2394 int nb_words;
2395 CString *cstr;
2397 nb_words = (sizeof(CString) + cv->cstr->size + 3) >> 2;
2398 while ((len + nb_words) > s->allocated_len)
2399 str = tok_str_realloc(s);
2400 cstr = (CString *)(str + len);
2401 cstr->data = NULL;
2402 cstr->size = cv->cstr->size;
2403 cstr->data_allocated = NULL;
2404 cstr->size_allocated = cstr->size;
2405 memcpy((char *)cstr + sizeof(CString),
2406 cv->cstr->data, cstr->size);
2407 len += nb_words;
2409 break;
2410 case TOK_CDOUBLE:
2411 case TOK_CLLONG:
2412 case TOK_CULLONG:
2413 #if LDOUBLE_SIZE == 8
2414 case TOK_CLDOUBLE:
2415 #endif
2416 str[len++] = cv->tab[0];
2417 str[len++] = cv->tab[1];
2418 break;
2419 #if LDOUBLE_SIZE == 12
2420 case TOK_CLDOUBLE:
2421 str[len++] = cv->tab[0];
2422 str[len++] = cv->tab[1];
2423 str[len++] = cv->tab[2];
2424 #elif LDOUBLE_SIZE != 8
2425 #error add long double size support
2426 #endif
2427 break;
2428 default:
2429 break;
2431 s->len = len;
2434 /* add the current parse token in token string 's' */
2435 static void tok_str_add_tok(TokenString *s)
2437 CValue cval;
2439 /* save line number info */
2440 if (file->line_num != s->last_line_num) {
2441 s->last_line_num = file->line_num;
2442 cval.i = s->last_line_num;
2443 tok_str_add2(s, TOK_LINENUM, &cval);
2445 tok_str_add2(s, tok, &tokc);
2448 #if LDOUBLE_SIZE == 12
2449 #define LDOUBLE_GET(p, cv) \
2450 cv.tab[0] = p[0]; \
2451 cv.tab[1] = p[1]; \
2452 cv.tab[2] = p[2];
2453 #elif LDOUBLE_SIZE == 8
2454 #define LDOUBLE_GET(p, cv) \
2455 cv.tab[0] = p[0]; \
2456 cv.tab[1] = p[1];
2457 #else
2458 #error add long double size support
2459 #endif
2462 /* get a token from an integer array and increment pointer
2463 accordingly. we code it as a macro to avoid pointer aliasing. */
2464 #define TOK_GET(t, p, cv) \
2466 t = *p++; \
2467 switch(t) { \
2468 case TOK_CINT: \
2469 case TOK_CUINT: \
2470 case TOK_CCHAR: \
2471 case TOK_LCHAR: \
2472 case TOK_CFLOAT: \
2473 case TOK_LINENUM: \
2474 cv.tab[0] = *p++; \
2475 break; \
2476 case TOK_STR: \
2477 case TOK_LSTR: \
2478 case TOK_PPNUM: \
2479 cv.cstr = (CString *)p; \
2480 cv.cstr->data = (char *)p + sizeof(CString);\
2481 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
2482 break; \
2483 case TOK_CDOUBLE: \
2484 case TOK_CLLONG: \
2485 case TOK_CULLONG: \
2486 cv.tab[0] = p[0]; \
2487 cv.tab[1] = p[1]; \
2488 p += 2; \
2489 break; \
2490 case TOK_CLDOUBLE: \
2491 LDOUBLE_GET(p, cv); \
2492 p += LDOUBLE_SIZE / 4; \
2493 break; \
2494 default: \
2495 break; \
2499 /* defines handling */
2500 static inline void define_push(int v, int macro_type, int *str, Sym *first_arg)
2502 Sym *s;
2504 s = sym_push2(&define_stack, v, macro_type, (int)str);
2505 s->next = first_arg;
2506 table_ident[v - TOK_IDENT]->sym_define = s;
2509 /* undefined a define symbol. Its name is just set to zero */
2510 static void define_undef(Sym *s)
2512 int v;
2513 v = s->v;
2514 if (v >= TOK_IDENT && v < tok_ident)
2515 table_ident[v - TOK_IDENT]->sym_define = NULL;
2516 s->v = 0;
2519 static inline Sym *define_find(int v)
2521 v -= TOK_IDENT;
2522 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
2523 return NULL;
2524 return table_ident[v]->sym_define;
2527 /* free define stack until top reaches 'b' */
2528 static void free_defines(Sym *b)
2530 Sym *top, *top1;
2531 int v;
2533 top = define_stack;
2534 while (top != b) {
2535 top1 = top->prev;
2536 /* do not free args or predefined defines */
2537 if (top->c)
2538 tok_str_free((int *)top->c);
2539 v = top->v;
2540 if (v >= TOK_IDENT && v < tok_ident)
2541 table_ident[v - TOK_IDENT]->sym_define = NULL;
2542 sym_free(top);
2543 top = top1;
2545 define_stack = b;
2548 /* label lookup */
2549 static Sym *label_find(int v)
2551 v -= TOK_IDENT;
2552 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
2553 return NULL;
2554 return table_ident[v]->sym_label;
2557 static Sym *label_push(Sym **ptop, int v, int flags)
2559 Sym *s, **ps;
2560 s = sym_push2(ptop, v, 0, 0);
2561 s->r = flags;
2562 ps = &table_ident[v - TOK_IDENT]->sym_label;
2563 if (ptop == &global_label_stack) {
2564 /* modify the top most local identifier, so that
2565 sym_identifier will point to 's' when popped */
2566 while (*ps != NULL)
2567 ps = &(*ps)->prev_tok;
2569 s->prev_tok = *ps;
2570 *ps = s;
2571 return s;
2574 /* pop labels until element last is reached. Look if any labels are
2575 undefined. Define symbols if '&&label' was used. */
2576 static void label_pop(Sym **ptop, Sym *slast)
2578 Sym *s, *s1;
2579 for(s = *ptop; s != slast; s = s1) {
2580 s1 = s->prev;
2581 if (s->r == LABEL_DECLARED) {
2582 warning("label '%s' declared but not used", get_tok_str(s->v, NULL));
2583 } else if (s->r == LABEL_FORWARD) {
2584 error("label '%s' used but not defined",
2585 get_tok_str(s->v, NULL));
2586 } else {
2587 if (s->c) {
2588 /* define corresponding symbol. A size of
2589 1 is put. */
2590 put_extern_sym(s, cur_text_section, (long)s->next, 1);
2593 /* remove label */
2594 table_ident[s->v - TOK_IDENT]->sym_label = s->prev_tok;
2595 sym_free(s);
2597 *ptop = slast;
2600 /* eval an expression for #if/#elif */
2601 static int expr_preprocess(void)
2603 int c, t;
2604 TokenString str;
2606 tok_str_new(&str);
2607 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
2608 next(); /* do macro subst */
2609 if (tok == TOK_DEFINED) {
2610 next_nomacro();
2611 t = tok;
2612 if (t == '(')
2613 next_nomacro();
2614 c = define_find(tok) != 0;
2615 if (t == '(')
2616 next_nomacro();
2617 tok = TOK_CINT;
2618 tokc.i = c;
2619 } else if (tok >= TOK_IDENT) {
2620 /* if undefined macro */
2621 tok = TOK_CINT;
2622 tokc.i = 0;
2624 tok_str_add_tok(&str);
2626 tok_str_add(&str, -1); /* simulate end of file */
2627 tok_str_add(&str, 0);
2628 /* now evaluate C constant expression */
2629 macro_ptr = str.str;
2630 next();
2631 c = expr_const();
2632 macro_ptr = NULL;
2633 tok_str_free(str.str);
2634 return c != 0;
2637 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2638 static void tok_print(int *str)
2640 int t;
2641 CValue cval;
2643 while (1) {
2644 TOK_GET(t, str, cval);
2645 if (!t)
2646 break;
2647 printf(" %s", get_tok_str(t, &cval));
2649 printf("\n");
2651 #endif
2653 /* parse after #define */
2654 static void parse_define(void)
2656 Sym *s, *first, **ps;
2657 int v, t, varg, is_vaargs, c;
2658 TokenString str;
2660 v = tok;
2661 if (v < TOK_IDENT)
2662 error("invalid macro name '%s'", get_tok_str(tok, &tokc));
2663 /* XXX: should check if same macro (ANSI) */
2664 first = NULL;
2665 t = MACRO_OBJ;
2666 /* '(' must be just after macro definition for MACRO_FUNC */
2667 c = file->buf_ptr[0];
2668 if (c == '\\')
2669 c = handle_stray1(file->buf_ptr);
2670 if (c == '(') {
2671 next_nomacro();
2672 next_nomacro();
2673 ps = &first;
2674 while (tok != ')') {
2675 varg = tok;
2676 next_nomacro();
2677 is_vaargs = 0;
2678 if (varg == TOK_DOTS) {
2679 varg = TOK___VA_ARGS__;
2680 is_vaargs = 1;
2681 } else if (tok == TOK_DOTS && gnu_ext) {
2682 is_vaargs = 1;
2683 next_nomacro();
2685 if (varg < TOK_IDENT)
2686 error("badly punctuated parameter list");
2687 s = sym_push2(&define_stack, varg | SYM_FIELD, is_vaargs, 0);
2688 *ps = s;
2689 ps = &s->next;
2690 if (tok != ',')
2691 break;
2692 next_nomacro();
2694 t = MACRO_FUNC;
2696 tok_str_new(&str);
2697 next_nomacro();
2698 /* EOF testing necessary for '-D' handling */
2699 while (tok != TOK_LINEFEED && tok != TOK_EOF) {
2700 tok_str_add2(&str, tok, &tokc);
2701 next_nomacro();
2703 tok_str_add(&str, 0);
2704 #ifdef PP_DEBUG
2705 printf("define %s %d: ", get_tok_str(v, NULL), t);
2706 tok_print(str.str);
2707 #endif
2708 define_push(v, t, str.str, first);
2711 static inline int hash_cached_include(int type, const char *filename)
2713 const unsigned char *s;
2714 unsigned int h;
2716 h = TOK_HASH_INIT;
2717 h = TOK_HASH_FUNC(h, type);
2718 s = filename;
2719 while (*s) {
2720 h = TOK_HASH_FUNC(h, *s);
2721 s++;
2723 h &= (CACHED_INCLUDES_HASH_SIZE - 1);
2724 return h;
2727 /* XXX: use a token or a hash table to accelerate matching ? */
2728 static CachedInclude *search_cached_include(TCCState *s1,
2729 int type, const char *filename)
2731 CachedInclude *e;
2732 int i, h;
2733 h = hash_cached_include(type, filename);
2734 i = s1->cached_includes_hash[h];
2735 for(;;) {
2736 if (i == 0)
2737 break;
2738 e = s1->cached_includes[i - 1];
2739 if (e->type == type && !strcmp(e->filename, filename))
2740 return e;
2741 i = e->hash_next;
2743 return NULL;
2746 static inline void add_cached_include(TCCState *s1, int type,
2747 const char *filename, int ifndef_macro)
2749 CachedInclude *e;
2750 int h;
2752 if (search_cached_include(s1, type, filename))
2753 return;
2754 #ifdef INC_DEBUG
2755 printf("adding cached '%s' %s\n", filename, get_tok_str(ifndef_macro, NULL));
2756 #endif
2757 e = tcc_malloc(sizeof(CachedInclude) + strlen(filename));
2758 if (!e)
2759 return;
2760 e->type = type;
2761 strcpy(e->filename, filename);
2762 e->ifndef_macro = ifndef_macro;
2763 dynarray_add((void ***)&s1->cached_includes, &s1->nb_cached_includes, e);
2764 /* add in hash table */
2765 h = hash_cached_include(type, filename);
2766 e->hash_next = s1->cached_includes_hash[h];
2767 s1->cached_includes_hash[h] = s1->nb_cached_includes;
2770 static void pragma_parse(TCCState *s1)
2772 int val;
2774 next();
2775 if (tok == TOK_pack) {
2777 This may be:
2778 #pragma pack(1) // set
2779 #pragma pack() // reset to default
2780 #pragma pack(push,1) // push & set
2781 #pragma pack(pop) // restore previous
2783 next();
2784 skip('(');
2785 if (tok == TOK_ASM_pop) {
2786 next();
2787 if (s1->pack_stack_ptr <= s1->pack_stack) {
2788 stk_error:
2789 error("out of pack stack");
2791 s1->pack_stack_ptr--;
2792 } else {
2793 val = 0;
2794 if (tok != ')') {
2795 if (tok == TOK_ASM_push) {
2796 next();
2797 if (s1->pack_stack_ptr >= s1->pack_stack + PACK_STACK_SIZE - 1)
2798 goto stk_error;
2799 s1->pack_stack_ptr++;
2800 skip(',');
2802 if (tok != TOK_CINT) {
2803 pack_error:
2804 error("invalid pack pragma");
2806 val = tokc.i;
2807 if (val < 1 || val > 16 || (val & (val - 1)) != 0)
2808 goto pack_error;
2809 next();
2811 *s1->pack_stack_ptr = val;
2812 skip(')');
2817 /* is_bof is true if first non space token at beginning of file */
2818 static void preprocess(int is_bof)
2820 TCCState *s1 = tcc_state;
2821 int size, i, c, n, saved_parse_flags;
2822 char buf[1024], *q, *p;
2823 char buf1[1024];
2824 BufferedFile *f;
2825 Sym *s;
2826 CachedInclude *e;
2828 saved_parse_flags = parse_flags;
2829 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM |
2830 PARSE_FLAG_LINEFEED;
2831 next_nomacro();
2832 redo:
2833 switch(tok) {
2834 case TOK_DEFINE:
2835 next_nomacro();
2836 parse_define();
2837 break;
2838 case TOK_UNDEF:
2839 next_nomacro();
2840 s = define_find(tok);
2841 /* undefine symbol by putting an invalid name */
2842 if (s)
2843 define_undef(s);
2844 break;
2845 case TOK_INCLUDE:
2846 case TOK_INCLUDE_NEXT:
2847 ch = file->buf_ptr[0];
2848 /* XXX: incorrect if comments : use next_nomacro with a special mode */
2849 skip_spaces();
2850 if (ch == '<') {
2851 c = '>';
2852 goto read_name;
2853 } else if (ch == '\"') {
2854 c = ch;
2855 read_name:
2856 /* XXX: better stray handling */
2857 minp();
2858 q = buf;
2859 while (ch != c && ch != '\n' && ch != CH_EOF) {
2860 if ((q - buf) < sizeof(buf) - 1)
2861 *q++ = ch;
2862 minp();
2864 *q = '\0';
2865 minp();
2866 #if 0
2867 /* eat all spaces and comments after include */
2868 /* XXX: slightly incorrect */
2869 while (ch1 != '\n' && ch1 != CH_EOF)
2870 inp();
2871 #endif
2872 } else {
2873 /* computed #include : either we have only strings or
2874 we have anything enclosed in '<>' */
2875 next();
2876 buf[0] = '\0';
2877 if (tok == TOK_STR) {
2878 while (tok != TOK_LINEFEED) {
2879 if (tok != TOK_STR) {
2880 include_syntax:
2881 error("'#include' expects \"FILENAME\" or <FILENAME>");
2883 pstrcat(buf, sizeof(buf), (char *)tokc.cstr->data);
2884 next();
2886 c = '\"';
2887 } else {
2888 int len;
2889 while (tok != TOK_LINEFEED) {
2890 pstrcat(buf, sizeof(buf), get_tok_str(tok, &tokc));
2891 next();
2893 len = strlen(buf);
2894 /* check syntax and remove '<>' */
2895 if (len < 2 || buf[0] != '<' || buf[len - 1] != '>')
2896 goto include_syntax;
2897 memmove(buf, buf + 1, len - 2);
2898 buf[len - 2] = '\0';
2899 c = '>';
2903 e = search_cached_include(s1, c, buf);
2904 if (e && define_find(e->ifndef_macro)) {
2905 /* no need to parse the include because the 'ifndef macro'
2906 is defined */
2907 #ifdef INC_DEBUG
2908 printf("%s: skipping %s\n", file->filename, buf);
2909 #endif
2910 } else {
2911 if (c == '\"') {
2912 /* first search in current dir if "header.h" */
2913 size = 0;
2914 p = strrchr(file->filename, '/');
2915 if (p)
2916 size = p + 1 - file->filename;
2917 if (size > sizeof(buf1) - 1)
2918 size = sizeof(buf1) - 1;
2919 memcpy(buf1, file->filename, size);
2920 buf1[size] = '\0';
2921 pstrcat(buf1, sizeof(buf1), buf);
2922 f = tcc_open(s1, buf1);
2923 if (f) {
2924 if (tok == TOK_INCLUDE_NEXT)
2925 tok = TOK_INCLUDE;
2926 else
2927 goto found;
2930 if (s1->include_stack_ptr >= s1->include_stack + INCLUDE_STACK_SIZE)
2931 error("#include recursion too deep");
2932 /* now search in all the include paths */
2933 n = s1->nb_include_paths + s1->nb_sysinclude_paths;
2934 for(i = 0; i < n; i++) {
2935 const char *path;
2936 if (i < s1->nb_include_paths)
2937 path = s1->include_paths[i];
2938 else
2939 path = s1->sysinclude_paths[i - s1->nb_include_paths];
2940 pstrcpy(buf1, sizeof(buf1), path);
2941 pstrcat(buf1, sizeof(buf1), "/");
2942 pstrcat(buf1, sizeof(buf1), buf);
2943 f = tcc_open(s1, buf1);
2944 if (f) {
2945 if (tok == TOK_INCLUDE_NEXT)
2946 tok = TOK_INCLUDE;
2947 else
2948 goto found;
2951 error("include file '%s' not found", buf);
2952 f = NULL;
2953 found:
2954 #ifdef INC_DEBUG
2955 printf("%s: including %s\n", file->filename, buf1);
2956 #endif
2957 f->inc_type = c;
2958 pstrcpy(f->inc_filename, sizeof(f->inc_filename), buf);
2959 /* push current file in stack */
2960 /* XXX: fix current line init */
2961 *s1->include_stack_ptr++ = file;
2962 file = f;
2963 /* add include file debug info */
2964 if (do_debug) {
2965 put_stabs(file->filename, N_BINCL, 0, 0, 0);
2967 tok_flags |= TOK_FLAG_BOF | TOK_FLAG_BOL;
2968 ch = file->buf_ptr[0];
2969 goto the_end;
2971 break;
2972 case TOK_IFNDEF:
2973 c = 1;
2974 goto do_ifdef;
2975 case TOK_IF:
2976 c = expr_preprocess();
2977 goto do_if;
2978 case TOK_IFDEF:
2979 c = 0;
2980 do_ifdef:
2981 next_nomacro();
2982 if (tok < TOK_IDENT)
2983 error("invalid argument for '#if%sdef'", c ? "n" : "");
2984 if (is_bof) {
2985 if (c) {
2986 #ifdef INC_DEBUG
2987 printf("#ifndef %s\n", get_tok_str(tok, NULL));
2988 #endif
2989 file->ifndef_macro = tok;
2992 c = (define_find(tok) != 0) ^ c;
2993 do_if:
2994 if (s1->ifdef_stack_ptr >= s1->ifdef_stack + IFDEF_STACK_SIZE)
2995 error("memory full");
2996 *s1->ifdef_stack_ptr++ = c;
2997 goto test_skip;
2998 case TOK_ELSE:
2999 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
3000 error("#else without matching #if");
3001 if (s1->ifdef_stack_ptr[-1] & 2)
3002 error("#else after #else");
3003 c = (s1->ifdef_stack_ptr[-1] ^= 3);
3004 goto test_skip;
3005 case TOK_ELIF:
3006 if (s1->ifdef_stack_ptr == s1->ifdef_stack)
3007 error("#elif without matching #if");
3008 c = s1->ifdef_stack_ptr[-1];
3009 if (c > 1)
3010 error("#elif after #else");
3011 /* last #if/#elif expression was true: we skip */
3012 if (c == 1)
3013 goto skip;
3014 c = expr_preprocess();
3015 s1->ifdef_stack_ptr[-1] = c;
3016 test_skip:
3017 if (!(c & 1)) {
3018 skip:
3019 preprocess_skip();
3020 is_bof = 0;
3021 goto redo;
3023 break;
3024 case TOK_ENDIF:
3025 if (s1->ifdef_stack_ptr <= file->ifdef_stack_ptr)
3026 error("#endif without matching #if");
3027 s1->ifdef_stack_ptr--;
3028 /* '#ifndef macro' was at the start of file. Now we check if
3029 an '#endif' is exactly at the end of file */
3030 if (file->ifndef_macro &&
3031 s1->ifdef_stack_ptr == file->ifdef_stack_ptr) {
3032 file->ifndef_macro_saved = file->ifndef_macro;
3033 /* need to set to zero to avoid false matches if another
3034 #ifndef at middle of file */
3035 file->ifndef_macro = 0;
3036 while (tok != TOK_LINEFEED)
3037 next_nomacro();
3038 tok_flags |= TOK_FLAG_ENDIF;
3039 goto the_end;
3041 break;
3042 case TOK_LINE:
3043 next();
3044 if (tok != TOK_CINT)
3045 error("#line");
3046 file->line_num = tokc.i - 1; /* the line number will be incremented after */
3047 next();
3048 if (tok != TOK_LINEFEED) {
3049 if (tok != TOK_STR)
3050 error("#line");
3051 pstrcpy(file->filename, sizeof(file->filename),
3052 (char *)tokc.cstr->data);
3054 break;
3055 case TOK_ERROR:
3056 case TOK_WARNING:
3057 c = tok;
3058 ch = file->buf_ptr[0];
3059 skip_spaces();
3060 q = buf;
3061 while (ch != '\n' && ch != CH_EOF) {
3062 if ((q - buf) < sizeof(buf) - 1)
3063 *q++ = ch;
3064 minp();
3066 *q = '\0';
3067 if (c == TOK_ERROR)
3068 error("#error %s", buf);
3069 else
3070 warning("#warning %s", buf);
3071 break;
3072 case TOK_PRAGMA:
3073 pragma_parse(s1);
3074 break;
3075 default:
3076 if (tok == TOK_LINEFEED || tok == '!' || tok == TOK_CINT) {
3077 /* '!' is ignored to allow C scripts. numbers are ignored
3078 to emulate cpp behaviour */
3079 } else {
3080 if (!(saved_parse_flags & PARSE_FLAG_ASM_COMMENTS))
3081 error("invalid preprocessing directive #%s", get_tok_str(tok, &tokc));
3083 break;
3085 /* ignore other preprocess commands or #! for C scripts */
3086 while (tok != TOK_LINEFEED)
3087 next_nomacro();
3088 the_end:
3089 parse_flags = saved_parse_flags;
3092 /* evaluate escape codes in a string. */
3093 static void parse_escape_string(CString *outstr, const uint8_t *buf, int is_long)
3095 int c, n;
3096 const uint8_t *p;
3098 p = buf;
3099 for(;;) {
3100 c = *p;
3101 if (c == '\0')
3102 break;
3103 if (c == '\\') {
3104 p++;
3105 /* escape */
3106 c = *p;
3107 switch(c) {
3108 case '0': case '1': case '2': case '3':
3109 case '4': case '5': case '6': case '7':
3110 /* at most three octal digits */
3111 n = c - '0';
3112 p++;
3113 c = *p;
3114 if (isoct(c)) {
3115 n = n * 8 + c - '0';
3116 p++;
3117 c = *p;
3118 if (isoct(c)) {
3119 n = n * 8 + c - '0';
3120 p++;
3123 c = n;
3124 goto add_char_nonext;
3125 case 'x':
3126 p++;
3127 n = 0;
3128 for(;;) {
3129 c = *p;
3130 if (c >= 'a' && c <= 'f')
3131 c = c - 'a' + 10;
3132 else if (c >= 'A' && c <= 'F')
3133 c = c - 'A' + 10;
3134 else if (isnum(c))
3135 c = c - '0';
3136 else
3137 break;
3138 n = n * 16 + c;
3139 p++;
3141 c = n;
3142 goto add_char_nonext;
3143 case 'a':
3144 c = '\a';
3145 break;
3146 case 'b':
3147 c = '\b';
3148 break;
3149 case 'f':
3150 c = '\f';
3151 break;
3152 case 'n':
3153 c = '\n';
3154 break;
3155 case 'r':
3156 c = '\r';
3157 break;
3158 case 't':
3159 c = '\t';
3160 break;
3161 case 'v':
3162 c = '\v';
3163 break;
3164 case 'e':
3165 if (!gnu_ext)
3166 goto invalid_escape;
3167 c = 27;
3168 break;
3169 case '\'':
3170 case '\"':
3171 case '\\':
3172 case '?':
3173 break;
3174 default:
3175 invalid_escape:
3176 if (c >= '!' && c <= '~')
3177 warning("unknown escape sequence: \'\\%c\'", c);
3178 else
3179 warning("unknown escape sequence: \'\\x%x\'", c);
3180 break;
3183 p++;
3184 add_char_nonext:
3185 if (!is_long)
3186 cstr_ccat(outstr, c);
3187 else
3188 cstr_wccat(outstr, c);
3190 /* add a trailing '\0' */
3191 if (!is_long)
3192 cstr_ccat(outstr, '\0');
3193 else
3194 cstr_wccat(outstr, '\0');
3197 /* we use 64 bit numbers */
3198 #define BN_SIZE 2
3200 /* bn = (bn << shift) | or_val */
3201 void bn_lshift(unsigned int *bn, int shift, int or_val)
3203 int i;
3204 unsigned int v;
3205 for(i=0;i<BN_SIZE;i++) {
3206 v = bn[i];
3207 bn[i] = (v << shift) | or_val;
3208 or_val = v >> (32 - shift);
3212 void bn_zero(unsigned int *bn)
3214 int i;
3215 for(i=0;i<BN_SIZE;i++) {
3216 bn[i] = 0;
3220 /* parse number in null terminated string 'p' and return it in the
3221 current token */
3222 void parse_number(const char *p)
3224 int b, t, shift, frac_bits, s, exp_val, ch;
3225 char *q;
3226 unsigned int bn[BN_SIZE];
3227 double d;
3229 /* number */
3230 q = token_buf;
3231 ch = *p++;
3232 t = ch;
3233 ch = *p++;
3234 *q++ = t;
3235 b = 10;
3236 if (t == '.') {
3237 goto float_frac_parse;
3238 } else if (t == '0') {
3239 if (ch == 'x' || ch == 'X') {
3240 q--;
3241 ch = *p++;
3242 b = 16;
3243 } else if (tcc_ext && (ch == 'b' || ch == 'B')) {
3244 q--;
3245 ch = *p++;
3246 b = 2;
3249 /* parse all digits. cannot check octal numbers at this stage
3250 because of floating point constants */
3251 while (1) {
3252 if (ch >= 'a' && ch <= 'f')
3253 t = ch - 'a' + 10;
3254 else if (ch >= 'A' && ch <= 'F')
3255 t = ch - 'A' + 10;
3256 else if (isnum(ch))
3257 t = ch - '0';
3258 else
3259 break;
3260 if (t >= b)
3261 break;
3262 if (q >= token_buf + STRING_MAX_SIZE) {
3263 num_too_long:
3264 error("number too long");
3266 *q++ = ch;
3267 ch = *p++;
3269 if (ch == '.' ||
3270 ((ch == 'e' || ch == 'E') && b == 10) ||
3271 ((ch == 'p' || ch == 'P') && (b == 16 || b == 2))) {
3272 if (b != 10) {
3273 /* NOTE: strtox should support that for hexa numbers, but
3274 non ISOC99 libcs do not support it, so we prefer to do
3275 it by hand */
3276 /* hexadecimal or binary floats */
3277 /* XXX: handle overflows */
3278 *q = '\0';
3279 if (b == 16)
3280 shift = 4;
3281 else
3282 shift = 2;
3283 bn_zero(bn);
3284 q = token_buf;
3285 while (1) {
3286 t = *q++;
3287 if (t == '\0') {
3288 break;
3289 } else if (t >= 'a') {
3290 t = t - 'a' + 10;
3291 } else if (t >= 'A') {
3292 t = t - 'A' + 10;
3293 } else {
3294 t = t - '0';
3296 bn_lshift(bn, shift, t);
3298 frac_bits = 0;
3299 if (ch == '.') {
3300 ch = *p++;
3301 while (1) {
3302 t = ch;
3303 if (t >= 'a' && t <= 'f') {
3304 t = t - 'a' + 10;
3305 } else if (t >= 'A' && t <= 'F') {
3306 t = t - 'A' + 10;
3307 } else if (t >= '0' && t <= '9') {
3308 t = t - '0';
3309 } else {
3310 break;
3312 if (t >= b)
3313 error("invalid digit");
3314 bn_lshift(bn, shift, t);
3315 frac_bits += shift;
3316 ch = *p++;
3319 if (ch != 'p' && ch != 'P')
3320 expect("exponent");
3321 ch = *p++;
3322 s = 1;
3323 exp_val = 0;
3324 if (ch == '+') {
3325 ch = *p++;
3326 } else if (ch == '-') {
3327 s = -1;
3328 ch = *p++;
3330 if (ch < '0' || ch > '9')
3331 expect("exponent digits");
3332 while (ch >= '0' && ch <= '9') {
3333 exp_val = exp_val * 10 + ch - '0';
3334 ch = *p++;
3336 exp_val = exp_val * s;
3338 /* now we can generate the number */
3339 /* XXX: should patch directly float number */
3340 d = (double)bn[1] * 4294967296.0 + (double)bn[0];
3341 d = ldexp(d, exp_val - frac_bits);
3342 t = toup(ch);
3343 if (t == 'F') {
3344 ch = *p++;
3345 tok = TOK_CFLOAT;
3346 /* float : should handle overflow */
3347 tokc.f = (float)d;
3348 } else if (t == 'L') {
3349 ch = *p++;
3350 tok = TOK_CLDOUBLE;
3351 /* XXX: not large enough */
3352 tokc.ld = (long double)d;
3353 } else {
3354 tok = TOK_CDOUBLE;
3355 tokc.d = d;
3357 } else {
3358 /* decimal floats */
3359 if (ch == '.') {
3360 if (q >= token_buf + STRING_MAX_SIZE)
3361 goto num_too_long;
3362 *q++ = ch;
3363 ch = *p++;
3364 float_frac_parse:
3365 while (ch >= '0' && ch <= '9') {
3366 if (q >= token_buf + STRING_MAX_SIZE)
3367 goto num_too_long;
3368 *q++ = ch;
3369 ch = *p++;
3372 if (ch == 'e' || ch == 'E') {
3373 if (q >= token_buf + STRING_MAX_SIZE)
3374 goto num_too_long;
3375 *q++ = ch;
3376 ch = *p++;
3377 if (ch == '-' || ch == '+') {
3378 if (q >= token_buf + STRING_MAX_SIZE)
3379 goto num_too_long;
3380 *q++ = ch;
3381 ch = *p++;
3383 if (ch < '0' || ch > '9')
3384 expect("exponent digits");
3385 while (ch >= '0' && ch <= '9') {
3386 if (q >= token_buf + STRING_MAX_SIZE)
3387 goto num_too_long;
3388 *q++ = ch;
3389 ch = *p++;
3392 *q = '\0';
3393 t = toup(ch);
3394 errno = 0;
3395 if (t == 'F') {
3396 ch = *p++;
3397 tok = TOK_CFLOAT;
3398 tokc.f = strtof(token_buf, NULL);
3399 } else if (t == 'L') {
3400 ch = *p++;
3401 tok = TOK_CLDOUBLE;
3402 tokc.ld = strtold(token_buf, NULL);
3403 } else {
3404 tok = TOK_CDOUBLE;
3405 tokc.d = strtod(token_buf, NULL);
3408 } else {
3409 unsigned long long n, n1;
3410 int lcount, ucount;
3412 /* integer number */
3413 *q = '\0';
3414 q = token_buf;
3415 if (b == 10 && *q == '0') {
3416 b = 8;
3417 q++;
3419 n = 0;
3420 while(1) {
3421 t = *q++;
3422 /* no need for checks except for base 10 / 8 errors */
3423 if (t == '\0') {
3424 break;
3425 } else if (t >= 'a') {
3426 t = t - 'a' + 10;
3427 } else if (t >= 'A') {
3428 t = t - 'A' + 10;
3429 } else {
3430 t = t - '0';
3431 if (t >= b)
3432 error("invalid digit");
3434 n1 = n;
3435 n = n * b + t;
3436 /* detect overflow */
3437 /* XXX: this test is not reliable */
3438 if (n < n1)
3439 error("integer constant overflow");
3442 /* XXX: not exactly ANSI compliant */
3443 if ((n & 0xffffffff00000000LL) != 0) {
3444 if ((n >> 63) != 0)
3445 tok = TOK_CULLONG;
3446 else
3447 tok = TOK_CLLONG;
3448 } else if (n > 0x7fffffff) {
3449 tok = TOK_CUINT;
3450 } else {
3451 tok = TOK_CINT;
3453 lcount = 0;
3454 ucount = 0;
3455 for(;;) {
3456 t = toup(ch);
3457 if (t == 'L') {
3458 if (lcount >= 2)
3459 error("three 'l's in integer constant");
3460 lcount++;
3461 if (lcount == 2) {
3462 if (tok == TOK_CINT)
3463 tok = TOK_CLLONG;
3464 else if (tok == TOK_CUINT)
3465 tok = TOK_CULLONG;
3467 ch = *p++;
3468 } else if (t == 'U') {
3469 if (ucount >= 1)
3470 error("two 'u's in integer constant");
3471 ucount++;
3472 if (tok == TOK_CINT)
3473 tok = TOK_CUINT;
3474 else if (tok == TOK_CLLONG)
3475 tok = TOK_CULLONG;
3476 ch = *p++;
3477 } else {
3478 break;
3481 if (tok == TOK_CINT || tok == TOK_CUINT)
3482 tokc.ui = n;
3483 else
3484 tokc.ull = n;
3489 #define PARSE2(c1, tok1, c2, tok2) \
3490 case c1: \
3491 PEEKC(c, p); \
3492 if (c == c2) { \
3493 p++; \
3494 tok = tok2; \
3495 } else { \
3496 tok = tok1; \
3498 break;
3500 /* return next token without macro substitution */
3501 static inline void next_nomacro1(void)
3503 int t, c, is_long;
3504 TokenSym *ts;
3505 uint8_t *p, *p1;
3506 unsigned int h;
3508 p = file->buf_ptr;
3509 redo_no_start:
3510 c = *p;
3511 switch(c) {
3512 case ' ':
3513 case '\t':
3514 case '\f':
3515 case '\v':
3516 case '\r':
3517 p++;
3518 goto redo_no_start;
3520 case '\\':
3521 /* first look if it is in fact an end of buffer */
3522 if (p >= file->buf_end) {
3523 file->buf_ptr = p;
3524 handle_eob();
3525 p = file->buf_ptr;
3526 if (p >= file->buf_end)
3527 goto parse_eof;
3528 else
3529 goto redo_no_start;
3530 } else {
3531 file->buf_ptr = p;
3532 ch = *p;
3533 handle_stray();
3534 p = file->buf_ptr;
3535 goto redo_no_start;
3537 parse_eof:
3539 TCCState *s1 = tcc_state;
3540 if (parse_flags & PARSE_FLAG_LINEFEED) {
3541 tok = TOK_LINEFEED;
3542 } else if (s1->include_stack_ptr == s1->include_stack ||
3543 !(parse_flags & PARSE_FLAG_PREPROCESS)) {
3544 /* no include left : end of file. */
3545 tok = TOK_EOF;
3546 } else {
3547 /* pop include file */
3549 /* test if previous '#endif' was after a #ifdef at
3550 start of file */
3551 if (tok_flags & TOK_FLAG_ENDIF) {
3552 #ifdef INC_DEBUG
3553 printf("#endif %s\n", get_tok_str(file->ifndef_macro_saved, NULL));
3554 #endif
3555 add_cached_include(s1, file->inc_type, file->inc_filename,
3556 file->ifndef_macro_saved);
3559 /* add end of include file debug info */
3560 if (do_debug) {
3561 put_stabd(N_EINCL, 0, 0);
3563 /* pop include stack */
3564 tcc_close(file);
3565 s1->include_stack_ptr--;
3566 file = *s1->include_stack_ptr;
3567 p = file->buf_ptr;
3568 goto redo_no_start;
3571 break;
3573 case '\n':
3574 if (parse_flags & PARSE_FLAG_LINEFEED) {
3575 tok = TOK_LINEFEED;
3576 } else {
3577 file->line_num++;
3578 tok_flags |= TOK_FLAG_BOL;
3579 p++;
3580 goto redo_no_start;
3582 break;
3584 case '#':
3585 /* XXX: simplify */
3586 PEEKC(c, p);
3587 if ((tok_flags & TOK_FLAG_BOL) &&
3588 (parse_flags & PARSE_FLAG_PREPROCESS)) {
3589 file->buf_ptr = p;
3590 preprocess(tok_flags & TOK_FLAG_BOF);
3591 p = file->buf_ptr;
3592 goto redo_no_start;
3593 } else {
3594 if (c == '#') {
3595 p++;
3596 tok = TOK_TWOSHARPS;
3597 } else {
3598 if (parse_flags & PARSE_FLAG_ASM_COMMENTS) {
3599 p = parse_line_comment(p - 1);
3600 goto redo_no_start;
3601 } else {
3602 tok = '#';
3606 break;
3608 case 'a': case 'b': case 'c': case 'd':
3609 case 'e': case 'f': case 'g': case 'h':
3610 case 'i': case 'j': case 'k': case 'l':
3611 case 'm': case 'n': case 'o': case 'p':
3612 case 'q': case 'r': case 's': case 't':
3613 case 'u': case 'v': case 'w': case 'x':
3614 case 'y': case 'z':
3615 case 'A': case 'B': case 'C': case 'D':
3616 case 'E': case 'F': case 'G': case 'H':
3617 case 'I': case 'J': case 'K':
3618 case 'M': case 'N': case 'O': case 'P':
3619 case 'Q': case 'R': case 'S': case 'T':
3620 case 'U': case 'V': case 'W': case 'X':
3621 case 'Y': case 'Z':
3622 case '_':
3623 parse_ident_fast:
3624 p1 = p;
3625 h = TOK_HASH_INIT;
3626 h = TOK_HASH_FUNC(h, c);
3627 p++;
3628 for(;;) {
3629 c = *p;
3630 if (!isidnum_table[c])
3631 break;
3632 h = TOK_HASH_FUNC(h, c);
3633 p++;
3635 if (c != '\\') {
3636 TokenSym **pts;
3637 int len;
3639 /* fast case : no stray found, so we have the full token
3640 and we have already hashed it */
3641 len = p - p1;
3642 h &= (TOK_HASH_SIZE - 1);
3643 pts = &hash_ident[h];
3644 for(;;) {
3645 ts = *pts;
3646 if (!ts)
3647 break;
3648 if (ts->len == len && !memcmp(ts->str, p1, len))
3649 goto token_found;
3650 pts = &(ts->hash_next);
3652 ts = tok_alloc_new(pts, p1, len);
3653 token_found: ;
3654 } else {
3655 /* slower case */
3656 cstr_reset(&tokcstr);
3658 while (p1 < p) {
3659 cstr_ccat(&tokcstr, *p1);
3660 p1++;
3662 p--;
3663 PEEKC(c, p);
3664 parse_ident_slow:
3665 while (isidnum_table[c]) {
3666 cstr_ccat(&tokcstr, c);
3667 PEEKC(c, p);
3669 ts = tok_alloc(tokcstr.data, tokcstr.size);
3671 tok = ts->tok;
3672 break;
3673 case 'L':
3674 t = p[1];
3675 if (t != '\\' && t != '\'' && t != '\"') {
3676 /* fast case */
3677 goto parse_ident_fast;
3678 } else {
3679 PEEKC(c, p);
3680 if (c == '\'' || c == '\"') {
3681 is_long = 1;
3682 goto str_const;
3683 } else {
3684 cstr_reset(&tokcstr);
3685 cstr_ccat(&tokcstr, 'L');
3686 goto parse_ident_slow;
3689 break;
3690 case '0': case '1': case '2': case '3':
3691 case '4': case '5': case '6': case '7':
3692 case '8': case '9':
3694 cstr_reset(&tokcstr);
3695 /* after the first digit, accept digits, alpha, '.' or sign if
3696 prefixed by 'eEpP' */
3697 parse_num:
3698 for(;;) {
3699 t = c;
3700 cstr_ccat(&tokcstr, c);
3701 PEEKC(c, p);
3702 if (!(isnum(c) || isid(c) || c == '.' ||
3703 ((c == '+' || c == '-') &&
3704 (t == 'e' || t == 'E' || t == 'p' || t == 'P'))))
3705 break;
3707 /* We add a trailing '\0' to ease parsing */
3708 cstr_ccat(&tokcstr, '\0');
3709 tokc.cstr = &tokcstr;
3710 tok = TOK_PPNUM;
3711 break;
3712 case '.':
3713 /* special dot handling because it can also start a number */
3714 PEEKC(c, p);
3715 if (isnum(c)) {
3716 cstr_reset(&tokcstr);
3717 cstr_ccat(&tokcstr, '.');
3718 goto parse_num;
3719 } else if (c == '.') {
3720 PEEKC(c, p);
3721 if (c != '.')
3722 expect("'.'");
3723 PEEKC(c, p);
3724 tok = TOK_DOTS;
3725 } else {
3726 tok = '.';
3728 break;
3729 case '\'':
3730 case '\"':
3731 is_long = 0;
3732 str_const:
3734 CString str;
3735 int sep;
3737 sep = c;
3739 /* parse the string */
3740 cstr_new(&str);
3741 p = parse_pp_string(p, sep, &str);
3742 cstr_ccat(&str, '\0');
3744 /* eval the escape (should be done as TOK_PPNUM) */
3745 cstr_reset(&tokcstr);
3746 parse_escape_string(&tokcstr, str.data, is_long);
3747 cstr_free(&str);
3749 if (sep == '\'') {
3750 int char_size;
3751 /* XXX: make it portable */
3752 if (!is_long)
3753 char_size = 1;
3754 else
3755 char_size = sizeof(nwchar_t);
3756 if (tokcstr.size <= char_size)
3757 error("empty character constant");
3758 if (tokcstr.size > 2 * char_size)
3759 warning("multi-character character constant");
3760 if (!is_long) {
3761 tokc.i = *(int8_t *)tokcstr.data;
3762 tok = TOK_CCHAR;
3763 } else {
3764 tokc.i = *(nwchar_t *)tokcstr.data;
3765 tok = TOK_LCHAR;
3767 } else {
3768 tokc.cstr = &tokcstr;
3769 if (!is_long)
3770 tok = TOK_STR;
3771 else
3772 tok = TOK_LSTR;
3775 break;
3777 case '<':
3778 PEEKC(c, p);
3779 if (c == '=') {
3780 p++;
3781 tok = TOK_LE;
3782 } else if (c == '<') {
3783 PEEKC(c, p);
3784 if (c == '=') {
3785 p++;
3786 tok = TOK_A_SHL;
3787 } else {
3788 tok = TOK_SHL;
3790 } else {
3791 tok = TOK_LT;
3793 break;
3795 case '>':
3796 PEEKC(c, p);
3797 if (c == '=') {
3798 p++;
3799 tok = TOK_GE;
3800 } else if (c == '>') {
3801 PEEKC(c, p);
3802 if (c == '=') {
3803 p++;
3804 tok = TOK_A_SAR;
3805 } else {
3806 tok = TOK_SAR;
3808 } else {
3809 tok = TOK_GT;
3811 break;
3813 case '&':
3814 PEEKC(c, p);
3815 if (c == '&') {
3816 p++;
3817 tok = TOK_LAND;
3818 } else if (c == '=') {
3819 p++;
3820 tok = TOK_A_AND;
3821 } else {
3822 tok = '&';
3824 break;
3826 case '|':
3827 PEEKC(c, p);
3828 if (c == '|') {
3829 p++;
3830 tok = TOK_LOR;
3831 } else if (c == '=') {
3832 p++;
3833 tok = TOK_A_OR;
3834 } else {
3835 tok = '|';
3837 break;
3839 case '+':
3840 PEEKC(c, p);
3841 if (c == '+') {
3842 p++;
3843 tok = TOK_INC;
3844 } else if (c == '=') {
3845 p++;
3846 tok = TOK_A_ADD;
3847 } else {
3848 tok = '+';
3850 break;
3852 case '-':
3853 PEEKC(c, p);
3854 if (c == '-') {
3855 p++;
3856 tok = TOK_DEC;
3857 } else if (c == '=') {
3858 p++;
3859 tok = TOK_A_SUB;
3860 } else if (c == '>') {
3861 p++;
3862 tok = TOK_ARROW;
3863 } else {
3864 tok = '-';
3866 break;
3868 PARSE2('!', '!', '=', TOK_NE)
3869 PARSE2('=', '=', '=', TOK_EQ)
3870 PARSE2('*', '*', '=', TOK_A_MUL)
3871 PARSE2('%', '%', '=', TOK_A_MOD)
3872 PARSE2('^', '^', '=', TOK_A_XOR)
3874 /* comments or operator */
3875 case '/':
3876 PEEKC(c, p);
3877 if (c == '*') {
3878 p = parse_comment(p);
3879 goto redo_no_start;
3880 } else if (c == '/') {
3881 p = parse_line_comment(p);
3882 goto redo_no_start;
3883 } else if (c == '=') {
3884 p++;
3885 tok = TOK_A_DIV;
3886 } else {
3887 tok = '/';
3889 break;
3891 /* simple tokens */
3892 case '(':
3893 case ')':
3894 case '[':
3895 case ']':
3896 case '{':
3897 case '}':
3898 case ',':
3899 case ';':
3900 case ':':
3901 case '?':
3902 case '~':
3903 case '$': /* only used in assembler */
3904 case '@': /* dito */
3905 tok = c;
3906 p++;
3907 break;
3908 default:
3909 error("unrecognized character \\x%02x", c);
3910 break;
3912 file->buf_ptr = p;
3913 tok_flags = 0;
3914 #if defined(PARSE_DEBUG)
3915 printf("token = %s\n", get_tok_str(tok, &tokc));
3916 #endif
3919 /* return next token without macro substitution. Can read input from
3920 macro_ptr buffer */
3921 static void next_nomacro(void)
3923 if (macro_ptr) {
3924 redo:
3925 tok = *macro_ptr;
3926 if (tok) {
3927 TOK_GET(tok, macro_ptr, tokc);
3928 if (tok == TOK_LINENUM) {
3929 file->line_num = tokc.i;
3930 goto redo;
3933 } else {
3934 next_nomacro1();
3938 /* substitute args in macro_str and return allocated string */
3939 static int *macro_arg_subst(Sym **nested_list, int *macro_str, Sym *args)
3941 int *st, last_tok, t, notfirst;
3942 Sym *s;
3943 CValue cval;
3944 TokenString str;
3945 CString cstr;
3947 tok_str_new(&str);
3948 last_tok = 0;
3949 while(1) {
3950 TOK_GET(t, macro_str, cval);
3951 if (!t)
3952 break;
3953 if (t == '#') {
3954 /* stringize */
3955 TOK_GET(t, macro_str, cval);
3956 if (!t)
3957 break;
3958 s = sym_find2(args, t);
3959 if (s) {
3960 cstr_new(&cstr);
3961 st = (int *)s->c;
3962 notfirst = 0;
3963 while (*st) {
3964 if (notfirst)
3965 cstr_ccat(&cstr, ' ');
3966 TOK_GET(t, st, cval);
3967 cstr_cat(&cstr, get_tok_str(t, &cval));
3968 notfirst = 1;
3970 cstr_ccat(&cstr, '\0');
3971 #ifdef PP_DEBUG
3972 printf("stringize: %s\n", (char *)cstr.data);
3973 #endif
3974 /* add string */
3975 cval.cstr = &cstr;
3976 tok_str_add2(&str, TOK_STR, &cval);
3977 cstr_free(&cstr);
3978 } else {
3979 tok_str_add2(&str, t, &cval);
3981 } else if (t >= TOK_IDENT) {
3982 s = sym_find2(args, t);
3983 if (s) {
3984 st = (int *)s->c;
3985 /* if '##' is present before or after, no arg substitution */
3986 if (*macro_str == TOK_TWOSHARPS || last_tok == TOK_TWOSHARPS) {
3987 /* special case for var arg macros : ## eats the
3988 ',' if empty VA_ARGS variable. */
3989 /* XXX: test of the ',' is not 100%
3990 reliable. should fix it to avoid security
3991 problems */
3992 if (gnu_ext && s->type.t &&
3993 last_tok == TOK_TWOSHARPS &&
3994 str.len >= 2 && str.str[str.len - 2] == ',') {
3995 if (*st == 0) {
3996 /* suppress ',' '##' */
3997 str.len -= 2;
3998 } else {
3999 /* suppress '##' and add variable */
4000 str.len--;
4001 goto add_var;
4003 } else {
4004 int t1;
4005 add_var:
4006 for(;;) {
4007 TOK_GET(t1, st, cval);
4008 if (!t1)
4009 break;
4010 tok_str_add2(&str, t1, &cval);
4013 } else {
4014 /* NOTE: the stream cannot be read when macro
4015 substituing an argument */
4016 macro_subst(&str, nested_list, st, NULL);
4018 } else {
4019 tok_str_add(&str, t);
4021 } else {
4022 tok_str_add2(&str, t, &cval);
4024 last_tok = t;
4026 tok_str_add(&str, 0);
4027 return str.str;
4030 static char const ab_month_name[12][4] =
4032 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
4033 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
4036 /* do macro substitution of current token with macro 's' and add
4037 result to (tok_str,tok_len). 'nested_list' is the list of all
4038 macros we got inside to avoid recursing. Return non zero if no
4039 substitution needs to be done */
4040 static int macro_subst_tok(TokenString *tok_str,
4041 Sym **nested_list, Sym *s, struct macro_level **can_read_stream)
4043 Sym *args, *sa, *sa1;
4044 int mstr_allocated, parlevel, *mstr, t, t1;
4045 TokenString str;
4046 char *cstrval;
4047 CValue cval;
4048 CString cstr;
4049 char buf[32];
4051 /* if symbol is a macro, prepare substitution */
4052 /* special macros */
4053 if (tok == TOK___LINE__) {
4054 snprintf(buf, sizeof(buf), "%d", file->line_num);
4055 cstrval = buf;
4056 t1 = TOK_PPNUM;
4057 goto add_cstr1;
4058 } else if (tok == TOK___FILE__) {
4059 cstrval = file->filename;
4060 goto add_cstr;
4061 } else if (tok == TOK___DATE__ || tok == TOK___TIME__) {
4062 time_t ti;
4063 struct tm *tm;
4065 time(&ti);
4066 tm = localtime(&ti);
4067 if (tok == TOK___DATE__) {
4068 snprintf(buf, sizeof(buf), "%s %2d %d",
4069 ab_month_name[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900);
4070 } else {
4071 snprintf(buf, sizeof(buf), "%02d:%02d:%02d",
4072 tm->tm_hour, tm->tm_min, tm->tm_sec);
4074 cstrval = buf;
4075 add_cstr:
4076 t1 = TOK_STR;
4077 add_cstr1:
4078 cstr_new(&cstr);
4079 cstr_cat(&cstr, cstrval);
4080 cstr_ccat(&cstr, '\0');
4081 cval.cstr = &cstr;
4082 tok_str_add2(tok_str, t1, &cval);
4083 cstr_free(&cstr);
4084 } else {
4085 mstr = (int *)s->c;
4086 mstr_allocated = 0;
4087 if (s->type.t == MACRO_FUNC) {
4088 /* NOTE: we do not use next_nomacro to avoid eating the
4089 next token. XXX: find better solution */
4090 redo:
4091 if (macro_ptr) {
4092 t = *macro_ptr;
4093 if (t == 0 && can_read_stream) {
4094 /* end of macro stream: we must look at the token
4095 after in the file */
4096 struct macro_level *ml = *can_read_stream;
4097 macro_ptr = NULL;
4098 if (ml)
4100 macro_ptr = ml->p;
4101 ml->p = NULL;
4102 *can_read_stream = ml -> prev;
4104 goto redo;
4106 } else {
4107 /* XXX: incorrect with comments */
4108 ch = file->buf_ptr[0];
4109 while (is_space(ch) || ch == '\n')
4110 cinp();
4111 t = ch;
4113 if (t != '(') /* no macro subst */
4114 return -1;
4116 /* argument macro */
4117 next_nomacro();
4118 next_nomacro();
4119 args = NULL;
4120 sa = s->next;
4121 /* NOTE: empty args are allowed, except if no args */
4122 for(;;) {
4123 /* handle '()' case */
4124 if (!args && !sa && tok == ')')
4125 break;
4126 if (!sa)
4127 error("macro '%s' used with too many args",
4128 get_tok_str(s->v, 0));
4129 tok_str_new(&str);
4130 parlevel = 0;
4131 /* NOTE: non zero sa->t indicates VA_ARGS */
4132 while ((parlevel > 0 ||
4133 (tok != ')' &&
4134 (tok != ',' || sa->type.t))) &&
4135 tok != -1) {
4136 if (tok == '(')
4137 parlevel++;
4138 else if (tok == ')')
4139 parlevel--;
4140 tok_str_add2(&str, tok, &tokc);
4141 next_nomacro();
4143 tok_str_add(&str, 0);
4144 sym_push2(&args, sa->v & ~SYM_FIELD, sa->type.t, (int)str.str);
4145 sa = sa->next;
4146 if (tok == ')') {
4147 /* special case for gcc var args: add an empty
4148 var arg argument if it is omitted */
4149 if (sa && sa->type.t && gnu_ext)
4150 continue;
4151 else
4152 break;
4154 if (tok != ',')
4155 expect(",");
4156 next_nomacro();
4158 if (sa) {
4159 error("macro '%s' used with too few args",
4160 get_tok_str(s->v, 0));
4163 /* now subst each arg */
4164 mstr = macro_arg_subst(nested_list, mstr, args);
4165 /* free memory */
4166 sa = args;
4167 while (sa) {
4168 sa1 = sa->prev;
4169 tok_str_free((int *)sa->c);
4170 sym_free(sa);
4171 sa = sa1;
4173 mstr_allocated = 1;
4175 sym_push2(nested_list, s->v, 0, 0);
4176 macro_subst(tok_str, nested_list, mstr, can_read_stream);
4177 /* pop nested defined symbol */
4178 sa1 = *nested_list;
4179 *nested_list = sa1->prev;
4180 sym_free(sa1);
4181 if (mstr_allocated)
4182 tok_str_free(mstr);
4184 return 0;
4187 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4188 return the resulting string (which must be freed). */
4189 static inline int *macro_twosharps(const int *macro_str)
4191 TokenSym *ts;
4192 const int *macro_ptr1, *start_macro_ptr, *ptr, *saved_macro_ptr;
4193 int t;
4194 const char *p1, *p2;
4195 CValue cval;
4196 TokenString macro_str1;
4197 CString cstr;
4199 start_macro_ptr = macro_str;
4200 /* we search the first '##' */
4201 for(;;) {
4202 macro_ptr1 = macro_str;
4203 TOK_GET(t, macro_str, cval);
4204 /* nothing more to do if end of string */
4205 if (t == 0)
4206 return NULL;
4207 if (*macro_str == TOK_TWOSHARPS)
4208 break;
4211 /* we saw '##', so we need more processing to handle it */
4212 cstr_new(&cstr);
4213 tok_str_new(&macro_str1);
4214 tok = t;
4215 tokc = cval;
4217 /* add all tokens seen so far */
4218 for(ptr = start_macro_ptr; ptr < macro_ptr1;) {
4219 TOK_GET(t, ptr, cval);
4220 tok_str_add2(&macro_str1, t, &cval);
4222 saved_macro_ptr = macro_ptr;
4223 /* XXX: get rid of the use of macro_ptr here */
4224 macro_ptr = (int *)macro_str;
4225 for(;;) {
4226 while (*macro_ptr == TOK_TWOSHARPS) {
4227 macro_ptr++;
4228 macro_ptr1 = macro_ptr;
4229 t = *macro_ptr;
4230 if (t) {
4231 TOK_GET(t, macro_ptr, cval);
4232 /* We concatenate the two tokens if we have an
4233 identifier or a preprocessing number */
4234 cstr_reset(&cstr);
4235 p1 = get_tok_str(tok, &tokc);
4236 cstr_cat(&cstr, p1);
4237 p2 = get_tok_str(t, &cval);
4238 cstr_cat(&cstr, p2);
4239 cstr_ccat(&cstr, '\0');
4241 if ((tok >= TOK_IDENT || tok == TOK_PPNUM) &&
4242 (t >= TOK_IDENT || t == TOK_PPNUM)) {
4243 if (tok == TOK_PPNUM) {
4244 /* if number, then create a number token */
4245 /* NOTE: no need to allocate because
4246 tok_str_add2() does it */
4247 cstr_reset(&tokcstr);
4248 tokcstr = cstr;
4249 cstr_new(&cstr);
4250 tokc.cstr = &tokcstr;
4251 } else {
4252 /* if identifier, we must do a test to
4253 validate we have a correct identifier */
4254 if (t == TOK_PPNUM) {
4255 const char *p;
4256 int c;
4258 p = p2;
4259 for(;;) {
4260 c = *p;
4261 if (c == '\0')
4262 break;
4263 p++;
4264 if (!isnum(c) && !isid(c))
4265 goto error_pasting;
4268 ts = tok_alloc(cstr.data, strlen(cstr.data));
4269 tok = ts->tok; /* modify current token */
4271 } else {
4272 const char *str = cstr.data;
4273 const unsigned char *q;
4275 /* we look for a valid token */
4276 /* XXX: do more extensive checks */
4277 if (!strcmp(str, ">>=")) {
4278 tok = TOK_A_SAR;
4279 } else if (!strcmp(str, "<<=")) {
4280 tok = TOK_A_SHL;
4281 } else if (strlen(str) == 2) {
4282 /* search in two bytes table */
4283 q = tok_two_chars;
4284 for(;;) {
4285 if (!*q)
4286 goto error_pasting;
4287 if (q[0] == str[0] && q[1] == str[1])
4288 break;
4289 q += 3;
4291 tok = q[2];
4292 } else {
4293 error_pasting:
4294 /* NOTE: because get_tok_str use a static buffer,
4295 we must save it */
4296 cstr_reset(&cstr);
4297 p1 = get_tok_str(tok, &tokc);
4298 cstr_cat(&cstr, p1);
4299 cstr_ccat(&cstr, '\0');
4300 p2 = get_tok_str(t, &cval);
4301 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr.data, p2);
4302 /* cannot merge tokens: just add them separately */
4303 tok_str_add2(&macro_str1, tok, &tokc);
4304 /* XXX: free associated memory ? */
4305 tok = t;
4306 tokc = cval;
4311 tok_str_add2(&macro_str1, tok, &tokc);
4312 next_nomacro();
4313 if (tok == 0)
4314 break;
4316 macro_ptr = (int *)saved_macro_ptr;
4317 cstr_free(&cstr);
4318 tok_str_add(&macro_str1, 0);
4319 return macro_str1.str;
4323 /* do macro substitution of macro_str and add result to
4324 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4325 inside to avoid recursing. */
4326 static void macro_subst(TokenString *tok_str, Sym **nested_list,
4327 const int *macro_str, struct macro_level ** can_read_stream)
4329 Sym *s;
4330 int *macro_str1;
4331 const int *ptr;
4332 int t, ret;
4333 CValue cval;
4334 struct macro_level ml;
4336 /* first scan for '##' operator handling */
4337 ptr = macro_str;
4338 macro_str1 = macro_twosharps(ptr);
4339 if (macro_str1)
4340 ptr = macro_str1;
4341 while (1) {
4342 /* NOTE: ptr == NULL can only happen if tokens are read from
4343 file stream due to a macro function call */
4344 if (ptr == NULL)
4345 break;
4346 TOK_GET(t, ptr, cval);
4347 if (t == 0)
4348 break;
4349 s = define_find(t);
4350 if (s != NULL) {
4351 /* if nested substitution, do nothing */
4352 if (sym_find2(*nested_list, t))
4353 goto no_subst;
4354 ml.p = macro_ptr;
4355 if (can_read_stream)
4356 ml.prev = *can_read_stream, *can_read_stream = &ml;
4357 macro_ptr = (int *)ptr;
4358 tok = t;
4359 ret = macro_subst_tok(tok_str, nested_list, s, can_read_stream);
4360 ptr = (int *)macro_ptr;
4361 macro_ptr = ml.p;
4362 if (can_read_stream && *can_read_stream == &ml)
4363 *can_read_stream = ml.prev;
4364 if (ret != 0)
4365 goto no_subst;
4366 } else {
4367 no_subst:
4368 tok_str_add2(tok_str, t, &cval);
4371 if (macro_str1)
4372 tok_str_free(macro_str1);
4375 /* return next token with macro substitution */
4376 static void next(void)
4378 Sym *nested_list, *s;
4379 TokenString str;
4380 struct macro_level *ml;
4382 redo:
4383 next_nomacro();
4384 if (!macro_ptr) {
4385 /* if not reading from macro substituted string, then try
4386 to substitute macros */
4387 if (tok >= TOK_IDENT &&
4388 (parse_flags & PARSE_FLAG_PREPROCESS)) {
4389 s = define_find(tok);
4390 if (s) {
4391 /* we have a macro: we try to substitute */
4392 tok_str_new(&str);
4393 nested_list = NULL;
4394 ml = NULL;
4395 if (macro_subst_tok(&str, &nested_list, s, &ml) == 0) {
4396 /* substitution done, NOTE: maybe empty */
4397 tok_str_add(&str, 0);
4398 macro_ptr = str.str;
4399 macro_ptr_allocated = str.str;
4400 goto redo;
4404 } else {
4405 if (tok == 0) {
4406 /* end of macro or end of unget buffer */
4407 if (unget_buffer_enabled) {
4408 macro_ptr = unget_saved_macro_ptr;
4409 unget_buffer_enabled = 0;
4410 } else {
4411 /* end of macro string: free it */
4412 tok_str_free(macro_ptr_allocated);
4413 macro_ptr = NULL;
4415 goto redo;
4419 /* convert preprocessor tokens into C tokens */
4420 if (tok == TOK_PPNUM &&
4421 (parse_flags & PARSE_FLAG_TOK_NUM)) {
4422 parse_number((char *)tokc.cstr->data);
4426 /* push back current token and set current token to 'last_tok'. Only
4427 identifier case handled for labels. */
4428 static inline void unget_tok(int last_tok)
4430 int i, n;
4431 int *q;
4432 unget_saved_macro_ptr = macro_ptr;
4433 unget_buffer_enabled = 1;
4434 q = unget_saved_buffer;
4435 macro_ptr = q;
4436 *q++ = tok;
4437 n = tok_ext_size(tok) - 1;
4438 for(i=0;i<n;i++)
4439 *q++ = tokc.tab[i];
4440 *q = 0; /* end of token string */
4441 tok = last_tok;
4445 void swap(int *p, int *q)
4447 int t;
4448 t = *p;
4449 *p = *q;
4450 *q = t;
4453 void vsetc(CType *type, int r, CValue *vc)
4455 int v;
4457 if (vtop >= vstack + (VSTACK_SIZE - 1))
4458 error("memory full");
4459 /* cannot let cpu flags if other instruction are generated. Also
4460 avoid leaving VT_JMP anywhere except on the top of the stack
4461 because it would complicate the code generator. */
4462 if (vtop >= vstack) {
4463 v = vtop->r & VT_VALMASK;
4464 if (v == VT_CMP || (v & ~1) == VT_JMP)
4465 gv(RC_INT);
4467 vtop++;
4468 vtop->type = *type;
4469 vtop->r = r;
4470 vtop->r2 = VT_CONST;
4471 vtop->c = *vc;
4474 /* push integer constant */
4475 void vpushi(int v)
4477 CValue cval;
4478 cval.i = v;
4479 vsetc(&int_type, VT_CONST, &cval);
4482 /* Return a static symbol pointing to a section */
4483 static Sym *get_sym_ref(CType *type, Section *sec,
4484 unsigned long offset, unsigned long size)
4486 int v;
4487 Sym *sym;
4489 v = anon_sym++;
4490 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
4491 sym->type.ref = type->ref;
4492 sym->r = VT_CONST | VT_SYM;
4493 put_extern_sym(sym, sec, offset, size);
4494 return sym;
4497 /* push a reference to a section offset by adding a dummy symbol */
4498 static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
4500 CValue cval;
4502 cval.ul = 0;
4503 vsetc(type, VT_CONST | VT_SYM, &cval);
4504 vtop->sym = get_sym_ref(type, sec, offset, size);
4507 /* define a new external reference to a symbol 'v' of type 'u' */
4508 static Sym *external_global_sym(int v, CType *type, int r)
4510 Sym *s;
4512 s = sym_find(v);
4513 if (!s) {
4514 /* push forward reference */
4515 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
4516 s->type.ref = type->ref;
4517 s->r = r | VT_CONST | VT_SYM;
4519 return s;
4522 /* define a new external reference to a symbol 'v' of type 'u' */
4523 static Sym *external_sym(int v, CType *type, int r)
4525 Sym *s;
4527 s = sym_find(v);
4528 if (!s) {
4529 /* push forward reference */
4530 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
4531 s->type.t |= VT_EXTERN;
4532 } else {
4533 if (!is_compatible_types(&s->type, type))
4534 error("incompatible types for redefinition of '%s'",
4535 get_tok_str(v, NULL));
4537 return s;
4540 /* push a reference to global symbol v */
4541 static void vpush_global_sym(CType *type, int v)
4543 Sym *sym;
4544 CValue cval;
4546 sym = external_global_sym(v, type, 0);
4547 cval.ul = 0;
4548 vsetc(type, VT_CONST | VT_SYM, &cval);
4549 vtop->sym = sym;
4552 void vset(CType *type, int r, int v)
4554 CValue cval;
4556 cval.i = v;
4557 vsetc(type, r, &cval);
4560 void vseti(int r, int v)
4562 CType type;
4563 type.t = VT_INT;
4564 vset(&type, r, v);
4567 void vswap(void)
4569 SValue tmp;
4571 tmp = vtop[0];
4572 vtop[0] = vtop[-1];
4573 vtop[-1] = tmp;
4576 void vpushv(SValue *v)
4578 if (vtop >= vstack + (VSTACK_SIZE - 1))
4579 error("memory full");
4580 vtop++;
4581 *vtop = *v;
4584 void vdup(void)
4586 vpushv(vtop);
4589 /* save r to the memory stack, and mark it as being free */
4590 void save_reg(int r)
4592 int l, saved, size, align;
4593 SValue *p, sv;
4594 CType *type;
4596 /* modify all stack values */
4597 saved = 0;
4598 l = 0;
4599 for(p=vstack;p<=vtop;p++) {
4600 if ((p->r & VT_VALMASK) == r ||
4601 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
4602 /* must save value on stack if not already done */
4603 if (!saved) {
4604 /* NOTE: must reload 'r' because r might be equal to r2 */
4605 r = p->r & VT_VALMASK;
4606 /* store register in the stack */
4607 type = &p->type;
4608 if ((p->r & VT_LVAL) ||
4609 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
4610 type = &int_type;
4611 size = type_size(type, &align);
4612 loc = (loc - size) & -align;
4613 sv.type.t = type->t;
4614 sv.r = VT_LOCAL | VT_LVAL;
4615 sv.c.ul = loc;
4616 store(r, &sv);
4617 #ifdef TCC_TARGET_I386
4618 /* x86 specific: need to pop fp register ST0 if saved */
4619 if (r == TREG_ST0) {
4620 o(0xd9dd); /* fstp %st(1) */
4622 #endif
4623 /* special long long case */
4624 if ((type->t & VT_BTYPE) == VT_LLONG) {
4625 sv.c.ul += 4;
4626 store(p->r2, &sv);
4628 l = loc;
4629 saved = 1;
4631 /* mark that stack entry as being saved on the stack */
4632 if (p->r & VT_LVAL) {
4633 /* also clear the bounded flag because the
4634 relocation address of the function was stored in
4635 p->c.ul */
4636 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
4637 } else {
4638 p->r = lvalue_type(p->type.t) | VT_LOCAL;
4640 p->r2 = VT_CONST;
4641 p->c.ul = l;
4646 /* find a register of class 'rc2' with at most one reference on stack.
4647 * If none, call get_reg(rc) */
4648 int get_reg_ex(int rc, int rc2)
4650 int r;
4651 SValue *p;
4653 for(r=0;r<NB_REGS;r++) {
4654 if (reg_classes[r] & rc2) {
4655 int n;
4656 n=0;
4657 for(p = vstack; p <= vtop; p++) {
4658 if ((p->r & VT_VALMASK) == r ||
4659 (p->r2 & VT_VALMASK) == r)
4660 n++;
4662 if (n <= 1)
4663 return r;
4666 return get_reg(rc);
4669 /* find a free register of class 'rc'. If none, save one register */
4670 int get_reg(int rc)
4672 int r;
4673 SValue *p;
4675 /* find a free register */
4676 for(r=0;r<NB_REGS;r++) {
4677 if (reg_classes[r] & rc) {
4678 for(p=vstack;p<=vtop;p++) {
4679 if ((p->r & VT_VALMASK) == r ||
4680 (p->r2 & VT_VALMASK) == r)
4681 goto notfound;
4683 return r;
4685 notfound: ;
4688 /* no register left : free the first one on the stack (VERY
4689 IMPORTANT to start from the bottom to ensure that we don't
4690 spill registers used in gen_opi()) */
4691 for(p=vstack;p<=vtop;p++) {
4692 r = p->r & VT_VALMASK;
4693 if (r < VT_CONST && (reg_classes[r] & rc))
4694 goto save_found;
4695 /* also look at second register (if long long) */
4696 r = p->r2 & VT_VALMASK;
4697 if (r < VT_CONST && (reg_classes[r] & rc)) {
4698 save_found:
4699 save_reg(r);
4700 return r;
4703 /* Should never comes here */
4704 return -1;
4707 /* save registers up to (vtop - n) stack entry */
4708 void save_regs(int n)
4710 int r;
4711 SValue *p, *p1;
4712 p1 = vtop - n;
4713 for(p = vstack;p <= p1; p++) {
4714 r = p->r & VT_VALMASK;
4715 if (r < VT_CONST) {
4716 save_reg(r);
4721 /* move register 's' to 'r', and flush previous value of r to memory
4722 if needed */
4723 void move_reg(int r, int s)
4725 SValue sv;
4727 if (r != s) {
4728 save_reg(r);
4729 sv.type.t = VT_INT;
4730 sv.r = s;
4731 sv.c.ul = 0;
4732 load(r, &sv);
4736 /* get address of vtop (vtop MUST BE an lvalue) */
4737 void gaddrof(void)
4739 vtop->r &= ~VT_LVAL;
4740 /* tricky: if saved lvalue, then we can go back to lvalue */
4741 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
4742 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
4745 #ifdef CONFIG_TCC_BCHECK
4746 /* generate lvalue bound code */
4747 void gbound(void)
4749 int lval_type;
4750 CType type1;
4752 vtop->r &= ~VT_MUSTBOUND;
4753 /* if lvalue, then use checking code before dereferencing */
4754 if (vtop->r & VT_LVAL) {
4755 /* if not VT_BOUNDED value, then make one */
4756 if (!(vtop->r & VT_BOUNDED)) {
4757 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
4758 /* must save type because we must set it to int to get pointer */
4759 type1 = vtop->type;
4760 vtop->type.t = VT_INT;
4761 gaddrof();
4762 vpushi(0);
4763 gen_bounded_ptr_add();
4764 vtop->r |= lval_type;
4765 vtop->type = type1;
4767 /* then check for dereferencing */
4768 gen_bounded_ptr_deref();
4771 #endif
4773 /* store vtop a register belonging to class 'rc'. lvalues are
4774 converted to values. Cannot be used if cannot be converted to
4775 register value (such as structures). */
4776 int gv(int rc)
4778 int r, r2, rc2, bit_pos, bit_size, size, align, i;
4779 unsigned long long ll;
4781 /* NOTE: get_reg can modify vstack[] */
4782 if (vtop->type.t & VT_BITFIELD) {
4783 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
4784 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
4785 /* remove bit field info to avoid loops */
4786 vtop->type.t &= ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
4787 /* generate shifts */
4788 vpushi(32 - (bit_pos + bit_size));
4789 gen_op(TOK_SHL);
4790 vpushi(32 - bit_size);
4791 /* NOTE: transformed to SHR if unsigned */
4792 gen_op(TOK_SAR);
4793 r = gv(rc);
4794 } else {
4795 if (is_float(vtop->type.t) &&
4796 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
4797 Sym *sym;
4798 int *ptr;
4799 unsigned long offset;
4801 /* XXX: unify with initializers handling ? */
4802 /* CPUs usually cannot use float constants, so we store them
4803 generically in data segment */
4804 size = type_size(&vtop->type, &align);
4805 offset = (data_section->data_offset + align - 1) & -align;
4806 data_section->data_offset = offset;
4807 /* XXX: not portable yet */
4808 #ifdef __i386__
4809 /* Zero pad x87 tenbyte long doubles */
4810 if (size == 12)
4811 vtop->c.tab[2] &= 0xffff;
4812 #endif
4813 ptr = section_ptr_add(data_section, size);
4814 size = size >> 2;
4815 for(i=0;i<size;i++)
4816 ptr[i] = vtop->c.tab[i];
4817 sym = get_sym_ref(&vtop->type, data_section, offset, size << 2);
4818 vtop->r |= VT_LVAL | VT_SYM;
4819 vtop->sym = sym;
4820 vtop->c.ul = 0;
4822 #ifdef CONFIG_TCC_BCHECK
4823 if (vtop->r & VT_MUSTBOUND)
4824 gbound();
4825 #endif
4827 r = vtop->r & VT_VALMASK;
4828 /* need to reload if:
4829 - constant
4830 - lvalue (need to dereference pointer)
4831 - already a register, but not in the right class */
4832 if (r >= VT_CONST ||
4833 (vtop->r & VT_LVAL) ||
4834 !(reg_classes[r] & rc) ||
4835 ((vtop->type.t & VT_BTYPE) == VT_LLONG &&
4836 !(reg_classes[vtop->r2] & rc))) {
4837 r = get_reg(rc);
4838 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
4839 /* two register type load : expand to two words
4840 temporarily */
4841 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
4842 /* load constant */
4843 ll = vtop->c.ull;
4844 vtop->c.ui = ll; /* first word */
4845 load(r, vtop);
4846 vtop->r = r; /* save register value */
4847 vpushi(ll >> 32); /* second word */
4848 } else if (r >= VT_CONST || /* XXX: test to VT_CONST incorrect ? */
4849 (vtop->r & VT_LVAL)) {
4850 /* We do not want to modifier the long long
4851 pointer here, so the safest (and less
4852 efficient) is to save all the other registers
4853 in the stack. XXX: totally inefficient. */
4854 save_regs(1);
4855 /* load from memory */
4856 load(r, vtop);
4857 vdup();
4858 vtop[-1].r = r; /* save register value */
4859 /* increment pointer to get second word */
4860 vtop->type.t = VT_INT;
4861 gaddrof();
4862 vpushi(4);
4863 gen_op('+');
4864 vtop->r |= VT_LVAL;
4865 } else {
4866 /* move registers */
4867 load(r, vtop);
4868 vdup();
4869 vtop[-1].r = r; /* save register value */
4870 vtop->r = vtop[-1].r2;
4872 /* allocate second register */
4873 rc2 = RC_INT;
4874 if (rc == RC_IRET)
4875 rc2 = RC_LRET;
4876 r2 = get_reg(rc2);
4877 load(r2, vtop);
4878 vpop();
4879 /* write second register */
4880 vtop->r2 = r2;
4881 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
4882 int t1, t;
4883 /* lvalue of scalar type : need to use lvalue type
4884 because of possible cast */
4885 t = vtop->type.t;
4886 t1 = t;
4887 /* compute memory access type */
4888 if (vtop->r & VT_LVAL_BYTE)
4889 t = VT_BYTE;
4890 else if (vtop->r & VT_LVAL_SHORT)
4891 t = VT_SHORT;
4892 if (vtop->r & VT_LVAL_UNSIGNED)
4893 t |= VT_UNSIGNED;
4894 vtop->type.t = t;
4895 load(r, vtop);
4896 /* restore wanted type */
4897 vtop->type.t = t1;
4898 } else {
4899 /* one register type load */
4900 load(r, vtop);
4903 vtop->r = r;
4904 #ifdef TCC_TARGET_C67
4905 /* uses register pairs for doubles */
4906 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
4907 vtop->r2 = r+1;
4908 #endif
4910 return r;
4913 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
4914 void gv2(int rc1, int rc2)
4916 int v;
4918 /* generate more generic register first. But VT_JMP or VT_CMP
4919 values must be generated first in all cases to avoid possible
4920 reload errors */
4921 v = vtop[0].r & VT_VALMASK;
4922 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
4923 vswap();
4924 gv(rc1);
4925 vswap();
4926 gv(rc2);
4927 /* test if reload is needed for first register */
4928 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
4929 vswap();
4930 gv(rc1);
4931 vswap();
4933 } else {
4934 gv(rc2);
4935 vswap();
4936 gv(rc1);
4937 vswap();
4938 /* test if reload is needed for first register */
4939 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
4940 gv(rc2);
4945 /* expand long long on stack in two int registers */
4946 void lexpand(void)
4948 int u;
4950 u = vtop->type.t & VT_UNSIGNED;
4951 gv(RC_INT);
4952 vdup();
4953 vtop[0].r = vtop[-1].r2;
4954 vtop[0].r2 = VT_CONST;
4955 vtop[-1].r2 = VT_CONST;
4956 vtop[0].type.t = VT_INT | u;
4957 vtop[-1].type.t = VT_INT | u;
4960 #ifdef TCC_TARGET_ARM
4961 /* expand long long on stack */
4962 void lexpand_nr(void)
4964 int u,v;
4966 u = vtop->type.t & VT_UNSIGNED;
4967 vdup();
4968 vtop->r2 = VT_CONST;
4969 vtop->type.t = VT_INT | u;
4970 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
4971 if (v == VT_CONST) {
4972 vtop[-1].c.ui = vtop->c.ull;
4973 vtop->c.ui = vtop->c.ull >> 32;
4974 vtop->r = VT_CONST;
4975 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
4976 vtop->c.ui += 4;
4977 vtop->r = vtop[-1].r;
4978 } else if (v > VT_CONST) {
4979 vtop--;
4980 lexpand();
4981 } else
4982 vtop->r = vtop[-1].r2;
4983 vtop[-1].r2 = VT_CONST;
4984 vtop[-1].type.t = VT_INT | u;
4986 #endif
4988 /* build a long long from two ints */
4989 void lbuild(int t)
4991 gv2(RC_INT, RC_INT);
4992 vtop[-1].r2 = vtop[0].r;
4993 vtop[-1].type.t = t;
4994 vpop();
4997 /* rotate n first stack elements to the bottom
4998 I1 ... In -> I2 ... In I1 [top is right]
5000 void vrotb(int n)
5002 int i;
5003 SValue tmp;
5005 tmp = vtop[-n + 1];
5006 for(i=-n+1;i!=0;i++)
5007 vtop[i] = vtop[i+1];
5008 vtop[0] = tmp;
5011 /* rotate n first stack elements to the top
5012 I1 ... In -> In I1 ... I(n-1) [top is right]
5014 void vrott(int n)
5016 int i;
5017 SValue tmp;
5019 tmp = vtop[0];
5020 for(i = 0;i < n - 1; i++)
5021 vtop[-i] = vtop[-i - 1];
5022 vtop[-n + 1] = tmp;
5025 #ifdef TCC_TARGET_ARM
5026 /* like vrott but in other direction
5027 In ... I1 -> I(n-1) ... I1 In [top is right]
5029 void vnrott(int n)
5031 int i;
5032 SValue tmp;
5034 tmp = vtop[-n + 1];
5035 for(i = n - 1; i > 0; i--)
5036 vtop[-i] = vtop[-i + 1];
5037 vtop[0] = tmp;
5039 #endif
5041 /* pop stack value */
5042 void vpop(void)
5044 int v;
5045 v = vtop->r & VT_VALMASK;
5046 #ifdef TCC_TARGET_I386
5047 /* for x86, we need to pop the FP stack */
5048 if (v == TREG_ST0 && !nocode_wanted) {
5049 o(0xd9dd); /* fstp %st(1) */
5050 } else
5051 #endif
5052 if (v == VT_JMP || v == VT_JMPI) {
5053 /* need to put correct jump if && or || without test */
5054 gsym(vtop->c.ul);
5056 vtop--;
5059 /* convert stack entry to register and duplicate its value in another
5060 register */
5061 void gv_dup(void)
5063 int rc, t, r, r1;
5064 SValue sv;
5066 t = vtop->type.t;
5067 if ((t & VT_BTYPE) == VT_LLONG) {
5068 lexpand();
5069 gv_dup();
5070 vswap();
5071 vrotb(3);
5072 gv_dup();
5073 vrotb(4);
5074 /* stack: H L L1 H1 */
5075 lbuild(t);
5076 vrotb(3);
5077 vrotb(3);
5078 vswap();
5079 lbuild(t);
5080 vswap();
5081 } else {
5082 /* duplicate value */
5083 rc = RC_INT;
5084 sv.type.t = VT_INT;
5085 if (is_float(t)) {
5086 rc = RC_FLOAT;
5087 sv.type.t = t;
5089 r = gv(rc);
5090 r1 = get_reg(rc);
5091 sv.r = r;
5092 sv.c.ul = 0;
5093 load(r1, &sv); /* move r to r1 */
5094 vdup();
5095 /* duplicates value */
5096 vtop->r = r1;
5100 /* generate CPU independent (unsigned) long long operations */
5101 void gen_opl(int op)
5103 int t, a, b, op1, c, i;
5104 int func;
5105 SValue tmp;
5107 switch(op) {
5108 case '/':
5109 case TOK_PDIV:
5110 func = TOK___divdi3;
5111 goto gen_func;
5112 case TOK_UDIV:
5113 func = TOK___udivdi3;
5114 goto gen_func;
5115 case '%':
5116 func = TOK___moddi3;
5117 goto gen_func;
5118 case TOK_UMOD:
5119 func = TOK___umoddi3;
5120 gen_func:
5121 /* call generic long long function */
5122 vpush_global_sym(&func_old_type, func);
5123 vrott(3);
5124 gfunc_call(2);
5125 vpushi(0);
5126 vtop->r = REG_IRET;
5127 vtop->r2 = REG_LRET;
5128 break;
5129 case '^':
5130 case '&':
5131 case '|':
5132 case '*':
5133 case '+':
5134 case '-':
5135 t = vtop->type.t;
5136 vswap();
5137 lexpand();
5138 vrotb(3);
5139 lexpand();
5140 /* stack: L1 H1 L2 H2 */
5141 tmp = vtop[0];
5142 vtop[0] = vtop[-3];
5143 vtop[-3] = tmp;
5144 tmp = vtop[-2];
5145 vtop[-2] = vtop[-3];
5146 vtop[-3] = tmp;
5147 vswap();
5148 /* stack: H1 H2 L1 L2 */
5149 if (op == '*') {
5150 vpushv(vtop - 1);
5151 vpushv(vtop - 1);
5152 gen_op(TOK_UMULL);
5153 lexpand();
5154 /* stack: H1 H2 L1 L2 ML MH */
5155 for(i=0;i<4;i++)
5156 vrotb(6);
5157 /* stack: ML MH H1 H2 L1 L2 */
5158 tmp = vtop[0];
5159 vtop[0] = vtop[-2];
5160 vtop[-2] = tmp;
5161 /* stack: ML MH H1 L2 H2 L1 */
5162 gen_op('*');
5163 vrotb(3);
5164 vrotb(3);
5165 gen_op('*');
5166 /* stack: ML MH M1 M2 */
5167 gen_op('+');
5168 gen_op('+');
5169 } else if (op == '+' || op == '-') {
5170 /* XXX: add non carry method too (for MIPS or alpha) */
5171 if (op == '+')
5172 op1 = TOK_ADDC1;
5173 else
5174 op1 = TOK_SUBC1;
5175 gen_op(op1);
5176 /* stack: H1 H2 (L1 op L2) */
5177 vrotb(3);
5178 vrotb(3);
5179 gen_op(op1 + 1); /* TOK_xxxC2 */
5180 } else {
5181 gen_op(op);
5182 /* stack: H1 H2 (L1 op L2) */
5183 vrotb(3);
5184 vrotb(3);
5185 /* stack: (L1 op L2) H1 H2 */
5186 gen_op(op);
5187 /* stack: (L1 op L2) (H1 op H2) */
5189 /* stack: L H */
5190 lbuild(t);
5191 break;
5192 case TOK_SAR:
5193 case TOK_SHR:
5194 case TOK_SHL:
5195 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5196 t = vtop[-1].type.t;
5197 vswap();
5198 lexpand();
5199 vrotb(3);
5200 /* stack: L H shift */
5201 c = (int)vtop->c.i;
5202 /* constant: simpler */
5203 /* NOTE: all comments are for SHL. the other cases are
5204 done by swaping words */
5205 vpop();
5206 if (op != TOK_SHL)
5207 vswap();
5208 if (c >= 32) {
5209 /* stack: L H */
5210 vpop();
5211 if (c > 32) {
5212 vpushi(c - 32);
5213 gen_op(op);
5215 if (op != TOK_SAR) {
5216 vpushi(0);
5217 } else {
5218 gv_dup();
5219 vpushi(31);
5220 gen_op(TOK_SAR);
5222 vswap();
5223 } else {
5224 vswap();
5225 gv_dup();
5226 /* stack: H L L */
5227 vpushi(c);
5228 gen_op(op);
5229 vswap();
5230 vpushi(32 - c);
5231 if (op == TOK_SHL)
5232 gen_op(TOK_SHR);
5233 else
5234 gen_op(TOK_SHL);
5235 vrotb(3);
5236 /* stack: L L H */
5237 vpushi(c);
5238 if (op == TOK_SHL)
5239 gen_op(TOK_SHL);
5240 else
5241 gen_op(TOK_SHR);
5242 gen_op('|');
5244 if (op != TOK_SHL)
5245 vswap();
5246 lbuild(t);
5247 } else {
5248 /* XXX: should provide a faster fallback on x86 ? */
5249 switch(op) {
5250 case TOK_SAR:
5251 func = TOK___sardi3;
5252 goto gen_func;
5253 case TOK_SHR:
5254 func = TOK___shrdi3;
5255 goto gen_func;
5256 case TOK_SHL:
5257 func = TOK___shldi3;
5258 goto gen_func;
5261 break;
5262 default:
5263 /* compare operations */
5264 t = vtop->type.t;
5265 vswap();
5266 lexpand();
5267 vrotb(3);
5268 lexpand();
5269 /* stack: L1 H1 L2 H2 */
5270 tmp = vtop[-1];
5271 vtop[-1] = vtop[-2];
5272 vtop[-2] = tmp;
5273 /* stack: L1 L2 H1 H2 */
5274 /* compare high */
5275 op1 = op;
5276 /* when values are equal, we need to compare low words. since
5277 the jump is inverted, we invert the test too. */
5278 if (op1 == TOK_LT)
5279 op1 = TOK_LE;
5280 else if (op1 == TOK_GT)
5281 op1 = TOK_GE;
5282 else if (op1 == TOK_ULT)
5283 op1 = TOK_ULE;
5284 else if (op1 == TOK_UGT)
5285 op1 = TOK_UGE;
5286 a = 0;
5287 b = 0;
5288 gen_op(op1);
5289 if (op1 != TOK_NE) {
5290 a = gtst(1, 0);
5292 if (op != TOK_EQ) {
5293 /* generate non equal test */
5294 /* XXX: NOT PORTABLE yet */
5295 if (a == 0) {
5296 b = gtst(0, 0);
5297 } else {
5298 #if defined(TCC_TARGET_I386)
5299 b = psym(0x850f, 0);
5300 #elif defined(TCC_TARGET_ARM)
5301 b = ind;
5302 o(0x1A000000 | encbranch(ind, 0, 1));
5303 #elif defined(TCC_TARGET_C67)
5304 error("not implemented");
5305 #else
5306 #error not supported
5307 #endif
5310 /* compare low. Always unsigned */
5311 op1 = op;
5312 if (op1 == TOK_LT)
5313 op1 = TOK_ULT;
5314 else if (op1 == TOK_LE)
5315 op1 = TOK_ULE;
5316 else if (op1 == TOK_GT)
5317 op1 = TOK_UGT;
5318 else if (op1 == TOK_GE)
5319 op1 = TOK_UGE;
5320 gen_op(op1);
5321 a = gtst(1, a);
5322 gsym(b);
5323 vseti(VT_JMPI, a);
5324 break;
5328 /* handle integer constant optimizations and various machine
5329 independent opt */
5330 void gen_opic(int op)
5332 int fc, c1, c2, n;
5333 SValue *v1, *v2;
5335 v1 = vtop - 1;
5336 v2 = vtop;
5337 /* currently, we cannot do computations with forward symbols */
5338 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5339 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5340 if (c1 && c2) {
5341 fc = v2->c.i;
5342 switch(op) {
5343 case '+': v1->c.i += fc; break;
5344 case '-': v1->c.i -= fc; break;
5345 case '&': v1->c.i &= fc; break;
5346 case '^': v1->c.i ^= fc; break;
5347 case '|': v1->c.i |= fc; break;
5348 case '*': v1->c.i *= fc; break;
5350 case TOK_PDIV:
5351 case '/':
5352 case '%':
5353 case TOK_UDIV:
5354 case TOK_UMOD:
5355 /* if division by zero, generate explicit division */
5356 if (fc == 0) {
5357 if (const_wanted)
5358 error("division by zero in constant");
5359 goto general_case;
5361 switch(op) {
5362 default: v1->c.i /= fc; break;
5363 case '%': v1->c.i %= fc; break;
5364 case TOK_UDIV: v1->c.i = (unsigned)v1->c.i / fc; break;
5365 case TOK_UMOD: v1->c.i = (unsigned)v1->c.i % fc; break;
5367 break;
5368 case TOK_SHL: v1->c.i <<= fc; break;
5369 case TOK_SHR: v1->c.i = (unsigned)v1->c.i >> fc; break;
5370 case TOK_SAR: v1->c.i >>= fc; break;
5371 /* tests */
5372 case TOK_ULT: v1->c.i = (unsigned)v1->c.i < (unsigned)fc; break;
5373 case TOK_UGE: v1->c.i = (unsigned)v1->c.i >= (unsigned)fc; break;
5374 case TOK_EQ: v1->c.i = v1->c.i == fc; break;
5375 case TOK_NE: v1->c.i = v1->c.i != fc; break;
5376 case TOK_ULE: v1->c.i = (unsigned)v1->c.i <= (unsigned)fc; break;
5377 case TOK_UGT: v1->c.i = (unsigned)v1->c.i > (unsigned)fc; break;
5378 case TOK_LT: v1->c.i = v1->c.i < fc; break;
5379 case TOK_GE: v1->c.i = v1->c.i >= fc; break;
5380 case TOK_LE: v1->c.i = v1->c.i <= fc; break;
5381 case TOK_GT: v1->c.i = v1->c.i > fc; break;
5382 /* logical */
5383 case TOK_LAND: v1->c.i = v1->c.i && fc; break;
5384 case TOK_LOR: v1->c.i = v1->c.i || fc; break;
5385 default:
5386 goto general_case;
5388 vtop--;
5389 } else {
5390 /* if commutative ops, put c2 as constant */
5391 if (c1 && (op == '+' || op == '&' || op == '^' ||
5392 op == '|' || op == '*')) {
5393 vswap();
5394 swap(&c1, &c2);
5396 fc = vtop->c.i;
5397 if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
5398 op == TOK_PDIV) &&
5399 fc == 1) ||
5400 ((op == '+' || op == '-' || op == '|' || op == '^' ||
5401 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
5402 fc == 0) ||
5403 (op == '&' &&
5404 fc == -1))) {
5405 /* nothing to do */
5406 vtop--;
5407 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
5408 /* try to use shifts instead of muls or divs */
5409 if (fc > 0 && (fc & (fc - 1)) == 0) {
5410 n = -1;
5411 while (fc) {
5412 fc >>= 1;
5413 n++;
5415 vtop->c.i = n;
5416 if (op == '*')
5417 op = TOK_SHL;
5418 else if (op == TOK_PDIV)
5419 op = TOK_SAR;
5420 else
5421 op = TOK_SHR;
5423 goto general_case;
5424 } else if (c2 && (op == '+' || op == '-') &&
5425 (vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) ==
5426 (VT_CONST | VT_SYM)) {
5427 /* symbol + constant case */
5428 if (op == '-')
5429 fc = -fc;
5430 vtop--;
5431 vtop->c.i += fc;
5432 } else {
5433 general_case:
5434 if (!nocode_wanted) {
5435 /* call low level op generator */
5436 gen_opi(op);
5437 } else {
5438 vtop--;
5444 /* generate a floating point operation with constant propagation */
5445 void gen_opif(int op)
5447 int c1, c2;
5448 SValue *v1, *v2;
5449 long double f1, f2;
5451 v1 = vtop - 1;
5452 v2 = vtop;
5453 /* currently, we cannot do computations with forward symbols */
5454 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5455 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5456 if (c1 && c2) {
5457 if (v1->type.t == VT_FLOAT) {
5458 f1 = v1->c.f;
5459 f2 = v2->c.f;
5460 } else if (v1->type.t == VT_DOUBLE) {
5461 f1 = v1->c.d;
5462 f2 = v2->c.d;
5463 } else {
5464 f1 = v1->c.ld;
5465 f2 = v2->c.ld;
5468 /* NOTE: we only do constant propagation if finite number (not
5469 NaN or infinity) (ANSI spec) */
5470 if (!ieee_finite(f1) || !ieee_finite(f2))
5471 goto general_case;
5473 switch(op) {
5474 case '+': f1 += f2; break;
5475 case '-': f1 -= f2; break;
5476 case '*': f1 *= f2; break;
5477 case '/':
5478 if (f2 == 0.0) {
5479 if (const_wanted)
5480 error("division by zero in constant");
5481 goto general_case;
5483 f1 /= f2;
5484 break;
5485 /* XXX: also handles tests ? */
5486 default:
5487 goto general_case;
5489 /* XXX: overflow test ? */
5490 if (v1->type.t == VT_FLOAT) {
5491 v1->c.f = f1;
5492 } else if (v1->type.t == VT_DOUBLE) {
5493 v1->c.d = f1;
5494 } else {
5495 v1->c.ld = f1;
5497 vtop--;
5498 } else {
5499 general_case:
5500 if (!nocode_wanted) {
5501 gen_opf(op);
5502 } else {
5503 vtop--;
5508 static int pointed_size(CType *type)
5510 int align;
5511 return type_size(pointed_type(type), &align);
5514 static inline int is_null_pointer(SValue *p)
5516 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
5517 return 0;
5518 return ((p->type.t & VT_BTYPE) == VT_INT && p->c.i == 0) ||
5519 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.ll == 0);
5522 static inline int is_integer_btype(int bt)
5524 return (bt == VT_BYTE || bt == VT_SHORT ||
5525 bt == VT_INT || bt == VT_LLONG);
5528 /* check types for comparison or substraction of pointers */
5529 static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
5531 CType *type1, *type2, tmp_type1, tmp_type2;
5532 int bt1, bt2;
5534 /* null pointers are accepted for all comparisons as gcc */
5535 if (is_null_pointer(p1) || is_null_pointer(p2))
5536 return;
5537 type1 = &p1->type;
5538 type2 = &p2->type;
5539 bt1 = type1->t & VT_BTYPE;
5540 bt2 = type2->t & VT_BTYPE;
5541 /* accept comparison between pointer and integer with a warning */
5542 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
5543 warning("comparison between pointer and integer");
5544 return;
5547 /* both must be pointers or implicit function pointers */
5548 if (bt1 == VT_PTR) {
5549 type1 = pointed_type(type1);
5550 } else if (bt1 != VT_FUNC)
5551 goto invalid_operands;
5553 if (bt2 == VT_PTR) {
5554 type2 = pointed_type(type2);
5555 } else if (bt2 != VT_FUNC) {
5556 invalid_operands:
5557 error("invalid operands to binary %s", get_tok_str(op, NULL));
5559 if ((type1->t & VT_BTYPE) == VT_VOID ||
5560 (type2->t & VT_BTYPE) == VT_VOID)
5561 return;
5562 tmp_type1 = *type1;
5563 tmp_type2 = *type2;
5564 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
5565 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
5566 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
5567 /* gcc-like error if '-' is used */
5568 if (op == '-')
5569 goto invalid_operands;
5570 else
5571 warning("comparison of distinct pointer types lacks a cast");
5575 /* generic gen_op: handles types problems */
5576 void gen_op(int op)
5578 int u, t1, t2, bt1, bt2, t;
5579 CType type1;
5581 t1 = vtop[-1].type.t;
5582 t2 = vtop[0].type.t;
5583 bt1 = t1 & VT_BTYPE;
5584 bt2 = t2 & VT_BTYPE;
5586 if (bt1 == VT_PTR || bt2 == VT_PTR) {
5587 /* at least one operand is a pointer */
5588 /* relationnal op: must be both pointers */
5589 if (op >= TOK_ULT && op <= TOK_GT) {
5590 check_comparison_pointer_types(vtop - 1, vtop, op);
5591 /* pointers are handled are unsigned */
5592 t = VT_INT | VT_UNSIGNED;
5593 goto std_op;
5595 /* if both pointers, then it must be the '-' op */
5596 if (bt1 == VT_PTR && bt2 == VT_PTR) {
5597 if (op != '-')
5598 error("cannot use pointers here");
5599 check_comparison_pointer_types(vtop - 1, vtop, op);
5600 /* XXX: check that types are compatible */
5601 u = pointed_size(&vtop[-1].type);
5602 gen_opic(op);
5603 /* set to integer type */
5604 vtop->type.t = VT_INT;
5605 vpushi(u);
5606 gen_op(TOK_PDIV);
5607 } else {
5608 /* exactly one pointer : must be '+' or '-'. */
5609 if (op != '-' && op != '+')
5610 error("cannot use pointers here");
5611 /* Put pointer as first operand */
5612 if (bt2 == VT_PTR) {
5613 vswap();
5614 swap(&t1, &t2);
5616 type1 = vtop[-1].type;
5617 /* XXX: cast to int ? (long long case) */
5618 vpushi(pointed_size(&vtop[-1].type));
5619 gen_op('*');
5620 #ifdef CONFIG_TCC_BCHECK
5621 /* if evaluating constant expression, no code should be
5622 generated, so no bound check */
5623 if (do_bounds_check && !const_wanted) {
5624 /* if bounded pointers, we generate a special code to
5625 test bounds */
5626 if (op == '-') {
5627 vpushi(0);
5628 vswap();
5629 gen_op('-');
5631 gen_bounded_ptr_add();
5632 } else
5633 #endif
5635 gen_opic(op);
5637 /* put again type if gen_opic() swaped operands */
5638 vtop->type = type1;
5640 } else if (is_float(bt1) || is_float(bt2)) {
5641 /* compute bigger type and do implicit casts */
5642 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
5643 t = VT_LDOUBLE;
5644 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
5645 t = VT_DOUBLE;
5646 } else {
5647 t = VT_FLOAT;
5649 /* floats can only be used for a few operations */
5650 if (op != '+' && op != '-' && op != '*' && op != '/' &&
5651 (op < TOK_ULT || op > TOK_GT))
5652 error("invalid operands for binary operation");
5653 goto std_op;
5654 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
5655 /* cast to biggest op */
5656 t = VT_LLONG;
5657 /* convert to unsigned if it does not fit in a long long */
5658 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
5659 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
5660 t |= VT_UNSIGNED;
5661 goto std_op;
5662 } else {
5663 /* integer operations */
5664 t = VT_INT;
5665 /* convert to unsigned if it does not fit in an integer */
5666 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
5667 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
5668 t |= VT_UNSIGNED;
5669 std_op:
5670 /* XXX: currently, some unsigned operations are explicit, so
5671 we modify them here */
5672 if (t & VT_UNSIGNED) {
5673 if (op == TOK_SAR)
5674 op = TOK_SHR;
5675 else if (op == '/')
5676 op = TOK_UDIV;
5677 else if (op == '%')
5678 op = TOK_UMOD;
5679 else if (op == TOK_LT)
5680 op = TOK_ULT;
5681 else if (op == TOK_GT)
5682 op = TOK_UGT;
5683 else if (op == TOK_LE)
5684 op = TOK_ULE;
5685 else if (op == TOK_GE)
5686 op = TOK_UGE;
5688 vswap();
5689 type1.t = t;
5690 gen_cast(&type1);
5691 vswap();
5692 /* special case for shifts and long long: we keep the shift as
5693 an integer */
5694 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
5695 type1.t = VT_INT;
5696 gen_cast(&type1);
5697 if (is_float(t))
5698 gen_opif(op);
5699 else if ((t & VT_BTYPE) == VT_LLONG)
5700 gen_opl(op);
5701 else
5702 gen_opic(op);
5703 if (op >= TOK_ULT && op <= TOK_GT) {
5704 /* relationnal op: the result is an int */
5705 vtop->type.t = VT_INT;
5706 } else {
5707 vtop->type.t = t;
5712 /* generic itof for unsigned long long case */
5713 void gen_cvt_itof1(int t)
5715 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
5716 (VT_LLONG | VT_UNSIGNED)) {
5718 if (t == VT_FLOAT)
5719 vpush_global_sym(&func_old_type, TOK___ulltof);
5720 else if (t == VT_DOUBLE)
5721 vpush_global_sym(&func_old_type, TOK___ulltod);
5722 else
5723 vpush_global_sym(&func_old_type, TOK___ulltold);
5724 vrott(2);
5725 gfunc_call(1);
5726 vpushi(0);
5727 vtop->r = REG_FRET;
5728 } else {
5729 gen_cvt_itof(t);
5733 /* generic ftoi for unsigned long long case */
5734 void gen_cvt_ftoi1(int t)
5736 int st;
5738 if (t == (VT_LLONG | VT_UNSIGNED)) {
5739 /* not handled natively */
5740 st = vtop->type.t & VT_BTYPE;
5741 if (st == VT_FLOAT)
5742 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
5743 else if (st == VT_DOUBLE)
5744 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
5745 else
5746 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
5747 vrott(2);
5748 gfunc_call(1);
5749 vpushi(0);
5750 vtop->r = REG_IRET;
5751 vtop->r2 = REG_LRET;
5752 } else {
5753 gen_cvt_ftoi(t);
5757 /* force char or short cast */
5758 void force_charshort_cast(int t)
5760 int bits, dbt;
5761 dbt = t & VT_BTYPE;
5762 /* XXX: add optimization if lvalue : just change type and offset */
5763 if (dbt == VT_BYTE)
5764 bits = 8;
5765 else
5766 bits = 16;
5767 if (t & VT_UNSIGNED) {
5768 vpushi((1 << bits) - 1);
5769 gen_op('&');
5770 } else {
5771 bits = 32 - bits;
5772 vpushi(bits);
5773 gen_op(TOK_SHL);
5774 /* result must be signed or the SAR is converted to an SHL
5775 This was not the case when "t" was a signed short
5776 and the last value on the stack was an unsigned int */
5777 vtop->type.t &= ~VT_UNSIGNED;
5778 vpushi(bits);
5779 gen_op(TOK_SAR);
5783 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
5784 static void gen_cast(CType *type)
5786 int sbt, dbt, sf, df, c;
5788 /* special delayed cast for char/short */
5789 /* XXX: in some cases (multiple cascaded casts), it may still
5790 be incorrect */
5791 if (vtop->r & VT_MUSTCAST) {
5792 vtop->r &= ~VT_MUSTCAST;
5793 force_charshort_cast(vtop->type.t);
5796 /* bitfields first get cast to ints */
5797 if (vtop->type.t & VT_BITFIELD) {
5798 gv(RC_INT);
5801 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
5802 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
5804 if (sbt != dbt && !nocode_wanted) {
5805 sf = is_float(sbt);
5806 df = is_float(dbt);
5807 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
5808 if (sf && df) {
5809 /* convert from fp to fp */
5810 if (c) {
5811 /* constant case: we can do it now */
5812 /* XXX: in ISOC, cannot do it if error in convert */
5813 if (dbt == VT_FLOAT && sbt == VT_DOUBLE)
5814 vtop->c.f = (float)vtop->c.d;
5815 else if (dbt == VT_FLOAT && sbt == VT_LDOUBLE)
5816 vtop->c.f = (float)vtop->c.ld;
5817 else if (dbt == VT_DOUBLE && sbt == VT_FLOAT)
5818 vtop->c.d = (double)vtop->c.f;
5819 else if (dbt == VT_DOUBLE && sbt == VT_LDOUBLE)
5820 vtop->c.d = (double)vtop->c.ld;
5821 else if (dbt == VT_LDOUBLE && sbt == VT_FLOAT)
5822 vtop->c.ld = (long double)vtop->c.f;
5823 else if (dbt == VT_LDOUBLE && sbt == VT_DOUBLE)
5824 vtop->c.ld = (long double)vtop->c.d;
5825 } else {
5826 /* non constant case: generate code */
5827 gen_cvt_ftof(dbt);
5829 } else if (df) {
5830 /* convert int to fp */
5831 if (c) {
5832 switch(sbt) {
5833 case VT_LLONG | VT_UNSIGNED:
5834 case VT_LLONG:
5835 /* XXX: add const cases for long long */
5836 goto do_itof;
5837 case VT_INT | VT_UNSIGNED:
5838 switch(dbt) {
5839 case VT_FLOAT: vtop->c.f = (float)vtop->c.ui; break;
5840 case VT_DOUBLE: vtop->c.d = (double)vtop->c.ui; break;
5841 case VT_LDOUBLE: vtop->c.ld = (long double)vtop->c.ui; break;
5843 break;
5844 default:
5845 switch(dbt) {
5846 case VT_FLOAT: vtop->c.f = (float)vtop->c.i; break;
5847 case VT_DOUBLE: vtop->c.d = (double)vtop->c.i; break;
5848 case VT_LDOUBLE: vtop->c.ld = (long double)vtop->c.i; break;
5850 break;
5852 } else {
5853 do_itof:
5854 #if !defined(TCC_TARGET_ARM)
5855 gen_cvt_itof1(dbt);
5856 #else
5857 gen_cvt_itof(dbt);
5858 #endif
5860 } else if (sf) {
5861 /* convert fp to int */
5862 if (dbt == VT_BOOL) {
5863 vpushi(0);
5864 gen_op(TOK_NE);
5865 } else {
5866 /* we handle char/short/etc... with generic code */
5867 if (dbt != (VT_INT | VT_UNSIGNED) &&
5868 dbt != (VT_LLONG | VT_UNSIGNED) &&
5869 dbt != VT_LLONG)
5870 dbt = VT_INT;
5871 if (c) {
5872 switch(dbt) {
5873 case VT_LLONG | VT_UNSIGNED:
5874 case VT_LLONG:
5875 /* XXX: add const cases for long long */
5876 goto do_ftoi;
5877 case VT_INT | VT_UNSIGNED:
5878 switch(sbt) {
5879 case VT_FLOAT: vtop->c.ui = (unsigned int)vtop->c.d; break;
5880 case VT_DOUBLE: vtop->c.ui = (unsigned int)vtop->c.d; break;
5881 case VT_LDOUBLE: vtop->c.ui = (unsigned int)vtop->c.d; break;
5883 break;
5884 default:
5885 /* int case */
5886 switch(sbt) {
5887 case VT_FLOAT: vtop->c.i = (int)vtop->c.d; break;
5888 case VT_DOUBLE: vtop->c.i = (int)vtop->c.d; break;
5889 case VT_LDOUBLE: vtop->c.i = (int)vtop->c.d; break;
5891 break;
5893 } else {
5894 do_ftoi:
5895 gen_cvt_ftoi1(dbt);
5897 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
5898 /* additional cast for char/short... */
5899 vtop->type.t = dbt;
5900 gen_cast(type);
5903 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
5904 if ((sbt & VT_BTYPE) != VT_LLONG) {
5905 /* scalar to long long */
5906 if (c) {
5907 if (sbt == (VT_INT | VT_UNSIGNED))
5908 vtop->c.ll = vtop->c.ui;
5909 else
5910 vtop->c.ll = vtop->c.i;
5911 } else {
5912 /* machine independent conversion */
5913 gv(RC_INT);
5914 /* generate high word */
5915 if (sbt == (VT_INT | VT_UNSIGNED)) {
5916 vpushi(0);
5917 gv(RC_INT);
5918 } else {
5919 gv_dup();
5920 vpushi(31);
5921 gen_op(TOK_SAR);
5923 /* patch second register */
5924 vtop[-1].r2 = vtop->r;
5925 vpop();
5928 } else if (dbt == VT_BOOL) {
5929 /* scalar to bool */
5930 vpushi(0);
5931 gen_op(TOK_NE);
5932 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
5933 (dbt & VT_BTYPE) == VT_SHORT) {
5934 if (sbt == VT_PTR) {
5935 vtop->type.t = VT_INT;
5936 warning("nonportable conversion from pointer to char/short");
5938 force_charshort_cast(dbt);
5939 } else if ((dbt & VT_BTYPE) == VT_INT) {
5940 /* scalar to int */
5941 if (sbt == VT_LLONG) {
5942 /* from long long: just take low order word */
5943 lexpand();
5944 vpop();
5946 /* if lvalue and single word type, nothing to do because
5947 the lvalue already contains the real type size (see
5948 VT_LVAL_xxx constants) */
5951 vtop->type = *type;
5954 /* return type size. Put alignment at 'a' */
5955 static int type_size(CType *type, int *a)
5957 Sym *s;
5958 int bt;
5960 bt = type->t & VT_BTYPE;
5961 if (bt == VT_STRUCT) {
5962 /* struct/union */
5963 s = type->ref;
5964 *a = s->r;
5965 return s->c;
5966 } else if (bt == VT_PTR) {
5967 if (type->t & VT_ARRAY) {
5968 s = type->ref;
5969 return type_size(&s->type, a) * s->c;
5970 } else {
5971 *a = PTR_SIZE;
5972 return PTR_SIZE;
5974 } else if (bt == VT_LDOUBLE) {
5975 *a = LDOUBLE_ALIGN;
5976 return LDOUBLE_SIZE;
5977 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
5978 #ifdef TCC_TARGET_I386
5979 *a = 4;
5980 #else
5981 *a = 8;
5982 #endif
5983 return 8;
5984 } else if (bt == VT_INT || bt == VT_ENUM || bt == VT_FLOAT) {
5985 *a = 4;
5986 return 4;
5987 } else if (bt == VT_SHORT) {
5988 *a = 2;
5989 return 2;
5990 } else {
5991 /* char, void, function, _Bool */
5992 *a = 1;
5993 return 1;
5997 /* return the pointed type of t */
5998 static inline CType *pointed_type(CType *type)
6000 return &type->ref->type;
6003 /* modify type so that its it is a pointer to type. */
6004 static void mk_pointer(CType *type)
6006 Sym *s;
6007 s = sym_push(SYM_FIELD, type, 0, -1);
6008 type->t = VT_PTR | (type->t & ~VT_TYPE);
6009 type->ref = s;
6012 /* compare function types. OLD functions match any new functions */
6013 static int is_compatible_func(CType *type1, CType *type2)
6015 Sym *s1, *s2;
6017 s1 = type1->ref;
6018 s2 = type2->ref;
6019 if (!is_compatible_types(&s1->type, &s2->type))
6020 return 0;
6021 /* check func_call */
6022 if (s1->r != s2->r)
6023 return 0;
6024 /* XXX: not complete */
6025 if (s1->c == FUNC_OLD || s2->c == FUNC_OLD)
6026 return 1;
6027 if (s1->c != s2->c)
6028 return 0;
6029 while (s1 != NULL) {
6030 if (s2 == NULL)
6031 return 0;
6032 if (!is_compatible_parameter_types(&s1->type, &s2->type))
6033 return 0;
6034 s1 = s1->next;
6035 s2 = s2->next;
6037 if (s2)
6038 return 0;
6039 return 1;
6042 /* return true if type1 and type2 are the same. If unqualified is
6043 true, qualifiers on the types are ignored.
6045 - enums are not checked as gcc __builtin_types_compatible_p ()
6047 static int compare_types(CType *type1, CType *type2, int unqualified)
6049 int bt1, t1, t2;
6051 t1 = type1->t & VT_TYPE;
6052 t2 = type2->t & VT_TYPE;
6053 if (unqualified) {
6054 /* strip qualifiers before comparing */
6055 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
6056 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
6058 /* XXX: bitfields ? */
6059 if (t1 != t2)
6060 return 0;
6061 /* test more complicated cases */
6062 bt1 = t1 & VT_BTYPE;
6063 if (bt1 == VT_PTR) {
6064 type1 = pointed_type(type1);
6065 type2 = pointed_type(type2);
6066 return is_compatible_types(type1, type2);
6067 } else if (bt1 == VT_STRUCT) {
6068 return (type1->ref == type2->ref);
6069 } else if (bt1 == VT_FUNC) {
6070 return is_compatible_func(type1, type2);
6071 } else {
6072 return 1;
6076 /* return true if type1 and type2 are exactly the same (including
6077 qualifiers).
6079 static int is_compatible_types(CType *type1, CType *type2)
6081 return compare_types(type1,type2,0);
6084 /* return true if type1 and type2 are the same (ignoring qualifiers).
6086 static int is_compatible_parameter_types(CType *type1, CType *type2)
6088 return compare_types(type1,type2,1);
6091 /* print a type. If 'varstr' is not NULL, then the variable is also
6092 printed in the type */
6093 /* XXX: union */
6094 /* XXX: add array and function pointers */
6095 void type_to_str(char *buf, int buf_size,
6096 CType *type, const char *varstr)
6098 int bt, v, t;
6099 Sym *s, *sa;
6100 char buf1[256];
6101 const char *tstr;
6103 t = type->t & VT_TYPE;
6104 bt = t & VT_BTYPE;
6105 buf[0] = '\0';
6106 if (t & VT_CONSTANT)
6107 pstrcat(buf, buf_size, "const ");
6108 if (t & VT_VOLATILE)
6109 pstrcat(buf, buf_size, "volatile ");
6110 if (t & VT_UNSIGNED)
6111 pstrcat(buf, buf_size, "unsigned ");
6112 switch(bt) {
6113 case VT_VOID:
6114 tstr = "void";
6115 goto add_tstr;
6116 case VT_BOOL:
6117 tstr = "_Bool";
6118 goto add_tstr;
6119 case VT_BYTE:
6120 tstr = "char";
6121 goto add_tstr;
6122 case VT_SHORT:
6123 tstr = "short";
6124 goto add_tstr;
6125 case VT_INT:
6126 tstr = "int";
6127 goto add_tstr;
6128 case VT_LONG:
6129 tstr = "long";
6130 goto add_tstr;
6131 case VT_LLONG:
6132 tstr = "long long";
6133 goto add_tstr;
6134 case VT_FLOAT:
6135 tstr = "float";
6136 goto add_tstr;
6137 case VT_DOUBLE:
6138 tstr = "double";
6139 goto add_tstr;
6140 case VT_LDOUBLE:
6141 tstr = "long double";
6142 add_tstr:
6143 pstrcat(buf, buf_size, tstr);
6144 break;
6145 case VT_ENUM:
6146 case VT_STRUCT:
6147 if (bt == VT_STRUCT)
6148 tstr = "struct ";
6149 else
6150 tstr = "enum ";
6151 pstrcat(buf, buf_size, tstr);
6152 v = type->ref->v & ~SYM_STRUCT;
6153 if (v >= SYM_FIRST_ANOM)
6154 pstrcat(buf, buf_size, "<anonymous>");
6155 else
6156 pstrcat(buf, buf_size, get_tok_str(v, NULL));
6157 break;
6158 case VT_FUNC:
6159 s = type->ref;
6160 type_to_str(buf, buf_size, &s->type, varstr);
6161 pstrcat(buf, buf_size, "(");
6162 sa = s->next;
6163 while (sa != NULL) {
6164 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
6165 pstrcat(buf, buf_size, buf1);
6166 sa = sa->next;
6167 if (sa)
6168 pstrcat(buf, buf_size, ", ");
6170 pstrcat(buf, buf_size, ")");
6171 goto no_var;
6172 case VT_PTR:
6173 s = type->ref;
6174 pstrcpy(buf1, sizeof(buf1), "*");
6175 if (varstr)
6176 pstrcat(buf1, sizeof(buf1), varstr);
6177 type_to_str(buf, buf_size, &s->type, buf1);
6178 goto no_var;
6180 if (varstr) {
6181 pstrcat(buf, buf_size, " ");
6182 pstrcat(buf, buf_size, varstr);
6184 no_var: ;
6187 /* verify type compatibility to store vtop in 'dt' type, and generate
6188 casts if needed. */
6189 static void gen_assign_cast(CType *dt)
6191 CType *st, *type1, *type2, tmp_type1, tmp_type2;
6192 char buf1[256], buf2[256];
6193 int dbt, sbt;
6195 st = &vtop->type; /* source type */
6196 dbt = dt->t & VT_BTYPE;
6197 sbt = st->t & VT_BTYPE;
6198 if (dt->t & VT_CONSTANT)
6199 warning("assignment of read-only location");
6200 switch(dbt) {
6201 case VT_PTR:
6202 /* special cases for pointers */
6203 /* '0' can also be a pointer */
6204 if (is_null_pointer(vtop))
6205 goto type_ok;
6206 /* accept implicit pointer to integer cast with warning */
6207 if (is_integer_btype(sbt)) {
6208 warning("assignment makes pointer from integer without a cast");
6209 goto type_ok;
6211 type1 = pointed_type(dt);
6212 /* a function is implicitely a function pointer */
6213 if (sbt == VT_FUNC) {
6214 if ((type1->t & VT_BTYPE) != VT_VOID &&
6215 !is_compatible_types(pointed_type(dt), st))
6216 goto error;
6217 else
6218 goto type_ok;
6220 if (sbt != VT_PTR)
6221 goto error;
6222 type2 = pointed_type(st);
6223 if ((type1->t & VT_BTYPE) == VT_VOID ||
6224 (type2->t & VT_BTYPE) == VT_VOID) {
6225 /* void * can match anything */
6226 } else {
6227 /* exact type match, except for unsigned */
6228 tmp_type1 = *type1;
6229 tmp_type2 = *type2;
6230 tmp_type1.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
6231 tmp_type2.t &= ~(VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
6232 if (!is_compatible_types(&tmp_type1, &tmp_type2))
6233 warning("assignment from incompatible pointer type");
6235 /* check const and volatile */
6236 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
6237 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
6238 warning("assignment discards qualifiers from pointer target type");
6239 break;
6240 case VT_BYTE:
6241 case VT_SHORT:
6242 case VT_INT:
6243 case VT_LLONG:
6244 if (sbt == VT_PTR || sbt == VT_FUNC) {
6245 warning("assignment makes integer from pointer without a cast");
6247 /* XXX: more tests */
6248 break;
6249 case VT_STRUCT:
6250 tmp_type1 = *dt;
6251 tmp_type2 = *st;
6252 tmp_type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
6253 tmp_type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
6254 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
6255 error:
6256 type_to_str(buf1, sizeof(buf1), st, NULL);
6257 type_to_str(buf2, sizeof(buf2), dt, NULL);
6258 error("cannot cast '%s' to '%s'", buf1, buf2);
6260 break;
6262 type_ok:
6263 gen_cast(dt);
6266 /* store vtop in lvalue pushed on stack */
6267 void vstore(void)
6269 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
6271 ft = vtop[-1].type.t;
6272 sbt = vtop->type.t & VT_BTYPE;
6273 dbt = ft & VT_BTYPE;
6274 if (((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
6275 (sbt == VT_INT && dbt == VT_SHORT)) {
6276 /* optimize char/short casts */
6277 delayed_cast = VT_MUSTCAST;
6278 vtop->type.t = ft & VT_TYPE;
6279 /* XXX: factorize */
6280 if (ft & VT_CONSTANT)
6281 warning("assignment of read-only location");
6282 } else {
6283 delayed_cast = 0;
6284 if (!(ft & VT_BITFIELD))
6285 gen_assign_cast(&vtop[-1].type);
6288 if (sbt == VT_STRUCT) {
6289 /* if structure, only generate pointer */
6290 /* structure assignment : generate memcpy */
6291 /* XXX: optimize if small size */
6292 if (!nocode_wanted) {
6293 size = type_size(&vtop->type, &align);
6295 vpush_global_sym(&func_old_type, TOK_memcpy);
6297 /* destination */
6298 vpushv(vtop - 2);
6299 vtop->type.t = VT_INT;
6300 gaddrof();
6301 /* source */
6302 vpushv(vtop - 2);
6303 vtop->type.t = VT_INT;
6304 gaddrof();
6305 /* type size */
6306 vpushi(size);
6307 gfunc_call(3);
6309 vswap();
6310 vpop();
6311 } else {
6312 vswap();
6313 vpop();
6315 /* leave source on stack */
6316 } else if (ft & VT_BITFIELD) {
6317 /* bitfield store handling */
6318 bit_pos = (ft >> VT_STRUCT_SHIFT) & 0x3f;
6319 bit_size = (ft >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
6320 /* remove bit field info to avoid loops */
6321 vtop[-1].type.t = ft & ~(VT_BITFIELD | (-1 << VT_STRUCT_SHIFT));
6323 /* duplicate source into other register */
6324 gv_dup();
6325 vswap();
6326 vrott(3);
6328 /* duplicate destination */
6329 vdup();
6330 vtop[-1] = vtop[-2];
6332 /* mask and shift source */
6333 vpushi((1 << bit_size) - 1);
6334 gen_op('&');
6335 vpushi(bit_pos);
6336 gen_op(TOK_SHL);
6337 /* load destination, mask and or with source */
6338 vswap();
6339 vpushi(~(((1 << bit_size) - 1) << bit_pos));
6340 gen_op('&');
6341 gen_op('|');
6342 /* store result */
6343 vstore();
6345 /* pop off shifted source from "duplicate source..." above */
6346 vpop();
6348 } else {
6349 #ifdef CONFIG_TCC_BCHECK
6350 /* bound check case */
6351 if (vtop[-1].r & VT_MUSTBOUND) {
6352 vswap();
6353 gbound();
6354 vswap();
6356 #endif
6357 if (!nocode_wanted) {
6358 rc = RC_INT;
6359 if (is_float(ft))
6360 rc = RC_FLOAT;
6361 r = gv(rc); /* generate value */
6362 /* if lvalue was saved on stack, must read it */
6363 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
6364 SValue sv;
6365 t = get_reg(RC_INT);
6366 sv.type.t = VT_INT;
6367 sv.r = VT_LOCAL | VT_LVAL;
6368 sv.c.ul = vtop[-1].c.ul;
6369 load(t, &sv);
6370 vtop[-1].r = t | VT_LVAL;
6372 store(r, vtop - 1);
6373 /* two word case handling : store second register at word + 4 */
6374 if ((ft & VT_BTYPE) == VT_LLONG) {
6375 vswap();
6376 /* convert to int to increment easily */
6377 vtop->type.t = VT_INT;
6378 gaddrof();
6379 vpushi(4);
6380 gen_op('+');
6381 vtop->r |= VT_LVAL;
6382 vswap();
6383 /* XXX: it works because r2 is spilled last ! */
6384 store(vtop->r2, vtop - 1);
6387 vswap();
6388 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
6389 vtop->r |= delayed_cast;
6393 /* post defines POST/PRE add. c is the token ++ or -- */
6394 void inc(int post, int c)
6396 test_lvalue();
6397 vdup(); /* save lvalue */
6398 if (post) {
6399 gv_dup(); /* duplicate value */
6400 vrotb(3);
6401 vrotb(3);
6403 /* add constant */
6404 vpushi(c - TOK_MID);
6405 gen_op('+');
6406 vstore(); /* store value */
6407 if (post)
6408 vpop(); /* if post op, return saved value */
6411 /* Parse GNUC __attribute__ extension. Currently, the following
6412 extensions are recognized:
6413 - aligned(n) : set data/function alignment.
6414 - packed : force data alignment to 1
6415 - section(x) : generate data/code in this section.
6416 - unused : currently ignored, but may be used someday.
6417 - regparm(n) : pass function parameters in registers (i386 only)
6419 static void parse_attribute(AttributeDef *ad)
6421 int t, n;
6423 while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
6424 next();
6425 skip('(');
6426 skip('(');
6427 while (tok != ')') {
6428 if (tok < TOK_IDENT)
6429 expect("attribute name");
6430 t = tok;
6431 next();
6432 switch(t) {
6433 case TOK_SECTION1:
6434 case TOK_SECTION2:
6435 skip('(');
6436 if (tok != TOK_STR)
6437 expect("section name");
6438 ad->section = find_section(tcc_state, (char *)tokc.cstr->data);
6439 next();
6440 skip(')');
6441 break;
6442 case TOK_ALIGNED1:
6443 case TOK_ALIGNED2:
6444 if (tok == '(') {
6445 next();
6446 n = expr_const();
6447 if (n <= 0 || (n & (n - 1)) != 0)
6448 error("alignment must be a positive power of two");
6449 skip(')');
6450 } else {
6451 n = MAX_ALIGN;
6453 ad->aligned = n;
6454 break;
6455 case TOK_PACKED1:
6456 case TOK_PACKED2:
6457 ad->packed = 1;
6458 break;
6459 case TOK_UNUSED1:
6460 case TOK_UNUSED2:
6461 /* currently, no need to handle it because tcc does not
6462 track unused objects */
6463 break;
6464 case TOK_NORETURN1:
6465 case TOK_NORETURN2:
6466 /* currently, no need to handle it because tcc does not
6467 track unused objects */
6468 break;
6469 case TOK_CDECL1:
6470 case TOK_CDECL2:
6471 case TOK_CDECL3:
6472 ad->func_call = FUNC_CDECL;
6473 break;
6474 case TOK_STDCALL1:
6475 case TOK_STDCALL2:
6476 case TOK_STDCALL3:
6477 ad->func_call = FUNC_STDCALL;
6478 break;
6479 #ifdef TCC_TARGET_I386
6480 case TOK_REGPARM1:
6481 case TOK_REGPARM2:
6482 skip('(');
6483 n = expr_const();
6484 if (n > 3)
6485 n = 3;
6486 else if (n < 0)
6487 n = 0;
6488 if (n > 0)
6489 ad->func_call = FUNC_FASTCALL1 + n - 1;
6490 skip(')');
6491 break;
6492 case TOK_FASTCALL1:
6493 case TOK_FASTCALL2:
6494 case TOK_FASTCALL3:
6495 ad->func_call = FUNC_FASTCALLW;
6496 break;
6497 #endif
6498 case TOK_DLLEXPORT:
6499 ad->dllexport = 1;
6500 break;
6501 default:
6502 if (tcc_state->warn_unsupported)
6503 warning("'%s' attribute ignored", get_tok_str(t, NULL));
6504 /* skip parameters */
6505 /* XXX: skip parenthesis too */
6506 if (tok == '(') {
6507 next();
6508 while (tok != ')' && tok != -1)
6509 next();
6510 next();
6512 break;
6514 if (tok != ',')
6515 break;
6516 next();
6518 skip(')');
6519 skip(')');
6523 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6524 static void struct_decl(CType *type, int u)
6526 int a, v, size, align, maxalign, c, offset;
6527 int bit_size, bit_pos, bsize, bt, lbit_pos;
6528 Sym *s, *ss, *ass, **ps;
6529 AttributeDef ad;
6530 CType type1, btype;
6532 a = tok; /* save decl type */
6533 next();
6534 if (tok != '{') {
6535 v = tok;
6536 next();
6537 /* struct already defined ? return it */
6538 if (v < TOK_IDENT)
6539 expect("struct/union/enum name");
6540 s = struct_find(v);
6541 if (s) {
6542 if (s->type.t != a)
6543 error("invalid type");
6544 goto do_decl;
6546 } else {
6547 v = anon_sym++;
6549 type1.t = a;
6550 /* we put an undefined size for struct/union */
6551 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
6552 s->r = 0; /* default alignment is zero as gcc */
6553 /* put struct/union/enum name in type */
6554 do_decl:
6555 type->t = u;
6556 type->ref = s;
6558 if (tok == '{') {
6559 next();
6560 if (s->c != -1)
6561 error("struct/union/enum already defined");
6562 /* cannot be empty */
6563 c = 0;
6564 /* non empty enums are not allowed */
6565 if (a == TOK_ENUM) {
6566 for(;;) {
6567 v = tok;
6568 if (v < TOK_UIDENT)
6569 expect("identifier");
6570 next();
6571 if (tok == '=') {
6572 next();
6573 c = expr_const();
6575 /* enum symbols have static storage */
6576 ss = sym_push(v, &int_type, VT_CONST, c);
6577 ss->type.t |= VT_STATIC;
6578 if (tok != ',')
6579 break;
6580 next();
6581 c++;
6582 /* NOTE: we accept a trailing comma */
6583 if (tok == '}')
6584 break;
6586 skip('}');
6587 } else {
6588 maxalign = 1;
6589 ps = &s->next;
6590 bit_pos = 0;
6591 offset = 0;
6592 while (tok != '}') {
6593 parse_btype(&btype, &ad);
6594 while (1) {
6595 bit_size = -1;
6596 v = 0;
6597 type1 = btype;
6598 if (tok != ':') {
6599 type_decl(&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
6600 if (v == 0 && (type1.t & VT_BTYPE) != VT_STRUCT)
6601 expect("identifier");
6602 if ((type1.t & VT_BTYPE) == VT_FUNC ||
6603 (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE)))
6604 error("invalid type for '%s'",
6605 get_tok_str(v, NULL));
6607 if (tok == ':') {
6608 next();
6609 bit_size = expr_const();
6610 /* XXX: handle v = 0 case for messages */
6611 if (bit_size < 0)
6612 error("negative width in bit-field '%s'",
6613 get_tok_str(v, NULL));
6614 if (v && bit_size == 0)
6615 error("zero width for bit-field '%s'",
6616 get_tok_str(v, NULL));
6618 size = type_size(&type1, &align);
6619 if (ad.aligned) {
6620 if (align < ad.aligned)
6621 align = ad.aligned;
6622 } else if (ad.packed) {
6623 align = 1;
6624 } else if (*tcc_state->pack_stack_ptr) {
6625 if (align > *tcc_state->pack_stack_ptr)
6626 align = *tcc_state->pack_stack_ptr;
6628 lbit_pos = 0;
6629 if (bit_size >= 0) {
6630 bt = type1.t & VT_BTYPE;
6631 if (bt != VT_INT &&
6632 bt != VT_BYTE &&
6633 bt != VT_SHORT &&
6634 bt != VT_BOOL &&
6635 bt != VT_ENUM)
6636 error("bitfields must have scalar type");
6637 bsize = size * 8;
6638 if (bit_size > bsize) {
6639 error("width of '%s' exceeds its type",
6640 get_tok_str(v, NULL));
6641 } else if (bit_size == bsize) {
6642 /* no need for bit fields */
6643 bit_pos = 0;
6644 } else if (bit_size == 0) {
6645 /* XXX: what to do if only padding in a
6646 structure ? */
6647 /* zero size: means to pad */
6648 if (bit_pos > 0)
6649 bit_pos = bsize;
6650 } else {
6651 /* we do not have enough room ? */
6652 if ((bit_pos + bit_size) > bsize)
6653 bit_pos = 0;
6654 lbit_pos = bit_pos;
6655 /* XXX: handle LSB first */
6656 type1.t |= VT_BITFIELD |
6657 (bit_pos << VT_STRUCT_SHIFT) |
6658 (bit_size << (VT_STRUCT_SHIFT + 6));
6659 bit_pos += bit_size;
6661 } else {
6662 bit_pos = 0;
6664 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
6665 /* add new memory data only if starting
6666 bit field */
6667 if (lbit_pos == 0) {
6668 if (a == TOK_STRUCT) {
6669 c = (c + align - 1) & -align;
6670 offset = c;
6671 c += size;
6672 } else {
6673 offset = 0;
6674 if (size > c)
6675 c = size;
6677 if (align > maxalign)
6678 maxalign = align;
6680 #if 0
6681 printf("add field %s offset=%d",
6682 get_tok_str(v, NULL), offset);
6683 if (type1.t & VT_BITFIELD) {
6684 printf(" pos=%d size=%d",
6685 (type1.t >> VT_STRUCT_SHIFT) & 0x3f,
6686 (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
6688 printf("\n");
6689 #endif
6691 if (v == 0 && (type1.t & VT_BTYPE) == VT_STRUCT) {
6692 ass = type1.ref;
6693 while ((ass = ass->next) != NULL) {
6694 ss = sym_push(ass->v, &ass->type, 0, offset + ass->c);
6695 *ps = ss;
6696 ps = &ss->next;
6698 } else if (v) {
6699 ss = sym_push(v | SYM_FIELD, &type1, 0, offset);
6700 *ps = ss;
6701 ps = &ss->next;
6703 if (tok == ';' || tok == TOK_EOF)
6704 break;
6705 skip(',');
6707 skip(';');
6709 skip('}');
6710 /* store size and alignment */
6711 s->c = (c + maxalign - 1) & -maxalign;
6712 s->r = maxalign;
6717 /* return 0 if no type declaration. otherwise, return the basic type
6718 and skip it.
6720 static int parse_btype(CType *type, AttributeDef *ad)
6722 int t, u, type_found, typespec_found;
6723 Sym *s;
6724 CType type1;
6726 memset(ad, 0, sizeof(AttributeDef));
6727 type_found = 0;
6728 typespec_found = 0;
6729 t = 0;
6730 while(1) {
6731 switch(tok) {
6732 case TOK_EXTENSION:
6733 /* currently, we really ignore extension */
6734 next();
6735 continue;
6737 /* basic types */
6738 case TOK_CHAR:
6739 u = VT_BYTE;
6740 basic_type:
6741 next();
6742 basic_type1:
6743 if ((t & VT_BTYPE) != 0)
6744 error("too many basic types");
6745 t |= u;
6746 typespec_found = 1;
6747 break;
6748 case TOK_VOID:
6749 u = VT_VOID;
6750 goto basic_type;
6751 case TOK_SHORT:
6752 u = VT_SHORT;
6753 goto basic_type;
6754 case TOK_INT:
6755 next();
6756 typespec_found = 1;
6757 break;
6758 case TOK_LONG:
6759 next();
6760 if ((t & VT_BTYPE) == VT_DOUBLE) {
6761 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
6762 } else if ((t & VT_BTYPE) == VT_LONG) {
6763 t = (t & ~VT_BTYPE) | VT_LLONG;
6764 } else {
6765 u = VT_LONG;
6766 goto basic_type1;
6768 break;
6769 case TOK_BOOL:
6770 u = VT_BOOL;
6771 goto basic_type;
6772 case TOK_FLOAT:
6773 u = VT_FLOAT;
6774 goto basic_type;
6775 case TOK_DOUBLE:
6776 next();
6777 if ((t & VT_BTYPE) == VT_LONG) {
6778 t = (t & ~VT_BTYPE) | VT_LDOUBLE;
6779 } else {
6780 u = VT_DOUBLE;
6781 goto basic_type1;
6783 break;
6784 case TOK_ENUM:
6785 struct_decl(&type1, VT_ENUM);
6786 basic_type2:
6787 u = type1.t;
6788 type->ref = type1.ref;
6789 goto basic_type1;
6790 case TOK_STRUCT:
6791 case TOK_UNION:
6792 struct_decl(&type1, VT_STRUCT);
6793 goto basic_type2;
6795 /* type modifiers */
6796 case TOK_CONST1:
6797 case TOK_CONST2:
6798 case TOK_CONST3:
6799 t |= VT_CONSTANT;
6800 next();
6801 break;
6802 case TOK_VOLATILE1:
6803 case TOK_VOLATILE2:
6804 case TOK_VOLATILE3:
6805 t |= VT_VOLATILE;
6806 next();
6807 break;
6808 case TOK_SIGNED1:
6809 case TOK_SIGNED2:
6810 case TOK_SIGNED3:
6811 typespec_found = 1;
6812 t |= VT_SIGNED;
6813 next();
6814 break;
6815 case TOK_REGISTER:
6816 case TOK_AUTO:
6817 case TOK_RESTRICT1:
6818 case TOK_RESTRICT2:
6819 case TOK_RESTRICT3:
6820 next();
6821 break;
6822 case TOK_UNSIGNED:
6823 t |= VT_UNSIGNED;
6824 next();
6825 typespec_found = 1;
6826 break;
6828 /* storage */
6829 case TOK_EXTERN:
6830 t |= VT_EXTERN;
6831 next();
6832 break;
6833 case TOK_STATIC:
6834 t |= VT_STATIC;
6835 next();
6836 break;
6837 case TOK_TYPEDEF:
6838 t |= VT_TYPEDEF;
6839 next();
6840 break;
6841 case TOK_INLINE1:
6842 case TOK_INLINE2:
6843 case TOK_INLINE3:
6844 t |= VT_INLINE;
6845 next();
6846 break;
6848 /* GNUC attribute */
6849 case TOK_ATTRIBUTE1:
6850 case TOK_ATTRIBUTE2:
6851 parse_attribute(ad);
6852 break;
6853 /* GNUC typeof */
6854 case TOK_TYPEOF1:
6855 case TOK_TYPEOF2:
6856 case TOK_TYPEOF3:
6857 next();
6858 parse_expr_type(&type1);
6859 goto basic_type2;
6860 default:
6861 if (typespec_found)
6862 goto the_end;
6863 s = sym_find(tok);
6864 if (!s || !(s->type.t & VT_TYPEDEF))
6865 goto the_end;
6866 t |= (s->type.t & ~VT_TYPEDEF);
6867 type->ref = s->type.ref;
6868 next();
6869 typespec_found = 1;
6870 break;
6872 type_found = 1;
6874 the_end:
6875 if ((t & (VT_SIGNED|VT_UNSIGNED)) == (VT_SIGNED|VT_UNSIGNED))
6876 error("signed and unsigned modifier");
6877 if (tcc_state->char_is_unsigned) {
6878 if ((t & (VT_SIGNED|VT_UNSIGNED|VT_BTYPE)) == VT_BYTE)
6879 t |= VT_UNSIGNED;
6881 t &= ~VT_SIGNED;
6883 /* long is never used as type */
6884 if ((t & VT_BTYPE) == VT_LONG)
6885 t = (t & ~VT_BTYPE) | VT_INT;
6886 type->t = t;
6887 return type_found;
6890 /* convert a function parameter type (array to pointer and function to
6891 function pointer) */
6892 static inline void convert_parameter_type(CType *pt)
6894 /* remove const and volatile qualifiers (XXX: const could be used
6895 to indicate a const function parameter */
6896 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
6897 /* array must be transformed to pointer according to ANSI C */
6898 pt->t &= ~VT_ARRAY;
6899 if ((pt->t & VT_BTYPE) == VT_FUNC) {
6900 mk_pointer(pt);
6904 static void post_type(CType *type, AttributeDef *ad)
6906 int n, l, t1;
6907 Sym **plast, *s, *first;
6908 AttributeDef ad1;
6909 CType pt;
6911 if (tok == '(') {
6912 /* function declaration */
6913 next();
6914 l = 0;
6915 first = NULL;
6916 plast = &first;
6917 if (tok != ')') {
6918 for(;;) {
6919 /* read param name and compute offset */
6920 if (l != FUNC_OLD) {
6921 if (!parse_btype(&pt, &ad1)) {
6922 if (l) {
6923 error("invalid type");
6924 } else {
6925 l = FUNC_OLD;
6926 goto old_proto;
6929 l = FUNC_NEW;
6930 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
6931 break;
6932 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
6933 if ((pt.t & VT_BTYPE) == VT_VOID)
6934 error("parameter declared as void");
6935 } else {
6936 old_proto:
6937 n = tok;
6938 if (n < TOK_UIDENT)
6939 expect("identifier");
6940 pt.t = VT_INT;
6941 next();
6943 convert_parameter_type(&pt);
6944 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
6945 *plast = s;
6946 plast = &s->next;
6947 if (tok == ')')
6948 break;
6949 skip(',');
6950 if (l == FUNC_NEW && tok == TOK_DOTS) {
6951 l = FUNC_ELLIPSIS;
6952 next();
6953 break;
6957 /* if no parameters, then old type prototype */
6958 if (l == 0)
6959 l = FUNC_OLD;
6960 skip(')');
6961 t1 = type->t & VT_STORAGE;
6962 /* NOTE: const is ignored in returned type as it has a special
6963 meaning in gcc / C++ */
6964 type->t &= ~(VT_STORAGE | VT_CONSTANT);
6965 post_type(type, ad);
6966 /* we push a anonymous symbol which will contain the function prototype */
6967 s = sym_push(SYM_FIELD, type, ad->func_call, l);
6968 s->next = first;
6969 type->t = t1 | VT_FUNC;
6970 type->ref = s;
6971 } else if (tok == '[') {
6972 /* array definition */
6973 next();
6974 n = -1;
6975 if (tok != ']') {
6976 n = expr_const();
6977 if (n < 0)
6978 error("invalid array size");
6980 skip(']');
6981 /* parse next post type */
6982 t1 = type->t & VT_STORAGE;
6983 type->t &= ~VT_STORAGE;
6984 post_type(type, ad);
6986 /* we push a anonymous symbol which will contain the array
6987 element type */
6988 s = sym_push(SYM_FIELD, type, 0, n);
6989 type->t = t1 | VT_ARRAY | VT_PTR;
6990 type->ref = s;
6994 /* Parse a type declaration (except basic type), and return the type
6995 in 'type'. 'td' is a bitmask indicating which kind of type decl is
6996 expected. 'type' should contain the basic type. 'ad' is the
6997 attribute definition of the basic type. It can be modified by
6998 type_decl().
7000 static void type_decl(CType *type, AttributeDef *ad, int *v, int td)
7002 Sym *s;
7003 CType type1, *type2;
7004 int qualifiers;
7006 while (tok == '*') {
7007 qualifiers = 0;
7008 redo:
7009 next();
7010 switch(tok) {
7011 case TOK_CONST1:
7012 case TOK_CONST2:
7013 case TOK_CONST3:
7014 qualifiers |= VT_CONSTANT;
7015 goto redo;
7016 case TOK_VOLATILE1:
7017 case TOK_VOLATILE2:
7018 case TOK_VOLATILE3:
7019 qualifiers |= VT_VOLATILE;
7020 goto redo;
7021 case TOK_RESTRICT1:
7022 case TOK_RESTRICT2:
7023 case TOK_RESTRICT3:
7024 goto redo;
7026 mk_pointer(type);
7027 type->t |= qualifiers;
7030 /* XXX: clarify attribute handling */
7031 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7032 parse_attribute(ad);
7034 /* recursive type */
7035 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
7036 type1.t = 0; /* XXX: same as int */
7037 if (tok == '(') {
7038 next();
7039 /* XXX: this is not correct to modify 'ad' at this point, but
7040 the syntax is not clear */
7041 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7042 parse_attribute(ad);
7043 type_decl(&type1, ad, v, td);
7044 skip(')');
7045 } else {
7046 /* type identifier */
7047 if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
7048 *v = tok;
7049 next();
7050 } else {
7051 if (!(td & TYPE_ABSTRACT))
7052 expect("identifier");
7053 *v = 0;
7056 post_type(type, ad);
7057 if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2)
7058 parse_attribute(ad);
7059 if (!type1.t)
7060 return;
7061 /* append type at the end of type1 */
7062 type2 = &type1;
7063 for(;;) {
7064 s = type2->ref;
7065 type2 = &s->type;
7066 if (!type2->t) {
7067 *type2 = *type;
7068 break;
7071 *type = type1;
7074 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
7075 static int lvalue_type(int t)
7077 int bt, r;
7078 r = VT_LVAL;
7079 bt = t & VT_BTYPE;
7080 if (bt == VT_BYTE || bt == VT_BOOL)
7081 r |= VT_LVAL_BYTE;
7082 else if (bt == VT_SHORT)
7083 r |= VT_LVAL_SHORT;
7084 else
7085 return r;
7086 if (t & VT_UNSIGNED)
7087 r |= VT_LVAL_UNSIGNED;
7088 return r;
7091 /* indirection with full error checking and bound check */
7092 static void indir(void)
7094 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
7095 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
7096 return;
7097 expect("pointer");
7099 if ((vtop->r & VT_LVAL) && !nocode_wanted)
7100 gv(RC_INT);
7101 vtop->type = *pointed_type(&vtop->type);
7102 /* Arrays and functions are never lvalues */
7103 if (!(vtop->type.t & VT_ARRAY)
7104 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
7105 vtop->r |= lvalue_type(vtop->type.t);
7106 /* if bound checking, the referenced pointer must be checked */
7107 if (do_bounds_check)
7108 vtop->r |= VT_MUSTBOUND;
7112 /* pass a parameter to a function and do type checking and casting */
7113 static void gfunc_param_typed(Sym *func, Sym *arg)
7115 int func_type;
7116 CType type;
7118 func_type = func->c;
7119 if (func_type == FUNC_OLD ||
7120 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
7121 /* default casting : only need to convert float to double */
7122 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
7123 type.t = VT_DOUBLE;
7124 gen_cast(&type);
7126 } else if (arg == NULL) {
7127 error("too many arguments to function");
7128 } else {
7129 type = arg->type;
7130 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
7131 gen_assign_cast(&type);
7135 /* parse an expression of the form '(type)' or '(expr)' and return its
7136 type */
7137 static void parse_expr_type(CType *type)
7139 int n;
7140 AttributeDef ad;
7142 skip('(');
7143 if (parse_btype(type, &ad)) {
7144 type_decl(type, &ad, &n, TYPE_ABSTRACT);
7145 } else {
7146 expr_type(type);
7148 skip(')');
7151 static void parse_type(CType *type)
7153 AttributeDef ad;
7154 int n;
7156 if (!parse_btype(type, &ad)) {
7157 expect("type");
7159 type_decl(type, &ad, &n, TYPE_ABSTRACT);
7162 static void vpush_tokc(int t)
7164 CType type;
7165 type.t = t;
7166 vsetc(&type, VT_CONST, &tokc);
7169 static void unary(void)
7171 int n, t, align, size, r;
7172 CType type;
7173 Sym *s;
7174 AttributeDef ad;
7176 /* XXX: GCC 2.95.3 does not generate a table although it should be
7177 better here */
7178 tok_next:
7179 switch(tok) {
7180 case TOK_EXTENSION:
7181 next();
7182 goto tok_next;
7183 case TOK_CINT:
7184 case TOK_CCHAR:
7185 case TOK_LCHAR:
7186 vpushi(tokc.i);
7187 next();
7188 break;
7189 case TOK_CUINT:
7190 vpush_tokc(VT_INT | VT_UNSIGNED);
7191 next();
7192 break;
7193 case TOK_CLLONG:
7194 vpush_tokc(VT_LLONG);
7195 next();
7196 break;
7197 case TOK_CULLONG:
7198 vpush_tokc(VT_LLONG | VT_UNSIGNED);
7199 next();
7200 break;
7201 case TOK_CFLOAT:
7202 vpush_tokc(VT_FLOAT);
7203 next();
7204 break;
7205 case TOK_CDOUBLE:
7206 vpush_tokc(VT_DOUBLE);
7207 next();
7208 break;
7209 case TOK_CLDOUBLE:
7210 vpush_tokc(VT_LDOUBLE);
7211 next();
7212 break;
7213 case TOK___FUNCTION__:
7214 if (!gnu_ext)
7215 goto tok_identifier;
7216 /* fall thru */
7217 case TOK___FUNC__:
7219 void *ptr;
7220 int len;
7221 /* special function name identifier */
7222 len = strlen(funcname) + 1;
7223 /* generate char[len] type */
7224 type.t = VT_BYTE;
7225 mk_pointer(&type);
7226 type.t |= VT_ARRAY;
7227 type.ref->c = len;
7228 vpush_ref(&type, data_section, data_section->data_offset, len);
7229 ptr = section_ptr_add(data_section, len);
7230 memcpy(ptr, funcname, len);
7231 next();
7233 break;
7234 case TOK_LSTR:
7235 #ifdef TCC_TARGET_PE
7236 t = VT_SHORT | VT_UNSIGNED;
7237 #else
7238 t = VT_INT;
7239 #endif
7240 goto str_init;
7241 case TOK_STR:
7242 /* string parsing */
7243 t = VT_BYTE;
7244 str_init:
7245 if (tcc_state->warn_write_strings)
7246 t |= VT_CONSTANT;
7247 type.t = t;
7248 mk_pointer(&type);
7249 type.t |= VT_ARRAY;
7250 memset(&ad, 0, sizeof(AttributeDef));
7251 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
7252 break;
7253 case '(':
7254 next();
7255 /* cast ? */
7256 if (parse_btype(&type, &ad)) {
7257 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
7258 skip(')');
7259 /* check ISOC99 compound literal */
7260 if (tok == '{') {
7261 /* data is allocated locally by default */
7262 if (global_expr)
7263 r = VT_CONST;
7264 else
7265 r = VT_LOCAL;
7266 /* all except arrays are lvalues */
7267 if (!(type.t & VT_ARRAY))
7268 r |= lvalue_type(type.t);
7269 memset(&ad, 0, sizeof(AttributeDef));
7270 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
7271 } else {
7272 unary();
7273 gen_cast(&type);
7275 } else if (tok == '{') {
7276 /* save all registers */
7277 save_regs(0);
7278 /* statement expression : we do not accept break/continue
7279 inside as GCC does */
7280 block(NULL, NULL, NULL, NULL, 0, 1);
7281 skip(')');
7282 } else {
7283 gexpr();
7284 skip(')');
7286 break;
7287 case '*':
7288 next();
7289 unary();
7290 indir();
7291 break;
7292 case '&':
7293 next();
7294 unary();
7295 /* functions names must be treated as function pointers,
7296 except for unary '&' and sizeof. Since we consider that
7297 functions are not lvalues, we only have to handle it
7298 there and in function calls. */
7299 /* arrays can also be used although they are not lvalues */
7300 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
7301 !(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_LLOCAL))
7302 test_lvalue();
7303 mk_pointer(&vtop->type);
7304 gaddrof();
7305 break;
7306 case '!':
7307 next();
7308 unary();
7309 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST)
7310 vtop->c.i = !vtop->c.i;
7311 else if ((vtop->r & VT_VALMASK) == VT_CMP)
7312 vtop->c.i = vtop->c.i ^ 1;
7313 else {
7314 save_regs(1);
7315 vseti(VT_JMP, gtst(1, 0));
7317 break;
7318 case '~':
7319 next();
7320 unary();
7321 vpushi(-1);
7322 gen_op('^');
7323 break;
7324 case '+':
7325 next();
7326 /* in order to force cast, we add zero */
7327 unary();
7328 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
7329 error("pointer not accepted for unary plus");
7330 vpushi(0);
7331 gen_op('+');
7332 break;
7333 case TOK_SIZEOF:
7334 case TOK_ALIGNOF1:
7335 case TOK_ALIGNOF2:
7336 t = tok;
7337 next();
7338 if (tok == '(') {
7339 parse_expr_type(&type);
7340 } else {
7341 unary_type(&type);
7343 size = type_size(&type, &align);
7344 if (t == TOK_SIZEOF) {
7345 if (size < 0)
7346 error("sizeof applied to an incomplete type");
7347 vpushi(size);
7348 } else {
7349 vpushi(align);
7351 vtop->type.t |= VT_UNSIGNED;
7352 break;
7354 case TOK_builtin_types_compatible_p:
7356 CType type1, type2;
7357 next();
7358 skip('(');
7359 parse_type(&type1);
7360 skip(',');
7361 parse_type(&type2);
7362 skip(')');
7363 type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
7364 type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
7365 vpushi(is_compatible_types(&type1, &type2));
7367 break;
7368 case TOK_builtin_constant_p:
7370 int saved_nocode_wanted, res;
7371 next();
7372 skip('(');
7373 saved_nocode_wanted = nocode_wanted;
7374 nocode_wanted = 1;
7375 gexpr();
7376 res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
7377 vpop();
7378 nocode_wanted = saved_nocode_wanted;
7379 skip(')');
7380 vpushi(res);
7382 break;
7383 case TOK_INC:
7384 case TOK_DEC:
7385 t = tok;
7386 next();
7387 unary();
7388 inc(0, t);
7389 break;
7390 case '-':
7391 next();
7392 vpushi(0);
7393 unary();
7394 gen_op('-');
7395 break;
7396 case TOK_LAND:
7397 if (!gnu_ext)
7398 goto tok_identifier;
7399 next();
7400 /* allow to take the address of a label */
7401 if (tok < TOK_UIDENT)
7402 expect("label identifier");
7403 s = label_find(tok);
7404 if (!s) {
7405 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
7406 } else {
7407 if (s->r == LABEL_DECLARED)
7408 s->r = LABEL_FORWARD;
7410 if (!s->type.t) {
7411 s->type.t = VT_VOID;
7412 mk_pointer(&s->type);
7413 s->type.t |= VT_STATIC;
7415 vset(&s->type, VT_CONST | VT_SYM, 0);
7416 vtop->sym = s;
7417 next();
7418 break;
7419 default:
7420 tok_identifier:
7421 t = tok;
7422 next();
7423 if (t < TOK_UIDENT)
7424 expect("identifier");
7425 s = sym_find(t);
7426 if (!s) {
7427 if (tok != '(')
7428 error("'%s' undeclared", get_tok_str(t, NULL));
7429 /* for simple function calls, we tolerate undeclared
7430 external reference to int() function */
7431 if (tcc_state->warn_implicit_function_declaration)
7432 warning("implicit declaration of function '%s'",
7433 get_tok_str(t, NULL));
7434 s = external_global_sym(t, &func_old_type, 0);
7436 if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
7437 (VT_STATIC | VT_INLINE | VT_FUNC)) {
7438 /* if referencing an inline function, then we generate a
7439 symbol to it if not already done. It will have the
7440 effect to generate code for it at the end of the
7441 compilation unit. Inline function as always
7442 generated in the text section. */
7443 if (!s->c)
7444 put_extern_sym(s, text_section, 0, 0);
7445 r = VT_SYM | VT_CONST;
7446 } else {
7447 r = s->r;
7449 vset(&s->type, r, s->c);
7450 /* if forward reference, we must point to s */
7451 if (vtop->r & VT_SYM) {
7452 vtop->sym = s;
7453 vtop->c.ul = 0;
7455 break;
7458 /* post operations */
7459 while (1) {
7460 if (tok == TOK_INC || tok == TOK_DEC) {
7461 inc(1, tok);
7462 next();
7463 } else if (tok == '.' || tok == TOK_ARROW) {
7464 /* field */
7465 if (tok == TOK_ARROW)
7466 indir();
7467 test_lvalue();
7468 gaddrof();
7469 next();
7470 /* expect pointer on structure */
7471 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
7472 expect("struct or union");
7473 s = vtop->type.ref;
7474 /* find field */
7475 tok |= SYM_FIELD;
7476 while ((s = s->next) != NULL) {
7477 if (s->v == tok)
7478 break;
7480 if (!s)
7481 error("field not found");
7482 /* add field offset to pointer */
7483 vtop->type = char_pointer_type; /* change type to 'char *' */
7484 vpushi(s->c);
7485 gen_op('+');
7486 /* change type to field type, and set to lvalue */
7487 vtop->type = s->type;
7488 /* an array is never an lvalue */
7489 if (!(vtop->type.t & VT_ARRAY)) {
7490 vtop->r |= lvalue_type(vtop->type.t);
7491 /* if bound checking, the referenced pointer must be checked */
7492 if (do_bounds_check)
7493 vtop->r |= VT_MUSTBOUND;
7495 next();
7496 } else if (tok == '[') {
7497 next();
7498 gexpr();
7499 gen_op('+');
7500 indir();
7501 skip(']');
7502 } else if (tok == '(') {
7503 SValue ret;
7504 Sym *sa;
7505 int nb_args;
7507 /* function call */
7508 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
7509 /* pointer test (no array accepted) */
7510 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
7511 vtop->type = *pointed_type(&vtop->type);
7512 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
7513 goto error_func;
7514 } else {
7515 error_func:
7516 expect("function pointer");
7518 } else {
7519 vtop->r &= ~VT_LVAL; /* no lvalue */
7521 /* get return type */
7522 s = vtop->type.ref;
7523 next();
7524 sa = s->next; /* first parameter */
7525 nb_args = 0;
7526 /* compute first implicit argument if a structure is returned */
7527 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
7528 /* get some space for the returned structure */
7529 size = type_size(&s->type, &align);
7530 loc = (loc - size) & -align;
7531 ret.type = s->type;
7532 ret.r = VT_LOCAL | VT_LVAL;
7533 /* pass it as 'int' to avoid structure arg passing
7534 problems */
7535 vseti(VT_LOCAL, loc);
7536 ret.c = vtop->c;
7537 nb_args++;
7538 } else {
7539 ret.type = s->type;
7540 ret.r2 = VT_CONST;
7541 /* return in register */
7542 if (is_float(ret.type.t)) {
7543 ret.r = REG_FRET;
7544 } else {
7545 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
7546 ret.r2 = REG_LRET;
7547 ret.r = REG_IRET;
7549 ret.c.i = 0;
7551 if (tok != ')') {
7552 for(;;) {
7553 expr_eq();
7554 gfunc_param_typed(s, sa);
7555 nb_args++;
7556 if (sa)
7557 sa = sa->next;
7558 if (tok == ')')
7559 break;
7560 skip(',');
7563 if (sa)
7564 error("too few arguments to function");
7565 skip(')');
7566 if (!nocode_wanted) {
7567 gfunc_call(nb_args);
7568 } else {
7569 vtop -= (nb_args + 1);
7571 /* return value */
7572 vsetc(&ret.type, ret.r, &ret.c);
7573 vtop->r2 = ret.r2;
7574 } else {
7575 break;
7580 static void uneq(void)
7582 int t;
7584 unary();
7585 if (tok == '=' ||
7586 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
7587 tok == TOK_A_XOR || tok == TOK_A_OR ||
7588 tok == TOK_A_SHL || tok == TOK_A_SAR) {
7589 test_lvalue();
7590 t = tok;
7591 next();
7592 if (t == '=') {
7593 expr_eq();
7594 } else {
7595 vdup();
7596 expr_eq();
7597 gen_op(t & 0x7f);
7599 vstore();
7603 static void expr_prod(void)
7605 int t;
7607 uneq();
7608 while (tok == '*' || tok == '/' || tok == '%') {
7609 t = tok;
7610 next();
7611 uneq();
7612 gen_op(t);
7616 static void expr_sum(void)
7618 int t;
7620 expr_prod();
7621 while (tok == '+' || tok == '-') {
7622 t = tok;
7623 next();
7624 expr_prod();
7625 gen_op(t);
7629 static void expr_shift(void)
7631 int t;
7633 expr_sum();
7634 while (tok == TOK_SHL || tok == TOK_SAR) {
7635 t = tok;
7636 next();
7637 expr_sum();
7638 gen_op(t);
7642 static void expr_cmp(void)
7644 int t;
7646 expr_shift();
7647 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
7648 tok == TOK_ULT || tok == TOK_UGE) {
7649 t = tok;
7650 next();
7651 expr_shift();
7652 gen_op(t);
7656 static void expr_cmpeq(void)
7658 int t;
7660 expr_cmp();
7661 while (tok == TOK_EQ || tok == TOK_NE) {
7662 t = tok;
7663 next();
7664 expr_cmp();
7665 gen_op(t);
7669 static void expr_and(void)
7671 expr_cmpeq();
7672 while (tok == '&') {
7673 next();
7674 expr_cmpeq();
7675 gen_op('&');
7679 static void expr_xor(void)
7681 expr_and();
7682 while (tok == '^') {
7683 next();
7684 expr_and();
7685 gen_op('^');
7689 static void expr_or(void)
7691 expr_xor();
7692 while (tok == '|') {
7693 next();
7694 expr_xor();
7695 gen_op('|');
7699 /* XXX: fix this mess */
7700 static void expr_land_const(void)
7702 expr_or();
7703 while (tok == TOK_LAND) {
7704 next();
7705 expr_or();
7706 gen_op(TOK_LAND);
7710 /* XXX: fix this mess */
7711 static void expr_lor_const(void)
7713 expr_land_const();
7714 while (tok == TOK_LOR) {
7715 next();
7716 expr_land_const();
7717 gen_op(TOK_LOR);
7721 /* only used if non constant */
7722 static void expr_land(void)
7724 int t;
7726 expr_or();
7727 if (tok == TOK_LAND) {
7728 t = 0;
7729 save_regs(1);
7730 for(;;) {
7731 t = gtst(1, t);
7732 if (tok != TOK_LAND) {
7733 vseti(VT_JMPI, t);
7734 break;
7736 next();
7737 expr_or();
7742 static void expr_lor(void)
7744 int t;
7746 expr_land();
7747 if (tok == TOK_LOR) {
7748 t = 0;
7749 save_regs(1);
7750 for(;;) {
7751 t = gtst(0, t);
7752 if (tok != TOK_LOR) {
7753 vseti(VT_JMP, t);
7754 break;
7756 next();
7757 expr_land();
7762 /* XXX: better constant handling */
7763 static void expr_eq(void)
7765 int tt, u, r1, r2, rc, t1, t2, bt1, bt2;
7766 SValue sv;
7767 CType type, type1, type2;
7769 if (const_wanted) {
7770 int c1, c;
7771 expr_lor_const();
7772 if (tok == '?') {
7773 c = vtop->c.i;
7774 vpop();
7775 next();
7776 if (tok == ':' && gnu_ext) {
7777 c1 = c;
7778 } else {
7779 gexpr();
7780 c1 = vtop->c.i;
7781 vpop();
7783 skip(':');
7784 expr_eq();
7785 if (c)
7786 vtop->c.i = c1;
7788 } else {
7789 expr_lor();
7790 if (tok == '?') {
7791 next();
7792 if (vtop != vstack) {
7793 /* needed to avoid having different registers saved in
7794 each branch */
7795 if (is_float(vtop->type.t))
7796 rc = RC_FLOAT;
7797 else
7798 rc = RC_INT;
7799 gv(rc);
7800 save_regs(1);
7802 if (tok == ':' && gnu_ext) {
7803 gv_dup();
7804 tt = gtst(1, 0);
7805 } else {
7806 tt = gtst(1, 0);
7807 gexpr();
7809 type1 = vtop->type;
7810 sv = *vtop; /* save value to handle it later */
7811 vtop--; /* no vpop so that FP stack is not flushed */
7812 skip(':');
7813 u = gjmp(0);
7814 gsym(tt);
7815 expr_eq();
7816 type2 = vtop->type;
7818 t1 = type1.t;
7819 bt1 = t1 & VT_BTYPE;
7820 t2 = type2.t;
7821 bt2 = t2 & VT_BTYPE;
7822 /* cast operands to correct type according to ISOC rules */
7823 if (is_float(bt1) || is_float(bt2)) {
7824 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
7825 type.t = VT_LDOUBLE;
7826 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
7827 type.t = VT_DOUBLE;
7828 } else {
7829 type.t = VT_FLOAT;
7831 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
7832 /* cast to biggest op */
7833 type.t = VT_LLONG;
7834 /* convert to unsigned if it does not fit in a long long */
7835 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED) ||
7836 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_LLONG | VT_UNSIGNED))
7837 type.t |= VT_UNSIGNED;
7838 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
7839 /* XXX: test pointer compatibility */
7840 type = type1;
7841 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
7842 /* XXX: test function pointer compatibility */
7843 type = type1;
7844 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
7845 /* XXX: test structure compatibility */
7846 type = type1;
7847 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
7848 /* NOTE: as an extension, we accept void on only one side */
7849 type.t = VT_VOID;
7850 } else {
7851 /* integer operations */
7852 type.t = VT_INT;
7853 /* convert to unsigned if it does not fit in an integer */
7854 if ((t1 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED) ||
7855 (t2 & (VT_BTYPE | VT_UNSIGNED)) == (VT_INT | VT_UNSIGNED))
7856 type.t |= VT_UNSIGNED;
7859 /* now we convert second operand */
7860 gen_cast(&type);
7861 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
7862 gaddrof();
7863 rc = RC_INT;
7864 if (is_float(type.t)) {
7865 rc = RC_FLOAT;
7866 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
7867 /* for long longs, we use fixed registers to avoid having
7868 to handle a complicated move */
7869 rc = RC_IRET;
7872 r2 = gv(rc);
7873 /* this is horrible, but we must also convert first
7874 operand */
7875 tt = gjmp(0);
7876 gsym(u);
7877 /* put again first value and cast it */
7878 *vtop = sv;
7879 gen_cast(&type);
7880 if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
7881 gaddrof();
7882 r1 = gv(rc);
7883 move_reg(r2, r1);
7884 vtop->r = r2;
7885 gsym(tt);
7890 static void gexpr(void)
7892 while (1) {
7893 expr_eq();
7894 if (tok != ',')
7895 break;
7896 vpop();
7897 next();
7901 /* parse an expression and return its type without any side effect. */
7902 static void expr_type(CType *type)
7904 int saved_nocode_wanted;
7906 saved_nocode_wanted = nocode_wanted;
7907 nocode_wanted = 1;
7908 gexpr();
7909 *type = vtop->type;
7910 vpop();
7911 nocode_wanted = saved_nocode_wanted;
7914 /* parse a unary expression and return its type without any side
7915 effect. */
7916 static void unary_type(CType *type)
7918 int a;
7920 a = nocode_wanted;
7921 nocode_wanted = 1;
7922 unary();
7923 *type = vtop->type;
7924 vpop();
7925 nocode_wanted = a;
7928 /* parse a constant expression and return value in vtop. */
7929 static void expr_const1(void)
7931 int a;
7932 a = const_wanted;
7933 const_wanted = 1;
7934 expr_eq();
7935 const_wanted = a;
7938 /* parse an integer constant and return its value. */
7939 static int expr_const(void)
7941 int c;
7942 expr_const1();
7943 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
7944 expect("constant expression");
7945 c = vtop->c.i;
7946 vpop();
7947 return c;
7950 /* return the label token if current token is a label, otherwise
7951 return zero */
7952 static int is_label(void)
7954 int last_tok;
7956 /* fast test first */
7957 if (tok < TOK_UIDENT)
7958 return 0;
7959 /* no need to save tokc because tok is an identifier */
7960 last_tok = tok;
7961 next();
7962 if (tok == ':') {
7963 next();
7964 return last_tok;
7965 } else {
7966 unget_tok(last_tok);
7967 return 0;
7971 static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
7972 int case_reg, int is_expr)
7974 int a, b, c, d;
7975 Sym *s;
7977 /* generate line number info */
7978 if (do_debug &&
7979 (last_line_num != file->line_num || last_ind != ind)) {
7980 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
7981 last_ind = ind;
7982 last_line_num = file->line_num;
7985 if (is_expr) {
7986 /* default return value is (void) */
7987 vpushi(0);
7988 vtop->type.t = VT_VOID;
7991 if (tok == TOK_IF) {
7992 /* if test */
7993 next();
7994 skip('(');
7995 gexpr();
7996 skip(')');
7997 a = gtst(1, 0);
7998 block(bsym, csym, case_sym, def_sym, case_reg, 0);
7999 c = tok;
8000 if (c == TOK_ELSE) {
8001 next();
8002 d = gjmp(0);
8003 gsym(a);
8004 block(bsym, csym, case_sym, def_sym, case_reg, 0);
8005 gsym(d); /* patch else jmp */
8006 } else
8007 gsym(a);
8008 } else if (tok == TOK_WHILE) {
8009 next();
8010 d = ind;
8011 skip('(');
8012 gexpr();
8013 skip(')');
8014 a = gtst(1, 0);
8015 b = 0;
8016 block(&a, &b, case_sym, def_sym, case_reg, 0);
8017 gjmp_addr(d);
8018 gsym(a);
8019 gsym_addr(b, d);
8020 } else if (tok == '{') {
8021 Sym *llabel;
8023 next();
8024 /* record local declaration stack position */
8025 s = local_stack;
8026 llabel = local_label_stack;
8027 /* handle local labels declarations */
8028 if (tok == TOK_LABEL) {
8029 next();
8030 for(;;) {
8031 if (tok < TOK_UIDENT)
8032 expect("label identifier");
8033 label_push(&local_label_stack, tok, LABEL_DECLARED);
8034 next();
8035 if (tok == ',') {
8036 next();
8037 } else {
8038 skip(';');
8039 break;
8043 while (tok != '}') {
8044 decl(VT_LOCAL);
8045 if (tok != '}') {
8046 if (is_expr)
8047 vpop();
8048 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
8051 /* pop locally defined labels */
8052 label_pop(&local_label_stack, llabel);
8053 /* pop locally defined symbols */
8054 sym_pop(&local_stack, s);
8055 next();
8056 } else if (tok == TOK_RETURN) {
8057 next();
8058 if (tok != ';') {
8059 gexpr();
8060 gen_assign_cast(&func_vt);
8061 if ((func_vt.t & VT_BTYPE) == VT_STRUCT) {
8062 CType type;
8063 /* if returning structure, must copy it to implicit
8064 first pointer arg location */
8065 type = func_vt;
8066 mk_pointer(&type);
8067 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
8068 indir();
8069 vswap();
8070 /* copy structure value to pointer */
8071 vstore();
8072 } else if (is_float(func_vt.t)) {
8073 gv(RC_FRET);
8074 } else {
8075 gv(RC_IRET);
8077 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
8079 skip(';');
8080 rsym = gjmp(rsym); /* jmp */
8081 } else if (tok == TOK_BREAK) {
8082 /* compute jump */
8083 if (!bsym)
8084 error("cannot break");
8085 *bsym = gjmp(*bsym);
8086 next();
8087 skip(';');
8088 } else if (tok == TOK_CONTINUE) {
8089 /* compute jump */
8090 if (!csym)
8091 error("cannot continue");
8092 *csym = gjmp(*csym);
8093 next();
8094 skip(';');
8095 } else if (tok == TOK_FOR) {
8096 int e;
8097 next();
8098 skip('(');
8099 if (tok != ';') {
8100 gexpr();
8101 vpop();
8103 skip(';');
8104 d = ind;
8105 c = ind;
8106 a = 0;
8107 b = 0;
8108 if (tok != ';') {
8109 gexpr();
8110 a = gtst(1, 0);
8112 skip(';');
8113 if (tok != ')') {
8114 e = gjmp(0);
8115 c = ind;
8116 gexpr();
8117 vpop();
8118 gjmp_addr(d);
8119 gsym(e);
8121 skip(')');
8122 block(&a, &b, case_sym, def_sym, case_reg, 0);
8123 gjmp_addr(c);
8124 gsym(a);
8125 gsym_addr(b, c);
8126 } else
8127 if (tok == TOK_DO) {
8128 next();
8129 a = 0;
8130 b = 0;
8131 d = ind;
8132 block(&a, &b, case_sym, def_sym, case_reg, 0);
8133 skip(TOK_WHILE);
8134 skip('(');
8135 gsym(b);
8136 gexpr();
8137 c = gtst(0, 0);
8138 gsym_addr(c, d);
8139 skip(')');
8140 gsym(a);
8141 skip(';');
8142 } else
8143 if (tok == TOK_SWITCH) {
8144 next();
8145 skip('(');
8146 gexpr();
8147 /* XXX: other types than integer */
8148 case_reg = gv(RC_INT);
8149 vpop();
8150 skip(')');
8151 a = 0;
8152 b = gjmp(0); /* jump to first case */
8153 c = 0;
8154 block(&a, csym, &b, &c, case_reg, 0);
8155 /* if no default, jmp after switch */
8156 if (c == 0)
8157 c = ind;
8158 /* default label */
8159 gsym_addr(b, c);
8160 /* break label */
8161 gsym(a);
8162 } else
8163 if (tok == TOK_CASE) {
8164 int v1, v2;
8165 if (!case_sym)
8166 expect("switch");
8167 next();
8168 v1 = expr_const();
8169 v2 = v1;
8170 if (gnu_ext && tok == TOK_DOTS) {
8171 next();
8172 v2 = expr_const();
8173 if (v2 < v1)
8174 warning("empty case range");
8176 /* since a case is like a label, we must skip it with a jmp */
8177 b = gjmp(0);
8178 gsym(*case_sym);
8179 vseti(case_reg, 0);
8180 vpushi(v1);
8181 if (v1 == v2) {
8182 gen_op(TOK_EQ);
8183 *case_sym = gtst(1, 0);
8184 } else {
8185 gen_op(TOK_GE);
8186 *case_sym = gtst(1, 0);
8187 vseti(case_reg, 0);
8188 vpushi(v2);
8189 gen_op(TOK_LE);
8190 *case_sym = gtst(1, *case_sym);
8192 gsym(b);
8193 skip(':');
8194 is_expr = 0;
8195 goto block_after_label;
8196 } else
8197 if (tok == TOK_DEFAULT) {
8198 next();
8199 skip(':');
8200 if (!def_sym)
8201 expect("switch");
8202 if (*def_sym)
8203 error("too many 'default'");
8204 *def_sym = ind;
8205 is_expr = 0;
8206 goto block_after_label;
8207 } else
8208 if (tok == TOK_GOTO) {
8209 next();
8210 if (tok == '*' && gnu_ext) {
8211 /* computed goto */
8212 next();
8213 gexpr();
8214 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
8215 expect("pointer");
8216 ggoto();
8217 } else if (tok >= TOK_UIDENT) {
8218 s = label_find(tok);
8219 /* put forward definition if needed */
8220 if (!s) {
8221 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
8222 } else {
8223 if (s->r == LABEL_DECLARED)
8224 s->r = LABEL_FORWARD;
8226 /* label already defined */
8227 if (s->r & LABEL_FORWARD)
8228 s->next = (void *)gjmp((long)s->next);
8229 else
8230 gjmp_addr((long)s->next);
8231 next();
8232 } else {
8233 expect("label identifier");
8235 skip(';');
8236 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
8237 asm_instr();
8238 } else {
8239 b = is_label();
8240 if (b) {
8241 /* label case */
8242 s = label_find(b);
8243 if (s) {
8244 if (s->r == LABEL_DEFINED)
8245 error("duplicate label '%s'", get_tok_str(s->v, NULL));
8246 gsym((long)s->next);
8247 s->r = LABEL_DEFINED;
8248 } else {
8249 s = label_push(&global_label_stack, b, LABEL_DEFINED);
8251 s->next = (void *)ind;
8252 /* we accept this, but it is a mistake */
8253 block_after_label:
8254 if (tok == '}') {
8255 warning("deprecated use of label at end of compound statement");
8256 } else {
8257 if (is_expr)
8258 vpop();
8259 block(bsym, csym, case_sym, def_sym, case_reg, is_expr);
8261 } else {
8262 /* expression case */
8263 if (tok != ';') {
8264 if (is_expr) {
8265 vpop();
8266 gexpr();
8267 } else {
8268 gexpr();
8269 vpop();
8272 skip(';');
8277 /* t is the array or struct type. c is the array or struct
8278 address. cur_index/cur_field is the pointer to the current
8279 value. 'size_only' is true if only size info is needed (only used
8280 in arrays) */
8281 static void decl_designator(CType *type, Section *sec, unsigned long c,
8282 int *cur_index, Sym **cur_field,
8283 int size_only)
8285 Sym *s, *f;
8286 int notfirst, index, index_last, align, l, nb_elems, elem_size;
8287 CType type1;
8289 notfirst = 0;
8290 elem_size = 0;
8291 nb_elems = 1;
8292 if (gnu_ext && (l = is_label()) != 0)
8293 goto struct_field;
8294 while (tok == '[' || tok == '.') {
8295 if (tok == '[') {
8296 if (!(type->t & VT_ARRAY))
8297 expect("array type");
8298 s = type->ref;
8299 next();
8300 index = expr_const();
8301 if (index < 0 || (s->c >= 0 && index >= s->c))
8302 expect("invalid index");
8303 if (tok == TOK_DOTS && gnu_ext) {
8304 next();
8305 index_last = expr_const();
8306 if (index_last < 0 ||
8307 (s->c >= 0 && index_last >= s->c) ||
8308 index_last < index)
8309 expect("invalid index");
8310 } else {
8311 index_last = index;
8313 skip(']');
8314 if (!notfirst)
8315 *cur_index = index_last;
8316 type = pointed_type(type);
8317 elem_size = type_size(type, &align);
8318 c += index * elem_size;
8319 /* NOTE: we only support ranges for last designator */
8320 nb_elems = index_last - index + 1;
8321 if (nb_elems != 1) {
8322 notfirst = 1;
8323 break;
8325 } else {
8326 next();
8327 l = tok;
8328 next();
8329 struct_field:
8330 if ((type->t & VT_BTYPE) != VT_STRUCT)
8331 expect("struct/union type");
8332 s = type->ref;
8333 l |= SYM_FIELD;
8334 f = s->next;
8335 while (f) {
8336 if (f->v == l)
8337 break;
8338 f = f->next;
8340 if (!f)
8341 expect("field");
8342 if (!notfirst)
8343 *cur_field = f;
8344 /* XXX: fix this mess by using explicit storage field */
8345 type1 = f->type;
8346 type1.t |= (type->t & ~VT_TYPE);
8347 type = &type1;
8348 c += f->c;
8350 notfirst = 1;
8352 if (notfirst) {
8353 if (tok == '=') {
8354 next();
8355 } else {
8356 if (!gnu_ext)
8357 expect("=");
8359 } else {
8360 if (type->t & VT_ARRAY) {
8361 index = *cur_index;
8362 type = pointed_type(type);
8363 c += index * type_size(type, &align);
8364 } else {
8365 f = *cur_field;
8366 if (!f)
8367 error("too many field init");
8368 /* XXX: fix this mess by using explicit storage field */
8369 type1 = f->type;
8370 type1.t |= (type->t & ~VT_TYPE);
8371 type = &type1;
8372 c += f->c;
8375 decl_initializer(type, sec, c, 0, size_only);
8377 /* XXX: make it more general */
8378 if (!size_only && nb_elems > 1) {
8379 unsigned long c_end;
8380 uint8_t *src, *dst;
8381 int i;
8383 if (!sec)
8384 error("range init not supported yet for dynamic storage");
8385 c_end = c + nb_elems * elem_size;
8386 if (c_end > sec->data_allocated)
8387 section_realloc(sec, c_end);
8388 src = sec->data + c;
8389 dst = src;
8390 for(i = 1; i < nb_elems; i++) {
8391 dst += elem_size;
8392 memcpy(dst, src, elem_size);
8397 #define EXPR_VAL 0
8398 #define EXPR_CONST 1
8399 #define EXPR_ANY 2
8401 /* store a value or an expression directly in global data or in local array */
8402 static void init_putv(CType *type, Section *sec, unsigned long c,
8403 int v, int expr_type)
8405 int saved_global_expr, bt, bit_pos, bit_size;
8406 void *ptr;
8407 unsigned long long bit_mask;
8408 CType dtype;
8410 switch(expr_type) {
8411 case EXPR_VAL:
8412 vpushi(v);
8413 break;
8414 case EXPR_CONST:
8415 /* compound literals must be allocated globally in this case */
8416 saved_global_expr = global_expr;
8417 global_expr = 1;
8418 expr_const1();
8419 global_expr = saved_global_expr;
8420 /* NOTE: symbols are accepted */
8421 if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST)
8422 error("initializer element is not constant");
8423 break;
8424 case EXPR_ANY:
8425 expr_eq();
8426 break;
8429 dtype = *type;
8430 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
8432 if (sec) {
8433 /* XXX: not portable */
8434 /* XXX: generate error if incorrect relocation */
8435 gen_assign_cast(&dtype);
8436 bt = type->t & VT_BTYPE;
8437 ptr = sec->data + c;
8438 /* XXX: make code faster ? */
8439 if (!(type->t & VT_BITFIELD)) {
8440 bit_pos = 0;
8441 bit_size = 32;
8442 bit_mask = -1LL;
8443 } else {
8444 bit_pos = (vtop->type.t >> VT_STRUCT_SHIFT) & 0x3f;
8445 bit_size = (vtop->type.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f;
8446 bit_mask = (1LL << bit_size) - 1;
8448 if ((vtop->r & VT_SYM) &&
8449 (bt == VT_BYTE ||
8450 bt == VT_SHORT ||
8451 bt == VT_DOUBLE ||
8452 bt == VT_LDOUBLE ||
8453 bt == VT_LLONG ||
8454 (bt == VT_INT && bit_size != 32)))
8455 error("initializer element is not computable at load time");
8456 switch(bt) {
8457 case VT_BYTE:
8458 *(char *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8459 break;
8460 case VT_SHORT:
8461 *(short *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8462 break;
8463 case VT_DOUBLE:
8464 *(double *)ptr = vtop->c.d;
8465 break;
8466 case VT_LDOUBLE:
8467 *(long double *)ptr = vtop->c.ld;
8468 break;
8469 case VT_LLONG:
8470 *(long long *)ptr |= (vtop->c.ll & bit_mask) << bit_pos;
8471 break;
8472 default:
8473 if (vtop->r & VT_SYM) {
8474 greloc(sec, vtop->sym, c, R_DATA_32);
8476 *(int *)ptr |= (vtop->c.i & bit_mask) << bit_pos;
8477 break;
8479 vtop--;
8480 } else {
8481 vset(&dtype, VT_LOCAL|VT_LVAL, c);
8482 vswap();
8483 vstore();
8484 vpop();
8488 /* put zeros for variable based init */
8489 static void init_putz(CType *t, Section *sec, unsigned long c, int size)
8491 if (sec) {
8492 /* nothing to do because globals are already set to zero */
8493 } else {
8494 vpush_global_sym(&func_old_type, TOK_memset);
8495 vseti(VT_LOCAL, c);
8496 vpushi(0);
8497 vpushi(size);
8498 gfunc_call(3);
8502 /* 't' contains the type and storage info. 'c' is the offset of the
8503 object in section 'sec'. If 'sec' is NULL, it means stack based
8504 allocation. 'first' is true if array '{' must be read (multi
8505 dimension implicit array init handling). 'size_only' is true if
8506 size only evaluation is wanted (only for arrays). */
8507 static void decl_initializer(CType *type, Section *sec, unsigned long c,
8508 int first, int size_only)
8510 int index, array_length, n, no_oblock, nb, parlevel, i;
8511 int size1, align1, expr_type;
8512 Sym *s, *f;
8513 CType *t1;
8515 if (type->t & VT_ARRAY) {
8516 s = type->ref;
8517 n = s->c;
8518 array_length = 0;
8519 t1 = pointed_type(type);
8520 size1 = type_size(t1, &align1);
8522 no_oblock = 1;
8523 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
8524 tok == '{') {
8525 skip('{');
8526 no_oblock = 0;
8529 /* only parse strings here if correct type (otherwise: handle
8530 them as ((w)char *) expressions */
8531 if ((tok == TOK_LSTR &&
8532 #ifdef TCC_TARGET_PE
8533 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)) ||
8534 #else
8535 (t1->t & VT_BTYPE) == VT_INT) ||
8536 #endif
8537 (tok == TOK_STR &&
8538 (t1->t & VT_BTYPE) == VT_BYTE)) {
8539 while (tok == TOK_STR || tok == TOK_LSTR) {
8540 int cstr_len, ch;
8541 CString *cstr;
8543 cstr = tokc.cstr;
8544 /* compute maximum number of chars wanted */
8545 if (tok == TOK_STR)
8546 cstr_len = cstr->size;
8547 else
8548 cstr_len = cstr->size / sizeof(nwchar_t);
8549 cstr_len--;
8550 nb = cstr_len;
8551 if (n >= 0 && nb > (n - array_length))
8552 nb = n - array_length;
8553 if (!size_only) {
8554 if (cstr_len > nb)
8555 warning("initializer-string for array is too long");
8556 /* in order to go faster for common case (char
8557 string in global variable, we handle it
8558 specifically */
8559 if (sec && tok == TOK_STR && size1 == 1) {
8560 memcpy(sec->data + c + array_length, cstr->data, nb);
8561 } else {
8562 for(i=0;i<nb;i++) {
8563 if (tok == TOK_STR)
8564 ch = ((unsigned char *)cstr->data)[i];
8565 else
8566 ch = ((nwchar_t *)cstr->data)[i];
8567 init_putv(t1, sec, c + (array_length + i) * size1,
8568 ch, EXPR_VAL);
8572 array_length += nb;
8573 next();
8575 /* only add trailing zero if enough storage (no
8576 warning in this case since it is standard) */
8577 if (n < 0 || array_length < n) {
8578 if (!size_only) {
8579 init_putv(t1, sec, c + (array_length * size1), 0, EXPR_VAL);
8581 array_length++;
8583 } else {
8584 index = 0;
8585 while (tok != '}') {
8586 decl_designator(type, sec, c, &index, NULL, size_only);
8587 if (n >= 0 && index >= n)
8588 error("index too large");
8589 /* must put zero in holes (note that doing it that way
8590 ensures that it even works with designators) */
8591 if (!size_only && array_length < index) {
8592 init_putz(t1, sec, c + array_length * size1,
8593 (index - array_length) * size1);
8595 index++;
8596 if (index > array_length)
8597 array_length = index;
8598 /* special test for multi dimensional arrays (may not
8599 be strictly correct if designators are used at the
8600 same time) */
8601 if (index >= n && no_oblock)
8602 break;
8603 if (tok == '}')
8604 break;
8605 skip(',');
8608 if (!no_oblock)
8609 skip('}');
8610 /* put zeros at the end */
8611 if (!size_only && n >= 0 && array_length < n) {
8612 init_putz(t1, sec, c + array_length * size1,
8613 (n - array_length) * size1);
8615 /* patch type size if needed */
8616 if (n < 0)
8617 s->c = array_length;
8618 } else if ((type->t & VT_BTYPE) == VT_STRUCT &&
8619 (sec || !first || tok == '{')) {
8620 int par_count;
8622 /* NOTE: the previous test is a specific case for automatic
8623 struct/union init */
8624 /* XXX: union needs only one init */
8626 /* XXX: this test is incorrect for local initializers
8627 beginning with ( without {. It would be much more difficult
8628 to do it correctly (ideally, the expression parser should
8629 be used in all cases) */
8630 par_count = 0;
8631 if (tok == '(') {
8632 AttributeDef ad1;
8633 CType type1;
8634 next();
8635 while (tok == '(') {
8636 par_count++;
8637 next();
8639 if (!parse_btype(&type1, &ad1))
8640 expect("cast");
8641 type_decl(&type1, &ad1, &n, TYPE_ABSTRACT);
8642 #if 0
8643 if (!is_assignable_types(type, &type1))
8644 error("invalid type for cast");
8645 #endif
8646 skip(')');
8648 no_oblock = 1;
8649 if (first || tok == '{') {
8650 skip('{');
8651 no_oblock = 0;
8653 s = type->ref;
8654 f = s->next;
8655 array_length = 0;
8656 index = 0;
8657 n = s->c;
8658 while (tok != '}') {
8659 decl_designator(type, sec, c, NULL, &f, size_only);
8660 index = f->c;
8661 if (!size_only && array_length < index) {
8662 init_putz(type, sec, c + array_length,
8663 index - array_length);
8665 index = index + type_size(&f->type, &align1);
8666 if (index > array_length)
8667 array_length = index;
8668 f = f->next;
8669 if (no_oblock && f == NULL)
8670 break;
8671 if (tok == '}')
8672 break;
8673 skip(',');
8675 /* put zeros at the end */
8676 if (!size_only && array_length < n) {
8677 init_putz(type, sec, c + array_length,
8678 n - array_length);
8680 if (!no_oblock)
8681 skip('}');
8682 while (par_count) {
8683 skip(')');
8684 par_count--;
8686 } else if (tok == '{') {
8687 next();
8688 decl_initializer(type, sec, c, first, size_only);
8689 skip('}');
8690 } else if (size_only) {
8691 /* just skip expression */
8692 parlevel = 0;
8693 while ((parlevel > 0 || (tok != '}' && tok != ',')) &&
8694 tok != -1) {
8695 if (tok == '(')
8696 parlevel++;
8697 else if (tok == ')')
8698 parlevel--;
8699 next();
8701 } else {
8702 /* currently, we always use constant expression for globals
8703 (may change for scripting case) */
8704 expr_type = EXPR_CONST;
8705 if (!sec)
8706 expr_type = EXPR_ANY;
8707 init_putv(type, sec, c, 0, expr_type);
8711 /* parse an initializer for type 't' if 'has_init' is non zero, and
8712 allocate space in local or global data space ('r' is either
8713 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
8714 variable 'v' of scope 'scope' is declared before initializers are
8715 parsed. If 'v' is zero, then a reference to the new object is put
8716 in the value stack. If 'has_init' is 2, a special parsing is done
8717 to handle string constants. */
8718 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
8719 int has_init, int v, int scope)
8721 int size, align, addr, data_offset;
8722 int level;
8723 ParseState saved_parse_state;
8724 TokenString init_str;
8725 Section *sec;
8727 size = type_size(type, &align);
8728 /* If unknown size, we must evaluate it before
8729 evaluating initializers because
8730 initializers can generate global data too
8731 (e.g. string pointers or ISOC99 compound
8732 literals). It also simplifies local
8733 initializers handling */
8734 tok_str_new(&init_str);
8735 if (size < 0) {
8736 if (!has_init)
8737 error("unknown type size");
8738 /* get all init string */
8739 if (has_init == 2) {
8740 /* only get strings */
8741 while (tok == TOK_STR || tok == TOK_LSTR) {
8742 tok_str_add_tok(&init_str);
8743 next();
8745 } else {
8746 level = 0;
8747 while (level > 0 || (tok != ',' && tok != ';')) {
8748 if (tok < 0)
8749 error("unexpected end of file in initializer");
8750 tok_str_add_tok(&init_str);
8751 if (tok == '{')
8752 level++;
8753 else if (tok == '}') {
8754 if (level == 0)
8755 break;
8756 level--;
8758 next();
8761 tok_str_add(&init_str, -1);
8762 tok_str_add(&init_str, 0);
8764 /* compute size */
8765 save_parse_state(&saved_parse_state);
8767 macro_ptr = init_str.str;
8768 next();
8769 decl_initializer(type, NULL, 0, 1, 1);
8770 /* prepare second initializer parsing */
8771 macro_ptr = init_str.str;
8772 next();
8774 /* if still unknown size, error */
8775 size = type_size(type, &align);
8776 if (size < 0)
8777 error("unknown type size");
8779 /* take into account specified alignment if bigger */
8780 if (ad->aligned) {
8781 if (ad->aligned > align)
8782 align = ad->aligned;
8783 } else if (ad->packed) {
8784 align = 1;
8786 if ((r & VT_VALMASK) == VT_LOCAL) {
8787 sec = NULL;
8788 if (do_bounds_check && (type->t & VT_ARRAY))
8789 loc--;
8790 loc = (loc - size) & -align;
8791 addr = loc;
8792 /* handles bounds */
8793 /* XXX: currently, since we do only one pass, we cannot track
8794 '&' operators, so we add only arrays */
8795 if (do_bounds_check && (type->t & VT_ARRAY)) {
8796 unsigned long *bounds_ptr;
8797 /* add padding between regions */
8798 loc--;
8799 /* then add local bound info */
8800 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(unsigned long));
8801 bounds_ptr[0] = addr;
8802 bounds_ptr[1] = size;
8804 if (v) {
8805 /* local variable */
8806 sym_push(v, type, r, addr);
8807 } else {
8808 /* push local reference */
8809 vset(type, r, addr);
8811 } else {
8812 Sym *sym;
8814 sym = NULL;
8815 if (v && scope == VT_CONST) {
8816 /* see if the symbol was already defined */
8817 sym = sym_find(v);
8818 if (sym) {
8819 if (!is_compatible_types(&sym->type, type))
8820 error("incompatible types for redefinition of '%s'",
8821 get_tok_str(v, NULL));
8822 if (sym->type.t & VT_EXTERN) {
8823 /* if the variable is extern, it was not allocated */
8824 sym->type.t &= ~VT_EXTERN;
8825 /* set array size if it was ommited in extern
8826 declaration */
8827 if ((sym->type.t & VT_ARRAY) &&
8828 sym->type.ref->c < 0 &&
8829 type->ref->c >= 0)
8830 sym->type.ref->c = type->ref->c;
8831 } else {
8832 /* we accept several definitions of the same
8833 global variable. this is tricky, because we
8834 must play with the SHN_COMMON type of the symbol */
8835 /* XXX: should check if the variable was already
8836 initialized. It is incorrect to initialized it
8837 twice */
8838 /* no init data, we won't add more to the symbol */
8839 if (!has_init)
8840 goto no_alloc;
8845 /* allocate symbol in corresponding section */
8846 sec = ad->section;
8847 if (!sec) {
8848 if (has_init)
8849 sec = data_section;
8850 else if (tcc_state->nocommon)
8851 sec = bss_section;
8853 if (sec) {
8854 data_offset = sec->data_offset;
8855 data_offset = (data_offset + align - 1) & -align;
8856 addr = data_offset;
8857 /* very important to increment global pointer at this time
8858 because initializers themselves can create new initializers */
8859 data_offset += size;
8860 /* add padding if bound check */
8861 if (do_bounds_check)
8862 data_offset++;
8863 sec->data_offset = data_offset;
8864 /* allocate section space to put the data */
8865 if (sec->sh_type != SHT_NOBITS &&
8866 data_offset > sec->data_allocated)
8867 section_realloc(sec, data_offset);
8868 /* align section if needed */
8869 if (align > sec->sh_addralign)
8870 sec->sh_addralign = align;
8871 } else {
8872 addr = 0; /* avoid warning */
8875 if (v) {
8876 if (scope == VT_CONST) {
8877 if (!sym)
8878 goto do_def;
8879 } else {
8880 do_def:
8881 sym = sym_push(v, type, r | VT_SYM, 0);
8883 /* update symbol definition */
8884 if (sec) {
8885 put_extern_sym(sym, sec, addr, size);
8886 } else {
8887 Elf32_Sym *esym;
8888 /* put a common area */
8889 put_extern_sym(sym, NULL, align, size);
8890 /* XXX: find a nicer way */
8891 esym = &((Elf32_Sym *)symtab_section->data)[sym->c];
8892 esym->st_shndx = SHN_COMMON;
8894 } else {
8895 CValue cval;
8897 /* push global reference */
8898 sym = get_sym_ref(type, sec, addr, size);
8899 cval.ul = 0;
8900 vsetc(type, VT_CONST | VT_SYM, &cval);
8901 vtop->sym = sym;
8904 /* handles bounds now because the symbol must be defined
8905 before for the relocation */
8906 if (do_bounds_check) {
8907 unsigned long *bounds_ptr;
8909 greloc(bounds_section, sym, bounds_section->data_offset, R_DATA_32);
8910 /* then add global bound info */
8911 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(long));
8912 bounds_ptr[0] = 0; /* relocated */
8913 bounds_ptr[1] = size;
8916 if (has_init) {
8917 decl_initializer(type, sec, addr, 1, 0);
8918 /* restore parse state if needed */
8919 if (init_str.str) {
8920 tok_str_free(init_str.str);
8921 restore_parse_state(&saved_parse_state);
8924 no_alloc: ;
8927 void put_func_debug(Sym *sym)
8929 char buf[512];
8931 /* stabs info */
8932 /* XXX: we put here a dummy type */
8933 snprintf(buf, sizeof(buf), "%s:%c1",
8934 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
8935 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
8936 cur_text_section, sym->c);
8937 last_ind = 0;
8938 last_line_num = 0;
8941 /* parse an old style function declaration list */
8942 /* XXX: check multiple parameter */
8943 static void func_decl_list(Sym *func_sym)
8945 AttributeDef ad;
8946 int v;
8947 Sym *s;
8948 CType btype, type;
8950 /* parse each declaration */
8951 while (tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF) {
8952 if (!parse_btype(&btype, &ad))
8953 expect("declaration list");
8954 if (((btype.t & VT_BTYPE) == VT_ENUM ||
8955 (btype.t & VT_BTYPE) == VT_STRUCT) &&
8956 tok == ';') {
8957 /* we accept no variable after */
8958 } else {
8959 for(;;) {
8960 type = btype;
8961 type_decl(&type, &ad, &v, TYPE_DIRECT);
8962 /* find parameter in function parameter list */
8963 s = func_sym->next;
8964 while (s != NULL) {
8965 if ((s->v & ~SYM_FIELD) == v)
8966 goto found;
8967 s = s->next;
8969 error("declaration for parameter '%s' but no such parameter",
8970 get_tok_str(v, NULL));
8971 found:
8972 /* check that no storage specifier except 'register' was given */
8973 if (type.t & VT_STORAGE)
8974 error("storage class specified for '%s'", get_tok_str(v, NULL));
8975 convert_parameter_type(&type);
8976 /* we can add the type (NOTE: it could be local to the function) */
8977 s->type = type;
8978 /* accept other parameters */
8979 if (tok == ',')
8980 next();
8981 else
8982 break;
8985 skip(';');
8989 /* parse a function defined by symbol 'sym' and generate its code in
8990 'cur_text_section' */
8991 static void gen_function(Sym *sym)
8993 ind = cur_text_section->data_offset;
8994 /* NOTE: we patch the symbol size later */
8995 put_extern_sym(sym, cur_text_section, ind, 0);
8996 funcname = get_tok_str(sym->v, NULL);
8997 func_ind = ind;
8998 /* put debug symbol */
8999 if (do_debug)
9000 put_func_debug(sym);
9001 /* push a dummy symbol to enable local sym storage */
9002 sym_push2(&local_stack, SYM_FIELD, 0, 0);
9003 gfunc_prolog(&sym->type);
9004 rsym = 0;
9005 block(NULL, NULL, NULL, NULL, 0, 0);
9006 gsym(rsym);
9007 gfunc_epilog();
9008 cur_text_section->data_offset = ind;
9009 label_pop(&global_label_stack, NULL);
9010 sym_pop(&local_stack, NULL); /* reset local stack */
9011 /* end of function */
9012 /* patch symbol size */
9013 ((Elf32_Sym *)symtab_section->data)[sym->c].st_size =
9014 ind - func_ind;
9015 if (do_debug) {
9016 put_stabn(N_FUN, 0, 0, ind - func_ind);
9018 funcname = ""; /* for safety */
9019 func_vt.t = VT_VOID; /* for safety */
9020 ind = 0; /* for safety */
9023 static void gen_inline_functions(void)
9025 Sym *sym;
9026 CType *type;
9027 int *str, inline_generated;
9029 /* iterate while inline function are referenced */
9030 for(;;) {
9031 inline_generated = 0;
9032 for(sym = global_stack; sym != NULL; sym = sym->prev) {
9033 type = &sym->type;
9034 if (((type->t & VT_BTYPE) == VT_FUNC) &&
9035 (type->t & (VT_STATIC | VT_INLINE)) ==
9036 (VT_STATIC | VT_INLINE) &&
9037 sym->c != 0) {
9038 /* the function was used: generate its code and
9039 convert it to a normal function */
9040 str = (int *)sym->r;
9041 sym->r = VT_SYM | VT_CONST;
9042 type->t &= ~VT_INLINE;
9044 macro_ptr = str;
9045 next();
9046 cur_text_section = text_section;
9047 gen_function(sym);
9048 macro_ptr = NULL; /* fail safe */
9050 tok_str_free(str);
9051 inline_generated = 1;
9054 if (!inline_generated)
9055 break;
9058 /* free all remaining inline function tokens */
9059 for(sym = global_stack; sym != NULL; sym = sym->prev) {
9060 type = &sym->type;
9061 if (((type->t & VT_BTYPE) == VT_FUNC) &&
9062 (type->t & (VT_STATIC | VT_INLINE)) ==
9063 (VT_STATIC | VT_INLINE)) {
9064 str = (int *)sym->r;
9065 tok_str_free(str);
9066 sym->r = 0; /* fail safe */
9071 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
9072 static void decl(int l)
9074 int v, has_init, r;
9075 CType type, btype;
9076 Sym *sym;
9077 AttributeDef ad;
9079 while (1) {
9080 if (!parse_btype(&btype, &ad)) {
9081 /* skip redundant ';' */
9082 /* XXX: find more elegant solution */
9083 if (tok == ';') {
9084 next();
9085 continue;
9087 if (l == VT_CONST &&
9088 (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
9089 /* global asm block */
9090 asm_global_instr();
9091 continue;
9093 /* special test for old K&R protos without explicit int
9094 type. Only accepted when defining global data */
9095 if (l == VT_LOCAL || tok < TOK_DEFINE)
9096 break;
9097 btype.t = VT_INT;
9099 if (((btype.t & VT_BTYPE) == VT_ENUM ||
9100 (btype.t & VT_BTYPE) == VT_STRUCT) &&
9101 tok == ';') {
9102 /* we accept no variable after */
9103 next();
9104 continue;
9106 while (1) { /* iterate thru each declaration */
9107 type = btype;
9108 type_decl(&type, &ad, &v, TYPE_DIRECT);
9109 #if 0
9111 char buf[500];
9112 type_to_str(buf, sizeof(buf), &type, get_tok_str(v, NULL));
9113 printf("type = '%s'\n", buf);
9115 #endif
9116 if ((type.t & VT_BTYPE) == VT_FUNC) {
9117 /* if old style function prototype, we accept a
9118 declaration list */
9119 sym = type.ref;
9120 if (sym->c == FUNC_OLD)
9121 func_decl_list(sym);
9124 if (tok == '{') {
9125 if (l == VT_LOCAL)
9126 error("cannot use local functions");
9127 if ((type.t & VT_BTYPE) != VT_FUNC)
9128 expect("function definition");
9130 /* reject abstract declarators in function definition */
9131 sym = type.ref;
9132 while ((sym = sym->next) != NULL)
9133 if (!(sym->v & ~SYM_FIELD))
9134 expect("identifier");
9136 /* XXX: cannot do better now: convert extern line to static inline */
9137 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
9138 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
9140 sym = sym_find(v);
9141 if (sym) {
9142 if ((sym->type.t & VT_BTYPE) != VT_FUNC)
9143 goto func_error1;
9144 /* specific case: if not func_call defined, we put
9145 the one of the prototype */
9146 /* XXX: should have default value */
9147 if (sym->type.ref->r != FUNC_CDECL &&
9148 type.ref->r == FUNC_CDECL)
9149 type.ref->r = sym->type.ref->r;
9150 if (!is_compatible_types(&sym->type, &type)) {
9151 func_error1:
9152 error("incompatible types for redefinition of '%s'",
9153 get_tok_str(v, NULL));
9155 /* if symbol is already defined, then put complete type */
9156 sym->type = type;
9157 } else {
9158 /* put function symbol */
9159 sym = global_identifier_push(v, type.t, 0);
9160 sym->type.ref = type.ref;
9163 /* static inline functions are just recorded as a kind
9164 of macro. Their code will be emitted at the end of
9165 the compilation unit only if they are used */
9166 if ((type.t & (VT_INLINE | VT_STATIC)) ==
9167 (VT_INLINE | VT_STATIC)) {
9168 TokenString func_str;
9169 int block_level;
9171 tok_str_new(&func_str);
9173 block_level = 0;
9174 for(;;) {
9175 int t;
9176 if (tok == TOK_EOF)
9177 error("unexpected end of file");
9178 tok_str_add_tok(&func_str);
9179 t = tok;
9180 next();
9181 if (t == '{') {
9182 block_level++;
9183 } else if (t == '}') {
9184 block_level--;
9185 if (block_level == 0)
9186 break;
9189 tok_str_add(&func_str, -1);
9190 tok_str_add(&func_str, 0);
9191 sym->r = (int)func_str.str;
9192 } else {
9193 /* compute text section */
9194 cur_text_section = ad.section;
9195 if (!cur_text_section)
9196 cur_text_section = text_section;
9197 sym->r = VT_SYM | VT_CONST;
9198 gen_function(sym);
9199 #ifdef TCC_TARGET_PE
9200 if (ad.dllexport) {
9201 ((Elf32_Sym *)symtab_section->data)[sym->c].st_other |= 1;
9203 #endif
9205 break;
9206 } else {
9207 if (btype.t & VT_TYPEDEF) {
9208 /* save typedefed type */
9209 /* XXX: test storage specifiers ? */
9210 sym = sym_push(v, &type, 0, 0);
9211 sym->type.t |= VT_TYPEDEF;
9212 } else if ((type.t & VT_BTYPE) == VT_FUNC) {
9213 /* external function definition */
9214 /* specific case for func_call attribute */
9215 if (ad.func_call)
9216 type.ref->r = ad.func_call;
9217 external_sym(v, &type, 0);
9218 } else {
9219 /* not lvalue if array */
9220 r = 0;
9221 if (!(type.t & VT_ARRAY))
9222 r |= lvalue_type(type.t);
9223 has_init = (tok == '=');
9224 if ((btype.t & VT_EXTERN) ||
9225 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
9226 !has_init && l == VT_CONST && type.ref->c < 0)) {
9227 /* external variable */
9228 /* NOTE: as GCC, uninitialized global static
9229 arrays of null size are considered as
9230 extern */
9231 external_sym(v, &type, r);
9232 } else {
9233 type.t |= (btype.t & VT_STATIC); /* Retain "static". */
9234 if (type.t & VT_STATIC)
9235 r |= VT_CONST;
9236 else
9237 r |= l;
9238 if (has_init)
9239 next();
9240 decl_initializer_alloc(&type, &ad, r,
9241 has_init, v, l);
9244 if (tok != ',') {
9245 skip(';');
9246 break;
9248 next();
9254 /* better than nothing, but needs extension to handle '-E' option
9255 correctly too */
9256 static void preprocess_init(TCCState *s1)
9258 s1->include_stack_ptr = s1->include_stack;
9259 /* XXX: move that before to avoid having to initialize
9260 file->ifdef_stack_ptr ? */
9261 s1->ifdef_stack_ptr = s1->ifdef_stack;
9262 file->ifdef_stack_ptr = s1->ifdef_stack_ptr;
9264 /* XXX: not ANSI compliant: bound checking says error */
9265 vtop = vstack - 1;
9266 s1->pack_stack[0] = 0;
9267 s1->pack_stack_ptr = s1->pack_stack;
9270 /* compile the C file opened in 'file'. Return non zero if errors. */
9271 static int tcc_compile(TCCState *s1)
9273 Sym *define_start;
9274 char buf[512];
9275 volatile int section_sym;
9277 #ifdef INC_DEBUG
9278 printf("%s: **** new file\n", file->filename);
9279 #endif
9280 preprocess_init(s1);
9282 funcname = "";
9283 anon_sym = SYM_FIRST_ANOM;
9285 /* file info: full path + filename */
9286 section_sym = 0; /* avoid warning */
9287 if (do_debug) {
9288 section_sym = put_elf_sym(symtab_section, 0, 0,
9289 ELF32_ST_INFO(STB_LOCAL, STT_SECTION), 0,
9290 text_section->sh_num, NULL);
9291 getcwd(buf, sizeof(buf));
9292 pstrcat(buf, sizeof(buf), "/");
9293 put_stabs_r(buf, N_SO, 0, 0,
9294 text_section->data_offset, text_section, section_sym);
9295 put_stabs_r(file->filename, N_SO, 0, 0,
9296 text_section->data_offset, text_section, section_sym);
9298 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
9299 symbols can be safely used */
9300 put_elf_sym(symtab_section, 0, 0,
9301 ELF32_ST_INFO(STB_LOCAL, STT_FILE), 0,
9302 SHN_ABS, file->filename);
9304 /* define some often used types */
9305 int_type.t = VT_INT;
9307 char_pointer_type.t = VT_BYTE;
9308 mk_pointer(&char_pointer_type);
9310 func_old_type.t = VT_FUNC;
9311 func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
9313 #if 0
9314 /* define 'void *alloca(unsigned int)' builtin function */
9316 Sym *s1;
9318 p = anon_sym++;
9319 sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
9320 s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
9321 s1->next = NULL;
9322 sym->next = s1;
9323 sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
9325 #endif
9327 define_start = define_stack;
9329 if (setjmp(s1->error_jmp_buf) == 0) {
9330 s1->nb_errors = 0;
9331 s1->error_set_jmp_enabled = 1;
9333 ch = file->buf_ptr[0];
9334 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
9335 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
9336 next();
9337 decl(VT_CONST);
9338 if (tok != TOK_EOF)
9339 expect("declaration");
9341 /* end of translation unit info */
9342 if (do_debug) {
9343 put_stabs_r(NULL, N_SO, 0, 0,
9344 text_section->data_offset, text_section, section_sym);
9347 s1->error_set_jmp_enabled = 0;
9349 /* reset define stack, but leave -Dsymbols (may be incorrect if
9350 they are undefined) */
9351 free_defines(define_start);
9353 gen_inline_functions();
9355 sym_pop(&global_stack, NULL);
9357 return s1->nb_errors != 0 ? -1 : 0;
9360 /* Preprocess the current file */
9361 /* XXX: add line and file infos, add options to preserve spaces */
9362 static int tcc_preprocess(TCCState *s1)
9364 Sym *define_start;
9365 int last_is_space;
9367 preprocess_init(s1);
9369 define_start = define_stack;
9371 ch = file->buf_ptr[0];
9372 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
9373 parse_flags = PARSE_FLAG_ASM_COMMENTS | PARSE_FLAG_PREPROCESS |
9374 PARSE_FLAG_LINEFEED;
9375 last_is_space = 1;
9376 next();
9377 for(;;) {
9378 if (tok == TOK_EOF)
9379 break;
9380 if (!last_is_space) {
9381 fputc(' ', s1->outfile);
9383 fputs(get_tok_str(tok, &tokc), s1->outfile);
9384 if (tok == TOK_LINEFEED) {
9385 last_is_space = 1;
9386 /* XXX: suppress that hack */
9387 parse_flags &= ~PARSE_FLAG_LINEFEED;
9388 next();
9389 parse_flags |= PARSE_FLAG_LINEFEED;
9390 } else {
9391 last_is_space = 0;
9392 next();
9396 free_defines(define_start);
9398 return 0;
9401 #ifdef LIBTCC
9402 int tcc_compile_string(TCCState *s, const char *str)
9404 BufferedFile bf1, *bf = &bf1;
9405 int ret, len;
9406 char *buf;
9408 /* init file structure */
9409 bf->fd = -1;
9410 /* XXX: avoid copying */
9411 len = strlen(str);
9412 buf = tcc_malloc(len + 1);
9413 if (!buf)
9414 return -1;
9415 memcpy(buf, str, len);
9416 buf[len] = CH_EOB;
9417 bf->buf_ptr = buf;
9418 bf->buf_end = buf + len;
9419 pstrcpy(bf->filename, sizeof(bf->filename), "<string>");
9420 bf->line_num = 1;
9421 file = bf;
9423 ret = tcc_compile(s);
9425 tcc_free(buf);
9427 /* currently, no need to close */
9428 return ret;
9430 #endif
9432 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9433 void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
9435 BufferedFile bf1, *bf = &bf1;
9437 pstrcpy(bf->buffer, IO_BUF_SIZE, sym);
9438 pstrcat(bf->buffer, IO_BUF_SIZE, " ");
9439 /* default value */
9440 if (!value)
9441 value = "1";
9442 pstrcat(bf->buffer, IO_BUF_SIZE, value);
9444 /* init file structure */
9445 bf->fd = -1;
9446 bf->buf_ptr = bf->buffer;
9447 bf->buf_end = bf->buffer + strlen(bf->buffer);
9448 *bf->buf_end = CH_EOB;
9449 bf->filename[0] = '\0';
9450 bf->line_num = 1;
9451 file = bf;
9453 s1->include_stack_ptr = s1->include_stack;
9455 /* parse with define parser */
9456 ch = file->buf_ptr[0];
9457 next_nomacro();
9458 parse_define();
9459 file = NULL;
9462 /* undefine a preprocessor symbol */
9463 void tcc_undefine_symbol(TCCState *s1, const char *sym)
9465 TokenSym *ts;
9466 Sym *s;
9467 ts = tok_alloc(sym, strlen(sym));
9468 s = define_find(ts->tok);
9469 /* undefine symbol by putting an invalid name */
9470 if (s)
9471 define_undef(s);
9474 #ifdef CONFIG_TCC_ASM
9476 #ifdef TCC_TARGET_I386
9477 #include "i386-asm.c"
9478 #endif
9479 #include "tccasm.c"
9481 #else
9482 static void asm_instr(void)
9484 error("inline asm() not supported");
9486 static void asm_global_instr(void)
9488 error("inline asm() not supported");
9490 #endif
9492 #include "tccelf.c"
9494 #ifdef TCC_TARGET_COFF
9495 #include "tcccoff.c"
9496 #endif
9498 #ifdef TCC_TARGET_PE
9499 #include "tccpe.c"
9500 #endif
9502 /* print the position in the source file of PC value 'pc' by reading
9503 the stabs debug information */
9504 static void rt_printline(unsigned long wanted_pc)
9506 Stab_Sym *sym, *sym_end;
9507 char func_name[128], last_func_name[128];
9508 unsigned long func_addr, last_pc, pc;
9509 const char *incl_files[INCLUDE_STACK_SIZE];
9510 int incl_index, len, last_line_num, i;
9511 const char *str, *p;
9513 fprintf(stderr, "0x%08lx:", wanted_pc);
9515 func_name[0] = '\0';
9516 func_addr = 0;
9517 incl_index = 0;
9518 last_func_name[0] = '\0';
9519 last_pc = 0xffffffff;
9520 last_line_num = 1;
9521 sym = (Stab_Sym *)stab_section->data + 1;
9522 sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
9523 while (sym < sym_end) {
9524 switch(sym->n_type) {
9525 /* function start or end */
9526 case N_FUN:
9527 if (sym->n_strx == 0) {
9528 /* we test if between last line and end of function */
9529 pc = sym->n_value + func_addr;
9530 if (wanted_pc >= last_pc && wanted_pc < pc)
9531 goto found;
9532 func_name[0] = '\0';
9533 func_addr = 0;
9534 } else {
9535 str = stabstr_section->data + sym->n_strx;
9536 p = strchr(str, ':');
9537 if (!p) {
9538 pstrcpy(func_name, sizeof(func_name), str);
9539 } else {
9540 len = p - str;
9541 if (len > sizeof(func_name) - 1)
9542 len = sizeof(func_name) - 1;
9543 memcpy(func_name, str, len);
9544 func_name[len] = '\0';
9546 func_addr = sym->n_value;
9548 break;
9549 /* line number info */
9550 case N_SLINE:
9551 pc = sym->n_value + func_addr;
9552 if (wanted_pc >= last_pc && wanted_pc < pc)
9553 goto found;
9554 last_pc = pc;
9555 last_line_num = sym->n_desc;
9556 /* XXX: slow! */
9557 strcpy(last_func_name, func_name);
9558 break;
9559 /* include files */
9560 case N_BINCL:
9561 str = stabstr_section->data + sym->n_strx;
9562 add_incl:
9563 if (incl_index < INCLUDE_STACK_SIZE) {
9564 incl_files[incl_index++] = str;
9566 break;
9567 case N_EINCL:
9568 if (incl_index > 1)
9569 incl_index--;
9570 break;
9571 case N_SO:
9572 if (sym->n_strx == 0) {
9573 incl_index = 0; /* end of translation unit */
9574 } else {
9575 str = stabstr_section->data + sym->n_strx;
9576 /* do not add path */
9577 len = strlen(str);
9578 if (len > 0 && str[len - 1] != '/')
9579 goto add_incl;
9581 break;
9583 sym++;
9586 /* second pass: we try symtab symbols (no line number info) */
9587 incl_index = 0;
9589 Elf32_Sym *sym, *sym_end;
9590 int type;
9592 sym_end = (Elf32_Sym *)(symtab_section->data + symtab_section->data_offset);
9593 for(sym = (Elf32_Sym *)symtab_section->data + 1;
9594 sym < sym_end;
9595 sym++) {
9596 type = ELF32_ST_TYPE(sym->st_info);
9597 if (type == STT_FUNC) {
9598 if (wanted_pc >= sym->st_value &&
9599 wanted_pc < sym->st_value + sym->st_size) {
9600 pstrcpy(last_func_name, sizeof(last_func_name),
9601 strtab_section->data + sym->st_name);
9602 goto found;
9607 /* did not find any info: */
9608 fprintf(stderr, " ???\n");
9609 return;
9610 found:
9611 if (last_func_name[0] != '\0') {
9612 fprintf(stderr, " %s()", last_func_name);
9614 if (incl_index > 0) {
9615 fprintf(stderr, " (%s:%d",
9616 incl_files[incl_index - 1], last_line_num);
9617 for(i = incl_index - 2; i >= 0; i--)
9618 fprintf(stderr, ", included from %s", incl_files[i]);
9619 fprintf(stderr, ")");
9621 fprintf(stderr, "\n");
9624 #if !defined(WIN32) && !defined(CONFIG_TCCBOOT)
9626 #ifdef __i386__
9628 /* fix for glibc 2.1 */
9629 #ifndef REG_EIP
9630 #define REG_EIP EIP
9631 #define REG_EBP EBP
9632 #endif
9634 /* return the PC at frame level 'level'. Return non zero if not found */
9635 static int rt_get_caller_pc(unsigned long *paddr,
9636 ucontext_t *uc, int level)
9638 unsigned long fp;
9639 int i;
9641 if (level == 0) {
9642 #if defined(__FreeBSD__)
9643 *paddr = uc->uc_mcontext.mc_eip;
9644 #elif defined(__dietlibc__)
9645 *paddr = uc->uc_mcontext.eip;
9646 #else
9647 *paddr = uc->uc_mcontext.gregs[REG_EIP];
9648 #endif
9649 return 0;
9650 } else {
9651 #if defined(__FreeBSD__)
9652 fp = uc->uc_mcontext.mc_ebp;
9653 #elif defined(__dietlibc__)
9654 fp = uc->uc_mcontext.ebp;
9655 #else
9656 fp = uc->uc_mcontext.gregs[REG_EBP];
9657 #endif
9658 for(i=1;i<level;i++) {
9659 /* XXX: check address validity with program info */
9660 if (fp <= 0x1000 || fp >= 0xc0000000)
9661 return -1;
9662 fp = ((unsigned long *)fp)[0];
9664 *paddr = ((unsigned long *)fp)[1];
9665 return 0;
9668 #else
9670 #warning add arch specific rt_get_caller_pc()
9672 static int rt_get_caller_pc(unsigned long *paddr,
9673 ucontext_t *uc, int level)
9675 return -1;
9677 #endif
9679 /* emit a run time error at position 'pc' */
9680 void rt_error(ucontext_t *uc, const char *fmt, ...)
9682 va_list ap;
9683 unsigned long pc;
9684 int i;
9686 va_start(ap, fmt);
9687 fprintf(stderr, "Runtime error: ");
9688 vfprintf(stderr, fmt, ap);
9689 fprintf(stderr, "\n");
9690 for(i=0;i<num_callers;i++) {
9691 if (rt_get_caller_pc(&pc, uc, i) < 0)
9692 break;
9693 if (i == 0)
9694 fprintf(stderr, "at ");
9695 else
9696 fprintf(stderr, "by ");
9697 rt_printline(pc);
9699 exit(255);
9700 va_end(ap);
9703 /* signal handler for fatal errors */
9704 static void sig_error(int signum, siginfo_t *siginf, void *puc)
9706 ucontext_t *uc = puc;
9708 switch(signum) {
9709 case SIGFPE:
9710 switch(siginf->si_code) {
9711 case FPE_INTDIV:
9712 case FPE_FLTDIV:
9713 rt_error(uc, "division by zero");
9714 break;
9715 default:
9716 rt_error(uc, "floating point exception");
9717 break;
9719 break;
9720 case SIGBUS:
9721 case SIGSEGV:
9722 if (rt_bound_error_msg && *rt_bound_error_msg)
9723 rt_error(uc, *rt_bound_error_msg);
9724 else
9725 rt_error(uc, "dereferencing invalid pointer");
9726 break;
9727 case SIGILL:
9728 rt_error(uc, "illegal instruction");
9729 break;
9730 case SIGABRT:
9731 rt_error(uc, "abort() called");
9732 break;
9733 default:
9734 rt_error(uc, "caught signal %d", signum);
9735 break;
9737 exit(255);
9739 #endif
9741 /* do all relocations (needed before using tcc_get_symbol()) */
9742 int tcc_relocate(TCCState *s1)
9744 Section *s;
9745 int i;
9747 s1->nb_errors = 0;
9749 #ifdef TCC_TARGET_PE
9750 pe_add_runtime(s1);
9751 #else
9752 tcc_add_runtime(s1);
9753 #endif
9755 relocate_common_syms();
9757 tcc_add_linker_symbols(s1);
9759 build_got_entries(s1);
9761 /* compute relocation address : section are relocated in place. We
9762 also alloc the bss space */
9763 for(i = 1; i < s1->nb_sections; i++) {
9764 s = s1->sections[i];
9765 if (s->sh_flags & SHF_ALLOC) {
9766 if (s->sh_type == SHT_NOBITS)
9767 s->data = tcc_mallocz(s->data_offset);
9768 s->sh_addr = (unsigned long)s->data;
9772 relocate_syms(s1, 1);
9774 if (s1->nb_errors != 0)
9775 return -1;
9777 /* relocate each section */
9778 for(i = 1; i < s1->nb_sections; i++) {
9779 s = s1->sections[i];
9780 if (s->reloc)
9781 relocate_section(s1, s);
9784 /* mark executable sections as executable in memory */
9785 for(i = 1; i < s1->nb_sections; i++) {
9786 s = s1->sections[i];
9787 if ((s->sh_flags & (SHF_ALLOC | SHF_EXECINSTR)) ==
9788 (SHF_ALLOC | SHF_EXECINSTR)) {
9789 #ifdef WIN32
9791 unsigned long old_protect;
9792 VirtualProtect(s->data, s->data_offset,
9793 PAGE_EXECUTE_READWRITE, &old_protect);
9795 #else
9797 unsigned long start, end;
9798 start = (unsigned long)(s->data) & ~(PAGESIZE - 1);
9799 end = (unsigned long)(s->data + s->data_offset);
9800 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
9801 mprotect((void *)start, end - start,
9802 PROT_READ | PROT_WRITE | PROT_EXEC);
9804 #endif
9807 return 0;
9810 /* launch the compiled program with the given arguments */
9811 int tcc_run(TCCState *s1, int argc, char **argv)
9813 int (*prog_main)(int, char **);
9815 if (tcc_relocate(s1) < 0)
9816 return -1;
9818 prog_main = tcc_get_symbol_err(s1, "main");
9820 if (do_debug) {
9821 #if defined(WIN32) || defined(CONFIG_TCCBOOT)
9822 error("debug mode currently not available for Windows");
9823 #else
9824 struct sigaction sigact;
9825 /* install TCC signal handlers to print debug info on fatal
9826 runtime errors */
9827 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
9828 sigact.sa_sigaction = sig_error;
9829 sigemptyset(&sigact.sa_mask);
9830 sigaction(SIGFPE, &sigact, NULL);
9831 sigaction(SIGILL, &sigact, NULL);
9832 sigaction(SIGSEGV, &sigact, NULL);
9833 sigaction(SIGBUS, &sigact, NULL);
9834 sigaction(SIGABRT, &sigact, NULL);
9835 #endif
9838 #ifdef CONFIG_TCC_BCHECK
9839 if (do_bounds_check) {
9840 void (*bound_init)(void);
9842 /* set error function */
9843 rt_bound_error_msg = (void *)tcc_get_symbol_err(s1,
9844 "__bound_error_msg");
9846 /* XXX: use .init section so that it also work in binary ? */
9847 bound_init = (void *)tcc_get_symbol_err(s1, "__bound_init");
9848 bound_init();
9850 #endif
9851 return (*prog_main)(argc, argv);
9854 TCCState *tcc_new(void)
9856 const char *p, *r;
9857 TCCState *s;
9858 TokenSym *ts;
9859 int i, c;
9861 s = tcc_mallocz(sizeof(TCCState));
9862 if (!s)
9863 return NULL;
9864 tcc_state = s;
9865 s->output_type = TCC_OUTPUT_MEMORY;
9867 /* init isid table */
9868 for(i=0;i<256;i++)
9869 isidnum_table[i] = isid(i) || isnum(i);
9871 /* add all tokens */
9872 table_ident = NULL;
9873 memset(hash_ident, 0, TOK_HASH_SIZE * sizeof(TokenSym *));
9875 tok_ident = TOK_IDENT;
9876 p = tcc_keywords;
9877 while (*p) {
9878 r = p;
9879 for(;;) {
9880 c = *r++;
9881 if (c == '\0')
9882 break;
9884 ts = tok_alloc(p, r - p - 1);
9885 p = r;
9888 /* we add dummy defines for some special macros to speed up tests
9889 and to have working defined() */
9890 define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
9891 define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
9892 define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
9893 define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
9895 /* standard defines */
9896 tcc_define_symbol(s, "__STDC__", NULL);
9897 #if defined(TCC_TARGET_I386)
9898 tcc_define_symbol(s, "__i386__", NULL);
9899 #endif
9900 #if defined(TCC_TARGET_ARM)
9901 tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
9902 tcc_define_symbol(s, "__arm_elf__", NULL);
9903 tcc_define_symbol(s, "__arm_elf", NULL);
9904 tcc_define_symbol(s, "arm_elf", NULL);
9905 tcc_define_symbol(s, "__arm__", NULL);
9906 tcc_define_symbol(s, "__arm", NULL);
9907 tcc_define_symbol(s, "arm", NULL);
9908 tcc_define_symbol(s, "__APCS_32__", NULL);
9909 #endif
9910 #if defined(linux)
9911 tcc_define_symbol(s, "__linux__", NULL);
9912 tcc_define_symbol(s, "linux", NULL);
9913 #endif
9914 /* tiny C specific defines */
9915 tcc_define_symbol(s, "__TINYC__", NULL);
9917 /* tiny C & gcc defines */
9918 tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned int");
9919 tcc_define_symbol(s, "__PTRDIFF_TYPE__", "int");
9920 #ifdef TCC_TARGET_PE
9921 tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
9922 #else
9923 tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
9924 #endif
9926 /* default library paths */
9927 #ifdef TCC_TARGET_PE
9929 char buf[1024];
9930 snprintf(buf, sizeof(buf), "%s/lib", tcc_lib_path);
9931 tcc_add_library_path(s, buf);
9933 #else
9934 tcc_add_library_path(s, "/usr/local/lib");
9935 tcc_add_library_path(s, "/usr/lib");
9936 tcc_add_library_path(s, "/lib");
9937 #endif
9939 /* no section zero */
9940 dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
9942 /* create standard sections */
9943 text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
9944 data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
9945 bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
9947 /* symbols are always generated for linking stage */
9948 symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
9949 ".strtab",
9950 ".hashtab", SHF_PRIVATE);
9951 strtab_section = symtab_section->link;
9953 /* private symbol table for dynamic symbols */
9954 s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
9955 ".dynstrtab",
9956 ".dynhashtab", SHF_PRIVATE);
9957 s->alacarte_link = 1;
9959 #ifdef CHAR_IS_UNSIGNED
9960 s->char_is_unsigned = 1;
9961 #endif
9962 #if defined(TCC_TARGET_PE) && 0
9963 /* XXX: currently the PE linker is not ready to support that */
9964 s->leading_underscore = 1;
9965 #endif
9966 return s;
9969 void tcc_delete(TCCState *s1)
9971 int i, n;
9973 /* free -D defines */
9974 free_defines(NULL);
9976 /* free tokens */
9977 n = tok_ident - TOK_IDENT;
9978 for(i = 0; i < n; i++)
9979 tcc_free(table_ident[i]);
9980 tcc_free(table_ident);
9982 /* free all sections */
9984 free_section(symtab_section->hash);
9986 free_section(s1->dynsymtab_section->hash);
9987 free_section(s1->dynsymtab_section->link);
9988 free_section(s1->dynsymtab_section);
9990 for(i = 1; i < s1->nb_sections; i++)
9991 free_section(s1->sections[i]);
9992 tcc_free(s1->sections);
9994 /* free loaded dlls array */
9995 for(i = 0; i < s1->nb_loaded_dlls; i++)
9996 tcc_free(s1->loaded_dlls[i]);
9997 tcc_free(s1->loaded_dlls);
9999 /* library paths */
10000 for(i = 0; i < s1->nb_library_paths; i++)
10001 tcc_free(s1->library_paths[i]);
10002 tcc_free(s1->library_paths);
10004 /* cached includes */
10005 for(i = 0; i < s1->nb_cached_includes; i++)
10006 tcc_free(s1->cached_includes[i]);
10007 tcc_free(s1->cached_includes);
10009 for(i = 0; i < s1->nb_include_paths; i++)
10010 tcc_free(s1->include_paths[i]);
10011 tcc_free(s1->include_paths);
10013 for(i = 0; i < s1->nb_sysinclude_paths; i++)
10014 tcc_free(s1->sysinclude_paths[i]);
10015 tcc_free(s1->sysinclude_paths);
10017 tcc_free(s1);
10020 int tcc_add_include_path(TCCState *s1, const char *pathname)
10022 char *pathname1;
10024 pathname1 = tcc_strdup(pathname);
10025 dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
10026 return 0;
10029 int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
10031 char *pathname1;
10033 pathname1 = tcc_strdup(pathname);
10034 dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
10035 return 0;
10038 static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
10040 const char *ext, *filename1;
10041 Elf32_Ehdr ehdr;
10042 int fd, ret;
10043 BufferedFile *saved_file;
10045 /* find source file type with extension */
10046 filename1 = strrchr(filename, '/');
10047 if (filename1)
10048 filename1++;
10049 else
10050 filename1 = filename;
10051 ext = strrchr(filename1, '.');
10052 if (ext)
10053 ext++;
10055 /* open the file */
10056 saved_file = file;
10057 file = tcc_open(s1, filename);
10058 if (!file) {
10059 if (flags & AFF_PRINT_ERROR) {
10060 error_noabort("file '%s' not found", filename);
10062 ret = -1;
10063 goto fail1;
10066 if (flags & AFF_PREPROCESS) {
10067 ret = tcc_preprocess(s1);
10068 } else if (!ext || !strcmp(ext, "c")) {
10069 /* C file assumed */
10070 ret = tcc_compile(s1);
10071 } else
10072 #ifdef CONFIG_TCC_ASM
10073 if (!strcmp(ext, "S")) {
10074 /* preprocessed assembler */
10075 ret = tcc_assemble(s1, 1);
10076 } else if (!strcmp(ext, "s")) {
10077 /* non preprocessed assembler */
10078 ret = tcc_assemble(s1, 0);
10079 } else
10080 #endif
10081 #ifdef TCC_TARGET_PE
10082 if (!strcmp(ext, "def")) {
10083 ret = pe_load_def_file(s1, fdopen(file->fd, "rb"));
10084 } else
10085 #endif
10087 fd = file->fd;
10088 /* assume executable format: auto guess file type */
10089 ret = read(fd, &ehdr, sizeof(ehdr));
10090 lseek(fd, 0, SEEK_SET);
10091 if (ret <= 0) {
10092 error_noabort("could not read header");
10093 goto fail;
10094 } else if (ret != sizeof(ehdr)) {
10095 goto try_load_script;
10098 if (ehdr.e_ident[0] == ELFMAG0 &&
10099 ehdr.e_ident[1] == ELFMAG1 &&
10100 ehdr.e_ident[2] == ELFMAG2 &&
10101 ehdr.e_ident[3] == ELFMAG3) {
10102 file->line_num = 0; /* do not display line number if error */
10103 if (ehdr.e_type == ET_REL) {
10104 ret = tcc_load_object_file(s1, fd, 0);
10105 } else if (ehdr.e_type == ET_DYN) {
10106 if (s1->output_type == TCC_OUTPUT_MEMORY) {
10107 #ifdef TCC_TARGET_PE
10108 ret = -1;
10109 #else
10110 void *h;
10111 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
10112 if (h)
10113 ret = 0;
10114 else
10115 ret = -1;
10116 #endif
10117 } else {
10118 ret = tcc_load_dll(s1, fd, filename,
10119 (flags & AFF_REFERENCED_DLL) != 0);
10121 } else {
10122 error_noabort("unrecognized ELF file");
10123 goto fail;
10125 } else if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
10126 file->line_num = 0; /* do not display line number if error */
10127 ret = tcc_load_archive(s1, fd);
10128 } else
10129 #ifdef TCC_TARGET_COFF
10130 if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
10131 ret = tcc_load_coff(s1, fd);
10132 } else
10133 #endif
10135 /* as GNU ld, consider it is an ld script if not recognized */
10136 try_load_script:
10137 ret = tcc_load_ldscript(s1);
10138 if (ret < 0) {
10139 error_noabort("unrecognized file type");
10140 goto fail;
10144 the_end:
10145 tcc_close(file);
10146 fail1:
10147 file = saved_file;
10148 return ret;
10149 fail:
10150 ret = -1;
10151 goto the_end;
10154 int tcc_add_file(TCCState *s, const char *filename)
10156 return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
10159 int tcc_add_library_path(TCCState *s, const char *pathname)
10161 char *pathname1;
10163 pathname1 = tcc_strdup(pathname);
10164 dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
10165 return 0;
10168 /* find and load a dll. Return non zero if not found */
10169 /* XXX: add '-rpath' option support ? */
10170 static int tcc_add_dll(TCCState *s, const char *filename, int flags)
10172 char buf[1024];
10173 int i;
10175 for(i = 0; i < s->nb_library_paths; i++) {
10176 snprintf(buf, sizeof(buf), "%s/%s",
10177 s->library_paths[i], filename);
10178 if (tcc_add_file_internal(s, buf, flags) == 0)
10179 return 0;
10181 return -1;
10184 /* the library name is the same as the argument of the '-l' option */
10185 int tcc_add_library(TCCState *s, const char *libraryname)
10187 char buf[1024];
10188 int i;
10190 /* first we look for the dynamic library if not static linking */
10191 if (!s->static_link) {
10192 #ifdef TCC_TARGET_PE
10193 snprintf(buf, sizeof(buf), "%s.def", libraryname);
10194 #else
10195 snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
10196 #endif
10197 if (tcc_add_dll(s, buf, 0) == 0)
10198 return 0;
10201 /* then we look for the static library */
10202 for(i = 0; i < s->nb_library_paths; i++) {
10203 snprintf(buf, sizeof(buf), "%s/lib%s.a",
10204 s->library_paths[i], libraryname);
10205 if (tcc_add_file_internal(s, buf, 0) == 0)
10206 return 0;
10208 return -1;
10211 int tcc_add_symbol(TCCState *s, const char *name, unsigned long val)
10213 add_elf_sym(symtab_section, val, 0,
10214 ELF32_ST_INFO(STB_GLOBAL, STT_NOTYPE), 0,
10215 SHN_ABS, name);
10216 return 0;
10219 int tcc_set_output_type(TCCState *s, int output_type)
10221 s->output_type = output_type;
10223 if (!s->nostdinc) {
10224 char buf[1024];
10226 /* default include paths */
10227 /* XXX: reverse order needed if -isystem support */
10228 #ifndef TCC_TARGET_PE
10229 tcc_add_sysinclude_path(s, "/usr/local/include");
10230 tcc_add_sysinclude_path(s, "/usr/include");
10231 #endif
10232 snprintf(buf, sizeof(buf), "%s/include", tcc_lib_path);
10233 tcc_add_sysinclude_path(s, buf);
10234 #ifdef TCC_TARGET_PE
10235 snprintf(buf, sizeof(buf), "%s/include/winapi", tcc_lib_path);
10236 tcc_add_sysinclude_path(s, buf);
10237 #endif
10240 /* if bound checking, then add corresponding sections */
10241 #ifdef CONFIG_TCC_BCHECK
10242 if (do_bounds_check) {
10243 /* define symbol */
10244 tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
10245 /* create bounds sections */
10246 bounds_section = new_section(s, ".bounds",
10247 SHT_PROGBITS, SHF_ALLOC);
10248 lbounds_section = new_section(s, ".lbounds",
10249 SHT_PROGBITS, SHF_ALLOC);
10251 #endif
10253 if (s->char_is_unsigned) {
10254 tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
10257 /* add debug sections */
10258 if (do_debug) {
10259 /* stab symbols */
10260 stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
10261 stab_section->sh_entsize = sizeof(Stab_Sym);
10262 stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
10263 put_elf_str(stabstr_section, "");
10264 stab_section->link = stabstr_section;
10265 /* put first entry */
10266 put_stabs("", 0, 0, 0, 0);
10269 /* add libc crt1/crti objects */
10270 #ifndef TCC_TARGET_PE
10271 if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
10272 !s->nostdlib) {
10273 if (output_type != TCC_OUTPUT_DLL)
10274 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
10275 tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
10277 #endif
10278 return 0;
10281 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
10282 #define FD_INVERT 0x0002 /* invert value before storing */
10284 typedef struct FlagDef {
10285 uint16_t offset;
10286 uint16_t flags;
10287 const char *name;
10288 } FlagDef;
10290 static const FlagDef warning_defs[] = {
10291 { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
10292 { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
10293 { offsetof(TCCState, warn_error), 0, "error" },
10294 { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
10295 "implicit-function-declaration" },
10298 static int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
10299 const char *name, int value)
10301 int i;
10302 const FlagDef *p;
10303 const char *r;
10305 r = name;
10306 if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
10307 r += 3;
10308 value = !value;
10310 for(i = 0, p = flags; i < nb_flags; i++, p++) {
10311 if (!strcmp(r, p->name))
10312 goto found;
10314 return -1;
10315 found:
10316 if (p->flags & FD_INVERT)
10317 value = !value;
10318 *(int *)((uint8_t *)s + p->offset) = value;
10319 return 0;
10323 /* set/reset a warning */
10324 int tcc_set_warning(TCCState *s, const char *warning_name, int value)
10326 int i;
10327 const FlagDef *p;
10329 if (!strcmp(warning_name, "all")) {
10330 for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
10331 if (p->flags & WD_ALL)
10332 *(int *)((uint8_t *)s + p->offset) = 1;
10334 return 0;
10335 } else {
10336 return set_flag(s, warning_defs, countof(warning_defs),
10337 warning_name, value);
10341 static const FlagDef flag_defs[] = {
10342 { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
10343 { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
10344 { offsetof(TCCState, nocommon), FD_INVERT, "common" },
10345 { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
10348 /* set/reset a flag */
10349 int tcc_set_flag(TCCState *s, const char *flag_name, int value)
10351 return set_flag(s, flag_defs, countof(flag_defs),
10352 flag_name, value);
10355 /* extract the basename of a file */
10356 static char *tcc_basename(const char *name)
10358 const char *p;
10359 p = strrchr(name, '/');
10360 #ifdef WIN32
10361 if (!p)
10362 p = strrchr(name, '\\');
10363 #endif
10364 if (!p)
10365 p = name;
10366 else
10367 p++;
10368 return (char*)p;
10371 #if !defined(LIBTCC)
10373 static int64_t getclock_us(void)
10375 #ifdef WIN32
10376 struct _timeb tb;
10377 _ftime(&tb);
10378 return (tb.time * 1000LL + tb.millitm) * 1000LL;
10379 #else
10380 struct timeval tv;
10381 gettimeofday(&tv, NULL);
10382 return tv.tv_sec * 1000000LL + tv.tv_usec;
10383 #endif
10386 void help(void)
10388 printf("tcc version " TCC_VERSION " - Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard\n"
10389 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
10390 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]\n"
10391 " [infile1 infile2...] [-run infile args...]\n"
10392 "\n"
10393 "General options:\n"
10394 " -v display current version\n"
10395 " -c compile only - generate an object file\n"
10396 " -o outfile set output filename\n"
10397 " -Bdir set tcc internal library path\n"
10398 " -bench output compilation statistics\n"
10399 " -run run compiled source\n"
10400 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
10401 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
10402 " -w disable all warnings\n"
10403 "Preprocessor options:\n"
10404 " -E preprocess only\n"
10405 " -Idir add include path 'dir'\n"
10406 " -Dsym[=val] define 'sym' with value 'val'\n"
10407 " -Usym undefine 'sym'\n"
10408 "Linker options:\n"
10409 " -Ldir add library path 'dir'\n"
10410 " -llib link with dynamic or static library 'lib'\n"
10411 " -shared generate a shared library\n"
10412 " -static static linking\n"
10413 " -rdynamic export all global symbols to dynamic linker\n"
10414 " -r relocatable output\n"
10415 "Debugger options:\n"
10416 " -g generate runtime debug info\n"
10417 #ifdef CONFIG_TCC_BCHECK
10418 " -b compile with built-in memory and bounds checker (implies -g)\n"
10419 #endif
10420 " -bt N show N callers in stack traces\n"
10424 #define TCC_OPTION_HAS_ARG 0x0001
10425 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
10427 typedef struct TCCOption {
10428 const char *name;
10429 uint16_t index;
10430 uint16_t flags;
10431 } TCCOption;
10433 enum {
10434 TCC_OPTION_HELP,
10435 TCC_OPTION_I,
10436 TCC_OPTION_D,
10437 TCC_OPTION_U,
10438 TCC_OPTION_L,
10439 TCC_OPTION_B,
10440 TCC_OPTION_l,
10441 TCC_OPTION_bench,
10442 TCC_OPTION_bt,
10443 TCC_OPTION_b,
10444 TCC_OPTION_g,
10445 TCC_OPTION_c,
10446 TCC_OPTION_static,
10447 TCC_OPTION_shared,
10448 TCC_OPTION_o,
10449 TCC_OPTION_r,
10450 TCC_OPTION_Wl,
10451 TCC_OPTION_W,
10452 TCC_OPTION_O,
10453 TCC_OPTION_m,
10454 TCC_OPTION_f,
10455 TCC_OPTION_nostdinc,
10456 TCC_OPTION_nostdlib,
10457 TCC_OPTION_print_search_dirs,
10458 TCC_OPTION_rdynamic,
10459 TCC_OPTION_run,
10460 TCC_OPTION_v,
10461 TCC_OPTION_w,
10462 TCC_OPTION_pipe,
10463 TCC_OPTION_E,
10466 static const TCCOption tcc_options[] = {
10467 { "h", TCC_OPTION_HELP, 0 },
10468 { "?", TCC_OPTION_HELP, 0 },
10469 { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
10470 { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
10471 { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
10472 { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
10473 { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
10474 { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
10475 { "bench", TCC_OPTION_bench, 0 },
10476 { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG },
10477 #ifdef CONFIG_TCC_BCHECK
10478 { "b", TCC_OPTION_b, 0 },
10479 #endif
10480 { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
10481 { "c", TCC_OPTION_c, 0 },
10482 { "static", TCC_OPTION_static, 0 },
10483 { "shared", TCC_OPTION_shared, 0 },
10484 { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
10485 { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
10486 { "rdynamic", TCC_OPTION_rdynamic, 0 },
10487 { "r", TCC_OPTION_r, 0 },
10488 { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
10489 { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
10490 { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
10491 { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG },
10492 { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
10493 { "nostdinc", TCC_OPTION_nostdinc, 0 },
10494 { "nostdlib", TCC_OPTION_nostdlib, 0 },
10495 { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
10496 { "v", TCC_OPTION_v, 0 },
10497 { "w", TCC_OPTION_w, 0 },
10498 { "pipe", TCC_OPTION_pipe, 0},
10499 { "E", TCC_OPTION_E, 0},
10500 { NULL },
10503 /* convert 'str' into an array of space separated strings */
10504 static int expand_args(char ***pargv, const char *str)
10506 const char *s1;
10507 char **argv, *arg;
10508 int argc, len;
10510 argc = 0;
10511 argv = NULL;
10512 for(;;) {
10513 while (is_space(*str))
10514 str++;
10515 if (*str == '\0')
10516 break;
10517 s1 = str;
10518 while (*str != '\0' && !is_space(*str))
10519 str++;
10520 len = str - s1;
10521 arg = tcc_malloc(len + 1);
10522 memcpy(arg, s1, len);
10523 arg[len] = '\0';
10524 dynarray_add((void ***)&argv, &argc, arg);
10526 *pargv = argv;
10527 return argc;
10530 static char **files;
10531 static int nb_files, nb_libraries;
10532 static int multiple_files;
10533 static int print_search_dirs;
10534 static int output_type;
10535 static int reloc_output;
10536 static const char *outfile;
10538 int parse_args(TCCState *s, int argc, char **argv)
10540 int optind;
10541 const TCCOption *popt;
10542 const char *optarg, *p1, *r1;
10543 char *r;
10545 optind = 0;
10546 while (1) {
10547 if (optind >= argc) {
10548 if (nb_files == 0 && !print_search_dirs)
10549 goto show_help;
10550 else
10551 break;
10553 r = argv[optind++];
10554 if (r[0] != '-') {
10555 /* add a new file */
10556 dynarray_add((void ***)&files, &nb_files, r);
10557 if (!multiple_files) {
10558 optind--;
10559 /* argv[0] will be this file */
10560 break;
10562 } else {
10563 /* find option in table (match only the first chars */
10564 popt = tcc_options;
10565 for(;;) {
10566 p1 = popt->name;
10567 if (p1 == NULL)
10568 error("invalid option -- '%s'", r);
10569 r1 = r + 1;
10570 for(;;) {
10571 if (*p1 == '\0')
10572 goto option_found;
10573 if (*r1 != *p1)
10574 break;
10575 p1++;
10576 r1++;
10578 popt++;
10580 option_found:
10581 if (popt->flags & TCC_OPTION_HAS_ARG) {
10582 if (*r1 != '\0' || (popt->flags & TCC_OPTION_NOSEP)) {
10583 optarg = r1;
10584 } else {
10585 if (optind >= argc)
10586 error("argument to '%s' is missing", r);
10587 optarg = argv[optind++];
10589 } else {
10590 if (*r1 != '\0')
10591 goto show_help;
10592 optarg = NULL;
10595 switch(popt->index) {
10596 case TCC_OPTION_HELP:
10597 show_help:
10598 help();
10599 exit(1);
10600 case TCC_OPTION_I:
10601 if (tcc_add_include_path(s, optarg) < 0)
10602 error("too many include paths");
10603 break;
10604 case TCC_OPTION_D:
10606 char *sym, *value;
10607 sym = (char *)optarg;
10608 value = strchr(sym, '=');
10609 if (value) {
10610 *value = '\0';
10611 value++;
10613 tcc_define_symbol(s, sym, value);
10615 break;
10616 case TCC_OPTION_U:
10617 tcc_undefine_symbol(s, optarg);
10618 break;
10619 case TCC_OPTION_L:
10620 tcc_add_library_path(s, optarg);
10621 break;
10622 case TCC_OPTION_B:
10623 /* set tcc utilities path (mainly for tcc development) */
10624 tcc_lib_path = optarg;
10625 break;
10626 case TCC_OPTION_l:
10627 dynarray_add((void ***)&files, &nb_files, r);
10628 nb_libraries++;
10629 break;
10630 case TCC_OPTION_bench:
10631 do_bench = 1;
10632 break;
10633 case TCC_OPTION_bt:
10634 num_callers = atoi(optarg);
10635 break;
10636 #ifdef CONFIG_TCC_BCHECK
10637 case TCC_OPTION_b:
10638 do_bounds_check = 1;
10639 do_debug = 1;
10640 break;
10641 #endif
10642 case TCC_OPTION_g:
10643 do_debug = 1;
10644 break;
10645 case TCC_OPTION_c:
10646 multiple_files = 1;
10647 output_type = TCC_OUTPUT_OBJ;
10648 break;
10649 case TCC_OPTION_static:
10650 s->static_link = 1;
10651 break;
10652 case TCC_OPTION_shared:
10653 output_type = TCC_OUTPUT_DLL;
10654 break;
10655 case TCC_OPTION_o:
10656 multiple_files = 1;
10657 outfile = optarg;
10658 break;
10659 case TCC_OPTION_r:
10660 /* generate a .o merging several output files */
10661 reloc_output = 1;
10662 output_type = TCC_OUTPUT_OBJ;
10663 break;
10664 case TCC_OPTION_nostdinc:
10665 s->nostdinc = 1;
10666 break;
10667 case TCC_OPTION_nostdlib:
10668 s->nostdlib = 1;
10669 break;
10670 case TCC_OPTION_print_search_dirs:
10671 print_search_dirs = 1;
10672 break;
10673 case TCC_OPTION_run:
10675 int argc1;
10676 char **argv1;
10677 argc1 = expand_args(&argv1, optarg);
10678 if (argc1 > 0) {
10679 parse_args(s, argc1, argv1);
10681 multiple_files = 0;
10682 output_type = TCC_OUTPUT_MEMORY;
10684 break;
10685 case TCC_OPTION_v:
10686 printf("tcc version %s\n", TCC_VERSION);
10687 exit(0);
10688 case TCC_OPTION_f:
10689 if (tcc_set_flag(s, optarg, 1) < 0 && s->warn_unsupported)
10690 goto unsupported_option;
10691 break;
10692 case TCC_OPTION_W:
10693 if (tcc_set_warning(s, optarg, 1) < 0 &&
10694 s->warn_unsupported)
10695 goto unsupported_option;
10696 break;
10697 case TCC_OPTION_w:
10698 s->warn_none = 1;
10699 break;
10700 case TCC_OPTION_rdynamic:
10701 s->rdynamic = 1;
10702 break;
10703 case TCC_OPTION_Wl:
10705 const char *p;
10706 if (strstart(optarg, "-Ttext,", &p)) {
10707 s->text_addr = strtoul(p, NULL, 16);
10708 s->has_text_addr = 1;
10709 } else if (strstart(optarg, "--oformat,", &p)) {
10710 if (strstart(p, "elf32-", NULL)) {
10711 s->output_format = TCC_OUTPUT_FORMAT_ELF;
10712 } else if (!strcmp(p, "binary")) {
10713 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
10714 } else
10715 #ifdef TCC_TARGET_COFF
10716 if (!strcmp(p, "coff")) {
10717 s->output_format = TCC_OUTPUT_FORMAT_COFF;
10718 } else
10719 #endif
10721 error("target %s not found", p);
10723 } else {
10724 error("unsupported linker option '%s'", optarg);
10727 break;
10728 case TCC_OPTION_E:
10729 output_type = TCC_OUTPUT_PREPROCESS;
10730 break;
10731 default:
10732 if (s->warn_unsupported) {
10733 unsupported_option:
10734 warning("unsupported option '%s'", r);
10736 break;
10740 return optind;
10743 int main(int argc, char **argv)
10745 int i;
10746 TCCState *s;
10747 int nb_objfiles, ret, optind;
10748 char objfilename[1024];
10749 int64_t start_time = 0;
10751 #ifdef WIN32
10752 /* on win32, we suppose the lib and includes are at the location
10753 of 'tcc.exe' */
10755 static char path[1024];
10756 char *p, *d;
10758 GetModuleFileNameA(NULL, path, sizeof path);
10759 p = d = strlwr(path);
10760 while (*d)
10762 if (*d == '\\') *d = '/', p = d;
10763 ++d;
10765 *p = '\0';
10766 tcc_lib_path = path;
10768 #endif
10770 s = tcc_new();
10771 output_type = TCC_OUTPUT_EXE;
10772 outfile = NULL;
10773 multiple_files = 1;
10774 files = NULL;
10775 nb_files = 0;
10776 nb_libraries = 0;
10777 reloc_output = 0;
10778 print_search_dirs = 0;
10780 optind = parse_args(s, argc - 1, argv + 1) + 1;
10782 if (print_search_dirs) {
10783 /* enough for Linux kernel */
10784 printf("install: %s/\n", tcc_lib_path);
10785 return 0;
10788 nb_objfiles = nb_files - nb_libraries;
10790 /* if outfile provided without other options, we output an
10791 executable */
10792 if (outfile && output_type == TCC_OUTPUT_MEMORY)
10793 output_type = TCC_OUTPUT_EXE;
10795 /* check -c consistency : only single file handled. XXX: checks file type */
10796 if (output_type == TCC_OUTPUT_OBJ && !reloc_output) {
10797 /* accepts only a single input file */
10798 if (nb_objfiles != 1)
10799 error("cannot specify multiple files with -c");
10800 if (nb_libraries != 0)
10801 error("cannot specify libraries with -c");
10805 if (output_type == TCC_OUTPUT_PREPROCESS) {
10806 if (!outfile) {
10807 s->outfile = stdout;
10808 } else {
10809 s->outfile = fopen(outfile, "wb");
10810 if (!s->outfile)
10811 error("could not open '%s", outfile);
10813 } else if (output_type != TCC_OUTPUT_MEMORY) {
10814 if (!outfile) {
10815 /* compute default outfile name */
10816 pstrcpy(objfilename, sizeof(objfilename) - 1,
10817 /* strip path */
10818 tcc_basename(files[0]));
10819 #ifdef TCC_TARGET_PE
10820 pe_guess_outfile(objfilename, output_type);
10821 #else
10822 if (output_type == TCC_OUTPUT_OBJ && !reloc_output) {
10823 char *ext = strrchr(objfilename, '.');
10824 if (!ext)
10825 goto default_outfile;
10826 /* add .o extension */
10827 strcpy(ext + 1, "o");
10828 } else {
10829 default_outfile:
10830 pstrcpy(objfilename, sizeof(objfilename), "a.out");
10832 #endif
10833 outfile = objfilename;
10837 if (do_bench) {
10838 start_time = getclock_us();
10841 tcc_set_output_type(s, output_type);
10843 /* compile or add each files or library */
10844 for(i = 0;i < nb_files; i++) {
10845 const char *filename;
10847 filename = files[i];
10848 if (output_type == TCC_OUTPUT_PREPROCESS) {
10849 tcc_add_file_internal(s, filename,
10850 AFF_PRINT_ERROR | AFF_PREPROCESS);
10851 } else {
10852 if (filename[0] == '-') {
10853 if (tcc_add_library(s, filename + 2) < 0)
10854 error("cannot find %s", filename);
10855 } else {
10856 if (tcc_add_file(s, filename) < 0) {
10857 ret = 1;
10858 goto the_end;
10864 /* free all files */
10865 tcc_free(files);
10867 if (do_bench) {
10868 double total_time;
10869 total_time = (double)(getclock_us() - start_time) / 1000000.0;
10870 if (total_time < 0.001)
10871 total_time = 0.001;
10872 if (total_bytes < 1)
10873 total_bytes = 1;
10874 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
10875 tok_ident - TOK_IDENT, total_lines, total_bytes,
10876 total_time, (int)(total_lines / total_time),
10877 total_bytes / total_time / 1000000.0);
10880 if (s->output_type == TCC_OUTPUT_PREPROCESS) {
10881 if (outfile)
10882 fclose(s->outfile);
10883 ret = 0;
10884 } else if (s->output_type == TCC_OUTPUT_MEMORY) {
10885 ret = tcc_run(s, argc - optind, argv + optind);
10886 } else
10887 #ifdef TCC_TARGET_PE
10888 if (s->output_type != TCC_OUTPUT_OBJ) {
10889 ret = tcc_output_pe(s, outfile);
10890 } else
10891 #endif
10893 ret = tcc_output_file(s, outfile) ? 1 : 0;
10895 the_end:
10896 /* XXX: cannot do it with bound checking because of the malloc hooks */
10897 if (!do_bounds_check)
10898 tcc_delete(s);
10900 #ifdef MEM_DEBUG
10901 if (do_bench) {
10902 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size, mem_max_size);
10904 #endif
10905 return ret;
10908 #endif