2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001, 2002 Fabrice Bellard
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program 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
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
35 #include <sys/timeb.h>
39 #include <sys/ucontext.h>
43 #ifndef CONFIG_TCC_STATIC
51 /* preprocessor debug */
53 /* include file debug */
61 /* target selection */
62 //#define TCC_TARGET_I386 /* i386 code generator */
64 /* default target is I386 */
65 #if !defined(TCC_TARGET_I386)
66 #define TCC_TARGET_I386
69 #if !defined(WIN32) && !defined(TCC_UCLIBC)
70 #define CONFIG_TCC_BCHECK /* enable bound checking code */
73 /* define it to include assembler support */
74 #define CONFIG_TCC_ASM
76 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
77 executables or dlls */
78 #define CONFIG_TCC_CRT_PREFIX "/usr/lib"
80 #define INCLUDE_STACK_SIZE 32
81 #define IFDEF_STACK_SIZE 64
82 #define VSTACK_SIZE 64
83 #define STRING_MAX_SIZE 1024
85 #define TOK_HASH_SIZE 2048 /* must be a power of two */
86 #define TOK_ALLOC_INCR 512 /* must be a power of two */
87 #define TOK_STR_ALLOC_INCR_BITS 6
88 #define TOK_STR_ALLOC_INCR (1 << TOK_STR_ALLOC_INCR_BITS)
89 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
91 /* token symbol management */
92 typedef struct TokenSym
{
93 struct TokenSym
*hash_next
;
94 struct Sym
*sym_define
; /* direct pointer to define */
95 struct Sym
*sym_label
; /* direct pointer to label */
96 struct Sym
*sym_struct
; /* direct pointer to structure */
97 struct Sym
*sym_identifier
; /* direct pointer to identifier */
98 int tok
; /* token number */
103 typedef struct CString
{
104 int size
; /* size in bytes */
105 void *data
; /* either 'char *' or 'int *' */
107 void *data_allocated
; /* if non NULL, data has been malloced */
110 /* type definition */
111 typedef struct CType
{
117 typedef union CValue
{
123 unsigned int ul
; /* address (should be unsigned long on 64 bit cpu) */
125 unsigned long long ull
;
126 struct CString
*cstr
;
132 typedef struct SValue
{
133 CType type
; /* type */
134 unsigned short r
; /* register + flags */
135 unsigned short r2
; /* second register, used for 'long long'
136 type. If not used, set to VT_CONST */
137 CValue c
; /* constant, if VT_CONST */
138 struct Sym
*sym
; /* symbol, if (VT_SYM | VT_CONST) */
141 /* symbol management */
143 int v
; /* symbol token */
144 int r
; /* associated register */
145 int c
; /* associated number */
146 CType type
; /* associated type */
147 struct Sym
*next
; /* next related symbol */
148 struct Sym
*prev
; /* prev symbol in stack */
149 struct Sym
*prev_tok
; /* previous symbol for this token */
152 /* section definition */
153 /* XXX: use directly ELF structure for parameters ? */
154 /* special flag to indicate that the section should not be linked to
156 #define SHF_PRIVATE 0x80000000
158 typedef struct Section
{
159 unsigned long data_offset
; /* current data offset */
160 unsigned char *data
; /* section data */
161 unsigned long data_allocated
; /* used for realloc() handling */
162 int sh_name
; /* elf section name (only used during output) */
163 int sh_num
; /* elf section number */
164 int sh_type
; /* elf section type */
165 int sh_flags
; /* elf section flags */
166 int sh_info
; /* elf section info */
167 int sh_addralign
; /* elf section alignment */
168 int sh_entsize
; /* elf entry size */
169 unsigned long sh_size
; /* section size (only used during output) */
170 unsigned long sh_addr
; /* address at which the section is relocated */
171 unsigned long sh_offset
; /* address at which the section is relocated */
172 int nb_hashed_syms
; /* used to resize the hash table */
173 struct Section
*link
; /* link to another section */
174 struct Section
*reloc
; /* corresponding section for relocation, if any */
175 struct Section
*hash
; /* hash table for symbols */
176 struct Section
*next
;
177 char name
[64]; /* section name */
180 typedef struct DLLReference
{
185 /* GNUC attribute definition */
186 typedef struct AttributeDef
{
189 unsigned char func_call
; /* FUNC_CDECL or FUNC_STDCALL */
192 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
193 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
194 #define SYM_FIRST_ANOM (1 << (31 - VT_STRUCT_SHIFT)) /* first anonymous sym */
196 /* stored in 'Sym.c' field */
197 #define FUNC_NEW 1 /* ansi function prototype */
198 #define FUNC_OLD 2 /* old function prototype */
199 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
201 /* stored in 'Sym.r' field */
202 #define FUNC_CDECL 0 /* standard c call */
203 #define FUNC_STDCALL 1 /* pascal c call */
205 /* field 'Sym.t' for macros */
206 #define MACRO_OBJ 0 /* object like macro */
207 #define MACRO_FUNC 1 /* function like macro */
209 /* field 'Sym.r' for C labels */
210 #define LABEL_DEFINED 0 /* label is defined */
211 #define LABEL_FORWARD 1 /* label is forward defined */
212 #define LABEL_DECLARED 2 /* label is declared but never used */
214 /* type_decl() types */
215 #define TYPE_ABSTRACT 1 /* type without variable */
216 #define TYPE_DIRECT 2 /* type with variable */
218 #define IO_BUF_SIZE 8192
220 typedef struct BufferedFile
{
224 int line_num
; /* current line number - here to simplify code */
225 int ifndef_macro
; /* #ifndef macro / #endif search */
226 int ifndef_macro_saved
; /* saved ifndef_macro */
227 int *ifdef_stack_ptr
; /* ifdef_stack value at the start of the file */
228 char inc_type
; /* type of include */
229 char inc_filename
[512]; /* filename specified by the user */
230 char filename
[1024]; /* current filename - here to simplify code */
231 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
234 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
235 #define CH_EOF (-1) /* end of file */
237 /* parsing state (used to save parser state to reparse part of the
238 source several times) */
239 typedef struct ParseState
{
246 /* used to record tokens */
247 typedef struct TokenString
{
254 /* include file cache, used to find files faster and also to eliminate
255 inclusion if the include file is protected by #ifndef ... #endif */
256 typedef struct CachedInclude
{
258 char type
; /* '"' or '>' to give include type */
259 char filename
[1]; /* path specified in #include */
263 static struct BufferedFile
*file
;
266 static CString tokcstr
; /* current parsed string, if any */
267 /* additional informations about token */
268 static int tok_flags
;
269 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
270 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
271 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
273 static int *macro_ptr
, *macro_ptr_allocated
;
274 static int *unget_saved_macro_ptr
;
275 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
276 static int unget_buffer_enabled
;
277 static int parse_flags
;
278 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
279 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
280 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
281 token. line feed is also
284 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
285 static Section
*cur_text_section
; /* current section where function code is
287 /* bound check related sections */
288 static Section
*bounds_section
; /* contains global data bound description */
289 static Section
*lbounds_section
; /* contains local data bound description */
290 /* symbol sections */
291 static Section
*symtab_section
, *strtab_section
;
294 static Section
*stab_section
, *stabstr_section
;
296 /* loc : local variable index
297 ind : output code index
299 anon_sym: anonymous symbol index
301 static int rsym
, anon_sym
, ind
, loc
;
302 /* expression generation modifiers */
303 static int const_wanted
; /* true if constant wanted */
304 static int nocode_wanted
; /* true if no code generation wanted for an expression */
305 static int global_expr
; /* true if compound literals must be allocated
306 globally (used during initializers parsing */
307 static CType func_vt
; /* current function return type (used by return
310 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
311 static int tok_ident
;
312 static TokenSym
**table_ident
;
313 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
314 static char token_buf
[STRING_MAX_SIZE
+ 1];
315 static char *funcname
;
316 static Sym
*global_stack
, *local_stack
;
317 static Sym
*define_stack
;
318 static Sym
*global_label_stack
, *local_label_stack
;
320 static SValue vstack
[VSTACK_SIZE
], *vtop
;
321 /* some predefined types */
322 static CType char_pointer_type
, func_old_type
, int_type
;
323 /* true if isid(c) || isnum(c) */
324 static unsigned char isidnum_table
[256];
326 /* compile with debug symbol (and use them if error during execution) */
327 static int do_debug
= 0;
329 /* compile with built-in memory and bounds checker */
330 static int do_bounds_check
= 0;
332 /* display benchmark infos */
334 static int do_bench
= 0;
336 static int total_lines
;
337 static int total_bytes
;
339 /* use GNU C extensions */
340 static int gnu_ext
= 1;
342 /* use Tiny C extensions */
343 static int tcc_ext
= 1;
345 /* max number of callers shown if error */
346 static int num_callers
= 6;
347 static const char **rt_bound_error_msg
;
349 /* XXX: get rid of this ASAP */
350 static struct TCCState
*tcc_state
;
352 /* give the path of the tcc libraries */
353 static const char *tcc_lib_path
= CONFIG_TCC_LIBDIR
"/tcc";
358 BufferedFile
**include_stack_ptr
;
359 int *ifdef_stack_ptr
;
361 /* include file handling */
362 char **include_paths
;
363 int nb_include_paths
;
364 char **sysinclude_paths
;
365 int nb_sysinclude_paths
;
366 CachedInclude
**cached_includes
;
367 int nb_cached_includes
;
369 char **library_paths
;
370 int nb_library_paths
;
372 /* array of all loaded dlls (including those referenced by loaded
374 DLLReference
**loaded_dlls
;
379 int nb_sections
; /* number of sections, including first dummy section */
384 unsigned long *got_offsets
;
386 /* give the correspondance from symtab indexes to dynsym indexes */
387 int *symtab_to_dynsym
;
389 /* temporary dynamic symbol sections (for dll loading) */
390 Section
*dynsymtab_section
;
391 /* exported dynamic symbol section */
394 /* if true, no standard headers are added */
397 /* if true, static linking is performed */
402 void (*error_func
)(void *opaque
, const char *msg
);
403 int error_set_jmp_enabled
;
404 jmp_buf error_jmp_buf
;
407 /* tiny assembler state */
410 /* see include_stack_ptr */
411 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
413 /* see ifdef_stack_ptr */
414 int ifdef_stack
[IFDEF_STACK_SIZE
];
417 /* The current value can be: */
418 #define VT_VALMASK 0x00ff
419 #define VT_CONST 0x00f0 /* constant in vc
420 (must be first non register value) */
421 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
422 #define VT_LOCAL 0x00f2 /* offset on stack */
423 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
424 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
425 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
426 #define VT_LVAL 0x0100 /* var is an lvalue */
427 #define VT_SYM 0x0200 /* a symbol value is added */
428 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
429 char/short stored in integer registers) */
430 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
431 dereferencing value */
432 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
433 bounding function call point is in vc */
434 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
435 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
436 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
437 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
440 #define VT_STRUCT_SHIFT 12 /* structure/enum name shift (20 bits left) */
442 #define VT_INT 0 /* integer type */
443 #define VT_BYTE 1 /* signed byte type */
444 #define VT_SHORT 2 /* short type */
445 #define VT_VOID 3 /* void type */
446 #define VT_PTR 4 /* pointer */
447 #define VT_ENUM 5 /* enum definition */
448 #define VT_FUNC 6 /* function type */
449 #define VT_STRUCT 7 /* struct/union definition */
450 #define VT_FLOAT 8 /* IEEE float */
451 #define VT_DOUBLE 9 /* IEEE double */
452 #define VT_LDOUBLE 10 /* IEEE long double */
453 #define VT_BOOL 11 /* ISOC99 boolean type */
454 #define VT_LLONG 12 /* 64 bit integer */
455 #define VT_LONG 13 /* long integer (NEVER USED as type, only
457 #define VT_BTYPE 0x000f /* mask for basic type */
458 #define VT_UNSIGNED 0x0010 /* unsigned type */
459 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
460 #define VT_BITFIELD 0x0040 /* bitfield modifier */
463 #define VT_EXTERN 0x00000080 /* extern definition */
464 #define VT_STATIC 0x00000100 /* static variable */
465 #define VT_TYPEDEF 0x00000200 /* typedef definition */
466 #define VT_INLINE 0x00000400 /* inline definition */
468 /* type mask (except storage) */
469 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
470 #define VT_TYPE (~(VT_STORAGE))
474 /* warning: the following compare tokens depend on i386 asm code */
486 #define TOK_LAND 0xa0
490 #define TOK_MID 0xa3 /* inc/dec, to void constant */
492 #define TOK_UDIV 0xb0 /* unsigned division */
493 #define TOK_UMOD 0xb1 /* unsigned modulo */
494 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
495 #define TOK_CINT 0xb3 /* number in tokc */
496 #define TOK_CCHAR 0xb4 /* char constant in tokc */
497 #define TOK_STR 0xb5 /* pointer to string in tokc */
498 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
499 #define TOK_LCHAR 0xb7
500 #define TOK_LSTR 0xb8
501 #define TOK_CFLOAT 0xb9 /* float constant */
502 #define TOK_LINENUM 0xba /* line number info */
503 #define TOK_CDOUBLE 0xc0 /* double constant */
504 #define TOK_CLDOUBLE 0xc1 /* long double constant */
505 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
506 #define TOK_ADDC1 0xc3 /* add with carry generation */
507 #define TOK_ADDC2 0xc4 /* add with carry use */
508 #define TOK_SUBC1 0xc5 /* add with carry generation */
509 #define TOK_SUBC2 0xc6 /* add with carry use */
510 #define TOK_CUINT 0xc8 /* unsigned int constant */
511 #define TOK_CLLONG 0xc9 /* long long constant */
512 #define TOK_CULLONG 0xca /* unsigned long long constant */
513 #define TOK_ARROW 0xcb
514 #define TOK_DOTS 0xcc /* three dots */
515 #define TOK_SHR 0xcd /* unsigned shift right */
516 #define TOK_PPNUM 0xce /* preprocessor number */
518 #define TOK_SHL 0x01 /* shift left */
519 #define TOK_SAR 0x02 /* signed shift right */
521 /* assignement operators : normal operator or 0x80 */
522 #define TOK_A_MOD 0xa5
523 #define TOK_A_AND 0xa6
524 #define TOK_A_MUL 0xaa
525 #define TOK_A_ADD 0xab
526 #define TOK_A_SUB 0xad
527 #define TOK_A_DIV 0xaf
528 #define TOK_A_XOR 0xde
529 #define TOK_A_OR 0xfc
530 #define TOK_A_SHL 0x81
531 #define TOK_A_SAR 0x82
533 /* WARNING: the content of this string encodes token numbers */
534 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";
536 #define TOK_EOF (-1) /* end of file */
537 #define TOK_LINEFEED 10 /* line feed */
539 /* all identificators and strings have token above that */
540 #define TOK_IDENT 256
542 /* only used for i386 asm opcodes definitions */
543 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
546 DEF(TOK_ASM_ ## x ## b, #x "b") \
547 DEF(TOK_ASM_ ## x ## w, #x "w") \
548 DEF(TOK_ASM_ ## x ## l, #x "l") \
549 DEF(TOK_ASM_ ## x, #x)
552 DEF(TOK_ASM_ ## x ## w, #x "w") \
553 DEF(TOK_ASM_ ## x ## l, #x "l") \
554 DEF(TOK_ASM_ ## x, #x)
557 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
558 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
559 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
560 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
563 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
564 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
567 #define DEF_ASMTEST(x) \
599 #define TOK_ASM_int TOK_INT
602 TOK_LAST
= TOK_IDENT
- 1,
603 #define DEF(id, str) id,
608 static const char tcc_keywords
[] =
609 #define DEF(id, str) str "\0"
614 #define TOK_UIDENT TOK_DEFINE
617 #define snprintf _snprintf
618 #define vsnprintf _vsnprintf
621 #if defined(WIN32) || defined(TCC_UCLIBC) || defined(__FreeBSD__)
622 /* currently incorrect */
623 long double strtold(const char *nptr
, char **endptr
)
625 return (long double)strtod(nptr
, endptr
);
627 float strtof(const char *nptr
, char **endptr
)
629 return (float)strtod(nptr
, endptr
);
632 /* XXX: need to define this to use them in non ISOC99 context */
633 extern float strtof (const char *__nptr
, char **__endptr
);
634 extern long double strtold (const char *__nptr
, char **__endptr
);
637 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
638 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
640 static void next(void);
641 static void next_nomacro(void);
642 static void parse_expr_type(CType
*type
);
643 static void expr_type(CType
*type
);
644 static void unary_type(CType
*type
);
645 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
646 int case_reg
, int is_expr
);
647 static int expr_const(void);
648 static void expr_eq(void);
649 static void gexpr(void);
650 static void decl(int l
);
651 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
652 int first
, int size_only
);
653 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
654 int has_init
, int v
, int scope
);
656 void gv2(int rc1
, int rc2
);
657 void move_reg(int r
, int s
);
658 void save_regs(int n
);
659 void save_reg(int r
);
665 static void macro_subst(TokenString
*tok_str
,
666 Sym
**nested_list
, const int *macro_str
);
667 int save_reg_forced(int r
);
669 void force_charshort_cast(int t
);
670 static void gen_cast(CType
*type
);
672 static Sym
*sym_find(int v
);
673 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
676 static int type_size(CType
*type
, int *a
);
677 static inline CType
*pointed_type(CType
*type
);
678 static int pointed_size(CType
*type
);
679 static int lvalue_type(int t
);
680 static int is_compatible_types(CType
*type1
, CType
*type2
);
681 static int parse_btype(CType
*type
, AttributeDef
*ad
);
682 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
684 void error(const char *fmt
, ...);
686 void vset(CType
*type
, int r
, int v
);
687 void type_to_str(char *buf
, int buf_size
,
688 CType
*type
, const char *varstr
);
689 char *get_tok_str(int v
, CValue
*cv
);
690 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
691 unsigned long offset
, unsigned long size
);
692 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
694 /* section generation */
695 static void section_realloc(Section
*sec
, unsigned long new_size
);
696 static void *section_ptr_add(Section
*sec
, unsigned long size
);
697 static void put_extern_sym(Sym
*sym
, Section
*section
,
698 unsigned long value
, unsigned long size
);
699 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
700 static int put_elf_str(Section
*s
, const char *sym
);
701 static int put_elf_sym(Section
*s
,
702 unsigned long value
, unsigned long size
,
703 int info
, int other
, int shndx
, const char *name
);
704 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
705 int info
, int sh_num
, const char *name
);
706 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
707 int type
, int symbol
);
708 static void put_stabs(const char *str
, int type
, int other
, int desc
,
709 unsigned long value
);
710 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
711 unsigned long value
, Section
*sec
, int sym_index
);
712 static void put_stabn(int type
, int other
, int desc
, int value
);
713 static void put_stabd(int type
, int other
, int desc
);
714 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
716 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
717 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
718 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
722 #ifdef CONFIG_TCC_ASM
724 typedef struct ExprValue
{
729 #define MAX_ASM_OPERANDS 30
731 typedef struct ASMOperand
{
732 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
734 char asm_str
[16]; /* computed asm string for operand */
735 SValue
*vt
; /* C value of the expression */
736 int ref_index
; /* if >= 0, gives reference to a output constraint */
737 int priority
; /* priority, used to assign registers */
738 int reg
; /* if >= 0, register number used for this operand */
741 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
742 static int asm_int_expr(TCCState
*s1
);
743 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
744 const char *name
, const char **pp
);
746 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
750 static void asm_instr(void);
752 /* true if float/double/long double type */
753 static inline int is_float(int t
)
757 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
760 #ifdef TCC_TARGET_I386
761 #include "i386-gen.c"
764 #ifdef CONFIG_TCC_STATIC
766 #define RTLD_LAZY 0x001
767 #define RTLD_NOW 0x002
768 #define RTLD_GLOBAL 0x100
769 #define RTLD_DEFAULT NULL
771 /* dummy function for profiling */
772 void *dlopen(const char *filename
, int flag
)
777 const char *dlerror(void)
782 typedef struct TCCSyms
{
787 #define TCCSYM(a) { #a, &a, },
789 /* add the symbol you want here if no dynamic linking is done */
790 static TCCSyms tcc_syms
[] = {
798 void *dlsym(void *handle
, const char *symbol
)
802 while (p
->str
!= NULL
) {
803 if (!strcmp(p
->str
, symbol
))
812 /********************************************************/
814 /* we use our own 'finite' function to avoid potential problems with
815 non standard math libs */
816 /* XXX: endianness dependent */
817 int ieee_finite(double d
)
820 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
823 /* copy a string and truncate it. */
824 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
831 q_end
= buf
+ buf_size
- 1;
843 /* strcat and truncate. */
844 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
849 pstrcpy(buf
+ len
, buf_size
- len
, s
);
853 /* memory management */
859 static inline void tcc_free(void *ptr
)
862 mem_cur_size
-= malloc_usable_size(ptr
);
867 static void *tcc_malloc(unsigned long size
)
872 error("memory full");
874 mem_cur_size
+= malloc_usable_size(ptr
);
875 if (mem_cur_size
> mem_max_size
)
876 mem_max_size
= mem_cur_size
;
881 static void *tcc_mallocz(unsigned long size
)
884 ptr
= tcc_malloc(size
);
885 memset(ptr
, 0, size
);
889 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
893 mem_cur_size
-= malloc_usable_size(ptr
);
895 ptr1
= realloc(ptr
, size
);
897 /* NOTE: count not correct if alloc error, but not critical */
898 mem_cur_size
+= malloc_usable_size(ptr1
);
899 if (mem_cur_size
> mem_max_size
)
900 mem_max_size
= mem_cur_size
;
905 static char *tcc_strdup(const char *str
)
908 ptr
= tcc_malloc(strlen(str
) + 1);
913 #define free(p) use_tcc_free(p)
914 #define malloc(s) use_tcc_malloc(s)
915 #define realloc(p, s) use_tcc_realloc(p, s)
917 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
924 /* every power of two we double array size */
925 if ((nb
& (nb
- 1)) == 0) {
930 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
932 error("memory full");
939 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
943 sec
= tcc_mallocz(sizeof(Section
));
944 pstrcpy(sec
->name
, sizeof(sec
->name
), name
);
945 sec
->sh_type
= sh_type
;
946 sec
->sh_flags
= sh_flags
;
953 sec
->sh_addralign
= 4;
956 sec
->sh_addralign
= 1;
959 sec
->sh_addralign
= 32; /* default conservative alignment */
963 /* only add section if not private */
964 if (!(sh_flags
& SHF_PRIVATE
)) {
965 sec
->sh_num
= s1
->nb_sections
;
966 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
971 static void free_section(Section
*s
)
977 /* realloc section and set its content to zero */
978 static void section_realloc(Section
*sec
, unsigned long new_size
)
983 size
= sec
->data_allocated
;
986 while (size
< new_size
)
988 data
= tcc_realloc(sec
->data
, size
);
990 error("memory full");
991 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
993 sec
->data_allocated
= size
;
996 /* reserve at least 'size' bytes in section 'sec' from
998 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1000 unsigned long offset
, offset1
;
1002 offset
= sec
->data_offset
;
1003 offset1
= offset
+ size
;
1004 if (offset1
> sec
->data_allocated
)
1005 section_realloc(sec
, offset1
);
1006 sec
->data_offset
= offset1
;
1007 return sec
->data
+ offset
;
1010 /* return a reference to a section, and create it if it does not
1012 Section
*find_section(TCCState
*s1
, const char *name
)
1016 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1017 sec
= s1
->sections
[i
];
1018 if (!strcmp(name
, sec
->name
))
1021 /* sections are created as PROGBITS */
1022 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1025 /* update sym->c so that it points to an external symbol in section
1026 'section' with value 'value' */
1027 static void put_extern_sym(Sym
*sym
, Section
*section
,
1028 unsigned long value
, unsigned long size
)
1030 int sym_type
, sym_bind
, sh_num
, info
;
1035 sh_num
= section
->sh_num
;
1039 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
)
1040 sym_type
= STT_FUNC
;
1042 sym_type
= STT_OBJECT
;
1043 if (sym
->type
.t
& VT_STATIC
)
1044 sym_bind
= STB_LOCAL
;
1046 sym_bind
= STB_GLOBAL
;
1048 name
= get_tok_str(sym
->v
, NULL
);
1049 #ifdef CONFIG_TCC_BCHECK
1050 if (do_bounds_check
) {
1053 /* XXX: avoid doing that for statics ? */
1054 /* if bound checking is activated, we change some function
1055 names by adding the "__bound" prefix */
1058 /* XXX: we rely only on malloc hooks */
1070 strcpy(buf
, "__bound_");
1077 info
= ELF32_ST_INFO(sym_bind
, sym_type
);
1078 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, sh_num
, name
);
1080 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
1081 esym
->st_value
= value
;
1082 esym
->st_size
= size
;
1083 esym
->st_shndx
= sh_num
;
1087 /* add a new relocation entry to symbol 'sym' in section 's' */
1088 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1091 put_extern_sym(sym
, NULL
, 0, 0);
1092 /* now we can add ELF relocation info */
1093 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1096 static inline int isid(int c
)
1098 return (c
>= 'a' && c
<= 'z') ||
1099 (c
>= 'A' && c
<= 'Z') ||
1103 static inline int isnum(int c
)
1105 return c
>= '0' && c
<= '9';
1108 static inline int isoct(int c
)
1110 return c
>= '0' && c
<= '7';
1113 static inline int toup(int c
)
1115 if (c
>= 'a' && c
<= 'z')
1116 return c
- 'a' + 'A';
1121 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1125 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1128 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1132 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1136 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1143 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1144 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1145 (*f
)->filename
, (*f
)->line_num
);
1146 if (file
->line_num
> 0) {
1147 strcat_printf(buf
, sizeof(buf
),
1148 "%s:%d: ", file
->filename
, file
->line_num
);
1150 strcat_printf(buf
, sizeof(buf
),
1151 "%s: ", file
->filename
);
1154 strcat_printf(buf
, sizeof(buf
),
1158 strcat_printf(buf
, sizeof(buf
), "warning: ");
1159 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1161 if (!s1
->error_func
) {
1162 /* default case: stderr */
1163 fprintf(stderr
, "%s\n", buf
);
1165 s1
->error_func(s1
->error_opaque
, buf
);
1172 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1173 void (*error_func
)(void *opaque
, const char *msg
))
1175 s
->error_opaque
= error_opaque
;
1176 s
->error_func
= error_func
;
1180 /* error without aborting current compilation */
1181 void error_noabort(const char *fmt
, ...)
1183 TCCState
*s1
= tcc_state
;
1187 error1(s1
, 0, fmt
, ap
);
1191 void error(const char *fmt
, ...)
1193 TCCState
*s1
= tcc_state
;
1197 error1(s1
, 0, fmt
, ap
);
1199 /* better than nothing: in some cases, we accept to handle errors */
1200 if (s1
->error_set_jmp_enabled
) {
1201 longjmp(s1
->error_jmp_buf
, 1);
1203 /* XXX: eliminate this someday */
1208 void expect(const char *msg
)
1210 error("%s expected", msg
);
1213 void warning(const char *fmt
, ...)
1215 TCCState
*s1
= tcc_state
;
1219 error1(s1
, 1, fmt
, ap
);
1226 error("'%c' expected", c
);
1230 static void test_lvalue(void)
1232 if (!(vtop
->r
& VT_LVAL
))
1236 /* allocate a new token */
1237 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1239 TokenSym
*ts
, **ptable
;
1242 if (tok_ident
>= SYM_FIRST_ANOM
)
1243 error("memory full");
1245 /* expand token table if needed */
1246 i
= tok_ident
- TOK_IDENT
;
1247 if ((i
% TOK_ALLOC_INCR
) == 0) {
1248 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1250 error("memory full");
1251 table_ident
= ptable
;
1254 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1255 table_ident
[i
] = ts
;
1256 ts
->tok
= tok_ident
++;
1257 ts
->sym_define
= NULL
;
1258 ts
->sym_label
= NULL
;
1259 ts
->sym_struct
= NULL
;
1260 ts
->sym_identifier
= NULL
;
1262 ts
->hash_next
= NULL
;
1263 memcpy(ts
->str
, str
, len
);
1264 ts
->str
[len
] = '\0';
1269 #define TOK_HASH_INIT 1
1270 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1272 /* find a token and add it if not found */
1273 static TokenSym
*tok_alloc(const char *str
, int len
)
1275 TokenSym
*ts
, **pts
;
1281 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1282 h
&= (TOK_HASH_SIZE
- 1);
1284 pts
= &hash_ident
[h
];
1289 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1291 pts
= &(ts
->hash_next
);
1293 return tok_alloc_new(pts
, str
, len
);
1296 /* CString handling */
1298 static void cstr_realloc(CString
*cstr
, int new_size
)
1303 size
= cstr
->size_allocated
;
1305 size
= 8; /* no need to allocate a too small first string */
1306 while (size
< new_size
)
1308 data
= tcc_realloc(cstr
->data_allocated
, size
);
1310 error("memory full");
1311 cstr
->data_allocated
= data
;
1312 cstr
->size_allocated
= size
;
1317 static void cstr_ccat(CString
*cstr
, int ch
)
1320 size
= cstr
->size
+ 1;
1321 if (size
> cstr
->size_allocated
)
1322 cstr_realloc(cstr
, size
);
1323 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1327 static void cstr_cat(CString
*cstr
, const char *str
)
1339 /* add a wide char */
1340 static void cstr_wccat(CString
*cstr
, int ch
)
1343 size
= cstr
->size
+ sizeof(int);
1344 if (size
> cstr
->size_allocated
)
1345 cstr_realloc(cstr
, size
);
1346 *(int *)(((unsigned char *)cstr
->data
) + size
- sizeof(int)) = ch
;
1350 static void cstr_new(CString
*cstr
)
1352 memset(cstr
, 0, sizeof(CString
));
1355 /* free string and reset it to NULL */
1356 static void cstr_free(CString
*cstr
)
1358 tcc_free(cstr
->data_allocated
);
1362 #define cstr_reset(cstr) cstr_free(cstr)
1364 static CString
*cstr_dup(CString
*cstr1
)
1369 cstr
= tcc_malloc(sizeof(CString
));
1372 cstr
->size_allocated
= size
;
1373 cstr
->data_allocated
= tcc_malloc(size
);
1374 cstr
->data
= cstr
->data_allocated
;
1375 memcpy(cstr
->data_allocated
, cstr1
->data_allocated
, size
);
1379 /* XXX: unicode ? */
1380 static void add_char(CString
*cstr
, int c
)
1382 if (c
== '\'' || c
== '\"' || c
== '\\') {
1383 /* XXX: could be more precise if char or string */
1384 cstr_ccat(cstr
, '\\');
1386 if (c
>= 32 && c
<= 126) {
1389 cstr_ccat(cstr
, '\\');
1391 cstr_ccat(cstr
, 'n');
1393 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1394 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1395 cstr_ccat(cstr
, '0' + (c
& 7));
1400 /* XXX: buffer overflow */
1401 /* XXX: float tokens */
1402 char *get_tok_str(int v
, CValue
*cv
)
1404 static char buf
[STRING_MAX_SIZE
+ 1];
1405 static CString cstr_buf
;
1411 /* NOTE: to go faster, we give a fixed buffer for small strings */
1412 cstr_reset(&cstr_buf
);
1413 cstr_buf
.data
= buf
;
1414 cstr_buf
.size_allocated
= sizeof(buf
);
1420 /* XXX: not quite exact, but only useful for testing */
1421 sprintf(p
, "%u", cv
->ui
);
1425 /* XXX: not quite exact, but only useful for testing */
1426 sprintf(p
, "%Lu", cv
->ull
);
1430 cstr_ccat(&cstr_buf
, '\'');
1431 add_char(&cstr_buf
, cv
->i
);
1432 cstr_ccat(&cstr_buf
, '\'');
1433 cstr_ccat(&cstr_buf
, '\0');
1437 len
= cstr
->size
- 1;
1439 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1440 cstr_ccat(&cstr_buf
, '\0');
1445 cstr_ccat(&cstr_buf
, '\"');
1447 len
= cstr
->size
- 1;
1449 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1451 len
= (cstr
->size
/ sizeof(int)) - 1;
1453 add_char(&cstr_buf
, ((int *)cstr
->data
)[i
]);
1455 cstr_ccat(&cstr_buf
, '\"');
1456 cstr_ccat(&cstr_buf
, '\0');
1465 return strcpy(p
, "<<=");
1467 return strcpy(p
, ">>=");
1469 if (v
< TOK_IDENT
) {
1470 /* search in two bytes table */
1484 } else if (v
< tok_ident
) {
1485 return table_ident
[v
- TOK_IDENT
]->str
;
1486 } else if (v
>= SYM_FIRST_ANOM
) {
1487 /* special name for anonymous symbol */
1488 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1490 /* should never happen */
1495 return cstr_buf
.data
;
1498 /* push, without hashing */
1499 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, int c
)
1502 s
= tcc_malloc(sizeof(Sym
));
1513 /* find a symbol and return its associated structure. 's' is the top
1514 of the symbol stack */
1515 static Sym
*sym_find2(Sym
*s
, int v
)
1525 /* structure lookup */
1526 static inline Sym
*struct_find(int v
)
1529 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1531 return table_ident
[v
]->sym_struct
;
1534 /* find an identifier */
1535 static inline Sym
*sym_find(int v
)
1538 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1540 return table_ident
[v
]->sym_identifier
;
1543 /* push a given symbol on the symbol stack */
1544 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1553 s
= sym_push2(ps
, v
, type
->t
, c
);
1554 s
->type
.ref
= type
->ref
;
1556 /* don't record fields or anonymous symbols */
1558 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1559 /* record symbol in token array */
1560 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1562 ps
= &ts
->sym_struct
;
1564 ps
= &ts
->sym_identifier
;
1571 /* push a global identifier */
1572 static Sym
*global_identifier_push(int v
, int t
, int c
)
1575 s
= sym_push2(&global_stack
, v
, t
, c
);
1576 /* don't record anonymous symbol */
1577 if (v
< SYM_FIRST_ANOM
) {
1578 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1579 /* modify the top most local identifier, so that
1580 sym_identifier will point to 's' when popped */
1582 ps
= &(*ps
)->prev_tok
;
1589 /* pop symbols until top reaches 'b' */
1590 static void sym_pop(Sym
**ptop
, Sym
*b
)
1600 /* remove symbol in token array */
1602 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1603 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1605 ps
= &ts
->sym_struct
;
1607 ps
= &ts
->sym_identifier
;
1618 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1623 fd
= open(filename
, O_RDONLY
);
1626 bf
= tcc_malloc(sizeof(BufferedFile
));
1632 bf
->buf_ptr
= bf
->buffer
;
1633 bf
->buf_end
= bf
->buffer
;
1634 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1635 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1637 bf
->ifndef_macro
= 0;
1638 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1639 // printf("opening '%s'\n", filename);
1643 void tcc_close(BufferedFile
*bf
)
1645 total_lines
+= bf
->line_num
;
1650 /* fill input buffer and peek next char */
1651 static int tcc_peekc_slow(BufferedFile
*bf
)
1654 /* only tries to read if really end of buffer */
1655 if (bf
->buf_ptr
>= bf
->buf_end
) {
1657 #if defined(PARSE_DEBUG)
1662 len
= read(bf
->fd
, bf
->buffer
, len
);
1669 bf
->buf_ptr
= bf
->buffer
;
1670 bf
->buf_end
= bf
->buffer
+ len
;
1671 *bf
->buf_end
= CH_EOB
;
1673 if (bf
->buf_ptr
< bf
->buf_end
) {
1674 return bf
->buf_ptr
[0];
1676 bf
->buf_ptr
= bf
->buf_end
;
1681 /* return the current character, handling end of block if necessary
1683 static int handle_eob(void)
1685 return tcc_peekc_slow(file
);
1688 /* read next char from current input file and handle end of input buffer */
1689 static inline void inp(void)
1691 ch
= *(++(file
->buf_ptr
));
1692 /* end of buffer/file handling */
1697 /* handle '\[\r]\n' */
1698 static void handle_stray(void)
1700 while (ch
== '\\') {
1705 } else if (ch
== '\r') {
1713 error("stray '\\' in program");
1718 /* skip the stray and handle the \\n case. Output an error if
1719 incorrect char after the stray */
1720 static int handle_stray1(uint8_t *p
)
1724 if (p
>= file
->buf_end
) {
1741 /* handle just the EOB case, but not stray */
1742 #define PEEKC_EOB(c, p)\
1753 /* handle the complicated stray case */
1754 #define PEEKC(c, p)\
1759 c = handle_stray1(p);\
1764 /* input with '\[\r]\n' handling. Note that this function cannot
1765 handle other characters after '\', so you cannot call it inside
1766 strings or comments */
1767 static void minp(void)
1775 /* single line C++ comments */
1776 static uint8_t *parse_line_comment(uint8_t *p
)
1783 if (c
== '\n' || c
== CH_EOF
) {
1785 } else if (c
== '\\') {
1790 } else if (c
== '\r') {
1805 static uint8_t *parse_comment(uint8_t *p
)
1811 /* fast skip loop */
1814 if (c
== '\n' || c
== '*' || c
== '\\')
1818 if (c
== '\n' || c
== '*' || c
== '\\')
1822 /* now we can handle all the cases */
1826 } else if (c
== '*') {
1832 } else if (c
== '/') {
1833 goto end_of_comment
;
1834 } else if (c
== '\\') {
1839 /* skip '\[\r]\n', otherwise just skip the stray */
1845 } else if (c
== '\r') {
1862 /* stray, eob or eof */
1867 error("unexpected end of file in comment");
1868 } else if (c
== '\\') {
1880 /* space exlcuding newline */
1881 static inline int is_space(int ch
)
1883 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
1886 static inline void skip_spaces(void)
1888 while (is_space(ch
))
1892 /* parse a string without interpreting escapes */
1893 static uint8_t *parse_pp_string(uint8_t *p
,
1894 int sep
, CString
*str
)
1902 } else if (c
== '\\') {
1907 unterminated_string
:
1908 /* XXX: indicate line number of start of string */
1909 error("missing terminating %c character", sep
);
1910 } else if (c
== '\\') {
1911 /* escape : just skip \[\r]\n */
1916 } else if (c
== '\r') {
1919 expect("'\n' after '\r'");
1922 } else if (c
== CH_EOF
) {
1923 goto unterminated_string
;
1926 cstr_ccat(str
, '\\');
1932 } else if (c
== '\n') {
1935 } else if (c
== '\r') {
1938 cstr_ccat(str
, '\r');
1954 /* skip block of text until #else, #elif or #endif. skip also pairs of
1956 void preprocess_skip(void)
1958 int a
, start_of_line
, c
;
1985 } else if (c
== '\\') {
1986 /* XXX: incorrect: should not give an error */
1987 ch
= file
->buf_ptr
[0];
1995 p
= parse_pp_string(p
, c
, NULL
);
2004 p
= parse_comment(p
);
2005 } else if (ch
== '/') {
2006 p
= parse_line_comment(p
);
2012 if (start_of_line
) {
2017 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2019 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2021 else if (tok
== TOK_ENDIF
)
2035 /* ParseState handling */
2037 /* XXX: currently, no include file info is stored. Thus, we cannot display
2038 accurate messages if the function or data definition spans multiple
2041 /* save current parse state in 's' */
2042 void save_parse_state(ParseState
*s
)
2044 s
->line_num
= file
->line_num
;
2045 s
->macro_ptr
= macro_ptr
;
2050 /* restore parse state from 's' */
2051 void restore_parse_state(ParseState
*s
)
2053 file
->line_num
= s
->line_num
;
2054 macro_ptr
= s
->macro_ptr
;
2059 /* return the number of additional 'ints' necessary to store the
2061 static inline int tok_ext_size(int t
)
2080 return LDOUBLE_SIZE
/ 4;
2086 /* token string handling */
2088 static inline void tok_str_new(TokenString
*s
)
2092 s
->allocated_len
= 0;
2093 s
->last_line_num
= -1;
2096 static void tok_str_free(int *str
)
2105 /* NOTE: we test zero separately so that GCC can generate a
2106 table for the following switch */
2121 /* XXX: use a macro to be portable on 64 bit ? */
2122 cstr
= (CString
*)p
[1];
2133 p
+= 1 + (LDOUBLE_SIZE
/ 4);
2143 static int *tok_str_realloc(TokenString
*s
)
2147 len
= s
->allocated_len
+ TOK_STR_ALLOC_INCR
;
2148 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2150 error("memory full");
2151 s
->allocated_len
= len
;
2156 static void tok_str_add(TokenString
*s
, int t
)
2162 if (len
>= s
->allocated_len
)
2163 str
= tok_str_realloc(s
);
2168 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2175 /* allocate space for worst case */
2176 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2177 str
= tok_str_realloc(s
);
2186 str
[len
++] = cv
->tab
[0];
2191 str
[len
++] = (int)cstr_dup(cv
->cstr
);
2196 str
[len
++] = cv
->tab
[0];
2197 str
[len
++] = cv
->tab
[1];
2200 #if LDOUBLE_SIZE == 12
2201 str
[len
++] = cv
->tab
[0];
2202 str
[len
++] = cv
->tab
[1];
2203 str
[len
++] = cv
->tab
[2];
2205 #error add long double size support
2214 /* add the current parse token in token string 's' */
2215 static void tok_str_add_tok(TokenString
*s
)
2219 /* save line number info */
2220 if (file
->line_num
!= s
->last_line_num
) {
2221 s
->last_line_num
= file
->line_num
;
2222 cval
.i
= s
->last_line_num
;
2223 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2225 tok_str_add2(s
, tok
, &tokc
);
2228 #if LDOUBLE_SIZE == 12
2229 #define LDOUBLE_GET(p, cv) \
2234 #error add long double size support
2238 /* get a token from an integer array and increment pointer
2239 accordingly. we code it as a macro to avoid pointer aliasing. */
2240 #define TOK_GET(t, p, cv) \
2262 case TOK_CLDOUBLE: \
2263 LDOUBLE_GET(p, cv); \
2264 p += LDOUBLE_SIZE / 4; \
2271 /* defines handling */
2272 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2276 s
= sym_push2(&define_stack
, v
, macro_type
, (int)str
);
2277 s
->next
= first_arg
;
2278 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2281 /* undefined a define symbol. Its name is just set to zero */
2282 static void define_undef(Sym
*s
)
2286 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2287 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2291 static inline Sym
*define_find(int v
)
2294 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2296 return table_ident
[v
]->sym_define
;
2299 /* free define stack until top reaches 'b' */
2300 static void free_defines(Sym
*b
)
2308 /* do not free args or predefined defines */
2310 tok_str_free((int *)top
->c
);
2312 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2313 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2321 static Sym
*label_find(int v
)
2324 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2326 return table_ident
[v
]->sym_label
;
2329 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2332 s
= sym_push2(ptop
, v
, 0, 0);
2334 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2335 if (ptop
== &global_label_stack
) {
2336 /* modify the top most local identifier, so that
2337 sym_identifier will point to 's' when popped */
2339 ps
= &(*ps
)->prev_tok
;
2346 /* pop labels until element last is reached. Look if any labels are
2347 undefined. Define symbols if '&&label' was used. */
2348 static void label_pop(Sym
**ptop
, Sym
*slast
)
2351 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2353 if (s
->r
== LABEL_DECLARED
) {
2354 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2355 } else if (s
->r
== LABEL_FORWARD
) {
2356 error("label '%s' used but not defined",
2357 get_tok_str(s
->v
, NULL
));
2360 /* define corresponding symbol. A size of
2362 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2366 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2372 /* eval an expression for #if/#elif */
2373 static int expr_preprocess(void)
2379 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2380 next(); /* do macro subst */
2381 if (tok
== TOK_DEFINED
) {
2386 c
= define_find(tok
) != 0;
2391 } else if (tok
>= TOK_IDENT
) {
2392 /* if undefined macro */
2396 tok_str_add_tok(&str
);
2398 tok_str_add(&str
, -1); /* simulate end of file */
2399 tok_str_add(&str
, 0);
2400 /* now evaluate C constant expression */
2401 macro_ptr
= str
.str
;
2405 tok_str_free(str
.str
);
2409 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2410 static void tok_print(int *str
)
2416 TOK_GET(t
, str
, cval
);
2419 printf(" %s", get_tok_str(t
, &cval
));
2425 /* parse after #define */
2426 static void parse_define(void)
2428 Sym
*s
, *first
, **ps
;
2429 int v
, t
, varg
, is_vaargs
, c
;
2434 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2435 /* XXX: should check if same macro (ANSI) */
2438 /* '(' must be just after macro definition for MACRO_FUNC */
2439 c
= file
->buf_ptr
[0];
2441 c
= handle_stray1(file
->buf_ptr
);
2446 while (tok
!= ')') {
2450 if (varg
== TOK_DOTS
) {
2451 varg
= TOK___VA_ARGS__
;
2453 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2457 if (varg
< TOK_IDENT
)
2458 error("badly punctuated parameter list");
2459 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2470 /* EOF testing necessary for '-D' handling */
2471 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2472 tok_str_add2(&str
, tok
, &tokc
);
2475 tok_str_add(&str
, 0);
2477 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2480 define_push(v
, t
, str
.str
, first
);
2483 /* XXX: use a token or a hash table to accelerate matching ? */
2484 static CachedInclude
*search_cached_include(TCCState
*s1
,
2485 int type
, const char *filename
)
2490 for(i
= 0;i
< s1
->nb_cached_includes
; i
++) {
2491 e
= s1
->cached_includes
[i
];
2492 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2498 static inline void add_cached_include(TCCState
*s1
, int type
,
2499 const char *filename
, int ifndef_macro
)
2503 if (search_cached_include(s1
, type
, filename
))
2506 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2508 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2512 strcpy(e
->filename
, filename
);
2513 e
->ifndef_macro
= ifndef_macro
;
2514 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2517 /* is_bof is true if first non space token at beginning of file */
2518 static void preprocess(int is_bof
)
2520 TCCState
*s1
= tcc_state
;
2521 int size
, i
, c
, n
, saved_parse_flags
;
2522 char buf
[1024], *q
, *p
;
2528 saved_parse_flags
= parse_flags
;
2529 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
2530 PARSE_FLAG_LINEFEED
;
2540 s
= define_find(tok
);
2541 /* undefine symbol by putting an invalid name */
2546 ch
= file
->buf_ptr
[0];
2547 /* XXX: incorrect if comments : use next_nomacro with a special mode */
2552 } else if (ch
== '\"') {
2555 /* XXX: better stray handling */
2558 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
2559 if ((q
- buf
) < sizeof(buf
) - 1)
2566 /* eat all spaces and comments after include */
2567 /* XXX: slightly incorrect */
2568 while (ch1
!= '\n' && ch1
!= CH_EOF
)
2572 /* computed #include : either we have only strings or
2573 we have anything enclosed in '<>' */
2576 if (tok
== TOK_STR
) {
2577 while (tok
!= TOK_LINEFEED
) {
2578 if (tok
!= TOK_STR
) {
2580 error("'#include' expects \"FILENAME\" or <FILENAME>");
2582 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
2588 while (tok
!= TOK_LINEFEED
) {
2589 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
2593 /* check syntax and remove '<>' */
2594 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
2595 goto include_syntax
;
2596 memmove(buf
, buf
+ 1, len
- 2);
2597 buf
[len
- 2] = '\0';
2602 e
= search_cached_include(s1
, c
, buf
);
2603 if (e
&& define_find(e
->ifndef_macro
)) {
2604 /* no need to parse the include because the 'ifndef macro'
2607 printf("%s: skipping %s\n", file
->filename
, buf
);
2611 /* first search in current dir if "header.h" */
2613 p
= strrchr(file
->filename
, '/');
2615 size
= p
+ 1 - file
->filename
;
2616 if (size
> sizeof(buf1
) - 1)
2617 size
= sizeof(buf1
) - 1;
2618 memcpy(buf1
, file
->filename
, size
);
2620 pstrcat(buf1
, sizeof(buf1
), buf
);
2621 f
= tcc_open(s1
, buf1
);
2625 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
2626 error("#include recursion too deep");
2627 /* now search in all the include paths */
2628 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
2629 for(i
= 0; i
< n
; i
++) {
2631 if (i
< s1
->nb_include_paths
)
2632 path
= s1
->include_paths
[i
];
2634 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
2635 pstrcpy(buf1
, sizeof(buf1
), path
);
2636 pstrcat(buf1
, sizeof(buf1
), "/");
2637 pstrcat(buf1
, sizeof(buf1
), buf
);
2638 f
= tcc_open(s1
, buf1
);
2642 error("include file '%s' not found", buf
);
2646 printf("%s: including %s\n", file
->filename
, buf1
);
2649 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
2650 /* push current file in stack */
2651 /* XXX: fix current line init */
2652 *s1
->include_stack_ptr
++ = file
;
2654 /* add include file debug info */
2656 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
2658 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
2659 ch
= file
->buf_ptr
[0];
2667 c
= expr_preprocess();
2673 if (tok
< TOK_IDENT
)
2674 error("invalid argument for '#if%sdef'", c
? "n" : "");
2678 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
2680 file
->ifndef_macro
= tok
;
2683 c
= (define_find(tok
) != 0) ^ c
;
2685 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
2686 error("memory full");
2687 *s1
->ifdef_stack_ptr
++ = c
;
2690 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2691 error("#else without matching #if");
2692 if (s1
->ifdef_stack_ptr
[-1] & 2)
2693 error("#else after #else");
2694 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
2697 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2698 error("#elif without matching #if");
2699 c
= s1
->ifdef_stack_ptr
[-1];
2701 error("#elif after #else");
2702 /* last #if/#elif expression was true: we skip */
2705 c
= expr_preprocess();
2706 s1
->ifdef_stack_ptr
[-1] = c
;
2716 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
2717 error("#endif without matching #if");
2718 s1
->ifdef_stack_ptr
--;
2719 /* '#ifndef macro' was at the start of file. Now we check if
2720 an '#endif' is exactly at the end of file */
2721 if (file
->ifndef_macro
&&
2722 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
2723 file
->ifndef_macro_saved
= file
->ifndef_macro
;
2724 /* need to set to zero to avoid false matches if another
2725 #ifndef at middle of file */
2726 file
->ifndef_macro
= 0;
2727 while (tok
!= TOK_LINEFEED
)
2729 tok_flags
|= TOK_FLAG_ENDIF
;
2735 if (tok
!= TOK_CINT
)
2737 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
2739 if (tok
!= TOK_LINEFEED
) {
2742 pstrcpy(file
->filename
, sizeof(file
->filename
),
2743 (char *)tokc
.cstr
->data
);
2749 ch
= file
->buf_ptr
[0];
2752 while (ch
!= '\n' && ch
!= CH_EOF
) {
2753 if ((q
- buf
) < sizeof(buf
) - 1)
2759 error("#error %s", buf
);
2761 warning("#warning %s", buf
);
2767 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
2768 /* '!' is ignored to allow C scripts. numbers are ignored
2769 to emulate cpp behaviour */
2771 error("invalid preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2775 /* ignore other preprocess commands or #! for C scripts */
2776 while (tok
!= TOK_LINEFEED
)
2779 parse_flags
= saved_parse_flags
;
2782 /* evaluate escape codes in a string. */
2783 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2798 case '0': case '1': case '2': case '3':
2799 case '4': case '5': case '6': case '7':
2800 /* at most three octal digits */
2805 n
= n
* 8 + c
- '0';
2809 n
= n
* 8 + c
- '0';
2814 goto add_char_nonext
;
2820 if (c
>= 'a' && c
<= 'f')
2822 else if (c
>= 'A' && c
<= 'F')
2832 goto add_char_nonext
;
2856 goto invalid_escape
;
2866 error("invalid escaped char");
2872 cstr_ccat(outstr
, c
);
2874 cstr_wccat(outstr
, c
);
2876 /* add a trailing '\0' */
2878 cstr_ccat(outstr
, '\0');
2880 cstr_wccat(outstr
, '\0');
2883 /* we use 64 bit numbers */
2886 /* bn = (bn << shift) | or_val */
2887 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2891 for(i
=0;i
<BN_SIZE
;i
++) {
2893 bn
[i
] = (v
<< shift
) | or_val
;
2894 or_val
= v
>> (32 - shift
);
2898 void bn_zero(unsigned int *bn
)
2901 for(i
=0;i
<BN_SIZE
;i
++) {
2906 /* parse number in null terminated string 'p' and return it in the
2908 void parse_number(const char *p
)
2910 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2912 unsigned int bn
[BN_SIZE
];
2923 goto float_frac_parse
;
2924 } else if (t
== '0') {
2925 if (ch
== 'x' || ch
== 'X') {
2929 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2935 /* parse all digits. cannot check octal numbers at this stage
2936 because of floating point constants */
2938 if (ch
>= 'a' && ch
<= 'f')
2940 else if (ch
>= 'A' && ch
<= 'F')
2948 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2950 error("number too long");
2956 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2957 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2959 /* NOTE: strtox should support that for hexa numbers, but
2960 non ISOC99 libcs do not support it, so we prefer to do
2962 /* hexadecimal or binary floats */
2963 /* XXX: handle overflows */
2975 } else if (t
>= 'a') {
2977 } else if (t
>= 'A') {
2982 bn_lshift(bn
, shift
, t
);
2989 if (t
>= 'a' && t
<= 'f') {
2991 } else if (t
>= 'A' && t
<= 'F') {
2993 } else if (t
>= '0' && t
<= '9') {
2999 error("invalid digit");
3000 bn_lshift(bn
, shift
, t
);
3005 if (ch
!= 'p' && ch
!= 'P')
3012 } else if (ch
== '-') {
3016 if (ch
< '0' || ch
> '9')
3017 expect("exponent digits");
3018 while (ch
>= '0' && ch
<= '9') {
3019 exp_val
= exp_val
* 10 + ch
- '0';
3022 exp_val
= exp_val
* s
;
3024 /* now we can generate the number */
3025 /* XXX: should patch directly float number */
3026 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3027 d
= ldexp(d
, exp_val
- frac_bits
);
3032 /* float : should handle overflow */
3034 } else if (t
== 'L') {
3037 /* XXX: not large enough */
3038 tokc
.ld
= (long double)d
;
3044 /* decimal floats */
3046 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3051 while (ch
>= '0' && ch
<= '9') {
3052 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3058 if (ch
== 'e' || ch
== 'E') {
3059 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3063 if (ch
== '-' || ch
== '+') {
3064 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3069 if (ch
< '0' || ch
> '9')
3070 expect("exponent digits");
3071 while (ch
>= '0' && ch
<= '9') {
3072 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3084 tokc
.f
= strtof(token_buf
, NULL
);
3085 } else if (t
== 'L') {
3088 tokc
.ld
= strtold(token_buf
, NULL
);
3091 tokc
.d
= strtod(token_buf
, NULL
);
3095 unsigned long long n
, n1
;
3098 /* integer number */
3101 if (b
== 10 && *q
== '0') {
3108 /* no need for checks except for base 10 / 8 errors */
3111 } else if (t
>= 'a') {
3113 } else if (t
>= 'A') {
3118 error("invalid digit");
3122 /* detect overflow */
3123 /* XXX: this test is not reliable */
3125 error("integer constant overflow");
3128 /* XXX: not exactly ANSI compliant */
3129 if ((n
& 0xffffffff00000000LL
) != 0) {
3134 } else if (n
> 0x7fffffff) {
3145 error("three 'l's in integer constant");
3148 if (tok
== TOK_CINT
)
3150 else if (tok
== TOK_CUINT
)
3154 } else if (t
== 'U') {
3156 error("two 'u's in integer constant");
3158 if (tok
== TOK_CINT
)
3160 else if (tok
== TOK_CLLONG
)
3167 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3175 #define PARSE2(c1, tok1, c2, tok2) \
3186 /* return next token without macro substitution */
3187 static inline void next_nomacro1(void)
3207 /* first look if it is in fact an end of buffer */
3208 if (p
>= file
->buf_end
) {
3212 if (p
>= file
->buf_end
)
3225 TCCState
*s1
= tcc_state
;
3226 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3228 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3229 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3230 /* no include left : end of file. */
3233 /* pop include file */
3235 /* test if previous '#endif' was after a #ifdef at
3237 if (tok_flags
& TOK_FLAG_ENDIF
) {
3239 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3241 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3242 file
->ifndef_macro_saved
);
3245 /* add end of include file debug info */
3247 put_stabd(N_EINCL
, 0, 0);
3249 /* pop include stack */
3251 s1
->include_stack_ptr
--;
3252 file
= *s1
->include_stack_ptr
;
3260 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3264 tok_flags
|= TOK_FLAG_BOL
;
3273 if ((tok_flags
& TOK_FLAG_BOL
) &&
3274 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3276 preprocess(tok_flags
& TOK_FLAG_BOF
);
3282 tok
= TOK_TWOSHARPS
;
3289 case 'a': case 'b': case 'c': case 'd':
3290 case 'e': case 'f': case 'g': case 'h':
3291 case 'i': case 'j': case 'k': case 'l':
3292 case 'm': case 'n': case 'o': case 'p':
3293 case 'q': case 'r': case 's': case 't':
3294 case 'u': case 'v': case 'w': case 'x':
3296 case 'A': case 'B': case 'C': case 'D':
3297 case 'E': case 'F': case 'G': case 'H':
3298 case 'I': case 'J': case 'K':
3299 case 'M': case 'N': case 'O': case 'P':
3300 case 'Q': case 'R': case 'S': case 'T':
3301 case 'U': case 'V': case 'W': case 'X':
3307 h
= TOK_HASH_FUNC(h
, c
);
3311 if (!isidnum_table
[c
])
3313 h
= TOK_HASH_FUNC(h
, c
);
3320 /* fast case : no stray found, so we have the full token
3321 and we have already hashed it */
3323 h
&= (TOK_HASH_SIZE
- 1);
3324 pts
= &hash_ident
[h
];
3329 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3331 pts
= &(ts
->hash_next
);
3333 ts
= tok_alloc_new(pts
, p1
, len
);
3337 cstr_reset(&tokcstr
);
3340 cstr_ccat(&tokcstr
, *p1
);
3346 while (isidnum_table
[c
]) {
3347 cstr_ccat(&tokcstr
, c
);
3350 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3356 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3358 goto parse_ident_fast
;
3361 if (c
== '\'' || c
== '\"') {
3365 cstr_reset(&tokcstr
);
3366 cstr_ccat(&tokcstr
, 'L');
3367 goto parse_ident_slow
;
3371 case '0': case '1': case '2': case '3':
3372 case '4': case '5': case '6': case '7':
3375 cstr_reset(&tokcstr
);
3376 /* after the first digit, accept digits, alpha, '.' or sign if
3377 prefixed by 'eEpP' */
3381 cstr_ccat(&tokcstr
, c
);
3383 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3384 ((c
== '+' || c
== '-') &&
3385 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3388 /* We add a trailing '\0' to ease parsing */
3389 cstr_ccat(&tokcstr
, '\0');
3390 tokc
.cstr
= &tokcstr
;
3394 /* special dot handling because it can also start a number */
3397 cstr_reset(&tokcstr
);
3398 cstr_ccat(&tokcstr
, '.');
3400 } else if (c
== '.') {
3420 /* parse the string */
3422 p
= parse_pp_string(p
, sep
, &str
);
3423 cstr_ccat(&str
, '\0');
3425 /* eval the escape (should be done as TOK_PPNUM) */
3426 cstr_reset(&tokcstr
);
3427 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3432 /* XXX: make it portable */
3436 char_size
= sizeof(int);
3437 if (tokcstr
.size
<= char_size
)
3438 error("empty character constant");
3439 if (tokcstr
.size
> 2 * char_size
)
3440 warning("multi-character character constant");
3442 tokc
.i
= *(int8_t *)tokcstr
.data
;
3445 tokc
.i
= *(int *)tokcstr
.data
;
3449 tokc
.cstr
= &tokcstr
;
3463 } else if (c
== '<') {
3481 } else if (c
== '>') {
3499 } else if (c
== '=') {
3512 } else if (c
== '=') {
3525 } else if (c
== '=') {
3538 } else if (c
== '=') {
3541 } else if (c
== '>') {
3549 PARSE2('!', '!', '=', TOK_NE
)
3550 PARSE2('=', '=', '=', TOK_EQ
)
3551 PARSE2('*', '*', '=', TOK_A_MUL
)
3552 PARSE2('%', '%', '=', TOK_A_MOD
)
3553 PARSE2('^', '^', '=', TOK_A_XOR
)
3555 /* comments or operator */
3559 p
= parse_comment(p
);
3561 } else if (c
== '/') {
3562 p
= parse_line_comment(p
);
3564 } else if (c
== '=') {
3584 case '$': /* only used in assembler */
3589 error("unrecognized character \\x%02x", c
);
3594 #if defined(PARSE_DEBUG)
3595 printf("token = %s\n", get_tok_str(tok
, &tokc
));
3599 /* return next token without macro substitution. Can read input from
3601 static void next_nomacro(void)
3607 TOK_GET(tok
, macro_ptr
, tokc
);
3608 if (tok
== TOK_LINENUM
) {
3609 file
->line_num
= tokc
.i
;
3618 /* substitute args in macro_str and return allocated string */
3619 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
3621 int *st
, last_tok
, t
, notfirst
;
3630 TOK_GET(t
, macro_str
, cval
);
3635 TOK_GET(t
, macro_str
, cval
);
3638 s
= sym_find2(args
, t
);
3645 cstr_ccat(&cstr
, ' ');
3646 TOK_GET(t
, st
, cval
);
3647 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
3650 cstr_ccat(&cstr
, '\0');
3652 printf("stringize: %s\n", (char *)cstr
.data
);
3656 tok_str_add2(&str
, TOK_STR
, &cval
);
3659 tok_str_add2(&str
, t
, &cval
);
3661 } else if (t
>= TOK_IDENT
) {
3662 s
= sym_find2(args
, t
);
3665 /* if '##' is present before or after, no arg substitution */
3666 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
3667 /* special case for var arg macros : ## eats the
3668 ',' if empty VA_ARGS variable. */
3669 /* XXX: test of the ',' is not 100%
3670 reliable. should fix it to avoid security
3672 if (gnu_ext
&& s
->type
.t
&&
3673 last_tok
== TOK_TWOSHARPS
&&
3674 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
3676 /* suppress ',' '##' */
3679 /* suppress '##' and add variable */
3687 TOK_GET(t1
, st
, cval
);
3690 tok_str_add2(&str
, t1
, &cval
);
3694 macro_subst(&str
, nested_list
, st
);
3697 tok_str_add(&str
, t
);
3700 tok_str_add2(&str
, t
, &cval
);
3704 tok_str_add(&str
, 0);
3708 /* do macro substitution of current token with macro 's' and add
3709 result to (tok_str,tok_len). 'nested_list' is the list of all
3710 macros we got inside to avoid recursing. Return non zero if no
3711 substitution needs to be done */
3712 static int macro_subst_tok(TokenString
*tok_str
,
3713 Sym
**nested_list
, Sym
*s
)
3715 Sym
*args
, *sa
, *sa1
;
3716 int mstr_allocated
, parlevel
, *mstr
, t
;
3722 /* if symbol is a macro, prepare substitution */
3724 /* special macros */
3725 if (tok
== TOK___LINE__
) {
3726 cval
.i
= file
->line_num
;
3727 tok_str_add2(tok_str
, TOK_CINT
, &cval
);
3728 } else if (tok
== TOK___FILE__
) {
3729 cstrval
= file
->filename
;
3731 tok_str_add2(tok_str
, TOK_STR
, &cval
);
3732 } else if (tok
== TOK___DATE__
) {
3733 cstrval
= "Jan 1 2002";
3735 } else if (tok
== TOK___TIME__
) {
3736 cstrval
= "00:00:00";
3739 cstr_cat(&cstr
, cstrval
);
3740 cstr_ccat(&cstr
, '\0');
3742 tok_str_add2(tok_str
, TOK_STR
, &cval
);
3747 if (s
->type
.t
== MACRO_FUNC
) {
3748 /* NOTE: we do not use next_nomacro to avoid eating the
3749 next token. XXX: find better solution */
3753 /* end of macro stream: we must look at the token
3754 after in the file */
3760 /* XXX: incorrect with comments */
3761 ch
= file
->buf_ptr
[0];
3762 while (is_space(ch
) || ch
== '\n')
3766 if (t
!= '(') /* no macro subst */
3769 /* argument macro */
3774 /* NOTE: empty args are allowed, except if no args */
3776 /* handle '()' case */
3777 if (!args
&& tok
== ')')
3780 error("macro '%s' used with too many args",
3781 get_tok_str(s
->v
, 0));
3784 /* NOTE: non zero sa->t indicates VA_ARGS */
3785 while ((parlevel
> 0 ||
3787 (tok
!= ',' || sa
->type
.t
))) &&
3791 else if (tok
== ')')
3793 tok_str_add2(&str
, tok
, &tokc
);
3796 tok_str_add(&str
, 0);
3797 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (int)str
.str
);
3800 /* special case for gcc var args: add an empty
3801 var arg argument if it is omitted */
3802 if (sa
&& sa
->type
.t
&& gnu_ext
)
3812 error("macro '%s' used with too few args",
3813 get_tok_str(s
->v
, 0));
3816 /* now subst each arg */
3817 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3822 tok_str_free((int *)sa
->c
);
3828 sym_push2(nested_list
, s
->v
, 0, 0);
3829 macro_subst(tok_str
, nested_list
, mstr
);
3830 /* pop nested defined symbol */
3832 *nested_list
= sa1
->prev
;
3840 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3841 return the resulting string (which must be freed). */
3842 static inline int *macro_twosharps(const int *macro_str
)
3845 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
3847 const char *p1
, *p2
;
3849 TokenString macro_str1
;
3852 start_macro_ptr
= macro_str
;
3853 /* we search the first '##' */
3855 macro_ptr1
= macro_str
;
3856 TOK_GET(t
, macro_str
, cval
);
3857 /* nothing more to do if end of string */
3860 if (*macro_str
== TOK_TWOSHARPS
)
3864 /* we saw '##', so we need more processing to handle it */
3866 tok_str_new(¯o_str1
);
3870 /* add all tokens seen so far */
3871 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
3872 TOK_GET(t
, ptr
, cval
);
3873 tok_str_add2(¯o_str1
, t
, &cval
);
3875 saved_macro_ptr
= macro_ptr
;
3876 /* XXX: get rid of the use of macro_ptr here */
3877 macro_ptr
= (int *)macro_str
;
3879 while (*macro_ptr
== TOK_TWOSHARPS
) {
3881 macro_ptr1
= macro_ptr
;
3884 TOK_GET(t
, macro_ptr
, cval
);
3885 /* We concatenate the two tokens if we have an
3886 identifier or a preprocessing number */
3888 p1
= get_tok_str(tok
, &tokc
);
3889 cstr_cat(&cstr
, p1
);
3890 p2
= get_tok_str(t
, &cval
);
3891 cstr_cat(&cstr
, p2
);
3892 cstr_ccat(&cstr
, '\0');
3894 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
3895 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
3896 if (tok
== TOK_PPNUM
) {
3897 /* if number, then create a number token */
3898 /* NOTE: no need to allocate because
3899 tok_str_add2() does it */
3902 /* if identifier, we must do a test to
3903 validate we have a correct identifier */
3904 if (t
== TOK_PPNUM
) {
3914 if (!isnum(c
) && !isid(c
))
3918 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
3919 tok
= ts
->tok
; /* modify current token */
3922 const char *str
= cstr
.data
;
3923 const unsigned char *q
;
3925 /* we look for a valid token */
3926 /* XXX: do more extensive checks */
3927 if (!strcmp(str
, ">>=")) {
3929 } else if (!strcmp(str
, "<<=")) {
3931 } else if (strlen(str
) == 2) {
3932 /* search in two bytes table */
3937 if (q
[0] == str
[0] && q
[1] == str
[1])
3944 /* NOTE: because get_tok_str use a static buffer,
3947 p1
= get_tok_str(tok
, &tokc
);
3948 cstr_cat(&cstr
, p1
);
3949 cstr_ccat(&cstr
, '\0');
3950 p2
= get_tok_str(t
, &cval
);
3951 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
3952 /* cannot merge tokens: just add them separately */
3953 tok_str_add2(¯o_str1
, tok
, &tokc
);
3954 /* XXX: free associated memory ? */
3961 tok_str_add2(¯o_str1
, tok
, &tokc
);
3966 macro_ptr
= (int *)saved_macro_ptr
;
3968 tok_str_add(¯o_str1
, 0);
3969 return macro_str1
.str
;
3973 /* do macro substitution of macro_str and add result to
3974 (tok_str,tok_len). 'nested_list' is the list of all macros we got
3975 inside to avoid recursing. */
3976 static void macro_subst(TokenString
*tok_str
,
3977 Sym
**nested_list
, const int *macro_str
)
3980 int *saved_macro_ptr
, *macro_str1
;
3985 /* first scan for '##' operator handling */
3987 macro_str1
= macro_twosharps(ptr
);
3991 /* NOTE: ptr == NULL can only happen if tokens are read from
3992 file stream due to a macro function call */
3995 TOK_GET(t
, ptr
, cval
);
4000 /* if nested substitution, do nothing */
4001 if (sym_find2(*nested_list
, t
))
4003 saved_macro_ptr
= macro_ptr
;
4004 macro_ptr
= (int *)ptr
;
4006 ret
= macro_subst_tok(tok_str
, nested_list
, s
);
4007 ptr
= (int *)macro_ptr
;
4008 macro_ptr
= saved_macro_ptr
;
4013 tok_str_add2(tok_str
, t
, &cval
);
4017 tok_str_free(macro_str1
);
4020 /* return next token with macro substitution */
4021 static void next(void)
4023 Sym
*nested_list
, *s
;
4029 /* if not reading from macro substituted string, then try
4030 to substitute macros */
4031 if (tok
>= TOK_IDENT
&&
4032 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4033 s
= define_find(tok
);
4035 /* we have a macro: we try to substitute */
4038 if (macro_subst_tok(&str
, &nested_list
, s
) == 0) {
4039 /* substitution done, NOTE: maybe empty */
4040 tok_str_add(&str
, 0);
4041 macro_ptr
= str
.str
;
4042 macro_ptr_allocated
= str
.str
;
4049 /* end of macro or end of unget buffer */
4050 if (unget_buffer_enabled
) {
4051 macro_ptr
= unget_saved_macro_ptr
;
4052 unget_buffer_enabled
= 0;
4054 /* end of macro string: free it */
4055 tok_str_free(macro_ptr_allocated
);
4062 /* convert preprocessor tokens into C tokens */
4063 if (tok
== TOK_PPNUM
&&
4064 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4065 parse_number((char *)tokc
.cstr
->data
);
4069 /* push back current token and set current token to 'last_tok'. Only
4070 identifier case handled for labels. */
4071 static inline void unget_tok(int last_tok
)
4075 unget_saved_macro_ptr
= macro_ptr
;
4076 unget_buffer_enabled
= 1;
4077 q
= unget_saved_buffer
;
4080 n
= tok_ext_size(tok
) - 1;
4083 *q
= 0; /* end of token string */
4088 void swap(int *p
, int *q
)
4096 void vsetc(CType
*type
, int r
, CValue
*vc
)
4100 if (vtop
>= vstack
+ VSTACK_SIZE
)
4101 error("memory full");
4102 /* cannot let cpu flags if other instruction are generated. Also
4103 avoid leaving VT_JMP anywhere except on the top of the stack
4104 because it would complicate the code generator. */
4105 if (vtop
>= vstack
) {
4106 v
= vtop
->r
& VT_VALMASK
;
4107 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4113 vtop
->r2
= VT_CONST
;
4117 /* push integer constant */
4122 vsetc(&int_type
, VT_CONST
, &cval
);
4125 /* Return a static symbol pointing to a section */
4126 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4127 unsigned long offset
, unsigned long size
)
4133 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4134 sym
->type
.ref
= type
->ref
;
4135 sym
->r
= VT_CONST
| VT_SYM
;
4136 put_extern_sym(sym
, sec
, offset
, size
);
4140 /* push a reference to a section offset by adding a dummy symbol */
4141 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4146 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4147 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4150 /* define a new external reference to a symbol 'v' of type 'u' */
4151 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4157 /* push forward reference */
4158 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4159 s
->type
.ref
= type
->ref
;
4160 s
->r
= r
| VT_CONST
| VT_SYM
;
4165 /* define a new external reference to a symbol 'v' of type 'u' */
4166 static Sym
*external_sym(int v
, CType
*type
, int r
)
4172 /* push forward reference */
4173 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4174 s
->type
.t
|= VT_EXTERN
;
4176 if (!is_compatible_types(&s
->type
, type
))
4177 error("incompatible types for redefinition of '%s'",
4178 get_tok_str(v
, NULL
));
4183 /* push a reference to global symbol v */
4184 static void vpush_global_sym(CType
*type
, int v
)
4189 sym
= external_global_sym(v
, type
, 0);
4191 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4195 void vset(CType
*type
, int r
, int v
)
4200 vsetc(type
, r
, &cval
);
4203 void vseti(int r
, int v
)
4219 void vpushv(SValue
*v
)
4221 if (vtop
>= vstack
+ VSTACK_SIZE
)
4222 error("memory full");
4232 /* save r to the memory stack, and mark it as being free */
4233 void save_reg(int r
)
4235 int l
, saved
, size
, align
;
4239 /* modify all stack values */
4242 for(p
=vstack
;p
<=vtop
;p
++) {
4243 if ((p
->r
& VT_VALMASK
) == r
||
4244 (p
->r2
& VT_VALMASK
) == r
) {
4245 /* must save value on stack if not already done */
4247 /* NOTE: must reload 'r' because r might be equal to r2 */
4248 r
= p
->r
& VT_VALMASK
;
4249 /* store register in the stack */
4251 if ((p
->r
& VT_LVAL
) ||
4252 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4254 size
= type_size(type
, &align
);
4255 loc
= (loc
- size
) & -align
;
4256 sv
.type
.t
= type
->t
;
4257 sv
.r
= VT_LOCAL
| VT_LVAL
;
4260 #ifdef TCC_TARGET_I386
4261 /* x86 specific: need to pop fp register ST0 if saved */
4262 if (r
== TREG_ST0
) {
4263 o(0xd9dd); /* fstp %st(1) */
4266 /* special long long case */
4267 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4274 /* mark that stack entry as being saved on the stack */
4275 if (p
->r
& VT_LVAL
) {
4276 /* also clear the bounded flag because the
4277 relocation address of the function was stored in
4279 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4281 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4289 /* find a free register of class 'rc'. If none, save one register */
4295 /* find a free register */
4296 for(r
=0;r
<NB_REGS
;r
++) {
4297 if (reg_classes
[r
] & rc
) {
4298 for(p
=vstack
;p
<=vtop
;p
++) {
4299 if ((p
->r
& VT_VALMASK
) == r
||
4300 (p
->r2
& VT_VALMASK
) == r
)
4308 /* no register left : free the first one on the stack (VERY
4309 IMPORTANT to start from the bottom to ensure that we don't
4310 spill registers used in gen_opi()) */
4311 for(p
=vstack
;p
<=vtop
;p
++) {
4312 r
= p
->r
& VT_VALMASK
;
4313 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4315 /* also look at second register (if long long) */
4316 r
= p
->r2
& VT_VALMASK
;
4317 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4323 /* Should never comes here */
4327 /* save registers up to (vtop - n) stack entry */
4328 void save_regs(int n
)
4333 for(p
= vstack
;p
<= p1
; p
++) {
4334 r
= p
->r
& VT_VALMASK
;
4341 /* move register 's' to 'r', and flush previous value of r to memory
4343 void move_reg(int r
, int s
)
4356 /* get address of vtop (vtop MUST BE an lvalue) */
4359 vtop
->r
&= ~VT_LVAL
;
4360 /* tricky: if saved lvalue, then we can go back to lvalue */
4361 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4362 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4365 #ifdef CONFIG_TCC_BCHECK
4366 /* generate lvalue bound code */
4372 vtop
->r
&= ~VT_MUSTBOUND
;
4373 /* if lvalue, then use checking code before dereferencing */
4374 if (vtop
->r
& VT_LVAL
) {
4375 /* if not VT_BOUNDED value, then make one */
4376 if (!(vtop
->r
& VT_BOUNDED
)) {
4377 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4378 /* must save type because we must set it to int to get pointer */
4380 vtop
->type
.t
= VT_INT
;
4383 gen_bounded_ptr_add();
4384 vtop
->r
|= lval_type
;
4387 /* then check for dereferencing */
4388 gen_bounded_ptr_deref();
4393 /* store vtop a register belonging to class 'rc'. lvalues are
4394 converted to values. Cannot be used if cannot be converted to
4395 register value (such as structures). */
4398 int r
, r2
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4399 unsigned long long ll
;
4401 /* NOTE: get_reg can modify vstack[] */
4402 if (vtop
->type
.t
& VT_BITFIELD
) {
4403 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4404 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4405 /* remove bit field info to avoid loops */
4406 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4407 /* generate shifts */
4408 vpushi(32 - (bit_pos
+ bit_size
));
4410 vpushi(32 - bit_size
);
4411 /* NOTE: transformed to SHR if unsigned */
4415 if (is_float(vtop
->type
.t
) &&
4416 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4419 unsigned long offset
;
4421 /* XXX: unify with initializers handling ? */
4422 /* CPUs usually cannot use float constants, so we store them
4423 generically in data segment */
4424 size
= type_size(&vtop
->type
, &align
);
4425 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
4426 data_section
->data_offset
= offset
;
4427 /* XXX: not portable yet */
4428 ptr
= section_ptr_add(data_section
, size
);
4431 ptr
[i
] = vtop
->c
.tab
[i
];
4432 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
4433 vtop
->r
|= VT_LVAL
| VT_SYM
;
4437 #ifdef CONFIG_TCC_BCHECK
4438 if (vtop
->r
& VT_MUSTBOUND
)
4442 r
= vtop
->r
& VT_VALMASK
;
4443 /* need to reload if:
4445 - lvalue (need to dereference pointer)
4446 - already a register, but not in the right class */
4447 if (r
>= VT_CONST
||
4448 (vtop
->r
& VT_LVAL
) ||
4449 !(reg_classes
[r
] & rc
) ||
4450 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
4451 !(reg_classes
[vtop
->r2
] & rc
))) {
4453 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
4454 /* two register type load : expand to two words
4456 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4459 vtop
->c
.ui
= ll
; /* first word */
4461 vtop
->r
= r
; /* save register value */
4462 vpushi(ll
>> 32); /* second word */
4463 } else if (r
>= VT_CONST
||
4464 (vtop
->r
& VT_LVAL
)) {
4465 /* load from memory */
4468 vtop
[-1].r
= r
; /* save register value */
4469 /* increment pointer to get second word */
4470 vtop
->type
.t
= VT_INT
;
4476 /* move registers */
4479 vtop
[-1].r
= r
; /* save register value */
4480 vtop
->r
= vtop
[-1].r2
;
4482 /* allocate second register */
4489 /* write second register */
4491 } else if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
4493 /* lvalue of scalar type : need to use lvalue type
4494 because of possible cast */
4497 /* compute memory access type */
4498 if (vtop
->r
& VT_LVAL_BYTE
)
4500 else if (vtop
->r
& VT_LVAL_SHORT
)
4502 if (vtop
->r
& VT_LVAL_UNSIGNED
)
4506 /* restore wanted type */
4509 /* one register type load */
4518 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
4519 void gv2(int rc1
, int rc2
)
4523 /* generate more generic register first. But VT_JMP or VT_CMP
4524 values must be generated first in all cases to avoid possible
4526 v
= vtop
[0].r
& VT_VALMASK
;
4527 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
4532 /* test if reload is needed for first register */
4533 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
4543 /* test if reload is needed for first register */
4544 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
4550 /* expand long long on stack in two int registers */
4555 u
= vtop
->type
.t
& VT_UNSIGNED
;
4558 vtop
[0].r
= vtop
[-1].r2
;
4559 vtop
[0].r2
= VT_CONST
;
4560 vtop
[-1].r2
= VT_CONST
;
4561 vtop
[0].type
.t
= VT_INT
| u
;
4562 vtop
[-1].type
.t
= VT_INT
| u
;
4565 /* build a long long from two ints */
4568 gv2(RC_INT
, RC_INT
);
4569 vtop
[-1].r2
= vtop
[0].r
;
4570 vtop
[-1].type
.t
= t
;
4574 /* rotate n first stack elements to the bottom */
4581 for(i
=-n
+1;i
!=0;i
++)
4582 vtop
[i
] = vtop
[i
+1];
4586 /* pop stack value */
4590 v
= vtop
->r
& VT_VALMASK
;
4591 #ifdef TCC_TARGET_I386
4592 /* for x86, we need to pop the FP stack */
4593 if (v
== TREG_ST0
&& !nocode_wanted
) {
4594 o(0xd9dd); /* fstp %st(1) */
4597 if (v
== VT_JMP
|| v
== VT_JMPI
) {
4598 /* need to put correct jump if && or || without test */
4604 /* convert stack entry to register and duplicate its value in another
4612 if ((t
& VT_BTYPE
) == VT_LLONG
) {
4619 /* stack: H L L1 H1 */
4627 /* duplicate value */
4638 load(r1
, &sv
); /* move r to r1 */
4640 /* duplicates value */
4645 /* generate CPU independent (unsigned) long long operations */
4646 void gen_opl(int op
)
4648 int t
, a
, b
, op1
, c
, i
;
4656 func
= TOK___divdi3
;
4659 func
= TOK___udivdi3
;
4662 func
= TOK___moddi3
;
4665 func
= TOK___umoddi3
;
4667 /* call generic long long function */
4668 gfunc_start(&gf
, FUNC_CDECL
);
4671 vpush_global_sym(&func_old_type
, func
);
4675 vtop
->r2
= REG_LRET
;
4688 /* stack: L1 H1 L2 H2 */
4693 vtop
[-2] = vtop
[-3];
4696 /* stack: H1 H2 L1 L2 */
4702 /* stack: H1 H2 L1 L2 ML MH */
4705 /* stack: ML MH H1 H2 L1 L2 */
4709 /* stack: ML MH H1 L2 H2 L1 */
4714 /* stack: ML MH M1 M2 */
4717 } else if (op
== '+' || op
== '-') {
4718 /* XXX: add non carry method too (for MIPS or alpha) */
4724 /* stack: H1 H2 (L1 op L2) */
4727 gen_op(op1
+ 1); /* TOK_xxxC2 */
4730 /* stack: H1 H2 (L1 op L2) */
4733 /* stack: (L1 op L2) H1 H2 */
4735 /* stack: (L1 op L2) (H1 op H2) */
4743 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
4744 t
= vtop
[-1].type
.t
;
4748 /* stack: L H shift */
4750 /* constant: simpler */
4751 /* NOTE: all comments are for SHL. the other cases are
4752 done by swaping words */
4763 if (op
!= TOK_SAR
) {
4796 /* XXX: should provide a faster fallback on x86 ? */
4799 func
= TOK___sardi3
;
4802 func
= TOK___shrdi3
;
4805 func
= TOK___shldi3
;
4811 /* compare operations */
4817 /* stack: L1 H1 L2 H2 */
4819 vtop
[-1] = vtop
[-2];
4821 /* stack: L1 L2 H1 H2 */
4824 /* when values are equal, we need to compare low words. since
4825 the jump is inverted, we invert the test too. */
4828 else if (op1
== TOK_GT
)
4830 else if (op1
== TOK_ULT
)
4832 else if (op1
== TOK_UGT
)
4837 if (op1
!= TOK_NE
) {
4841 /* generate non equal test */
4842 /* XXX: NOT PORTABLE yet */
4846 #ifdef TCC_TARGET_I386
4847 b
= psym(0x850f, 0);
4849 error("not implemented");
4853 /* compare low. Always unsigned */
4857 else if (op1
== TOK_LE
)
4859 else if (op1
== TOK_GT
)
4861 else if (op1
== TOK_GE
)
4871 /* handle integer constant optimizations and various machine
4873 void gen_opic(int op
)
4880 /* currently, we cannot do computations with forward symbols */
4881 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4882 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4886 case '+': v1
->c
.i
+= fc
; break;
4887 case '-': v1
->c
.i
-= fc
; break;
4888 case '&': v1
->c
.i
&= fc
; break;
4889 case '^': v1
->c
.i
^= fc
; break;
4890 case '|': v1
->c
.i
|= fc
; break;
4891 case '*': v1
->c
.i
*= fc
; break;
4898 /* if division by zero, generate explicit division */
4901 error("division by zero in constant");
4905 default: v1
->c
.i
/= fc
; break;
4906 case '%': v1
->c
.i
%= fc
; break;
4907 case TOK_UDIV
: v1
->c
.i
= (unsigned)v1
->c
.i
/ fc
; break;
4908 case TOK_UMOD
: v1
->c
.i
= (unsigned)v1
->c
.i
% fc
; break;
4911 case TOK_SHL
: v1
->c
.i
<<= fc
; break;
4912 case TOK_SHR
: v1
->c
.i
= (unsigned)v1
->c
.i
>> fc
; break;
4913 case TOK_SAR
: v1
->c
.i
>>= fc
; break;
4915 case TOK_ULT
: v1
->c
.i
= (unsigned)v1
->c
.i
< (unsigned)fc
; break;
4916 case TOK_UGE
: v1
->c
.i
= (unsigned)v1
->c
.i
>= (unsigned)fc
; break;
4917 case TOK_EQ
: v1
->c
.i
= v1
->c
.i
== fc
; break;
4918 case TOK_NE
: v1
->c
.i
= v1
->c
.i
!= fc
; break;
4919 case TOK_ULE
: v1
->c
.i
= (unsigned)v1
->c
.i
<= (unsigned)fc
; break;
4920 case TOK_UGT
: v1
->c
.i
= (unsigned)v1
->c
.i
> (unsigned)fc
; break;
4921 case TOK_LT
: v1
->c
.i
= v1
->c
.i
< fc
; break;
4922 case TOK_GE
: v1
->c
.i
= v1
->c
.i
>= fc
; break;
4923 case TOK_LE
: v1
->c
.i
= v1
->c
.i
<= fc
; break;
4924 case TOK_GT
: v1
->c
.i
= v1
->c
.i
> fc
; break;
4926 case TOK_LAND
: v1
->c
.i
= v1
->c
.i
&& fc
; break;
4927 case TOK_LOR
: v1
->c
.i
= v1
->c
.i
|| fc
; break;
4933 /* if commutative ops, put c2 as constant */
4934 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
4935 op
== '|' || op
== '*')) {
4940 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
4943 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
4944 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
4950 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
4951 /* try to use shifts instead of muls or divs */
4952 if (fc
> 0 && (fc
& (fc
- 1)) == 0) {
4961 else if (op
== TOK_PDIV
)
4967 } else if (c2
&& (op
== '+' || op
== '-') &&
4968 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
4969 (VT_CONST
| VT_SYM
)) {
4970 /* symbol + constant case */
4977 if (!nocode_wanted
) {
4978 /* call low level op generator */
4987 /* generate a floating point operation with constant propagation */
4988 void gen_opif(int op
)
4996 /* currently, we cannot do computations with forward symbols */
4997 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4998 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5000 if (v1
->type
.t
== VT_FLOAT
) {
5003 } else if (v1
->type
.t
== VT_DOUBLE
) {
5011 /* NOTE: we only do constant propagation if finite number (not
5012 NaN or infinity) (ANSI spec) */
5013 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5017 case '+': f1
+= f2
; break;
5018 case '-': f1
-= f2
; break;
5019 case '*': f1
*= f2
; break;
5023 error("division by zero in constant");
5028 /* XXX: also handles tests ? */
5032 /* XXX: overflow test ? */
5033 if (v1
->type
.t
== VT_FLOAT
) {
5035 } else if (v1
->type
.t
== VT_DOUBLE
) {
5043 if (!nocode_wanted
) {
5051 static int pointed_size(CType
*type
)
5054 return type_size(pointed_type(type
), &align
);
5058 void check_pointer_types(SValue
*p1
, SValue
*p2
)
5060 char buf1
[256], buf2
[256];
5064 if (!is_compatible_types(t1
, t2
)) {
5065 type_to_str(buf1
, sizeof(buf1
), t1
, NULL
);
5066 type_to_str(buf2
, sizeof(buf2
), t2
, NULL
);
5067 error("incompatible pointers '%s' and '%s'", buf1
, buf2
);
5072 /* generic gen_op: handles types problems */
5075 int u
, t1
, t2
, bt1
, bt2
, t
;
5078 t1
= vtop
[-1].type
.t
;
5079 t2
= vtop
[0].type
.t
;
5080 bt1
= t1
& VT_BTYPE
;
5081 bt2
= t2
& VT_BTYPE
;
5083 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5084 /* at least one operand is a pointer */
5085 /* relationnal op: must be both pointers */
5086 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5087 // check_pointer_types(vtop, vtop - 1);
5088 /* pointers are handled are unsigned */
5089 t
= VT_INT
| VT_UNSIGNED
;
5092 /* if both pointers, then it must be the '-' op */
5093 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5095 error("cannot use pointers here");
5096 // check_pointer_types(vtop - 1, vtop);
5097 /* XXX: check that types are compatible */
5098 u
= pointed_size(&vtop
[-1].type
);
5100 /* set to integer type */
5101 vtop
->type
.t
= VT_INT
;
5105 /* exactly one pointer : must be '+' or '-'. */
5106 if (op
!= '-' && op
!= '+')
5107 error("cannot use pointers here");
5108 /* Put pointer as first operand */
5109 if (bt2
== VT_PTR
) {
5113 type1
= vtop
[-1].type
;
5114 /* XXX: cast to int ? (long long case) */
5115 vpushi(pointed_size(&vtop
[-1].type
));
5117 #ifdef CONFIG_TCC_BCHECK
5118 /* if evaluating constant expression, no code should be
5119 generated, so no bound check */
5120 if (do_bounds_check
&& !const_wanted
) {
5121 /* if bounded pointers, we generate a special code to
5128 gen_bounded_ptr_add();
5134 /* put again type if gen_opic() swaped operands */
5137 } else if (is_float(bt1
) || is_float(bt2
)) {
5138 /* compute bigger type and do implicit casts */
5139 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5141 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5146 /* floats can only be used for a few operations */
5147 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5148 (op
< TOK_ULT
|| op
> TOK_GT
))
5149 error("invalid operands for binary operation");
5151 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5152 /* cast to biggest op */
5154 /* convert to unsigned if it does not fit in a long long */
5155 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5156 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5160 /* integer operations */
5162 /* convert to unsigned if it does not fit in an integer */
5163 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5164 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5167 /* XXX: currently, some unsigned operations are explicit, so
5168 we modify them here */
5169 if (t
& VT_UNSIGNED
) {
5176 else if (op
== TOK_LT
)
5178 else if (op
== TOK_GT
)
5180 else if (op
== TOK_LE
)
5182 else if (op
== TOK_GE
)
5189 /* special case for shifts and long long: we keep the shift as
5191 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5196 else if ((t
& VT_BTYPE
) == VT_LLONG
)
5200 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5201 /* relationnal op: the result is an int */
5202 vtop
->type
.t
= VT_INT
;
5209 /* generic itof for unsigned long long case */
5210 void gen_cvt_itof1(int t
)
5214 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
5215 (VT_LLONG
| VT_UNSIGNED
)) {
5217 gfunc_start(&gf
, FUNC_CDECL
);
5220 vpush_global_sym(&func_old_type
, TOK___ulltof
);
5221 else if (t
== VT_DOUBLE
)
5222 vpush_global_sym(&func_old_type
, TOK___ulltod
);
5224 vpush_global_sym(&func_old_type
, TOK___ulltold
);
5233 /* generic ftoi for unsigned long long case */
5234 void gen_cvt_ftoi1(int t
)
5239 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
5240 /* not handled natively */
5241 gfunc_start(&gf
, FUNC_CDECL
);
5242 st
= vtop
->type
.t
& VT_BTYPE
;
5245 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
5246 else if (st
== VT_DOUBLE
)
5247 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
5249 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
5253 vtop
->r2
= REG_LRET
;
5259 /* force char or short cast */
5260 void force_charshort_cast(int t
)
5264 /* XXX: add optimization if lvalue : just change type and offset */
5269 if (t
& VT_UNSIGNED
) {
5270 vpushi((1 << bits
) - 1);
5281 /* cast 'vtop' to 'type' */
5282 static void gen_cast(CType
*type
)
5284 int sbt
, dbt
, sf
, df
, c
;
5286 /* special delayed cast for char/short */
5287 /* XXX: in some cases (multiple cascaded casts), it may still
5289 if (vtop
->r
& VT_MUSTCAST
) {
5290 vtop
->r
&= ~VT_MUSTCAST
;
5291 force_charshort_cast(vtop
->type
.t
);
5294 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
5295 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
5297 if (sbt
!= dbt
&& !nocode_wanted
) {
5300 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5302 /* convert from fp to fp */
5304 /* constant case: we can do it now */
5305 /* XXX: in ISOC, cannot do it if error in convert */
5306 if (dbt
== VT_FLOAT
&& sbt
== VT_DOUBLE
)
5307 vtop
->c
.f
= (float)vtop
->c
.d
;
5308 else if (dbt
== VT_FLOAT
&& sbt
== VT_LDOUBLE
)
5309 vtop
->c
.f
= (float)vtop
->c
.ld
;
5310 else if (dbt
== VT_DOUBLE
&& sbt
== VT_FLOAT
)
5311 vtop
->c
.d
= (double)vtop
->c
.f
;
5312 else if (dbt
== VT_DOUBLE
&& sbt
== VT_LDOUBLE
)
5313 vtop
->c
.d
= (double)vtop
->c
.ld
;
5314 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_FLOAT
)
5315 vtop
->c
.ld
= (long double)vtop
->c
.f
;
5316 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_DOUBLE
)
5317 vtop
->c
.ld
= (long double)vtop
->c
.d
;
5319 /* non constant case: generate code */
5323 /* convert int to fp */
5326 case VT_LLONG
| VT_UNSIGNED
:
5328 /* XXX: add const cases for long long */
5330 case VT_INT
| VT_UNSIGNED
:
5332 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.ui
; break;
5333 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.ui
; break;
5334 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.ui
; break;
5339 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.i
; break;
5340 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.i
; break;
5341 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.i
; break;
5350 /* convert fp to int */
5351 /* we handle char/short/etc... with generic code */
5352 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
5353 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
5358 case VT_LLONG
| VT_UNSIGNED
:
5360 /* XXX: add const cases for long long */
5362 case VT_INT
| VT_UNSIGNED
:
5364 case VT_FLOAT
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5365 case VT_DOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5366 case VT_LDOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5372 case VT_FLOAT
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5373 case VT_DOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5374 case VT_LDOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5382 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
5383 /* additional cast for char/short/bool... */
5387 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
5388 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
5389 /* scalar to long long */
5391 if (sbt
== (VT_INT
| VT_UNSIGNED
))
5392 vtop
->c
.ll
= vtop
->c
.ui
;
5394 vtop
->c
.ll
= vtop
->c
.i
;
5396 /* machine independent conversion */
5398 /* generate high word */
5399 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
5407 /* patch second register */
5408 vtop
[-1].r2
= vtop
->r
;
5412 } else if (dbt
== VT_BOOL
) {
5413 /* scalar to bool */
5416 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
5417 (dbt
& VT_BTYPE
) == VT_SHORT
) {
5418 force_charshort_cast(dbt
);
5419 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
5421 if (sbt
== VT_LLONG
) {
5422 /* from long long: just take low order word */
5426 /* if lvalue and single word type, nothing to do because
5427 the lvalue already contains the real type size (see
5428 VT_LVAL_xxx constants) */
5434 /* return type size. Put alignment at 'a' */
5435 static int type_size(CType
*type
, int *a
)
5440 bt
= type
->t
& VT_BTYPE
;
5441 if (bt
== VT_STRUCT
) {
5446 } else if (bt
== VT_PTR
) {
5447 if (type
->t
& VT_ARRAY
) {
5449 return type_size(&s
->type
, a
) * s
->c
;
5454 } else if (bt
== VT_LDOUBLE
) {
5456 return LDOUBLE_SIZE
;
5457 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
5458 *a
= 4; /* XXX: i386 specific */
5460 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
5463 } else if (bt
== VT_SHORT
) {
5467 /* char, void, function, _Bool */
5473 /* return the pointed type of t */
5474 static inline CType
*pointed_type(CType
*type
)
5476 return &type
->ref
->type
;
5479 /* modify type so that its it is a pointer to type. */
5480 static void mk_pointer(CType
*type
)
5483 s
= sym_push(SYM_FIELD
, type
, 0, -1);
5484 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
5488 static int is_compatible_types(CType
*type1
, CType
*type2
)
5491 int bt1
, bt2
, t1
, t2
;
5493 t1
= type1
->t
& VT_TYPE
;
5494 t2
= type2
->t
& VT_TYPE
;
5495 bt1
= t1
& VT_BTYPE
;
5496 bt2
= t2
& VT_BTYPE
;
5497 if (bt1
== VT_PTR
) {
5498 type1
= pointed_type(type1
);
5499 /* if function, then convert implicitely to function pointer */
5500 if (bt2
!= VT_FUNC
) {
5503 type2
= pointed_type(type2
);
5505 /* void matches everything */
5506 /* XXX: not fully compliant */
5507 if ((type1
->t
& VT_TYPE
) == VT_VOID
|| (type2
->t
& VT_TYPE
) == VT_VOID
)
5509 return is_compatible_types(type1
, type2
);
5510 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
5511 return (type1
->ref
== type2
->ref
);
5512 } else if (bt1
== VT_FUNC
) {
5517 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5519 /* XXX: not complete */
5520 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
5524 while (s1
!= NULL
) {
5527 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5536 /* XXX: not complete */
5541 /* print a type. If 'varstr' is not NULL, then the variable is also
5542 printed in the type */
5544 /* XXX: add array and function pointers */
5545 void type_to_str(char *buf
, int buf_size
,
5546 CType
*type
, const char *varstr
)
5553 t
= type
->t
& VT_TYPE
;
5556 if (t
& VT_UNSIGNED
)
5557 pstrcat(buf
, buf_size
, "unsigned ");
5587 tstr
= "long double";
5589 pstrcat(buf
, buf_size
, tstr
);
5593 if (bt
== VT_STRUCT
)
5597 pstrcat(buf
, buf_size
, tstr
);
5598 v
= type
->ref
->v
& ~SYM_STRUCT
;
5599 if (v
>= SYM_FIRST_ANOM
)
5600 pstrcat(buf
, buf_size
, "<anonymous>");
5602 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
5606 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
5607 pstrcat(buf
, buf_size
, "(");
5609 while (sa
!= NULL
) {
5610 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
5611 pstrcat(buf
, buf_size
, buf1
);
5614 pstrcat(buf
, buf_size
, ", ");
5616 pstrcat(buf
, buf_size
, ")");
5620 pstrcpy(buf1
, sizeof(buf1
), "*");
5622 pstrcat(buf1
, sizeof(buf1
), varstr
);
5623 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
5627 pstrcat(buf
, buf_size
, " ");
5628 pstrcat(buf
, buf_size
, varstr
);
5633 /* verify type compatibility to store vtop in 'dt' type, and generate
5635 static void gen_assign_cast(CType
*dt
)
5638 char buf1
[256], buf2
[256];
5641 st
= &vtop
->type
; /* source type */
5642 dbt
= dt
->t
& VT_BTYPE
;
5643 sbt
= st
->t
& VT_BTYPE
;
5644 if (dbt
== VT_PTR
) {
5645 /* special cases for pointers */
5646 /* a function is implicitely a function pointer */
5647 if (sbt
== VT_FUNC
) {
5648 if (!is_compatible_types(pointed_type(dt
), st
))
5653 /* '0' can also be a pointer */
5654 if (sbt
== VT_INT
&&
5655 ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) &&
5658 /* accept implicit pointer to integer cast with warning */
5659 if (sbt
== VT_BYTE
|| sbt
== VT_SHORT
||
5660 sbt
== VT_INT
|| sbt
== VT_LLONG
) {
5661 warning("assignment makes pointer from integer without a cast");
5664 } else if (dbt
== VT_BYTE
|| dbt
== VT_SHORT
||
5665 dbt
== VT_INT
|| dbt
== VT_LLONG
) {
5666 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
5667 warning("assignment makes integer from pointer without a cast");
5671 if (!is_compatible_types(dt
, st
)) {
5673 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
5674 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
5675 error("cannot cast '%s' to '%s'", buf1
, buf2
);
5681 /* store vtop in lvalue pushed on stack */
5684 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
5687 ft
= vtop
[-1].type
.t
;
5688 sbt
= vtop
->type
.t
& VT_BTYPE
;
5689 dbt
= ft
& VT_BTYPE
;
5690 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
5691 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
5692 /* optimize char/short casts */
5693 delayed_cast
= VT_MUSTCAST
;
5694 vtop
->type
.t
= ft
& VT_TYPE
;
5697 gen_assign_cast(&vtop
[-1].type
);
5700 if (sbt
== VT_STRUCT
) {
5701 /* if structure, only generate pointer */
5702 /* structure assignment : generate memcpy */
5703 /* XXX: optimize if small size */
5704 if (!nocode_wanted
) {
5706 gfunc_start(&gf
, FUNC_CDECL
);
5708 size
= type_size(&vtop
->type
, &align
);
5712 vtop
->type
.t
= VT_INT
;
5717 vtop
->type
.t
= VT_INT
;
5722 vpush_global_sym(&func_old_type
, TOK_memcpy
);
5728 /* leave source on stack */
5729 } else if (ft
& VT_BITFIELD
) {
5730 /* bitfield store handling */
5731 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
5732 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
5733 /* remove bit field info to avoid loops */
5734 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
5736 /* duplicate destination */
5738 vtop
[-1] = vtop
[-2];
5740 /* mask and shift source */
5741 vpushi((1 << bit_size
) - 1);
5745 /* load destination, mask and or with source */
5747 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
5753 #ifdef CONFIG_TCC_BCHECK
5754 /* bound check case */
5755 if (vtop
[-1].r
& VT_MUSTBOUND
) {
5761 if (!nocode_wanted
) {
5765 r
= gv(rc
); /* generate value */
5766 /* if lvalue was saved on stack, must read it */
5767 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
5769 t
= get_reg(RC_INT
);
5771 sv
.r
= VT_LOCAL
| VT_LVAL
;
5772 sv
.c
.ul
= vtop
[-1].c
.ul
;
5774 vtop
[-1].r
= t
| VT_LVAL
;
5777 /* two word case handling : store second register at word + 4 */
5778 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
5780 /* convert to int to increment easily */
5781 vtop
->type
.t
= VT_INT
;
5787 /* XXX: it works because r2 is spilled last ! */
5788 store(vtop
->r2
, vtop
- 1);
5792 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
5793 vtop
->r
|= delayed_cast
;
5797 /* post defines POST/PRE add. c is the token ++ or -- */
5798 void inc(int post
, int c
)
5801 vdup(); /* save lvalue */
5803 gv_dup(); /* duplicate value */
5808 vpushi(c
- TOK_MID
);
5810 vstore(); /* store value */
5812 vpop(); /* if post op, return saved value */
5815 /* Parse GNUC __attribute__ extension. Currently, the following
5816 extensions are recognized:
5817 - aligned(n) : set data/function alignment.
5818 - section(x) : generate data/code in this section.
5819 - unused : currently ignored, but may be used someday.
5821 static void parse_attribute(AttributeDef
*ad
)
5825 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
5829 while (tok
!= ')') {
5830 if (tok
< TOK_IDENT
)
5831 expect("attribute name");
5839 expect("section name");
5840 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
5849 if (n
<= 0 || (n
& (n
- 1)) != 0)
5850 error("alignment must be a positive power of two");
5859 /* currently, no need to handle it because tcc does not
5860 track unused objects */
5864 /* currently, no need to handle it because tcc does not
5865 track unused objects */
5870 ad
->func_call
= FUNC_CDECL
;
5875 ad
->func_call
= FUNC_STDCALL
;
5878 // warning("'%s' attribute ignored", get_tok_str(t, NULL));
5879 /* skip parameters */
5880 /* XXX: skip parenthesis too */
5883 while (tok
!= ')' && tok
!= -1)
5898 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
5899 static void struct_decl(CType
*type
, int u
)
5901 int a
, v
, size
, align
, maxalign
, c
, offset
;
5902 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
;
5907 a
= tok
; /* save decl type */
5912 /* struct already defined ? return it */
5914 expect("struct/union/enum name");
5918 error("invalid type");
5925 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, 0);
5926 /* put struct/union/enum name in type */
5934 error("struct/union/enum already defined");
5935 /* cannot be empty */
5937 /* non empty enums are not allowed */
5938 if (a
== TOK_ENUM
) {
5942 expect("identifier");
5948 /* enum symbols have static storage */
5949 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
5950 ss
->type
.t
|= VT_STATIC
;
5955 /* NOTE: we accept a trailing comma */
5965 while (tok
!= '}') {
5966 parse_btype(&btype
, &ad
);
5972 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
);
5973 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
5974 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
5975 error("invalid type for '%s'",
5976 get_tok_str(v
, NULL
));
5980 bit_size
= expr_const();
5981 /* XXX: handle v = 0 case for messages */
5983 error("negative width in bit-field '%s'",
5984 get_tok_str(v
, NULL
));
5985 if (v
&& bit_size
== 0)
5986 error("zero width for bit-field '%s'",
5987 get_tok_str(v
, NULL
));
5989 size
= type_size(&type1
, &align
);
5991 if (bit_size
>= 0) {
5992 bt
= type1
.t
& VT_BTYPE
;
5997 error("bitfields must have scalar type");
5999 if (bit_size
> bsize
) {
6000 error("width of '%s' exceeds its type",
6001 get_tok_str(v
, NULL
));
6002 } else if (bit_size
== bsize
) {
6003 /* no need for bit fields */
6005 } else if (bit_size
== 0) {
6006 /* XXX: what to do if only padding in a
6008 /* zero size: means to pad */
6012 /* we do not have enough room ? */
6013 if ((bit_pos
+ bit_size
) > bsize
)
6016 /* XXX: handle LSB first */
6017 type1
.t
|= VT_BITFIELD
|
6018 (bit_pos
<< VT_STRUCT_SHIFT
) |
6019 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
6020 bit_pos
+= bit_size
;
6026 /* add new memory data only if starting
6028 if (lbit_pos
== 0) {
6029 if (a
== TOK_STRUCT
) {
6030 c
= (c
+ align
- 1) & -align
;
6038 if (align
> maxalign
)
6042 printf("add field %s offset=%d",
6043 get_tok_str(v
, NULL
), offset
);
6044 if (type1
.t
& VT_BITFIELD
) {
6045 printf(" pos=%d size=%d",
6046 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
6047 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
6051 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
6055 if (tok
== ';' || tok
== TOK_EOF
)
6062 /* store size and alignment */
6063 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
6069 /* return 0 if no type declaration. otherwise, return the basic type
6072 static int parse_btype(CType
*type
, AttributeDef
*ad
)
6074 int t
, u
, type_found
;
6078 memset(ad
, 0, sizeof(AttributeDef
));
6084 /* currently, we really ignore extension */
6094 if ((t
& VT_BTYPE
) != 0)
6095 error("too many basic types");
6109 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
6110 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6111 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
6112 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
6126 if ((t
& VT_BTYPE
) == VT_LONG
) {
6127 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6134 struct_decl(&type1
, VT_ENUM
);
6137 type
->ref
= type1
.ref
;
6141 struct_decl(&type1
, VT_STRUCT
);
6144 /* type modifiers */
6186 /* GNUC attribute */
6187 case TOK_ATTRIBUTE1
:
6188 case TOK_ATTRIBUTE2
:
6189 parse_attribute(ad
);
6196 parse_expr_type(&type1
);
6200 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
6202 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
6203 type
->ref
= s
->type
.ref
;
6210 /* long is never used as type */
6211 if ((t
& VT_BTYPE
) == VT_LONG
)
6212 t
= (t
& ~VT_BTYPE
) | VT_INT
;
6217 /* convert a function parameter type (array to pointer and function to
6218 function pointer) */
6219 static inline void convert_parameter_type(CType
*pt
)
6221 /* array must be transformed to pointer according to ANSI C */
6223 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
6228 static void post_type(CType
*type
, AttributeDef
*ad
)
6231 Sym
**plast
, *s
, *first
;
6236 /* function declaration */
6241 while (tok
!= ')') {
6242 /* read param name and compute offset */
6243 if (l
!= FUNC_OLD
) {
6244 if (!parse_btype(&pt
, &ad1
)) {
6246 error("invalid type");
6253 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
6255 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6256 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
6257 error("parameter declared as void");
6264 convert_parameter_type(&pt
);
6265 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
6270 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
6277 /* if no parameters, then old type prototype */
6281 t1
= type
->t
& VT_STORAGE
;
6282 type
->t
&= ~VT_STORAGE
;
6283 post_type(type
, ad
);
6284 /* we push a anonymous symbol which will contain the function prototype */
6285 s
= sym_push(SYM_FIELD
, type
, ad
->func_call
, l
);
6287 type
->t
= t1
| VT_FUNC
;
6289 } else if (tok
== '[') {
6290 /* array definition */
6296 error("invalid array size");
6299 /* parse next post type */
6300 t1
= type
->t
& VT_STORAGE
;
6301 type
->t
&= ~VT_STORAGE
;
6302 post_type(type
, ad
);
6304 /* we push a anonymous symbol which will contain the array
6306 s
= sym_push(SYM_FIELD
, type
, 0, n
);
6307 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
6312 /* Parse a type declaration (except basic type), and return the type
6313 in 'type'. 'td' is a bitmask indicating which kind of type decl is
6314 expected. 'type' should contain the basic type. 'ad' is the
6315 attribute definition of the basic type. It can be modified by
6318 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
6321 CType type1
, *type2
;
6323 while (tok
== '*') {
6342 /* XXX: clarify attribute handling */
6343 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6344 parse_attribute(ad
);
6346 /* recursive type */
6347 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
6348 type1
.t
= 0; /* XXX: same as int */
6351 /* XXX: this is not correct to modify 'ad' at this point, but
6352 the syntax is not clear */
6353 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6354 parse_attribute(ad
);
6355 type_decl(&type1
, ad
, v
, td
);
6358 /* type identifier */
6359 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
6363 if (!(td
& TYPE_ABSTRACT
))
6364 expect("identifier");
6368 post_type(type
, ad
);
6369 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6370 parse_attribute(ad
);
6373 /* append type at the end of type1 */
6386 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
6387 static int lvalue_type(int t
)
6392 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
6394 else if (bt
== VT_SHORT
)
6398 if (t
& VT_UNSIGNED
)
6399 r
|= VT_LVAL_UNSIGNED
;
6403 /* indirection with full error checking and bound check */
6404 static void indir(void)
6406 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
6408 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
6410 vtop
->type
= *pointed_type(&vtop
->type
);
6411 /* an array is never an lvalue */
6412 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6413 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6414 /* if bound checking, the referenced pointer must be checked */
6415 if (do_bounds_check
)
6416 vtop
->r
|= VT_MUSTBOUND
;
6420 /* pass a parameter to a function and do type checking and casting */
6421 void gfunc_param_typed(GFuncContext
*gf
, Sym
*func
, Sym
*arg
)
6426 func_type
= func
->c
;
6427 if (func_type
== FUNC_OLD
||
6428 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
6429 /* default casting : only need to convert float to double */
6430 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
6434 } else if (arg
== NULL
) {
6435 error("too many arguments to function");
6437 gen_assign_cast(&arg
->type
);
6439 if (!nocode_wanted
) {
6446 /* parse an expression of the form '(type)' or '(expr)' and return its
6448 static void parse_expr_type(CType
*type
)
6454 if (parse_btype(type
, &ad
)) {
6455 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6462 static void vpush_tokc(int t
)
6466 vsetc(&type
, VT_CONST
, &tokc
);
6469 static void unary(void)
6471 int n
, t
, align
, size
, r
;
6477 /* XXX: GCC 2.95.3 does not generate a table although it should be
6491 vpush_tokc(VT_INT
| VT_UNSIGNED
);
6495 vpush_tokc(VT_LLONG
);
6499 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
6503 vpush_tokc(VT_FLOAT
);
6507 vpush_tokc(VT_DOUBLE
);
6511 vpush_tokc(VT_LDOUBLE
);
6514 case TOK___FUNCTION__
:
6516 goto tok_identifier
;
6522 /* special function name identifier */
6523 len
= strlen(funcname
) + 1;
6524 /* generate char[len] type */
6529 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
6530 ptr
= section_ptr_add(data_section
, len
);
6531 memcpy(ptr
, funcname
, len
);
6539 /* string parsing */
6545 memset(&ad
, 0, sizeof(AttributeDef
));
6546 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
6551 if (parse_btype(&type
, &ad
)) {
6552 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
6554 /* check ISOC99 compound literal */
6556 /* data is allocated locally by default */
6561 /* all except arrays are lvalues */
6562 if (!(type
.t
& VT_ARRAY
))
6563 r
|= lvalue_type(type
.t
);
6564 memset(&ad
, 0, sizeof(AttributeDef
));
6565 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
6570 } else if (tok
== '{') {
6571 /* save all registers */
6573 /* statement expression : we do not accept break/continue
6574 inside as GCC does */
6575 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
6590 /* functions names must be treated as function pointers,
6591 except for unary '&' and sizeof. Since we consider that
6592 functions are not lvalues, we only have to handle it
6593 there and in function calls. */
6594 /* arrays can also be used although they are not lvalues */
6595 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
6596 !(vtop
->type
.t
& VT_ARRAY
))
6598 mk_pointer(&vtop
->type
);
6604 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
)
6605 vtop
->c
.i
= !vtop
->c
.i
;
6606 else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
6607 vtop
->c
.i
= vtop
->c
.i
^ 1;
6609 vseti(VT_JMP
, gtst(1, 0));
6619 /* in order to force cast, we add zero */
6621 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
6622 error("pointer not accepted for unary plus");
6632 parse_expr_type(&type
);
6636 size
= type_size(&type
, &align
);
6637 if (t
== TOK_SIZEOF
)
6658 goto tok_identifier
;
6660 /* allow to take the address of a label */
6661 if (tok
< TOK_UIDENT
)
6662 expect("label identifier");
6663 s
= label_find(tok
);
6665 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
6667 if (s
->r
== LABEL_DECLARED
)
6668 s
->r
= LABEL_FORWARD
;
6671 s
->type
.t
= VT_VOID
;
6672 mk_pointer(&s
->type
);
6673 s
->type
.t
|= VT_STATIC
;
6675 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
6684 expect("identifier");
6688 error("'%s' undeclared", get_tok_str(t
, NULL
));
6689 /* for simple function calls, we tolerate undeclared
6690 external reference to int() function */
6691 s
= external_global_sym(t
, &func_old_type
, 0);
6693 vset(&s
->type
, s
->r
, s
->c
);
6694 /* if forward reference, we must point to s */
6695 if (vtop
->r
& VT_SYM
) {
6702 /* post operations */
6704 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
6707 } else if (tok
== '.' || tok
== TOK_ARROW
) {
6709 if (tok
== TOK_ARROW
)
6714 /* expect pointer on structure */
6715 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
6716 expect("struct or union");
6720 while ((s
= s
->next
) != NULL
) {
6725 error("field not found");
6726 /* add field offset to pointer */
6727 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
6730 /* change type to field type, and set to lvalue */
6731 vtop
->type
= s
->type
;
6732 /* an array is never an lvalue */
6733 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6734 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6735 /* if bound checking, the referenced pointer must be checked */
6736 if (do_bounds_check
)
6737 vtop
->r
|= VT_MUSTBOUND
;
6740 } else if (tok
== '[') {
6746 } else if (tok
== '(') {
6751 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
6752 /* pointer test (no array accepted) */
6753 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
6754 vtop
->type
= *pointed_type(&vtop
->type
);
6755 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
6759 expect("function pointer");
6762 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
6764 /* get return type */
6766 if (!nocode_wanted
) {
6767 save_regs(0); /* save used temporary registers */
6768 gfunc_start(&gf
, s
->r
);
6771 sa
= s
->next
; /* first parameter */
6772 #ifdef INVERT_FUNC_PARAMS
6776 ParseState saved_parse_state
;
6779 /* read each argument and store it on a stack */
6785 while ((parlevel
> 0 || (tok
!= ')' && tok
!= ',')) &&
6789 else if (tok
== ')')
6791 tok_str_add_tok(&str
);
6794 tok_str_add(&str
, -1); /* end of file added */
6795 tok_str_add(&str
, 0);
6796 s1
= sym_push2(&args
, 0, 0, (int)str
.str
);
6797 s1
->next
= sa
; /* add reference to argument */
6806 /* now generate code in reverse order by reading the stack */
6807 save_parse_state(&saved_parse_state
);
6809 macro_ptr
= (int *)args
->c
;
6813 expect("',' or ')'");
6814 gfunc_param_typed(&gf
, s
, args
->next
);
6816 tok_str_free((int *)args
->c
);
6820 restore_parse_state(&saved_parse_state
);
6823 /* compute first implicit argument if a structure is returned */
6824 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
6825 /* get some space for the returned structure */
6826 size
= type_size(&s
->type
, &align
);
6827 loc
= (loc
- size
) & -align
;
6829 ret
.r
= VT_LOCAL
| VT_LVAL
;
6830 /* pass it as 'int' to avoid structure arg passing
6832 vseti(VT_LOCAL
, loc
);
6841 /* return in register */
6842 if (is_float(ret
.type
.t
)) {
6845 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
6851 #ifndef INVERT_FUNC_PARAMS
6855 gfunc_param_typed(&gf
, s
, sa
);
6865 error("too few arguments to function");
6872 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
6880 static void uneq(void)
6886 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
6887 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
6888 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
6903 static void expr_prod(void)
6908 while (tok
== '*' || tok
== '/' || tok
== '%') {
6916 static void expr_sum(void)
6921 while (tok
== '+' || tok
== '-') {
6929 static void expr_shift(void)
6934 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
6942 static void expr_cmp(void)
6947 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
6948 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
6956 static void expr_cmpeq(void)
6961 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
6969 static void expr_and(void)
6972 while (tok
== '&') {
6979 static void expr_xor(void)
6982 while (tok
== '^') {
6989 static void expr_or(void)
6992 while (tok
== '|') {
6999 /* XXX: fix this mess */
7000 static void expr_land_const(void)
7003 while (tok
== TOK_LAND
) {
7010 /* XXX: fix this mess */
7011 static void expr_lor_const(void)
7014 while (tok
== TOK_LOR
) {
7021 /* only used if non constant */
7022 static void expr_land(void)
7027 if (tok
== TOK_LAND
) {
7031 if (tok
!= TOK_LAND
) {
7041 static void expr_lor(void)
7046 if (tok
== TOK_LOR
) {
7050 if (tok
!= TOK_LOR
) {
7060 /* XXX: better constant handling */
7061 static void expr_eq(void)
7063 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
7065 CType type
, type1
, type2
;
7074 if (tok
== ':' && gnu_ext
) {
7090 if (vtop
!= vstack
) {
7091 /* needed to avoid having different registers saved in
7093 if (is_float(vtop
->type
.t
))
7100 if (tok
== ':' && gnu_ext
) {
7108 sv
= *vtop
; /* save value to handle it later */
7109 vtop
--; /* no vpop so that FP stack is not flushed */
7117 bt1
= t1
& VT_BTYPE
;
7119 bt2
= t2
& VT_BTYPE
;
7120 /* cast operands to correct type according to ISOC rules */
7121 if (is_float(bt1
) || is_float(bt2
)) {
7122 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
7123 type
.t
= VT_LDOUBLE
;
7124 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
7129 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
7130 /* cast to biggest op */
7132 /* convert to unsigned if it does not fit in a long long */
7133 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
7134 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
7135 type
.t
|= VT_UNSIGNED
;
7136 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
7137 /* XXX: test pointer compatibility */
7139 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
7140 /* XXX: test structure compatibility */
7142 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
7143 /* NOTE: as an extension, we accept void on only one side */
7146 /* integer operations */
7148 /* convert to unsigned if it does not fit in an integer */
7149 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
7150 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
7151 type
.t
|= VT_UNSIGNED
;
7154 /* now we convert second operand */
7157 if (is_float(type
.t
)) {
7159 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
7160 /* for long longs, we use fixed registers to avoid having
7161 to handle a complicated move */
7166 /* this is horrible, but we must also convert first
7170 /* put again first value and cast it */
7181 static void gexpr(void)
7192 /* parse an expression and return its type without any side effect. */
7193 static void expr_type(CType
*type
)
7205 /* parse a unary expression and return its type without any side
7207 static void unary_type(CType
*type
)
7219 /* parse a constant expression and return value in vtop. */
7220 static void expr_const1(void)
7229 /* parse an integer constant and return its value. */
7230 static int expr_const(void)
7234 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
7235 expect("constant expression");
7241 /* return the label token if current token is a label, otherwise
7243 static int is_label(void)
7247 /* fast test first */
7248 if (tok
< TOK_UIDENT
)
7250 /* no need to save tokc because tok is an identifier */
7257 unget_tok(last_tok
);
7262 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
7263 int case_reg
, int is_expr
)
7268 /* generate line number info */
7270 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
7271 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
7273 last_line_num
= file
->line_num
;
7277 /* default return value is (void) */
7279 vtop
->type
.t
= VT_VOID
;
7282 if (tok
== TOK_IF
) {
7289 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7291 if (c
== TOK_ELSE
) {
7295 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7296 gsym(d
); /* patch else jmp */
7299 } else if (tok
== TOK_WHILE
) {
7307 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7311 } else if (tok
== '{') {
7315 /* record local declaration stack position */
7317 llabel
= local_label_stack
;
7318 /* handle local labels declarations */
7319 if (tok
== TOK_LABEL
) {
7322 if (tok
< TOK_UIDENT
)
7323 expect("label identifier");
7324 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
7334 while (tok
!= '}') {
7339 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7342 /* pop locally defined labels */
7343 label_pop(&local_label_stack
, llabel
);
7344 /* pop locally defined symbols */
7345 sym_pop(&local_stack
, s
);
7347 } else if (tok
== TOK_RETURN
) {
7351 gen_assign_cast(&func_vt
);
7352 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
7354 /* if returning structure, must copy it to implicit
7355 first pointer arg location */
7358 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
7361 /* copy structure value to pointer */
7363 } else if (is_float(func_vt
.t
)) {
7368 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
7371 rsym
= gjmp(rsym
); /* jmp */
7372 } else if (tok
== TOK_BREAK
) {
7375 error("cannot break");
7376 *bsym
= gjmp(*bsym
);
7379 } else if (tok
== TOK_CONTINUE
) {
7382 error("cannot continue");
7383 *csym
= gjmp(*csym
);
7386 } else if (tok
== TOK_FOR
) {
7413 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7418 if (tok
== TOK_DO
) {
7423 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7434 if (tok
== TOK_SWITCH
) {
7438 /* XXX: other types than integer */
7439 case_reg
= gv(RC_INT
);
7443 b
= gjmp(0); /* jump to first case */
7445 block(&a
, csym
, &b
, &c
, case_reg
, 0);
7446 /* if no default, jmp after switch */
7454 if (tok
== TOK_CASE
) {
7461 if (gnu_ext
&& tok
== TOK_DOTS
) {
7465 warning("empty case range");
7467 /* since a case is like a label, we must skip it with a jmp */
7474 *case_sym
= gtst(1, 0);
7477 *case_sym
= gtst(1, 0);
7481 *case_sym
= gtst(1, *case_sym
);
7485 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7487 if (tok
== TOK_DEFAULT
) {
7493 error("too many 'default'");
7495 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7497 if (tok
== TOK_GOTO
) {
7499 if (tok
== '*' && gnu_ext
) {
7503 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
7506 } else if (tok
>= TOK_UIDENT
) {
7507 s
= label_find(tok
);
7508 /* put forward definition if needed */
7510 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7512 if (s
->r
== LABEL_DECLARED
)
7513 s
->r
= LABEL_FORWARD
;
7515 /* label already defined */
7516 if (s
->r
& LABEL_FORWARD
)
7517 s
->next
= (void *)gjmp((long)s
->next
);
7519 gjmp_addr((long)s
->next
);
7522 expect("label identifier");
7525 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
7533 if (s
->r
== LABEL_DEFINED
)
7534 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
7535 gsym((long)s
->next
);
7536 s
->r
= LABEL_DEFINED
;
7538 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
7540 s
->next
= (void *)ind
;
7541 /* we accept this, but it is a mistake */
7543 warning("deprecated use of label at end of compound statement");
7547 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7550 /* expression case */
7565 /* t is the array or struct type. c is the array or struct
7566 address. cur_index/cur_field is the pointer to the current
7567 value. 'size_only' is true if only size info is needed (only used
7569 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
7570 int *cur_index
, Sym
**cur_field
,
7574 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
7580 if (gnu_ext
&& (l
= is_label()) != 0)
7582 while (tok
== '[' || tok
== '.') {
7584 if (!(type
->t
& VT_ARRAY
))
7585 expect("array type");
7588 index
= expr_const();
7589 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
7590 expect("invalid index");
7591 if (tok
== TOK_DOTS
&& gnu_ext
) {
7593 index_last
= expr_const();
7594 if (index_last
< 0 ||
7595 (s
->c
>= 0 && index_last
>= s
->c
) ||
7597 expect("invalid index");
7603 *cur_index
= index_last
;
7604 type
= pointed_type(type
);
7605 elem_size
= type_size(type
, &align
);
7606 c
+= index
* elem_size
;
7607 /* NOTE: we only support ranges for last designator */
7608 nb_elems
= index_last
- index
+ 1;
7609 if (nb_elems
!= 1) {
7618 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
7619 expect("struct/union type");
7632 /* XXX: fix this mess by using explicit storage field */
7634 type1
.t
|= (type
->t
& ~VT_TYPE
);
7648 if (type
->t
& VT_ARRAY
) {
7650 type
= pointed_type(type
);
7651 c
+= index
* type_size(type
, &align
);
7655 error("too many field init");
7656 /* XXX: fix this mess by using explicit storage field */
7658 type1
.t
|= (type
->t
& ~VT_TYPE
);
7663 decl_initializer(type
, sec
, c
, 0, size_only
);
7665 /* XXX: make it more general */
7666 if (!size_only
&& nb_elems
> 1) {
7667 unsigned long c_end
;
7672 error("range init not supported yet for dynamic storage");
7673 c_end
= c
+ nb_elems
* elem_size
;
7674 if (c_end
> sec
->data_allocated
)
7675 section_realloc(sec
, c_end
);
7676 src
= sec
->data
+ c
;
7678 for(i
= 1; i
< nb_elems
; i
++) {
7680 memcpy(dst
, src
, elem_size
);
7686 #define EXPR_CONST 1
7689 /* store a value or an expression directly in global data or in local array */
7690 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
7691 int v
, int expr_type
)
7693 int saved_global_expr
, bt
, bit_pos
, bit_size
;
7695 unsigned long long bit_mask
;
7702 /* compound literals must be allocated globally in this case */
7703 saved_global_expr
= global_expr
;
7706 global_expr
= saved_global_expr
;
7707 /* NOTE: symbols are accepted */
7708 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
7709 error("initializer element is not constant");
7717 /* XXX: not portable */
7718 /* XXX: generate error if incorrect relocation */
7719 gen_assign_cast(type
);
7720 bt
= type
->t
& VT_BTYPE
;
7721 ptr
= sec
->data
+ c
;
7722 /* XXX: make code faster ? */
7723 if (!(type
->t
& VT_BITFIELD
)) {
7728 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
7729 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
7730 bit_mask
= (1LL << bit_size
) - 1;
7732 if ((vtop
->r
& VT_SYM
) &&
7738 (bt
== VT_INT
&& bit_size
!= 32)))
7739 error("initializer element is not computable at load time");
7742 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7745 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7748 *(double *)ptr
= vtop
->c
.d
;
7751 *(long double *)ptr
= vtop
->c
.ld
;
7754 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
7757 if (vtop
->r
& VT_SYM
) {
7758 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
7760 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7765 vset(type
, VT_LOCAL
, c
);
7772 /* put zeros for variable based init */
7773 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
7778 /* nothing to do because globals are already set to zero */
7780 gfunc_start(&gf
, FUNC_CDECL
);
7787 vpush_global_sym(&func_old_type
, TOK_memset
);
7792 /* 't' contains the type and storage info. 'c' is the offset of the
7793 object in section 'sec'. If 'sec' is NULL, it means stack based
7794 allocation. 'first' is true if array '{' must be read (multi
7795 dimension implicit array init handling). 'size_only' is true if
7796 size only evaluation is wanted (only for arrays). */
7797 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
7798 int first
, int size_only
)
7800 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
7801 int size1
, align1
, expr_type
;
7805 if (type
->t
& VT_ARRAY
) {
7809 t1
= pointed_type(type
);
7810 size1
= type_size(t1
, &align1
);
7813 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
7819 /* only parse strings here if correct type (otherwise: handle
7820 them as ((w)char *) expressions */
7821 if ((tok
== TOK_LSTR
&&
7822 (t1
->t
& VT_BTYPE
) == VT_INT
) ||
7824 (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
7825 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
7830 /* compute maximum number of chars wanted */
7832 cstr_len
= cstr
->size
;
7834 cstr_len
= cstr
->size
/ sizeof(int);
7837 if (n
>= 0 && nb
> (n
- array_length
))
7838 nb
= n
- array_length
;
7841 warning("initializer-string for array is too long");
7842 /* in order to go faster for common case (char
7843 string in global variable, we handle it
7845 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
7846 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
7850 ch
= ((unsigned char *)cstr
->data
)[i
];
7852 ch
= ((int *)cstr
->data
)[i
];
7853 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
7861 /* only add trailing zero if enough storage (no
7862 warning in this case since it is standard) */
7863 if (n
< 0 || array_length
< n
) {
7865 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
7871 while (tok
!= '}') {
7872 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
7873 if (n
>= 0 && index
>= n
)
7874 error("index too large");
7875 /* must put zero in holes (note that doing it that way
7876 ensures that it even works with designators) */
7877 if (!size_only
&& array_length
< index
) {
7878 init_putz(t1
, sec
, c
+ array_length
* size1
,
7879 (index
- array_length
) * size1
);
7882 if (index
> array_length
)
7883 array_length
= index
;
7884 /* special test for multi dimensional arrays (may not
7885 be strictly correct if designators are used at the
7887 if (index
>= n
&& no_oblock
)
7896 /* put zeros at the end */
7897 if (!size_only
&& n
>= 0 && array_length
< n
) {
7898 init_putz(t1
, sec
, c
+ array_length
* size1
,
7899 (n
- array_length
) * size1
);
7901 /* patch type size if needed */
7903 s
->c
= array_length
;
7904 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
7905 (sec
|| !first
|| tok
== '{')) {
7908 /* NOTE: the previous test is a specific case for automatic
7909 struct/union init */
7910 /* XXX: union needs only one init */
7912 /* XXX: this test is incorrect for local initializers
7913 beginning with ( without {. It would be much more difficult
7914 to do it correctly (ideally, the expression parser should
7915 be used in all cases) */
7921 while (tok
== '(') {
7925 if (!parse_btype(&type1
, &ad1
))
7927 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
7928 if (!is_compatible_types(type
, &type1
))
7929 error("invalid type for cast");
7933 if (first
|| tok
== '{') {
7942 while (tok
!= '}') {
7943 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
7945 if (!size_only
&& array_length
< index
) {
7946 init_putz(type
, sec
, c
+ array_length
,
7947 index
- array_length
);
7949 index
= index
+ type_size(&f
->type
, &align1
);
7950 if (index
> array_length
)
7951 array_length
= index
;
7953 if (no_oblock
&& f
== NULL
)
7959 /* put zeros at the end */
7960 if (!size_only
&& array_length
< n
) {
7961 init_putz(type
, sec
, c
+ array_length
,
7970 } else if (tok
== '{') {
7972 decl_initializer(type
, sec
, c
, first
, size_only
);
7974 } else if (size_only
) {
7975 /* just skip expression */
7977 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
7981 else if (tok
== ')')
7986 /* currently, we always use constant expression for globals
7987 (may change for scripting case) */
7988 expr_type
= EXPR_CONST
;
7990 expr_type
= EXPR_ANY
;
7991 init_putv(type
, sec
, c
, 0, expr_type
);
7995 /* parse an initializer for type 't' if 'has_init' is non zero, and
7996 allocate space in local or global data space ('r' is either
7997 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
7998 variable 'v' of scope 'scope' is declared before initializers are
7999 parsed. If 'v' is zero, then a reference to the new object is put
8000 in the value stack. If 'has_init' is 2, a special parsing is done
8001 to handle string constants. */
8002 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
8003 int has_init
, int v
, int scope
)
8005 int size
, align
, addr
, data_offset
;
8007 ParseState saved_parse_state
;
8008 TokenString init_str
;
8011 size
= type_size(type
, &align
);
8012 /* If unknown size, we must evaluate it before
8013 evaluating initializers because
8014 initializers can generate global data too
8015 (e.g. string pointers or ISOC99 compound
8016 literals). It also simplifies local
8017 initializers handling */
8018 tok_str_new(&init_str
);
8021 error("unknown type size");
8022 /* get all init string */
8023 if (has_init
== 2) {
8024 /* only get strings */
8025 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8026 tok_str_add_tok(&init_str
);
8031 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
8033 error("unexpected end of file in initializer");
8034 tok_str_add_tok(&init_str
);
8037 else if (tok
== '}') {
8045 tok_str_add(&init_str
, -1);
8046 tok_str_add(&init_str
, 0);
8049 save_parse_state(&saved_parse_state
);
8051 macro_ptr
= init_str
.str
;
8053 decl_initializer(type
, NULL
, 0, 1, 1);
8054 /* prepare second initializer parsing */
8055 macro_ptr
= init_str
.str
;
8058 /* if still unknown size, error */
8059 size
= type_size(type
, &align
);
8061 error("unknown type size");
8063 /* take into account specified alignment if bigger */
8064 if (ad
->aligned
> align
)
8065 align
= ad
->aligned
;
8066 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
8068 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
8070 loc
= (loc
- size
) & -align
;
8072 /* handles bounds */
8073 /* XXX: currently, since we do only one pass, we cannot track
8074 '&' operators, so we add only arrays */
8075 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
8076 unsigned long *bounds_ptr
;
8077 /* add padding between regions */
8079 /* then add local bound info */
8080 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
8081 bounds_ptr
[0] = addr
;
8082 bounds_ptr
[1] = size
;
8085 /* local variable */
8086 sym_push(v
, type
, r
, addr
);
8088 /* push local reference */
8089 vset(type
, r
, addr
);
8095 if (v
&& scope
== VT_CONST
) {
8096 /* see if the symbol was already defined */
8099 if (!is_compatible_types(&sym
->type
, type
))
8100 error("incompatible types for redefinition of '%s'",
8101 get_tok_str(v
, NULL
));
8102 if (sym
->type
.t
& VT_EXTERN
) {
8103 /* if the variable is extern, it was not allocated */
8104 sym
->type
.t
&= ~VT_EXTERN
;
8106 /* we accept several definitions of the same
8107 global variable. this is tricky, because we
8108 must play with the SHN_COMMON type of the symbol */
8109 /* XXX: should check if the variable was already
8110 initialized. It is incorrect to initialized it
8112 /* no init data, we won't add more to the symbol */
8119 /* allocate symbol in corresponding section */
8126 data_offset
= sec
->data_offset
;
8127 data_offset
= (data_offset
+ align
- 1) & -align
;
8129 /* very important to increment global pointer at this time
8130 because initializers themselves can create new initializers */
8131 data_offset
+= size
;
8132 /* add padding if bound check */
8133 if (do_bounds_check
)
8135 sec
->data_offset
= data_offset
;
8136 /* allocate section space to put the data */
8137 if (sec
->sh_type
!= SHT_NOBITS
&&
8138 data_offset
> sec
->data_allocated
)
8139 section_realloc(sec
, data_offset
);
8141 addr
= 0; /* avoid warning */
8145 if (scope
== VT_CONST
) {
8150 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
8152 /* update symbol definition */
8154 put_extern_sym(sym
, sec
, addr
, size
);
8157 /* put a common area */
8158 put_extern_sym(sym
, NULL
, align
, size
);
8159 /* XXX: find a nicer way */
8160 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
8161 esym
->st_shndx
= SHN_COMMON
;
8166 /* push global reference */
8167 sym
= get_sym_ref(type
, sec
, addr
, size
);
8169 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
8173 /* handles bounds now because the symbol must be defined
8174 before for the relocation */
8175 if (do_bounds_check
) {
8176 unsigned long *bounds_ptr
;
8178 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
8179 /* then add global bound info */
8180 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
8181 bounds_ptr
[0] = 0; /* relocated */
8182 bounds_ptr
[1] = size
;
8186 decl_initializer(type
, sec
, addr
, 1, 0);
8187 /* restore parse state if needed */
8189 tok_str_free(init_str
.str
);
8190 restore_parse_state(&saved_parse_state
);
8196 void put_func_debug(Sym
*sym
)
8201 /* XXX: we put here a dummy type */
8202 snprintf(buf
, sizeof(buf
), "%s:%c1",
8203 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
8204 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
8205 cur_text_section
, sym
->c
);
8210 /* not finished : try to put some local vars in registers */
8211 //#define CONFIG_REG_VARS
8213 #ifdef CONFIG_REG_VARS
8214 void add_var_ref(int t
)
8216 printf("%s:%d: &%s\n",
8217 file
->filename
, file
->line_num
,
8218 get_tok_str(t
, NULL
));
8221 /* first pass on a function with heuristic to extract variable usage
8222 and pointer references to local variables for register allocation */
8223 void analyse_function(void)
8230 /* any symbol coming after '&' is considered as being a
8231 variable whose reference is taken. It is highly unaccurate
8232 but it is difficult to do better without a complete parse */
8235 /* if '& number', then no need to examine next tokens */
8236 if (tok
== TOK_CINT
||
8238 tok
== TOK_CLLONG
||
8239 tok
== TOK_CULLONG
) {
8241 } else if (tok
>= TOK_UIDENT
) {
8242 /* if '& ident [' or '& ident ->', then ident address
8246 if (tok
!= '[' && tok
!= TOK_ARROW
)
8250 while (tok
!= '}' && tok
!= ';' &&
8251 !((tok
== ',' || tok
== ')') && level
== 0)) {
8252 if (tok
>= TOK_UIDENT
) {
8254 } else if (tok
== '(') {
8256 } else if (tok
== ')') {
8269 /* parse an old style function declaration list */
8270 /* XXX: check multiple parameter */
8271 static void func_decl_list(Sym
*func_sym
)
8278 /* parse each declaration */
8279 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
8280 if (!parse_btype(&btype
, &ad
))
8281 expect("declaration list");
8282 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8283 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8285 /* we accept no variable after */
8289 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8290 /* find parameter in function parameter list */
8293 if ((s
->v
& ~SYM_FIELD
) == v
)
8297 error("declaration for parameter '%s' but no such parameter",
8298 get_tok_str(v
, NULL
));
8300 /* check that no storage specifier except 'register' was given */
8301 if (type
.t
& VT_STORAGE
)
8302 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
8303 convert_parameter_type(&type
);
8304 /* we can add the type (NOTE: it could be local to the function) */
8306 /* accept other parameters */
8317 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
8318 static void decl(int l
)
8326 if (!parse_btype(&btype
, &ad
)) {
8327 /* skip redundant ';' */
8328 /* XXX: find more elegant solution */
8333 /* special test for old K&R protos without explicit int
8334 type. Only accepted when defining global data */
8335 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
8339 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8340 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8342 /* we accept no variable after */
8346 while (1) { /* iterate thru each declaration */
8348 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8352 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
8353 printf("type = '%s'\n", buf
);
8356 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8357 /* if old style function prototype, we accept a
8360 if (sym
->c
== FUNC_OLD
)
8361 func_decl_list(sym
);
8365 #ifdef CONFIG_REG_VARS
8366 TokenString func_str
;
8367 ParseState saved_parse_state
;
8372 error("cannot use local functions");
8373 if (!(type
.t
& VT_FUNC
))
8374 expect("function definition");
8375 /* XXX: cannot do better now: convert extern line to static inline */
8376 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
8377 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
8379 #ifdef CONFIG_REG_VARS
8380 /* parse all function code and record it */
8382 tok_str_new(&func_str
);
8388 error("unexpected end of file");
8389 tok_str_add_tok(&func_str
);
8394 } else if (t
== '}') {
8396 if (block_level
== 0)
8400 tok_str_add(&func_str
, -1);
8401 tok_str_add(&func_str
, 0);
8403 save_parse_state(&saved_parse_state
);
8405 macro_ptr
= func_str
.str
;
8410 /* compute text section */
8411 cur_text_section
= ad
.section
;
8412 if (!cur_text_section
)
8413 cur_text_section
= text_section
;
8414 ind
= cur_text_section
->data_offset
;
8415 funcname
= get_tok_str(v
, NULL
);
8418 /* if symbol is already defined, then put complete type */
8421 /* put function symbol */
8422 sym
= global_identifier_push(v
, type
.t
, 0);
8423 sym
->type
.ref
= type
.ref
;
8425 /* NOTE: we patch the symbol size later */
8426 put_extern_sym(sym
, cur_text_section
, ind
, 0);
8428 sym
->r
= VT_SYM
| VT_CONST
;
8429 /* put debug symbol */
8431 put_func_debug(sym
);
8432 /* push a dummy symbol to enable local sym storage */
8433 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
8434 gfunc_prolog(&type
);
8437 #ifdef CONFIG_REG_VARS
8438 macro_ptr
= func_str
.str
;
8441 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
8444 cur_text_section
->data_offset
= ind
;
8445 label_pop(&global_label_stack
, NULL
);
8446 sym_pop(&local_stack
, NULL
); /* reset local stack */
8447 /* end of function */
8448 /* patch symbol size */
8449 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_size
=
8452 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
8454 funcname
= ""; /* for safety */
8455 func_vt
.t
= VT_VOID
; /* for safety */
8456 ind
= 0; /* for safety */
8458 #ifdef CONFIG_REG_VARS
8459 tok_str_free(func_str
.str
);
8460 restore_parse_state(&saved_parse_state
);
8464 if (btype
.t
& VT_TYPEDEF
) {
8465 /* save typedefed type */
8466 /* XXX: test storage specifiers ? */
8467 sym
= sym_push(v
, &type
, 0, 0);
8468 sym
->type
.t
|= VT_TYPEDEF
;
8469 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8470 /* external function definition */
8471 external_sym(v
, &type
, 0);
8473 /* not lvalue if array */
8475 if (!(type
.t
& VT_ARRAY
))
8476 r
|= lvalue_type(type
.t
);
8477 has_init
= (tok
== '=');
8478 if ((btype
.t
& VT_EXTERN
) ||
8479 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
8480 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
8481 /* external variable */
8482 /* NOTE: as GCC, uninitialized global static
8483 arrays of null size are considered as
8485 external_sym(v
, &type
, r
);
8487 if (type
.t
& VT_STATIC
)
8493 decl_initializer_alloc(&type
, &ad
, r
,
8507 /* better than nothing, but needs extension to handle '-E' option
8509 static void preprocess_init(TCCState
*s1
)
8511 s1
->include_stack_ptr
= s1
->include_stack
;
8512 /* XXX: move that before to avoid having to initialize
8513 file->ifdef_stack_ptr ? */
8514 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
8515 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
8517 /* XXX: not ANSI compliant: bound checking says error */
8521 /* compile the C file opened in 'file'. Return non zero if errors. */
8522 static int tcc_compile(TCCState
*s1
)
8526 volatile int section_sym
;
8529 printf("%s: **** new file\n", file
->filename
);
8531 preprocess_init(s1
);
8534 anon_sym
= SYM_FIRST_ANOM
;
8536 /* file info: full path + filename */
8537 section_sym
= 0; /* avoid warning */
8539 section_sym
= put_elf_sym(symtab_section
, 0, 0,
8540 ELF32_ST_INFO(STB_LOCAL
, STT_SECTION
), 0,
8541 text_section
->sh_num
, NULL
);
8542 getcwd(buf
, sizeof(buf
));
8543 pstrcat(buf
, sizeof(buf
), "/");
8544 put_stabs_r(buf
, N_SO
, 0, 0,
8545 text_section
->data_offset
, text_section
, section_sym
);
8546 put_stabs_r(file
->filename
, N_SO
, 0, 0,
8547 text_section
->data_offset
, text_section
, section_sym
);
8549 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
8550 symbols can be safely used */
8551 put_elf_sym(symtab_section
, 0, 0,
8552 ELF32_ST_INFO(STB_LOCAL
, STT_FILE
), 0,
8553 SHN_ABS
, file
->filename
);
8555 /* define some often used types */
8556 int_type
.t
= VT_INT
;
8558 char_pointer_type
.t
= VT_BYTE
;
8559 mk_pointer(&char_pointer_type
);
8561 func_old_type
.t
= VT_FUNC
;
8562 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
8565 /* define 'void *alloca(unsigned int)' builtin function */
8570 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
8571 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
8574 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
8578 define_start
= define_stack
;
8580 if (setjmp(s1
->error_jmp_buf
) == 0) {
8582 s1
->error_set_jmp_enabled
= 1;
8584 ch
= file
->buf_ptr
[0];
8585 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
8586 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
8590 expect("declaration");
8592 /* end of translation unit info */
8594 put_stabs_r(NULL
, N_SO
, 0, 0,
8595 text_section
->data_offset
, text_section
, section_sym
);
8598 s1
->error_set_jmp_enabled
= 0;
8600 /* reset define stack, but leave -Dsymbols (may be incorrect if
8601 they are undefined) */
8602 free_defines(define_start
);
8604 sym_pop(&global_stack
, NULL
);
8606 return s1
->nb_errors
!= 0 ? -1 : 0;
8610 int tcc_compile_string(TCCState
*s
, const char *str
)
8612 BufferedFile bf1
, *bf
= &bf1
;
8616 /* init file structure */
8618 /* XXX: avoid copying */
8620 buf
= tcc_malloc(len
+ 1);
8623 memcpy(buf
, str
, len
);
8626 bf
->buf_end
= buf
+ len
;
8627 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
8631 ret
= tcc_compile(s
);
8635 /* currently, no need to close */
8640 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
8641 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
8643 BufferedFile bf1
, *bf
= &bf1
;
8645 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
8646 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
8650 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
8652 /* init file structure */
8654 bf
->buf_ptr
= bf
->buffer
;
8655 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
8656 *bf
->buf_end
= CH_EOB
;
8657 bf
->filename
[0] = '\0';
8661 s1
->include_stack_ptr
= s1
->include_stack
;
8663 /* parse with define parser */
8664 ch
= file
->buf_ptr
[0];
8670 /* undefine a preprocessor symbol */
8671 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
8675 ts
= tok_alloc(sym
, strlen(sym
));
8676 s
= define_find(ts
->tok
);
8677 /* undefine symbol by putting an invalid name */
8682 #ifdef CONFIG_TCC_ASM
8684 #include "i386-asm.c"
8688 static void asm_instr(void)
8690 error("inline asm() not supported");
8696 /* print the position in the source file of PC value 'pc' by reading
8697 the stabs debug information */
8698 static void rt_printline(unsigned long wanted_pc
)
8700 Stab_Sym
*sym
, *sym_end
;
8701 char func_name
[128], last_func_name
[128];
8702 unsigned long func_addr
, last_pc
, pc
;
8703 const char *incl_files
[INCLUDE_STACK_SIZE
];
8704 int incl_index
, len
, last_line_num
, i
;
8705 const char *str
, *p
;
8707 fprintf(stderr
, "0x%08lx:", wanted_pc
);
8709 func_name
[0] = '\0';
8712 last_func_name
[0] = '\0';
8713 last_pc
= 0xffffffff;
8715 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
8716 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
8717 while (sym
< sym_end
) {
8718 switch(sym
->n_type
) {
8719 /* function start or end */
8721 if (sym
->n_strx
== 0) {
8722 /* we test if between last line and end of function */
8723 pc
= sym
->n_value
+ func_addr
;
8724 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
8726 func_name
[0] = '\0';
8729 str
= stabstr_section
->data
+ sym
->n_strx
;
8730 p
= strchr(str
, ':');
8732 pstrcpy(func_name
, sizeof(func_name
), str
);
8735 if (len
> sizeof(func_name
) - 1)
8736 len
= sizeof(func_name
) - 1;
8737 memcpy(func_name
, str
, len
);
8738 func_name
[len
] = '\0';
8740 func_addr
= sym
->n_value
;
8743 /* line number info */
8745 pc
= sym
->n_value
+ func_addr
;
8746 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
8749 last_line_num
= sym
->n_desc
;
8751 strcpy(last_func_name
, func_name
);
8755 str
= stabstr_section
->data
+ sym
->n_strx
;
8757 if (incl_index
< INCLUDE_STACK_SIZE
) {
8758 incl_files
[incl_index
++] = str
;
8766 if (sym
->n_strx
== 0) {
8767 incl_index
= 0; /* end of translation unit */
8769 str
= stabstr_section
->data
+ sym
->n_strx
;
8770 /* do not add path */
8772 if (len
> 0 && str
[len
- 1] != '/')
8780 /* second pass: we try symtab symbols (no line number info) */
8783 Elf32_Sym
*sym
, *sym_end
;
8786 sym_end
= (Elf32_Sym
*)(symtab_section
->data
+ symtab_section
->data_offset
);
8787 for(sym
= (Elf32_Sym
*)symtab_section
->data
+ 1;
8790 type
= ELF32_ST_TYPE(sym
->st_info
);
8791 if (type
== STT_FUNC
) {
8792 if (wanted_pc
>= sym
->st_value
&&
8793 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
8794 pstrcpy(last_func_name
, sizeof(last_func_name
),
8795 strtab_section
->data
+ sym
->st_name
);
8801 /* did not find any info: */
8802 fprintf(stderr
, " ???\n");
8805 if (last_func_name
[0] != '\0') {
8806 fprintf(stderr
, " %s()", last_func_name
);
8808 if (incl_index
> 0) {
8809 fprintf(stderr
, " (%s:%d",
8810 incl_files
[incl_index
- 1], last_line_num
);
8811 for(i
= incl_index
- 2; i
>= 0; i
--)
8812 fprintf(stderr
, ", included from %s", incl_files
[i
]);
8813 fprintf(stderr
, ")");
8815 fprintf(stderr
, "\n");
8822 /* fix for glibc 2.1 */
8828 /* return the PC at frame level 'level'. Return non zero if not found */
8829 static int rt_get_caller_pc(unsigned long *paddr
,
8830 ucontext_t
*uc
, int level
)
8837 *paddr
= uc
->uc_mcontext
.mc_eip
;
8839 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
8844 fp
= uc
->uc_mcontext
.mc_ebp
;
8846 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
8848 for(i
=1;i
<level
;i
++) {
8849 /* XXX: check address validity with program info */
8850 if (fp
<= 0x1000 || fp
>= 0xc0000000)
8852 fp
= ((unsigned long *)fp
)[0];
8854 *paddr
= ((unsigned long *)fp
)[1];
8859 #error add arch specific rt_get_caller_pc()
8862 /* emit a run time error at position 'pc' */
8863 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
8870 fprintf(stderr
, "Runtime error: ");
8871 vfprintf(stderr
, fmt
, ap
);
8872 fprintf(stderr
, "\n");
8873 for(i
=0;i
<num_callers
;i
++) {
8874 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
8877 fprintf(stderr
, "at ");
8879 fprintf(stderr
, "by ");
8886 /* signal handler for fatal errors */
8887 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
8889 ucontext_t
*uc
= puc
;
8893 switch(siginf
->si_code
) {
8896 rt_error(uc
, "division by zero");
8899 rt_error(uc
, "floating point exception");
8905 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
8906 rt_error(uc
, *rt_bound_error_msg
);
8908 rt_error(uc
, "dereferencing invalid pointer");
8911 rt_error(uc
, "illegal instruction");
8914 rt_error(uc
, "abort() called");
8917 rt_error(uc
, "caught signal %d", signum
);
8924 /* do all relocations (needed before using tcc_get_symbol()) */
8925 int tcc_relocate(TCCState
*s1
)
8932 tcc_add_runtime(s1
);
8934 relocate_common_syms();
8936 /* compute relocation address : section are relocated in place. We
8937 also alloc the bss space */
8938 for(i
= 1; i
< s1
->nb_sections
; i
++) {
8939 s
= s1
->sections
[i
];
8940 if (s
->sh_flags
& SHF_ALLOC
) {
8941 if (s
->sh_type
== SHT_NOBITS
)
8942 s
->data
= tcc_mallocz(s
->data_offset
);
8943 s
->sh_addr
= (unsigned long)s
->data
;
8947 relocate_syms(s1
, 1);
8949 if (s1
->nb_errors
!= 0)
8952 /* relocate each section */
8953 for(i
= 1; i
< s1
->nb_sections
; i
++) {
8954 s
= s1
->sections
[i
];
8956 relocate_section(s1
, s
);
8961 /* launch the compiled program with the given arguments */
8962 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
8964 int (*prog_main
)(int, char **);
8966 if (tcc_relocate(s1
) < 0)
8969 prog_main
= tcc_get_symbol(s1
, "main");
8973 error("debug mode currently not available for Windows");
8975 struct sigaction sigact
;
8976 /* install TCC signal handlers to print debug info on fatal
8978 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
8979 sigact
.sa_sigaction
= sig_error
;
8980 sigemptyset(&sigact
.sa_mask
);
8981 sigaction(SIGFPE
, &sigact
, NULL
);
8982 sigaction(SIGILL
, &sigact
, NULL
);
8983 sigaction(SIGSEGV
, &sigact
, NULL
);
8984 sigaction(SIGBUS
, &sigact
, NULL
);
8985 sigaction(SIGABRT
, &sigact
, NULL
);
8989 #ifdef CONFIG_TCC_BCHECK
8990 if (do_bounds_check
) {
8991 void (*bound_init
)(void);
8993 /* set error function */
8994 rt_bound_error_msg
= (void *)tcc_get_symbol(s1
, "__bound_error_msg");
8996 /* XXX: use .init section so that it also work in binary ? */
8997 bound_init
= (void *)tcc_get_symbol(s1
, "__bound_init");
9001 return (*prog_main
)(argc
, argv
);
9004 TCCState
*tcc_new(void)
9011 s
= tcc_mallocz(sizeof(TCCState
));
9015 s
->output_type
= TCC_OUTPUT_MEMORY
;
9017 /* init isid table */
9019 isidnum_table
[i
] = isid(i
) || isnum(i
);
9021 /* add all tokens */
9023 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
9025 tok_ident
= TOK_IDENT
;
9034 ts
= tok_alloc(p
, r
- p
- 1);
9038 /* we add dummy defines for some special macros to speed up tests
9039 and to have working defined() */
9040 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
9041 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
9042 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
9043 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
9045 /* standard defines */
9046 tcc_define_symbol(s
, "__STDC__", NULL
);
9047 #if defined(TCC_TARGET_I386)
9048 tcc_define_symbol(s
, "__i386__", NULL
);
9051 tcc_define_symbol(s
, "__linux__", NULL
);
9052 tcc_define_symbol(s
, "linux", NULL
);
9054 /* tiny C specific defines */
9055 tcc_define_symbol(s
, "__TINYC__", NULL
);
9057 /* tiny C & gcc defines */
9058 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
9059 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
9060 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
9062 /* default library paths */
9063 tcc_add_library_path(s
, "/usr/local/lib");
9064 tcc_add_library_path(s
, "/usr/lib");
9065 tcc_add_library_path(s
, "/lib");
9067 /* no section zero */
9068 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
9070 /* create standard sections */
9071 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
9072 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
9073 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
9075 /* symbols are always generated for linking stage */
9076 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
9078 ".hashtab", SHF_PRIVATE
);
9079 strtab_section
= symtab_section
->link
;
9081 /* private symbol table for dynamic symbols */
9082 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
9084 ".dynhashtab", SHF_PRIVATE
);
9088 void tcc_delete(TCCState
*s1
)
9092 /* free -D defines */
9096 n
= tok_ident
- TOK_IDENT
;
9097 for(i
= 0; i
< n
; i
++)
9098 tcc_free(table_ident
[i
]);
9099 tcc_free(table_ident
);
9101 /* free all sections */
9103 free_section(symtab_section
->hash
);
9105 free_section(s1
->dynsymtab_section
->hash
);
9106 free_section(s1
->dynsymtab_section
->link
);
9107 free_section(s1
->dynsymtab_section
);
9109 for(i
= 1; i
< s1
->nb_sections
; i
++)
9110 free_section(s1
->sections
[i
]);
9111 tcc_free(s1
->sections
);
9113 /* free loaded dlls array */
9114 for(i
= 0; i
< s1
->nb_loaded_dlls
; i
++)
9115 tcc_free(s1
->loaded_dlls
[i
]);
9116 tcc_free(s1
->loaded_dlls
);
9119 for(i
= 0; i
< s1
->nb_library_paths
; i
++)
9120 tcc_free(s1
->library_paths
[i
]);
9121 tcc_free(s1
->library_paths
);
9123 /* cached includes */
9124 for(i
= 0; i
< s1
->nb_cached_includes
; i
++)
9125 tcc_free(s1
->cached_includes
[i
]);
9126 tcc_free(s1
->cached_includes
);
9128 for(i
= 0; i
< s1
->nb_include_paths
; i
++)
9129 tcc_free(s1
->include_paths
[i
]);
9130 tcc_free(s1
->include_paths
);
9132 for(i
= 0; i
< s1
->nb_sysinclude_paths
; i
++)
9133 tcc_free(s1
->sysinclude_paths
[i
]);
9134 tcc_free(s1
->sysinclude_paths
);
9139 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
9143 pathname1
= tcc_strdup(pathname
);
9144 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
9148 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
9152 pathname1
= tcc_strdup(pathname
);
9153 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
9157 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
9159 const char *ext
, *filename1
;
9162 BufferedFile
*saved_file
;
9164 /* find source file type with extension */
9165 filename1
= strrchr(filename
, '/');
9169 filename1
= filename
;
9170 ext
= strrchr(filename1
, '.');
9176 file
= tcc_open(s1
, filename
);
9178 if (flags
& AFF_PRINT_ERROR
) {
9179 error_noabort("file '%s' not found", filename
);
9185 if (!ext
|| !strcmp(ext
, "c")) {
9186 /* C file assumed */
9187 ret
= tcc_compile(s1
);
9189 #ifdef CONFIG_TCC_ASM
9190 if (!strcmp(ext
, "S")) {
9191 /* preprocessed assembler */
9192 ret
= tcc_assemble(s1
, 1);
9193 } else if (!strcmp(ext
, "s")) {
9194 /* non preprocessed assembler */
9195 ret
= tcc_assemble(s1
, 0);
9200 /* assume executable format: auto guess file type */
9201 if (read(fd
, &ehdr
, sizeof(ehdr
)) != sizeof(ehdr
)) {
9202 error_noabort("could not read header");
9205 lseek(fd
, 0, SEEK_SET
);
9207 if (ehdr
.e_ident
[0] == ELFMAG0
&&
9208 ehdr
.e_ident
[1] == ELFMAG1
&&
9209 ehdr
.e_ident
[2] == ELFMAG2
&&
9210 ehdr
.e_ident
[3] == ELFMAG3
) {
9211 file
->line_num
= 0; /* do not display line number if error */
9212 if (ehdr
.e_type
== ET_REL
) {
9213 ret
= tcc_load_object_file(s1
, fd
, 0);
9214 } else if (ehdr
.e_type
== ET_DYN
) {
9215 ret
= tcc_load_dll(s1
, fd
, filename
,
9216 (flags
& AFF_REFERENCED_DLL
) != 0);
9218 error_noabort("unrecognized ELF file");
9221 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
9222 file
->line_num
= 0; /* do not display line number if error */
9223 ret
= tcc_load_archive(s1
, fd
);
9225 /* as GNU ld, consider it is an ld script if not recognized */
9226 ret
= tcc_load_ldscript(s1
);
9228 error_noabort("unrecognized file type");
9243 int tcc_add_file(TCCState
*s
, const char *filename
)
9245 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
9248 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
9252 pathname1
= tcc_strdup(pathname
);
9253 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
9257 /* find and load a dll. Return non zero if not found */
9258 /* XXX: add '-rpath' option support ? */
9259 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
9264 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9265 snprintf(buf
, sizeof(buf
), "%s/%s",
9266 s
->library_paths
[i
], filename
);
9267 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
9273 /* the library name is the same as the argument of the '-l' option */
9274 int tcc_add_library(TCCState
*s
, const char *libraryname
)
9280 /* first we look for the dynamic library if not static linking */
9281 if (!s
->static_link
) {
9282 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
9283 /* if we output to memory, then we simply we dlopen(). */
9284 if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
9285 /* Since the libc is already loaded, we don't need to load it again */
9286 if (!strcmp(libraryname
, "c"))
9288 h
= dlopen(buf
, RTLD_GLOBAL
| RTLD_LAZY
);
9292 if (tcc_add_dll(s
, buf
, 0) == 0)
9297 /* then we look for the static library */
9298 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9299 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
9300 s
->library_paths
[i
], libraryname
);
9301 if (tcc_add_file_internal(s
, buf
, 0) == 0)
9307 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
9309 add_elf_sym(symtab_section
, val
, 0,
9310 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
),
9315 int tcc_set_output_type(TCCState
*s
, int output_type
)
9319 s
->output_type
= output_type
;
9322 /* default include paths */
9323 /* XXX: reverse order needed if -isystem support */
9324 tcc_add_sysinclude_path(s
, "/usr/local/include");
9325 tcc_add_sysinclude_path(s
, "/usr/include");
9326 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
9327 tcc_add_sysinclude_path(s
, buf
);
9330 /* if bound checking, then add corresponding sections */
9331 #ifdef CONFIG_TCC_BCHECK
9332 if (do_bounds_check
) {
9334 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
9335 /* create bounds sections */
9336 bounds_section
= new_section(s
, ".bounds",
9337 SHT_PROGBITS
, SHF_ALLOC
);
9338 lbounds_section
= new_section(s
, ".lbounds",
9339 SHT_PROGBITS
, SHF_ALLOC
);
9343 /* add debug sections */
9346 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
9347 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
9348 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
9349 put_elf_str(stabstr_section
, "");
9350 stab_section
->link
= stabstr_section
;
9351 /* put first entry */
9352 put_stabs("", 0, 0, 0, 0);
9355 /* add libc crt1/crti objects */
9356 if (output_type
== TCC_OUTPUT_EXE
||
9357 output_type
== TCC_OUTPUT_DLL
) {
9358 if (output_type
!= TCC_OUTPUT_DLL
)
9359 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
9360 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
9365 #if !defined(LIBTCC)
9367 static int64_t getclock_us(void)
9372 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
9375 gettimeofday(&tv
, NULL
);
9376 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
9382 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001, 2002 Fabrice Bellard\n"
9383 "usage: tcc [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
9384 " [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]\n"
9385 " [--] infile1 [infile2... --] [infile_args...]\n"
9387 "General options:\n"
9388 " -c compile only - generate an object file\n"
9389 " -o outfile set output filename\n"
9390 " -- allows multiples input files if no -o option given. Also\n"
9391 " separate input files from runtime arguments\n"
9392 " -Bdir set tcc internal library path\n"
9393 " -bench output compilation statistics\n"
9394 "Preprocessor options:\n"
9395 " -Idir add include path 'dir'\n"
9396 " -Dsym[=val] define 'sym' with value 'val'\n"
9397 " -Usym undefine 'sym'\n"
9399 " -Ldir add library path 'dir'\n"
9400 " -llib link with dynamic or static library 'lib'\n"
9401 " -shared generate a shared library\n"
9402 " -static static linking\n"
9403 " -r relocatable output\n"
9404 "Debugger options:\n"
9405 " -g generate runtime debug info\n"
9406 #ifdef CONFIG_TCC_BCHECK
9407 " -b compile with built-in memory and bounds checker (implies -g)\n"
9409 " -bt N show N callers in stack traces\n"
9413 #define TCC_OPTION_HAS_ARG 0x0001
9414 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
9416 typedef struct TCCOption
{
9444 TCC_OPTION_nostdinc
,
9445 TCC_OPTION_print_search_dirs
,
9446 TCC_OPTION_rdynamic
,
9449 static const TCCOption tcc_options
[] = {
9450 { "h", TCC_OPTION_HELP
, 0 },
9451 { "?", TCC_OPTION_HELP
, 0 },
9452 { "-", TCC_OPTION_MARKER
, 0 },
9453 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
9454 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
9455 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
9456 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
9457 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
9458 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9459 { "bench", TCC_OPTION_bench
, 0 },
9460 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
9461 #ifdef CONFIG_TCC_BCHECK
9462 { "b", TCC_OPTION_b
, 0 },
9464 { "g", TCC_OPTION_g
, 0 },
9465 { "c", TCC_OPTION_c
, 0 },
9466 { "static", TCC_OPTION_static
, 0 },
9467 { "shared", TCC_OPTION_shared
, 0 },
9468 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
9469 { "rdynamic", TCC_OPTION_rdynamic
, 0 }, /* currently ignored */
9470 { "r", TCC_OPTION_r
, 0 },
9471 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9472 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9473 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
9474 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9475 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
9476 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
9480 int main(int argc
, char **argv
)
9483 int optind
, output_type
, multiple_files
, i
, reloc_output
;
9486 int nb_files
, nb_libraries
, nb_objfiles
, dminus
, ret
;
9487 char objfilename
[1024];
9488 int64_t start_time
= 0;
9489 const TCCOption
*popt
;
9490 const char *optarg
, *p1
, *r1
, *outfile
;
9491 int print_search_dirs
;
9494 output_type
= TCC_OUTPUT_MEMORY
;
9504 print_search_dirs
= 0;
9506 if (optind
>= argc
) {
9507 if (nb_files
== 0 && !print_search_dirs
)
9514 /* add a new file */
9515 dynarray_add((void ***)&files
, &nb_files
, r
);
9516 if (!multiple_files
) {
9518 /* argv[0] will be this file */
9522 /* find option in table (match only the first chars */
9527 error("invalid option -- '%s'", r
);
9540 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
9541 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
9545 error("argument to '%s' is missing", r
);
9546 optarg
= argv
[optind
++];
9554 switch(popt
->index
) {
9555 case TCC_OPTION_HELP
:
9559 case TCC_OPTION_MARKER
:
9560 /* '--' enables multiple files input and also ends several
9562 if (dminus
&& multiple_files
) {
9563 optind
--; /* argv[0] will be '--' */
9569 if (tcc_add_include_path(s
, optarg
) < 0)
9570 error("too many include paths");
9575 sym
= (char *)optarg
;
9576 value
= strchr(sym
, '=');
9581 tcc_define_symbol(s
, sym
, value
);
9585 tcc_undefine_symbol(s
, optarg
);
9588 tcc_add_library_path(s
, optarg
);
9591 /* set tcc utilities path (mainly for tcc development) */
9592 tcc_lib_path
= optarg
;
9595 dynarray_add((void ***)&files
, &nb_files
, r
);
9598 case TCC_OPTION_bench
:
9602 num_callers
= atoi(optarg
);
9604 #ifdef CONFIG_TCC_BCHECK
9606 do_bounds_check
= 1;
9615 output_type
= TCC_OUTPUT_OBJ
;
9617 case TCC_OPTION_static
:
9620 case TCC_OPTION_shared
:
9621 output_type
= TCC_OUTPUT_DLL
;
9628 /* generate a .o merging several output files */
9630 output_type
= TCC_OUTPUT_OBJ
;
9632 case TCC_OPTION_nostdinc
:
9635 case TCC_OPTION_print_search_dirs
:
9636 print_search_dirs
= 1;
9644 if (print_search_dirs
) {
9645 /* enough for Linux kernel */
9646 printf("install: %s/\n", tcc_lib_path
);
9650 nb_objfiles
= nb_files
- nb_libraries
;
9652 /* if outfile provided without other options, we output an
9654 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
9655 output_type
= TCC_OUTPUT_EXE
;
9657 /* check -c consistency : only single file handled. XXX: checks file type */
9658 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
9659 /* accepts only a single input file */
9660 if (nb_objfiles
!= 1)
9661 error("cannot specify multiple files with -c");
9662 if (nb_libraries
!= 0)
9663 error("cannot specify libraries with -c");
9666 /* compute default outfile name */
9667 if (output_type
!= TCC_OUTPUT_MEMORY
&& !outfile
) {
9668 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
9670 /* add .o extension */
9671 pstrcpy(objfilename
, sizeof(objfilename
) - 1, files
[0]);
9672 ext
= strrchr(objfilename
, '.');
9674 goto default_outfile
;
9675 strcpy(ext
+ 1, "o");
9678 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
9680 outfile
= objfilename
;
9684 start_time
= getclock_us();
9687 tcc_set_output_type(s
, output_type
);
9689 /* compile or add each files or library */
9690 for(i
= 0;i
< nb_files
; i
++) {
9691 const char *filename
;
9693 filename
= files
[i
];
9694 if (filename
[0] == '-') {
9695 if (tcc_add_library(s
, filename
+ 2) < 0)
9696 error("cannot find %s", filename
);
9698 if (tcc_add_file(s
, filename
) < 0) {
9705 /* free all files */
9710 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
9711 if (total_time
< 0.001)
9713 if (total_bytes
< 1)
9715 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
9716 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
9717 total_time
, (int)(total_lines
/ total_time
),
9718 total_bytes
/ total_time
/ 1000000.0);
9721 if (s
->output_type
!= TCC_OUTPUT_MEMORY
) {
9722 tcc_output_file(s
, outfile
);
9725 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
9728 /* XXX: cannot do it with bound checking because of the malloc hooks */
9729 if (!do_bounds_check
)
9734 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);