2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001, 2002, 2003 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
36 #include <sys/timeb.h>
40 #include <sys/ucontext.h>
44 #ifndef CONFIG_TCC_STATIC
52 /* preprocessor debug */
54 /* include file debug */
62 /* target selection */
63 //#define TCC_TARGET_I386 /* i386 code generator */
64 //#define TCC_TARGET_ARM /* ARMv4 code generator */
65 //#define TCC_TARGET_C67 /* TMS320C67xx code generator */
67 /* default target is I386 */
68 #if !defined(TCC_TARGET_I386) && !defined(TCC_TARGET_ARM) && \
69 !defined(TCC_TARGET_C67)
70 #define TCC_TARGET_I386
73 #if !defined(WIN32) && !defined(TCC_UCLIBC) && !defined(TCC_TARGET_ARM) && \
74 !defined(TCC_TARGET_C67)
75 #define CONFIG_TCC_BCHECK /* enable bound checking code */
78 /* define it to include assembler support */
79 #if !defined(TCC_TARGET_ARM) && !defined(TCC_TARGET_C67)
80 #define CONFIG_TCC_ASM
83 /* object format selection */
84 #if defined(TCC_TARGET_C67)
85 #define TCC_TARGET_COFF
96 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
97 executables or dlls */
98 #define CONFIG_TCC_CRT_PREFIX "/usr/lib"
100 #define INCLUDE_STACK_SIZE 32
101 #define IFDEF_STACK_SIZE 64
102 #define VSTACK_SIZE 64
103 #define STRING_MAX_SIZE 1024
105 #define TOK_HASH_SIZE 2048 /* must be a power of two */
106 #define TOK_ALLOC_INCR 512 /* must be a power of two */
107 #define TOK_STR_ALLOC_INCR_BITS 6
108 #define TOK_STR_ALLOC_INCR (1 << TOK_STR_ALLOC_INCR_BITS)
109 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
111 /* token symbol management */
112 typedef struct TokenSym
{
113 struct TokenSym
*hash_next
;
114 struct Sym
*sym_define
; /* direct pointer to define */
115 struct Sym
*sym_label
; /* direct pointer to label */
116 struct Sym
*sym_struct
; /* direct pointer to structure */
117 struct Sym
*sym_identifier
; /* direct pointer to identifier */
118 int tok
; /* token number */
123 typedef struct CString
{
124 int size
; /* size in bytes */
125 void *data
; /* either 'char *' or 'int *' */
127 void *data_allocated
; /* if non NULL, data has been malloced */
130 /* type definition */
131 typedef struct CType
{
137 typedef union CValue
{
143 unsigned int ul
; /* address (should be unsigned long on 64 bit cpu) */
145 unsigned long long ull
;
146 struct CString
*cstr
;
152 typedef struct SValue
{
153 CType type
; /* type */
154 unsigned short r
; /* register + flags */
155 unsigned short r2
; /* second register, used for 'long long'
156 type. If not used, set to VT_CONST */
157 CValue c
; /* constant, if VT_CONST */
158 struct Sym
*sym
; /* symbol, if (VT_SYM | VT_CONST) */
161 /* symbol management */
163 int v
; /* symbol token */
164 int r
; /* associated register */
165 int c
; /* associated number */
166 CType type
; /* associated type */
167 struct Sym
*next
; /* next related symbol */
168 struct Sym
*prev
; /* prev symbol in stack */
169 struct Sym
*prev_tok
; /* previous symbol for this token */
172 /* section definition */
173 /* XXX: use directly ELF structure for parameters ? */
174 /* special flag to indicate that the section should not be linked to
176 #define SHF_PRIVATE 0x80000000
178 typedef struct Section
{
179 unsigned long data_offset
; /* current data offset */
180 unsigned char *data
; /* section data */
181 unsigned long data_allocated
; /* used for realloc() handling */
182 int sh_name
; /* elf section name (only used during output) */
183 int sh_num
; /* elf section number */
184 int sh_type
; /* elf section type */
185 int sh_flags
; /* elf section flags */
186 int sh_info
; /* elf section info */
187 int sh_addralign
; /* elf section alignment */
188 int sh_entsize
; /* elf entry size */
189 unsigned long sh_size
; /* section size (only used during output) */
190 unsigned long sh_addr
; /* address at which the section is relocated */
191 unsigned long sh_offset
; /* address at which the section is relocated */
192 int nb_hashed_syms
; /* used to resize the hash table */
193 struct Section
*link
; /* link to another section */
194 struct Section
*reloc
; /* corresponding section for relocation, if any */
195 struct Section
*hash
; /* hash table for symbols */
196 struct Section
*next
;
197 char name
[1]; /* section name */
200 typedef struct DLLReference
{
205 /* GNUC attribute definition */
206 typedef struct AttributeDef
{
209 unsigned char func_call
; /* FUNC_CDECL or FUNC_STDCALL */
212 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
213 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
214 #define SYM_FIRST_ANOM (1 << (31 - VT_STRUCT_SHIFT)) /* first anonymous sym */
216 /* stored in 'Sym.c' field */
217 #define FUNC_NEW 1 /* ansi function prototype */
218 #define FUNC_OLD 2 /* old function prototype */
219 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
221 /* stored in 'Sym.r' field */
222 #define FUNC_CDECL 0 /* standard c call */
223 #define FUNC_STDCALL 1 /* pascal c call */
225 /* field 'Sym.t' for macros */
226 #define MACRO_OBJ 0 /* object like macro */
227 #define MACRO_FUNC 1 /* function like macro */
229 /* field 'Sym.r' for C labels */
230 #define LABEL_DEFINED 0 /* label is defined */
231 #define LABEL_FORWARD 1 /* label is forward defined */
232 #define LABEL_DECLARED 2 /* label is declared but never used */
234 /* type_decl() types */
235 #define TYPE_ABSTRACT 1 /* type without variable */
236 #define TYPE_DIRECT 2 /* type with variable */
238 #define IO_BUF_SIZE 8192
240 typedef struct BufferedFile
{
244 int line_num
; /* current line number - here to simplify code */
245 int ifndef_macro
; /* #ifndef macro / #endif search */
246 int ifndef_macro_saved
; /* saved ifndef_macro */
247 int *ifdef_stack_ptr
; /* ifdef_stack value at the start of the file */
248 char inc_type
; /* type of include */
249 char inc_filename
[512]; /* filename specified by the user */
250 char filename
[1024]; /* current filename - here to simplify code */
251 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
254 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
255 #define CH_EOF (-1) /* end of file */
257 /* parsing state (used to save parser state to reparse part of the
258 source several times) */
259 typedef struct ParseState
{
266 /* used to record tokens */
267 typedef struct TokenString
{
274 /* include file cache, used to find files faster and also to eliminate
275 inclusion if the include file is protected by #ifndef ... #endif */
276 typedef struct CachedInclude
{
278 char type
; /* '"' or '>' to give include type */
279 char filename
[1]; /* path specified in #include */
283 static struct BufferedFile
*file
;
286 static CString tokcstr
; /* current parsed string, if any */
287 /* additional informations about token */
288 static int tok_flags
;
289 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
290 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
291 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
293 static int *macro_ptr
, *macro_ptr_allocated
;
294 static int *unget_saved_macro_ptr
;
295 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
296 static int unget_buffer_enabled
;
297 static int parse_flags
;
298 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
299 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
300 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
301 token. line feed is also
304 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
305 static Section
*cur_text_section
; /* current section where function code is
307 /* bound check related sections */
308 static Section
*bounds_section
; /* contains global data bound description */
309 static Section
*lbounds_section
; /* contains local data bound description */
310 /* symbol sections */
311 static Section
*symtab_section
, *strtab_section
;
314 static Section
*stab_section
, *stabstr_section
;
316 /* loc : local variable index
317 ind : output code index
319 anon_sym: anonymous symbol index
321 static int rsym
, anon_sym
, ind
, loc
;
322 /* expression generation modifiers */
323 static int const_wanted
; /* true if constant wanted */
324 static int nocode_wanted
; /* true if no code generation wanted for an expression */
325 static int global_expr
; /* true if compound literals must be allocated
326 globally (used during initializers parsing */
327 static CType func_vt
; /* current function return type (used by return
330 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
331 static int tok_ident
;
332 static TokenSym
**table_ident
;
333 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
334 static char token_buf
[STRING_MAX_SIZE
+ 1];
335 static char *funcname
;
336 static Sym
*global_stack
, *local_stack
;
337 static Sym
*define_stack
;
338 static Sym
*global_label_stack
, *local_label_stack
;
340 static SValue vstack
[VSTACK_SIZE
], *vtop
;
341 /* some predefined types */
342 static CType char_pointer_type
, func_old_type
, int_type
;
343 /* true if isid(c) || isnum(c) */
344 static unsigned char isidnum_table
[256];
346 /* compile with debug symbol (and use them if error during execution) */
347 static int do_debug
= 0;
349 /* compile with built-in memory and bounds checker */
350 static int do_bounds_check
= 0;
352 /* display benchmark infos */
354 static int do_bench
= 0;
356 static int total_lines
;
357 static int total_bytes
;
359 /* use GNU C extensions */
360 static int gnu_ext
= 1;
362 /* use Tiny C extensions */
363 static int tcc_ext
= 1;
365 /* max number of callers shown if error */
366 static int num_callers
= 6;
367 static const char **rt_bound_error_msg
;
369 /* XXX: get rid of this ASAP */
370 static struct TCCState
*tcc_state
;
372 /* give the path of the tcc libraries */
373 static const char *tcc_lib_path
= CONFIG_TCC_LIBDIR
"/tcc";
378 BufferedFile
**include_stack_ptr
;
379 int *ifdef_stack_ptr
;
381 /* include file handling */
382 char **include_paths
;
383 int nb_include_paths
;
384 char **sysinclude_paths
;
385 int nb_sysinclude_paths
;
386 CachedInclude
**cached_includes
;
387 int nb_cached_includes
;
389 char **library_paths
;
390 int nb_library_paths
;
392 /* array of all loaded dlls (including those referenced by loaded
394 DLLReference
**loaded_dlls
;
399 int nb_sections
; /* number of sections, including first dummy section */
404 unsigned long *got_offsets
;
406 /* give the correspondance from symtab indexes to dynsym indexes */
407 int *symtab_to_dynsym
;
409 /* temporary dynamic symbol sections (for dll loading) */
410 Section
*dynsymtab_section
;
411 /* exported dynamic symbol section */
414 int nostdinc
; /* if true, no standard headers are added */
415 int nostdlib
; /* if true, no standard libraries are added */
417 /* if true, static linking is performed */
420 /* if true, all symbols are exported */
423 /* if true, only link in referenced objects from archive */
426 /* C language options */
427 int char_is_unsigned
;
429 /* warning switches */
430 int warn_write_strings
;
431 int warn_unsupported
;
434 int warn_implicit_function_declaration
;
438 void (*error_func
)(void *opaque
, const char *msg
);
439 int error_set_jmp_enabled
;
440 jmp_buf error_jmp_buf
;
443 /* tiny assembler state */
446 /* see include_stack_ptr */
447 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
449 /* see ifdef_stack_ptr */
450 int ifdef_stack
[IFDEF_STACK_SIZE
];
453 /* The current value can be: */
454 #define VT_VALMASK 0x00ff
455 #define VT_CONST 0x00f0 /* constant in vc
456 (must be first non register value) */
457 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
458 #define VT_LOCAL 0x00f2 /* offset on stack */
459 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
460 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
461 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
462 #define VT_LVAL 0x0100 /* var is an lvalue */
463 #define VT_SYM 0x0200 /* a symbol value is added */
464 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
465 char/short stored in integer registers) */
466 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
467 dereferencing value */
468 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
469 bounding function call point is in vc */
470 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
471 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
472 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
473 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
476 #define VT_INT 0 /* integer type */
477 #define VT_BYTE 1 /* signed byte type */
478 #define VT_SHORT 2 /* short type */
479 #define VT_VOID 3 /* void type */
480 #define VT_PTR 4 /* pointer */
481 #define VT_ENUM 5 /* enum definition */
482 #define VT_FUNC 6 /* function type */
483 #define VT_STRUCT 7 /* struct/union definition */
484 #define VT_FLOAT 8 /* IEEE float */
485 #define VT_DOUBLE 9 /* IEEE double */
486 #define VT_LDOUBLE 10 /* IEEE long double */
487 #define VT_BOOL 11 /* ISOC99 boolean type */
488 #define VT_LLONG 12 /* 64 bit integer */
489 #define VT_LONG 13 /* long integer (NEVER USED as type, only
491 #define VT_BTYPE 0x000f /* mask for basic type */
492 #define VT_UNSIGNED 0x0010 /* unsigned type */
493 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
494 #define VT_BITFIELD 0x0040 /* bitfield modifier */
495 #define VT_CONSTANT 0x0800 /* const modifier */
496 #define VT_VOLATILE 0x1000 /* volatile modifier */
497 #define VT_SIGNED 0x2000 /* signed type */
500 #define VT_EXTERN 0x00000080 /* extern definition */
501 #define VT_STATIC 0x00000100 /* static variable */
502 #define VT_TYPEDEF 0x00000200 /* typedef definition */
503 #define VT_INLINE 0x00000400 /* inline definition */
505 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
507 /* type mask (except storage) */
508 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
509 #define VT_TYPE (~(VT_STORAGE))
513 /* warning: the following compare tokens depend on i386 asm code */
525 #define TOK_LAND 0xa0
529 #define TOK_MID 0xa3 /* inc/dec, to void constant */
531 #define TOK_UDIV 0xb0 /* unsigned division */
532 #define TOK_UMOD 0xb1 /* unsigned modulo */
533 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
534 #define TOK_CINT 0xb3 /* number in tokc */
535 #define TOK_CCHAR 0xb4 /* char constant in tokc */
536 #define TOK_STR 0xb5 /* pointer to string in tokc */
537 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
538 #define TOK_LCHAR 0xb7
539 #define TOK_LSTR 0xb8
540 #define TOK_CFLOAT 0xb9 /* float constant */
541 #define TOK_LINENUM 0xba /* line number info */
542 #define TOK_CDOUBLE 0xc0 /* double constant */
543 #define TOK_CLDOUBLE 0xc1 /* long double constant */
544 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
545 #define TOK_ADDC1 0xc3 /* add with carry generation */
546 #define TOK_ADDC2 0xc4 /* add with carry use */
547 #define TOK_SUBC1 0xc5 /* add with carry generation */
548 #define TOK_SUBC2 0xc6 /* add with carry use */
549 #define TOK_CUINT 0xc8 /* unsigned int constant */
550 #define TOK_CLLONG 0xc9 /* long long constant */
551 #define TOK_CULLONG 0xca /* unsigned long long constant */
552 #define TOK_ARROW 0xcb
553 #define TOK_DOTS 0xcc /* three dots */
554 #define TOK_SHR 0xcd /* unsigned shift right */
555 #define TOK_PPNUM 0xce /* preprocessor number */
557 #define TOK_SHL 0x01 /* shift left */
558 #define TOK_SAR 0x02 /* signed shift right */
560 /* assignement operators : normal operator or 0x80 */
561 #define TOK_A_MOD 0xa5
562 #define TOK_A_AND 0xa6
563 #define TOK_A_MUL 0xaa
564 #define TOK_A_ADD 0xab
565 #define TOK_A_SUB 0xad
566 #define TOK_A_DIV 0xaf
567 #define TOK_A_XOR 0xde
568 #define TOK_A_OR 0xfc
569 #define TOK_A_SHL 0x81
570 #define TOK_A_SAR 0x82
573 #define offsetof(type, field) ((size_t) &((type *)0)->field)
577 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
580 /* WARNING: the content of this string encodes token numbers */
581 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";
583 #define TOK_EOF (-1) /* end of file */
584 #define TOK_LINEFEED 10 /* line feed */
586 /* all identificators and strings have token above that */
587 #define TOK_IDENT 256
589 /* only used for i386 asm opcodes definitions */
590 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
593 DEF(TOK_ASM_ ## x ## b, #x "b") \
594 DEF(TOK_ASM_ ## x ## w, #x "w") \
595 DEF(TOK_ASM_ ## x ## l, #x "l") \
596 DEF(TOK_ASM_ ## x, #x)
599 DEF(TOK_ASM_ ## x ## w, #x "w") \
600 DEF(TOK_ASM_ ## x ## l, #x "l") \
601 DEF(TOK_ASM_ ## x, #x)
604 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
605 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
606 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
607 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
610 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
611 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
614 #define DEF_ASMTEST(x) \
646 #define TOK_ASM_int TOK_INT
649 TOK_LAST
= TOK_IDENT
- 1,
650 #define DEF(id, str) id,
655 static const char tcc_keywords
[] =
656 #define DEF(id, str) str "\0"
661 #define TOK_UIDENT TOK_DEFINE
664 #define snprintf _snprintf
665 #define vsnprintf _vsnprintf
668 #if defined(WIN32) || defined(TCC_UCLIBC) || defined(__FreeBSD__)
669 /* currently incorrect */
670 long double strtold(const char *nptr
, char **endptr
)
672 return (long double)strtod(nptr
, endptr
);
674 float strtof(const char *nptr
, char **endptr
)
676 return (float)strtod(nptr
, endptr
);
679 /* XXX: need to define this to use them in non ISOC99 context */
680 extern float strtof (const char *__nptr
, char **__endptr
);
681 extern long double strtold (const char *__nptr
, char **__endptr
);
684 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
685 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
687 static void next(void);
688 static void next_nomacro(void);
689 static void parse_expr_type(CType
*type
);
690 static void expr_type(CType
*type
);
691 static void unary_type(CType
*type
);
692 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
693 int case_reg
, int is_expr
);
694 static int expr_const(void);
695 static void expr_eq(void);
696 static void gexpr(void);
697 static void decl(int l
);
698 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
699 int first
, int size_only
);
700 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
701 int has_init
, int v
, int scope
);
703 void gv2(int rc1
, int rc2
);
704 void move_reg(int r
, int s
);
705 void save_regs(int n
);
706 void save_reg(int r
);
711 int get_reg_ex(int rc
,int rc2
);
713 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
714 const int *macro_str
, int can_read_stream
);
715 int save_reg_forced(int r
);
717 void force_charshort_cast(int t
);
718 static void gen_cast(CType
*type
);
720 static Sym
*sym_find(int v
);
721 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
724 static int type_size(CType
*type
, int *a
);
725 static inline CType
*pointed_type(CType
*type
);
726 static int pointed_size(CType
*type
);
727 static int lvalue_type(int t
);
728 static int parse_btype(CType
*type
, AttributeDef
*ad
);
729 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
730 static int is_compatible_types(CType
*type1
, CType
*type2
);
732 int ieee_finite(double d
);
733 void error(const char *fmt
, ...);
737 void lexpand_nr(void);
738 static void vpush_global_sym(CType
*type
, int v
);
739 void vset(CType
*type
, int r
, int v
);
740 void type_to_str(char *buf
, int buf_size
,
741 CType
*type
, const char *varstr
);
742 char *get_tok_str(int v
, CValue
*cv
);
743 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
744 unsigned long offset
, unsigned long size
);
745 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
747 /* section generation */
748 static void section_realloc(Section
*sec
, unsigned long new_size
);
749 static void *section_ptr_add(Section
*sec
, unsigned long size
);
750 static void put_extern_sym(Sym
*sym
, Section
*section
,
751 unsigned long value
, unsigned long size
);
752 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
753 static int put_elf_str(Section
*s
, const char *sym
);
754 static int put_elf_sym(Section
*s
,
755 unsigned long value
, unsigned long size
,
756 int info
, int other
, int shndx
, const char *name
);
757 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
758 int info
, int sh_num
, const char *name
);
759 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
760 int type
, int symbol
);
761 static void put_stabs(const char *str
, int type
, int other
, int desc
,
762 unsigned long value
);
763 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
764 unsigned long value
, Section
*sec
, int sym_index
);
765 static void put_stabn(int type
, int other
, int desc
, int value
);
766 static void put_stabd(int type
, int other
, int desc
);
767 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
769 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
770 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
771 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
774 int tcc_output_coff(TCCState
*s1
, const char *OutFile
);
778 #ifdef CONFIG_TCC_ASM
780 typedef struct ExprValue
{
785 #define MAX_ASM_OPERANDS 30
787 typedef struct ASMOperand
{
788 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
790 char asm_str
[16]; /* computed asm string for operand */
791 SValue
*vt
; /* C value of the expression */
792 int ref_index
; /* if >= 0, gives reference to a output constraint */
793 int priority
; /* priority, used to assign registers */
794 int reg
; /* if >= 0, register number used for this operand */
795 int is_llong
; /* true if double register value */
798 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
799 static int asm_int_expr(TCCState
*s1
);
800 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
801 const char *name
, const char **pp
);
803 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
807 static void asm_instr(void);
809 /* true if float/double/long double type */
810 static inline int is_float(int t
)
814 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
817 #ifdef TCC_TARGET_I386
818 #include "i386-gen.c"
821 #ifdef TCC_TARGET_ARM
825 #ifdef TCC_TARGET_C67
829 #ifdef CONFIG_TCC_STATIC
831 #define RTLD_LAZY 0x001
832 #define RTLD_NOW 0x002
833 #define RTLD_GLOBAL 0x100
834 #define RTLD_DEFAULT NULL
836 /* dummy function for profiling */
837 void *dlopen(const char *filename
, int flag
)
842 const char *dlerror(void)
847 typedef struct TCCSyms
{
852 #define TCCSYM(a) { #a, &a, },
854 /* add the symbol you want here if no dynamic linking is done */
855 static TCCSyms tcc_syms
[] = {
863 void *dlsym(void *handle
, const char *symbol
)
867 while (p
->str
!= NULL
) {
868 if (!strcmp(p
->str
, symbol
))
877 /********************************************************/
879 /* we use our own 'finite' function to avoid potential problems with
880 non standard math libs */
881 /* XXX: endianness dependent */
882 int ieee_finite(double d
)
885 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
888 /* copy a string and truncate it. */
889 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
896 q_end
= buf
+ buf_size
- 1;
908 /* strcat and truncate. */
909 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
914 pstrcpy(buf
+ len
, buf_size
- len
, s
);
918 /* memory management */
924 static inline void tcc_free(void *ptr
)
927 mem_cur_size
-= malloc_usable_size(ptr
);
932 static void *tcc_malloc(unsigned long size
)
937 error("memory full");
939 mem_cur_size
+= malloc_usable_size(ptr
);
940 if (mem_cur_size
> mem_max_size
)
941 mem_max_size
= mem_cur_size
;
946 static void *tcc_mallocz(unsigned long size
)
949 ptr
= tcc_malloc(size
);
950 memset(ptr
, 0, size
);
954 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
958 mem_cur_size
-= malloc_usable_size(ptr
);
960 ptr1
= realloc(ptr
, size
);
962 /* NOTE: count not correct if alloc error, but not critical */
963 mem_cur_size
+= malloc_usable_size(ptr1
);
964 if (mem_cur_size
> mem_max_size
)
965 mem_max_size
= mem_cur_size
;
970 static char *tcc_strdup(const char *str
)
973 ptr
= tcc_malloc(strlen(str
) + 1);
978 #define free(p) use_tcc_free(p)
979 #define malloc(s) use_tcc_malloc(s)
980 #define realloc(p, s) use_tcc_realloc(p, s)
982 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
989 /* every power of two we double array size */
990 if ((nb
& (nb
- 1)) == 0) {
995 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
997 error("memory full");
1004 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
1008 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
1009 strcpy(sec
->name
, name
);
1010 sec
->sh_type
= sh_type
;
1011 sec
->sh_flags
= sh_flags
;
1018 sec
->sh_addralign
= 4;
1021 sec
->sh_addralign
= 1;
1024 sec
->sh_addralign
= 32; /* default conservative alignment */
1028 /* only add section if not private */
1029 if (!(sh_flags
& SHF_PRIVATE
)) {
1030 sec
->sh_num
= s1
->nb_sections
;
1031 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
1036 static void free_section(Section
*s
)
1042 /* realloc section and set its content to zero */
1043 static void section_realloc(Section
*sec
, unsigned long new_size
)
1046 unsigned char *data
;
1048 size
= sec
->data_allocated
;
1051 while (size
< new_size
)
1053 data
= tcc_realloc(sec
->data
, size
);
1055 error("memory full");
1056 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1058 sec
->data_allocated
= size
;
1061 /* reserve at least 'size' bytes in section 'sec' from
1062 sec->data_offset. */
1063 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1065 unsigned long offset
, offset1
;
1067 offset
= sec
->data_offset
;
1068 offset1
= offset
+ size
;
1069 if (offset1
> sec
->data_allocated
)
1070 section_realloc(sec
, offset1
);
1071 sec
->data_offset
= offset1
;
1072 return sec
->data
+ offset
;
1075 /* return a reference to a section, and create it if it does not
1077 Section
*find_section(TCCState
*s1
, const char *name
)
1081 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1082 sec
= s1
->sections
[i
];
1083 if (!strcmp(name
, sec
->name
))
1086 /* sections are created as PROGBITS */
1087 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1090 /* update sym->c so that it points to an external symbol in section
1091 'section' with value 'value' */
1092 static void put_extern_sym(Sym
*sym
, Section
*section
,
1093 unsigned long value
, unsigned long size
)
1095 int sym_type
, sym_bind
, sh_num
, info
;
1100 sh_num
= section
->sh_num
;
1104 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
)
1105 sym_type
= STT_FUNC
;
1107 sym_type
= STT_OBJECT
;
1108 if (sym
->type
.t
& VT_STATIC
)
1109 sym_bind
= STB_LOCAL
;
1111 sym_bind
= STB_GLOBAL
;
1113 name
= get_tok_str(sym
->v
, NULL
);
1114 #ifdef CONFIG_TCC_BCHECK
1115 if (do_bounds_check
) {
1118 /* XXX: avoid doing that for statics ? */
1119 /* if bound checking is activated, we change some function
1120 names by adding the "__bound" prefix */
1123 /* XXX: we rely only on malloc hooks */
1135 strcpy(buf
, "__bound_");
1142 info
= ELF32_ST_INFO(sym_bind
, sym_type
);
1143 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, sh_num
, name
);
1145 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
1146 esym
->st_value
= value
;
1147 esym
->st_size
= size
;
1148 esym
->st_shndx
= sh_num
;
1152 /* add a new relocation entry to symbol 'sym' in section 's' */
1153 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1156 put_extern_sym(sym
, NULL
, 0, 0);
1157 /* now we can add ELF relocation info */
1158 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1161 static inline int isid(int c
)
1163 return (c
>= 'a' && c
<= 'z') ||
1164 (c
>= 'A' && c
<= 'Z') ||
1168 static inline int isnum(int c
)
1170 return c
>= '0' && c
<= '9';
1173 static inline int isoct(int c
)
1175 return c
>= '0' && c
<= '7';
1178 static inline int toup(int c
)
1180 if (c
>= 'a' && c
<= 'z')
1181 return c
- 'a' + 'A';
1186 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1190 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1193 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1197 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1201 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1208 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1209 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1210 (*f
)->filename
, (*f
)->line_num
);
1211 if (file
->line_num
> 0) {
1212 strcat_printf(buf
, sizeof(buf
),
1213 "%s:%d: ", file
->filename
, file
->line_num
);
1215 strcat_printf(buf
, sizeof(buf
),
1216 "%s: ", file
->filename
);
1219 strcat_printf(buf
, sizeof(buf
),
1223 strcat_printf(buf
, sizeof(buf
), "warning: ");
1224 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1226 if (!s1
->error_func
) {
1227 /* default case: stderr */
1228 fprintf(stderr
, "%s\n", buf
);
1230 s1
->error_func(s1
->error_opaque
, buf
);
1232 if (!is_warning
|| s1
->warn_error
)
1237 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1238 void (*error_func
)(void *opaque
, const char *msg
))
1240 s
->error_opaque
= error_opaque
;
1241 s
->error_func
= error_func
;
1245 /* error without aborting current compilation */
1246 void error_noabort(const char *fmt
, ...)
1248 TCCState
*s1
= tcc_state
;
1252 error1(s1
, 0, fmt
, ap
);
1256 void error(const char *fmt
, ...)
1258 TCCState
*s1
= tcc_state
;
1262 error1(s1
, 0, fmt
, ap
);
1264 /* better than nothing: in some cases, we accept to handle errors */
1265 if (s1
->error_set_jmp_enabled
) {
1266 longjmp(s1
->error_jmp_buf
, 1);
1268 /* XXX: eliminate this someday */
1273 void expect(const char *msg
)
1275 error("%s expected", msg
);
1278 void warning(const char *fmt
, ...)
1280 TCCState
*s1
= tcc_state
;
1287 error1(s1
, 1, fmt
, ap
);
1294 error("'%c' expected", c
);
1298 static void test_lvalue(void)
1300 if (!(vtop
->r
& VT_LVAL
))
1304 /* allocate a new token */
1305 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1307 TokenSym
*ts
, **ptable
;
1310 if (tok_ident
>= SYM_FIRST_ANOM
)
1311 error("memory full");
1313 /* expand token table if needed */
1314 i
= tok_ident
- TOK_IDENT
;
1315 if ((i
% TOK_ALLOC_INCR
) == 0) {
1316 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1318 error("memory full");
1319 table_ident
= ptable
;
1322 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1323 table_ident
[i
] = ts
;
1324 ts
->tok
= tok_ident
++;
1325 ts
->sym_define
= NULL
;
1326 ts
->sym_label
= NULL
;
1327 ts
->sym_struct
= NULL
;
1328 ts
->sym_identifier
= NULL
;
1330 ts
->hash_next
= NULL
;
1331 memcpy(ts
->str
, str
, len
);
1332 ts
->str
[len
] = '\0';
1337 #define TOK_HASH_INIT 1
1338 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1340 /* find a token and add it if not found */
1341 static TokenSym
*tok_alloc(const char *str
, int len
)
1343 TokenSym
*ts
, **pts
;
1349 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1350 h
&= (TOK_HASH_SIZE
- 1);
1352 pts
= &hash_ident
[h
];
1357 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1359 pts
= &(ts
->hash_next
);
1361 return tok_alloc_new(pts
, str
, len
);
1364 /* CString handling */
1366 static void cstr_realloc(CString
*cstr
, int new_size
)
1371 size
= cstr
->size_allocated
;
1373 size
= 8; /* no need to allocate a too small first string */
1374 while (size
< new_size
)
1376 data
= tcc_realloc(cstr
->data_allocated
, size
);
1378 error("memory full");
1379 cstr
->data_allocated
= data
;
1380 cstr
->size_allocated
= size
;
1385 static void cstr_ccat(CString
*cstr
, int ch
)
1388 size
= cstr
->size
+ 1;
1389 if (size
> cstr
->size_allocated
)
1390 cstr_realloc(cstr
, size
);
1391 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1395 static void cstr_cat(CString
*cstr
, const char *str
)
1407 /* add a wide char */
1408 static void cstr_wccat(CString
*cstr
, int ch
)
1411 size
= cstr
->size
+ sizeof(int);
1412 if (size
> cstr
->size_allocated
)
1413 cstr_realloc(cstr
, size
);
1414 *(int *)(((unsigned char *)cstr
->data
) + size
- sizeof(int)) = ch
;
1418 static void cstr_new(CString
*cstr
)
1420 memset(cstr
, 0, sizeof(CString
));
1423 /* free string and reset it to NULL */
1424 static void cstr_free(CString
*cstr
)
1426 tcc_free(cstr
->data_allocated
);
1430 #define cstr_reset(cstr) cstr_free(cstr)
1432 static CString
*cstr_dup(CString
*cstr1
)
1437 cstr
= tcc_malloc(sizeof(CString
));
1440 cstr
->size_allocated
= size
;
1441 cstr
->data_allocated
= tcc_malloc(size
);
1442 cstr
->data
= cstr
->data_allocated
;
1443 memcpy(cstr
->data_allocated
, cstr1
->data_allocated
, size
);
1447 /* XXX: unicode ? */
1448 static void add_char(CString
*cstr
, int c
)
1450 if (c
== '\'' || c
== '\"' || c
== '\\') {
1451 /* XXX: could be more precise if char or string */
1452 cstr_ccat(cstr
, '\\');
1454 if (c
>= 32 && c
<= 126) {
1457 cstr_ccat(cstr
, '\\');
1459 cstr_ccat(cstr
, 'n');
1461 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1462 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1463 cstr_ccat(cstr
, '0' + (c
& 7));
1468 /* XXX: buffer overflow */
1469 /* XXX: float tokens */
1470 char *get_tok_str(int v
, CValue
*cv
)
1472 static char buf
[STRING_MAX_SIZE
+ 1];
1473 static CString cstr_buf
;
1479 /* NOTE: to go faster, we give a fixed buffer for small strings */
1480 cstr_reset(&cstr_buf
);
1481 cstr_buf
.data
= buf
;
1482 cstr_buf
.size_allocated
= sizeof(buf
);
1488 /* XXX: not quite exact, but only useful for testing */
1489 sprintf(p
, "%u", cv
->ui
);
1493 /* XXX: not quite exact, but only useful for testing */
1494 sprintf(p
, "%Lu", cv
->ull
);
1498 cstr_ccat(&cstr_buf
, '\'');
1499 add_char(&cstr_buf
, cv
->i
);
1500 cstr_ccat(&cstr_buf
, '\'');
1501 cstr_ccat(&cstr_buf
, '\0');
1505 len
= cstr
->size
- 1;
1507 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1508 cstr_ccat(&cstr_buf
, '\0');
1513 cstr_ccat(&cstr_buf
, '\"');
1515 len
= cstr
->size
- 1;
1517 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1519 len
= (cstr
->size
/ sizeof(int)) - 1;
1521 add_char(&cstr_buf
, ((int *)cstr
->data
)[i
]);
1523 cstr_ccat(&cstr_buf
, '\"');
1524 cstr_ccat(&cstr_buf
, '\0');
1533 return strcpy(p
, "<<=");
1535 return strcpy(p
, ">>=");
1537 if (v
< TOK_IDENT
) {
1538 /* search in two bytes table */
1552 } else if (v
< tok_ident
) {
1553 return table_ident
[v
- TOK_IDENT
]->str
;
1554 } else if (v
>= SYM_FIRST_ANOM
) {
1555 /* special name for anonymous symbol */
1556 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1558 /* should never happen */
1563 return cstr_buf
.data
;
1566 /* push, without hashing */
1567 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, int c
)
1570 s
= tcc_malloc(sizeof(Sym
));
1581 /* find a symbol and return its associated structure. 's' is the top
1582 of the symbol stack */
1583 static Sym
*sym_find2(Sym
*s
, int v
)
1593 /* structure lookup */
1594 static inline Sym
*struct_find(int v
)
1597 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1599 return table_ident
[v
]->sym_struct
;
1602 /* find an identifier */
1603 static inline Sym
*sym_find(int v
)
1606 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1608 return table_ident
[v
]->sym_identifier
;
1611 /* push a given symbol on the symbol stack */
1612 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1621 s
= sym_push2(ps
, v
, type
->t
, c
);
1622 s
->type
.ref
= type
->ref
;
1624 /* don't record fields or anonymous symbols */
1626 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1627 /* record symbol in token array */
1628 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1630 ps
= &ts
->sym_struct
;
1632 ps
= &ts
->sym_identifier
;
1639 /* push a global identifier */
1640 static Sym
*global_identifier_push(int v
, int t
, int c
)
1643 s
= sym_push2(&global_stack
, v
, t
, c
);
1644 /* don't record anonymous symbol */
1645 if (v
< SYM_FIRST_ANOM
) {
1646 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1647 /* modify the top most local identifier, so that
1648 sym_identifier will point to 's' when popped */
1650 ps
= &(*ps
)->prev_tok
;
1657 /* pop symbols until top reaches 'b' */
1658 static void sym_pop(Sym
**ptop
, Sym
*b
)
1668 /* remove symbol in token array */
1670 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1671 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1673 ps
= &ts
->sym_struct
;
1675 ps
= &ts
->sym_identifier
;
1686 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1691 fd
= open(filename
, O_RDONLY
);
1694 bf
= tcc_malloc(sizeof(BufferedFile
));
1700 bf
->buf_ptr
= bf
->buffer
;
1701 bf
->buf_end
= bf
->buffer
;
1702 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1703 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1705 bf
->ifndef_macro
= 0;
1706 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1707 // printf("opening '%s'\n", filename);
1711 void tcc_close(BufferedFile
*bf
)
1713 total_lines
+= bf
->line_num
;
1718 /* fill input buffer and peek next char */
1719 static int tcc_peekc_slow(BufferedFile
*bf
)
1722 /* only tries to read if really end of buffer */
1723 if (bf
->buf_ptr
>= bf
->buf_end
) {
1725 #if defined(PARSE_DEBUG)
1730 len
= read(bf
->fd
, bf
->buffer
, len
);
1737 bf
->buf_ptr
= bf
->buffer
;
1738 bf
->buf_end
= bf
->buffer
+ len
;
1739 *bf
->buf_end
= CH_EOB
;
1741 if (bf
->buf_ptr
< bf
->buf_end
) {
1742 return bf
->buf_ptr
[0];
1744 bf
->buf_ptr
= bf
->buf_end
;
1749 /* return the current character, handling end of block if necessary
1751 static int handle_eob(void)
1753 return tcc_peekc_slow(file
);
1756 /* read next char from current input file and handle end of input buffer */
1757 static inline void inp(void)
1759 ch
= *(++(file
->buf_ptr
));
1760 /* end of buffer/file handling */
1765 /* handle '\[\r]\n' */
1766 static void handle_stray(void)
1768 while (ch
== '\\') {
1773 } else if (ch
== '\r') {
1781 error("stray '\\' in program");
1786 /* skip the stray and handle the \\n case. Output an error if
1787 incorrect char after the stray */
1788 static int handle_stray1(uint8_t *p
)
1792 if (p
>= file
->buf_end
) {
1809 /* handle just the EOB case, but not stray */
1810 #define PEEKC_EOB(c, p)\
1821 /* handle the complicated stray case */
1822 #define PEEKC(c, p)\
1827 c = handle_stray1(p);\
1832 /* input with '\[\r]\n' handling. Note that this function cannot
1833 handle other characters after '\', so you cannot call it inside
1834 strings or comments */
1835 static void minp(void)
1843 /* single line C++ comments */
1844 static uint8_t *parse_line_comment(uint8_t *p
)
1852 if (c
== '\n' || c
== CH_EOF
) {
1854 } else if (c
== '\\') {
1863 } else if (c
== '\r') {
1881 static uint8_t *parse_comment(uint8_t *p
)
1887 /* fast skip loop */
1890 if (c
== '\n' || c
== '*' || c
== '\\')
1894 if (c
== '\n' || c
== '*' || c
== '\\')
1898 /* now we can handle all the cases */
1902 } else if (c
== '*') {
1908 } else if (c
== '/') {
1909 goto end_of_comment
;
1910 } else if (c
== '\\') {
1915 /* skip '\[\r]\n', otherwise just skip the stray */
1921 } else if (c
== '\r') {
1938 /* stray, eob or eof */
1943 error("unexpected end of file in comment");
1944 } else if (c
== '\\') {
1956 /* space exlcuding newline */
1957 static inline int is_space(int ch
)
1959 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
1962 static inline void skip_spaces(void)
1964 while (is_space(ch
))
1968 /* parse a string without interpreting escapes */
1969 static uint8_t *parse_pp_string(uint8_t *p
,
1970 int sep
, CString
*str
)
1978 } else if (c
== '\\') {
1983 unterminated_string
:
1984 /* XXX: indicate line number of start of string */
1985 error("missing terminating %c character", sep
);
1986 } else if (c
== '\\') {
1987 /* escape : just skip \[\r]\n */
1992 } else if (c
== '\r') {
1995 expect("'\n' after '\r'");
1998 } else if (c
== CH_EOF
) {
1999 goto unterminated_string
;
2002 cstr_ccat(str
, '\\');
2008 } else if (c
== '\n') {
2011 } else if (c
== '\r') {
2014 cstr_ccat(str
, '\r');
2030 /* skip block of text until #else, #elif or #endif. skip also pairs of
2032 void preprocess_skip(void)
2034 int a
, start_of_line
, c
;
2061 } else if (c
== '\\') {
2062 /* XXX: incorrect: should not give an error */
2063 ch
= file
->buf_ptr
[0];
2071 p
= parse_pp_string(p
, c
, NULL
);
2080 p
= parse_comment(p
);
2081 } else if (ch
== '/') {
2082 p
= parse_line_comment(p
);
2088 if (start_of_line
) {
2093 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2095 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2097 else if (tok
== TOK_ENDIF
)
2111 /* ParseState handling */
2113 /* XXX: currently, no include file info is stored. Thus, we cannot display
2114 accurate messages if the function or data definition spans multiple
2117 /* save current parse state in 's' */
2118 void save_parse_state(ParseState
*s
)
2120 s
->line_num
= file
->line_num
;
2121 s
->macro_ptr
= macro_ptr
;
2126 /* restore parse state from 's' */
2127 void restore_parse_state(ParseState
*s
)
2129 file
->line_num
= s
->line_num
;
2130 macro_ptr
= s
->macro_ptr
;
2135 /* return the number of additional 'ints' necessary to store the
2137 static inline int tok_ext_size(int t
)
2156 return LDOUBLE_SIZE
/ 4;
2162 /* token string handling */
2164 static inline void tok_str_new(TokenString
*s
)
2168 s
->allocated_len
= 0;
2169 s
->last_line_num
= -1;
2172 static void tok_str_free(int *str
)
2181 /* NOTE: we test zero separately so that GCC can generate a
2182 table for the following switch */
2197 /* XXX: use a macro to be portable on 64 bit ? */
2198 cstr
= (CString
*)p
[1];
2209 p
+= 1 + (LDOUBLE_SIZE
/ 4);
2219 static int *tok_str_realloc(TokenString
*s
)
2223 len
= s
->allocated_len
+ TOK_STR_ALLOC_INCR
;
2224 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2226 error("memory full");
2227 s
->allocated_len
= len
;
2232 static void tok_str_add(TokenString
*s
, int t
)
2238 if (len
>= s
->allocated_len
)
2239 str
= tok_str_realloc(s
);
2244 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2251 /* allocate space for worst case */
2252 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2253 str
= tok_str_realloc(s
);
2262 str
[len
++] = cv
->tab
[0];
2267 str
[len
++] = (int)cstr_dup(cv
->cstr
);
2272 #if LDOUBLE_SIZE == 8
2275 str
[len
++] = cv
->tab
[0];
2276 str
[len
++] = cv
->tab
[1];
2278 #if LDOUBLE_SIZE == 12
2280 str
[len
++] = cv
->tab
[0];
2281 str
[len
++] = cv
->tab
[1];
2282 str
[len
++] = cv
->tab
[2];
2283 #elif LDOUBLE_SIZE != 8
2284 #error add long double size support
2293 /* add the current parse token in token string 's' */
2294 static void tok_str_add_tok(TokenString
*s
)
2298 /* save line number info */
2299 if (file
->line_num
!= s
->last_line_num
) {
2300 s
->last_line_num
= file
->line_num
;
2301 cval
.i
= s
->last_line_num
;
2302 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2304 tok_str_add2(s
, tok
, &tokc
);
2307 #if LDOUBLE_SIZE == 12
2308 #define LDOUBLE_GET(p, cv) \
2312 #elif LDOUBLE_SIZE == 8
2313 #define LDOUBLE_GET(p, cv) \
2317 #error add long double size support
2321 /* get a token from an integer array and increment pointer
2322 accordingly. we code it as a macro to avoid pointer aliasing. */
2323 #define TOK_GET(t, p, cv) \
2345 case TOK_CLDOUBLE: \
2346 LDOUBLE_GET(p, cv); \
2347 p += LDOUBLE_SIZE / 4; \
2354 /* defines handling */
2355 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2359 s
= sym_push2(&define_stack
, v
, macro_type
, (int)str
);
2360 s
->next
= first_arg
;
2361 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2364 /* undefined a define symbol. Its name is just set to zero */
2365 static void define_undef(Sym
*s
)
2369 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2370 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2374 static inline Sym
*define_find(int v
)
2377 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2379 return table_ident
[v
]->sym_define
;
2382 /* free define stack until top reaches 'b' */
2383 static void free_defines(Sym
*b
)
2391 /* do not free args or predefined defines */
2393 tok_str_free((int *)top
->c
);
2395 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2396 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2404 static Sym
*label_find(int v
)
2407 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2409 return table_ident
[v
]->sym_label
;
2412 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2415 s
= sym_push2(ptop
, v
, 0, 0);
2417 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2418 if (ptop
== &global_label_stack
) {
2419 /* modify the top most local identifier, so that
2420 sym_identifier will point to 's' when popped */
2422 ps
= &(*ps
)->prev_tok
;
2429 /* pop labels until element last is reached. Look if any labels are
2430 undefined. Define symbols if '&&label' was used. */
2431 static void label_pop(Sym
**ptop
, Sym
*slast
)
2434 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2436 if (s
->r
== LABEL_DECLARED
) {
2437 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2438 } else if (s
->r
== LABEL_FORWARD
) {
2439 error("label '%s' used but not defined",
2440 get_tok_str(s
->v
, NULL
));
2443 /* define corresponding symbol. A size of
2445 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2449 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2455 /* eval an expression for #if/#elif */
2456 static int expr_preprocess(void)
2462 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2463 next(); /* do macro subst */
2464 if (tok
== TOK_DEFINED
) {
2469 c
= define_find(tok
) != 0;
2474 } else if (tok
>= TOK_IDENT
) {
2475 /* if undefined macro */
2479 tok_str_add_tok(&str
);
2481 tok_str_add(&str
, -1); /* simulate end of file */
2482 tok_str_add(&str
, 0);
2483 /* now evaluate C constant expression */
2484 macro_ptr
= str
.str
;
2488 tok_str_free(str
.str
);
2492 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2493 static void tok_print(int *str
)
2499 TOK_GET(t
, str
, cval
);
2502 printf(" %s", get_tok_str(t
, &cval
));
2508 /* parse after #define */
2509 static void parse_define(void)
2511 Sym
*s
, *first
, **ps
;
2512 int v
, t
, varg
, is_vaargs
, c
;
2517 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2518 /* XXX: should check if same macro (ANSI) */
2521 /* '(' must be just after macro definition for MACRO_FUNC */
2522 c
= file
->buf_ptr
[0];
2524 c
= handle_stray1(file
->buf_ptr
);
2529 while (tok
!= ')') {
2533 if (varg
== TOK_DOTS
) {
2534 varg
= TOK___VA_ARGS__
;
2536 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2540 if (varg
< TOK_IDENT
)
2541 error("badly punctuated parameter list");
2542 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2553 /* EOF testing necessary for '-D' handling */
2554 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2555 tok_str_add2(&str
, tok
, &tokc
);
2558 tok_str_add(&str
, 0);
2560 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2563 define_push(v
, t
, str
.str
, first
);
2566 /* XXX: use a token or a hash table to accelerate matching ? */
2567 static CachedInclude
*search_cached_include(TCCState
*s1
,
2568 int type
, const char *filename
)
2573 for(i
= 0;i
< s1
->nb_cached_includes
; i
++) {
2574 e
= s1
->cached_includes
[i
];
2575 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2581 static inline void add_cached_include(TCCState
*s1
, int type
,
2582 const char *filename
, int ifndef_macro
)
2586 if (search_cached_include(s1
, type
, filename
))
2589 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2591 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2595 strcpy(e
->filename
, filename
);
2596 e
->ifndef_macro
= ifndef_macro
;
2597 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2600 /* is_bof is true if first non space token at beginning of file */
2601 static void preprocess(int is_bof
)
2603 TCCState
*s1
= tcc_state
;
2604 int size
, i
, c
, n
, saved_parse_flags
;
2605 char buf
[1024], *q
, *p
;
2611 saved_parse_flags
= parse_flags
;
2612 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
2613 PARSE_FLAG_LINEFEED
;
2623 s
= define_find(tok
);
2624 /* undefine symbol by putting an invalid name */
2629 ch
= file
->buf_ptr
[0];
2630 /* XXX: incorrect if comments : use next_nomacro with a special mode */
2635 } else if (ch
== '\"') {
2638 /* XXX: better stray handling */
2641 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
2642 if ((q
- buf
) < sizeof(buf
) - 1)
2649 /* eat all spaces and comments after include */
2650 /* XXX: slightly incorrect */
2651 while (ch1
!= '\n' && ch1
!= CH_EOF
)
2655 /* computed #include : either we have only strings or
2656 we have anything enclosed in '<>' */
2659 if (tok
== TOK_STR
) {
2660 while (tok
!= TOK_LINEFEED
) {
2661 if (tok
!= TOK_STR
) {
2663 error("'#include' expects \"FILENAME\" or <FILENAME>");
2665 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
2671 while (tok
!= TOK_LINEFEED
) {
2672 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
2676 /* check syntax and remove '<>' */
2677 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
2678 goto include_syntax
;
2679 memmove(buf
, buf
+ 1, len
- 2);
2680 buf
[len
- 2] = '\0';
2685 e
= search_cached_include(s1
, c
, buf
);
2686 if (e
&& define_find(e
->ifndef_macro
)) {
2687 /* no need to parse the include because the 'ifndef macro'
2690 printf("%s: skipping %s\n", file
->filename
, buf
);
2694 /* first search in current dir if "header.h" */
2696 p
= strrchr(file
->filename
, '/');
2698 size
= p
+ 1 - file
->filename
;
2699 if (size
> sizeof(buf1
) - 1)
2700 size
= sizeof(buf1
) - 1;
2701 memcpy(buf1
, file
->filename
, size
);
2703 pstrcat(buf1
, sizeof(buf1
), buf
);
2704 f
= tcc_open(s1
, buf1
);
2708 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
2709 error("#include recursion too deep");
2710 /* now search in all the include paths */
2711 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
2712 for(i
= 0; i
< n
; i
++) {
2714 if (i
< s1
->nb_include_paths
)
2715 path
= s1
->include_paths
[i
];
2717 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
2718 pstrcpy(buf1
, sizeof(buf1
), path
);
2719 pstrcat(buf1
, sizeof(buf1
), "/");
2720 pstrcat(buf1
, sizeof(buf1
), buf
);
2721 f
= tcc_open(s1
, buf1
);
2725 error("include file '%s' not found", buf
);
2729 printf("%s: including %s\n", file
->filename
, buf1
);
2732 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
2733 /* push current file in stack */
2734 /* XXX: fix current line init */
2735 *s1
->include_stack_ptr
++ = file
;
2737 /* add include file debug info */
2739 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
2741 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
2742 ch
= file
->buf_ptr
[0];
2750 c
= expr_preprocess();
2756 if (tok
< TOK_IDENT
)
2757 error("invalid argument for '#if%sdef'", c
? "n" : "");
2761 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
2763 file
->ifndef_macro
= tok
;
2766 c
= (define_find(tok
) != 0) ^ c
;
2768 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
2769 error("memory full");
2770 *s1
->ifdef_stack_ptr
++ = c
;
2773 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2774 error("#else without matching #if");
2775 if (s1
->ifdef_stack_ptr
[-1] & 2)
2776 error("#else after #else");
2777 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
2780 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2781 error("#elif without matching #if");
2782 c
= s1
->ifdef_stack_ptr
[-1];
2784 error("#elif after #else");
2785 /* last #if/#elif expression was true: we skip */
2788 c
= expr_preprocess();
2789 s1
->ifdef_stack_ptr
[-1] = c
;
2799 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
2800 error("#endif without matching #if");
2801 s1
->ifdef_stack_ptr
--;
2802 /* '#ifndef macro' was at the start of file. Now we check if
2803 an '#endif' is exactly at the end of file */
2804 if (file
->ifndef_macro
&&
2805 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
2806 file
->ifndef_macro_saved
= file
->ifndef_macro
;
2807 /* need to set to zero to avoid false matches if another
2808 #ifndef at middle of file */
2809 file
->ifndef_macro
= 0;
2810 while (tok
!= TOK_LINEFEED
)
2812 tok_flags
|= TOK_FLAG_ENDIF
;
2818 if (tok
!= TOK_CINT
)
2820 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
2822 if (tok
!= TOK_LINEFEED
) {
2825 pstrcpy(file
->filename
, sizeof(file
->filename
),
2826 (char *)tokc
.cstr
->data
);
2832 ch
= file
->buf_ptr
[0];
2835 while (ch
!= '\n' && ch
!= CH_EOF
) {
2836 if ((q
- buf
) < sizeof(buf
) - 1)
2842 error("#error %s", buf
);
2844 warning("#warning %s", buf
);
2850 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
2851 /* '!' is ignored to allow C scripts. numbers are ignored
2852 to emulate cpp behaviour */
2854 error("invalid preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2858 /* ignore other preprocess commands or #! for C scripts */
2859 while (tok
!= TOK_LINEFEED
)
2862 parse_flags
= saved_parse_flags
;
2865 /* evaluate escape codes in a string. */
2866 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2881 case '0': case '1': case '2': case '3':
2882 case '4': case '5': case '6': case '7':
2883 /* at most three octal digits */
2888 n
= n
* 8 + c
- '0';
2892 n
= n
* 8 + c
- '0';
2897 goto add_char_nonext
;
2903 if (c
>= 'a' && c
<= 'f')
2905 else if (c
>= 'A' && c
<= 'F')
2915 goto add_char_nonext
;
2939 goto invalid_escape
;
2949 if (c
>= '!' && c
<= '~')
2950 warning("unknown escape sequence: \'\\%c\'", c
);
2952 warning("unknown escape sequence: \'\\x%x\'", c
);
2959 cstr_ccat(outstr
, c
);
2961 cstr_wccat(outstr
, c
);
2963 /* add a trailing '\0' */
2965 cstr_ccat(outstr
, '\0');
2967 cstr_wccat(outstr
, '\0');
2970 /* we use 64 bit numbers */
2973 /* bn = (bn << shift) | or_val */
2974 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2978 for(i
=0;i
<BN_SIZE
;i
++) {
2980 bn
[i
] = (v
<< shift
) | or_val
;
2981 or_val
= v
>> (32 - shift
);
2985 void bn_zero(unsigned int *bn
)
2988 for(i
=0;i
<BN_SIZE
;i
++) {
2993 /* parse number in null terminated string 'p' and return it in the
2995 void parse_number(const char *p
)
2997 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2999 unsigned int bn
[BN_SIZE
];
3010 goto float_frac_parse
;
3011 } else if (t
== '0') {
3012 if (ch
== 'x' || ch
== 'X') {
3016 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
3022 /* parse all digits. cannot check octal numbers at this stage
3023 because of floating point constants */
3025 if (ch
>= 'a' && ch
<= 'f')
3027 else if (ch
>= 'A' && ch
<= 'F')
3035 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
3037 error("number too long");
3043 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
3044 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
3046 /* NOTE: strtox should support that for hexa numbers, but
3047 non ISOC99 libcs do not support it, so we prefer to do
3049 /* hexadecimal or binary floats */
3050 /* XXX: handle overflows */
3062 } else if (t
>= 'a') {
3064 } else if (t
>= 'A') {
3069 bn_lshift(bn
, shift
, t
);
3076 if (t
>= 'a' && t
<= 'f') {
3078 } else if (t
>= 'A' && t
<= 'F') {
3080 } else if (t
>= '0' && t
<= '9') {
3086 error("invalid digit");
3087 bn_lshift(bn
, shift
, t
);
3092 if (ch
!= 'p' && ch
!= 'P')
3099 } else if (ch
== '-') {
3103 if (ch
< '0' || ch
> '9')
3104 expect("exponent digits");
3105 while (ch
>= '0' && ch
<= '9') {
3106 exp_val
= exp_val
* 10 + ch
- '0';
3109 exp_val
= exp_val
* s
;
3111 /* now we can generate the number */
3112 /* XXX: should patch directly float number */
3113 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3114 d
= ldexp(d
, exp_val
- frac_bits
);
3119 /* float : should handle overflow */
3121 } else if (t
== 'L') {
3124 /* XXX: not large enough */
3125 tokc
.ld
= (long double)d
;
3131 /* decimal floats */
3133 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3138 while (ch
>= '0' && ch
<= '9') {
3139 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3145 if (ch
== 'e' || ch
== 'E') {
3146 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3150 if (ch
== '-' || ch
== '+') {
3151 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3156 if (ch
< '0' || ch
> '9')
3157 expect("exponent digits");
3158 while (ch
>= '0' && ch
<= '9') {
3159 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3171 tokc
.f
= strtof(token_buf
, NULL
);
3172 } else if (t
== 'L') {
3175 tokc
.ld
= strtold(token_buf
, NULL
);
3178 tokc
.d
= strtod(token_buf
, NULL
);
3182 unsigned long long n
, n1
;
3185 /* integer number */
3188 if (b
== 10 && *q
== '0') {
3195 /* no need for checks except for base 10 / 8 errors */
3198 } else if (t
>= 'a') {
3200 } else if (t
>= 'A') {
3205 error("invalid digit");
3209 /* detect overflow */
3210 /* XXX: this test is not reliable */
3212 error("integer constant overflow");
3215 /* XXX: not exactly ANSI compliant */
3216 if ((n
& 0xffffffff00000000LL
) != 0) {
3221 } else if (n
> 0x7fffffff) {
3232 error("three 'l's in integer constant");
3235 if (tok
== TOK_CINT
)
3237 else if (tok
== TOK_CUINT
)
3241 } else if (t
== 'U') {
3243 error("two 'u's in integer constant");
3245 if (tok
== TOK_CINT
)
3247 else if (tok
== TOK_CLLONG
)
3254 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3262 #define PARSE2(c1, tok1, c2, tok2) \
3273 /* return next token without macro substitution */
3274 static inline void next_nomacro1(void)
3294 /* first look if it is in fact an end of buffer */
3295 if (p
>= file
->buf_end
) {
3299 if (p
>= file
->buf_end
)
3312 TCCState
*s1
= tcc_state
;
3313 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3315 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3316 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3317 /* no include left : end of file. */
3320 /* pop include file */
3322 /* test if previous '#endif' was after a #ifdef at
3324 if (tok_flags
& TOK_FLAG_ENDIF
) {
3326 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3328 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3329 file
->ifndef_macro_saved
);
3332 /* add end of include file debug info */
3334 put_stabd(N_EINCL
, 0, 0);
3336 /* pop include stack */
3338 s1
->include_stack_ptr
--;
3339 file
= *s1
->include_stack_ptr
;
3347 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3351 tok_flags
|= TOK_FLAG_BOL
;
3360 if ((tok_flags
& TOK_FLAG_BOL
) &&
3361 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3363 preprocess(tok_flags
& TOK_FLAG_BOF
);
3369 tok
= TOK_TWOSHARPS
;
3376 case 'a': case 'b': case 'c': case 'd':
3377 case 'e': case 'f': case 'g': case 'h':
3378 case 'i': case 'j': case 'k': case 'l':
3379 case 'm': case 'n': case 'o': case 'p':
3380 case 'q': case 'r': case 's': case 't':
3381 case 'u': case 'v': case 'w': case 'x':
3383 case 'A': case 'B': case 'C': case 'D':
3384 case 'E': case 'F': case 'G': case 'H':
3385 case 'I': case 'J': case 'K':
3386 case 'M': case 'N': case 'O': case 'P':
3387 case 'Q': case 'R': case 'S': case 'T':
3388 case 'U': case 'V': case 'W': case 'X':
3394 h
= TOK_HASH_FUNC(h
, c
);
3398 if (!isidnum_table
[c
])
3400 h
= TOK_HASH_FUNC(h
, c
);
3407 /* fast case : no stray found, so we have the full token
3408 and we have already hashed it */
3410 h
&= (TOK_HASH_SIZE
- 1);
3411 pts
= &hash_ident
[h
];
3416 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3418 pts
= &(ts
->hash_next
);
3420 ts
= tok_alloc_new(pts
, p1
, len
);
3424 cstr_reset(&tokcstr
);
3427 cstr_ccat(&tokcstr
, *p1
);
3433 while (isidnum_table
[c
]) {
3434 cstr_ccat(&tokcstr
, c
);
3437 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3443 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3445 goto parse_ident_fast
;
3448 if (c
== '\'' || c
== '\"') {
3452 cstr_reset(&tokcstr
);
3453 cstr_ccat(&tokcstr
, 'L');
3454 goto parse_ident_slow
;
3458 case '0': case '1': case '2': case '3':
3459 case '4': case '5': case '6': case '7':
3462 cstr_reset(&tokcstr
);
3463 /* after the first digit, accept digits, alpha, '.' or sign if
3464 prefixed by 'eEpP' */
3468 cstr_ccat(&tokcstr
, c
);
3470 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3471 ((c
== '+' || c
== '-') &&
3472 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3475 /* We add a trailing '\0' to ease parsing */
3476 cstr_ccat(&tokcstr
, '\0');
3477 tokc
.cstr
= &tokcstr
;
3481 /* special dot handling because it can also start a number */
3484 cstr_reset(&tokcstr
);
3485 cstr_ccat(&tokcstr
, '.');
3487 } else if (c
== '.') {
3507 /* parse the string */
3509 p
= parse_pp_string(p
, sep
, &str
);
3510 cstr_ccat(&str
, '\0');
3512 /* eval the escape (should be done as TOK_PPNUM) */
3513 cstr_reset(&tokcstr
);
3514 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3519 /* XXX: make it portable */
3523 char_size
= sizeof(int);
3524 if (tokcstr
.size
<= char_size
)
3525 error("empty character constant");
3526 if (tokcstr
.size
> 2 * char_size
)
3527 warning("multi-character character constant");
3529 tokc
.i
= *(int8_t *)tokcstr
.data
;
3532 tokc
.i
= *(int *)tokcstr
.data
;
3536 tokc
.cstr
= &tokcstr
;
3550 } else if (c
== '<') {
3568 } else if (c
== '>') {
3586 } else if (c
== '=') {
3599 } else if (c
== '=') {
3612 } else if (c
== '=') {
3625 } else if (c
== '=') {
3628 } else if (c
== '>') {
3636 PARSE2('!', '!', '=', TOK_NE
)
3637 PARSE2('=', '=', '=', TOK_EQ
)
3638 PARSE2('*', '*', '=', TOK_A_MUL
)
3639 PARSE2('%', '%', '=', TOK_A_MOD
)
3640 PARSE2('^', '^', '=', TOK_A_XOR
)
3642 /* comments or operator */
3646 p
= parse_comment(p
);
3648 } else if (c
== '/') {
3649 p
= parse_line_comment(p
);
3651 } else if (c
== '=') {
3671 case '$': /* only used in assembler */
3676 error("unrecognized character \\x%02x", c
);
3681 #if defined(PARSE_DEBUG)
3682 printf("token = %s\n", get_tok_str(tok
, &tokc
));
3686 /* return next token without macro substitution. Can read input from
3688 static void next_nomacro(void)
3694 TOK_GET(tok
, macro_ptr
, tokc
);
3695 if (tok
== TOK_LINENUM
) {
3696 file
->line_num
= tokc
.i
;
3705 /* substitute args in macro_str and return allocated string */
3706 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
3708 int *st
, last_tok
, t
, notfirst
;
3717 TOK_GET(t
, macro_str
, cval
);
3722 TOK_GET(t
, macro_str
, cval
);
3725 s
= sym_find2(args
, t
);
3732 cstr_ccat(&cstr
, ' ');
3733 TOK_GET(t
, st
, cval
);
3734 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
3737 cstr_ccat(&cstr
, '\0');
3739 printf("stringize: %s\n", (char *)cstr
.data
);
3743 tok_str_add2(&str
, TOK_STR
, &cval
);
3746 tok_str_add2(&str
, t
, &cval
);
3748 } else if (t
>= TOK_IDENT
) {
3749 s
= sym_find2(args
, t
);
3752 /* if '##' is present before or after, no arg substitution */
3753 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
3754 /* special case for var arg macros : ## eats the
3755 ',' if empty VA_ARGS variable. */
3756 /* XXX: test of the ',' is not 100%
3757 reliable. should fix it to avoid security
3759 if (gnu_ext
&& s
->type
.t
&&
3760 last_tok
== TOK_TWOSHARPS
&&
3761 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
3763 /* suppress ',' '##' */
3766 /* suppress '##' and add variable */
3774 TOK_GET(t1
, st
, cval
);
3777 tok_str_add2(&str
, t1
, &cval
);
3781 /* NOTE: the stream cannot be read when macro
3782 substituing an argument */
3783 macro_subst(&str
, nested_list
, st
, 0);
3786 tok_str_add(&str
, t
);
3789 tok_str_add2(&str
, t
, &cval
);
3793 tok_str_add(&str
, 0);
3797 static char const ab_month_name
[12][4] =
3799 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3800 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3803 /* do macro substitution of current token with macro 's' and add
3804 result to (tok_str,tok_len). 'nested_list' is the list of all
3805 macros we got inside to avoid recursing. Return non zero if no
3806 substitution needs to be done */
3807 static int macro_subst_tok(TokenString
*tok_str
,
3808 Sym
**nested_list
, Sym
*s
, int can_read_stream
)
3810 Sym
*args
, *sa
, *sa1
;
3811 int mstr_allocated
, parlevel
, *mstr
, t
;
3817 /* if symbol is a macro, prepare substitution */
3819 /* special macros */
3820 if (tok
== TOK___LINE__
) {
3821 cval
.i
= file
->line_num
;
3822 tok_str_add2(tok_str
, TOK_CINT
, &cval
);
3823 } else if (tok
== TOK___FILE__
) {
3824 cstrval
= file
->filename
;
3826 tok_str_add2(tok_str
, TOK_STR
, &cval
);
3827 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3833 tm
= localtime(&ti
);
3834 if (tok
== TOK___DATE__
) {
3835 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3836 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3838 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3839 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3844 cstr_cat(&cstr
, cstrval
);
3845 cstr_ccat(&cstr
, '\0');
3847 tok_str_add2(tok_str
, TOK_STR
, &cval
);
3852 if (s
->type
.t
== MACRO_FUNC
) {
3853 /* NOTE: we do not use next_nomacro to avoid eating the
3854 next token. XXX: find better solution */
3857 if (t
== 0 && can_read_stream
) {
3858 /* end of macro stream: we must look at the token
3859 after in the file */
3865 /* XXX: incorrect with comments */
3866 ch
= file
->buf_ptr
[0];
3867 while (is_space(ch
) || ch
== '\n')
3871 if (t
!= '(') /* no macro subst */
3874 /* argument macro */
3879 /* NOTE: empty args are allowed, except if no args */
3881 /* handle '()' case */
3882 if (!args
&& !sa
&& tok
== ')')
3885 error("macro '%s' used with too many args",
3886 get_tok_str(s
->v
, 0));
3889 /* NOTE: non zero sa->t indicates VA_ARGS */
3890 while ((parlevel
> 0 ||
3892 (tok
!= ',' || sa
->type
.t
))) &&
3896 else if (tok
== ')')
3898 tok_str_add2(&str
, tok
, &tokc
);
3901 tok_str_add(&str
, 0);
3902 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (int)str
.str
);
3905 /* special case for gcc var args: add an empty
3906 var arg argument if it is omitted */
3907 if (sa
&& sa
->type
.t
&& gnu_ext
)
3917 error("macro '%s' used with too few args",
3918 get_tok_str(s
->v
, 0));
3921 /* now subst each arg */
3922 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3927 tok_str_free((int *)sa
->c
);
3933 sym_push2(nested_list
, s
->v
, 0, 0);
3934 macro_subst(tok_str
, nested_list
, mstr
, 1);
3935 /* pop nested defined symbol */
3937 *nested_list
= sa1
->prev
;
3945 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3946 return the resulting string (which must be freed). */
3947 static inline int *macro_twosharps(const int *macro_str
)
3950 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
3952 const char *p1
, *p2
;
3954 TokenString macro_str1
;
3957 start_macro_ptr
= macro_str
;
3958 /* we search the first '##' */
3960 macro_ptr1
= macro_str
;
3961 TOK_GET(t
, macro_str
, cval
);
3962 /* nothing more to do if end of string */
3965 if (*macro_str
== TOK_TWOSHARPS
)
3969 /* we saw '##', so we need more processing to handle it */
3971 tok_str_new(¯o_str1
);
3975 /* add all tokens seen so far */
3976 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
3977 TOK_GET(t
, ptr
, cval
);
3978 tok_str_add2(¯o_str1
, t
, &cval
);
3980 saved_macro_ptr
= macro_ptr
;
3981 /* XXX: get rid of the use of macro_ptr here */
3982 macro_ptr
= (int *)macro_str
;
3984 while (*macro_ptr
== TOK_TWOSHARPS
) {
3986 macro_ptr1
= macro_ptr
;
3989 TOK_GET(t
, macro_ptr
, cval
);
3990 /* We concatenate the two tokens if we have an
3991 identifier or a preprocessing number */
3993 p1
= get_tok_str(tok
, &tokc
);
3994 cstr_cat(&cstr
, p1
);
3995 p2
= get_tok_str(t
, &cval
);
3996 cstr_cat(&cstr
, p2
);
3997 cstr_ccat(&cstr
, '\0');
3999 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
4000 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
4001 if (tok
== TOK_PPNUM
) {
4002 /* if number, then create a number token */
4003 /* NOTE: no need to allocate because
4004 tok_str_add2() does it */
4007 /* if identifier, we must do a test to
4008 validate we have a correct identifier */
4009 if (t
== TOK_PPNUM
) {
4019 if (!isnum(c
) && !isid(c
))
4023 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
4024 tok
= ts
->tok
; /* modify current token */
4027 const char *str
= cstr
.data
;
4028 const unsigned char *q
;
4030 /* we look for a valid token */
4031 /* XXX: do more extensive checks */
4032 if (!strcmp(str
, ">>=")) {
4034 } else if (!strcmp(str
, "<<=")) {
4036 } else if (strlen(str
) == 2) {
4037 /* search in two bytes table */
4042 if (q
[0] == str
[0] && q
[1] == str
[1])
4049 /* NOTE: because get_tok_str use a static buffer,
4052 p1
= get_tok_str(tok
, &tokc
);
4053 cstr_cat(&cstr
, p1
);
4054 cstr_ccat(&cstr
, '\0');
4055 p2
= get_tok_str(t
, &cval
);
4056 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
4057 /* cannot merge tokens: just add them separately */
4058 tok_str_add2(¯o_str1
, tok
, &tokc
);
4059 /* XXX: free associated memory ? */
4066 tok_str_add2(¯o_str1
, tok
, &tokc
);
4071 macro_ptr
= (int *)saved_macro_ptr
;
4073 tok_str_add(¯o_str1
, 0);
4074 return macro_str1
.str
;
4078 /* do macro substitution of macro_str and add result to
4079 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4080 inside to avoid recursing. */
4081 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
4082 const int *macro_str
, int can_read_stream
)
4085 int *saved_macro_ptr
, *macro_str1
;
4090 /* first scan for '##' operator handling */
4092 macro_str1
= macro_twosharps(ptr
);
4096 /* NOTE: ptr == NULL can only happen if tokens are read from
4097 file stream due to a macro function call */
4100 TOK_GET(t
, ptr
, cval
);
4105 /* if nested substitution, do nothing */
4106 if (sym_find2(*nested_list
, t
))
4108 saved_macro_ptr
= macro_ptr
;
4109 macro_ptr
= (int *)ptr
;
4111 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
4112 ptr
= (int *)macro_ptr
;
4113 macro_ptr
= saved_macro_ptr
;
4118 tok_str_add2(tok_str
, t
, &cval
);
4122 tok_str_free(macro_str1
);
4125 /* return next token with macro substitution */
4126 static void next(void)
4128 Sym
*nested_list
, *s
;
4134 /* if not reading from macro substituted string, then try
4135 to substitute macros */
4136 if (tok
>= TOK_IDENT
&&
4137 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4138 s
= define_find(tok
);
4140 /* we have a macro: we try to substitute */
4143 if (macro_subst_tok(&str
, &nested_list
, s
, 1) == 0) {
4144 /* substitution done, NOTE: maybe empty */
4145 tok_str_add(&str
, 0);
4146 macro_ptr
= str
.str
;
4147 macro_ptr_allocated
= str
.str
;
4154 /* end of macro or end of unget buffer */
4155 if (unget_buffer_enabled
) {
4156 macro_ptr
= unget_saved_macro_ptr
;
4157 unget_buffer_enabled
= 0;
4159 /* end of macro string: free it */
4160 tok_str_free(macro_ptr_allocated
);
4167 /* convert preprocessor tokens into C tokens */
4168 if (tok
== TOK_PPNUM
&&
4169 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4170 parse_number((char *)tokc
.cstr
->data
);
4174 /* push back current token and set current token to 'last_tok'. Only
4175 identifier case handled for labels. */
4176 static inline void unget_tok(int last_tok
)
4180 unget_saved_macro_ptr
= macro_ptr
;
4181 unget_buffer_enabled
= 1;
4182 q
= unget_saved_buffer
;
4185 n
= tok_ext_size(tok
) - 1;
4188 *q
= 0; /* end of token string */
4193 void swap(int *p
, int *q
)
4201 void vsetc(CType
*type
, int r
, CValue
*vc
)
4205 if (vtop
>= vstack
+ VSTACK_SIZE
)
4206 error("memory full");
4207 /* cannot let cpu flags if other instruction are generated. Also
4208 avoid leaving VT_JMP anywhere except on the top of the stack
4209 because it would complicate the code generator. */
4210 if (vtop
>= vstack
) {
4211 v
= vtop
->r
& VT_VALMASK
;
4212 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4218 vtop
->r2
= VT_CONST
;
4222 /* push integer constant */
4227 vsetc(&int_type
, VT_CONST
, &cval
);
4230 /* Return a static symbol pointing to a section */
4231 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4232 unsigned long offset
, unsigned long size
)
4238 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4239 sym
->type
.ref
= type
->ref
;
4240 sym
->r
= VT_CONST
| VT_SYM
;
4241 put_extern_sym(sym
, sec
, offset
, size
);
4245 /* push a reference to a section offset by adding a dummy symbol */
4246 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4251 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4252 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4255 /* define a new external reference to a symbol 'v' of type 'u' */
4256 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4262 /* push forward reference */
4263 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4264 s
->type
.ref
= type
->ref
;
4265 s
->r
= r
| VT_CONST
| VT_SYM
;
4270 /* define a new external reference to a symbol 'v' of type 'u' */
4271 static Sym
*external_sym(int v
, CType
*type
, int r
)
4277 /* push forward reference */
4278 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4279 s
->type
.t
|= VT_EXTERN
;
4281 if (!is_compatible_types(&s
->type
, type
))
4282 error("incompatible types for redefinition of '%s'",
4283 get_tok_str(v
, NULL
));
4288 /* push a reference to global symbol v */
4289 static void vpush_global_sym(CType
*type
, int v
)
4294 sym
= external_global_sym(v
, type
, 0);
4296 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4300 void vset(CType
*type
, int r
, int v
)
4305 vsetc(type
, r
, &cval
);
4308 void vseti(int r
, int v
)
4324 void vpushv(SValue
*v
)
4326 if (vtop
>= vstack
+ VSTACK_SIZE
)
4327 error("memory full");
4337 /* save r to the memory stack, and mark it as being free */
4338 void save_reg(int r
)
4340 int l
, saved
, size
, align
;
4344 /* modify all stack values */
4347 for(p
=vstack
;p
<=vtop
;p
++) {
4348 if ((p
->r
& VT_VALMASK
) == r
||
4349 (p
->r2
& VT_VALMASK
) == r
) {
4350 /* must save value on stack if not already done */
4352 /* NOTE: must reload 'r' because r might be equal to r2 */
4353 r
= p
->r
& VT_VALMASK
;
4354 /* store register in the stack */
4356 if ((p
->r
& VT_LVAL
) ||
4357 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4359 size
= type_size(type
, &align
);
4360 loc
= (loc
- size
) & -align
;
4361 sv
.type
.t
= type
->t
;
4362 sv
.r
= VT_LOCAL
| VT_LVAL
;
4365 #ifdef TCC_TARGET_I386
4366 /* x86 specific: need to pop fp register ST0 if saved */
4367 if (r
== TREG_ST0
) {
4368 o(0xd9dd); /* fstp %st(1) */
4371 /* special long long case */
4372 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4379 /* mark that stack entry as being saved on the stack */
4380 if (p
->r
& VT_LVAL
) {
4381 /* also clear the bounded flag because the
4382 relocation address of the function was stored in
4384 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4386 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4394 /* find a register of class 'rc2' with at most one reference on stack.
4395 * If none, call get_reg(rc) */
4396 int get_reg_ex(int rc
, int rc2
)
4401 for(r
=0;r
<NB_REGS
;r
++) {
4402 if (reg_classes
[r
] & rc2
) {
4405 for(p
= vstack
; p
<= vtop
; p
++) {
4406 if ((p
->r
& VT_VALMASK
) == r
||
4407 (p
->r2
& VT_VALMASK
) == r
)
4417 /* find a free register of class 'rc'. If none, save one register */
4423 /* find a free register */
4424 for(r
=0;r
<NB_REGS
;r
++) {
4425 if (reg_classes
[r
] & rc
) {
4426 for(p
=vstack
;p
<=vtop
;p
++) {
4427 if ((p
->r
& VT_VALMASK
) == r
||
4428 (p
->r2
& VT_VALMASK
) == r
)
4436 /* no register left : free the first one on the stack (VERY
4437 IMPORTANT to start from the bottom to ensure that we don't
4438 spill registers used in gen_opi()) */
4439 for(p
=vstack
;p
<=vtop
;p
++) {
4440 r
= p
->r
& VT_VALMASK
;
4441 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4443 /* also look at second register (if long long) */
4444 r
= p
->r2
& VT_VALMASK
;
4445 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4451 /* Should never comes here */
4455 /* save registers up to (vtop - n) stack entry */
4456 void save_regs(int n
)
4461 for(p
= vstack
;p
<= p1
; p
++) {
4462 r
= p
->r
& VT_VALMASK
;
4469 /* move register 's' to 'r', and flush previous value of r to memory
4471 void move_reg(int r
, int s
)
4484 /* get address of vtop (vtop MUST BE an lvalue) */
4487 vtop
->r
&= ~VT_LVAL
;
4488 /* tricky: if saved lvalue, then we can go back to lvalue */
4489 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4490 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4493 #ifdef CONFIG_TCC_BCHECK
4494 /* generate lvalue bound code */
4500 vtop
->r
&= ~VT_MUSTBOUND
;
4501 /* if lvalue, then use checking code before dereferencing */
4502 if (vtop
->r
& VT_LVAL
) {
4503 /* if not VT_BOUNDED value, then make one */
4504 if (!(vtop
->r
& VT_BOUNDED
)) {
4505 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4506 /* must save type because we must set it to int to get pointer */
4508 vtop
->type
.t
= VT_INT
;
4511 gen_bounded_ptr_add();
4512 vtop
->r
|= lval_type
;
4515 /* then check for dereferencing */
4516 gen_bounded_ptr_deref();
4521 /* store vtop a register belonging to class 'rc'. lvalues are
4522 converted to values. Cannot be used if cannot be converted to
4523 register value (such as structures). */
4526 int r
, r2
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4527 unsigned long long ll
;
4529 /* NOTE: get_reg can modify vstack[] */
4530 if (vtop
->type
.t
& VT_BITFIELD
) {
4531 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4532 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4533 /* remove bit field info to avoid loops */
4534 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4535 /* generate shifts */
4536 vpushi(32 - (bit_pos
+ bit_size
));
4538 vpushi(32 - bit_size
);
4539 /* NOTE: transformed to SHR if unsigned */
4543 if (is_float(vtop
->type
.t
) &&
4544 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4547 unsigned long offset
;
4549 /* XXX: unify with initializers handling ? */
4550 /* CPUs usually cannot use float constants, so we store them
4551 generically in data segment */
4552 size
= type_size(&vtop
->type
, &align
);
4553 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
4554 data_section
->data_offset
= offset
;
4555 /* XXX: not portable yet */
4556 ptr
= section_ptr_add(data_section
, size
);
4559 ptr
[i
] = vtop
->c
.tab
[i
];
4560 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
4561 vtop
->r
|= VT_LVAL
| VT_SYM
;
4565 #ifdef CONFIG_TCC_BCHECK
4566 if (vtop
->r
& VT_MUSTBOUND
)
4570 r
= vtop
->r
& VT_VALMASK
;
4571 /* need to reload if:
4573 - lvalue (need to dereference pointer)
4574 - already a register, but not in the right class */
4575 if (r
>= VT_CONST
||
4576 (vtop
->r
& VT_LVAL
) ||
4577 !(reg_classes
[r
] & rc
) ||
4578 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
4579 !(reg_classes
[vtop
->r2
] & rc
))) {
4581 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
4582 /* two register type load : expand to two words
4584 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4587 vtop
->c
.ui
= ll
; /* first word */
4589 vtop
->r
= r
; /* save register value */
4590 vpushi(ll
>> 32); /* second word */
4591 } else if (r
>= VT_CONST
||
4592 (vtop
->r
& VT_LVAL
)) {
4593 /* load from memory */
4596 vtop
[-1].r
= r
; /* save register value */
4597 /* increment pointer to get second word */
4598 vtop
->type
.t
= VT_INT
;
4604 /* move registers */
4607 vtop
[-1].r
= r
; /* save register value */
4608 vtop
->r
= vtop
[-1].r2
;
4610 /* allocate second register */
4617 /* write second register */
4619 } else if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
4621 /* lvalue of scalar type : need to use lvalue type
4622 because of possible cast */
4625 /* compute memory access type */
4626 if (vtop
->r
& VT_LVAL_BYTE
)
4628 else if (vtop
->r
& VT_LVAL_SHORT
)
4630 if (vtop
->r
& VT_LVAL_UNSIGNED
)
4634 /* restore wanted type */
4637 /* one register type load */
4642 #ifdef TCC_TARGET_C67
4643 /* uses register pairs for doubles */
4644 if ((vtop
->type
.t
& VT_BTYPE
) == VT_DOUBLE
)
4651 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
4652 void gv2(int rc1
, int rc2
)
4656 /* generate more generic register first. But VT_JMP or VT_CMP
4657 values must be generated first in all cases to avoid possible
4659 v
= vtop
[0].r
& VT_VALMASK
;
4660 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
4665 /* test if reload is needed for first register */
4666 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
4676 /* test if reload is needed for first register */
4677 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
4683 /* expand long long on stack in two int registers */
4688 u
= vtop
->type
.t
& VT_UNSIGNED
;
4691 vtop
[0].r
= vtop
[-1].r2
;
4692 vtop
[0].r2
= VT_CONST
;
4693 vtop
[-1].r2
= VT_CONST
;
4694 vtop
[0].type
.t
= VT_INT
| u
;
4695 vtop
[-1].type
.t
= VT_INT
| u
;
4698 #ifdef TCC_TARGET_ARM
4699 /* expand long long on stack */
4700 void lexpand_nr(void)
4704 u
= vtop
->type
.t
& VT_UNSIGNED
;
4706 vtop
->r2
= VT_CONST
;
4707 vtop
->type
.t
= VT_INT
| u
;
4708 v
=vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
);
4709 if (v
== VT_CONST
) {
4710 vtop
[-1].c
.ui
= vtop
->c
.ull
;
4711 vtop
->c
.ui
= vtop
->c
.ull
>> 32;
4713 } else if (v
== (VT_LVAL
|VT_CONST
) || v
== (VT_LVAL
|VT_LOCAL
)) {
4715 vtop
->r
= vtop
[-1].r
;
4716 } else if (v
> VT_CONST
) {
4720 vtop
->r
= vtop
[-1].r2
;
4721 vtop
[-1].r2
= VT_CONST
;
4722 vtop
[-1].type
.t
= VT_INT
| u
;
4726 /* build a long long from two ints */
4729 gv2(RC_INT
, RC_INT
);
4730 vtop
[-1].r2
= vtop
[0].r
;
4731 vtop
[-1].type
.t
= t
;
4735 /* rotate n first stack elements to the bottom
4736 I1 ... In -> I2 ... In I1 [top is right]
4744 for(i
=-n
+1;i
!=0;i
++)
4745 vtop
[i
] = vtop
[i
+1];
4749 /* rotate n first stack elements to the top
4750 I1 ... In -> In I1 ... I(n-1) [top is right]
4758 for(i
= 0;i
< n
- 1; i
++)
4759 vtop
[-i
] = vtop
[-i
- 1];
4763 #ifdef TCC_TARGET_ARM
4764 /* like vrott but in other direction
4765 In ... I1 -> I(n-1) ... I1 In [top is right]
4773 for(i
= n
- 1; i
> 0; i
--)
4774 vtop
[-i
] = vtop
[-i
+ 1];
4779 /* pop stack value */
4783 v
= vtop
->r
& VT_VALMASK
;
4784 #ifdef TCC_TARGET_I386
4785 /* for x86, we need to pop the FP stack */
4786 if (v
== TREG_ST0
&& !nocode_wanted
) {
4787 o(0xd9dd); /* fstp %st(1) */
4790 if (v
== VT_JMP
|| v
== VT_JMPI
) {
4791 /* need to put correct jump if && or || without test */
4797 /* convert stack entry to register and duplicate its value in another
4805 if ((t
& VT_BTYPE
) == VT_LLONG
) {
4812 /* stack: H L L1 H1 */
4820 /* duplicate value */
4831 load(r1
, &sv
); /* move r to r1 */
4833 /* duplicates value */
4838 /* generate CPU independent (unsigned) long long operations */
4839 void gen_opl(int op
)
4841 int t
, a
, b
, op1
, c
, i
;
4848 func
= TOK___divdi3
;
4851 func
= TOK___udivdi3
;
4854 func
= TOK___moddi3
;
4857 func
= TOK___umoddi3
;
4859 /* call generic long long function */
4860 vpush_global_sym(&func_old_type
, func
);
4865 vtop
->r2
= REG_LRET
;
4878 /* stack: L1 H1 L2 H2 */
4883 vtop
[-2] = vtop
[-3];
4886 /* stack: H1 H2 L1 L2 */
4892 /* stack: H1 H2 L1 L2 ML MH */
4895 /* stack: ML MH H1 H2 L1 L2 */
4899 /* stack: ML MH H1 L2 H2 L1 */
4904 /* stack: ML MH M1 M2 */
4907 } else if (op
== '+' || op
== '-') {
4908 /* XXX: add non carry method too (for MIPS or alpha) */
4914 /* stack: H1 H2 (L1 op L2) */
4917 gen_op(op1
+ 1); /* TOK_xxxC2 */
4920 /* stack: H1 H2 (L1 op L2) */
4923 /* stack: (L1 op L2) H1 H2 */
4925 /* stack: (L1 op L2) (H1 op H2) */
4933 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
4934 t
= vtop
[-1].type
.t
;
4938 /* stack: L H shift */
4940 /* constant: simpler */
4941 /* NOTE: all comments are for SHL. the other cases are
4942 done by swaping words */
4953 if (op
!= TOK_SAR
) {
4986 /* XXX: should provide a faster fallback on x86 ? */
4989 func
= TOK___sardi3
;
4992 func
= TOK___shrdi3
;
4995 func
= TOK___shldi3
;
5001 /* compare operations */
5007 /* stack: L1 H1 L2 H2 */
5009 vtop
[-1] = vtop
[-2];
5011 /* stack: L1 L2 H1 H2 */
5014 /* when values are equal, we need to compare low words. since
5015 the jump is inverted, we invert the test too. */
5018 else if (op1
== TOK_GT
)
5020 else if (op1
== TOK_ULT
)
5022 else if (op1
== TOK_UGT
)
5027 if (op1
!= TOK_NE
) {
5031 /* generate non equal test */
5032 /* XXX: NOT PORTABLE yet */
5036 #if defined(TCC_TARGET_I386)
5037 b
= psym(0x850f, 0);
5038 #elif defined(TCC_TARGET_ARM)
5040 o(0x1A000000 | encbranch(ind
, 0, 1));
5041 #elif defined(TCC_TARGET_C67)
5042 error("not implemented");
5044 #error not supported
5048 /* compare low. Always unsigned */
5052 else if (op1
== TOK_LE
)
5054 else if (op1
== TOK_GT
)
5056 else if (op1
== TOK_GE
)
5066 /* handle integer constant optimizations and various machine
5068 void gen_opic(int op
)
5075 /* currently, we cannot do computations with forward symbols */
5076 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5077 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5081 case '+': v1
->c
.i
+= fc
; break;
5082 case '-': v1
->c
.i
-= fc
; break;
5083 case '&': v1
->c
.i
&= fc
; break;
5084 case '^': v1
->c
.i
^= fc
; break;
5085 case '|': v1
->c
.i
|= fc
; break;
5086 case '*': v1
->c
.i
*= fc
; break;
5093 /* if division by zero, generate explicit division */
5096 error("division by zero in constant");
5100 default: v1
->c
.i
/= fc
; break;
5101 case '%': v1
->c
.i
%= fc
; break;
5102 case TOK_UDIV
: v1
->c
.i
= (unsigned)v1
->c
.i
/ fc
; break;
5103 case TOK_UMOD
: v1
->c
.i
= (unsigned)v1
->c
.i
% fc
; break;
5106 case TOK_SHL
: v1
->c
.i
<<= fc
; break;
5107 case TOK_SHR
: v1
->c
.i
= (unsigned)v1
->c
.i
>> fc
; break;
5108 case TOK_SAR
: v1
->c
.i
>>= fc
; break;
5110 case TOK_ULT
: v1
->c
.i
= (unsigned)v1
->c
.i
< (unsigned)fc
; break;
5111 case TOK_UGE
: v1
->c
.i
= (unsigned)v1
->c
.i
>= (unsigned)fc
; break;
5112 case TOK_EQ
: v1
->c
.i
= v1
->c
.i
== fc
; break;
5113 case TOK_NE
: v1
->c
.i
= v1
->c
.i
!= fc
; break;
5114 case TOK_ULE
: v1
->c
.i
= (unsigned)v1
->c
.i
<= (unsigned)fc
; break;
5115 case TOK_UGT
: v1
->c
.i
= (unsigned)v1
->c
.i
> (unsigned)fc
; break;
5116 case TOK_LT
: v1
->c
.i
= v1
->c
.i
< fc
; break;
5117 case TOK_GE
: v1
->c
.i
= v1
->c
.i
>= fc
; break;
5118 case TOK_LE
: v1
->c
.i
= v1
->c
.i
<= fc
; break;
5119 case TOK_GT
: v1
->c
.i
= v1
->c
.i
> fc
; break;
5121 case TOK_LAND
: v1
->c
.i
= v1
->c
.i
&& fc
; break;
5122 case TOK_LOR
: v1
->c
.i
= v1
->c
.i
|| fc
; break;
5128 /* if commutative ops, put c2 as constant */
5129 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
5130 op
== '|' || op
== '*')) {
5135 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
5138 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
5139 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
5145 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
5146 /* try to use shifts instead of muls or divs */
5147 if (fc
> 0 && (fc
& (fc
- 1)) == 0) {
5156 else if (op
== TOK_PDIV
)
5162 } else if (c2
&& (op
== '+' || op
== '-') &&
5163 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5164 (VT_CONST
| VT_SYM
)) {
5165 /* symbol + constant case */
5172 if (!nocode_wanted
) {
5173 /* call low level op generator */
5182 /* generate a floating point operation with constant propagation */
5183 void gen_opif(int op
)
5191 /* currently, we cannot do computations with forward symbols */
5192 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5193 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5195 if (v1
->type
.t
== VT_FLOAT
) {
5198 } else if (v1
->type
.t
== VT_DOUBLE
) {
5206 /* NOTE: we only do constant propagation if finite number (not
5207 NaN or infinity) (ANSI spec) */
5208 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5212 case '+': f1
+= f2
; break;
5213 case '-': f1
-= f2
; break;
5214 case '*': f1
*= f2
; break;
5218 error("division by zero in constant");
5223 /* XXX: also handles tests ? */
5227 /* XXX: overflow test ? */
5228 if (v1
->type
.t
== VT_FLOAT
) {
5230 } else if (v1
->type
.t
== VT_DOUBLE
) {
5238 if (!nocode_wanted
) {
5246 static int pointed_size(CType
*type
)
5249 return type_size(pointed_type(type
), &align
);
5252 static inline int is_null_pointer(SValue
*p
)
5254 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5256 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5257 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5260 static inline int is_integer_btype(int bt
)
5262 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5263 bt
== VT_INT
|| bt
== VT_LLONG
);
5266 /* check types for comparison or substraction of pointers */
5267 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5269 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5272 /* null pointers are accepted for all comparisons as gcc */
5273 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5277 bt1
= type1
->t
& VT_BTYPE
;
5278 bt2
= type2
->t
& VT_BTYPE
;
5279 /* accept comparison between pointer and integer with a warning */
5280 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5281 warning("comparison between pointer and integer");
5285 /* both must be pointers or implicit function pointers */
5286 if (bt1
== VT_PTR
) {
5287 type1
= pointed_type(type1
);
5288 } else if (bt1
!= VT_FUNC
)
5289 goto invalid_operands
;
5291 if (bt2
== VT_PTR
) {
5292 type2
= pointed_type(type2
);
5293 } else if (bt2
!= VT_FUNC
) {
5295 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5297 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5298 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5302 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5303 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5304 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5305 /* gcc-like error if '-' is used */
5307 goto invalid_operands
;
5309 warning("comparison of distinct pointer types lacks a cast");
5313 /* generic gen_op: handles types problems */
5316 int u
, t1
, t2
, bt1
, bt2
, t
;
5319 t1
= vtop
[-1].type
.t
;
5320 t2
= vtop
[0].type
.t
;
5321 bt1
= t1
& VT_BTYPE
;
5322 bt2
= t2
& VT_BTYPE
;
5324 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5325 /* at least one operand is a pointer */
5326 /* relationnal op: must be both pointers */
5327 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5328 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5329 /* pointers are handled are unsigned */
5330 t
= VT_INT
| VT_UNSIGNED
;
5333 /* if both pointers, then it must be the '-' op */
5334 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5336 error("cannot use pointers here");
5337 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5338 /* XXX: check that types are compatible */
5339 u
= pointed_size(&vtop
[-1].type
);
5341 /* set to integer type */
5342 vtop
->type
.t
= VT_INT
;
5346 /* exactly one pointer : must be '+' or '-'. */
5347 if (op
!= '-' && op
!= '+')
5348 error("cannot use pointers here");
5349 /* Put pointer as first operand */
5350 if (bt2
== VT_PTR
) {
5354 type1
= vtop
[-1].type
;
5355 /* XXX: cast to int ? (long long case) */
5356 vpushi(pointed_size(&vtop
[-1].type
));
5358 #ifdef CONFIG_TCC_BCHECK
5359 /* if evaluating constant expression, no code should be
5360 generated, so no bound check */
5361 if (do_bounds_check
&& !const_wanted
) {
5362 /* if bounded pointers, we generate a special code to
5369 gen_bounded_ptr_add();
5375 /* put again type if gen_opic() swaped operands */
5378 } else if (is_float(bt1
) || is_float(bt2
)) {
5379 /* compute bigger type and do implicit casts */
5380 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5382 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5387 /* floats can only be used for a few operations */
5388 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5389 (op
< TOK_ULT
|| op
> TOK_GT
))
5390 error("invalid operands for binary operation");
5392 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5393 /* cast to biggest op */
5395 /* convert to unsigned if it does not fit in a long long */
5396 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5397 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5401 /* integer operations */
5403 /* convert to unsigned if it does not fit in an integer */
5404 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5405 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5408 /* XXX: currently, some unsigned operations are explicit, so
5409 we modify them here */
5410 if (t
& VT_UNSIGNED
) {
5417 else if (op
== TOK_LT
)
5419 else if (op
== TOK_GT
)
5421 else if (op
== TOK_LE
)
5423 else if (op
== TOK_GE
)
5430 /* special case for shifts and long long: we keep the shift as
5432 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5437 else if ((t
& VT_BTYPE
) == VT_LLONG
)
5441 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5442 /* relationnal op: the result is an int */
5443 vtop
->type
.t
= VT_INT
;
5450 /* generic itof for unsigned long long case */
5451 void gen_cvt_itof1(int t
)
5453 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
5454 (VT_LLONG
| VT_UNSIGNED
)) {
5457 vpush_global_sym(&func_old_type
, TOK___ulltof
);
5458 else if (t
== VT_DOUBLE
)
5459 vpush_global_sym(&func_old_type
, TOK___ulltod
);
5461 vpush_global_sym(&func_old_type
, TOK___ulltold
);
5471 /* generic ftoi for unsigned long long case */
5472 void gen_cvt_ftoi1(int t
)
5476 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
5477 /* not handled natively */
5478 st
= vtop
->type
.t
& VT_BTYPE
;
5480 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
5481 else if (st
== VT_DOUBLE
)
5482 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
5484 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
5489 vtop
->r2
= REG_LRET
;
5495 /* force char or short cast */
5496 void force_charshort_cast(int t
)
5500 /* XXX: add optimization if lvalue : just change type and offset */
5505 if (t
& VT_UNSIGNED
) {
5506 vpushi((1 << bits
) - 1);
5517 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
5518 static void gen_cast(CType
*type
)
5520 int sbt
, dbt
, sf
, df
, c
;
5522 /* special delayed cast for char/short */
5523 /* XXX: in some cases (multiple cascaded casts), it may still
5525 if (vtop
->r
& VT_MUSTCAST
) {
5526 vtop
->r
&= ~VT_MUSTCAST
;
5527 force_charshort_cast(vtop
->type
.t
);
5530 /* bitfields first get cast to ints */
5531 if (vtop
->type
.t
& VT_BITFIELD
) {
5535 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
5536 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
5538 if (sbt
!= dbt
&& !nocode_wanted
) {
5541 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5543 /* convert from fp to fp */
5545 /* constant case: we can do it now */
5546 /* XXX: in ISOC, cannot do it if error in convert */
5547 if (dbt
== VT_FLOAT
&& sbt
== VT_DOUBLE
)
5548 vtop
->c
.f
= (float)vtop
->c
.d
;
5549 else if (dbt
== VT_FLOAT
&& sbt
== VT_LDOUBLE
)
5550 vtop
->c
.f
= (float)vtop
->c
.ld
;
5551 else if (dbt
== VT_DOUBLE
&& sbt
== VT_FLOAT
)
5552 vtop
->c
.d
= (double)vtop
->c
.f
;
5553 else if (dbt
== VT_DOUBLE
&& sbt
== VT_LDOUBLE
)
5554 vtop
->c
.d
= (double)vtop
->c
.ld
;
5555 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_FLOAT
)
5556 vtop
->c
.ld
= (long double)vtop
->c
.f
;
5557 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_DOUBLE
)
5558 vtop
->c
.ld
= (long double)vtop
->c
.d
;
5560 /* non constant case: generate code */
5564 /* convert int to fp */
5567 case VT_LLONG
| VT_UNSIGNED
:
5569 /* XXX: add const cases for long long */
5571 case VT_INT
| VT_UNSIGNED
:
5573 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.ui
; break;
5574 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.ui
; break;
5575 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.ui
; break;
5580 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.i
; break;
5581 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.i
; break;
5582 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.i
; break;
5588 #if !defined(TCC_TARGET_ARM)
5595 /* convert fp to int */
5596 /* we handle char/short/etc... with generic code */
5597 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
5598 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
5603 case VT_LLONG
| VT_UNSIGNED
:
5605 /* XXX: add const cases for long long */
5607 case VT_INT
| VT_UNSIGNED
:
5609 case VT_FLOAT
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5610 case VT_DOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5611 case VT_LDOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5617 case VT_FLOAT
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5618 case VT_DOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5619 case VT_LDOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5627 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
5628 /* additional cast for char/short/bool... */
5632 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
5633 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
5634 /* scalar to long long */
5636 if (sbt
== (VT_INT
| VT_UNSIGNED
))
5637 vtop
->c
.ll
= vtop
->c
.ui
;
5639 vtop
->c
.ll
= vtop
->c
.i
;
5641 /* machine independent conversion */
5643 /* generate high word */
5644 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
5652 /* patch second register */
5653 vtop
[-1].r2
= vtop
->r
;
5657 } else if (dbt
== VT_BOOL
) {
5658 /* scalar to bool */
5661 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
5662 (dbt
& VT_BTYPE
) == VT_SHORT
) {
5663 force_charshort_cast(dbt
);
5664 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
5666 if (sbt
== VT_LLONG
) {
5667 /* from long long: just take low order word */
5671 /* if lvalue and single word type, nothing to do because
5672 the lvalue already contains the real type size (see
5673 VT_LVAL_xxx constants) */
5679 /* return type size. Put alignment at 'a' */
5680 static int type_size(CType
*type
, int *a
)
5685 bt
= type
->t
& VT_BTYPE
;
5686 if (bt
== VT_STRUCT
) {
5691 } else if (bt
== VT_PTR
) {
5692 if (type
->t
& VT_ARRAY
) {
5694 return type_size(&s
->type
, a
) * s
->c
;
5699 } else if (bt
== VT_LDOUBLE
) {
5701 return LDOUBLE_SIZE
;
5702 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
5703 #ifdef TCC_TARGET_I386
5709 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
5712 } else if (bt
== VT_SHORT
) {
5716 /* char, void, function, _Bool */
5722 /* return the pointed type of t */
5723 static inline CType
*pointed_type(CType
*type
)
5725 return &type
->ref
->type
;
5728 /* modify type so that its it is a pointer to type. */
5729 static void mk_pointer(CType
*type
)
5732 s
= sym_push(SYM_FIELD
, type
, 0, -1);
5733 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
5737 /* compare function types. OLD functions match any new functions */
5738 static int is_compatible_func(CType
*type1
, CType
*type2
)
5744 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5746 /* XXX: not complete */
5747 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
5751 while (s1
!= NULL
) {
5754 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5764 /* return true if type1 and type2 are exactly the same (including
5767 - enums are not checked as gcc __builtin_types_compatible_p ()
5769 static int is_compatible_types(CType
*type1
, CType
*type2
)
5773 t1
= type1
->t
& VT_TYPE
;
5774 t2
= type2
->t
& VT_TYPE
;
5775 /* XXX: bitfields ? */
5778 /* test more complicated cases */
5779 bt1
= t1
& VT_BTYPE
;
5780 if (bt1
== VT_PTR
) {
5781 type1
= pointed_type(type1
);
5782 type2
= pointed_type(type2
);
5783 return is_compatible_types(type1
, type2
);
5784 } else if (bt1
== VT_STRUCT
) {
5785 return (type1
->ref
== type2
->ref
);
5786 } else if (bt1
== VT_FUNC
) {
5787 return is_compatible_func(type1
, type2
);
5793 /* print a type. If 'varstr' is not NULL, then the variable is also
5794 printed in the type */
5796 /* XXX: add array and function pointers */
5797 void type_to_str(char *buf
, int buf_size
,
5798 CType
*type
, const char *varstr
)
5805 t
= type
->t
& VT_TYPE
;
5808 if (t
& VT_CONSTANT
)
5809 pstrcat(buf
, buf_size
, "const ");
5810 if (t
& VT_VOLATILE
)
5811 pstrcat(buf
, buf_size
, "volatile ");
5812 if (t
& VT_UNSIGNED
)
5813 pstrcat(buf
, buf_size
, "unsigned ");
5843 tstr
= "long double";
5845 pstrcat(buf
, buf_size
, tstr
);
5849 if (bt
== VT_STRUCT
)
5853 pstrcat(buf
, buf_size
, tstr
);
5854 v
= type
->ref
->v
& ~SYM_STRUCT
;
5855 if (v
>= SYM_FIRST_ANOM
)
5856 pstrcat(buf
, buf_size
, "<anonymous>");
5858 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
5862 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
5863 pstrcat(buf
, buf_size
, "(");
5865 while (sa
!= NULL
) {
5866 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
5867 pstrcat(buf
, buf_size
, buf1
);
5870 pstrcat(buf
, buf_size
, ", ");
5872 pstrcat(buf
, buf_size
, ")");
5876 pstrcpy(buf1
, sizeof(buf1
), "*");
5878 pstrcat(buf1
, sizeof(buf1
), varstr
);
5879 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
5883 pstrcat(buf
, buf_size
, " ");
5884 pstrcat(buf
, buf_size
, varstr
);
5889 /* verify type compatibility to store vtop in 'dt' type, and generate
5891 static void gen_assign_cast(CType
*dt
)
5893 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
5894 char buf1
[256], buf2
[256];
5897 st
= &vtop
->type
; /* source type */
5898 dbt
= dt
->t
& VT_BTYPE
;
5899 sbt
= st
->t
& VT_BTYPE
;
5900 if (dt
->t
& VT_CONSTANT
)
5901 warning("assignment of read-only location");
5904 /* special cases for pointers */
5905 /* '0' can also be a pointer */
5906 if (is_null_pointer(vtop
))
5908 /* accept implicit pointer to integer cast with warning */
5909 if (is_integer_btype(sbt
)) {
5910 warning("assignment makes pointer from integer without a cast");
5913 type1
= pointed_type(dt
);
5914 /* a function is implicitely a function pointer */
5915 if (sbt
== VT_FUNC
) {
5916 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
5917 !is_compatible_types(pointed_type(dt
), st
))
5924 type2
= pointed_type(st
);
5925 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5926 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
5927 /* void * can match anything */
5929 /* exact type match, except for unsigned */
5932 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5933 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5934 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
5937 /* check const and volatile */
5938 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
5939 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
5940 warning("assignment discards qualifiers from pointer target type");
5946 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
5947 warning("assignment makes integer from pointer without a cast");
5949 /* XXX: more tests */
5954 tmp_type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
5955 tmp_type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
5956 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5958 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
5959 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
5960 error("cannot cast '%s' to '%s'", buf1
, buf2
);
5968 /* store vtop in lvalue pushed on stack */
5971 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
5973 ft
= vtop
[-1].type
.t
;
5974 sbt
= vtop
->type
.t
& VT_BTYPE
;
5975 dbt
= ft
& VT_BTYPE
;
5976 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
5977 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
5978 /* optimize char/short casts */
5979 delayed_cast
= VT_MUSTCAST
;
5980 vtop
->type
.t
= ft
& VT_TYPE
;
5981 /* XXX: factorize */
5982 if (ft
& VT_CONSTANT
)
5983 warning("assignment of read-only location");
5986 gen_assign_cast(&vtop
[-1].type
);
5989 if (sbt
== VT_STRUCT
) {
5990 /* if structure, only generate pointer */
5991 /* structure assignment : generate memcpy */
5992 /* XXX: optimize if small size */
5993 if (!nocode_wanted
) {
5994 size
= type_size(&vtop
->type
, &align
);
5996 vpush_global_sym(&func_old_type
, TOK_memcpy
);
6000 vtop
->type
.t
= VT_INT
;
6004 vtop
->type
.t
= VT_INT
;
6016 /* leave source on stack */
6017 } else if (ft
& VT_BITFIELD
) {
6018 /* bitfield store handling */
6019 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
6020 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
6021 /* remove bit field info to avoid loops */
6022 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
6024 /* duplicate destination */
6026 vtop
[-1] = vtop
[-2];
6028 /* mask and shift source */
6029 vpushi((1 << bit_size
) - 1);
6033 /* load destination, mask and or with source */
6035 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
6041 #ifdef CONFIG_TCC_BCHECK
6042 /* bound check case */
6043 if (vtop
[-1].r
& VT_MUSTBOUND
) {
6049 if (!nocode_wanted
) {
6053 r
= gv(rc
); /* generate value */
6054 /* if lvalue was saved on stack, must read it */
6055 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
6057 t
= get_reg(RC_INT
);
6059 sv
.r
= VT_LOCAL
| VT_LVAL
;
6060 sv
.c
.ul
= vtop
[-1].c
.ul
;
6062 vtop
[-1].r
= t
| VT_LVAL
;
6065 /* two word case handling : store second register at word + 4 */
6066 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
6068 /* convert to int to increment easily */
6069 vtop
->type
.t
= VT_INT
;
6075 /* XXX: it works because r2 is spilled last ! */
6076 store(vtop
->r2
, vtop
- 1);
6080 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
6081 vtop
->r
|= delayed_cast
;
6085 /* post defines POST/PRE add. c is the token ++ or -- */
6086 void inc(int post
, int c
)
6089 vdup(); /* save lvalue */
6091 gv_dup(); /* duplicate value */
6096 vpushi(c
- TOK_MID
);
6098 vstore(); /* store value */
6100 vpop(); /* if post op, return saved value */
6103 /* Parse GNUC __attribute__ extension. Currently, the following
6104 extensions are recognized:
6105 - aligned(n) : set data/function alignment.
6106 - section(x) : generate data/code in this section.
6107 - unused : currently ignored, but may be used someday.
6109 static void parse_attribute(AttributeDef
*ad
)
6113 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
6117 while (tok
!= ')') {
6118 if (tok
< TOK_IDENT
)
6119 expect("attribute name");
6127 expect("section name");
6128 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
6137 if (n
<= 0 || (n
& (n
- 1)) != 0)
6138 error("alignment must be a positive power of two");
6147 /* currently, no need to handle it because tcc does not
6148 track unused objects */
6152 /* currently, no need to handle it because tcc does not
6153 track unused objects */
6158 ad
->func_call
= FUNC_CDECL
;
6163 ad
->func_call
= FUNC_STDCALL
;
6166 if (tcc_state
->warn_unsupported
)
6167 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6168 /* skip parameters */
6169 /* XXX: skip parenthesis too */
6172 while (tok
!= ')' && tok
!= -1)
6187 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6188 static void struct_decl(CType
*type
, int u
)
6190 int a
, v
, size
, align
, maxalign
, c
, offset
;
6191 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
;
6196 a
= tok
; /* save decl type */
6201 /* struct already defined ? return it */
6203 expect("struct/union/enum name");
6207 error("invalid type");
6214 /* we put an undefined size for struct/union */
6215 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6216 s
->r
= 0; /* default alignment is zero as gcc */
6217 /* put struct/union/enum name in type */
6225 error("struct/union/enum already defined");
6226 /* cannot be empty */
6228 /* non empty enums are not allowed */
6229 if (a
== TOK_ENUM
) {
6233 expect("identifier");
6239 /* enum symbols have static storage */
6240 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6241 ss
->type
.t
|= VT_STATIC
;
6246 /* NOTE: we accept a trailing comma */
6256 while (tok
!= '}') {
6257 parse_btype(&btype
, &ad
);
6263 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
);
6264 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6265 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6266 error("invalid type for '%s'",
6267 get_tok_str(v
, NULL
));
6271 bit_size
= expr_const();
6272 /* XXX: handle v = 0 case for messages */
6274 error("negative width in bit-field '%s'",
6275 get_tok_str(v
, NULL
));
6276 if (v
&& bit_size
== 0)
6277 error("zero width for bit-field '%s'",
6278 get_tok_str(v
, NULL
));
6280 size
= type_size(&type1
, &align
);
6282 if (bit_size
>= 0) {
6283 bt
= type1
.t
& VT_BTYPE
;
6288 error("bitfields must have scalar type");
6290 if (bit_size
> bsize
) {
6291 error("width of '%s' exceeds its type",
6292 get_tok_str(v
, NULL
));
6293 } else if (bit_size
== bsize
) {
6294 /* no need for bit fields */
6296 } else if (bit_size
== 0) {
6297 /* XXX: what to do if only padding in a
6299 /* zero size: means to pad */
6303 /* we do not have enough room ? */
6304 if ((bit_pos
+ bit_size
) > bsize
)
6307 /* XXX: handle LSB first */
6308 type1
.t
|= VT_BITFIELD
|
6309 (bit_pos
<< VT_STRUCT_SHIFT
) |
6310 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
6311 bit_pos
+= bit_size
;
6317 /* add new memory data only if starting
6319 if (lbit_pos
== 0) {
6320 if (a
== TOK_STRUCT
) {
6321 c
= (c
+ align
- 1) & -align
;
6329 if (align
> maxalign
)
6333 printf("add field %s offset=%d",
6334 get_tok_str(v
, NULL
), offset
);
6335 if (type1
.t
& VT_BITFIELD
) {
6336 printf(" pos=%d size=%d",
6337 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
6338 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
6342 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
6346 if (tok
== ';' || tok
== TOK_EOF
)
6353 /* store size and alignment */
6354 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
6360 /* return 0 if no type declaration. otherwise, return the basic type
6363 static int parse_btype(CType
*type
, AttributeDef
*ad
)
6365 int t
, u
, type_found
, typespec_found
;
6369 memset(ad
, 0, sizeof(AttributeDef
));
6376 /* currently, we really ignore extension */
6386 if ((t
& VT_BTYPE
) != 0)
6387 error("too many basic types");
6403 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
6404 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6405 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
6406 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
6420 if ((t
& VT_BTYPE
) == VT_LONG
) {
6421 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6428 struct_decl(&type1
, VT_ENUM
);
6431 type
->ref
= type1
.ref
;
6435 struct_decl(&type1
, VT_STRUCT
);
6438 /* type modifiers */
6491 /* GNUC attribute */
6492 case TOK_ATTRIBUTE1
:
6493 case TOK_ATTRIBUTE2
:
6494 parse_attribute(ad
);
6501 parse_expr_type(&type1
);
6507 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
6509 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
6510 type
->ref
= s
->type
.ref
;
6517 if ((t
& (VT_SIGNED
|VT_UNSIGNED
)) == (VT_SIGNED
|VT_UNSIGNED
))
6518 error("signed and unsigned modifier");
6519 if (tcc_state
->char_is_unsigned
) {
6520 if ((t
& (VT_SIGNED
|VT_UNSIGNED
|VT_BTYPE
)) == VT_BYTE
)
6525 /* long is never used as type */
6526 if ((t
& VT_BTYPE
) == VT_LONG
)
6527 t
= (t
& ~VT_BTYPE
) | VT_INT
;
6532 /* convert a function parameter type (array to pointer and function to
6533 function pointer) */
6534 static inline void convert_parameter_type(CType
*pt
)
6536 /* array must be transformed to pointer according to ANSI C */
6538 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
6543 static void post_type(CType
*type
, AttributeDef
*ad
)
6546 Sym
**plast
, *s
, *first
;
6551 /* function declaration */
6556 while (tok
!= ')') {
6557 /* read param name and compute offset */
6558 if (l
!= FUNC_OLD
) {
6559 if (!parse_btype(&pt
, &ad1
)) {
6561 error("invalid type");
6568 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
6570 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6571 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
6572 error("parameter declared as void");
6579 convert_parameter_type(&pt
);
6580 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
6585 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
6592 /* if no parameters, then old type prototype */
6596 t1
= type
->t
& VT_STORAGE
;
6597 /* NOTE: const is ignored in returned type as it has a special
6598 meaning in gcc / C++ */
6599 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
6600 post_type(type
, ad
);
6601 /* we push a anonymous symbol which will contain the function prototype */
6602 s
= sym_push(SYM_FIELD
, type
, ad
->func_call
, l
);
6604 type
->t
= t1
| VT_FUNC
;
6606 } else if (tok
== '[') {
6607 /* array definition */
6613 error("invalid array size");
6616 /* parse next post type */
6617 t1
= type
->t
& VT_STORAGE
;
6618 type
->t
&= ~VT_STORAGE
;
6619 post_type(type
, ad
);
6621 /* we push a anonymous symbol which will contain the array
6623 s
= sym_push(SYM_FIELD
, type
, 0, n
);
6624 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
6629 /* Parse a type declaration (except basic type), and return the type
6630 in 'type'. 'td' is a bitmask indicating which kind of type decl is
6631 expected. 'type' should contain the basic type. 'ad' is the
6632 attribute definition of the basic type. It can be modified by
6635 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
6638 CType type1
, *type2
;
6641 while (tok
== '*') {
6649 qualifiers
|= VT_CONSTANT
;
6654 qualifiers
|= VT_VOLATILE
;
6662 type
->t
|= qualifiers
;
6665 /* XXX: clarify attribute handling */
6666 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6667 parse_attribute(ad
);
6669 /* recursive type */
6670 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
6671 type1
.t
= 0; /* XXX: same as int */
6674 /* XXX: this is not correct to modify 'ad' at this point, but
6675 the syntax is not clear */
6676 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6677 parse_attribute(ad
);
6678 type_decl(&type1
, ad
, v
, td
);
6681 /* type identifier */
6682 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
6686 if (!(td
& TYPE_ABSTRACT
))
6687 expect("identifier");
6691 post_type(type
, ad
);
6692 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6693 parse_attribute(ad
);
6696 /* append type at the end of type1 */
6709 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
6710 static int lvalue_type(int t
)
6715 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
6717 else if (bt
== VT_SHORT
)
6721 if (t
& VT_UNSIGNED
)
6722 r
|= VT_LVAL_UNSIGNED
;
6726 /* indirection with full error checking and bound check */
6727 static void indir(void)
6729 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
6731 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
6733 vtop
->type
= *pointed_type(&vtop
->type
);
6734 /* an array is never an lvalue */
6735 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6736 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6737 /* if bound checking, the referenced pointer must be checked */
6738 if (do_bounds_check
)
6739 vtop
->r
|= VT_MUSTBOUND
;
6743 /* pass a parameter to a function and do type checking and casting */
6744 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
6749 func_type
= func
->c
;
6750 if (func_type
== FUNC_OLD
||
6751 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
6752 /* default casting : only need to convert float to double */
6753 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
6757 } else if (arg
== NULL
) {
6758 error("too many arguments to function");
6761 type
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
6762 gen_assign_cast(&type
);
6766 /* parse an expression of the form '(type)' or '(expr)' and return its
6768 static void parse_expr_type(CType
*type
)
6774 if (parse_btype(type
, &ad
)) {
6775 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6782 static void parse_type(CType
*type
)
6787 if (!parse_btype(type
, &ad
)) {
6790 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6793 static void vpush_tokc(int t
)
6797 vsetc(&type
, VT_CONST
, &tokc
);
6800 static void unary(void)
6802 int n
, t
, align
, size
, r
;
6807 /* XXX: GCC 2.95.3 does not generate a table although it should be
6821 vpush_tokc(VT_INT
| VT_UNSIGNED
);
6825 vpush_tokc(VT_LLONG
);
6829 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
6833 vpush_tokc(VT_FLOAT
);
6837 vpush_tokc(VT_DOUBLE
);
6841 vpush_tokc(VT_LDOUBLE
);
6844 case TOK___FUNCTION__
:
6846 goto tok_identifier
;
6852 /* special function name identifier */
6853 len
= strlen(funcname
) + 1;
6854 /* generate char[len] type */
6859 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
6860 ptr
= section_ptr_add(data_section
, len
);
6861 memcpy(ptr
, funcname
, len
);
6869 /* string parsing */
6872 if (tcc_state
->warn_write_strings
)
6877 memset(&ad
, 0, sizeof(AttributeDef
));
6878 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
6883 if (parse_btype(&type
, &ad
)) {
6884 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
6886 /* check ISOC99 compound literal */
6888 /* data is allocated locally by default */
6893 /* all except arrays are lvalues */
6894 if (!(type
.t
& VT_ARRAY
))
6895 r
|= lvalue_type(type
.t
);
6896 memset(&ad
, 0, sizeof(AttributeDef
));
6897 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
6902 } else if (tok
== '{') {
6903 /* save all registers */
6905 /* statement expression : we do not accept break/continue
6906 inside as GCC does */
6907 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
6922 /* functions names must be treated as function pointers,
6923 except for unary '&' and sizeof. Since we consider that
6924 functions are not lvalues, we only have to handle it
6925 there and in function calls. */
6926 /* arrays can also be used although they are not lvalues */
6927 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
6928 !(vtop
->type
.t
& VT_ARRAY
))
6930 mk_pointer(&vtop
->type
);
6936 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
)
6937 vtop
->c
.i
= !vtop
->c
.i
;
6938 else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
6939 vtop
->c
.i
= vtop
->c
.i
^ 1;
6941 vseti(VT_JMP
, gtst(1, 0));
6951 /* in order to force cast, we add zero */
6953 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
6954 error("pointer not accepted for unary plus");
6964 parse_expr_type(&type
);
6968 size
= type_size(&type
, &align
);
6969 if (t
== TOK_SIZEOF
) {
6971 error("sizeof applied to an incomplete type");
6978 case TOK_builtin_types_compatible_p
:
6987 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6988 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6989 vpushi(is_compatible_types(&type1
, &type2
));
6992 case TOK_builtin_constant_p
:
6994 int saved_nocode_wanted
, res
;
6997 saved_nocode_wanted
= nocode_wanted
;
7000 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
7002 nocode_wanted
= saved_nocode_wanted
;
7022 goto tok_identifier
;
7024 /* allow to take the address of a label */
7025 if (tok
< TOK_UIDENT
)
7026 expect("label identifier");
7027 s
= label_find(tok
);
7029 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7031 if (s
->r
== LABEL_DECLARED
)
7032 s
->r
= LABEL_FORWARD
;
7035 s
->type
.t
= VT_VOID
;
7036 mk_pointer(&s
->type
);
7037 s
->type
.t
|= VT_STATIC
;
7039 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
7048 expect("identifier");
7052 error("'%s' undeclared", get_tok_str(t
, NULL
));
7053 /* for simple function calls, we tolerate undeclared
7054 external reference to int() function */
7055 if (tcc_state
->warn_implicit_function_declaration
)
7056 warning("implicit declaration of function '%s'",
7057 get_tok_str(t
, NULL
));
7058 s
= external_global_sym(t
, &func_old_type
, 0);
7060 vset(&s
->type
, s
->r
, s
->c
);
7061 /* if forward reference, we must point to s */
7062 if (vtop
->r
& VT_SYM
) {
7069 /* post operations */
7071 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
7074 } else if (tok
== '.' || tok
== TOK_ARROW
) {
7076 if (tok
== TOK_ARROW
)
7081 /* expect pointer on structure */
7082 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
7083 expect("struct or union");
7087 while ((s
= s
->next
) != NULL
) {
7092 error("field not found");
7093 /* add field offset to pointer */
7094 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
7097 /* change type to field type, and set to lvalue */
7098 vtop
->type
= s
->type
;
7099 /* an array is never an lvalue */
7100 if (!(vtop
->type
.t
& VT_ARRAY
)) {
7101 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7102 /* if bound checking, the referenced pointer must be checked */
7103 if (do_bounds_check
)
7104 vtop
->r
|= VT_MUSTBOUND
;
7107 } else if (tok
== '[') {
7113 } else if (tok
== '(') {
7119 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7120 /* pointer test (no array accepted) */
7121 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
7122 vtop
->type
= *pointed_type(&vtop
->type
);
7123 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
7127 expect("function pointer");
7130 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
7132 /* get return type */
7135 sa
= s
->next
; /* first parameter */
7137 /* compute first implicit argument if a structure is returned */
7138 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
7139 /* get some space for the returned structure */
7140 size
= type_size(&s
->type
, &align
);
7141 loc
= (loc
- size
) & -align
;
7143 ret
.r
= VT_LOCAL
| VT_LVAL
;
7144 /* pass it as 'int' to avoid structure arg passing
7146 vseti(VT_LOCAL
, loc
);
7152 /* return in register */
7153 if (is_float(ret
.type
.t
)) {
7156 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
7165 gfunc_param_typed(s
, sa
);
7175 error("too few arguments to function");
7177 if (!nocode_wanted
) {
7178 gfunc_call(nb_args
);
7180 vtop
-= (nb_args
+ 1);
7183 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
7191 static void uneq(void)
7197 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
7198 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
7199 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
7214 static void expr_prod(void)
7219 while (tok
== '*' || tok
== '/' || tok
== '%') {
7227 static void expr_sum(void)
7232 while (tok
== '+' || tok
== '-') {
7240 static void expr_shift(void)
7245 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
7253 static void expr_cmp(void)
7258 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
7259 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
7267 static void expr_cmpeq(void)
7272 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
7280 static void expr_and(void)
7283 while (tok
== '&') {
7290 static void expr_xor(void)
7293 while (tok
== '^') {
7300 static void expr_or(void)
7303 while (tok
== '|') {
7310 /* XXX: fix this mess */
7311 static void expr_land_const(void)
7314 while (tok
== TOK_LAND
) {
7321 /* XXX: fix this mess */
7322 static void expr_lor_const(void)
7325 while (tok
== TOK_LOR
) {
7332 /* only used if non constant */
7333 static void expr_land(void)
7338 if (tok
== TOK_LAND
) {
7342 if (tok
!= TOK_LAND
) {
7352 static void expr_lor(void)
7357 if (tok
== TOK_LOR
) {
7361 if (tok
!= TOK_LOR
) {
7371 /* XXX: better constant handling */
7372 static void expr_eq(void)
7374 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
7376 CType type
, type1
, type2
;
7385 if (tok
== ':' && gnu_ext
) {
7401 if (vtop
!= vstack
) {
7402 /* needed to avoid having different registers saved in
7404 if (is_float(vtop
->type
.t
))
7411 if (tok
== ':' && gnu_ext
) {
7419 sv
= *vtop
; /* save value to handle it later */
7420 vtop
--; /* no vpop so that FP stack is not flushed */
7428 bt1
= t1
& VT_BTYPE
;
7430 bt2
= t2
& VT_BTYPE
;
7431 /* cast operands to correct type according to ISOC rules */
7432 if (is_float(bt1
) || is_float(bt2
)) {
7433 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
7434 type
.t
= VT_LDOUBLE
;
7435 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
7440 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
7441 /* cast to biggest op */
7443 /* convert to unsigned if it does not fit in a long long */
7444 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
7445 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
7446 type
.t
|= VT_UNSIGNED
;
7447 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
7448 /* XXX: test pointer compatibility */
7450 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
7451 /* XXX: test structure compatibility */
7453 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
7454 /* NOTE: as an extension, we accept void on only one side */
7457 /* integer operations */
7459 /* convert to unsigned if it does not fit in an integer */
7460 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
7461 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
7462 type
.t
|= VT_UNSIGNED
;
7465 /* now we convert second operand */
7468 if (is_float(type
.t
)) {
7470 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
7471 /* for long longs, we use fixed registers to avoid having
7472 to handle a complicated move */
7477 /* this is horrible, but we must also convert first
7481 /* put again first value and cast it */
7492 static void gexpr(void)
7503 /* parse an expression and return its type without any side effect. */
7504 static void expr_type(CType
*type
)
7506 int saved_nocode_wanted
;
7508 saved_nocode_wanted
= nocode_wanted
;
7513 nocode_wanted
= saved_nocode_wanted
;
7516 /* parse a unary expression and return its type without any side
7518 static void unary_type(CType
*type
)
7530 /* parse a constant expression and return value in vtop. */
7531 static void expr_const1(void)
7540 /* parse an integer constant and return its value. */
7541 static int expr_const(void)
7545 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
7546 expect("constant expression");
7552 /* return the label token if current token is a label, otherwise
7554 static int is_label(void)
7558 /* fast test first */
7559 if (tok
< TOK_UIDENT
)
7561 /* no need to save tokc because tok is an identifier */
7568 unget_tok(last_tok
);
7573 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
7574 int case_reg
, int is_expr
)
7579 /* generate line number info */
7581 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
7582 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
7584 last_line_num
= file
->line_num
;
7588 /* default return value is (void) */
7590 vtop
->type
.t
= VT_VOID
;
7593 if (tok
== TOK_IF
) {
7600 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7602 if (c
== TOK_ELSE
) {
7606 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7607 gsym(d
); /* patch else jmp */
7610 } else if (tok
== TOK_WHILE
) {
7618 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7622 } else if (tok
== '{') {
7626 /* record local declaration stack position */
7628 llabel
= local_label_stack
;
7629 /* handle local labels declarations */
7630 if (tok
== TOK_LABEL
) {
7633 if (tok
< TOK_UIDENT
)
7634 expect("label identifier");
7635 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
7645 while (tok
!= '}') {
7650 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7653 /* pop locally defined labels */
7654 label_pop(&local_label_stack
, llabel
);
7655 /* pop locally defined symbols */
7656 sym_pop(&local_stack
, s
);
7658 } else if (tok
== TOK_RETURN
) {
7662 gen_assign_cast(&func_vt
);
7663 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
7665 /* if returning structure, must copy it to implicit
7666 first pointer arg location */
7669 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
7672 /* copy structure value to pointer */
7674 } else if (is_float(func_vt
.t
)) {
7679 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
7682 rsym
= gjmp(rsym
); /* jmp */
7683 } else if (tok
== TOK_BREAK
) {
7686 error("cannot break");
7687 *bsym
= gjmp(*bsym
);
7690 } else if (tok
== TOK_CONTINUE
) {
7693 error("cannot continue");
7694 *csym
= gjmp(*csym
);
7697 } else if (tok
== TOK_FOR
) {
7724 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7729 if (tok
== TOK_DO
) {
7734 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7745 if (tok
== TOK_SWITCH
) {
7749 /* XXX: other types than integer */
7750 case_reg
= gv(RC_INT
);
7754 b
= gjmp(0); /* jump to first case */
7756 block(&a
, csym
, &b
, &c
, case_reg
, 0);
7757 /* if no default, jmp after switch */
7765 if (tok
== TOK_CASE
) {
7772 if (gnu_ext
&& tok
== TOK_DOTS
) {
7776 warning("empty case range");
7778 /* since a case is like a label, we must skip it with a jmp */
7785 *case_sym
= gtst(1, 0);
7788 *case_sym
= gtst(1, 0);
7792 *case_sym
= gtst(1, *case_sym
);
7797 goto block_after_label
;
7799 if (tok
== TOK_DEFAULT
) {
7805 error("too many 'default'");
7808 goto block_after_label
;
7810 if (tok
== TOK_GOTO
) {
7812 if (tok
== '*' && gnu_ext
) {
7816 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
7819 } else if (tok
>= TOK_UIDENT
) {
7820 s
= label_find(tok
);
7821 /* put forward definition if needed */
7823 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7825 if (s
->r
== LABEL_DECLARED
)
7826 s
->r
= LABEL_FORWARD
;
7828 /* label already defined */
7829 if (s
->r
& LABEL_FORWARD
)
7830 s
->next
= (void *)gjmp((long)s
->next
);
7832 gjmp_addr((long)s
->next
);
7835 expect("label identifier");
7838 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
7846 if (s
->r
== LABEL_DEFINED
)
7847 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
7848 gsym((long)s
->next
);
7849 s
->r
= LABEL_DEFINED
;
7851 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
7853 s
->next
= (void *)ind
;
7854 /* we accept this, but it is a mistake */
7857 warning("deprecated use of label at end of compound statement");
7861 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7864 /* expression case */
7879 /* t is the array or struct type. c is the array or struct
7880 address. cur_index/cur_field is the pointer to the current
7881 value. 'size_only' is true if only size info is needed (only used
7883 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
7884 int *cur_index
, Sym
**cur_field
,
7888 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
7894 if (gnu_ext
&& (l
= is_label()) != 0)
7896 while (tok
== '[' || tok
== '.') {
7898 if (!(type
->t
& VT_ARRAY
))
7899 expect("array type");
7902 index
= expr_const();
7903 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
7904 expect("invalid index");
7905 if (tok
== TOK_DOTS
&& gnu_ext
) {
7907 index_last
= expr_const();
7908 if (index_last
< 0 ||
7909 (s
->c
>= 0 && index_last
>= s
->c
) ||
7911 expect("invalid index");
7917 *cur_index
= index_last
;
7918 type
= pointed_type(type
);
7919 elem_size
= type_size(type
, &align
);
7920 c
+= index
* elem_size
;
7921 /* NOTE: we only support ranges for last designator */
7922 nb_elems
= index_last
- index
+ 1;
7923 if (nb_elems
!= 1) {
7932 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
7933 expect("struct/union type");
7946 /* XXX: fix this mess by using explicit storage field */
7948 type1
.t
|= (type
->t
& ~VT_TYPE
);
7962 if (type
->t
& VT_ARRAY
) {
7964 type
= pointed_type(type
);
7965 c
+= index
* type_size(type
, &align
);
7969 error("too many field init");
7970 /* XXX: fix this mess by using explicit storage field */
7972 type1
.t
|= (type
->t
& ~VT_TYPE
);
7977 decl_initializer(type
, sec
, c
, 0, size_only
);
7979 /* XXX: make it more general */
7980 if (!size_only
&& nb_elems
> 1) {
7981 unsigned long c_end
;
7986 error("range init not supported yet for dynamic storage");
7987 c_end
= c
+ nb_elems
* elem_size
;
7988 if (c_end
> sec
->data_allocated
)
7989 section_realloc(sec
, c_end
);
7990 src
= sec
->data
+ c
;
7992 for(i
= 1; i
< nb_elems
; i
++) {
7994 memcpy(dst
, src
, elem_size
);
8000 #define EXPR_CONST 1
8003 /* store a value or an expression directly in global data or in local array */
8004 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
8005 int v
, int expr_type
)
8007 int saved_global_expr
, bt
, bit_pos
, bit_size
;
8009 unsigned long long bit_mask
;
8017 /* compound literals must be allocated globally in this case */
8018 saved_global_expr
= global_expr
;
8021 global_expr
= saved_global_expr
;
8022 /* NOTE: symbols are accepted */
8023 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
8024 error("initializer element is not constant");
8032 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
8035 /* XXX: not portable */
8036 /* XXX: generate error if incorrect relocation */
8037 gen_assign_cast(&dtype
);
8038 bt
= type
->t
& VT_BTYPE
;
8039 ptr
= sec
->data
+ c
;
8040 /* XXX: make code faster ? */
8041 if (!(type
->t
& VT_BITFIELD
)) {
8046 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
8047 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
8048 bit_mask
= (1LL << bit_size
) - 1;
8050 if ((vtop
->r
& VT_SYM
) &&
8056 (bt
== VT_INT
&& bit_size
!= 32)))
8057 error("initializer element is not computable at load time");
8060 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8063 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8066 *(double *)ptr
= vtop
->c
.d
;
8069 *(long double *)ptr
= vtop
->c
.ld
;
8072 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
8075 if (vtop
->r
& VT_SYM
) {
8076 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
8078 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8083 vset(&dtype
, VT_LOCAL
, c
);
8090 /* put zeros for variable based init */
8091 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
8094 /* nothing to do because globals are already set to zero */
8096 vpush_global_sym(&func_old_type
, TOK_memset
);
8104 /* 't' contains the type and storage info. 'c' is the offset of the
8105 object in section 'sec'. If 'sec' is NULL, it means stack based
8106 allocation. 'first' is true if array '{' must be read (multi
8107 dimension implicit array init handling). 'size_only' is true if
8108 size only evaluation is wanted (only for arrays). */
8109 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
8110 int first
, int size_only
)
8112 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
8113 int size1
, align1
, expr_type
;
8117 if (type
->t
& VT_ARRAY
) {
8121 t1
= pointed_type(type
);
8122 size1
= type_size(t1
, &align1
);
8125 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
8131 /* only parse strings here if correct type (otherwise: handle
8132 them as ((w)char *) expressions */
8133 if ((tok
== TOK_LSTR
&&
8134 (t1
->t
& VT_BTYPE
) == VT_INT
) ||
8136 (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
8137 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8142 /* compute maximum number of chars wanted */
8144 cstr_len
= cstr
->size
;
8146 cstr_len
= cstr
->size
/ sizeof(int);
8149 if (n
>= 0 && nb
> (n
- array_length
))
8150 nb
= n
- array_length
;
8153 warning("initializer-string for array is too long");
8154 /* in order to go faster for common case (char
8155 string in global variable, we handle it
8157 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
8158 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
8162 ch
= ((unsigned char *)cstr
->data
)[i
];
8164 ch
= ((int *)cstr
->data
)[i
];
8165 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
8173 /* only add trailing zero if enough storage (no
8174 warning in this case since it is standard) */
8175 if (n
< 0 || array_length
< n
) {
8177 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
8183 while (tok
!= '}') {
8184 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
8185 if (n
>= 0 && index
>= n
)
8186 error("index too large");
8187 /* must put zero in holes (note that doing it that way
8188 ensures that it even works with designators) */
8189 if (!size_only
&& array_length
< index
) {
8190 init_putz(t1
, sec
, c
+ array_length
* size1
,
8191 (index
- array_length
) * size1
);
8194 if (index
> array_length
)
8195 array_length
= index
;
8196 /* special test for multi dimensional arrays (may not
8197 be strictly correct if designators are used at the
8199 if (index
>= n
&& no_oblock
)
8208 /* put zeros at the end */
8209 if (!size_only
&& n
>= 0 && array_length
< n
) {
8210 init_putz(t1
, sec
, c
+ array_length
* size1
,
8211 (n
- array_length
) * size1
);
8213 /* patch type size if needed */
8215 s
->c
= array_length
;
8216 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
8217 (sec
|| !first
|| tok
== '{')) {
8220 /* NOTE: the previous test is a specific case for automatic
8221 struct/union init */
8222 /* XXX: union needs only one init */
8224 /* XXX: this test is incorrect for local initializers
8225 beginning with ( without {. It would be much more difficult
8226 to do it correctly (ideally, the expression parser should
8227 be used in all cases) */
8233 while (tok
== '(') {
8237 if (!parse_btype(&type1
, &ad1
))
8239 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
8241 if (!is_assignable_types(type
, &type1
))
8242 error("invalid type for cast");
8247 if (first
|| tok
== '{') {
8256 while (tok
!= '}') {
8257 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
8259 if (!size_only
&& array_length
< index
) {
8260 init_putz(type
, sec
, c
+ array_length
,
8261 index
- array_length
);
8263 index
= index
+ type_size(&f
->type
, &align1
);
8264 if (index
> array_length
)
8265 array_length
= index
;
8267 if (no_oblock
&& f
== NULL
)
8273 /* put zeros at the end */
8274 if (!size_only
&& array_length
< n
) {
8275 init_putz(type
, sec
, c
+ array_length
,
8284 } else if (tok
== '{') {
8286 decl_initializer(type
, sec
, c
, first
, size_only
);
8288 } else if (size_only
) {
8289 /* just skip expression */
8291 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
8295 else if (tok
== ')')
8300 /* currently, we always use constant expression for globals
8301 (may change for scripting case) */
8302 expr_type
= EXPR_CONST
;
8304 expr_type
= EXPR_ANY
;
8305 init_putv(type
, sec
, c
, 0, expr_type
);
8309 /* parse an initializer for type 't' if 'has_init' is non zero, and
8310 allocate space in local or global data space ('r' is either
8311 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
8312 variable 'v' of scope 'scope' is declared before initializers are
8313 parsed. If 'v' is zero, then a reference to the new object is put
8314 in the value stack. If 'has_init' is 2, a special parsing is done
8315 to handle string constants. */
8316 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
8317 int has_init
, int v
, int scope
)
8319 int size
, align
, addr
, data_offset
;
8321 ParseState saved_parse_state
;
8322 TokenString init_str
;
8325 size
= type_size(type
, &align
);
8326 /* If unknown size, we must evaluate it before
8327 evaluating initializers because
8328 initializers can generate global data too
8329 (e.g. string pointers or ISOC99 compound
8330 literals). It also simplifies local
8331 initializers handling */
8332 tok_str_new(&init_str
);
8335 error("unknown type size");
8336 /* get all init string */
8337 if (has_init
== 2) {
8338 /* only get strings */
8339 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8340 tok_str_add_tok(&init_str
);
8345 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
8347 error("unexpected end of file in initializer");
8348 tok_str_add_tok(&init_str
);
8351 else if (tok
== '}') {
8359 tok_str_add(&init_str
, -1);
8360 tok_str_add(&init_str
, 0);
8363 save_parse_state(&saved_parse_state
);
8365 macro_ptr
= init_str
.str
;
8367 decl_initializer(type
, NULL
, 0, 1, 1);
8368 /* prepare second initializer parsing */
8369 macro_ptr
= init_str
.str
;
8372 /* if still unknown size, error */
8373 size
= type_size(type
, &align
);
8375 error("unknown type size");
8377 /* take into account specified alignment if bigger */
8378 if (ad
->aligned
> align
)
8379 align
= ad
->aligned
;
8380 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
8382 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
8384 loc
= (loc
- size
) & -align
;
8386 /* handles bounds */
8387 /* XXX: currently, since we do only one pass, we cannot track
8388 '&' operators, so we add only arrays */
8389 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
8390 unsigned long *bounds_ptr
;
8391 /* add padding between regions */
8393 /* then add local bound info */
8394 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
8395 bounds_ptr
[0] = addr
;
8396 bounds_ptr
[1] = size
;
8399 /* local variable */
8400 sym_push(v
, type
, r
, addr
);
8402 /* push local reference */
8403 vset(type
, r
, addr
);
8409 if (v
&& scope
== VT_CONST
) {
8410 /* see if the symbol was already defined */
8413 if (!is_compatible_types(&sym
->type
, type
))
8414 error("incompatible types for redefinition of '%s'",
8415 get_tok_str(v
, NULL
));
8416 if (sym
->type
.t
& VT_EXTERN
) {
8417 /* if the variable is extern, it was not allocated */
8418 sym
->type
.t
&= ~VT_EXTERN
;
8420 /* we accept several definitions of the same
8421 global variable. this is tricky, because we
8422 must play with the SHN_COMMON type of the symbol */
8423 /* XXX: should check if the variable was already
8424 initialized. It is incorrect to initialized it
8426 /* no init data, we won't add more to the symbol */
8433 /* allocate symbol in corresponding section */
8440 data_offset
= sec
->data_offset
;
8441 data_offset
= (data_offset
+ align
- 1) & -align
;
8443 /* very important to increment global pointer at this time
8444 because initializers themselves can create new initializers */
8445 data_offset
+= size
;
8446 /* add padding if bound check */
8447 if (do_bounds_check
)
8449 sec
->data_offset
= data_offset
;
8450 /* allocate section space to put the data */
8451 if (sec
->sh_type
!= SHT_NOBITS
&&
8452 data_offset
> sec
->data_allocated
)
8453 section_realloc(sec
, data_offset
);
8455 addr
= 0; /* avoid warning */
8459 if (scope
== VT_CONST
) {
8464 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
8466 /* update symbol definition */
8468 put_extern_sym(sym
, sec
, addr
, size
);
8471 /* put a common area */
8472 put_extern_sym(sym
, NULL
, align
, size
);
8473 /* XXX: find a nicer way */
8474 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
8475 esym
->st_shndx
= SHN_COMMON
;
8480 /* push global reference */
8481 sym
= get_sym_ref(type
, sec
, addr
, size
);
8483 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
8487 /* handles bounds now because the symbol must be defined
8488 before for the relocation */
8489 if (do_bounds_check
) {
8490 unsigned long *bounds_ptr
;
8492 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
8493 /* then add global bound info */
8494 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
8495 bounds_ptr
[0] = 0; /* relocated */
8496 bounds_ptr
[1] = size
;
8500 decl_initializer(type
, sec
, addr
, 1, 0);
8501 /* restore parse state if needed */
8503 tok_str_free(init_str
.str
);
8504 restore_parse_state(&saved_parse_state
);
8510 void put_func_debug(Sym
*sym
)
8515 /* XXX: we put here a dummy type */
8516 snprintf(buf
, sizeof(buf
), "%s:%c1",
8517 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
8518 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
8519 cur_text_section
, sym
->c
);
8524 /* not finished : try to put some local vars in registers */
8525 //#define CONFIG_REG_VARS
8527 #ifdef CONFIG_REG_VARS
8528 void add_var_ref(int t
)
8530 printf("%s:%d: &%s\n",
8531 file
->filename
, file
->line_num
,
8532 get_tok_str(t
, NULL
));
8535 /* first pass on a function with heuristic to extract variable usage
8536 and pointer references to local variables for register allocation */
8537 void analyse_function(void)
8544 /* any symbol coming after '&' is considered as being a
8545 variable whose reference is taken. It is highly unaccurate
8546 but it is difficult to do better without a complete parse */
8549 /* if '& number', then no need to examine next tokens */
8550 if (tok
== TOK_CINT
||
8552 tok
== TOK_CLLONG
||
8553 tok
== TOK_CULLONG
) {
8555 } else if (tok
>= TOK_UIDENT
) {
8556 /* if '& ident [' or '& ident ->', then ident address
8560 if (tok
!= '[' && tok
!= TOK_ARROW
)
8564 while (tok
!= '}' && tok
!= ';' &&
8565 !((tok
== ',' || tok
== ')') && level
== 0)) {
8566 if (tok
>= TOK_UIDENT
) {
8568 } else if (tok
== '(') {
8570 } else if (tok
== ')') {
8583 /* parse an old style function declaration list */
8584 /* XXX: check multiple parameter */
8585 static void func_decl_list(Sym
*func_sym
)
8592 /* parse each declaration */
8593 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
8594 if (!parse_btype(&btype
, &ad
))
8595 expect("declaration list");
8596 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8597 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8599 /* we accept no variable after */
8603 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8604 /* find parameter in function parameter list */
8607 if ((s
->v
& ~SYM_FIELD
) == v
)
8611 error("declaration for parameter '%s' but no such parameter",
8612 get_tok_str(v
, NULL
));
8614 /* check that no storage specifier except 'register' was given */
8615 if (type
.t
& VT_STORAGE
)
8616 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
8617 convert_parameter_type(&type
);
8618 /* we can add the type (NOTE: it could be local to the function) */
8620 /* accept other parameters */
8631 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
8632 static void decl(int l
)
8640 if (!parse_btype(&btype
, &ad
)) {
8641 /* skip redundant ';' */
8642 /* XXX: find more elegant solution */
8647 /* special test for old K&R protos without explicit int
8648 type. Only accepted when defining global data */
8649 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
8653 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8654 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8656 /* we accept no variable after */
8660 while (1) { /* iterate thru each declaration */
8662 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8666 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
8667 printf("type = '%s'\n", buf
);
8670 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8671 /* if old style function prototype, we accept a
8674 if (sym
->c
== FUNC_OLD
)
8675 func_decl_list(sym
);
8679 #ifdef CONFIG_REG_VARS
8680 TokenString func_str
;
8681 ParseState saved_parse_state
;
8686 error("cannot use local functions");
8687 if (!(type
.t
& VT_FUNC
))
8688 expect("function definition");
8690 /* reject abstract declarators in function definition */
8692 while ((sym
= sym
->next
) != NULL
)
8693 if (!(sym
->v
& ~SYM_FIELD
))
8694 expect("identifier");
8696 /* XXX: cannot do better now: convert extern line to static inline */
8697 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
8698 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
8700 #ifdef CONFIG_REG_VARS
8701 /* parse all function code and record it */
8703 tok_str_new(&func_str
);
8709 error("unexpected end of file");
8710 tok_str_add_tok(&func_str
);
8715 } else if (t
== '}') {
8717 if (block_level
== 0)
8721 tok_str_add(&func_str
, -1);
8722 tok_str_add(&func_str
, 0);
8724 save_parse_state(&saved_parse_state
);
8726 macro_ptr
= func_str
.str
;
8731 /* compute text section */
8732 cur_text_section
= ad
.section
;
8733 if (!cur_text_section
)
8734 cur_text_section
= text_section
;
8735 ind
= cur_text_section
->data_offset
;
8736 funcname
= get_tok_str(v
, NULL
);
8739 /* if symbol is already defined, then put complete type */
8742 /* put function symbol */
8743 sym
= global_identifier_push(v
, type
.t
, 0);
8744 sym
->type
.ref
= type
.ref
;
8746 /* NOTE: we patch the symbol size later */
8747 put_extern_sym(sym
, cur_text_section
, ind
, 0);
8749 sym
->r
= VT_SYM
| VT_CONST
;
8750 /* put debug symbol */
8752 put_func_debug(sym
);
8753 /* push a dummy symbol to enable local sym storage */
8754 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
8755 gfunc_prolog(&type
);
8757 #ifdef CONFIG_REG_VARS
8758 macro_ptr
= func_str
.str
;
8761 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
8764 cur_text_section
->data_offset
= ind
;
8765 label_pop(&global_label_stack
, NULL
);
8766 sym_pop(&local_stack
, NULL
); /* reset local stack */
8767 /* end of function */
8768 /* patch symbol size */
8769 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_size
=
8772 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
8774 funcname
= ""; /* for safety */
8775 func_vt
.t
= VT_VOID
; /* for safety */
8776 ind
= 0; /* for safety */
8778 #ifdef CONFIG_REG_VARS
8779 tok_str_free(func_str
.str
);
8780 restore_parse_state(&saved_parse_state
);
8784 if (btype
.t
& VT_TYPEDEF
) {
8785 /* save typedefed type */
8786 /* XXX: test storage specifiers ? */
8787 sym
= sym_push(v
, &type
, 0, 0);
8788 sym
->type
.t
|= VT_TYPEDEF
;
8789 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8790 /* external function definition */
8791 external_sym(v
, &type
, 0);
8793 /* not lvalue if array */
8795 if (!(type
.t
& VT_ARRAY
))
8796 r
|= lvalue_type(type
.t
);
8797 has_init
= (tok
== '=');
8798 if ((btype
.t
& VT_EXTERN
) ||
8799 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
8800 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
8801 /* external variable */
8802 /* NOTE: as GCC, uninitialized global static
8803 arrays of null size are considered as
8805 external_sym(v
, &type
, r
);
8807 if (type
.t
& VT_STATIC
)
8813 decl_initializer_alloc(&type
, &ad
, r
,
8827 /* better than nothing, but needs extension to handle '-E' option
8829 static void preprocess_init(TCCState
*s1
)
8831 s1
->include_stack_ptr
= s1
->include_stack
;
8832 /* XXX: move that before to avoid having to initialize
8833 file->ifdef_stack_ptr ? */
8834 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
8835 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
8837 /* XXX: not ANSI compliant: bound checking says error */
8841 /* compile the C file opened in 'file'. Return non zero if errors. */
8842 static int tcc_compile(TCCState
*s1
)
8846 volatile int section_sym
;
8849 printf("%s: **** new file\n", file
->filename
);
8851 preprocess_init(s1
);
8854 anon_sym
= SYM_FIRST_ANOM
;
8856 /* file info: full path + filename */
8857 section_sym
= 0; /* avoid warning */
8859 section_sym
= put_elf_sym(symtab_section
, 0, 0,
8860 ELF32_ST_INFO(STB_LOCAL
, STT_SECTION
), 0,
8861 text_section
->sh_num
, NULL
);
8862 getcwd(buf
, sizeof(buf
));
8863 pstrcat(buf
, sizeof(buf
), "/");
8864 put_stabs_r(buf
, N_SO
, 0, 0,
8865 text_section
->data_offset
, text_section
, section_sym
);
8866 put_stabs_r(file
->filename
, N_SO
, 0, 0,
8867 text_section
->data_offset
, text_section
, section_sym
);
8869 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
8870 symbols can be safely used */
8871 put_elf_sym(symtab_section
, 0, 0,
8872 ELF32_ST_INFO(STB_LOCAL
, STT_FILE
), 0,
8873 SHN_ABS
, file
->filename
);
8875 /* define some often used types */
8876 int_type
.t
= VT_INT
;
8878 char_pointer_type
.t
= VT_BYTE
;
8879 mk_pointer(&char_pointer_type
);
8881 func_old_type
.t
= VT_FUNC
;
8882 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
8885 /* define 'void *alloca(unsigned int)' builtin function */
8890 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
8891 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
8894 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
8898 define_start
= define_stack
;
8900 if (setjmp(s1
->error_jmp_buf
) == 0) {
8902 s1
->error_set_jmp_enabled
= 1;
8904 ch
= file
->buf_ptr
[0];
8905 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
8906 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
8910 expect("declaration");
8912 /* end of translation unit info */
8914 put_stabs_r(NULL
, N_SO
, 0, 0,
8915 text_section
->data_offset
, text_section
, section_sym
);
8918 s1
->error_set_jmp_enabled
= 0;
8920 /* reset define stack, but leave -Dsymbols (may be incorrect if
8921 they are undefined) */
8922 free_defines(define_start
);
8924 sym_pop(&global_stack
, NULL
);
8926 return s1
->nb_errors
!= 0 ? -1 : 0;
8930 int tcc_compile_string(TCCState
*s
, const char *str
)
8932 BufferedFile bf1
, *bf
= &bf1
;
8936 /* init file structure */
8938 /* XXX: avoid copying */
8940 buf
= tcc_malloc(len
+ 1);
8943 memcpy(buf
, str
, len
);
8946 bf
->buf_end
= buf
+ len
;
8947 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
8951 ret
= tcc_compile(s
);
8955 /* currently, no need to close */
8960 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
8961 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
8963 BufferedFile bf1
, *bf
= &bf1
;
8965 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
8966 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
8970 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
8972 /* init file structure */
8974 bf
->buf_ptr
= bf
->buffer
;
8975 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
8976 *bf
->buf_end
= CH_EOB
;
8977 bf
->filename
[0] = '\0';
8981 s1
->include_stack_ptr
= s1
->include_stack
;
8983 /* parse with define parser */
8984 ch
= file
->buf_ptr
[0];
8990 /* undefine a preprocessor symbol */
8991 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
8995 ts
= tok_alloc(sym
, strlen(sym
));
8996 s
= define_find(ts
->tok
);
8997 /* undefine symbol by putting an invalid name */
9002 #ifdef CONFIG_TCC_ASM
9004 #ifdef TCC_TARGET_I386
9005 #include "i386-asm.c"
9010 static void asm_instr(void)
9012 error("inline asm() not supported");
9018 #ifdef TCC_TARGET_COFF
9019 #include "tcccoff.c"
9022 /* print the position in the source file of PC value 'pc' by reading
9023 the stabs debug information */
9024 static void rt_printline(unsigned long wanted_pc
)
9026 Stab_Sym
*sym
, *sym_end
;
9027 char func_name
[128], last_func_name
[128];
9028 unsigned long func_addr
, last_pc
, pc
;
9029 const char *incl_files
[INCLUDE_STACK_SIZE
];
9030 int incl_index
, len
, last_line_num
, i
;
9031 const char *str
, *p
;
9033 fprintf(stderr
, "0x%08lx:", wanted_pc
);
9035 func_name
[0] = '\0';
9038 last_func_name
[0] = '\0';
9039 last_pc
= 0xffffffff;
9041 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
9042 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
9043 while (sym
< sym_end
) {
9044 switch(sym
->n_type
) {
9045 /* function start or end */
9047 if (sym
->n_strx
== 0) {
9048 /* we test if between last line and end of function */
9049 pc
= sym
->n_value
+ func_addr
;
9050 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9052 func_name
[0] = '\0';
9055 str
= stabstr_section
->data
+ sym
->n_strx
;
9056 p
= strchr(str
, ':');
9058 pstrcpy(func_name
, sizeof(func_name
), str
);
9061 if (len
> sizeof(func_name
) - 1)
9062 len
= sizeof(func_name
) - 1;
9063 memcpy(func_name
, str
, len
);
9064 func_name
[len
] = '\0';
9066 func_addr
= sym
->n_value
;
9069 /* line number info */
9071 pc
= sym
->n_value
+ func_addr
;
9072 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9075 last_line_num
= sym
->n_desc
;
9077 strcpy(last_func_name
, func_name
);
9081 str
= stabstr_section
->data
+ sym
->n_strx
;
9083 if (incl_index
< INCLUDE_STACK_SIZE
) {
9084 incl_files
[incl_index
++] = str
;
9092 if (sym
->n_strx
== 0) {
9093 incl_index
= 0; /* end of translation unit */
9095 str
= stabstr_section
->data
+ sym
->n_strx
;
9096 /* do not add path */
9098 if (len
> 0 && str
[len
- 1] != '/')
9106 /* second pass: we try symtab symbols (no line number info) */
9109 Elf32_Sym
*sym
, *sym_end
;
9112 sym_end
= (Elf32_Sym
*)(symtab_section
->data
+ symtab_section
->data_offset
);
9113 for(sym
= (Elf32_Sym
*)symtab_section
->data
+ 1;
9116 type
= ELF32_ST_TYPE(sym
->st_info
);
9117 if (type
== STT_FUNC
) {
9118 if (wanted_pc
>= sym
->st_value
&&
9119 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
9120 pstrcpy(last_func_name
, sizeof(last_func_name
),
9121 strtab_section
->data
+ sym
->st_name
);
9127 /* did not find any info: */
9128 fprintf(stderr
, " ???\n");
9131 if (last_func_name
[0] != '\0') {
9132 fprintf(stderr
, " %s()", last_func_name
);
9134 if (incl_index
> 0) {
9135 fprintf(stderr
, " (%s:%d",
9136 incl_files
[incl_index
- 1], last_line_num
);
9137 for(i
= incl_index
- 2; i
>= 0; i
--)
9138 fprintf(stderr
, ", included from %s", incl_files
[i
]);
9139 fprintf(stderr
, ")");
9141 fprintf(stderr
, "\n");
9148 /* fix for glibc 2.1 */
9154 /* return the PC at frame level 'level'. Return non zero if not found */
9155 static int rt_get_caller_pc(unsigned long *paddr
,
9156 ucontext_t
*uc
, int level
)
9162 #if defined(__FreeBSD__)
9163 *paddr
= uc
->uc_mcontext
.mc_eip
;
9164 #elif defined(__dietlibc__)
9165 *paddr
= uc
->uc_mcontext
.eip
;
9167 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
9171 #if defined(__FreeBSD__)
9172 fp
= uc
->uc_mcontext
.mc_ebp
;
9173 #elif defined(__dietlibc__)
9174 fp
= uc
->uc_mcontext
.ebp
;
9176 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
9178 for(i
=1;i
<level
;i
++) {
9179 /* XXX: check address validity with program info */
9180 if (fp
<= 0x1000 || fp
>= 0xc0000000)
9182 fp
= ((unsigned long *)fp
)[0];
9184 *paddr
= ((unsigned long *)fp
)[1];
9190 #warning add arch specific rt_get_caller_pc()
9192 static int rt_get_caller_pc(unsigned long *paddr
,
9193 ucontext_t
*uc
, int level
)
9199 /* emit a run time error at position 'pc' */
9200 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
9207 fprintf(stderr
, "Runtime error: ");
9208 vfprintf(stderr
, fmt
, ap
);
9209 fprintf(stderr
, "\n");
9210 for(i
=0;i
<num_callers
;i
++) {
9211 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
9214 fprintf(stderr
, "at ");
9216 fprintf(stderr
, "by ");
9223 /* signal handler for fatal errors */
9224 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
9226 ucontext_t
*uc
= puc
;
9230 switch(siginf
->si_code
) {
9233 rt_error(uc
, "division by zero");
9236 rt_error(uc
, "floating point exception");
9242 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
9243 rt_error(uc
, *rt_bound_error_msg
);
9245 rt_error(uc
, "dereferencing invalid pointer");
9248 rt_error(uc
, "illegal instruction");
9251 rt_error(uc
, "abort() called");
9254 rt_error(uc
, "caught signal %d", signum
);
9261 /* do all relocations (needed before using tcc_get_symbol()) */
9262 int tcc_relocate(TCCState
*s1
)
9269 tcc_add_runtime(s1
);
9271 build_got_entries(s1
);
9273 relocate_common_syms();
9275 /* compute relocation address : section are relocated in place. We
9276 also alloc the bss space */
9277 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9278 s
= s1
->sections
[i
];
9279 if (s
->sh_flags
& SHF_ALLOC
) {
9280 if (s
->sh_type
== SHT_NOBITS
)
9281 s
->data
= tcc_mallocz(s
->data_offset
);
9282 s
->sh_addr
= (unsigned long)s
->data
;
9286 relocate_syms(s1
, 1);
9288 if (s1
->nb_errors
!= 0)
9291 /* relocate each section */
9292 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9293 s
= s1
->sections
[i
];
9295 relocate_section(s1
, s
);
9300 /* launch the compiled program with the given arguments */
9301 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
9303 int (*prog_main
)(int, char **);
9305 if (tcc_relocate(s1
) < 0)
9308 prog_main
= tcc_get_symbol_err(s1
, "main");
9312 error("debug mode currently not available for Windows");
9314 struct sigaction sigact
;
9315 /* install TCC signal handlers to print debug info on fatal
9317 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
9318 sigact
.sa_sigaction
= sig_error
;
9319 sigemptyset(&sigact
.sa_mask
);
9320 sigaction(SIGFPE
, &sigact
, NULL
);
9321 sigaction(SIGILL
, &sigact
, NULL
);
9322 sigaction(SIGSEGV
, &sigact
, NULL
);
9323 sigaction(SIGBUS
, &sigact
, NULL
);
9324 sigaction(SIGABRT
, &sigact
, NULL
);
9328 #ifdef CONFIG_TCC_BCHECK
9329 if (do_bounds_check
) {
9330 void (*bound_init
)(void);
9332 /* set error function */
9333 rt_bound_error_msg
= (void *)tcc_get_symbol_err(s1
,
9334 "__bound_error_msg");
9336 /* XXX: use .init section so that it also work in binary ? */
9337 bound_init
= (void *)tcc_get_symbol_err(s1
, "__bound_init");
9341 return (*prog_main
)(argc
, argv
);
9344 TCCState
*tcc_new(void)
9351 s
= tcc_mallocz(sizeof(TCCState
));
9355 s
->output_type
= TCC_OUTPUT_MEMORY
;
9357 /* init isid table */
9359 isidnum_table
[i
] = isid(i
) || isnum(i
);
9361 /* add all tokens */
9363 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
9365 tok_ident
= TOK_IDENT
;
9374 ts
= tok_alloc(p
, r
- p
- 1);
9378 /* we add dummy defines for some special macros to speed up tests
9379 and to have working defined() */
9380 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
9381 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
9382 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
9383 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
9385 /* standard defines */
9386 tcc_define_symbol(s
, "__STDC__", NULL
);
9387 #if defined(TCC_TARGET_I386)
9388 tcc_define_symbol(s
, "__i386__", NULL
);
9390 #if defined(TCC_TARGET_ARM)
9391 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
9392 tcc_define_symbol(s
, "__arm_elf__", NULL
);
9393 tcc_define_symbol(s
, "__arm_elf", NULL
);
9394 tcc_define_symbol(s
, "arm_elf", NULL
);
9395 tcc_define_symbol(s
, "__arm__", NULL
);
9396 tcc_define_symbol(s
, "__arm", NULL
);
9397 tcc_define_symbol(s
, "arm", NULL
);
9398 tcc_define_symbol(s
, "__APCS_32__", NULL
);
9401 tcc_define_symbol(s
, "__linux__", NULL
);
9402 tcc_define_symbol(s
, "linux", NULL
);
9404 /* tiny C specific defines */
9405 tcc_define_symbol(s
, "__TINYC__", NULL
);
9407 /* tiny C & gcc defines */
9408 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
9409 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
9410 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
9412 /* default library paths */
9413 tcc_add_library_path(s
, "/usr/local/lib");
9414 tcc_add_library_path(s
, "/usr/lib");
9415 tcc_add_library_path(s
, "/lib");
9417 /* no section zero */
9418 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
9420 /* create standard sections */
9421 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
9422 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
9423 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
9425 /* symbols are always generated for linking stage */
9426 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
9428 ".hashtab", SHF_PRIVATE
);
9429 strtab_section
= symtab_section
->link
;
9431 /* private symbol table for dynamic symbols */
9432 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
9434 ".dynhashtab", SHF_PRIVATE
);
9435 s
->alacarte_link
= 1;
9437 #ifdef CHAR_IS_UNSIGNED
9438 s
->char_is_unsigned
= 1;
9443 void tcc_delete(TCCState
*s1
)
9447 /* free -D defines */
9451 n
= tok_ident
- TOK_IDENT
;
9452 for(i
= 0; i
< n
; i
++)
9453 tcc_free(table_ident
[i
]);
9454 tcc_free(table_ident
);
9456 /* free all sections */
9458 free_section(symtab_section
->hash
);
9460 free_section(s1
->dynsymtab_section
->hash
);
9461 free_section(s1
->dynsymtab_section
->link
);
9462 free_section(s1
->dynsymtab_section
);
9464 for(i
= 1; i
< s1
->nb_sections
; i
++)
9465 free_section(s1
->sections
[i
]);
9466 tcc_free(s1
->sections
);
9468 /* free loaded dlls array */
9469 for(i
= 0; i
< s1
->nb_loaded_dlls
; i
++)
9470 tcc_free(s1
->loaded_dlls
[i
]);
9471 tcc_free(s1
->loaded_dlls
);
9474 for(i
= 0; i
< s1
->nb_library_paths
; i
++)
9475 tcc_free(s1
->library_paths
[i
]);
9476 tcc_free(s1
->library_paths
);
9478 /* cached includes */
9479 for(i
= 0; i
< s1
->nb_cached_includes
; i
++)
9480 tcc_free(s1
->cached_includes
[i
]);
9481 tcc_free(s1
->cached_includes
);
9483 for(i
= 0; i
< s1
->nb_include_paths
; i
++)
9484 tcc_free(s1
->include_paths
[i
]);
9485 tcc_free(s1
->include_paths
);
9487 for(i
= 0; i
< s1
->nb_sysinclude_paths
; i
++)
9488 tcc_free(s1
->sysinclude_paths
[i
]);
9489 tcc_free(s1
->sysinclude_paths
);
9494 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
9498 pathname1
= tcc_strdup(pathname
);
9499 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
9503 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
9507 pathname1
= tcc_strdup(pathname
);
9508 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
9512 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
9514 const char *ext
, *filename1
;
9517 BufferedFile
*saved_file
;
9519 /* find source file type with extension */
9520 filename1
= strrchr(filename
, '/');
9524 filename1
= filename
;
9525 ext
= strrchr(filename1
, '.');
9531 file
= tcc_open(s1
, filename
);
9533 if (flags
& AFF_PRINT_ERROR
) {
9534 error_noabort("file '%s' not found", filename
);
9540 if (!ext
|| !strcmp(ext
, "c")) {
9541 /* C file assumed */
9542 ret
= tcc_compile(s1
);
9544 #ifdef CONFIG_TCC_ASM
9545 if (!strcmp(ext
, "S")) {
9546 /* preprocessed assembler */
9547 ret
= tcc_assemble(s1
, 1);
9548 } else if (!strcmp(ext
, "s")) {
9549 /* non preprocessed assembler */
9550 ret
= tcc_assemble(s1
, 0);
9555 /* assume executable format: auto guess file type */
9556 ret
= read(fd
, &ehdr
, sizeof(ehdr
));
9557 lseek(fd
, 0, SEEK_SET
);
9559 error_noabort("could not read header");
9561 } else if (ret
!= sizeof(ehdr
)) {
9562 goto try_load_script
;
9565 if (ehdr
.e_ident
[0] == ELFMAG0
&&
9566 ehdr
.e_ident
[1] == ELFMAG1
&&
9567 ehdr
.e_ident
[2] == ELFMAG2
&&
9568 ehdr
.e_ident
[3] == ELFMAG3
) {
9569 file
->line_num
= 0; /* do not display line number if error */
9570 if (ehdr
.e_type
== ET_REL
) {
9571 ret
= tcc_load_object_file(s1
, fd
, 0);
9572 } else if (ehdr
.e_type
== ET_DYN
) {
9573 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
9575 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
9581 ret
= tcc_load_dll(s1
, fd
, filename
,
9582 (flags
& AFF_REFERENCED_DLL
) != 0);
9585 error_noabort("unrecognized ELF file");
9588 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
9589 file
->line_num
= 0; /* do not display line number if error */
9590 ret
= tcc_load_archive(s1
, fd
);
9592 #ifdef TCC_TARGET_COFF
9593 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
9594 ret
= tcc_load_coff(s1
, fd
);
9598 /* as GNU ld, consider it is an ld script if not recognized */
9600 ret
= tcc_load_ldscript(s1
);
9602 error_noabort("unrecognized file type");
9617 int tcc_add_file(TCCState
*s
, const char *filename
)
9619 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
9622 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
9626 pathname1
= tcc_strdup(pathname
);
9627 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
9631 /* find and load a dll. Return non zero if not found */
9632 /* XXX: add '-rpath' option support ? */
9633 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
9638 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9639 snprintf(buf
, sizeof(buf
), "%s/%s",
9640 s
->library_paths
[i
], filename
);
9641 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
9647 /* the library name is the same as the argument of the '-l' option */
9648 int tcc_add_library(TCCState
*s
, const char *libraryname
)
9653 /* first we look for the dynamic library if not static linking */
9654 if (!s
->static_link
) {
9655 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
9656 if (tcc_add_dll(s
, buf
, 0) == 0)
9660 /* then we look for the static library */
9661 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9662 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
9663 s
->library_paths
[i
], libraryname
);
9664 if (tcc_add_file_internal(s
, buf
, 0) == 0)
9670 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
9672 add_elf_sym(symtab_section
, val
, 0,
9673 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
),
9678 int tcc_set_output_type(TCCState
*s
, int output_type
)
9682 s
->output_type
= output_type
;
9685 /* default include paths */
9686 /* XXX: reverse order needed if -isystem support */
9687 tcc_add_sysinclude_path(s
, "/usr/local/include");
9688 tcc_add_sysinclude_path(s
, "/usr/include");
9689 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
9690 tcc_add_sysinclude_path(s
, buf
);
9693 /* if bound checking, then add corresponding sections */
9694 #ifdef CONFIG_TCC_BCHECK
9695 if (do_bounds_check
) {
9697 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
9698 /* create bounds sections */
9699 bounds_section
= new_section(s
, ".bounds",
9700 SHT_PROGBITS
, SHF_ALLOC
);
9701 lbounds_section
= new_section(s
, ".lbounds",
9702 SHT_PROGBITS
, SHF_ALLOC
);
9706 if (s
->char_is_unsigned
) {
9707 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
9710 /* add debug sections */
9713 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
9714 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
9715 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
9716 put_elf_str(stabstr_section
, "");
9717 stab_section
->link
= stabstr_section
;
9718 /* put first entry */
9719 put_stabs("", 0, 0, 0, 0);
9722 /* add libc crt1/crti objects */
9723 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
9725 if (output_type
!= TCC_OUTPUT_DLL
)
9726 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
9727 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
9732 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
9733 #define FD_INVERT 0x0002 /* invert value before storing */
9735 typedef struct FlagDef
{
9741 static const FlagDef warning_defs
[] = {
9742 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
9743 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
9744 { offsetof(TCCState
, warn_error
), 0, "error" },
9745 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
9746 "implicit-function-declaration" },
9749 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
9750 const char *name
, int value
)
9757 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
9761 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
9762 if (!strcmp(r
, p
->name
))
9767 if (p
->flags
& FD_INVERT
)
9769 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
9774 /* set/reset a warning */
9775 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
9780 if (!strcmp(warning_name
, "all")) {
9781 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
9782 if (p
->flags
& WD_ALL
)
9783 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
9787 return set_flag(s
, warning_defs
, countof(warning_defs
),
9788 warning_name
, value
);
9792 static const FlagDef flag_defs
[] = {
9793 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
9794 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
9797 /* set/reset a flag */
9798 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
9800 return set_flag(s
, flag_defs
, countof(flag_defs
),
9804 #if !defined(LIBTCC)
9806 /* extract the basename of a file */
9807 static const char *tcc_basename(const char *name
)
9810 p
= strrchr(name
, '/');
9813 p
= strrchr(name
, '\\');
9822 static int64_t getclock_us(void)
9827 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
9830 gettimeofday(&tv
, NULL
);
9831 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
9837 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2003 Fabrice Bellard\n"
9838 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
9839 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]\n"
9840 " [infile1 infile2...] [-run infile args...]\n"
9842 "General options:\n"
9843 " -v display current version\n"
9844 " -c compile only - generate an object file\n"
9845 " -o outfile set output filename\n"
9846 " -Bdir set tcc internal library path\n"
9847 " -bench output compilation statistics\n"
9848 " -run run compiled source\n"
9849 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
9850 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
9851 " -w disable all warnings\n"
9852 "Preprocessor options:\n"
9853 " -Idir add include path 'dir'\n"
9854 " -Dsym[=val] define 'sym' with value 'val'\n"
9855 " -Usym undefine 'sym'\n"
9857 " -Ldir add library path 'dir'\n"
9858 " -llib link with dynamic or static library 'lib'\n"
9859 " -shared generate a shared library\n"
9860 " -static static linking\n"
9861 " -rdynamic export all global symbols to dynamic linker\n"
9862 " -r relocatable output\n"
9863 "Debugger options:\n"
9864 " -g generate runtime debug info\n"
9865 #ifdef CONFIG_TCC_BCHECK
9866 " -b compile with built-in memory and bounds checker (implies -g)\n"
9868 " -bt N show N callers in stack traces\n"
9872 #define TCC_OPTION_HAS_ARG 0x0001
9873 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
9875 typedef struct TCCOption
{
9902 TCC_OPTION_nostdinc
,
9903 TCC_OPTION_nostdlib
,
9904 TCC_OPTION_print_search_dirs
,
9905 TCC_OPTION_rdynamic
,
9911 static const TCCOption tcc_options
[] = {
9912 { "h", TCC_OPTION_HELP
, 0 },
9913 { "?", TCC_OPTION_HELP
, 0 },
9914 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
9915 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
9916 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
9917 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
9918 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
9919 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9920 { "bench", TCC_OPTION_bench
, 0 },
9921 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
9922 #ifdef CONFIG_TCC_BCHECK
9923 { "b", TCC_OPTION_b
, 0 },
9925 { "g", TCC_OPTION_g
, 0 },
9926 { "c", TCC_OPTION_c
, 0 },
9927 { "static", TCC_OPTION_static
, 0 },
9928 { "shared", TCC_OPTION_shared
, 0 },
9929 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
9930 { "run", TCC_OPTION_run
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9931 { "rdynamic", TCC_OPTION_rdynamic
, 0 },
9932 { "r", TCC_OPTION_r
, 0 },
9933 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9934 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9935 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
9936 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9937 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
9938 { "nostdlib", TCC_OPTION_nostdlib
, 0 },
9939 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
9940 { "v", TCC_OPTION_v
, 0 },
9941 { "w", TCC_OPTION_w
, 0 },
9945 /* convert 'str' into an array of space separated strings */
9946 static int expand_args(char ***pargv
, const char *str
)
9955 while (is_space(*str
))
9960 while (*str
!= '\0' && !is_space(*str
))
9963 arg
= tcc_malloc(len
+ 1);
9964 memcpy(arg
, s1
, len
);
9966 dynarray_add((void ***)&argv
, &argc
, arg
);
9972 static char **files
;
9973 static int nb_files
, nb_libraries
;
9974 static int multiple_files
;
9975 static int print_search_dirs
;
9976 static int output_type
;
9977 static int reloc_output
;
9978 static const char *outfile
;
9980 int parse_args(TCCState
*s
, int argc
, char **argv
)
9983 const TCCOption
*popt
;
9984 const char *optarg
, *p1
, *r1
;
9989 if (optind
>= argc
) {
9990 if (nb_files
== 0 && !print_search_dirs
)
9997 /* add a new file */
9998 dynarray_add((void ***)&files
, &nb_files
, r
);
9999 if (!multiple_files
) {
10001 /* argv[0] will be this file */
10005 /* find option in table (match only the first chars */
10006 popt
= tcc_options
;
10010 error("invalid option -- '%s'", r
);
10023 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
10024 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
10027 if (optind
>= argc
)
10028 error("argument to '%s' is missing", r
);
10029 optarg
= argv
[optind
++];
10037 switch(popt
->index
) {
10038 case TCC_OPTION_HELP
:
10043 if (tcc_add_include_path(s
, optarg
) < 0)
10044 error("too many include paths");
10049 sym
= (char *)optarg
;
10050 value
= strchr(sym
, '=');
10055 tcc_define_symbol(s
, sym
, value
);
10059 tcc_undefine_symbol(s
, optarg
);
10062 tcc_add_library_path(s
, optarg
);
10065 /* set tcc utilities path (mainly for tcc development) */
10066 tcc_lib_path
= optarg
;
10069 dynarray_add((void ***)&files
, &nb_files
, r
);
10072 case TCC_OPTION_bench
:
10075 case TCC_OPTION_bt
:
10076 num_callers
= atoi(optarg
);
10078 #ifdef CONFIG_TCC_BCHECK
10080 do_bounds_check
= 1;
10088 multiple_files
= 1;
10089 output_type
= TCC_OUTPUT_OBJ
;
10091 case TCC_OPTION_static
:
10092 s
->static_link
= 1;
10094 case TCC_OPTION_shared
:
10095 output_type
= TCC_OUTPUT_DLL
;
10098 multiple_files
= 1;
10102 /* generate a .o merging several output files */
10104 output_type
= TCC_OUTPUT_OBJ
;
10106 case TCC_OPTION_nostdinc
:
10109 case TCC_OPTION_nostdlib
:
10112 case TCC_OPTION_print_search_dirs
:
10113 print_search_dirs
= 1;
10115 case TCC_OPTION_run
:
10119 argc1
= expand_args(&argv1
, optarg
);
10121 parse_args(s
, argc1
, argv1
);
10123 multiple_files
= 0;
10124 output_type
= TCC_OUTPUT_MEMORY
;
10128 printf("tcc version %s\n", TCC_VERSION
);
10131 if (tcc_set_flag(s
, optarg
, 1) < 0 && s
->warn_unsupported
)
10132 goto unsupported_option
;
10135 if (tcc_set_warning(s
, optarg
, 1) < 0 &&
10136 s
->warn_unsupported
)
10137 goto unsupported_option
;
10142 case TCC_OPTION_rdynamic
:
10146 if (s
->warn_unsupported
) {
10147 unsupported_option
:
10148 warning("unsupported option '%s'", r
);
10157 int main(int argc
, char **argv
)
10161 int nb_objfiles
, ret
, optind
;
10162 char objfilename
[1024];
10163 int64_t start_time
= 0;
10166 output_type
= TCC_OUTPUT_EXE
;
10168 multiple_files
= 1;
10173 print_search_dirs
= 0;
10175 optind
= parse_args(s
, argc
- 1, argv
+ 1) + 1;
10177 if (print_search_dirs
) {
10178 /* enough for Linux kernel */
10179 printf("install: %s/\n", tcc_lib_path
);
10183 nb_objfiles
= nb_files
- nb_libraries
;
10185 /* if outfile provided without other options, we output an
10187 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
10188 output_type
= TCC_OUTPUT_EXE
;
10190 /* check -c consistency : only single file handled. XXX: checks file type */
10191 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
10192 /* accepts only a single input file */
10193 if (nb_objfiles
!= 1)
10194 error("cannot specify multiple files with -c");
10195 if (nb_libraries
!= 0)
10196 error("cannot specify libraries with -c");
10199 /* compute default outfile name */
10200 if (output_type
!= TCC_OUTPUT_MEMORY
&& !outfile
) {
10201 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
10204 pstrcpy(objfilename
, sizeof(objfilename
) - 1,
10205 tcc_basename(files
[0]));
10206 /* add .o extension */
10207 ext
= strrchr(objfilename
, '.');
10209 goto default_outfile
;
10210 strcpy(ext
+ 1, "o");
10213 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
10215 outfile
= objfilename
;
10219 start_time
= getclock_us();
10222 tcc_set_output_type(s
, output_type
);
10224 /* compile or add each files or library */
10225 for(i
= 0;i
< nb_files
; i
++) {
10226 const char *filename
;
10228 filename
= files
[i
];
10229 if (filename
[0] == '-') {
10230 if (tcc_add_library(s
, filename
+ 2) < 0)
10231 error("cannot find %s", filename
);
10233 if (tcc_add_file(s
, filename
) < 0) {
10240 /* free all files */
10245 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
10246 if (total_time
< 0.001)
10247 total_time
= 0.001;
10248 if (total_bytes
< 1)
10250 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
10251 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
10252 total_time
, (int)(total_lines
/ total_time
),
10253 total_bytes
/ total_time
/ 1000000.0);
10256 if (s
->output_type
!= TCC_OUTPUT_MEMORY
) {
10257 tcc_output_file(s
, outfile
);
10260 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
10263 /* XXX: cannot do it with bound checking because of the malloc hooks */
10264 if (!do_bounds_check
)
10269 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);