2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001, 2002, 2003 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.
36 #include <sys/timeb.h>
40 #include <sys/ucontext.h>
44 #ifndef CONFIG_TCC_STATIC
52 /* preprocessor debug */
54 /* include file debug */
62 /* target selection */
63 //#define TCC_TARGET_I386 /* i386 code generator */
65 /* default target is I386 */
66 #if !defined(TCC_TARGET_I386)
67 #define TCC_TARGET_I386
70 #if !defined(WIN32) && !defined(TCC_UCLIBC)
71 #define CONFIG_TCC_BCHECK /* enable bound checking code */
74 /* define it to include assembler support */
75 #define CONFIG_TCC_ASM
77 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
78 executables or dlls */
79 #define CONFIG_TCC_CRT_PREFIX "/usr/lib"
81 #define INCLUDE_STACK_SIZE 32
82 #define IFDEF_STACK_SIZE 64
83 #define VSTACK_SIZE 64
84 #define STRING_MAX_SIZE 1024
86 #define TOK_HASH_SIZE 2048 /* must be a power of two */
87 #define TOK_ALLOC_INCR 512 /* must be a power of two */
88 #define TOK_STR_ALLOC_INCR_BITS 6
89 #define TOK_STR_ALLOC_INCR (1 << TOK_STR_ALLOC_INCR_BITS)
90 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
92 /* token symbol management */
93 typedef struct TokenSym
{
94 struct TokenSym
*hash_next
;
95 struct Sym
*sym_define
; /* direct pointer to define */
96 struct Sym
*sym_label
; /* direct pointer to label */
97 struct Sym
*sym_struct
; /* direct pointer to structure */
98 struct Sym
*sym_identifier
; /* direct pointer to identifier */
99 int tok
; /* token number */
104 typedef struct CString
{
105 int size
; /* size in bytes */
106 void *data
; /* either 'char *' or 'int *' */
108 void *data_allocated
; /* if non NULL, data has been malloced */
111 /* type definition */
112 typedef struct CType
{
118 typedef union CValue
{
124 unsigned int ul
; /* address (should be unsigned long on 64 bit cpu) */
126 unsigned long long ull
;
127 struct CString
*cstr
;
133 typedef struct SValue
{
134 CType type
; /* type */
135 unsigned short r
; /* register + flags */
136 unsigned short r2
; /* second register, used for 'long long'
137 type. If not used, set to VT_CONST */
138 CValue c
; /* constant, if VT_CONST */
139 struct Sym
*sym
; /* symbol, if (VT_SYM | VT_CONST) */
142 /* symbol management */
144 int v
; /* symbol token */
145 int r
; /* associated register */
146 int c
; /* associated number */
147 CType type
; /* associated type */
148 struct Sym
*next
; /* next related symbol */
149 struct Sym
*prev
; /* prev symbol in stack */
150 struct Sym
*prev_tok
; /* previous symbol for this token */
153 /* section definition */
154 /* XXX: use directly ELF structure for parameters ? */
155 /* special flag to indicate that the section should not be linked to
157 #define SHF_PRIVATE 0x80000000
159 typedef struct Section
{
160 unsigned long data_offset
; /* current data offset */
161 unsigned char *data
; /* section data */
162 unsigned long data_allocated
; /* used for realloc() handling */
163 int sh_name
; /* elf section name (only used during output) */
164 int sh_num
; /* elf section number */
165 int sh_type
; /* elf section type */
166 int sh_flags
; /* elf section flags */
167 int sh_info
; /* elf section info */
168 int sh_addralign
; /* elf section alignment */
169 int sh_entsize
; /* elf entry size */
170 unsigned long sh_size
; /* section size (only used during output) */
171 unsigned long sh_addr
; /* address at which the section is relocated */
172 unsigned long sh_offset
; /* address at which the section is relocated */
173 int nb_hashed_syms
; /* used to resize the hash table */
174 struct Section
*link
; /* link to another section */
175 struct Section
*reloc
; /* corresponding section for relocation, if any */
176 struct Section
*hash
; /* hash table for symbols */
177 struct Section
*next
;
178 char name
[64]; /* section name */
181 typedef struct DLLReference
{
186 /* GNUC attribute definition */
187 typedef struct AttributeDef
{
190 unsigned char func_call
; /* FUNC_CDECL or FUNC_STDCALL */
193 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
194 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
195 #define SYM_FIRST_ANOM (1 << (31 - VT_STRUCT_SHIFT)) /* first anonymous sym */
197 /* stored in 'Sym.c' field */
198 #define FUNC_NEW 1 /* ansi function prototype */
199 #define FUNC_OLD 2 /* old function prototype */
200 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
202 /* stored in 'Sym.r' field */
203 #define FUNC_CDECL 0 /* standard c call */
204 #define FUNC_STDCALL 1 /* pascal c call */
206 /* field 'Sym.t' for macros */
207 #define MACRO_OBJ 0 /* object like macro */
208 #define MACRO_FUNC 1 /* function like macro */
210 /* field 'Sym.r' for C labels */
211 #define LABEL_DEFINED 0 /* label is defined */
212 #define LABEL_FORWARD 1 /* label is forward defined */
213 #define LABEL_DECLARED 2 /* label is declared but never used */
215 /* type_decl() types */
216 #define TYPE_ABSTRACT 1 /* type without variable */
217 #define TYPE_DIRECT 2 /* type with variable */
219 #define IO_BUF_SIZE 8192
221 typedef struct BufferedFile
{
225 int line_num
; /* current line number - here to simplify code */
226 int ifndef_macro
; /* #ifndef macro / #endif search */
227 int ifndef_macro_saved
; /* saved ifndef_macro */
228 int *ifdef_stack_ptr
; /* ifdef_stack value at the start of the file */
229 char inc_type
; /* type of include */
230 char inc_filename
[512]; /* filename specified by the user */
231 char filename
[1024]; /* current filename - here to simplify code */
232 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
235 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
236 #define CH_EOF (-1) /* end of file */
238 /* parsing state (used to save parser state to reparse part of the
239 source several times) */
240 typedef struct ParseState
{
247 /* used to record tokens */
248 typedef struct TokenString
{
255 /* include file cache, used to find files faster and also to eliminate
256 inclusion if the include file is protected by #ifndef ... #endif */
257 typedef struct CachedInclude
{
259 char type
; /* '"' or '>' to give include type */
260 char filename
[1]; /* path specified in #include */
264 static struct BufferedFile
*file
;
267 static CString tokcstr
; /* current parsed string, if any */
268 /* additional informations about token */
269 static int tok_flags
;
270 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
271 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
272 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
274 static int *macro_ptr
, *macro_ptr_allocated
;
275 static int *unget_saved_macro_ptr
;
276 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
277 static int unget_buffer_enabled
;
278 static int parse_flags
;
279 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
280 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
281 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
282 token. line feed is also
285 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
286 static Section
*cur_text_section
; /* current section where function code is
288 /* bound check related sections */
289 static Section
*bounds_section
; /* contains global data bound description */
290 static Section
*lbounds_section
; /* contains local data bound description */
291 /* symbol sections */
292 static Section
*symtab_section
, *strtab_section
;
295 static Section
*stab_section
, *stabstr_section
;
297 /* loc : local variable index
298 ind : output code index
300 anon_sym: anonymous symbol index
302 static int rsym
, anon_sym
, ind
, loc
;
303 /* expression generation modifiers */
304 static int const_wanted
; /* true if constant wanted */
305 static int nocode_wanted
; /* true if no code generation wanted for an expression */
306 static int global_expr
; /* true if compound literals must be allocated
307 globally (used during initializers parsing */
308 static CType func_vt
; /* current function return type (used by return
311 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
312 static int tok_ident
;
313 static TokenSym
**table_ident
;
314 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
315 static char token_buf
[STRING_MAX_SIZE
+ 1];
316 static char *funcname
;
317 static Sym
*global_stack
, *local_stack
;
318 static Sym
*define_stack
;
319 static Sym
*global_label_stack
, *local_label_stack
;
321 static SValue vstack
[VSTACK_SIZE
], *vtop
;
322 /* some predefined types */
323 static CType char_pointer_type
, func_old_type
, int_type
;
324 /* true if isid(c) || isnum(c) */
325 static unsigned char isidnum_table
[256];
327 /* compile with debug symbol (and use them if error during execution) */
328 static int do_debug
= 0;
330 /* compile with built-in memory and bounds checker */
331 static int do_bounds_check
= 0;
333 /* display benchmark infos */
335 static int do_bench
= 0;
337 static int total_lines
;
338 static int total_bytes
;
340 /* use GNU C extensions */
341 static int gnu_ext
= 1;
343 /* use Tiny C extensions */
344 static int tcc_ext
= 1;
346 /* max number of callers shown if error */
347 static int num_callers
= 6;
348 static const char **rt_bound_error_msg
;
350 /* XXX: get rid of this ASAP */
351 static struct TCCState
*tcc_state
;
353 /* give the path of the tcc libraries */
354 static const char *tcc_lib_path
= CONFIG_TCC_LIBDIR
"/tcc";
359 BufferedFile
**include_stack_ptr
;
360 int *ifdef_stack_ptr
;
362 /* include file handling */
363 char **include_paths
;
364 int nb_include_paths
;
365 char **sysinclude_paths
;
366 int nb_sysinclude_paths
;
367 CachedInclude
**cached_includes
;
368 int nb_cached_includes
;
370 char **library_paths
;
371 int nb_library_paths
;
373 /* array of all loaded dlls (including those referenced by loaded
375 DLLReference
**loaded_dlls
;
380 int nb_sections
; /* number of sections, including first dummy section */
385 unsigned long *got_offsets
;
387 /* give the correspondance from symtab indexes to dynsym indexes */
388 int *symtab_to_dynsym
;
390 /* temporary dynamic symbol sections (for dll loading) */
391 Section
*dynsymtab_section
;
392 /* exported dynamic symbol section */
395 /* if true, no standard headers are added */
398 /* if true, static linking is performed */
401 /* warning switches */
402 int warn_write_strings
;
403 int warn_unsupported
;
408 void (*error_func
)(void *opaque
, const char *msg
);
409 int error_set_jmp_enabled
;
410 jmp_buf error_jmp_buf
;
413 /* tiny assembler state */
416 /* see include_stack_ptr */
417 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
419 /* see ifdef_stack_ptr */
420 int ifdef_stack
[IFDEF_STACK_SIZE
];
423 /* The current value can be: */
424 #define VT_VALMASK 0x00ff
425 #define VT_CONST 0x00f0 /* constant in vc
426 (must be first non register value) */
427 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
428 #define VT_LOCAL 0x00f2 /* offset on stack */
429 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
430 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
431 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
432 #define VT_LVAL 0x0100 /* var is an lvalue */
433 #define VT_SYM 0x0200 /* a symbol value is added */
434 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
435 char/short stored in integer registers) */
436 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
437 dereferencing value */
438 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
439 bounding function call point is in vc */
440 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
441 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
442 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
443 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
446 #define VT_INT 0 /* integer type */
447 #define VT_BYTE 1 /* signed byte type */
448 #define VT_SHORT 2 /* short type */
449 #define VT_VOID 3 /* void type */
450 #define VT_PTR 4 /* pointer */
451 #define VT_ENUM 5 /* enum definition */
452 #define VT_FUNC 6 /* function type */
453 #define VT_STRUCT 7 /* struct/union definition */
454 #define VT_FLOAT 8 /* IEEE float */
455 #define VT_DOUBLE 9 /* IEEE double */
456 #define VT_LDOUBLE 10 /* IEEE long double */
457 #define VT_BOOL 11 /* ISOC99 boolean type */
458 #define VT_LLONG 12 /* 64 bit integer */
459 #define VT_LONG 13 /* long integer (NEVER USED as type, only
461 #define VT_BTYPE 0x000f /* mask for basic type */
462 #define VT_UNSIGNED 0x0010 /* unsigned type */
463 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
464 #define VT_BITFIELD 0x0040 /* bitfield modifier */
465 #define VT_CONSTANT 0x0800 /* const modifier */
466 #define VT_VOLATILE 0x1000 /* volatile modifier */
469 #define VT_EXTERN 0x00000080 /* extern definition */
470 #define VT_STATIC 0x00000100 /* static variable */
471 #define VT_TYPEDEF 0x00000200 /* typedef definition */
472 #define VT_INLINE 0x00000400 /* inline definition */
474 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
476 /* type mask (except storage) */
477 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
478 #define VT_TYPE (~(VT_STORAGE))
482 /* warning: the following compare tokens depend on i386 asm code */
494 #define TOK_LAND 0xa0
498 #define TOK_MID 0xa3 /* inc/dec, to void constant */
500 #define TOK_UDIV 0xb0 /* unsigned division */
501 #define TOK_UMOD 0xb1 /* unsigned modulo */
502 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
503 #define TOK_CINT 0xb3 /* number in tokc */
504 #define TOK_CCHAR 0xb4 /* char constant in tokc */
505 #define TOK_STR 0xb5 /* pointer to string in tokc */
506 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
507 #define TOK_LCHAR 0xb7
508 #define TOK_LSTR 0xb8
509 #define TOK_CFLOAT 0xb9 /* float constant */
510 #define TOK_LINENUM 0xba /* line number info */
511 #define TOK_CDOUBLE 0xc0 /* double constant */
512 #define TOK_CLDOUBLE 0xc1 /* long double constant */
513 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
514 #define TOK_ADDC1 0xc3 /* add with carry generation */
515 #define TOK_ADDC2 0xc4 /* add with carry use */
516 #define TOK_SUBC1 0xc5 /* add with carry generation */
517 #define TOK_SUBC2 0xc6 /* add with carry use */
518 #define TOK_CUINT 0xc8 /* unsigned int constant */
519 #define TOK_CLLONG 0xc9 /* long long constant */
520 #define TOK_CULLONG 0xca /* unsigned long long constant */
521 #define TOK_ARROW 0xcb
522 #define TOK_DOTS 0xcc /* three dots */
523 #define TOK_SHR 0xcd /* unsigned shift right */
524 #define TOK_PPNUM 0xce /* preprocessor number */
526 #define TOK_SHL 0x01 /* shift left */
527 #define TOK_SAR 0x02 /* signed shift right */
529 /* assignement operators : normal operator or 0x80 */
530 #define TOK_A_MOD 0xa5
531 #define TOK_A_AND 0xa6
532 #define TOK_A_MUL 0xaa
533 #define TOK_A_ADD 0xab
534 #define TOK_A_SUB 0xad
535 #define TOK_A_DIV 0xaf
536 #define TOK_A_XOR 0xde
537 #define TOK_A_OR 0xfc
538 #define TOK_A_SHL 0x81
539 #define TOK_A_SAR 0x82
542 #define offsetof(type, field) ((size_t) &((type *)0)->field)
546 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
549 /* WARNING: the content of this string encodes token numbers */
550 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";
552 #define TOK_EOF (-1) /* end of file */
553 #define TOK_LINEFEED 10 /* line feed */
555 /* all identificators and strings have token above that */
556 #define TOK_IDENT 256
558 /* only used for i386 asm opcodes definitions */
559 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
562 DEF(TOK_ASM_ ## x ## b, #x "b") \
563 DEF(TOK_ASM_ ## x ## w, #x "w") \
564 DEF(TOK_ASM_ ## x ## l, #x "l") \
565 DEF(TOK_ASM_ ## x, #x)
568 DEF(TOK_ASM_ ## x ## w, #x "w") \
569 DEF(TOK_ASM_ ## x ## l, #x "l") \
570 DEF(TOK_ASM_ ## x, #x)
573 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
574 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
575 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
576 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
579 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
580 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
583 #define DEF_ASMTEST(x) \
615 #define TOK_ASM_int TOK_INT
618 TOK_LAST
= TOK_IDENT
- 1,
619 #define DEF(id, str) id,
624 static const char tcc_keywords
[] =
625 #define DEF(id, str) str "\0"
630 #define TOK_UIDENT TOK_DEFINE
633 #define snprintf _snprintf
634 #define vsnprintf _vsnprintf
637 #if defined(WIN32) || defined(TCC_UCLIBC) || defined(__FreeBSD__)
638 /* currently incorrect */
639 long double strtold(const char *nptr
, char **endptr
)
641 return (long double)strtod(nptr
, endptr
);
643 float strtof(const char *nptr
, char **endptr
)
645 return (float)strtod(nptr
, endptr
);
648 /* XXX: need to define this to use them in non ISOC99 context */
649 extern float strtof (const char *__nptr
, char **__endptr
);
650 extern long double strtold (const char *__nptr
, char **__endptr
);
653 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
654 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
656 static void next(void);
657 static void next_nomacro(void);
658 static void parse_expr_type(CType
*type
);
659 static void expr_type(CType
*type
);
660 static void unary_type(CType
*type
);
661 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
662 int case_reg
, int is_expr
);
663 static int expr_const(void);
664 static void expr_eq(void);
665 static void gexpr(void);
666 static void decl(int l
);
667 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
668 int first
, int size_only
);
669 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
670 int has_init
, int v
, int scope
);
672 void gv2(int rc1
, int rc2
);
673 void move_reg(int r
, int s
);
674 void save_regs(int n
);
675 void save_reg(int r
);
681 static void macro_subst(TokenString
*tok_str
,
682 Sym
**nested_list
, const int *macro_str
);
683 int save_reg_forced(int r
);
685 void force_charshort_cast(int t
);
686 static void gen_cast(CType
*type
);
688 static Sym
*sym_find(int v
);
689 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
692 static int type_size(CType
*type
, int *a
);
693 static inline CType
*pointed_type(CType
*type
);
694 static int pointed_size(CType
*type
);
695 static int lvalue_type(int t
);
696 static int parse_btype(CType
*type
, AttributeDef
*ad
);
697 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
698 static int is_compatible_types(CType
*type1
, CType
*type2
);
700 void error(const char *fmt
, ...);
702 void vset(CType
*type
, int r
, int v
);
703 void type_to_str(char *buf
, int buf_size
,
704 CType
*type
, const char *varstr
);
705 char *get_tok_str(int v
, CValue
*cv
);
706 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
707 unsigned long offset
, unsigned long size
);
708 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
710 /* section generation */
711 static void section_realloc(Section
*sec
, unsigned long new_size
);
712 static void *section_ptr_add(Section
*sec
, unsigned long size
);
713 static void put_extern_sym(Sym
*sym
, Section
*section
,
714 unsigned long value
, unsigned long size
);
715 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
716 static int put_elf_str(Section
*s
, const char *sym
);
717 static int put_elf_sym(Section
*s
,
718 unsigned long value
, unsigned long size
,
719 int info
, int other
, int shndx
, const char *name
);
720 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
721 int info
, int sh_num
, const char *name
);
722 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
723 int type
, int symbol
);
724 static void put_stabs(const char *str
, int type
, int other
, int desc
,
725 unsigned long value
);
726 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
727 unsigned long value
, Section
*sec
, int sym_index
);
728 static void put_stabn(int type
, int other
, int desc
, int value
);
729 static void put_stabd(int type
, int other
, int desc
);
730 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
732 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
733 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
734 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
738 #ifdef CONFIG_TCC_ASM
740 typedef struct ExprValue
{
745 #define MAX_ASM_OPERANDS 30
747 typedef struct ASMOperand
{
748 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
750 char asm_str
[16]; /* computed asm string for operand */
751 SValue
*vt
; /* C value of the expression */
752 int ref_index
; /* if >= 0, gives reference to a output constraint */
753 int priority
; /* priority, used to assign registers */
754 int reg
; /* if >= 0, register number used for this operand */
755 int is_llong
; /* true if double register value */
758 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
759 static int asm_int_expr(TCCState
*s1
);
760 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
761 const char *name
, const char **pp
);
763 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
767 static void asm_instr(void);
769 /* true if float/double/long double type */
770 static inline int is_float(int t
)
774 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
777 #ifdef TCC_TARGET_I386
778 #include "i386-gen.c"
781 #ifdef CONFIG_TCC_STATIC
783 #define RTLD_LAZY 0x001
784 #define RTLD_NOW 0x002
785 #define RTLD_GLOBAL 0x100
786 #define RTLD_DEFAULT NULL
788 /* dummy function for profiling */
789 void *dlopen(const char *filename
, int flag
)
794 const char *dlerror(void)
799 typedef struct TCCSyms
{
804 #define TCCSYM(a) { #a, &a, },
806 /* add the symbol you want here if no dynamic linking is done */
807 static TCCSyms tcc_syms
[] = {
815 void *dlsym(void *handle
, const char *symbol
)
819 while (p
->str
!= NULL
) {
820 if (!strcmp(p
->str
, symbol
))
829 /********************************************************/
831 /* we use our own 'finite' function to avoid potential problems with
832 non standard math libs */
833 /* XXX: endianness dependent */
834 int ieee_finite(double d
)
837 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
840 /* copy a string and truncate it. */
841 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
848 q_end
= buf
+ buf_size
- 1;
860 /* strcat and truncate. */
861 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
866 pstrcpy(buf
+ len
, buf_size
- len
, s
);
870 /* memory management */
876 static inline void tcc_free(void *ptr
)
879 mem_cur_size
-= malloc_usable_size(ptr
);
884 static void *tcc_malloc(unsigned long size
)
889 error("memory full");
891 mem_cur_size
+= malloc_usable_size(ptr
);
892 if (mem_cur_size
> mem_max_size
)
893 mem_max_size
= mem_cur_size
;
898 static void *tcc_mallocz(unsigned long size
)
901 ptr
= tcc_malloc(size
);
902 memset(ptr
, 0, size
);
906 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
910 mem_cur_size
-= malloc_usable_size(ptr
);
912 ptr1
= realloc(ptr
, size
);
914 /* NOTE: count not correct if alloc error, but not critical */
915 mem_cur_size
+= malloc_usable_size(ptr1
);
916 if (mem_cur_size
> mem_max_size
)
917 mem_max_size
= mem_cur_size
;
922 static char *tcc_strdup(const char *str
)
925 ptr
= tcc_malloc(strlen(str
) + 1);
930 #define free(p) use_tcc_free(p)
931 #define malloc(s) use_tcc_malloc(s)
932 #define realloc(p, s) use_tcc_realloc(p, s)
934 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
941 /* every power of two we double array size */
942 if ((nb
& (nb
- 1)) == 0) {
947 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
949 error("memory full");
956 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
960 sec
= tcc_mallocz(sizeof(Section
));
961 pstrcpy(sec
->name
, sizeof(sec
->name
), name
);
962 sec
->sh_type
= sh_type
;
963 sec
->sh_flags
= sh_flags
;
970 sec
->sh_addralign
= 4;
973 sec
->sh_addralign
= 1;
976 sec
->sh_addralign
= 32; /* default conservative alignment */
980 /* only add section if not private */
981 if (!(sh_flags
& SHF_PRIVATE
)) {
982 sec
->sh_num
= s1
->nb_sections
;
983 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
988 static void free_section(Section
*s
)
994 /* realloc section and set its content to zero */
995 static void section_realloc(Section
*sec
, unsigned long new_size
)
1000 size
= sec
->data_allocated
;
1003 while (size
< new_size
)
1005 data
= tcc_realloc(sec
->data
, size
);
1007 error("memory full");
1008 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1010 sec
->data_allocated
= size
;
1013 /* reserve at least 'size' bytes in section 'sec' from
1014 sec->data_offset. */
1015 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1017 unsigned long offset
, offset1
;
1019 offset
= sec
->data_offset
;
1020 offset1
= offset
+ size
;
1021 if (offset1
> sec
->data_allocated
)
1022 section_realloc(sec
, offset1
);
1023 sec
->data_offset
= offset1
;
1024 return sec
->data
+ offset
;
1027 /* return a reference to a section, and create it if it does not
1029 Section
*find_section(TCCState
*s1
, const char *name
)
1033 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1034 sec
= s1
->sections
[i
];
1035 if (!strcmp(name
, sec
->name
))
1038 /* sections are created as PROGBITS */
1039 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1042 /* update sym->c so that it points to an external symbol in section
1043 'section' with value 'value' */
1044 static void put_extern_sym(Sym
*sym
, Section
*section
,
1045 unsigned long value
, unsigned long size
)
1047 int sym_type
, sym_bind
, sh_num
, info
;
1052 sh_num
= section
->sh_num
;
1056 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
)
1057 sym_type
= STT_FUNC
;
1059 sym_type
= STT_OBJECT
;
1060 if (sym
->type
.t
& VT_STATIC
)
1061 sym_bind
= STB_LOCAL
;
1063 sym_bind
= STB_GLOBAL
;
1065 name
= get_tok_str(sym
->v
, NULL
);
1066 #ifdef CONFIG_TCC_BCHECK
1067 if (do_bounds_check
) {
1070 /* XXX: avoid doing that for statics ? */
1071 /* if bound checking is activated, we change some function
1072 names by adding the "__bound" prefix */
1075 /* XXX: we rely only on malloc hooks */
1087 strcpy(buf
, "__bound_");
1094 info
= ELF32_ST_INFO(sym_bind
, sym_type
);
1095 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, sh_num
, name
);
1097 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
1098 esym
->st_value
= value
;
1099 esym
->st_size
= size
;
1100 esym
->st_shndx
= sh_num
;
1104 /* add a new relocation entry to symbol 'sym' in section 's' */
1105 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1108 put_extern_sym(sym
, NULL
, 0, 0);
1109 /* now we can add ELF relocation info */
1110 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1113 static inline int isid(int c
)
1115 return (c
>= 'a' && c
<= 'z') ||
1116 (c
>= 'A' && c
<= 'Z') ||
1120 static inline int isnum(int c
)
1122 return c
>= '0' && c
<= '9';
1125 static inline int isoct(int c
)
1127 return c
>= '0' && c
<= '7';
1130 static inline int toup(int c
)
1132 if (c
>= 'a' && c
<= 'z')
1133 return c
- 'a' + 'A';
1138 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1142 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1145 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1149 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1153 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1160 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1161 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1162 (*f
)->filename
, (*f
)->line_num
);
1163 if (file
->line_num
> 0) {
1164 strcat_printf(buf
, sizeof(buf
),
1165 "%s:%d: ", file
->filename
, file
->line_num
);
1167 strcat_printf(buf
, sizeof(buf
),
1168 "%s: ", file
->filename
);
1171 strcat_printf(buf
, sizeof(buf
),
1175 strcat_printf(buf
, sizeof(buf
), "warning: ");
1176 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1178 if (!s1
->error_func
) {
1179 /* default case: stderr */
1180 fprintf(stderr
, "%s\n", buf
);
1182 s1
->error_func(s1
->error_opaque
, buf
);
1184 if (!is_warning
|| s1
->warn_error
)
1189 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1190 void (*error_func
)(void *opaque
, const char *msg
))
1192 s
->error_opaque
= error_opaque
;
1193 s
->error_func
= error_func
;
1197 /* error without aborting current compilation */
1198 void error_noabort(const char *fmt
, ...)
1200 TCCState
*s1
= tcc_state
;
1204 error1(s1
, 0, fmt
, ap
);
1208 void error(const char *fmt
, ...)
1210 TCCState
*s1
= tcc_state
;
1214 error1(s1
, 0, fmt
, ap
);
1216 /* better than nothing: in some cases, we accept to handle errors */
1217 if (s1
->error_set_jmp_enabled
) {
1218 longjmp(s1
->error_jmp_buf
, 1);
1220 /* XXX: eliminate this someday */
1225 void expect(const char *msg
)
1227 error("%s expected", msg
);
1230 void warning(const char *fmt
, ...)
1232 TCCState
*s1
= tcc_state
;
1236 error1(s1
, 1, fmt
, ap
);
1243 error("'%c' expected", c
);
1247 static void test_lvalue(void)
1249 if (!(vtop
->r
& VT_LVAL
))
1253 /* allocate a new token */
1254 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1256 TokenSym
*ts
, **ptable
;
1259 if (tok_ident
>= SYM_FIRST_ANOM
)
1260 error("memory full");
1262 /* expand token table if needed */
1263 i
= tok_ident
- TOK_IDENT
;
1264 if ((i
% TOK_ALLOC_INCR
) == 0) {
1265 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1267 error("memory full");
1268 table_ident
= ptable
;
1271 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1272 table_ident
[i
] = ts
;
1273 ts
->tok
= tok_ident
++;
1274 ts
->sym_define
= NULL
;
1275 ts
->sym_label
= NULL
;
1276 ts
->sym_struct
= NULL
;
1277 ts
->sym_identifier
= NULL
;
1279 ts
->hash_next
= NULL
;
1280 memcpy(ts
->str
, str
, len
);
1281 ts
->str
[len
] = '\0';
1286 #define TOK_HASH_INIT 1
1287 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1289 /* find a token and add it if not found */
1290 static TokenSym
*tok_alloc(const char *str
, int len
)
1292 TokenSym
*ts
, **pts
;
1298 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1299 h
&= (TOK_HASH_SIZE
- 1);
1301 pts
= &hash_ident
[h
];
1306 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1308 pts
= &(ts
->hash_next
);
1310 return tok_alloc_new(pts
, str
, len
);
1313 /* CString handling */
1315 static void cstr_realloc(CString
*cstr
, int new_size
)
1320 size
= cstr
->size_allocated
;
1322 size
= 8; /* no need to allocate a too small first string */
1323 while (size
< new_size
)
1325 data
= tcc_realloc(cstr
->data_allocated
, size
);
1327 error("memory full");
1328 cstr
->data_allocated
= data
;
1329 cstr
->size_allocated
= size
;
1334 static void cstr_ccat(CString
*cstr
, int ch
)
1337 size
= cstr
->size
+ 1;
1338 if (size
> cstr
->size_allocated
)
1339 cstr_realloc(cstr
, size
);
1340 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1344 static void cstr_cat(CString
*cstr
, const char *str
)
1356 /* add a wide char */
1357 static void cstr_wccat(CString
*cstr
, int ch
)
1360 size
= cstr
->size
+ sizeof(int);
1361 if (size
> cstr
->size_allocated
)
1362 cstr_realloc(cstr
, size
);
1363 *(int *)(((unsigned char *)cstr
->data
) + size
- sizeof(int)) = ch
;
1367 static void cstr_new(CString
*cstr
)
1369 memset(cstr
, 0, sizeof(CString
));
1372 /* free string and reset it to NULL */
1373 static void cstr_free(CString
*cstr
)
1375 tcc_free(cstr
->data_allocated
);
1379 #define cstr_reset(cstr) cstr_free(cstr)
1381 static CString
*cstr_dup(CString
*cstr1
)
1386 cstr
= tcc_malloc(sizeof(CString
));
1389 cstr
->size_allocated
= size
;
1390 cstr
->data_allocated
= tcc_malloc(size
);
1391 cstr
->data
= cstr
->data_allocated
;
1392 memcpy(cstr
->data_allocated
, cstr1
->data_allocated
, size
);
1396 /* XXX: unicode ? */
1397 static void add_char(CString
*cstr
, int c
)
1399 if (c
== '\'' || c
== '\"' || c
== '\\') {
1400 /* XXX: could be more precise if char or string */
1401 cstr_ccat(cstr
, '\\');
1403 if (c
>= 32 && c
<= 126) {
1406 cstr_ccat(cstr
, '\\');
1408 cstr_ccat(cstr
, 'n');
1410 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1411 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1412 cstr_ccat(cstr
, '0' + (c
& 7));
1417 /* XXX: buffer overflow */
1418 /* XXX: float tokens */
1419 char *get_tok_str(int v
, CValue
*cv
)
1421 static char buf
[STRING_MAX_SIZE
+ 1];
1422 static CString cstr_buf
;
1428 /* NOTE: to go faster, we give a fixed buffer for small strings */
1429 cstr_reset(&cstr_buf
);
1430 cstr_buf
.data
= buf
;
1431 cstr_buf
.size_allocated
= sizeof(buf
);
1437 /* XXX: not quite exact, but only useful for testing */
1438 sprintf(p
, "%u", cv
->ui
);
1442 /* XXX: not quite exact, but only useful for testing */
1443 sprintf(p
, "%Lu", cv
->ull
);
1447 cstr_ccat(&cstr_buf
, '\'');
1448 add_char(&cstr_buf
, cv
->i
);
1449 cstr_ccat(&cstr_buf
, '\'');
1450 cstr_ccat(&cstr_buf
, '\0');
1454 len
= cstr
->size
- 1;
1456 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1457 cstr_ccat(&cstr_buf
, '\0');
1462 cstr_ccat(&cstr_buf
, '\"');
1464 len
= cstr
->size
- 1;
1466 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1468 len
= (cstr
->size
/ sizeof(int)) - 1;
1470 add_char(&cstr_buf
, ((int *)cstr
->data
)[i
]);
1472 cstr_ccat(&cstr_buf
, '\"');
1473 cstr_ccat(&cstr_buf
, '\0');
1482 return strcpy(p
, "<<=");
1484 return strcpy(p
, ">>=");
1486 if (v
< TOK_IDENT
) {
1487 /* search in two bytes table */
1501 } else if (v
< tok_ident
) {
1502 return table_ident
[v
- TOK_IDENT
]->str
;
1503 } else if (v
>= SYM_FIRST_ANOM
) {
1504 /* special name for anonymous symbol */
1505 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1507 /* should never happen */
1512 return cstr_buf
.data
;
1515 /* push, without hashing */
1516 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, int c
)
1519 s
= tcc_malloc(sizeof(Sym
));
1530 /* find a symbol and return its associated structure. 's' is the top
1531 of the symbol stack */
1532 static Sym
*sym_find2(Sym
*s
, int v
)
1542 /* structure lookup */
1543 static inline Sym
*struct_find(int v
)
1546 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1548 return table_ident
[v
]->sym_struct
;
1551 /* find an identifier */
1552 static inline Sym
*sym_find(int v
)
1555 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1557 return table_ident
[v
]->sym_identifier
;
1560 /* push a given symbol on the symbol stack */
1561 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1570 s
= sym_push2(ps
, v
, type
->t
, c
);
1571 s
->type
.ref
= type
->ref
;
1573 /* don't record fields or anonymous symbols */
1575 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1576 /* record symbol in token array */
1577 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1579 ps
= &ts
->sym_struct
;
1581 ps
= &ts
->sym_identifier
;
1588 /* push a global identifier */
1589 static Sym
*global_identifier_push(int v
, int t
, int c
)
1592 s
= sym_push2(&global_stack
, v
, t
, c
);
1593 /* don't record anonymous symbol */
1594 if (v
< SYM_FIRST_ANOM
) {
1595 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1596 /* modify the top most local identifier, so that
1597 sym_identifier will point to 's' when popped */
1599 ps
= &(*ps
)->prev_tok
;
1606 /* pop symbols until top reaches 'b' */
1607 static void sym_pop(Sym
**ptop
, Sym
*b
)
1617 /* remove symbol in token array */
1619 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1620 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1622 ps
= &ts
->sym_struct
;
1624 ps
= &ts
->sym_identifier
;
1635 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1640 fd
= open(filename
, O_RDONLY
);
1643 bf
= tcc_malloc(sizeof(BufferedFile
));
1649 bf
->buf_ptr
= bf
->buffer
;
1650 bf
->buf_end
= bf
->buffer
;
1651 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1652 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1654 bf
->ifndef_macro
= 0;
1655 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1656 // printf("opening '%s'\n", filename);
1660 void tcc_close(BufferedFile
*bf
)
1662 total_lines
+= bf
->line_num
;
1667 /* fill input buffer and peek next char */
1668 static int tcc_peekc_slow(BufferedFile
*bf
)
1671 /* only tries to read if really end of buffer */
1672 if (bf
->buf_ptr
>= bf
->buf_end
) {
1674 #if defined(PARSE_DEBUG)
1679 len
= read(bf
->fd
, bf
->buffer
, len
);
1686 bf
->buf_ptr
= bf
->buffer
;
1687 bf
->buf_end
= bf
->buffer
+ len
;
1688 *bf
->buf_end
= CH_EOB
;
1690 if (bf
->buf_ptr
< bf
->buf_end
) {
1691 return bf
->buf_ptr
[0];
1693 bf
->buf_ptr
= bf
->buf_end
;
1698 /* return the current character, handling end of block if necessary
1700 static int handle_eob(void)
1702 return tcc_peekc_slow(file
);
1705 /* read next char from current input file and handle end of input buffer */
1706 static inline void inp(void)
1708 ch
= *(++(file
->buf_ptr
));
1709 /* end of buffer/file handling */
1714 /* handle '\[\r]\n' */
1715 static void handle_stray(void)
1717 while (ch
== '\\') {
1722 } else if (ch
== '\r') {
1730 error("stray '\\' in program");
1735 /* skip the stray and handle the \\n case. Output an error if
1736 incorrect char after the stray */
1737 static int handle_stray1(uint8_t *p
)
1741 if (p
>= file
->buf_end
) {
1758 /* handle just the EOB case, but not stray */
1759 #define PEEKC_EOB(c, p)\
1770 /* handle the complicated stray case */
1771 #define PEEKC(c, p)\
1776 c = handle_stray1(p);\
1781 /* input with '\[\r]\n' handling. Note that this function cannot
1782 handle other characters after '\', so you cannot call it inside
1783 strings or comments */
1784 static void minp(void)
1792 /* single line C++ comments */
1793 static uint8_t *parse_line_comment(uint8_t *p
)
1800 if (c
== '\n' || c
== CH_EOF
) {
1802 } else if (c
== '\\') {
1807 } else if (c
== '\r') {
1822 static uint8_t *parse_comment(uint8_t *p
)
1828 /* fast skip loop */
1831 if (c
== '\n' || c
== '*' || c
== '\\')
1835 if (c
== '\n' || c
== '*' || c
== '\\')
1839 /* now we can handle all the cases */
1843 } else if (c
== '*') {
1849 } else if (c
== '/') {
1850 goto end_of_comment
;
1851 } else if (c
== '\\') {
1856 /* skip '\[\r]\n', otherwise just skip the stray */
1862 } else if (c
== '\r') {
1879 /* stray, eob or eof */
1884 error("unexpected end of file in comment");
1885 } else if (c
== '\\') {
1897 /* space exlcuding newline */
1898 static inline int is_space(int ch
)
1900 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
1903 static inline void skip_spaces(void)
1905 while (is_space(ch
))
1909 /* parse a string without interpreting escapes */
1910 static uint8_t *parse_pp_string(uint8_t *p
,
1911 int sep
, CString
*str
)
1919 } else if (c
== '\\') {
1924 unterminated_string
:
1925 /* XXX: indicate line number of start of string */
1926 error("missing terminating %c character", sep
);
1927 } else if (c
== '\\') {
1928 /* escape : just skip \[\r]\n */
1933 } else if (c
== '\r') {
1936 expect("'\n' after '\r'");
1939 } else if (c
== CH_EOF
) {
1940 goto unterminated_string
;
1943 cstr_ccat(str
, '\\');
1949 } else if (c
== '\n') {
1952 } else if (c
== '\r') {
1955 cstr_ccat(str
, '\r');
1971 /* skip block of text until #else, #elif or #endif. skip also pairs of
1973 void preprocess_skip(void)
1975 int a
, start_of_line
, c
;
2002 } else if (c
== '\\') {
2003 /* XXX: incorrect: should not give an error */
2004 ch
= file
->buf_ptr
[0];
2012 p
= parse_pp_string(p
, c
, NULL
);
2021 p
= parse_comment(p
);
2022 } else if (ch
== '/') {
2023 p
= parse_line_comment(p
);
2029 if (start_of_line
) {
2034 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2036 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2038 else if (tok
== TOK_ENDIF
)
2052 /* ParseState handling */
2054 /* XXX: currently, no include file info is stored. Thus, we cannot display
2055 accurate messages if the function or data definition spans multiple
2058 /* save current parse state in 's' */
2059 void save_parse_state(ParseState
*s
)
2061 s
->line_num
= file
->line_num
;
2062 s
->macro_ptr
= macro_ptr
;
2067 /* restore parse state from 's' */
2068 void restore_parse_state(ParseState
*s
)
2070 file
->line_num
= s
->line_num
;
2071 macro_ptr
= s
->macro_ptr
;
2076 /* return the number of additional 'ints' necessary to store the
2078 static inline int tok_ext_size(int t
)
2097 return LDOUBLE_SIZE
/ 4;
2103 /* token string handling */
2105 static inline void tok_str_new(TokenString
*s
)
2109 s
->allocated_len
= 0;
2110 s
->last_line_num
= -1;
2113 static void tok_str_free(int *str
)
2122 /* NOTE: we test zero separately so that GCC can generate a
2123 table for the following switch */
2138 /* XXX: use a macro to be portable on 64 bit ? */
2139 cstr
= (CString
*)p
[1];
2150 p
+= 1 + (LDOUBLE_SIZE
/ 4);
2160 static int *tok_str_realloc(TokenString
*s
)
2164 len
= s
->allocated_len
+ TOK_STR_ALLOC_INCR
;
2165 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2167 error("memory full");
2168 s
->allocated_len
= len
;
2173 static void tok_str_add(TokenString
*s
, int t
)
2179 if (len
>= s
->allocated_len
)
2180 str
= tok_str_realloc(s
);
2185 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2192 /* allocate space for worst case */
2193 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2194 str
= tok_str_realloc(s
);
2203 str
[len
++] = cv
->tab
[0];
2208 str
[len
++] = (int)cstr_dup(cv
->cstr
);
2213 str
[len
++] = cv
->tab
[0];
2214 str
[len
++] = cv
->tab
[1];
2217 #if LDOUBLE_SIZE == 12
2218 str
[len
++] = cv
->tab
[0];
2219 str
[len
++] = cv
->tab
[1];
2220 str
[len
++] = cv
->tab
[2];
2222 #error add long double size support
2231 /* add the current parse token in token string 's' */
2232 static void tok_str_add_tok(TokenString
*s
)
2236 /* save line number info */
2237 if (file
->line_num
!= s
->last_line_num
) {
2238 s
->last_line_num
= file
->line_num
;
2239 cval
.i
= s
->last_line_num
;
2240 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2242 tok_str_add2(s
, tok
, &tokc
);
2245 #if LDOUBLE_SIZE == 12
2246 #define LDOUBLE_GET(p, cv) \
2251 #error add long double size support
2255 /* get a token from an integer array and increment pointer
2256 accordingly. we code it as a macro to avoid pointer aliasing. */
2257 #define TOK_GET(t, p, cv) \
2279 case TOK_CLDOUBLE: \
2280 LDOUBLE_GET(p, cv); \
2281 p += LDOUBLE_SIZE / 4; \
2288 /* defines handling */
2289 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2293 s
= sym_push2(&define_stack
, v
, macro_type
, (int)str
);
2294 s
->next
= first_arg
;
2295 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2298 /* undefined a define symbol. Its name is just set to zero */
2299 static void define_undef(Sym
*s
)
2303 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2304 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2308 static inline Sym
*define_find(int v
)
2311 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2313 return table_ident
[v
]->sym_define
;
2316 /* free define stack until top reaches 'b' */
2317 static void free_defines(Sym
*b
)
2325 /* do not free args or predefined defines */
2327 tok_str_free((int *)top
->c
);
2329 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2330 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2338 static Sym
*label_find(int v
)
2341 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2343 return table_ident
[v
]->sym_label
;
2346 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2349 s
= sym_push2(ptop
, v
, 0, 0);
2351 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2352 if (ptop
== &global_label_stack
) {
2353 /* modify the top most local identifier, so that
2354 sym_identifier will point to 's' when popped */
2356 ps
= &(*ps
)->prev_tok
;
2363 /* pop labels until element last is reached. Look if any labels are
2364 undefined. Define symbols if '&&label' was used. */
2365 static void label_pop(Sym
**ptop
, Sym
*slast
)
2368 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2370 if (s
->r
== LABEL_DECLARED
) {
2371 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2372 } else if (s
->r
== LABEL_FORWARD
) {
2373 error("label '%s' used but not defined",
2374 get_tok_str(s
->v
, NULL
));
2377 /* define corresponding symbol. A size of
2379 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2383 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2389 /* eval an expression for #if/#elif */
2390 static int expr_preprocess(void)
2396 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2397 next(); /* do macro subst */
2398 if (tok
== TOK_DEFINED
) {
2403 c
= define_find(tok
) != 0;
2408 } else if (tok
>= TOK_IDENT
) {
2409 /* if undefined macro */
2413 tok_str_add_tok(&str
);
2415 tok_str_add(&str
, -1); /* simulate end of file */
2416 tok_str_add(&str
, 0);
2417 /* now evaluate C constant expression */
2418 macro_ptr
= str
.str
;
2422 tok_str_free(str
.str
);
2426 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2427 static void tok_print(int *str
)
2433 TOK_GET(t
, str
, cval
);
2436 printf(" %s", get_tok_str(t
, &cval
));
2442 /* parse after #define */
2443 static void parse_define(void)
2445 Sym
*s
, *first
, **ps
;
2446 int v
, t
, varg
, is_vaargs
, c
;
2451 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2452 /* XXX: should check if same macro (ANSI) */
2455 /* '(' must be just after macro definition for MACRO_FUNC */
2456 c
= file
->buf_ptr
[0];
2458 c
= handle_stray1(file
->buf_ptr
);
2463 while (tok
!= ')') {
2467 if (varg
== TOK_DOTS
) {
2468 varg
= TOK___VA_ARGS__
;
2470 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2474 if (varg
< TOK_IDENT
)
2475 error("badly punctuated parameter list");
2476 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2487 /* EOF testing necessary for '-D' handling */
2488 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2489 tok_str_add2(&str
, tok
, &tokc
);
2492 tok_str_add(&str
, 0);
2494 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2497 define_push(v
, t
, str
.str
, first
);
2500 /* XXX: use a token or a hash table to accelerate matching ? */
2501 static CachedInclude
*search_cached_include(TCCState
*s1
,
2502 int type
, const char *filename
)
2507 for(i
= 0;i
< s1
->nb_cached_includes
; i
++) {
2508 e
= s1
->cached_includes
[i
];
2509 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2515 static inline void add_cached_include(TCCState
*s1
, int type
,
2516 const char *filename
, int ifndef_macro
)
2520 if (search_cached_include(s1
, type
, filename
))
2523 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2525 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2529 strcpy(e
->filename
, filename
);
2530 e
->ifndef_macro
= ifndef_macro
;
2531 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2534 /* is_bof is true if first non space token at beginning of file */
2535 static void preprocess(int is_bof
)
2537 TCCState
*s1
= tcc_state
;
2538 int size
, i
, c
, n
, saved_parse_flags
;
2539 char buf
[1024], *q
, *p
;
2545 saved_parse_flags
= parse_flags
;
2546 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
2547 PARSE_FLAG_LINEFEED
;
2557 s
= define_find(tok
);
2558 /* undefine symbol by putting an invalid name */
2563 ch
= file
->buf_ptr
[0];
2564 /* XXX: incorrect if comments : use next_nomacro with a special mode */
2569 } else if (ch
== '\"') {
2572 /* XXX: better stray handling */
2575 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
2576 if ((q
- buf
) < sizeof(buf
) - 1)
2583 /* eat all spaces and comments after include */
2584 /* XXX: slightly incorrect */
2585 while (ch1
!= '\n' && ch1
!= CH_EOF
)
2589 /* computed #include : either we have only strings or
2590 we have anything enclosed in '<>' */
2593 if (tok
== TOK_STR
) {
2594 while (tok
!= TOK_LINEFEED
) {
2595 if (tok
!= TOK_STR
) {
2597 error("'#include' expects \"FILENAME\" or <FILENAME>");
2599 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
2605 while (tok
!= TOK_LINEFEED
) {
2606 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
2610 /* check syntax and remove '<>' */
2611 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
2612 goto include_syntax
;
2613 memmove(buf
, buf
+ 1, len
- 2);
2614 buf
[len
- 2] = '\0';
2619 e
= search_cached_include(s1
, c
, buf
);
2620 if (e
&& define_find(e
->ifndef_macro
)) {
2621 /* no need to parse the include because the 'ifndef macro'
2624 printf("%s: skipping %s\n", file
->filename
, buf
);
2628 /* first search in current dir if "header.h" */
2630 p
= strrchr(file
->filename
, '/');
2632 size
= p
+ 1 - file
->filename
;
2633 if (size
> sizeof(buf1
) - 1)
2634 size
= sizeof(buf1
) - 1;
2635 memcpy(buf1
, file
->filename
, size
);
2637 pstrcat(buf1
, sizeof(buf1
), buf
);
2638 f
= tcc_open(s1
, buf1
);
2642 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
2643 error("#include recursion too deep");
2644 /* now search in all the include paths */
2645 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
2646 for(i
= 0; i
< n
; i
++) {
2648 if (i
< s1
->nb_include_paths
)
2649 path
= s1
->include_paths
[i
];
2651 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
2652 pstrcpy(buf1
, sizeof(buf1
), path
);
2653 pstrcat(buf1
, sizeof(buf1
), "/");
2654 pstrcat(buf1
, sizeof(buf1
), buf
);
2655 f
= tcc_open(s1
, buf1
);
2659 error("include file '%s' not found", buf
);
2663 printf("%s: including %s\n", file
->filename
, buf1
);
2666 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
2667 /* push current file in stack */
2668 /* XXX: fix current line init */
2669 *s1
->include_stack_ptr
++ = file
;
2671 /* add include file debug info */
2673 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
2675 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
2676 ch
= file
->buf_ptr
[0];
2684 c
= expr_preprocess();
2690 if (tok
< TOK_IDENT
)
2691 error("invalid argument for '#if%sdef'", c
? "n" : "");
2695 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
2697 file
->ifndef_macro
= tok
;
2700 c
= (define_find(tok
) != 0) ^ c
;
2702 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
2703 error("memory full");
2704 *s1
->ifdef_stack_ptr
++ = c
;
2707 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2708 error("#else without matching #if");
2709 if (s1
->ifdef_stack_ptr
[-1] & 2)
2710 error("#else after #else");
2711 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
2714 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2715 error("#elif without matching #if");
2716 c
= s1
->ifdef_stack_ptr
[-1];
2718 error("#elif after #else");
2719 /* last #if/#elif expression was true: we skip */
2722 c
= expr_preprocess();
2723 s1
->ifdef_stack_ptr
[-1] = c
;
2733 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
2734 error("#endif without matching #if");
2735 s1
->ifdef_stack_ptr
--;
2736 /* '#ifndef macro' was at the start of file. Now we check if
2737 an '#endif' is exactly at the end of file */
2738 if (file
->ifndef_macro
&&
2739 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
2740 file
->ifndef_macro_saved
= file
->ifndef_macro
;
2741 /* need to set to zero to avoid false matches if another
2742 #ifndef at middle of file */
2743 file
->ifndef_macro
= 0;
2744 while (tok
!= TOK_LINEFEED
)
2746 tok_flags
|= TOK_FLAG_ENDIF
;
2752 if (tok
!= TOK_CINT
)
2754 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
2756 if (tok
!= TOK_LINEFEED
) {
2759 pstrcpy(file
->filename
, sizeof(file
->filename
),
2760 (char *)tokc
.cstr
->data
);
2766 ch
= file
->buf_ptr
[0];
2769 while (ch
!= '\n' && ch
!= CH_EOF
) {
2770 if ((q
- buf
) < sizeof(buf
) - 1)
2776 error("#error %s", buf
);
2778 warning("#warning %s", buf
);
2784 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
2785 /* '!' is ignored to allow C scripts. numbers are ignored
2786 to emulate cpp behaviour */
2788 error("invalid preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2792 /* ignore other preprocess commands or #! for C scripts */
2793 while (tok
!= TOK_LINEFEED
)
2796 parse_flags
= saved_parse_flags
;
2799 /* evaluate escape codes in a string. */
2800 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2815 case '0': case '1': case '2': case '3':
2816 case '4': case '5': case '6': case '7':
2817 /* at most three octal digits */
2822 n
= n
* 8 + c
- '0';
2826 n
= n
* 8 + c
- '0';
2831 goto add_char_nonext
;
2837 if (c
>= 'a' && c
<= 'f')
2839 else if (c
>= 'A' && c
<= 'F')
2849 goto add_char_nonext
;
2873 goto invalid_escape
;
2883 error("invalid escaped char");
2889 cstr_ccat(outstr
, c
);
2891 cstr_wccat(outstr
, c
);
2893 /* add a trailing '\0' */
2895 cstr_ccat(outstr
, '\0');
2897 cstr_wccat(outstr
, '\0');
2900 /* we use 64 bit numbers */
2903 /* bn = (bn << shift) | or_val */
2904 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2908 for(i
=0;i
<BN_SIZE
;i
++) {
2910 bn
[i
] = (v
<< shift
) | or_val
;
2911 or_val
= v
>> (32 - shift
);
2915 void bn_zero(unsigned int *bn
)
2918 for(i
=0;i
<BN_SIZE
;i
++) {
2923 /* parse number in null terminated string 'p' and return it in the
2925 void parse_number(const char *p
)
2927 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2929 unsigned int bn
[BN_SIZE
];
2940 goto float_frac_parse
;
2941 } else if (t
== '0') {
2942 if (ch
== 'x' || ch
== 'X') {
2946 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2952 /* parse all digits. cannot check octal numbers at this stage
2953 because of floating point constants */
2955 if (ch
>= 'a' && ch
<= 'f')
2957 else if (ch
>= 'A' && ch
<= 'F')
2965 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2967 error("number too long");
2973 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2974 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2976 /* NOTE: strtox should support that for hexa numbers, but
2977 non ISOC99 libcs do not support it, so we prefer to do
2979 /* hexadecimal or binary floats */
2980 /* XXX: handle overflows */
2992 } else if (t
>= 'a') {
2994 } else if (t
>= 'A') {
2999 bn_lshift(bn
, shift
, t
);
3006 if (t
>= 'a' && t
<= 'f') {
3008 } else if (t
>= 'A' && t
<= 'F') {
3010 } else if (t
>= '0' && t
<= '9') {
3016 error("invalid digit");
3017 bn_lshift(bn
, shift
, t
);
3022 if (ch
!= 'p' && ch
!= 'P')
3029 } else if (ch
== '-') {
3033 if (ch
< '0' || ch
> '9')
3034 expect("exponent digits");
3035 while (ch
>= '0' && ch
<= '9') {
3036 exp_val
= exp_val
* 10 + ch
- '0';
3039 exp_val
= exp_val
* s
;
3041 /* now we can generate the number */
3042 /* XXX: should patch directly float number */
3043 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3044 d
= ldexp(d
, exp_val
- frac_bits
);
3049 /* float : should handle overflow */
3051 } else if (t
== 'L') {
3054 /* XXX: not large enough */
3055 tokc
.ld
= (long double)d
;
3061 /* decimal floats */
3063 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3068 while (ch
>= '0' && ch
<= '9') {
3069 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3075 if (ch
== 'e' || ch
== 'E') {
3076 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3080 if (ch
== '-' || ch
== '+') {
3081 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3086 if (ch
< '0' || ch
> '9')
3087 expect("exponent digits");
3088 while (ch
>= '0' && ch
<= '9') {
3089 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3101 tokc
.f
= strtof(token_buf
, NULL
);
3102 } else if (t
== 'L') {
3105 tokc
.ld
= strtold(token_buf
, NULL
);
3108 tokc
.d
= strtod(token_buf
, NULL
);
3112 unsigned long long n
, n1
;
3115 /* integer number */
3118 if (b
== 10 && *q
== '0') {
3125 /* no need for checks except for base 10 / 8 errors */
3128 } else if (t
>= 'a') {
3130 } else if (t
>= 'A') {
3135 error("invalid digit");
3139 /* detect overflow */
3140 /* XXX: this test is not reliable */
3142 error("integer constant overflow");
3145 /* XXX: not exactly ANSI compliant */
3146 if ((n
& 0xffffffff00000000LL
) != 0) {
3151 } else if (n
> 0x7fffffff) {
3162 error("three 'l's in integer constant");
3165 if (tok
== TOK_CINT
)
3167 else if (tok
== TOK_CUINT
)
3171 } else if (t
== 'U') {
3173 error("two 'u's in integer constant");
3175 if (tok
== TOK_CINT
)
3177 else if (tok
== TOK_CLLONG
)
3184 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3192 #define PARSE2(c1, tok1, c2, tok2) \
3203 /* return next token without macro substitution */
3204 static inline void next_nomacro1(void)
3224 /* first look if it is in fact an end of buffer */
3225 if (p
>= file
->buf_end
) {
3229 if (p
>= file
->buf_end
)
3242 TCCState
*s1
= tcc_state
;
3243 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3245 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3246 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3247 /* no include left : end of file. */
3250 /* pop include file */
3252 /* test if previous '#endif' was after a #ifdef at
3254 if (tok_flags
& TOK_FLAG_ENDIF
) {
3256 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3258 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3259 file
->ifndef_macro_saved
);
3262 /* add end of include file debug info */
3264 put_stabd(N_EINCL
, 0, 0);
3266 /* pop include stack */
3268 s1
->include_stack_ptr
--;
3269 file
= *s1
->include_stack_ptr
;
3277 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3281 tok_flags
|= TOK_FLAG_BOL
;
3290 if ((tok_flags
& TOK_FLAG_BOL
) &&
3291 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3293 preprocess(tok_flags
& TOK_FLAG_BOF
);
3299 tok
= TOK_TWOSHARPS
;
3306 case 'a': case 'b': case 'c': case 'd':
3307 case 'e': case 'f': case 'g': case 'h':
3308 case 'i': case 'j': case 'k': case 'l':
3309 case 'm': case 'n': case 'o': case 'p':
3310 case 'q': case 'r': case 's': case 't':
3311 case 'u': case 'v': case 'w': case 'x':
3313 case 'A': case 'B': case 'C': case 'D':
3314 case 'E': case 'F': case 'G': case 'H':
3315 case 'I': case 'J': case 'K':
3316 case 'M': case 'N': case 'O': case 'P':
3317 case 'Q': case 'R': case 'S': case 'T':
3318 case 'U': case 'V': case 'W': case 'X':
3324 h
= TOK_HASH_FUNC(h
, c
);
3328 if (!isidnum_table
[c
])
3330 h
= TOK_HASH_FUNC(h
, c
);
3337 /* fast case : no stray found, so we have the full token
3338 and we have already hashed it */
3340 h
&= (TOK_HASH_SIZE
- 1);
3341 pts
= &hash_ident
[h
];
3346 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3348 pts
= &(ts
->hash_next
);
3350 ts
= tok_alloc_new(pts
, p1
, len
);
3354 cstr_reset(&tokcstr
);
3357 cstr_ccat(&tokcstr
, *p1
);
3363 while (isidnum_table
[c
]) {
3364 cstr_ccat(&tokcstr
, c
);
3367 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3373 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3375 goto parse_ident_fast
;
3378 if (c
== '\'' || c
== '\"') {
3382 cstr_reset(&tokcstr
);
3383 cstr_ccat(&tokcstr
, 'L');
3384 goto parse_ident_slow
;
3388 case '0': case '1': case '2': case '3':
3389 case '4': case '5': case '6': case '7':
3392 cstr_reset(&tokcstr
);
3393 /* after the first digit, accept digits, alpha, '.' or sign if
3394 prefixed by 'eEpP' */
3398 cstr_ccat(&tokcstr
, c
);
3400 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3401 ((c
== '+' || c
== '-') &&
3402 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3405 /* We add a trailing '\0' to ease parsing */
3406 cstr_ccat(&tokcstr
, '\0');
3407 tokc
.cstr
= &tokcstr
;
3411 /* special dot handling because it can also start a number */
3414 cstr_reset(&tokcstr
);
3415 cstr_ccat(&tokcstr
, '.');
3417 } else if (c
== '.') {
3437 /* parse the string */
3439 p
= parse_pp_string(p
, sep
, &str
);
3440 cstr_ccat(&str
, '\0');
3442 /* eval the escape (should be done as TOK_PPNUM) */
3443 cstr_reset(&tokcstr
);
3444 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3449 /* XXX: make it portable */
3453 char_size
= sizeof(int);
3454 if (tokcstr
.size
<= char_size
)
3455 error("empty character constant");
3456 if (tokcstr
.size
> 2 * char_size
)
3457 warning("multi-character character constant");
3459 tokc
.i
= *(int8_t *)tokcstr
.data
;
3462 tokc
.i
= *(int *)tokcstr
.data
;
3466 tokc
.cstr
= &tokcstr
;
3480 } else if (c
== '<') {
3498 } else if (c
== '>') {
3516 } else if (c
== '=') {
3529 } else if (c
== '=') {
3542 } else if (c
== '=') {
3555 } else if (c
== '=') {
3558 } else if (c
== '>') {
3566 PARSE2('!', '!', '=', TOK_NE
)
3567 PARSE2('=', '=', '=', TOK_EQ
)
3568 PARSE2('*', '*', '=', TOK_A_MUL
)
3569 PARSE2('%', '%', '=', TOK_A_MOD
)
3570 PARSE2('^', '^', '=', TOK_A_XOR
)
3572 /* comments or operator */
3576 p
= parse_comment(p
);
3578 } else if (c
== '/') {
3579 p
= parse_line_comment(p
);
3581 } else if (c
== '=') {
3601 case '$': /* only used in assembler */
3606 error("unrecognized character \\x%02x", c
);
3611 #if defined(PARSE_DEBUG)
3612 printf("token = %s\n", get_tok_str(tok
, &tokc
));
3616 /* return next token without macro substitution. Can read input from
3618 static void next_nomacro(void)
3624 TOK_GET(tok
, macro_ptr
, tokc
);
3625 if (tok
== TOK_LINENUM
) {
3626 file
->line_num
= tokc
.i
;
3635 /* substitute args in macro_str and return allocated string */
3636 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
3638 int *st
, last_tok
, t
, notfirst
;
3647 TOK_GET(t
, macro_str
, cval
);
3652 TOK_GET(t
, macro_str
, cval
);
3655 s
= sym_find2(args
, t
);
3662 cstr_ccat(&cstr
, ' ');
3663 TOK_GET(t
, st
, cval
);
3664 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
3667 cstr_ccat(&cstr
, '\0');
3669 printf("stringize: %s\n", (char *)cstr
.data
);
3673 tok_str_add2(&str
, TOK_STR
, &cval
);
3676 tok_str_add2(&str
, t
, &cval
);
3678 } else if (t
>= TOK_IDENT
) {
3679 s
= sym_find2(args
, t
);
3682 /* if '##' is present before or after, no arg substitution */
3683 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
3684 /* special case for var arg macros : ## eats the
3685 ',' if empty VA_ARGS variable. */
3686 /* XXX: test of the ',' is not 100%
3687 reliable. should fix it to avoid security
3689 if (gnu_ext
&& s
->type
.t
&&
3690 last_tok
== TOK_TWOSHARPS
&&
3691 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
3693 /* suppress ',' '##' */
3696 /* suppress '##' and add variable */
3704 TOK_GET(t1
, st
, cval
);
3707 tok_str_add2(&str
, t1
, &cval
);
3711 macro_subst(&str
, nested_list
, st
);
3714 tok_str_add(&str
, t
);
3717 tok_str_add2(&str
, t
, &cval
);
3721 tok_str_add(&str
, 0);
3725 static char const ab_month_name
[12][4] =
3727 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3728 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3731 /* do macro substitution of current token with macro 's' and add
3732 result to (tok_str,tok_len). 'nested_list' is the list of all
3733 macros we got inside to avoid recursing. Return non zero if no
3734 substitution needs to be done */
3735 static int macro_subst_tok(TokenString
*tok_str
,
3736 Sym
**nested_list
, Sym
*s
)
3738 Sym
*args
, *sa
, *sa1
;
3739 int mstr_allocated
, parlevel
, *mstr
, t
;
3745 /* if symbol is a macro, prepare substitution */
3747 /* special macros */
3748 if (tok
== TOK___LINE__
) {
3749 cval
.i
= file
->line_num
;
3750 tok_str_add2(tok_str
, TOK_CINT
, &cval
);
3751 } else if (tok
== TOK___FILE__
) {
3752 cstrval
= file
->filename
;
3754 tok_str_add2(tok_str
, TOK_STR
, &cval
);
3755 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3761 tm
= localtime(&ti
);
3762 if (tok
== TOK___DATE__
) {
3763 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3764 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3766 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3767 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3772 cstr_cat(&cstr
, cstrval
);
3773 cstr_ccat(&cstr
, '\0');
3775 tok_str_add2(tok_str
, TOK_STR
, &cval
);
3780 if (s
->type
.t
== MACRO_FUNC
) {
3781 /* NOTE: we do not use next_nomacro to avoid eating the
3782 next token. XXX: find better solution */
3786 /* end of macro stream: we must look at the token
3787 after in the file */
3793 /* XXX: incorrect with comments */
3794 ch
= file
->buf_ptr
[0];
3795 while (is_space(ch
) || ch
== '\n')
3799 if (t
!= '(') /* no macro subst */
3802 /* argument macro */
3807 /* NOTE: empty args are allowed, except if no args */
3809 /* handle '()' case */
3810 if (!args
&& tok
== ')')
3813 error("macro '%s' used with too many args",
3814 get_tok_str(s
->v
, 0));
3817 /* NOTE: non zero sa->t indicates VA_ARGS */
3818 while ((parlevel
> 0 ||
3820 (tok
!= ',' || sa
->type
.t
))) &&
3824 else if (tok
== ')')
3826 tok_str_add2(&str
, tok
, &tokc
);
3829 tok_str_add(&str
, 0);
3830 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (int)str
.str
);
3833 /* special case for gcc var args: add an empty
3834 var arg argument if it is omitted */
3835 if (sa
&& sa
->type
.t
&& gnu_ext
)
3845 error("macro '%s' used with too few args",
3846 get_tok_str(s
->v
, 0));
3849 /* now subst each arg */
3850 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3855 tok_str_free((int *)sa
->c
);
3861 sym_push2(nested_list
, s
->v
, 0, 0);
3862 macro_subst(tok_str
, nested_list
, mstr
);
3863 /* pop nested defined symbol */
3865 *nested_list
= sa1
->prev
;
3873 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3874 return the resulting string (which must be freed). */
3875 static inline int *macro_twosharps(const int *macro_str
)
3878 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
3880 const char *p1
, *p2
;
3882 TokenString macro_str1
;
3885 start_macro_ptr
= macro_str
;
3886 /* we search the first '##' */
3888 macro_ptr1
= macro_str
;
3889 TOK_GET(t
, macro_str
, cval
);
3890 /* nothing more to do if end of string */
3893 if (*macro_str
== TOK_TWOSHARPS
)
3897 /* we saw '##', so we need more processing to handle it */
3899 tok_str_new(¯o_str1
);
3903 /* add all tokens seen so far */
3904 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
3905 TOK_GET(t
, ptr
, cval
);
3906 tok_str_add2(¯o_str1
, t
, &cval
);
3908 saved_macro_ptr
= macro_ptr
;
3909 /* XXX: get rid of the use of macro_ptr here */
3910 macro_ptr
= (int *)macro_str
;
3912 while (*macro_ptr
== TOK_TWOSHARPS
) {
3914 macro_ptr1
= macro_ptr
;
3917 TOK_GET(t
, macro_ptr
, cval
);
3918 /* We concatenate the two tokens if we have an
3919 identifier or a preprocessing number */
3921 p1
= get_tok_str(tok
, &tokc
);
3922 cstr_cat(&cstr
, p1
);
3923 p2
= get_tok_str(t
, &cval
);
3924 cstr_cat(&cstr
, p2
);
3925 cstr_ccat(&cstr
, '\0');
3927 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
3928 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
3929 if (tok
== TOK_PPNUM
) {
3930 /* if number, then create a number token */
3931 /* NOTE: no need to allocate because
3932 tok_str_add2() does it */
3935 /* if identifier, we must do a test to
3936 validate we have a correct identifier */
3937 if (t
== TOK_PPNUM
) {
3947 if (!isnum(c
) && !isid(c
))
3951 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
3952 tok
= ts
->tok
; /* modify current token */
3955 const char *str
= cstr
.data
;
3956 const unsigned char *q
;
3958 /* we look for a valid token */
3959 /* XXX: do more extensive checks */
3960 if (!strcmp(str
, ">>=")) {
3962 } else if (!strcmp(str
, "<<=")) {
3964 } else if (strlen(str
) == 2) {
3965 /* search in two bytes table */
3970 if (q
[0] == str
[0] && q
[1] == str
[1])
3977 /* NOTE: because get_tok_str use a static buffer,
3980 p1
= get_tok_str(tok
, &tokc
);
3981 cstr_cat(&cstr
, p1
);
3982 cstr_ccat(&cstr
, '\0');
3983 p2
= get_tok_str(t
, &cval
);
3984 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
3985 /* cannot merge tokens: just add them separately */
3986 tok_str_add2(¯o_str1
, tok
, &tokc
);
3987 /* XXX: free associated memory ? */
3994 tok_str_add2(¯o_str1
, tok
, &tokc
);
3999 macro_ptr
= (int *)saved_macro_ptr
;
4001 tok_str_add(¯o_str1
, 0);
4002 return macro_str1
.str
;
4006 /* do macro substitution of macro_str and add result to
4007 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4008 inside to avoid recursing. */
4009 static void macro_subst(TokenString
*tok_str
,
4010 Sym
**nested_list
, const int *macro_str
)
4013 int *saved_macro_ptr
, *macro_str1
;
4018 /* first scan for '##' operator handling */
4020 macro_str1
= macro_twosharps(ptr
);
4024 /* NOTE: ptr == NULL can only happen if tokens are read from
4025 file stream due to a macro function call */
4028 TOK_GET(t
, ptr
, cval
);
4033 /* if nested substitution, do nothing */
4034 if (sym_find2(*nested_list
, t
))
4036 saved_macro_ptr
= macro_ptr
;
4037 macro_ptr
= (int *)ptr
;
4039 ret
= macro_subst_tok(tok_str
, nested_list
, s
);
4040 ptr
= (int *)macro_ptr
;
4041 macro_ptr
= saved_macro_ptr
;
4046 tok_str_add2(tok_str
, t
, &cval
);
4050 tok_str_free(macro_str1
);
4053 /* return next token with macro substitution */
4054 static void next(void)
4056 Sym
*nested_list
, *s
;
4062 /* if not reading from macro substituted string, then try
4063 to substitute macros */
4064 if (tok
>= TOK_IDENT
&&
4065 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4066 s
= define_find(tok
);
4068 /* we have a macro: we try to substitute */
4071 if (macro_subst_tok(&str
, &nested_list
, s
) == 0) {
4072 /* substitution done, NOTE: maybe empty */
4073 tok_str_add(&str
, 0);
4074 macro_ptr
= str
.str
;
4075 macro_ptr_allocated
= str
.str
;
4082 /* end of macro or end of unget buffer */
4083 if (unget_buffer_enabled
) {
4084 macro_ptr
= unget_saved_macro_ptr
;
4085 unget_buffer_enabled
= 0;
4087 /* end of macro string: free it */
4088 tok_str_free(macro_ptr_allocated
);
4095 /* convert preprocessor tokens into C tokens */
4096 if (tok
== TOK_PPNUM
&&
4097 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4098 parse_number((char *)tokc
.cstr
->data
);
4102 /* push back current token and set current token to 'last_tok'. Only
4103 identifier case handled for labels. */
4104 static inline void unget_tok(int last_tok
)
4108 unget_saved_macro_ptr
= macro_ptr
;
4109 unget_buffer_enabled
= 1;
4110 q
= unget_saved_buffer
;
4113 n
= tok_ext_size(tok
) - 1;
4116 *q
= 0; /* end of token string */
4121 void swap(int *p
, int *q
)
4129 void vsetc(CType
*type
, int r
, CValue
*vc
)
4133 if (vtop
>= vstack
+ VSTACK_SIZE
)
4134 error("memory full");
4135 /* cannot let cpu flags if other instruction are generated. Also
4136 avoid leaving VT_JMP anywhere except on the top of the stack
4137 because it would complicate the code generator. */
4138 if (vtop
>= vstack
) {
4139 v
= vtop
->r
& VT_VALMASK
;
4140 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4146 vtop
->r2
= VT_CONST
;
4150 /* push integer constant */
4155 vsetc(&int_type
, VT_CONST
, &cval
);
4158 /* Return a static symbol pointing to a section */
4159 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4160 unsigned long offset
, unsigned long size
)
4166 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4167 sym
->type
.ref
= type
->ref
;
4168 sym
->r
= VT_CONST
| VT_SYM
;
4169 put_extern_sym(sym
, sec
, offset
, size
);
4173 /* push a reference to a section offset by adding a dummy symbol */
4174 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4179 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4180 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4183 /* define a new external reference to a symbol 'v' of type 'u' */
4184 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4190 /* push forward reference */
4191 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4192 s
->type
.ref
= type
->ref
;
4193 s
->r
= r
| VT_CONST
| VT_SYM
;
4198 /* define a new external reference to a symbol 'v' of type 'u' */
4199 static Sym
*external_sym(int v
, CType
*type
, int r
)
4205 /* push forward reference */
4206 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4207 s
->type
.t
|= VT_EXTERN
;
4209 if (!is_compatible_types(&s
->type
, type
))
4210 error("incompatible types for redefinition of '%s'",
4211 get_tok_str(v
, NULL
));
4216 /* push a reference to global symbol v */
4217 static void vpush_global_sym(CType
*type
, int v
)
4222 sym
= external_global_sym(v
, type
, 0);
4224 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4228 void vset(CType
*type
, int r
, int v
)
4233 vsetc(type
, r
, &cval
);
4236 void vseti(int r
, int v
)
4252 void vpushv(SValue
*v
)
4254 if (vtop
>= vstack
+ VSTACK_SIZE
)
4255 error("memory full");
4265 /* save r to the memory stack, and mark it as being free */
4266 void save_reg(int r
)
4268 int l
, saved
, size
, align
;
4272 /* modify all stack values */
4275 for(p
=vstack
;p
<=vtop
;p
++) {
4276 if ((p
->r
& VT_VALMASK
) == r
||
4277 (p
->r2
& VT_VALMASK
) == r
) {
4278 /* must save value on stack if not already done */
4280 /* NOTE: must reload 'r' because r might be equal to r2 */
4281 r
= p
->r
& VT_VALMASK
;
4282 /* store register in the stack */
4284 if ((p
->r
& VT_LVAL
) ||
4285 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4287 size
= type_size(type
, &align
);
4288 loc
= (loc
- size
) & -align
;
4289 sv
.type
.t
= type
->t
;
4290 sv
.r
= VT_LOCAL
| VT_LVAL
;
4293 #ifdef TCC_TARGET_I386
4294 /* x86 specific: need to pop fp register ST0 if saved */
4295 if (r
== TREG_ST0
) {
4296 o(0xd9dd); /* fstp %st(1) */
4299 /* special long long case */
4300 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4307 /* mark that stack entry as being saved on the stack */
4308 if (p
->r
& VT_LVAL
) {
4309 /* also clear the bounded flag because the
4310 relocation address of the function was stored in
4312 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4314 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4322 /* find a free register of class 'rc'. If none, save one register */
4328 /* find a free register */
4329 for(r
=0;r
<NB_REGS
;r
++) {
4330 if (reg_classes
[r
] & rc
) {
4331 for(p
=vstack
;p
<=vtop
;p
++) {
4332 if ((p
->r
& VT_VALMASK
) == r
||
4333 (p
->r2
& VT_VALMASK
) == r
)
4341 /* no register left : free the first one on the stack (VERY
4342 IMPORTANT to start from the bottom to ensure that we don't
4343 spill registers used in gen_opi()) */
4344 for(p
=vstack
;p
<=vtop
;p
++) {
4345 r
= p
->r
& VT_VALMASK
;
4346 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4348 /* also look at second register (if long long) */
4349 r
= p
->r2
& VT_VALMASK
;
4350 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4356 /* Should never comes here */
4360 /* save registers up to (vtop - n) stack entry */
4361 void save_regs(int n
)
4366 for(p
= vstack
;p
<= p1
; p
++) {
4367 r
= p
->r
& VT_VALMASK
;
4374 /* move register 's' to 'r', and flush previous value of r to memory
4376 void move_reg(int r
, int s
)
4389 /* get address of vtop (vtop MUST BE an lvalue) */
4392 vtop
->r
&= ~VT_LVAL
;
4393 /* tricky: if saved lvalue, then we can go back to lvalue */
4394 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4395 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4398 #ifdef CONFIG_TCC_BCHECK
4399 /* generate lvalue bound code */
4405 vtop
->r
&= ~VT_MUSTBOUND
;
4406 /* if lvalue, then use checking code before dereferencing */
4407 if (vtop
->r
& VT_LVAL
) {
4408 /* if not VT_BOUNDED value, then make one */
4409 if (!(vtop
->r
& VT_BOUNDED
)) {
4410 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4411 /* must save type because we must set it to int to get pointer */
4413 vtop
->type
.t
= VT_INT
;
4416 gen_bounded_ptr_add();
4417 vtop
->r
|= lval_type
;
4420 /* then check for dereferencing */
4421 gen_bounded_ptr_deref();
4426 /* store vtop a register belonging to class 'rc'. lvalues are
4427 converted to values. Cannot be used if cannot be converted to
4428 register value (such as structures). */
4431 int r
, r2
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4432 unsigned long long ll
;
4434 /* NOTE: get_reg can modify vstack[] */
4435 if (vtop
->type
.t
& VT_BITFIELD
) {
4436 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4437 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4438 /* remove bit field info to avoid loops */
4439 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4440 /* generate shifts */
4441 vpushi(32 - (bit_pos
+ bit_size
));
4443 vpushi(32 - bit_size
);
4444 /* NOTE: transformed to SHR if unsigned */
4448 if (is_float(vtop
->type
.t
) &&
4449 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4452 unsigned long offset
;
4454 /* XXX: unify with initializers handling ? */
4455 /* CPUs usually cannot use float constants, so we store them
4456 generically in data segment */
4457 size
= type_size(&vtop
->type
, &align
);
4458 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
4459 data_section
->data_offset
= offset
;
4460 /* XXX: not portable yet */
4461 ptr
= section_ptr_add(data_section
, size
);
4464 ptr
[i
] = vtop
->c
.tab
[i
];
4465 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
4466 vtop
->r
|= VT_LVAL
| VT_SYM
;
4470 #ifdef CONFIG_TCC_BCHECK
4471 if (vtop
->r
& VT_MUSTBOUND
)
4475 r
= vtop
->r
& VT_VALMASK
;
4476 /* need to reload if:
4478 - lvalue (need to dereference pointer)
4479 - already a register, but not in the right class */
4480 if (r
>= VT_CONST
||
4481 (vtop
->r
& VT_LVAL
) ||
4482 !(reg_classes
[r
] & rc
) ||
4483 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
4484 !(reg_classes
[vtop
->r2
] & rc
))) {
4486 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
4487 /* two register type load : expand to two words
4489 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4492 vtop
->c
.ui
= ll
; /* first word */
4494 vtop
->r
= r
; /* save register value */
4495 vpushi(ll
>> 32); /* second word */
4496 } else if (r
>= VT_CONST
||
4497 (vtop
->r
& VT_LVAL
)) {
4498 /* load from memory */
4501 vtop
[-1].r
= r
; /* save register value */
4502 /* increment pointer to get second word */
4503 vtop
->type
.t
= VT_INT
;
4509 /* move registers */
4512 vtop
[-1].r
= r
; /* save register value */
4513 vtop
->r
= vtop
[-1].r2
;
4515 /* allocate second register */
4522 /* write second register */
4524 } else if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
4526 /* lvalue of scalar type : need to use lvalue type
4527 because of possible cast */
4530 /* compute memory access type */
4531 if (vtop
->r
& VT_LVAL_BYTE
)
4533 else if (vtop
->r
& VT_LVAL_SHORT
)
4535 if (vtop
->r
& VT_LVAL_UNSIGNED
)
4539 /* restore wanted type */
4542 /* one register type load */
4551 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
4552 void gv2(int rc1
, int rc2
)
4556 /* generate more generic register first. But VT_JMP or VT_CMP
4557 values must be generated first in all cases to avoid possible
4559 v
= vtop
[0].r
& VT_VALMASK
;
4560 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
4565 /* test if reload is needed for first register */
4566 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
4576 /* test if reload is needed for first register */
4577 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
4583 /* expand long long on stack in two int registers */
4588 u
= vtop
->type
.t
& VT_UNSIGNED
;
4591 vtop
[0].r
= vtop
[-1].r2
;
4592 vtop
[0].r2
= VT_CONST
;
4593 vtop
[-1].r2
= VT_CONST
;
4594 vtop
[0].type
.t
= VT_INT
| u
;
4595 vtop
[-1].type
.t
= VT_INT
| u
;
4598 /* build a long long from two ints */
4601 gv2(RC_INT
, RC_INT
);
4602 vtop
[-1].r2
= vtop
[0].r
;
4603 vtop
[-1].type
.t
= t
;
4607 /* rotate n first stack elements to the bottom
4608 I1 ... In -> I2 ... In I1 [top is right]
4616 for(i
=-n
+1;i
!=0;i
++)
4617 vtop
[i
] = vtop
[i
+1];
4621 /* rotate n first stack elements to the top
4622 I1 ... In -> In I1 ... I(n-1) [top is right]
4630 for(i
= 0;i
< n
- 1; i
++)
4631 vtop
[-i
] = vtop
[-i
- 1];
4635 /* pop stack value */
4639 v
= vtop
->r
& VT_VALMASK
;
4640 #ifdef TCC_TARGET_I386
4641 /* for x86, we need to pop the FP stack */
4642 if (v
== TREG_ST0
&& !nocode_wanted
) {
4643 o(0xd9dd); /* fstp %st(1) */
4646 if (v
== VT_JMP
|| v
== VT_JMPI
) {
4647 /* need to put correct jump if && or || without test */
4653 /* convert stack entry to register and duplicate its value in another
4661 if ((t
& VT_BTYPE
) == VT_LLONG
) {
4668 /* stack: H L L1 H1 */
4676 /* duplicate value */
4687 load(r1
, &sv
); /* move r to r1 */
4689 /* duplicates value */
4694 /* generate CPU independent (unsigned) long long operations */
4695 void gen_opl(int op
)
4697 int t
, a
, b
, op1
, c
, i
;
4704 func
= TOK___divdi3
;
4707 func
= TOK___udivdi3
;
4710 func
= TOK___moddi3
;
4713 func
= TOK___umoddi3
;
4715 /* call generic long long function */
4716 vpush_global_sym(&func_old_type
, func
);
4721 vtop
->r2
= REG_LRET
;
4734 /* stack: L1 H1 L2 H2 */
4739 vtop
[-2] = vtop
[-3];
4742 /* stack: H1 H2 L1 L2 */
4748 /* stack: H1 H2 L1 L2 ML MH */
4751 /* stack: ML MH H1 H2 L1 L2 */
4755 /* stack: ML MH H1 L2 H2 L1 */
4760 /* stack: ML MH M1 M2 */
4763 } else if (op
== '+' || op
== '-') {
4764 /* XXX: add non carry method too (for MIPS or alpha) */
4770 /* stack: H1 H2 (L1 op L2) */
4773 gen_op(op1
+ 1); /* TOK_xxxC2 */
4776 /* stack: H1 H2 (L1 op L2) */
4779 /* stack: (L1 op L2) H1 H2 */
4781 /* stack: (L1 op L2) (H1 op H2) */
4789 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
4790 t
= vtop
[-1].type
.t
;
4794 /* stack: L H shift */
4796 /* constant: simpler */
4797 /* NOTE: all comments are for SHL. the other cases are
4798 done by swaping words */
4809 if (op
!= TOK_SAR
) {
4842 /* XXX: should provide a faster fallback on x86 ? */
4845 func
= TOK___sardi3
;
4848 func
= TOK___shrdi3
;
4851 func
= TOK___shldi3
;
4857 /* compare operations */
4863 /* stack: L1 H1 L2 H2 */
4865 vtop
[-1] = vtop
[-2];
4867 /* stack: L1 L2 H1 H2 */
4870 /* when values are equal, we need to compare low words. since
4871 the jump is inverted, we invert the test too. */
4874 else if (op1
== TOK_GT
)
4876 else if (op1
== TOK_ULT
)
4878 else if (op1
== TOK_UGT
)
4883 if (op1
!= TOK_NE
) {
4887 /* generate non equal test */
4888 /* XXX: NOT PORTABLE yet */
4892 #ifdef TCC_TARGET_I386
4893 b
= psym(0x850f, 0);
4895 error("not implemented");
4899 /* compare low. Always unsigned */
4903 else if (op1
== TOK_LE
)
4905 else if (op1
== TOK_GT
)
4907 else if (op1
== TOK_GE
)
4917 /* handle integer constant optimizations and various machine
4919 void gen_opic(int op
)
4926 /* currently, we cannot do computations with forward symbols */
4927 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4928 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4932 case '+': v1
->c
.i
+= fc
; break;
4933 case '-': v1
->c
.i
-= fc
; break;
4934 case '&': v1
->c
.i
&= fc
; break;
4935 case '^': v1
->c
.i
^= fc
; break;
4936 case '|': v1
->c
.i
|= fc
; break;
4937 case '*': v1
->c
.i
*= fc
; break;
4944 /* if division by zero, generate explicit division */
4947 error("division by zero in constant");
4951 default: v1
->c
.i
/= fc
; break;
4952 case '%': v1
->c
.i
%= fc
; break;
4953 case TOK_UDIV
: v1
->c
.i
= (unsigned)v1
->c
.i
/ fc
; break;
4954 case TOK_UMOD
: v1
->c
.i
= (unsigned)v1
->c
.i
% fc
; break;
4957 case TOK_SHL
: v1
->c
.i
<<= fc
; break;
4958 case TOK_SHR
: v1
->c
.i
= (unsigned)v1
->c
.i
>> fc
; break;
4959 case TOK_SAR
: v1
->c
.i
>>= fc
; break;
4961 case TOK_ULT
: v1
->c
.i
= (unsigned)v1
->c
.i
< (unsigned)fc
; break;
4962 case TOK_UGE
: v1
->c
.i
= (unsigned)v1
->c
.i
>= (unsigned)fc
; break;
4963 case TOK_EQ
: v1
->c
.i
= v1
->c
.i
== fc
; break;
4964 case TOK_NE
: v1
->c
.i
= v1
->c
.i
!= fc
; break;
4965 case TOK_ULE
: v1
->c
.i
= (unsigned)v1
->c
.i
<= (unsigned)fc
; break;
4966 case TOK_UGT
: v1
->c
.i
= (unsigned)v1
->c
.i
> (unsigned)fc
; break;
4967 case TOK_LT
: v1
->c
.i
= v1
->c
.i
< fc
; break;
4968 case TOK_GE
: v1
->c
.i
= v1
->c
.i
>= fc
; break;
4969 case TOK_LE
: v1
->c
.i
= v1
->c
.i
<= fc
; break;
4970 case TOK_GT
: v1
->c
.i
= v1
->c
.i
> fc
; break;
4972 case TOK_LAND
: v1
->c
.i
= v1
->c
.i
&& fc
; break;
4973 case TOK_LOR
: v1
->c
.i
= v1
->c
.i
|| fc
; break;
4979 /* if commutative ops, put c2 as constant */
4980 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
4981 op
== '|' || op
== '*')) {
4986 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
4989 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
4990 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
4996 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
4997 /* try to use shifts instead of muls or divs */
4998 if (fc
> 0 && (fc
& (fc
- 1)) == 0) {
5007 else if (op
== TOK_PDIV
)
5013 } else if (c2
&& (op
== '+' || op
== '-') &&
5014 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5015 (VT_CONST
| VT_SYM
)) {
5016 /* symbol + constant case */
5023 if (!nocode_wanted
) {
5024 /* call low level op generator */
5033 /* generate a floating point operation with constant propagation */
5034 void gen_opif(int op
)
5042 /* currently, we cannot do computations with forward symbols */
5043 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5044 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5046 if (v1
->type
.t
== VT_FLOAT
) {
5049 } else if (v1
->type
.t
== VT_DOUBLE
) {
5057 /* NOTE: we only do constant propagation if finite number (not
5058 NaN or infinity) (ANSI spec) */
5059 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5063 case '+': f1
+= f2
; break;
5064 case '-': f1
-= f2
; break;
5065 case '*': f1
*= f2
; break;
5069 error("division by zero in constant");
5074 /* XXX: also handles tests ? */
5078 /* XXX: overflow test ? */
5079 if (v1
->type
.t
== VT_FLOAT
) {
5081 } else if (v1
->type
.t
== VT_DOUBLE
) {
5089 if (!nocode_wanted
) {
5097 static int pointed_size(CType
*type
)
5100 return type_size(pointed_type(type
), &align
);
5103 static inline int is_null_pointer(SValue
*p
)
5105 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5107 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5108 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5111 static inline int is_integer_btype(int bt
)
5113 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5114 bt
== VT_INT
|| bt
== VT_LLONG
);
5117 /* check types for comparison or substraction of pointers */
5118 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5120 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5123 /* null pointers are accepted for all comparisons as gcc */
5124 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5128 bt1
= type1
->t
& VT_BTYPE
;
5129 bt2
= type2
->t
& VT_BTYPE
;
5130 /* accept comparison between pointer and integer with a warning */
5131 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5132 warning("comparison between pointer and integer");
5136 /* both must be pointers or implicit function pointers */
5137 if (bt1
== VT_PTR
) {
5138 type1
= pointed_type(type1
);
5139 } else if (bt1
!= VT_FUNC
)
5140 goto invalid_operands
;
5142 if (bt2
== VT_PTR
) {
5143 type2
= pointed_type(type2
);
5144 } else if (bt2
!= VT_FUNC
) {
5146 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5148 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5149 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5153 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5154 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5155 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5156 /* gcc-like error if '-' is used */
5158 goto invalid_operands
;
5160 warning("comparison of distinct pointer types lacks a cast");
5164 /* generic gen_op: handles types problems */
5167 int u
, t1
, t2
, bt1
, bt2
, t
;
5170 t1
= vtop
[-1].type
.t
;
5171 t2
= vtop
[0].type
.t
;
5172 bt1
= t1
& VT_BTYPE
;
5173 bt2
= t2
& VT_BTYPE
;
5175 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5176 /* at least one operand is a pointer */
5177 /* relationnal op: must be both pointers */
5178 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5179 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5180 /* pointers are handled are unsigned */
5181 t
= VT_INT
| VT_UNSIGNED
;
5184 /* if both pointers, then it must be the '-' op */
5185 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5187 error("cannot use pointers here");
5188 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5189 /* XXX: check that types are compatible */
5190 u
= pointed_size(&vtop
[-1].type
);
5192 /* set to integer type */
5193 vtop
->type
.t
= VT_INT
;
5197 /* exactly one pointer : must be '+' or '-'. */
5198 if (op
!= '-' && op
!= '+')
5199 error("cannot use pointers here");
5200 /* Put pointer as first operand */
5201 if (bt2
== VT_PTR
) {
5205 type1
= vtop
[-1].type
;
5206 /* XXX: cast to int ? (long long case) */
5207 vpushi(pointed_size(&vtop
[-1].type
));
5209 #ifdef CONFIG_TCC_BCHECK
5210 /* if evaluating constant expression, no code should be
5211 generated, so no bound check */
5212 if (do_bounds_check
&& !const_wanted
) {
5213 /* if bounded pointers, we generate a special code to
5220 gen_bounded_ptr_add();
5226 /* put again type if gen_opic() swaped operands */
5229 } else if (is_float(bt1
) || is_float(bt2
)) {
5230 /* compute bigger type and do implicit casts */
5231 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5233 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5238 /* floats can only be used for a few operations */
5239 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5240 (op
< TOK_ULT
|| op
> TOK_GT
))
5241 error("invalid operands for binary operation");
5243 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5244 /* cast to biggest op */
5246 /* convert to unsigned if it does not fit in a long long */
5247 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5248 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5252 /* integer operations */
5254 /* convert to unsigned if it does not fit in an integer */
5255 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5256 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5259 /* XXX: currently, some unsigned operations are explicit, so
5260 we modify them here */
5261 if (t
& VT_UNSIGNED
) {
5268 else if (op
== TOK_LT
)
5270 else if (op
== TOK_GT
)
5272 else if (op
== TOK_LE
)
5274 else if (op
== TOK_GE
)
5281 /* special case for shifts and long long: we keep the shift as
5283 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5288 else if ((t
& VT_BTYPE
) == VT_LLONG
)
5292 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5293 /* relationnal op: the result is an int */
5294 vtop
->type
.t
= VT_INT
;
5301 /* generic itof for unsigned long long case */
5302 void gen_cvt_itof1(int t
)
5304 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
5305 (VT_LLONG
| VT_UNSIGNED
)) {
5308 vpush_global_sym(&func_old_type
, TOK___ulltof
);
5309 else if (t
== VT_DOUBLE
)
5310 vpush_global_sym(&func_old_type
, TOK___ulltod
);
5312 vpush_global_sym(&func_old_type
, TOK___ulltold
);
5322 /* generic ftoi for unsigned long long case */
5323 void gen_cvt_ftoi1(int t
)
5327 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
5328 /* not handled natively */
5329 st
= vtop
->type
.t
& VT_BTYPE
;
5331 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
5332 else if (st
== VT_DOUBLE
)
5333 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
5335 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
5340 vtop
->r2
= REG_LRET
;
5346 /* force char or short cast */
5347 void force_charshort_cast(int t
)
5351 /* XXX: add optimization if lvalue : just change type and offset */
5356 if (t
& VT_UNSIGNED
) {
5357 vpushi((1 << bits
) - 1);
5368 /* cast 'vtop' to 'type' */
5369 static void gen_cast(CType
*type
)
5371 int sbt
, dbt
, sf
, df
, c
;
5373 /* special delayed cast for char/short */
5374 /* XXX: in some cases (multiple cascaded casts), it may still
5376 if (vtop
->r
& VT_MUSTCAST
) {
5377 vtop
->r
&= ~VT_MUSTCAST
;
5378 force_charshort_cast(vtop
->type
.t
);
5381 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
5382 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
5384 if (sbt
!= dbt
&& !nocode_wanted
) {
5387 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5389 /* convert from fp to fp */
5391 /* constant case: we can do it now */
5392 /* XXX: in ISOC, cannot do it if error in convert */
5393 if (dbt
== VT_FLOAT
&& sbt
== VT_DOUBLE
)
5394 vtop
->c
.f
= (float)vtop
->c
.d
;
5395 else if (dbt
== VT_FLOAT
&& sbt
== VT_LDOUBLE
)
5396 vtop
->c
.f
= (float)vtop
->c
.ld
;
5397 else if (dbt
== VT_DOUBLE
&& sbt
== VT_FLOAT
)
5398 vtop
->c
.d
= (double)vtop
->c
.f
;
5399 else if (dbt
== VT_DOUBLE
&& sbt
== VT_LDOUBLE
)
5400 vtop
->c
.d
= (double)vtop
->c
.ld
;
5401 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_FLOAT
)
5402 vtop
->c
.ld
= (long double)vtop
->c
.f
;
5403 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_DOUBLE
)
5404 vtop
->c
.ld
= (long double)vtop
->c
.d
;
5406 /* non constant case: generate code */
5410 /* convert int to fp */
5413 case VT_LLONG
| VT_UNSIGNED
:
5415 /* XXX: add const cases for long long */
5417 case VT_INT
| VT_UNSIGNED
:
5419 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.ui
; break;
5420 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.ui
; break;
5421 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.ui
; break;
5426 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.i
; break;
5427 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.i
; break;
5428 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.i
; break;
5437 /* convert fp to int */
5438 /* we handle char/short/etc... with generic code */
5439 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
5440 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
5445 case VT_LLONG
| VT_UNSIGNED
:
5447 /* XXX: add const cases for long long */
5449 case VT_INT
| VT_UNSIGNED
:
5451 case VT_FLOAT
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5452 case VT_DOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5453 case VT_LDOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5459 case VT_FLOAT
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5460 case VT_DOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5461 case VT_LDOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5469 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
5470 /* additional cast for char/short/bool... */
5474 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
5475 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
5476 /* scalar to long long */
5478 if (sbt
== (VT_INT
| VT_UNSIGNED
))
5479 vtop
->c
.ll
= vtop
->c
.ui
;
5481 vtop
->c
.ll
= vtop
->c
.i
;
5483 /* machine independent conversion */
5485 /* generate high word */
5486 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
5494 /* patch second register */
5495 vtop
[-1].r2
= vtop
->r
;
5499 } else if (dbt
== VT_BOOL
) {
5500 /* scalar to bool */
5503 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
5504 (dbt
& VT_BTYPE
) == VT_SHORT
) {
5505 force_charshort_cast(dbt
);
5506 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
5508 if (sbt
== VT_LLONG
) {
5509 /* from long long: just take low order word */
5513 /* if lvalue and single word type, nothing to do because
5514 the lvalue already contains the real type size (see
5515 VT_LVAL_xxx constants) */
5521 /* return type size. Put alignment at 'a' */
5522 static int type_size(CType
*type
, int *a
)
5527 bt
= type
->t
& VT_BTYPE
;
5528 if (bt
== VT_STRUCT
) {
5533 } else if (bt
== VT_PTR
) {
5534 if (type
->t
& VT_ARRAY
) {
5536 return type_size(&s
->type
, a
) * s
->c
;
5541 } else if (bt
== VT_LDOUBLE
) {
5543 return LDOUBLE_SIZE
;
5544 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
5545 *a
= 4; /* XXX: i386 specific */
5547 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
5550 } else if (bt
== VT_SHORT
) {
5554 /* char, void, function, _Bool */
5560 /* return the pointed type of t */
5561 static inline CType
*pointed_type(CType
*type
)
5563 return &type
->ref
->type
;
5566 /* modify type so that its it is a pointer to type. */
5567 static void mk_pointer(CType
*type
)
5570 s
= sym_push(SYM_FIELD
, type
, 0, -1);
5571 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
5575 /* compare function types. OLD functions match any new functions */
5576 static int is_compatible_func(CType
*type1
, CType
*type2
)
5582 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5584 /* XXX: not complete */
5585 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
5589 while (s1
!= NULL
) {
5592 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5602 /* return true if type1 and type2 are exactly the same (including
5605 - enums are not checked as gcc __builtin_types_compatible_p ()
5607 static int is_compatible_types(CType
*type1
, CType
*type2
)
5611 t1
= type1
->t
& VT_TYPE
;
5612 t2
= type2
->t
& VT_TYPE
;
5613 /* XXX: bitfields ? */
5616 /* test more complicated cases */
5617 bt1
= t1
& VT_BTYPE
;
5618 if (bt1
== VT_PTR
) {
5619 type1
= pointed_type(type1
);
5620 type2
= pointed_type(type2
);
5621 return is_compatible_types(type1
, type2
);
5622 } else if (bt1
== VT_STRUCT
) {
5623 return (type1
->ref
== type2
->ref
);
5624 } else if (bt1
== VT_FUNC
) {
5625 return is_compatible_func(type1
, type2
);
5631 /* print a type. If 'varstr' is not NULL, then the variable is also
5632 printed in the type */
5634 /* XXX: add array and function pointers */
5635 void type_to_str(char *buf
, int buf_size
,
5636 CType
*type
, const char *varstr
)
5643 t
= type
->t
& VT_TYPE
;
5646 if (t
& VT_CONSTANT
)
5647 pstrcat(buf
, buf_size
, "const ");
5648 if (t
& VT_VOLATILE
)
5649 pstrcat(buf
, buf_size
, "volatile ");
5650 if (t
& VT_UNSIGNED
)
5651 pstrcat(buf
, buf_size
, "unsigned ");
5681 tstr
= "long double";
5683 pstrcat(buf
, buf_size
, tstr
);
5687 if (bt
== VT_STRUCT
)
5691 pstrcat(buf
, buf_size
, tstr
);
5692 v
= type
->ref
->v
& ~SYM_STRUCT
;
5693 if (v
>= SYM_FIRST_ANOM
)
5694 pstrcat(buf
, buf_size
, "<anonymous>");
5696 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
5700 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
5701 pstrcat(buf
, buf_size
, "(");
5703 while (sa
!= NULL
) {
5704 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
5705 pstrcat(buf
, buf_size
, buf1
);
5708 pstrcat(buf
, buf_size
, ", ");
5710 pstrcat(buf
, buf_size
, ")");
5714 pstrcpy(buf1
, sizeof(buf1
), "*");
5716 pstrcat(buf1
, sizeof(buf1
), varstr
);
5717 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
5721 pstrcat(buf
, buf_size
, " ");
5722 pstrcat(buf
, buf_size
, varstr
);
5727 /* verify type compatibility to store vtop in 'dt' type, and generate
5729 static void gen_assign_cast(CType
*dt
)
5731 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
5732 char buf1
[256], buf2
[256];
5735 st
= &vtop
->type
; /* source type */
5736 dbt
= dt
->t
& VT_BTYPE
;
5737 sbt
= st
->t
& VT_BTYPE
;
5738 if (dt
->t
& VT_CONSTANT
)
5739 warning("assignment of read-only location");
5742 /* special cases for pointers */
5743 /* '0' can also be a pointer */
5744 if (is_null_pointer(vtop
))
5746 /* accept implicit pointer to integer cast with warning */
5747 if (is_integer_btype(sbt
)) {
5748 warning("assignment makes pointer from integer without a cast");
5751 type1
= pointed_type(dt
);
5752 /* a function is implicitely a function pointer */
5753 if (sbt
== VT_FUNC
) {
5754 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
5755 !is_compatible_types(pointed_type(dt
), st
))
5762 type2
= pointed_type(st
);
5763 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5764 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
5765 /* void * can match anything */
5767 /* exact type match, except for unsigned */
5770 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5771 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5772 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
5775 /* check const and volatile */
5776 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
5777 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
5778 warning("assignment discards qualifiers from pointer target type");
5784 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
5785 warning("assignment makes integer from pointer without a cast");
5787 /* XXX: more tests */
5790 if (!is_compatible_types(dt
, st
)) {
5792 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
5793 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
5794 error("cannot cast '%s' to '%s'", buf1
, buf2
);
5802 /* store vtop in lvalue pushed on stack */
5805 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
5807 ft
= vtop
[-1].type
.t
;
5808 sbt
= vtop
->type
.t
& VT_BTYPE
;
5809 dbt
= ft
& VT_BTYPE
;
5810 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
5811 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
5812 /* optimize char/short casts */
5813 delayed_cast
= VT_MUSTCAST
;
5814 vtop
->type
.t
= ft
& VT_TYPE
;
5815 /* XXX: factorize */
5816 if (ft
& VT_CONSTANT
)
5817 warning("assignment of read-only location");
5820 gen_assign_cast(&vtop
[-1].type
);
5823 if (sbt
== VT_STRUCT
) {
5824 /* if structure, only generate pointer */
5825 /* structure assignment : generate memcpy */
5826 /* XXX: optimize if small size */
5827 if (!nocode_wanted
) {
5828 size
= type_size(&vtop
->type
, &align
);
5830 vpush_global_sym(&func_old_type
, TOK_memcpy
);
5834 vtop
->type
.t
= VT_INT
;
5838 vtop
->type
.t
= VT_INT
;
5850 /* leave source on stack */
5851 } else if (ft
& VT_BITFIELD
) {
5852 /* bitfield store handling */
5853 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
5854 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
5855 /* remove bit field info to avoid loops */
5856 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
5858 /* duplicate destination */
5860 vtop
[-1] = vtop
[-2];
5862 /* mask and shift source */
5863 vpushi((1 << bit_size
) - 1);
5867 /* load destination, mask and or with source */
5869 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
5875 #ifdef CONFIG_TCC_BCHECK
5876 /* bound check case */
5877 if (vtop
[-1].r
& VT_MUSTBOUND
) {
5883 if (!nocode_wanted
) {
5887 r
= gv(rc
); /* generate value */
5888 /* if lvalue was saved on stack, must read it */
5889 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
5891 t
= get_reg(RC_INT
);
5893 sv
.r
= VT_LOCAL
| VT_LVAL
;
5894 sv
.c
.ul
= vtop
[-1].c
.ul
;
5896 vtop
[-1].r
= t
| VT_LVAL
;
5899 /* two word case handling : store second register at word + 4 */
5900 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
5902 /* convert to int to increment easily */
5903 vtop
->type
.t
= VT_INT
;
5909 /* XXX: it works because r2 is spilled last ! */
5910 store(vtop
->r2
, vtop
- 1);
5914 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
5915 vtop
->r
|= delayed_cast
;
5919 /* post defines POST/PRE add. c is the token ++ or -- */
5920 void inc(int post
, int c
)
5923 vdup(); /* save lvalue */
5925 gv_dup(); /* duplicate value */
5930 vpushi(c
- TOK_MID
);
5932 vstore(); /* store value */
5934 vpop(); /* if post op, return saved value */
5937 /* Parse GNUC __attribute__ extension. Currently, the following
5938 extensions are recognized:
5939 - aligned(n) : set data/function alignment.
5940 - section(x) : generate data/code in this section.
5941 - unused : currently ignored, but may be used someday.
5943 static void parse_attribute(AttributeDef
*ad
)
5947 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
5951 while (tok
!= ')') {
5952 if (tok
< TOK_IDENT
)
5953 expect("attribute name");
5961 expect("section name");
5962 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
5971 if (n
<= 0 || (n
& (n
- 1)) != 0)
5972 error("alignment must be a positive power of two");
5981 /* currently, no need to handle it because tcc does not
5982 track unused objects */
5986 /* currently, no need to handle it because tcc does not
5987 track unused objects */
5992 ad
->func_call
= FUNC_CDECL
;
5997 ad
->func_call
= FUNC_STDCALL
;
6000 if (tcc_state
->warn_unsupported
)
6001 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6002 /* skip parameters */
6003 /* XXX: skip parenthesis too */
6006 while (tok
!= ')' && tok
!= -1)
6021 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6022 static void struct_decl(CType
*type
, int u
)
6024 int a
, v
, size
, align
, maxalign
, c
, offset
;
6025 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
;
6030 a
= tok
; /* save decl type */
6035 /* struct already defined ? return it */
6037 expect("struct/union/enum name");
6041 error("invalid type");
6048 /* we put an undefined size for struct/union */
6049 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6050 s
->r
= 0; /* default alignment is zero as gcc */
6051 /* put struct/union/enum name in type */
6059 error("struct/union/enum already defined");
6060 /* cannot be empty */
6062 /* non empty enums are not allowed */
6063 if (a
== TOK_ENUM
) {
6067 expect("identifier");
6073 /* enum symbols have static storage */
6074 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6075 ss
->type
.t
|= VT_STATIC
;
6080 /* NOTE: we accept a trailing comma */
6090 while (tok
!= '}') {
6091 parse_btype(&btype
, &ad
);
6097 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
);
6098 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6099 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6100 error("invalid type for '%s'",
6101 get_tok_str(v
, NULL
));
6105 bit_size
= expr_const();
6106 /* XXX: handle v = 0 case for messages */
6108 error("negative width in bit-field '%s'",
6109 get_tok_str(v
, NULL
));
6110 if (v
&& bit_size
== 0)
6111 error("zero width for bit-field '%s'",
6112 get_tok_str(v
, NULL
));
6114 size
= type_size(&type1
, &align
);
6116 if (bit_size
>= 0) {
6117 bt
= type1
.t
& VT_BTYPE
;
6122 error("bitfields must have scalar type");
6124 if (bit_size
> bsize
) {
6125 error("width of '%s' exceeds its type",
6126 get_tok_str(v
, NULL
));
6127 } else if (bit_size
== bsize
) {
6128 /* no need for bit fields */
6130 } else if (bit_size
== 0) {
6131 /* XXX: what to do if only padding in a
6133 /* zero size: means to pad */
6137 /* we do not have enough room ? */
6138 if ((bit_pos
+ bit_size
) > bsize
)
6141 /* XXX: handle LSB first */
6142 type1
.t
|= VT_BITFIELD
|
6143 (bit_pos
<< VT_STRUCT_SHIFT
) |
6144 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
6145 bit_pos
+= bit_size
;
6151 /* add new memory data only if starting
6153 if (lbit_pos
== 0) {
6154 if (a
== TOK_STRUCT
) {
6155 c
= (c
+ align
- 1) & -align
;
6163 if (align
> maxalign
)
6167 printf("add field %s offset=%d",
6168 get_tok_str(v
, NULL
), offset
);
6169 if (type1
.t
& VT_BITFIELD
) {
6170 printf(" pos=%d size=%d",
6171 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
6172 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
6176 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
6180 if (tok
== ';' || tok
== TOK_EOF
)
6187 /* store size and alignment */
6188 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
6194 /* return 0 if no type declaration. otherwise, return the basic type
6197 static int parse_btype(CType
*type
, AttributeDef
*ad
)
6199 int t
, u
, type_found
;
6203 memset(ad
, 0, sizeof(AttributeDef
));
6209 /* currently, we really ignore extension */
6219 if ((t
& VT_BTYPE
) != 0)
6220 error("too many basic types");
6234 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
6235 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6236 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
6237 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
6251 if ((t
& VT_BTYPE
) == VT_LONG
) {
6252 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6259 struct_decl(&type1
, VT_ENUM
);
6262 type
->ref
= type1
.ref
;
6266 struct_decl(&type1
, VT_STRUCT
);
6269 /* type modifiers */
6317 /* GNUC attribute */
6318 case TOK_ATTRIBUTE1
:
6319 case TOK_ATTRIBUTE2
:
6320 parse_attribute(ad
);
6327 parse_expr_type(&type1
);
6331 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
6333 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
6334 type
->ref
= s
->type
.ref
;
6341 /* long is never used as type */
6342 if ((t
& VT_BTYPE
) == VT_LONG
)
6343 t
= (t
& ~VT_BTYPE
) | VT_INT
;
6348 /* convert a function parameter type (array to pointer and function to
6349 function pointer) */
6350 static inline void convert_parameter_type(CType
*pt
)
6352 /* array must be transformed to pointer according to ANSI C */
6354 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
6359 static void post_type(CType
*type
, AttributeDef
*ad
)
6362 Sym
**plast
, *s
, *first
;
6367 /* function declaration */
6372 while (tok
!= ')') {
6373 /* read param name and compute offset */
6374 if (l
!= FUNC_OLD
) {
6375 if (!parse_btype(&pt
, &ad1
)) {
6377 error("invalid type");
6384 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
6386 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6387 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
6388 error("parameter declared as void");
6395 convert_parameter_type(&pt
);
6396 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
6401 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
6408 /* if no parameters, then old type prototype */
6412 t1
= type
->t
& VT_STORAGE
;
6413 /* NOTE: const is ignored in returned type as it has a special
6414 meaning in gcc / C++ */
6415 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
6416 post_type(type
, ad
);
6417 /* we push a anonymous symbol which will contain the function prototype */
6418 s
= sym_push(SYM_FIELD
, type
, ad
->func_call
, l
);
6420 type
->t
= t1
| VT_FUNC
;
6422 } else if (tok
== '[') {
6423 /* array definition */
6429 error("invalid array size");
6432 /* parse next post type */
6433 t1
= type
->t
& VT_STORAGE
;
6434 type
->t
&= ~VT_STORAGE
;
6435 post_type(type
, ad
);
6437 /* we push a anonymous symbol which will contain the array
6439 s
= sym_push(SYM_FIELD
, type
, 0, n
);
6440 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
6445 /* Parse a type declaration (except basic type), and return the type
6446 in 'type'. 'td' is a bitmask indicating which kind of type decl is
6447 expected. 'type' should contain the basic type. 'ad' is the
6448 attribute definition of the basic type. It can be modified by
6451 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
6454 CType type1
, *type2
;
6457 while (tok
== '*') {
6465 qualifiers
|= VT_CONSTANT
;
6470 qualifiers
|= VT_VOLATILE
;
6478 type
->t
|= qualifiers
;
6481 /* XXX: clarify attribute handling */
6482 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6483 parse_attribute(ad
);
6485 /* recursive type */
6486 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
6487 type1
.t
= 0; /* XXX: same as int */
6490 /* XXX: this is not correct to modify 'ad' at this point, but
6491 the syntax is not clear */
6492 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6493 parse_attribute(ad
);
6494 type_decl(&type1
, ad
, v
, td
);
6497 /* type identifier */
6498 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
6502 if (!(td
& TYPE_ABSTRACT
))
6503 expect("identifier");
6507 post_type(type
, ad
);
6508 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6509 parse_attribute(ad
);
6512 /* append type at the end of type1 */
6525 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
6526 static int lvalue_type(int t
)
6531 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
6533 else if (bt
== VT_SHORT
)
6537 if (t
& VT_UNSIGNED
)
6538 r
|= VT_LVAL_UNSIGNED
;
6542 /* indirection with full error checking and bound check */
6543 static void indir(void)
6545 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
6547 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
6549 vtop
->type
= *pointed_type(&vtop
->type
);
6550 /* an array is never an lvalue */
6551 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6552 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6553 /* if bound checking, the referenced pointer must be checked */
6554 if (do_bounds_check
)
6555 vtop
->r
|= VT_MUSTBOUND
;
6559 /* pass a parameter to a function and do type checking and casting */
6560 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
6565 func_type
= func
->c
;
6566 if (func_type
== FUNC_OLD
||
6567 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
6568 /* default casting : only need to convert float to double */
6569 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
6573 } else if (arg
== NULL
) {
6574 error("too many arguments to function");
6576 gen_assign_cast(&arg
->type
);
6580 /* parse an expression of the form '(type)' or '(expr)' and return its
6582 static void parse_expr_type(CType
*type
)
6588 if (parse_btype(type
, &ad
)) {
6589 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6596 static void vpush_tokc(int t
)
6600 vsetc(&type
, VT_CONST
, &tokc
);
6603 static void unary(void)
6605 int n
, t
, align
, size
, r
;
6610 /* XXX: GCC 2.95.3 does not generate a table although it should be
6624 vpush_tokc(VT_INT
| VT_UNSIGNED
);
6628 vpush_tokc(VT_LLONG
);
6632 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
6636 vpush_tokc(VT_FLOAT
);
6640 vpush_tokc(VT_DOUBLE
);
6644 vpush_tokc(VT_LDOUBLE
);
6647 case TOK___FUNCTION__
:
6649 goto tok_identifier
;
6655 /* special function name identifier */
6656 len
= strlen(funcname
) + 1;
6657 /* generate char[len] type */
6662 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
6663 ptr
= section_ptr_add(data_section
, len
);
6664 memcpy(ptr
, funcname
, len
);
6672 /* string parsing */
6675 if (tcc_state
->warn_write_strings
)
6680 memset(&ad
, 0, sizeof(AttributeDef
));
6681 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
6686 if (parse_btype(&type
, &ad
)) {
6687 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
6689 /* check ISOC99 compound literal */
6691 /* data is allocated locally by default */
6696 /* all except arrays are lvalues */
6697 if (!(type
.t
& VT_ARRAY
))
6698 r
|= lvalue_type(type
.t
);
6699 memset(&ad
, 0, sizeof(AttributeDef
));
6700 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
6705 } else if (tok
== '{') {
6706 /* save all registers */
6708 /* statement expression : we do not accept break/continue
6709 inside as GCC does */
6710 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
6725 /* functions names must be treated as function pointers,
6726 except for unary '&' and sizeof. Since we consider that
6727 functions are not lvalues, we only have to handle it
6728 there and in function calls. */
6729 /* arrays can also be used although they are not lvalues */
6730 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
6731 !(vtop
->type
.t
& VT_ARRAY
))
6733 mk_pointer(&vtop
->type
);
6739 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
)
6740 vtop
->c
.i
= !vtop
->c
.i
;
6741 else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
6742 vtop
->c
.i
= vtop
->c
.i
^ 1;
6744 vseti(VT_JMP
, gtst(1, 0));
6754 /* in order to force cast, we add zero */
6756 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
6757 error("pointer not accepted for unary plus");
6767 parse_expr_type(&type
);
6771 size
= type_size(&type
, &align
);
6772 if (t
== TOK_SIZEOF
) {
6774 error("sizeof applied to an incomplete type");
6796 goto tok_identifier
;
6798 /* allow to take the address of a label */
6799 if (tok
< TOK_UIDENT
)
6800 expect("label identifier");
6801 s
= label_find(tok
);
6803 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
6805 if (s
->r
== LABEL_DECLARED
)
6806 s
->r
= LABEL_FORWARD
;
6809 s
->type
.t
= VT_VOID
;
6810 mk_pointer(&s
->type
);
6811 s
->type
.t
|= VT_STATIC
;
6813 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
6822 expect("identifier");
6826 error("'%s' undeclared", get_tok_str(t
, NULL
));
6827 /* for simple function calls, we tolerate undeclared
6828 external reference to int() function */
6829 s
= external_global_sym(t
, &func_old_type
, 0);
6831 vset(&s
->type
, s
->r
, s
->c
);
6832 /* if forward reference, we must point to s */
6833 if (vtop
->r
& VT_SYM
) {
6840 /* post operations */
6842 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
6845 } else if (tok
== '.' || tok
== TOK_ARROW
) {
6847 if (tok
== TOK_ARROW
)
6852 /* expect pointer on structure */
6853 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
6854 expect("struct or union");
6858 while ((s
= s
->next
) != NULL
) {
6863 error("field not found");
6864 /* add field offset to pointer */
6865 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
6868 /* change type to field type, and set to lvalue */
6869 vtop
->type
= s
->type
;
6870 /* an array is never an lvalue */
6871 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6872 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6873 /* if bound checking, the referenced pointer must be checked */
6874 if (do_bounds_check
)
6875 vtop
->r
|= VT_MUSTBOUND
;
6878 } else if (tok
== '[') {
6884 } else if (tok
== '(') {
6890 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
6891 /* pointer test (no array accepted) */
6892 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
6893 vtop
->type
= *pointed_type(&vtop
->type
);
6894 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
6898 expect("function pointer");
6901 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
6903 /* get return type */
6906 sa
= s
->next
; /* first parameter */
6908 /* compute first implicit argument if a structure is returned */
6909 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
6910 /* get some space for the returned structure */
6911 size
= type_size(&s
->type
, &align
);
6912 loc
= (loc
- size
) & -align
;
6914 ret
.r
= VT_LOCAL
| VT_LVAL
;
6915 /* pass it as 'int' to avoid structure arg passing
6917 vseti(VT_LOCAL
, loc
);
6923 /* return in register */
6924 if (is_float(ret
.type
.t
)) {
6927 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
6936 gfunc_param_typed(s
, sa
);
6946 error("too few arguments to function");
6948 if (!nocode_wanted
) {
6949 gfunc_call(nb_args
);
6951 vtop
-= (nb_args
+ 1);
6954 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
6962 static void uneq(void)
6968 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
6969 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
6970 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
6985 static void expr_prod(void)
6990 while (tok
== '*' || tok
== '/' || tok
== '%') {
6998 static void expr_sum(void)
7003 while (tok
== '+' || tok
== '-') {
7011 static void expr_shift(void)
7016 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
7024 static void expr_cmp(void)
7029 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
7030 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
7038 static void expr_cmpeq(void)
7043 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
7051 static void expr_and(void)
7054 while (tok
== '&') {
7061 static void expr_xor(void)
7064 while (tok
== '^') {
7071 static void expr_or(void)
7074 while (tok
== '|') {
7081 /* XXX: fix this mess */
7082 static void expr_land_const(void)
7085 while (tok
== TOK_LAND
) {
7092 /* XXX: fix this mess */
7093 static void expr_lor_const(void)
7096 while (tok
== TOK_LOR
) {
7103 /* only used if non constant */
7104 static void expr_land(void)
7109 if (tok
== TOK_LAND
) {
7113 if (tok
!= TOK_LAND
) {
7123 static void expr_lor(void)
7128 if (tok
== TOK_LOR
) {
7132 if (tok
!= TOK_LOR
) {
7142 /* XXX: better constant handling */
7143 static void expr_eq(void)
7145 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
7147 CType type
, type1
, type2
;
7156 if (tok
== ':' && gnu_ext
) {
7172 if (vtop
!= vstack
) {
7173 /* needed to avoid having different registers saved in
7175 if (is_float(vtop
->type
.t
))
7182 if (tok
== ':' && gnu_ext
) {
7190 sv
= *vtop
; /* save value to handle it later */
7191 vtop
--; /* no vpop so that FP stack is not flushed */
7199 bt1
= t1
& VT_BTYPE
;
7201 bt2
= t2
& VT_BTYPE
;
7202 /* cast operands to correct type according to ISOC rules */
7203 if (is_float(bt1
) || is_float(bt2
)) {
7204 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
7205 type
.t
= VT_LDOUBLE
;
7206 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
7211 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
7212 /* cast to biggest op */
7214 /* convert to unsigned if it does not fit in a long long */
7215 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
7216 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
7217 type
.t
|= VT_UNSIGNED
;
7218 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
7219 /* XXX: test pointer compatibility */
7221 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
7222 /* XXX: test structure compatibility */
7224 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
7225 /* NOTE: as an extension, we accept void on only one side */
7228 /* integer operations */
7230 /* convert to unsigned if it does not fit in an integer */
7231 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
7232 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
7233 type
.t
|= VT_UNSIGNED
;
7236 /* now we convert second operand */
7239 if (is_float(type
.t
)) {
7241 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
7242 /* for long longs, we use fixed registers to avoid having
7243 to handle a complicated move */
7248 /* this is horrible, but we must also convert first
7252 /* put again first value and cast it */
7263 static void gexpr(void)
7274 /* parse an expression and return its type without any side effect. */
7275 static void expr_type(CType
*type
)
7287 /* parse a unary expression and return its type without any side
7289 static void unary_type(CType
*type
)
7301 /* parse a constant expression and return value in vtop. */
7302 static void expr_const1(void)
7311 /* parse an integer constant and return its value. */
7312 static int expr_const(void)
7316 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
7317 expect("constant expression");
7323 /* return the label token if current token is a label, otherwise
7325 static int is_label(void)
7329 /* fast test first */
7330 if (tok
< TOK_UIDENT
)
7332 /* no need to save tokc because tok is an identifier */
7339 unget_tok(last_tok
);
7344 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
7345 int case_reg
, int is_expr
)
7350 /* generate line number info */
7352 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
7353 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
7355 last_line_num
= file
->line_num
;
7359 /* default return value is (void) */
7361 vtop
->type
.t
= VT_VOID
;
7364 if (tok
== TOK_IF
) {
7371 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7373 if (c
== TOK_ELSE
) {
7377 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7378 gsym(d
); /* patch else jmp */
7381 } else if (tok
== TOK_WHILE
) {
7389 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7393 } else if (tok
== '{') {
7397 /* record local declaration stack position */
7399 llabel
= local_label_stack
;
7400 /* handle local labels declarations */
7401 if (tok
== TOK_LABEL
) {
7404 if (tok
< TOK_UIDENT
)
7405 expect("label identifier");
7406 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
7416 while (tok
!= '}') {
7421 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7424 /* pop locally defined labels */
7425 label_pop(&local_label_stack
, llabel
);
7426 /* pop locally defined symbols */
7427 sym_pop(&local_stack
, s
);
7429 } else if (tok
== TOK_RETURN
) {
7433 gen_assign_cast(&func_vt
);
7434 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
7436 /* if returning structure, must copy it to implicit
7437 first pointer arg location */
7440 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
7443 /* copy structure value to pointer */
7445 } else if (is_float(func_vt
.t
)) {
7450 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
7453 rsym
= gjmp(rsym
); /* jmp */
7454 } else if (tok
== TOK_BREAK
) {
7457 error("cannot break");
7458 *bsym
= gjmp(*bsym
);
7461 } else if (tok
== TOK_CONTINUE
) {
7464 error("cannot continue");
7465 *csym
= gjmp(*csym
);
7468 } else if (tok
== TOK_FOR
) {
7495 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7500 if (tok
== TOK_DO
) {
7505 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7516 if (tok
== TOK_SWITCH
) {
7520 /* XXX: other types than integer */
7521 case_reg
= gv(RC_INT
);
7525 b
= gjmp(0); /* jump to first case */
7527 block(&a
, csym
, &b
, &c
, case_reg
, 0);
7528 /* if no default, jmp after switch */
7536 if (tok
== TOK_CASE
) {
7543 if (gnu_ext
&& tok
== TOK_DOTS
) {
7547 warning("empty case range");
7549 /* since a case is like a label, we must skip it with a jmp */
7556 *case_sym
= gtst(1, 0);
7559 *case_sym
= gtst(1, 0);
7563 *case_sym
= gtst(1, *case_sym
);
7568 goto block_after_label
;
7570 if (tok
== TOK_DEFAULT
) {
7576 error("too many 'default'");
7579 goto block_after_label
;
7581 if (tok
== TOK_GOTO
) {
7583 if (tok
== '*' && gnu_ext
) {
7587 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
7590 } else if (tok
>= TOK_UIDENT
) {
7591 s
= label_find(tok
);
7592 /* put forward definition if needed */
7594 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7596 if (s
->r
== LABEL_DECLARED
)
7597 s
->r
= LABEL_FORWARD
;
7599 /* label already defined */
7600 if (s
->r
& LABEL_FORWARD
)
7601 s
->next
= (void *)gjmp((long)s
->next
);
7603 gjmp_addr((long)s
->next
);
7606 expect("label identifier");
7609 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
7617 if (s
->r
== LABEL_DEFINED
)
7618 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
7619 gsym((long)s
->next
);
7620 s
->r
= LABEL_DEFINED
;
7622 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
7624 s
->next
= (void *)ind
;
7625 /* we accept this, but it is a mistake */
7628 warning("deprecated use of label at end of compound statement");
7632 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7635 /* expression case */
7650 /* t is the array or struct type. c is the array or struct
7651 address. cur_index/cur_field is the pointer to the current
7652 value. 'size_only' is true if only size info is needed (only used
7654 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
7655 int *cur_index
, Sym
**cur_field
,
7659 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
7665 if (gnu_ext
&& (l
= is_label()) != 0)
7667 while (tok
== '[' || tok
== '.') {
7669 if (!(type
->t
& VT_ARRAY
))
7670 expect("array type");
7673 index
= expr_const();
7674 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
7675 expect("invalid index");
7676 if (tok
== TOK_DOTS
&& gnu_ext
) {
7678 index_last
= expr_const();
7679 if (index_last
< 0 ||
7680 (s
->c
>= 0 && index_last
>= s
->c
) ||
7682 expect("invalid index");
7688 *cur_index
= index_last
;
7689 type
= pointed_type(type
);
7690 elem_size
= type_size(type
, &align
);
7691 c
+= index
* elem_size
;
7692 /* NOTE: we only support ranges for last designator */
7693 nb_elems
= index_last
- index
+ 1;
7694 if (nb_elems
!= 1) {
7703 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
7704 expect("struct/union type");
7717 /* XXX: fix this mess by using explicit storage field */
7719 type1
.t
|= (type
->t
& ~VT_TYPE
);
7733 if (type
->t
& VT_ARRAY
) {
7735 type
= pointed_type(type
);
7736 c
+= index
* type_size(type
, &align
);
7740 error("too many field init");
7741 /* XXX: fix this mess by using explicit storage field */
7743 type1
.t
|= (type
->t
& ~VT_TYPE
);
7748 decl_initializer(type
, sec
, c
, 0, size_only
);
7750 /* XXX: make it more general */
7751 if (!size_only
&& nb_elems
> 1) {
7752 unsigned long c_end
;
7757 error("range init not supported yet for dynamic storage");
7758 c_end
= c
+ nb_elems
* elem_size
;
7759 if (c_end
> sec
->data_allocated
)
7760 section_realloc(sec
, c_end
);
7761 src
= sec
->data
+ c
;
7763 for(i
= 1; i
< nb_elems
; i
++) {
7765 memcpy(dst
, src
, elem_size
);
7771 #define EXPR_CONST 1
7774 /* store a value or an expression directly in global data or in local array */
7775 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
7776 int v
, int expr_type
)
7778 int saved_global_expr
, bt
, bit_pos
, bit_size
;
7780 unsigned long long bit_mask
;
7788 /* compound literals must be allocated globally in this case */
7789 saved_global_expr
= global_expr
;
7792 global_expr
= saved_global_expr
;
7793 /* NOTE: symbols are accepted */
7794 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
7795 error("initializer element is not constant");
7803 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
7806 /* XXX: not portable */
7807 /* XXX: generate error if incorrect relocation */
7808 gen_assign_cast(&dtype
);
7809 bt
= type
->t
& VT_BTYPE
;
7810 ptr
= sec
->data
+ c
;
7811 /* XXX: make code faster ? */
7812 if (!(type
->t
& VT_BITFIELD
)) {
7817 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
7818 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
7819 bit_mask
= (1LL << bit_size
) - 1;
7821 if ((vtop
->r
& VT_SYM
) &&
7827 (bt
== VT_INT
&& bit_size
!= 32)))
7828 error("initializer element is not computable at load time");
7831 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7834 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7837 *(double *)ptr
= vtop
->c
.d
;
7840 *(long double *)ptr
= vtop
->c
.ld
;
7843 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
7846 if (vtop
->r
& VT_SYM
) {
7847 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
7849 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7854 vset(&dtype
, VT_LOCAL
, c
);
7861 /* put zeros for variable based init */
7862 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
7865 /* nothing to do because globals are already set to zero */
7867 vpush_global_sym(&func_old_type
, TOK_memset
);
7875 /* 't' contains the type and storage info. 'c' is the offset of the
7876 object in section 'sec'. If 'sec' is NULL, it means stack based
7877 allocation. 'first' is true if array '{' must be read (multi
7878 dimension implicit array init handling). 'size_only' is true if
7879 size only evaluation is wanted (only for arrays). */
7880 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
7881 int first
, int size_only
)
7883 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
7884 int size1
, align1
, expr_type
;
7888 if (type
->t
& VT_ARRAY
) {
7892 t1
= pointed_type(type
);
7893 size1
= type_size(t1
, &align1
);
7896 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
7902 /* only parse strings here if correct type (otherwise: handle
7903 them as ((w)char *) expressions */
7904 if ((tok
== TOK_LSTR
&&
7905 (t1
->t
& VT_BTYPE
) == VT_INT
) ||
7907 (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
7908 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
7913 /* compute maximum number of chars wanted */
7915 cstr_len
= cstr
->size
;
7917 cstr_len
= cstr
->size
/ sizeof(int);
7920 if (n
>= 0 && nb
> (n
- array_length
))
7921 nb
= n
- array_length
;
7924 warning("initializer-string for array is too long");
7925 /* in order to go faster for common case (char
7926 string in global variable, we handle it
7928 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
7929 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
7933 ch
= ((unsigned char *)cstr
->data
)[i
];
7935 ch
= ((int *)cstr
->data
)[i
];
7936 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
7944 /* only add trailing zero if enough storage (no
7945 warning in this case since it is standard) */
7946 if (n
< 0 || array_length
< n
) {
7948 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
7954 while (tok
!= '}') {
7955 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
7956 if (n
>= 0 && index
>= n
)
7957 error("index too large");
7958 /* must put zero in holes (note that doing it that way
7959 ensures that it even works with designators) */
7960 if (!size_only
&& array_length
< index
) {
7961 init_putz(t1
, sec
, c
+ array_length
* size1
,
7962 (index
- array_length
) * size1
);
7965 if (index
> array_length
)
7966 array_length
= index
;
7967 /* special test for multi dimensional arrays (may not
7968 be strictly correct if designators are used at the
7970 if (index
>= n
&& no_oblock
)
7979 /* put zeros at the end */
7980 if (!size_only
&& n
>= 0 && array_length
< n
) {
7981 init_putz(t1
, sec
, c
+ array_length
* size1
,
7982 (n
- array_length
) * size1
);
7984 /* patch type size if needed */
7986 s
->c
= array_length
;
7987 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
7988 (sec
|| !first
|| tok
== '{')) {
7991 /* NOTE: the previous test is a specific case for automatic
7992 struct/union init */
7993 /* XXX: union needs only one init */
7995 /* XXX: this test is incorrect for local initializers
7996 beginning with ( without {. It would be much more difficult
7997 to do it correctly (ideally, the expression parser should
7998 be used in all cases) */
8004 while (tok
== '(') {
8008 if (!parse_btype(&type1
, &ad1
))
8010 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
8012 if (!is_assignable_types(type
, &type1
))
8013 error("invalid type for cast");
8018 if (first
|| tok
== '{') {
8027 while (tok
!= '}') {
8028 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
8030 if (!size_only
&& array_length
< index
) {
8031 init_putz(type
, sec
, c
+ array_length
,
8032 index
- array_length
);
8034 index
= index
+ type_size(&f
->type
, &align1
);
8035 if (index
> array_length
)
8036 array_length
= index
;
8038 if (no_oblock
&& f
== NULL
)
8044 /* put zeros at the end */
8045 if (!size_only
&& array_length
< n
) {
8046 init_putz(type
, sec
, c
+ array_length
,
8055 } else if (tok
== '{') {
8057 decl_initializer(type
, sec
, c
, first
, size_only
);
8059 } else if (size_only
) {
8060 /* just skip expression */
8062 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
8066 else if (tok
== ')')
8071 /* currently, we always use constant expression for globals
8072 (may change for scripting case) */
8073 expr_type
= EXPR_CONST
;
8075 expr_type
= EXPR_ANY
;
8076 init_putv(type
, sec
, c
, 0, expr_type
);
8080 /* parse an initializer for type 't' if 'has_init' is non zero, and
8081 allocate space in local or global data space ('r' is either
8082 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
8083 variable 'v' of scope 'scope' is declared before initializers are
8084 parsed. If 'v' is zero, then a reference to the new object is put
8085 in the value stack. If 'has_init' is 2, a special parsing is done
8086 to handle string constants. */
8087 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
8088 int has_init
, int v
, int scope
)
8090 int size
, align
, addr
, data_offset
;
8092 ParseState saved_parse_state
;
8093 TokenString init_str
;
8096 size
= type_size(type
, &align
);
8097 /* If unknown size, we must evaluate it before
8098 evaluating initializers because
8099 initializers can generate global data too
8100 (e.g. string pointers or ISOC99 compound
8101 literals). It also simplifies local
8102 initializers handling */
8103 tok_str_new(&init_str
);
8106 error("unknown type size");
8107 /* get all init string */
8108 if (has_init
== 2) {
8109 /* only get strings */
8110 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8111 tok_str_add_tok(&init_str
);
8116 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
8118 error("unexpected end of file in initializer");
8119 tok_str_add_tok(&init_str
);
8122 else if (tok
== '}') {
8130 tok_str_add(&init_str
, -1);
8131 tok_str_add(&init_str
, 0);
8134 save_parse_state(&saved_parse_state
);
8136 macro_ptr
= init_str
.str
;
8138 decl_initializer(type
, NULL
, 0, 1, 1);
8139 /* prepare second initializer parsing */
8140 macro_ptr
= init_str
.str
;
8143 /* if still unknown size, error */
8144 size
= type_size(type
, &align
);
8146 error("unknown type size");
8148 /* take into account specified alignment if bigger */
8149 if (ad
->aligned
> align
)
8150 align
= ad
->aligned
;
8151 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
8153 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
8155 loc
= (loc
- size
) & -align
;
8157 /* handles bounds */
8158 /* XXX: currently, since we do only one pass, we cannot track
8159 '&' operators, so we add only arrays */
8160 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
8161 unsigned long *bounds_ptr
;
8162 /* add padding between regions */
8164 /* then add local bound info */
8165 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
8166 bounds_ptr
[0] = addr
;
8167 bounds_ptr
[1] = size
;
8170 /* local variable */
8171 sym_push(v
, type
, r
, addr
);
8173 /* push local reference */
8174 vset(type
, r
, addr
);
8180 if (v
&& scope
== VT_CONST
) {
8181 /* see if the symbol was already defined */
8184 if (!is_compatible_types(&sym
->type
, type
))
8185 error("incompatible types for redefinition of '%s'",
8186 get_tok_str(v
, NULL
));
8187 if (sym
->type
.t
& VT_EXTERN
) {
8188 /* if the variable is extern, it was not allocated */
8189 sym
->type
.t
&= ~VT_EXTERN
;
8191 /* we accept several definitions of the same
8192 global variable. this is tricky, because we
8193 must play with the SHN_COMMON type of the symbol */
8194 /* XXX: should check if the variable was already
8195 initialized. It is incorrect to initialized it
8197 /* no init data, we won't add more to the symbol */
8204 /* allocate symbol in corresponding section */
8211 data_offset
= sec
->data_offset
;
8212 data_offset
= (data_offset
+ align
- 1) & -align
;
8214 /* very important to increment global pointer at this time
8215 because initializers themselves can create new initializers */
8216 data_offset
+= size
;
8217 /* add padding if bound check */
8218 if (do_bounds_check
)
8220 sec
->data_offset
= data_offset
;
8221 /* allocate section space to put the data */
8222 if (sec
->sh_type
!= SHT_NOBITS
&&
8223 data_offset
> sec
->data_allocated
)
8224 section_realloc(sec
, data_offset
);
8226 addr
= 0; /* avoid warning */
8230 if (scope
== VT_CONST
) {
8235 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
8237 /* update symbol definition */
8239 put_extern_sym(sym
, sec
, addr
, size
);
8242 /* put a common area */
8243 put_extern_sym(sym
, NULL
, align
, size
);
8244 /* XXX: find a nicer way */
8245 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
8246 esym
->st_shndx
= SHN_COMMON
;
8251 /* push global reference */
8252 sym
= get_sym_ref(type
, sec
, addr
, size
);
8254 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
8258 /* handles bounds now because the symbol must be defined
8259 before for the relocation */
8260 if (do_bounds_check
) {
8261 unsigned long *bounds_ptr
;
8263 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
8264 /* then add global bound info */
8265 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
8266 bounds_ptr
[0] = 0; /* relocated */
8267 bounds_ptr
[1] = size
;
8271 decl_initializer(type
, sec
, addr
, 1, 0);
8272 /* restore parse state if needed */
8274 tok_str_free(init_str
.str
);
8275 restore_parse_state(&saved_parse_state
);
8281 void put_func_debug(Sym
*sym
)
8286 /* XXX: we put here a dummy type */
8287 snprintf(buf
, sizeof(buf
), "%s:%c1",
8288 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
8289 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
8290 cur_text_section
, sym
->c
);
8295 /* not finished : try to put some local vars in registers */
8296 //#define CONFIG_REG_VARS
8298 #ifdef CONFIG_REG_VARS
8299 void add_var_ref(int t
)
8301 printf("%s:%d: &%s\n",
8302 file
->filename
, file
->line_num
,
8303 get_tok_str(t
, NULL
));
8306 /* first pass on a function with heuristic to extract variable usage
8307 and pointer references to local variables for register allocation */
8308 void analyse_function(void)
8315 /* any symbol coming after '&' is considered as being a
8316 variable whose reference is taken. It is highly unaccurate
8317 but it is difficult to do better without a complete parse */
8320 /* if '& number', then no need to examine next tokens */
8321 if (tok
== TOK_CINT
||
8323 tok
== TOK_CLLONG
||
8324 tok
== TOK_CULLONG
) {
8326 } else if (tok
>= TOK_UIDENT
) {
8327 /* if '& ident [' or '& ident ->', then ident address
8331 if (tok
!= '[' && tok
!= TOK_ARROW
)
8335 while (tok
!= '}' && tok
!= ';' &&
8336 !((tok
== ',' || tok
== ')') && level
== 0)) {
8337 if (tok
>= TOK_UIDENT
) {
8339 } else if (tok
== '(') {
8341 } else if (tok
== ')') {
8354 /* parse an old style function declaration list */
8355 /* XXX: check multiple parameter */
8356 static void func_decl_list(Sym
*func_sym
)
8363 /* parse each declaration */
8364 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
8365 if (!parse_btype(&btype
, &ad
))
8366 expect("declaration list");
8367 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8368 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8370 /* we accept no variable after */
8374 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8375 /* find parameter in function parameter list */
8378 if ((s
->v
& ~SYM_FIELD
) == v
)
8382 error("declaration for parameter '%s' but no such parameter",
8383 get_tok_str(v
, NULL
));
8385 /* check that no storage specifier except 'register' was given */
8386 if (type
.t
& VT_STORAGE
)
8387 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
8388 convert_parameter_type(&type
);
8389 /* we can add the type (NOTE: it could be local to the function) */
8391 /* accept other parameters */
8402 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
8403 static void decl(int l
)
8411 if (!parse_btype(&btype
, &ad
)) {
8412 /* skip redundant ';' */
8413 /* XXX: find more elegant solution */
8418 /* special test for old K&R protos without explicit int
8419 type. Only accepted when defining global data */
8420 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
8424 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8425 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8427 /* we accept no variable after */
8431 while (1) { /* iterate thru each declaration */
8433 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8437 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
8438 printf("type = '%s'\n", buf
);
8441 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8442 /* if old style function prototype, we accept a
8445 if (sym
->c
== FUNC_OLD
)
8446 func_decl_list(sym
);
8450 #ifdef CONFIG_REG_VARS
8451 TokenString func_str
;
8452 ParseState saved_parse_state
;
8457 error("cannot use local functions");
8458 if (!(type
.t
& VT_FUNC
))
8459 expect("function definition");
8460 /* XXX: cannot do better now: convert extern line to static inline */
8461 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
8462 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
8464 #ifdef CONFIG_REG_VARS
8465 /* parse all function code and record it */
8467 tok_str_new(&func_str
);
8473 error("unexpected end of file");
8474 tok_str_add_tok(&func_str
);
8479 } else if (t
== '}') {
8481 if (block_level
== 0)
8485 tok_str_add(&func_str
, -1);
8486 tok_str_add(&func_str
, 0);
8488 save_parse_state(&saved_parse_state
);
8490 macro_ptr
= func_str
.str
;
8495 /* compute text section */
8496 cur_text_section
= ad
.section
;
8497 if (!cur_text_section
)
8498 cur_text_section
= text_section
;
8499 ind
= cur_text_section
->data_offset
;
8500 funcname
= get_tok_str(v
, NULL
);
8503 /* if symbol is already defined, then put complete type */
8506 /* put function symbol */
8507 sym
= global_identifier_push(v
, type
.t
, 0);
8508 sym
->type
.ref
= type
.ref
;
8510 /* NOTE: we patch the symbol size later */
8511 put_extern_sym(sym
, cur_text_section
, ind
, 0);
8513 sym
->r
= VT_SYM
| VT_CONST
;
8514 /* put debug symbol */
8516 put_func_debug(sym
);
8517 /* push a dummy symbol to enable local sym storage */
8518 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
8519 gfunc_prolog(&type
);
8522 #ifdef CONFIG_REG_VARS
8523 macro_ptr
= func_str
.str
;
8526 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
8529 cur_text_section
->data_offset
= ind
;
8530 label_pop(&global_label_stack
, NULL
);
8531 sym_pop(&local_stack
, NULL
); /* reset local stack */
8532 /* end of function */
8533 /* patch symbol size */
8534 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_size
=
8537 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
8539 funcname
= ""; /* for safety */
8540 func_vt
.t
= VT_VOID
; /* for safety */
8541 ind
= 0; /* for safety */
8543 #ifdef CONFIG_REG_VARS
8544 tok_str_free(func_str
.str
);
8545 restore_parse_state(&saved_parse_state
);
8549 if (btype
.t
& VT_TYPEDEF
) {
8550 /* save typedefed type */
8551 /* XXX: test storage specifiers ? */
8552 sym
= sym_push(v
, &type
, 0, 0);
8553 sym
->type
.t
|= VT_TYPEDEF
;
8554 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8555 /* external function definition */
8556 external_sym(v
, &type
, 0);
8558 /* not lvalue if array */
8560 if (!(type
.t
& VT_ARRAY
))
8561 r
|= lvalue_type(type
.t
);
8562 has_init
= (tok
== '=');
8563 if ((btype
.t
& VT_EXTERN
) ||
8564 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
8565 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
8566 /* external variable */
8567 /* NOTE: as GCC, uninitialized global static
8568 arrays of null size are considered as
8570 external_sym(v
, &type
, r
);
8572 if (type
.t
& VT_STATIC
)
8578 decl_initializer_alloc(&type
, &ad
, r
,
8592 /* better than nothing, but needs extension to handle '-E' option
8594 static void preprocess_init(TCCState
*s1
)
8596 s1
->include_stack_ptr
= s1
->include_stack
;
8597 /* XXX: move that before to avoid having to initialize
8598 file->ifdef_stack_ptr ? */
8599 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
8600 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
8602 /* XXX: not ANSI compliant: bound checking says error */
8606 /* compile the C file opened in 'file'. Return non zero if errors. */
8607 static int tcc_compile(TCCState
*s1
)
8611 volatile int section_sym
;
8614 printf("%s: **** new file\n", file
->filename
);
8616 preprocess_init(s1
);
8619 anon_sym
= SYM_FIRST_ANOM
;
8621 /* file info: full path + filename */
8622 section_sym
= 0; /* avoid warning */
8624 section_sym
= put_elf_sym(symtab_section
, 0, 0,
8625 ELF32_ST_INFO(STB_LOCAL
, STT_SECTION
), 0,
8626 text_section
->sh_num
, NULL
);
8627 getcwd(buf
, sizeof(buf
));
8628 pstrcat(buf
, sizeof(buf
), "/");
8629 put_stabs_r(buf
, N_SO
, 0, 0,
8630 text_section
->data_offset
, text_section
, section_sym
);
8631 put_stabs_r(file
->filename
, N_SO
, 0, 0,
8632 text_section
->data_offset
, text_section
, section_sym
);
8634 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
8635 symbols can be safely used */
8636 put_elf_sym(symtab_section
, 0, 0,
8637 ELF32_ST_INFO(STB_LOCAL
, STT_FILE
), 0,
8638 SHN_ABS
, file
->filename
);
8640 /* define some often used types */
8641 int_type
.t
= VT_INT
;
8643 char_pointer_type
.t
= VT_BYTE
;
8644 mk_pointer(&char_pointer_type
);
8646 func_old_type
.t
= VT_FUNC
;
8647 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
8650 /* define 'void *alloca(unsigned int)' builtin function */
8655 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
8656 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
8659 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
8663 define_start
= define_stack
;
8665 if (setjmp(s1
->error_jmp_buf
) == 0) {
8667 s1
->error_set_jmp_enabled
= 1;
8669 ch
= file
->buf_ptr
[0];
8670 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
8671 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
8675 expect("declaration");
8677 /* end of translation unit info */
8679 put_stabs_r(NULL
, N_SO
, 0, 0,
8680 text_section
->data_offset
, text_section
, section_sym
);
8683 s1
->error_set_jmp_enabled
= 0;
8685 /* reset define stack, but leave -Dsymbols (may be incorrect if
8686 they are undefined) */
8687 free_defines(define_start
);
8689 sym_pop(&global_stack
, NULL
);
8691 return s1
->nb_errors
!= 0 ? -1 : 0;
8695 int tcc_compile_string(TCCState
*s
, const char *str
)
8697 BufferedFile bf1
, *bf
= &bf1
;
8701 /* init file structure */
8703 /* XXX: avoid copying */
8705 buf
= tcc_malloc(len
+ 1);
8708 memcpy(buf
, str
, len
);
8711 bf
->buf_end
= buf
+ len
;
8712 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
8716 ret
= tcc_compile(s
);
8720 /* currently, no need to close */
8725 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
8726 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
8728 BufferedFile bf1
, *bf
= &bf1
;
8730 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
8731 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
8735 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
8737 /* init file structure */
8739 bf
->buf_ptr
= bf
->buffer
;
8740 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
8741 *bf
->buf_end
= CH_EOB
;
8742 bf
->filename
[0] = '\0';
8746 s1
->include_stack_ptr
= s1
->include_stack
;
8748 /* parse with define parser */
8749 ch
= file
->buf_ptr
[0];
8755 /* undefine a preprocessor symbol */
8756 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
8760 ts
= tok_alloc(sym
, strlen(sym
));
8761 s
= define_find(ts
->tok
);
8762 /* undefine symbol by putting an invalid name */
8767 #ifdef CONFIG_TCC_ASM
8769 #include "i386-asm.c"
8773 static void asm_instr(void)
8775 error("inline asm() not supported");
8781 /* print the position in the source file of PC value 'pc' by reading
8782 the stabs debug information */
8783 static void rt_printline(unsigned long wanted_pc
)
8785 Stab_Sym
*sym
, *sym_end
;
8786 char func_name
[128], last_func_name
[128];
8787 unsigned long func_addr
, last_pc
, pc
;
8788 const char *incl_files
[INCLUDE_STACK_SIZE
];
8789 int incl_index
, len
, last_line_num
, i
;
8790 const char *str
, *p
;
8792 fprintf(stderr
, "0x%08lx:", wanted_pc
);
8794 func_name
[0] = '\0';
8797 last_func_name
[0] = '\0';
8798 last_pc
= 0xffffffff;
8800 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
8801 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
8802 while (sym
< sym_end
) {
8803 switch(sym
->n_type
) {
8804 /* function start or end */
8806 if (sym
->n_strx
== 0) {
8807 /* we test if between last line and end of function */
8808 pc
= sym
->n_value
+ func_addr
;
8809 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
8811 func_name
[0] = '\0';
8814 str
= stabstr_section
->data
+ sym
->n_strx
;
8815 p
= strchr(str
, ':');
8817 pstrcpy(func_name
, sizeof(func_name
), str
);
8820 if (len
> sizeof(func_name
) - 1)
8821 len
= sizeof(func_name
) - 1;
8822 memcpy(func_name
, str
, len
);
8823 func_name
[len
] = '\0';
8825 func_addr
= sym
->n_value
;
8828 /* line number info */
8830 pc
= sym
->n_value
+ func_addr
;
8831 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
8834 last_line_num
= sym
->n_desc
;
8836 strcpy(last_func_name
, func_name
);
8840 str
= stabstr_section
->data
+ sym
->n_strx
;
8842 if (incl_index
< INCLUDE_STACK_SIZE
) {
8843 incl_files
[incl_index
++] = str
;
8851 if (sym
->n_strx
== 0) {
8852 incl_index
= 0; /* end of translation unit */
8854 str
= stabstr_section
->data
+ sym
->n_strx
;
8855 /* do not add path */
8857 if (len
> 0 && str
[len
- 1] != '/')
8865 /* second pass: we try symtab symbols (no line number info) */
8868 Elf32_Sym
*sym
, *sym_end
;
8871 sym_end
= (Elf32_Sym
*)(symtab_section
->data
+ symtab_section
->data_offset
);
8872 for(sym
= (Elf32_Sym
*)symtab_section
->data
+ 1;
8875 type
= ELF32_ST_TYPE(sym
->st_info
);
8876 if (type
== STT_FUNC
) {
8877 if (wanted_pc
>= sym
->st_value
&&
8878 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
8879 pstrcpy(last_func_name
, sizeof(last_func_name
),
8880 strtab_section
->data
+ sym
->st_name
);
8886 /* did not find any info: */
8887 fprintf(stderr
, " ???\n");
8890 if (last_func_name
[0] != '\0') {
8891 fprintf(stderr
, " %s()", last_func_name
);
8893 if (incl_index
> 0) {
8894 fprintf(stderr
, " (%s:%d",
8895 incl_files
[incl_index
- 1], last_line_num
);
8896 for(i
= incl_index
- 2; i
>= 0; i
--)
8897 fprintf(stderr
, ", included from %s", incl_files
[i
]);
8898 fprintf(stderr
, ")");
8900 fprintf(stderr
, "\n");
8907 /* fix for glibc 2.1 */
8913 /* return the PC at frame level 'level'. Return non zero if not found */
8914 static int rt_get_caller_pc(unsigned long *paddr
,
8915 ucontext_t
*uc
, int level
)
8922 *paddr
= uc
->uc_mcontext
.mc_eip
;
8924 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
8929 fp
= uc
->uc_mcontext
.mc_ebp
;
8931 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
8933 for(i
=1;i
<level
;i
++) {
8934 /* XXX: check address validity with program info */
8935 if (fp
<= 0x1000 || fp
>= 0xc0000000)
8937 fp
= ((unsigned long *)fp
)[0];
8939 *paddr
= ((unsigned long *)fp
)[1];
8944 #error add arch specific rt_get_caller_pc()
8947 /* emit a run time error at position 'pc' */
8948 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
8955 fprintf(stderr
, "Runtime error: ");
8956 vfprintf(stderr
, fmt
, ap
);
8957 fprintf(stderr
, "\n");
8958 for(i
=0;i
<num_callers
;i
++) {
8959 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
8962 fprintf(stderr
, "at ");
8964 fprintf(stderr
, "by ");
8971 /* signal handler for fatal errors */
8972 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
8974 ucontext_t
*uc
= puc
;
8978 switch(siginf
->si_code
) {
8981 rt_error(uc
, "division by zero");
8984 rt_error(uc
, "floating point exception");
8990 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
8991 rt_error(uc
, *rt_bound_error_msg
);
8993 rt_error(uc
, "dereferencing invalid pointer");
8996 rt_error(uc
, "illegal instruction");
8999 rt_error(uc
, "abort() called");
9002 rt_error(uc
, "caught signal %d", signum
);
9009 /* do all relocations (needed before using tcc_get_symbol()) */
9010 int tcc_relocate(TCCState
*s1
)
9017 tcc_add_runtime(s1
);
9019 relocate_common_syms();
9021 /* compute relocation address : section are relocated in place. We
9022 also alloc the bss space */
9023 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9024 s
= s1
->sections
[i
];
9025 if (s
->sh_flags
& SHF_ALLOC
) {
9026 if (s
->sh_type
== SHT_NOBITS
)
9027 s
->data
= tcc_mallocz(s
->data_offset
);
9028 s
->sh_addr
= (unsigned long)s
->data
;
9032 relocate_syms(s1
, 1);
9034 if (s1
->nb_errors
!= 0)
9037 /* relocate each section */
9038 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9039 s
= s1
->sections
[i
];
9041 relocate_section(s1
, s
);
9046 /* launch the compiled program with the given arguments */
9047 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
9049 int (*prog_main
)(int, char **);
9051 if (tcc_relocate(s1
) < 0)
9054 prog_main
= tcc_get_symbol(s1
, "main");
9058 error("debug mode currently not available for Windows");
9060 struct sigaction sigact
;
9061 /* install TCC signal handlers to print debug info on fatal
9063 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
9064 sigact
.sa_sigaction
= sig_error
;
9065 sigemptyset(&sigact
.sa_mask
);
9066 sigaction(SIGFPE
, &sigact
, NULL
);
9067 sigaction(SIGILL
, &sigact
, NULL
);
9068 sigaction(SIGSEGV
, &sigact
, NULL
);
9069 sigaction(SIGBUS
, &sigact
, NULL
);
9070 sigaction(SIGABRT
, &sigact
, NULL
);
9074 #ifdef CONFIG_TCC_BCHECK
9075 if (do_bounds_check
) {
9076 void (*bound_init
)(void);
9078 /* set error function */
9079 rt_bound_error_msg
= (void *)tcc_get_symbol(s1
, "__bound_error_msg");
9081 /* XXX: use .init section so that it also work in binary ? */
9082 bound_init
= (void *)tcc_get_symbol(s1
, "__bound_init");
9086 return (*prog_main
)(argc
, argv
);
9089 TCCState
*tcc_new(void)
9096 s
= tcc_mallocz(sizeof(TCCState
));
9100 s
->output_type
= TCC_OUTPUT_MEMORY
;
9102 /* init isid table */
9104 isidnum_table
[i
] = isid(i
) || isnum(i
);
9106 /* add all tokens */
9108 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
9110 tok_ident
= TOK_IDENT
;
9119 ts
= tok_alloc(p
, r
- p
- 1);
9123 /* we add dummy defines for some special macros to speed up tests
9124 and to have working defined() */
9125 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
9126 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
9127 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
9128 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
9130 /* standard defines */
9131 tcc_define_symbol(s
, "__STDC__", NULL
);
9132 #if defined(TCC_TARGET_I386)
9133 tcc_define_symbol(s
, "__i386__", NULL
);
9136 tcc_define_symbol(s
, "__linux__", NULL
);
9137 tcc_define_symbol(s
, "linux", NULL
);
9139 /* tiny C specific defines */
9140 tcc_define_symbol(s
, "__TINYC__", NULL
);
9142 /* tiny C & gcc defines */
9143 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
9144 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
9145 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
9147 /* default library paths */
9148 tcc_add_library_path(s
, "/usr/local/lib");
9149 tcc_add_library_path(s
, "/usr/lib");
9150 tcc_add_library_path(s
, "/lib");
9152 /* no section zero */
9153 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
9155 /* create standard sections */
9156 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
9157 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
9158 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
9160 /* symbols are always generated for linking stage */
9161 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
9163 ".hashtab", SHF_PRIVATE
);
9164 strtab_section
= symtab_section
->link
;
9166 /* private symbol table for dynamic symbols */
9167 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
9169 ".dynhashtab", SHF_PRIVATE
);
9173 void tcc_delete(TCCState
*s1
)
9177 /* free -D defines */
9181 n
= tok_ident
- TOK_IDENT
;
9182 for(i
= 0; i
< n
; i
++)
9183 tcc_free(table_ident
[i
]);
9184 tcc_free(table_ident
);
9186 /* free all sections */
9188 free_section(symtab_section
->hash
);
9190 free_section(s1
->dynsymtab_section
->hash
);
9191 free_section(s1
->dynsymtab_section
->link
);
9192 free_section(s1
->dynsymtab_section
);
9194 for(i
= 1; i
< s1
->nb_sections
; i
++)
9195 free_section(s1
->sections
[i
]);
9196 tcc_free(s1
->sections
);
9198 /* free loaded dlls array */
9199 for(i
= 0; i
< s1
->nb_loaded_dlls
; i
++)
9200 tcc_free(s1
->loaded_dlls
[i
]);
9201 tcc_free(s1
->loaded_dlls
);
9204 for(i
= 0; i
< s1
->nb_library_paths
; i
++)
9205 tcc_free(s1
->library_paths
[i
]);
9206 tcc_free(s1
->library_paths
);
9208 /* cached includes */
9209 for(i
= 0; i
< s1
->nb_cached_includes
; i
++)
9210 tcc_free(s1
->cached_includes
[i
]);
9211 tcc_free(s1
->cached_includes
);
9213 for(i
= 0; i
< s1
->nb_include_paths
; i
++)
9214 tcc_free(s1
->include_paths
[i
]);
9215 tcc_free(s1
->include_paths
);
9217 for(i
= 0; i
< s1
->nb_sysinclude_paths
; i
++)
9218 tcc_free(s1
->sysinclude_paths
[i
]);
9219 tcc_free(s1
->sysinclude_paths
);
9224 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
9228 pathname1
= tcc_strdup(pathname
);
9229 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
9233 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
9237 pathname1
= tcc_strdup(pathname
);
9238 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
9242 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
9244 const char *ext
, *filename1
;
9247 BufferedFile
*saved_file
;
9249 /* find source file type with extension */
9250 filename1
= strrchr(filename
, '/');
9254 filename1
= filename
;
9255 ext
= strrchr(filename1
, '.');
9261 file
= tcc_open(s1
, filename
);
9263 if (flags
& AFF_PRINT_ERROR
) {
9264 error_noabort("file '%s' not found", filename
);
9270 if (!ext
|| !strcmp(ext
, "c")) {
9271 /* C file assumed */
9272 ret
= tcc_compile(s1
);
9274 #ifdef CONFIG_TCC_ASM
9275 if (!strcmp(ext
, "S")) {
9276 /* preprocessed assembler */
9277 ret
= tcc_assemble(s1
, 1);
9278 } else if (!strcmp(ext
, "s")) {
9279 /* non preprocessed assembler */
9280 ret
= tcc_assemble(s1
, 0);
9285 /* assume executable format: auto guess file type */
9286 if (read(fd
, &ehdr
, sizeof(ehdr
)) != sizeof(ehdr
)) {
9287 error_noabort("could not read header");
9290 lseek(fd
, 0, SEEK_SET
);
9292 if (ehdr
.e_ident
[0] == ELFMAG0
&&
9293 ehdr
.e_ident
[1] == ELFMAG1
&&
9294 ehdr
.e_ident
[2] == ELFMAG2
&&
9295 ehdr
.e_ident
[3] == ELFMAG3
) {
9296 file
->line_num
= 0; /* do not display line number if error */
9297 if (ehdr
.e_type
== ET_REL
) {
9298 ret
= tcc_load_object_file(s1
, fd
, 0);
9299 } else if (ehdr
.e_type
== ET_DYN
) {
9300 ret
= tcc_load_dll(s1
, fd
, filename
,
9301 (flags
& AFF_REFERENCED_DLL
) != 0);
9303 error_noabort("unrecognized ELF file");
9306 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
9307 file
->line_num
= 0; /* do not display line number if error */
9308 ret
= tcc_load_archive(s1
, fd
);
9310 /* as GNU ld, consider it is an ld script if not recognized */
9311 ret
= tcc_load_ldscript(s1
);
9313 error_noabort("unrecognized file type");
9328 int tcc_add_file(TCCState
*s
, const char *filename
)
9330 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
9333 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
9337 pathname1
= tcc_strdup(pathname
);
9338 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
9342 /* find and load a dll. Return non zero if not found */
9343 /* XXX: add '-rpath' option support ? */
9344 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
9349 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9350 snprintf(buf
, sizeof(buf
), "%s/%s",
9351 s
->library_paths
[i
], filename
);
9352 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
9358 /* the library name is the same as the argument of the '-l' option */
9359 int tcc_add_library(TCCState
*s
, const char *libraryname
)
9365 /* first we look for the dynamic library if not static linking */
9366 if (!s
->static_link
) {
9367 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
9368 /* if we output to memory, then we simply we dlopen(). */
9369 if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
9370 /* Since the libc is already loaded, we don't need to load it again */
9371 if (!strcmp(libraryname
, "c"))
9373 h
= dlopen(buf
, RTLD_GLOBAL
| RTLD_LAZY
);
9377 if (tcc_add_dll(s
, buf
, 0) == 0)
9382 /* then we look for the static library */
9383 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9384 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
9385 s
->library_paths
[i
], libraryname
);
9386 if (tcc_add_file_internal(s
, buf
, 0) == 0)
9392 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
9394 add_elf_sym(symtab_section
, val
, 0,
9395 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
),
9400 int tcc_set_output_type(TCCState
*s
, int output_type
)
9404 s
->output_type
= output_type
;
9407 /* default include paths */
9408 /* XXX: reverse order needed if -isystem support */
9409 tcc_add_sysinclude_path(s
, "/usr/local/include");
9410 tcc_add_sysinclude_path(s
, "/usr/include");
9411 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
9412 tcc_add_sysinclude_path(s
, buf
);
9415 /* if bound checking, then add corresponding sections */
9416 #ifdef CONFIG_TCC_BCHECK
9417 if (do_bounds_check
) {
9419 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
9420 /* create bounds sections */
9421 bounds_section
= new_section(s
, ".bounds",
9422 SHT_PROGBITS
, SHF_ALLOC
);
9423 lbounds_section
= new_section(s
, ".lbounds",
9424 SHT_PROGBITS
, SHF_ALLOC
);
9428 /* add debug sections */
9431 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
9432 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
9433 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
9434 put_elf_str(stabstr_section
, "");
9435 stab_section
->link
= stabstr_section
;
9436 /* put first entry */
9437 put_stabs("", 0, 0, 0, 0);
9440 /* add libc crt1/crti objects */
9441 if (output_type
== TCC_OUTPUT_EXE
||
9442 output_type
== TCC_OUTPUT_DLL
) {
9443 if (output_type
!= TCC_OUTPUT_DLL
)
9444 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
9445 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
9450 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
9452 typedef struct WarningDef
{
9458 static const WarningDef warning_defs
[] = {
9459 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
9460 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
9461 { offsetof(TCCState
, warn_error
), 0, "error" },
9464 /* set/reset a warning */
9465 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
9468 const WarningDef
*p
;
9469 if (!strcmp(warning_name
, "all")) {
9470 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
9471 if (p
->flags
& WD_ALL
)
9472 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
9475 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
9476 if (!strcmp(warning_name
, p
->name
))
9481 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
9487 #if !defined(LIBTCC)
9489 /* extract the basename of a file */
9490 static const char *tcc_basename(const char *name
)
9493 p
= strrchr(name
, '/');
9496 p
= strrchr(name
, '\\');
9505 static int64_t getclock_us(void)
9510 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
9513 gettimeofday(&tv
, NULL
);
9514 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
9520 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2003 Fabrice Bellard\n"
9521 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
9522 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]\n"
9523 " [infile1 infile2...] [-run infile args...]\n"
9525 "General options:\n"
9526 " -v display current version\n"
9527 " -c compile only - generate an object file\n"
9528 " -o outfile set output filename\n"
9529 " -Bdir set tcc internal library path\n"
9530 " -bench output compilation statistics\n"
9531 " -run run compiled source\n"
9532 " -Wwarning set or reset (with 'no-' prefix) 'warning'\n"
9533 "Preprocessor options:\n"
9534 " -Idir add include path 'dir'\n"
9535 " -Dsym[=val] define 'sym' with value 'val'\n"
9536 " -Usym undefine 'sym'\n"
9538 " -Ldir add library path 'dir'\n"
9539 " -llib link with dynamic or static library 'lib'\n"
9540 " -shared generate a shared library\n"
9541 " -static static linking\n"
9542 " -r relocatable output\n"
9543 "Debugger options:\n"
9544 " -g generate runtime debug info\n"
9545 #ifdef CONFIG_TCC_BCHECK
9546 " -b compile with built-in memory and bounds checker (implies -g)\n"
9548 " -bt N show N callers in stack traces\n"
9552 #define TCC_OPTION_HAS_ARG 0x0001
9553 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
9555 typedef struct TCCOption
{
9582 TCC_OPTION_nostdinc
,
9583 TCC_OPTION_print_search_dirs
,
9584 TCC_OPTION_rdynamic
,
9589 static const TCCOption tcc_options
[] = {
9590 { "h", TCC_OPTION_HELP
, 0 },
9591 { "?", TCC_OPTION_HELP
, 0 },
9592 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
9593 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
9594 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
9595 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
9596 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
9597 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9598 { "bench", TCC_OPTION_bench
, 0 },
9599 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
9600 #ifdef CONFIG_TCC_BCHECK
9601 { "b", TCC_OPTION_b
, 0 },
9603 { "g", TCC_OPTION_g
, 0 },
9604 { "c", TCC_OPTION_c
, 0 },
9605 { "static", TCC_OPTION_static
, 0 },
9606 { "shared", TCC_OPTION_shared
, 0 },
9607 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
9608 { "run", TCC_OPTION_run
, 0 },
9609 { "rdynamic", TCC_OPTION_rdynamic
, 0 }, /* currently ignored */
9610 { "r", TCC_OPTION_r
, 0 },
9611 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9612 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9613 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
9614 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9615 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
9616 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
9617 { "v", TCC_OPTION_v
, 0 },
9621 int main(int argc
, char **argv
)
9624 int optind
, output_type
, multiple_files
, i
, reloc_output
;
9627 int nb_files
, nb_libraries
, nb_objfiles
, dminus
, ret
;
9628 char objfilename
[1024];
9629 int64_t start_time
= 0;
9630 const TCCOption
*popt
;
9631 const char *optarg
, *p1
, *r1
, *outfile
;
9632 int print_search_dirs
;
9635 output_type
= TCC_OUTPUT_EXE
;
9645 print_search_dirs
= 0;
9647 if (optind
>= argc
) {
9648 if (nb_files
== 0 && !print_search_dirs
)
9655 /* add a new file */
9656 dynarray_add((void ***)&files
, &nb_files
, r
);
9657 if (!multiple_files
) {
9659 /* argv[0] will be this file */
9663 /* find option in table (match only the first chars */
9668 error("invalid option -- '%s'", r
);
9681 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
9682 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
9686 error("argument to '%s' is missing", r
);
9687 optarg
= argv
[optind
++];
9695 switch(popt
->index
) {
9696 case TCC_OPTION_HELP
:
9701 if (tcc_add_include_path(s
, optarg
) < 0)
9702 error("too many include paths");
9707 sym
= (char *)optarg
;
9708 value
= strchr(sym
, '=');
9713 tcc_define_symbol(s
, sym
, value
);
9717 tcc_undefine_symbol(s
, optarg
);
9720 tcc_add_library_path(s
, optarg
);
9723 /* set tcc utilities path (mainly for tcc development) */
9724 tcc_lib_path
= optarg
;
9727 dynarray_add((void ***)&files
, &nb_files
, r
);
9730 case TCC_OPTION_bench
:
9734 num_callers
= atoi(optarg
);
9736 #ifdef CONFIG_TCC_BCHECK
9738 do_bounds_check
= 1;
9747 output_type
= TCC_OUTPUT_OBJ
;
9749 case TCC_OPTION_static
:
9752 case TCC_OPTION_shared
:
9753 output_type
= TCC_OUTPUT_DLL
;
9760 /* generate a .o merging several output files */
9762 output_type
= TCC_OUTPUT_OBJ
;
9764 case TCC_OPTION_nostdinc
:
9767 case TCC_OPTION_print_search_dirs
:
9768 print_search_dirs
= 1;
9770 case TCC_OPTION_run
:
9772 output_type
= TCC_OUTPUT_MEMORY
;
9775 printf("tcc version %s\n", TCC_VERSION
);
9779 const char *p
= optarg
;
9782 if (p
[0] == 'n' && p
[1] == 'o' && p
[2] == '-') {
9786 if (tcc_set_warning(s
, p
, value
) < 0 && s
->warn_unsupported
)
9787 goto unsupported_option
;
9791 if (s
->warn_unsupported
) {
9793 warning("unsupported option '%s'", r
);
9799 if (print_search_dirs
) {
9800 /* enough for Linux kernel */
9801 printf("install: %s/\n", tcc_lib_path
);
9805 nb_objfiles
= nb_files
- nb_libraries
;
9807 /* if outfile provided without other options, we output an
9809 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
9810 output_type
= TCC_OUTPUT_EXE
;
9812 /* check -c consistency : only single file handled. XXX: checks file type */
9813 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
9814 /* accepts only a single input file */
9815 if (nb_objfiles
!= 1)
9816 error("cannot specify multiple files with -c");
9817 if (nb_libraries
!= 0)
9818 error("cannot specify libraries with -c");
9821 /* compute default outfile name */
9822 if (output_type
!= TCC_OUTPUT_MEMORY
&& !outfile
) {
9823 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
9826 pstrcpy(objfilename
, sizeof(objfilename
) - 1,
9827 tcc_basename(files
[0]));
9828 /* add .o extension */
9829 ext
= strrchr(objfilename
, '.');
9831 goto default_outfile
;
9832 strcpy(ext
+ 1, "o");
9835 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
9837 outfile
= objfilename
;
9841 start_time
= getclock_us();
9844 tcc_set_output_type(s
, output_type
);
9846 /* compile or add each files or library */
9847 for(i
= 0;i
< nb_files
; i
++) {
9848 const char *filename
;
9850 filename
= files
[i
];
9851 if (filename
[0] == '-') {
9852 if (tcc_add_library(s
, filename
+ 2) < 0)
9853 error("cannot find %s", filename
);
9855 if (tcc_add_file(s
, filename
) < 0) {
9862 /* free all files */
9867 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
9868 if (total_time
< 0.001)
9870 if (total_bytes
< 1)
9872 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
9873 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
9874 total_time
, (int)(total_lines
/ total_time
),
9875 total_bytes
/ total_time
/ 1000000.0);
9878 if (s
->output_type
!= TCC_OUTPUT_MEMORY
) {
9879 tcc_output_file(s
, outfile
);
9882 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
9885 /* XXX: cannot do it with bound checking because of the malloc hooks */
9886 if (!do_bounds_check
)
9891 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);