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 int nostdinc
; /* if true, no standard headers are added */
396 int nostdlib
; /* if true, no standard libraries are added */
398 /* if true, static linking is performed */
401 /* if true, only link in referenced objects from archive */
404 /* warning switches */
405 int warn_write_strings
;
406 int warn_unsupported
;
411 void (*error_func
)(void *opaque
, const char *msg
);
412 int error_set_jmp_enabled
;
413 jmp_buf error_jmp_buf
;
416 /* tiny assembler state */
419 /* see include_stack_ptr */
420 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
422 /* see ifdef_stack_ptr */
423 int ifdef_stack
[IFDEF_STACK_SIZE
];
426 /* The current value can be: */
427 #define VT_VALMASK 0x00ff
428 #define VT_CONST 0x00f0 /* constant in vc
429 (must be first non register value) */
430 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
431 #define VT_LOCAL 0x00f2 /* offset on stack */
432 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
433 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
434 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
435 #define VT_LVAL 0x0100 /* var is an lvalue */
436 #define VT_SYM 0x0200 /* a symbol value is added */
437 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
438 char/short stored in integer registers) */
439 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
440 dereferencing value */
441 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
442 bounding function call point is in vc */
443 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
444 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
445 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
446 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
449 #define VT_INT 0 /* integer type */
450 #define VT_BYTE 1 /* signed byte type */
451 #define VT_SHORT 2 /* short type */
452 #define VT_VOID 3 /* void type */
453 #define VT_PTR 4 /* pointer */
454 #define VT_ENUM 5 /* enum definition */
455 #define VT_FUNC 6 /* function type */
456 #define VT_STRUCT 7 /* struct/union definition */
457 #define VT_FLOAT 8 /* IEEE float */
458 #define VT_DOUBLE 9 /* IEEE double */
459 #define VT_LDOUBLE 10 /* IEEE long double */
460 #define VT_BOOL 11 /* ISOC99 boolean type */
461 #define VT_LLONG 12 /* 64 bit integer */
462 #define VT_LONG 13 /* long integer (NEVER USED as type, only
464 #define VT_BTYPE 0x000f /* mask for basic type */
465 #define VT_UNSIGNED 0x0010 /* unsigned type */
466 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
467 #define VT_BITFIELD 0x0040 /* bitfield modifier */
468 #define VT_CONSTANT 0x0800 /* const modifier */
469 #define VT_VOLATILE 0x1000 /* volatile modifier */
472 #define VT_EXTERN 0x00000080 /* extern definition */
473 #define VT_STATIC 0x00000100 /* static variable */
474 #define VT_TYPEDEF 0x00000200 /* typedef definition */
475 #define VT_INLINE 0x00000400 /* inline definition */
477 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
479 /* type mask (except storage) */
480 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
481 #define VT_TYPE (~(VT_STORAGE))
485 /* warning: the following compare tokens depend on i386 asm code */
497 #define TOK_LAND 0xa0
501 #define TOK_MID 0xa3 /* inc/dec, to void constant */
503 #define TOK_UDIV 0xb0 /* unsigned division */
504 #define TOK_UMOD 0xb1 /* unsigned modulo */
505 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
506 #define TOK_CINT 0xb3 /* number in tokc */
507 #define TOK_CCHAR 0xb4 /* char constant in tokc */
508 #define TOK_STR 0xb5 /* pointer to string in tokc */
509 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
510 #define TOK_LCHAR 0xb7
511 #define TOK_LSTR 0xb8
512 #define TOK_CFLOAT 0xb9 /* float constant */
513 #define TOK_LINENUM 0xba /* line number info */
514 #define TOK_CDOUBLE 0xc0 /* double constant */
515 #define TOK_CLDOUBLE 0xc1 /* long double constant */
516 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
517 #define TOK_ADDC1 0xc3 /* add with carry generation */
518 #define TOK_ADDC2 0xc4 /* add with carry use */
519 #define TOK_SUBC1 0xc5 /* add with carry generation */
520 #define TOK_SUBC2 0xc6 /* add with carry use */
521 #define TOK_CUINT 0xc8 /* unsigned int constant */
522 #define TOK_CLLONG 0xc9 /* long long constant */
523 #define TOK_CULLONG 0xca /* unsigned long long constant */
524 #define TOK_ARROW 0xcb
525 #define TOK_DOTS 0xcc /* three dots */
526 #define TOK_SHR 0xcd /* unsigned shift right */
527 #define TOK_PPNUM 0xce /* preprocessor number */
529 #define TOK_SHL 0x01 /* shift left */
530 #define TOK_SAR 0x02 /* signed shift right */
532 /* assignement operators : normal operator or 0x80 */
533 #define TOK_A_MOD 0xa5
534 #define TOK_A_AND 0xa6
535 #define TOK_A_MUL 0xaa
536 #define TOK_A_ADD 0xab
537 #define TOK_A_SUB 0xad
538 #define TOK_A_DIV 0xaf
539 #define TOK_A_XOR 0xde
540 #define TOK_A_OR 0xfc
541 #define TOK_A_SHL 0x81
542 #define TOK_A_SAR 0x82
545 #define offsetof(type, field) ((size_t) &((type *)0)->field)
549 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
552 /* WARNING: the content of this string encodes token numbers */
553 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";
555 #define TOK_EOF (-1) /* end of file */
556 #define TOK_LINEFEED 10 /* line feed */
558 /* all identificators and strings have token above that */
559 #define TOK_IDENT 256
561 /* only used for i386 asm opcodes definitions */
562 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
565 DEF(TOK_ASM_ ## x ## b, #x "b") \
566 DEF(TOK_ASM_ ## x ## w, #x "w") \
567 DEF(TOK_ASM_ ## x ## l, #x "l") \
568 DEF(TOK_ASM_ ## x, #x)
571 DEF(TOK_ASM_ ## x ## w, #x "w") \
572 DEF(TOK_ASM_ ## x ## l, #x "l") \
573 DEF(TOK_ASM_ ## x, #x)
576 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
577 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
578 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
579 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
582 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
583 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
586 #define DEF_ASMTEST(x) \
618 #define TOK_ASM_int TOK_INT
621 TOK_LAST
= TOK_IDENT
- 1,
622 #define DEF(id, str) id,
627 static const char tcc_keywords
[] =
628 #define DEF(id, str) str "\0"
633 #define TOK_UIDENT TOK_DEFINE
636 #define snprintf _snprintf
637 #define vsnprintf _vsnprintf
640 #if defined(WIN32) || defined(TCC_UCLIBC) || defined(__FreeBSD__)
641 /* currently incorrect */
642 long double strtold(const char *nptr
, char **endptr
)
644 return (long double)strtod(nptr
, endptr
);
646 float strtof(const char *nptr
, char **endptr
)
648 return (float)strtod(nptr
, endptr
);
651 /* XXX: need to define this to use them in non ISOC99 context */
652 extern float strtof (const char *__nptr
, char **__endptr
);
653 extern long double strtold (const char *__nptr
, char **__endptr
);
656 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
657 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
659 static void next(void);
660 static void next_nomacro(void);
661 static void parse_expr_type(CType
*type
);
662 static void expr_type(CType
*type
);
663 static void unary_type(CType
*type
);
664 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
665 int case_reg
, int is_expr
);
666 static int expr_const(void);
667 static void expr_eq(void);
668 static void gexpr(void);
669 static void decl(int l
);
670 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
671 int first
, int size_only
);
672 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
673 int has_init
, int v
, int scope
);
675 void gv2(int rc1
, int rc2
);
676 void move_reg(int r
, int s
);
677 void save_regs(int n
);
678 void save_reg(int r
);
684 static void macro_subst(TokenString
*tok_str
,
685 Sym
**nested_list
, const int *macro_str
);
686 int save_reg_forced(int r
);
688 void force_charshort_cast(int t
);
689 static void gen_cast(CType
*type
);
691 static Sym
*sym_find(int v
);
692 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
695 static int type_size(CType
*type
, int *a
);
696 static inline CType
*pointed_type(CType
*type
);
697 static int pointed_size(CType
*type
);
698 static int lvalue_type(int t
);
699 static int parse_btype(CType
*type
, AttributeDef
*ad
);
700 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
701 static int is_compatible_types(CType
*type1
, CType
*type2
);
703 void error(const char *fmt
, ...);
705 void vset(CType
*type
, int r
, int v
);
706 void type_to_str(char *buf
, int buf_size
,
707 CType
*type
, const char *varstr
);
708 char *get_tok_str(int v
, CValue
*cv
);
709 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
710 unsigned long offset
, unsigned long size
);
711 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
713 /* section generation */
714 static void section_realloc(Section
*sec
, unsigned long new_size
);
715 static void *section_ptr_add(Section
*sec
, unsigned long size
);
716 static void put_extern_sym(Sym
*sym
, Section
*section
,
717 unsigned long value
, unsigned long size
);
718 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
719 static int put_elf_str(Section
*s
, const char *sym
);
720 static int put_elf_sym(Section
*s
,
721 unsigned long value
, unsigned long size
,
722 int info
, int other
, int shndx
, const char *name
);
723 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
724 int info
, int sh_num
, const char *name
);
725 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
726 int type
, int symbol
);
727 static void put_stabs(const char *str
, int type
, int other
, int desc
,
728 unsigned long value
);
729 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
730 unsigned long value
, Section
*sec
, int sym_index
);
731 static void put_stabn(int type
, int other
, int desc
, int value
);
732 static void put_stabd(int type
, int other
, int desc
);
733 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
735 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
736 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
737 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
741 #ifdef CONFIG_TCC_ASM
743 typedef struct ExprValue
{
748 #define MAX_ASM_OPERANDS 30
750 typedef struct ASMOperand
{
751 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
753 char asm_str
[16]; /* computed asm string for operand */
754 SValue
*vt
; /* C value of the expression */
755 int ref_index
; /* if >= 0, gives reference to a output constraint */
756 int priority
; /* priority, used to assign registers */
757 int reg
; /* if >= 0, register number used for this operand */
758 int is_llong
; /* true if double register value */
761 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
762 static int asm_int_expr(TCCState
*s1
);
763 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
764 const char *name
, const char **pp
);
766 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
770 static void asm_instr(void);
772 /* true if float/double/long double type */
773 static inline int is_float(int t
)
777 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
780 #ifdef TCC_TARGET_I386
781 #include "i386-gen.c"
784 #ifdef CONFIG_TCC_STATIC
786 #define RTLD_LAZY 0x001
787 #define RTLD_NOW 0x002
788 #define RTLD_GLOBAL 0x100
789 #define RTLD_DEFAULT NULL
791 /* dummy function for profiling */
792 void *dlopen(const char *filename
, int flag
)
797 const char *dlerror(void)
802 typedef struct TCCSyms
{
807 #define TCCSYM(a) { #a, &a, },
809 /* add the symbol you want here if no dynamic linking is done */
810 static TCCSyms tcc_syms
[] = {
818 void *dlsym(void *handle
, const char *symbol
)
822 while (p
->str
!= NULL
) {
823 if (!strcmp(p
->str
, symbol
))
832 /********************************************************/
834 /* we use our own 'finite' function to avoid potential problems with
835 non standard math libs */
836 /* XXX: endianness dependent */
837 int ieee_finite(double d
)
840 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
843 /* copy a string and truncate it. */
844 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
851 q_end
= buf
+ buf_size
- 1;
863 /* strcat and truncate. */
864 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
869 pstrcpy(buf
+ len
, buf_size
- len
, s
);
873 /* memory management */
879 static inline void tcc_free(void *ptr
)
882 mem_cur_size
-= malloc_usable_size(ptr
);
887 static void *tcc_malloc(unsigned long size
)
892 error("memory full");
894 mem_cur_size
+= malloc_usable_size(ptr
);
895 if (mem_cur_size
> mem_max_size
)
896 mem_max_size
= mem_cur_size
;
901 static void *tcc_mallocz(unsigned long size
)
904 ptr
= tcc_malloc(size
);
905 memset(ptr
, 0, size
);
909 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
913 mem_cur_size
-= malloc_usable_size(ptr
);
915 ptr1
= realloc(ptr
, size
);
917 /* NOTE: count not correct if alloc error, but not critical */
918 mem_cur_size
+= malloc_usable_size(ptr1
);
919 if (mem_cur_size
> mem_max_size
)
920 mem_max_size
= mem_cur_size
;
925 static char *tcc_strdup(const char *str
)
928 ptr
= tcc_malloc(strlen(str
) + 1);
933 #define free(p) use_tcc_free(p)
934 #define malloc(s) use_tcc_malloc(s)
935 #define realloc(p, s) use_tcc_realloc(p, s)
937 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
944 /* every power of two we double array size */
945 if ((nb
& (nb
- 1)) == 0) {
950 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
952 error("memory full");
959 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
963 sec
= tcc_mallocz(sizeof(Section
));
964 pstrcpy(sec
->name
, sizeof(sec
->name
), name
);
965 sec
->sh_type
= sh_type
;
966 sec
->sh_flags
= sh_flags
;
973 sec
->sh_addralign
= 4;
976 sec
->sh_addralign
= 1;
979 sec
->sh_addralign
= 32; /* default conservative alignment */
983 /* only add section if not private */
984 if (!(sh_flags
& SHF_PRIVATE
)) {
985 sec
->sh_num
= s1
->nb_sections
;
986 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
991 static void free_section(Section
*s
)
997 /* realloc section and set its content to zero */
998 static void section_realloc(Section
*sec
, unsigned long new_size
)
1001 unsigned char *data
;
1003 size
= sec
->data_allocated
;
1006 while (size
< new_size
)
1008 data
= tcc_realloc(sec
->data
, size
);
1010 error("memory full");
1011 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1013 sec
->data_allocated
= size
;
1016 /* reserve at least 'size' bytes in section 'sec' from
1017 sec->data_offset. */
1018 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1020 unsigned long offset
, offset1
;
1022 offset
= sec
->data_offset
;
1023 offset1
= offset
+ size
;
1024 if (offset1
> sec
->data_allocated
)
1025 section_realloc(sec
, offset1
);
1026 sec
->data_offset
= offset1
;
1027 return sec
->data
+ offset
;
1030 /* return a reference to a section, and create it if it does not
1032 Section
*find_section(TCCState
*s1
, const char *name
)
1036 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1037 sec
= s1
->sections
[i
];
1038 if (!strcmp(name
, sec
->name
))
1041 /* sections are created as PROGBITS */
1042 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1045 /* update sym->c so that it points to an external symbol in section
1046 'section' with value 'value' */
1047 static void put_extern_sym(Sym
*sym
, Section
*section
,
1048 unsigned long value
, unsigned long size
)
1050 int sym_type
, sym_bind
, sh_num
, info
;
1055 sh_num
= section
->sh_num
;
1059 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
)
1060 sym_type
= STT_FUNC
;
1062 sym_type
= STT_OBJECT
;
1063 if (sym
->type
.t
& VT_STATIC
)
1064 sym_bind
= STB_LOCAL
;
1066 sym_bind
= STB_GLOBAL
;
1068 name
= get_tok_str(sym
->v
, NULL
);
1069 #ifdef CONFIG_TCC_BCHECK
1070 if (do_bounds_check
) {
1073 /* XXX: avoid doing that for statics ? */
1074 /* if bound checking is activated, we change some function
1075 names by adding the "__bound" prefix */
1078 /* XXX: we rely only on malloc hooks */
1090 strcpy(buf
, "__bound_");
1097 info
= ELF32_ST_INFO(sym_bind
, sym_type
);
1098 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, sh_num
, name
);
1100 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
1101 esym
->st_value
= value
;
1102 esym
->st_size
= size
;
1103 esym
->st_shndx
= sh_num
;
1107 /* add a new relocation entry to symbol 'sym' in section 's' */
1108 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1111 put_extern_sym(sym
, NULL
, 0, 0);
1112 /* now we can add ELF relocation info */
1113 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1116 static inline int isid(int c
)
1118 return (c
>= 'a' && c
<= 'z') ||
1119 (c
>= 'A' && c
<= 'Z') ||
1123 static inline int isnum(int c
)
1125 return c
>= '0' && c
<= '9';
1128 static inline int isoct(int c
)
1130 return c
>= '0' && c
<= '7';
1133 static inline int toup(int c
)
1135 if (c
>= 'a' && c
<= 'z')
1136 return c
- 'a' + 'A';
1141 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1145 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1148 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1152 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1156 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1163 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1164 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1165 (*f
)->filename
, (*f
)->line_num
);
1166 if (file
->line_num
> 0) {
1167 strcat_printf(buf
, sizeof(buf
),
1168 "%s:%d: ", file
->filename
, file
->line_num
);
1170 strcat_printf(buf
, sizeof(buf
),
1171 "%s: ", file
->filename
);
1174 strcat_printf(buf
, sizeof(buf
),
1178 strcat_printf(buf
, sizeof(buf
), "warning: ");
1179 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1181 if (!s1
->error_func
) {
1182 /* default case: stderr */
1183 fprintf(stderr
, "%s\n", buf
);
1185 s1
->error_func(s1
->error_opaque
, buf
);
1187 if (!is_warning
|| s1
->warn_error
)
1192 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1193 void (*error_func
)(void *opaque
, const char *msg
))
1195 s
->error_opaque
= error_opaque
;
1196 s
->error_func
= error_func
;
1200 /* error without aborting current compilation */
1201 void error_noabort(const char *fmt
, ...)
1203 TCCState
*s1
= tcc_state
;
1207 error1(s1
, 0, fmt
, ap
);
1211 void error(const char *fmt
, ...)
1213 TCCState
*s1
= tcc_state
;
1217 error1(s1
, 0, fmt
, ap
);
1219 /* better than nothing: in some cases, we accept to handle errors */
1220 if (s1
->error_set_jmp_enabled
) {
1221 longjmp(s1
->error_jmp_buf
, 1);
1223 /* XXX: eliminate this someday */
1228 void expect(const char *msg
)
1230 error("%s expected", msg
);
1233 void warning(const char *fmt
, ...)
1235 TCCState
*s1
= tcc_state
;
1239 error1(s1
, 1, fmt
, ap
);
1246 error("'%c' expected", c
);
1250 static void test_lvalue(void)
1252 if (!(vtop
->r
& VT_LVAL
))
1256 /* allocate a new token */
1257 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1259 TokenSym
*ts
, **ptable
;
1262 if (tok_ident
>= SYM_FIRST_ANOM
)
1263 error("memory full");
1265 /* expand token table if needed */
1266 i
= tok_ident
- TOK_IDENT
;
1267 if ((i
% TOK_ALLOC_INCR
) == 0) {
1268 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1270 error("memory full");
1271 table_ident
= ptable
;
1274 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1275 table_ident
[i
] = ts
;
1276 ts
->tok
= tok_ident
++;
1277 ts
->sym_define
= NULL
;
1278 ts
->sym_label
= NULL
;
1279 ts
->sym_struct
= NULL
;
1280 ts
->sym_identifier
= NULL
;
1282 ts
->hash_next
= NULL
;
1283 memcpy(ts
->str
, str
, len
);
1284 ts
->str
[len
] = '\0';
1289 #define TOK_HASH_INIT 1
1290 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1292 /* find a token and add it if not found */
1293 static TokenSym
*tok_alloc(const char *str
, int len
)
1295 TokenSym
*ts
, **pts
;
1301 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1302 h
&= (TOK_HASH_SIZE
- 1);
1304 pts
= &hash_ident
[h
];
1309 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1311 pts
= &(ts
->hash_next
);
1313 return tok_alloc_new(pts
, str
, len
);
1316 /* CString handling */
1318 static void cstr_realloc(CString
*cstr
, int new_size
)
1323 size
= cstr
->size_allocated
;
1325 size
= 8; /* no need to allocate a too small first string */
1326 while (size
< new_size
)
1328 data
= tcc_realloc(cstr
->data_allocated
, size
);
1330 error("memory full");
1331 cstr
->data_allocated
= data
;
1332 cstr
->size_allocated
= size
;
1337 static void cstr_ccat(CString
*cstr
, int ch
)
1340 size
= cstr
->size
+ 1;
1341 if (size
> cstr
->size_allocated
)
1342 cstr_realloc(cstr
, size
);
1343 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1347 static void cstr_cat(CString
*cstr
, const char *str
)
1359 /* add a wide char */
1360 static void cstr_wccat(CString
*cstr
, int ch
)
1363 size
= cstr
->size
+ sizeof(int);
1364 if (size
> cstr
->size_allocated
)
1365 cstr_realloc(cstr
, size
);
1366 *(int *)(((unsigned char *)cstr
->data
) + size
- sizeof(int)) = ch
;
1370 static void cstr_new(CString
*cstr
)
1372 memset(cstr
, 0, sizeof(CString
));
1375 /* free string and reset it to NULL */
1376 static void cstr_free(CString
*cstr
)
1378 tcc_free(cstr
->data_allocated
);
1382 #define cstr_reset(cstr) cstr_free(cstr)
1384 static CString
*cstr_dup(CString
*cstr1
)
1389 cstr
= tcc_malloc(sizeof(CString
));
1392 cstr
->size_allocated
= size
;
1393 cstr
->data_allocated
= tcc_malloc(size
);
1394 cstr
->data
= cstr
->data_allocated
;
1395 memcpy(cstr
->data_allocated
, cstr1
->data_allocated
, size
);
1399 /* XXX: unicode ? */
1400 static void add_char(CString
*cstr
, int c
)
1402 if (c
== '\'' || c
== '\"' || c
== '\\') {
1403 /* XXX: could be more precise if char or string */
1404 cstr_ccat(cstr
, '\\');
1406 if (c
>= 32 && c
<= 126) {
1409 cstr_ccat(cstr
, '\\');
1411 cstr_ccat(cstr
, 'n');
1413 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1414 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1415 cstr_ccat(cstr
, '0' + (c
& 7));
1420 /* XXX: buffer overflow */
1421 /* XXX: float tokens */
1422 char *get_tok_str(int v
, CValue
*cv
)
1424 static char buf
[STRING_MAX_SIZE
+ 1];
1425 static CString cstr_buf
;
1431 /* NOTE: to go faster, we give a fixed buffer for small strings */
1432 cstr_reset(&cstr_buf
);
1433 cstr_buf
.data
= buf
;
1434 cstr_buf
.size_allocated
= sizeof(buf
);
1440 /* XXX: not quite exact, but only useful for testing */
1441 sprintf(p
, "%u", cv
->ui
);
1445 /* XXX: not quite exact, but only useful for testing */
1446 sprintf(p
, "%Lu", cv
->ull
);
1450 cstr_ccat(&cstr_buf
, '\'');
1451 add_char(&cstr_buf
, cv
->i
);
1452 cstr_ccat(&cstr_buf
, '\'');
1453 cstr_ccat(&cstr_buf
, '\0');
1457 len
= cstr
->size
- 1;
1459 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1460 cstr_ccat(&cstr_buf
, '\0');
1465 cstr_ccat(&cstr_buf
, '\"');
1467 len
= cstr
->size
- 1;
1469 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1471 len
= (cstr
->size
/ sizeof(int)) - 1;
1473 add_char(&cstr_buf
, ((int *)cstr
->data
)[i
]);
1475 cstr_ccat(&cstr_buf
, '\"');
1476 cstr_ccat(&cstr_buf
, '\0');
1485 return strcpy(p
, "<<=");
1487 return strcpy(p
, ">>=");
1489 if (v
< TOK_IDENT
) {
1490 /* search in two bytes table */
1504 } else if (v
< tok_ident
) {
1505 return table_ident
[v
- TOK_IDENT
]->str
;
1506 } else if (v
>= SYM_FIRST_ANOM
) {
1507 /* special name for anonymous symbol */
1508 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1510 /* should never happen */
1515 return cstr_buf
.data
;
1518 /* push, without hashing */
1519 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, int c
)
1522 s
= tcc_malloc(sizeof(Sym
));
1533 /* find a symbol and return its associated structure. 's' is the top
1534 of the symbol stack */
1535 static Sym
*sym_find2(Sym
*s
, int v
)
1545 /* structure lookup */
1546 static inline Sym
*struct_find(int v
)
1549 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1551 return table_ident
[v
]->sym_struct
;
1554 /* find an identifier */
1555 static inline Sym
*sym_find(int v
)
1558 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1560 return table_ident
[v
]->sym_identifier
;
1563 /* push a given symbol on the symbol stack */
1564 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1573 s
= sym_push2(ps
, v
, type
->t
, c
);
1574 s
->type
.ref
= type
->ref
;
1576 /* don't record fields or anonymous symbols */
1578 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1579 /* record symbol in token array */
1580 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1582 ps
= &ts
->sym_struct
;
1584 ps
= &ts
->sym_identifier
;
1591 /* push a global identifier */
1592 static Sym
*global_identifier_push(int v
, int t
, int c
)
1595 s
= sym_push2(&global_stack
, v
, t
, c
);
1596 /* don't record anonymous symbol */
1597 if (v
< SYM_FIRST_ANOM
) {
1598 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1599 /* modify the top most local identifier, so that
1600 sym_identifier will point to 's' when popped */
1602 ps
= &(*ps
)->prev_tok
;
1609 /* pop symbols until top reaches 'b' */
1610 static void sym_pop(Sym
**ptop
, Sym
*b
)
1620 /* remove symbol in token array */
1622 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1623 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1625 ps
= &ts
->sym_struct
;
1627 ps
= &ts
->sym_identifier
;
1638 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1643 fd
= open(filename
, O_RDONLY
);
1646 bf
= tcc_malloc(sizeof(BufferedFile
));
1652 bf
->buf_ptr
= bf
->buffer
;
1653 bf
->buf_end
= bf
->buffer
;
1654 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1655 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1657 bf
->ifndef_macro
= 0;
1658 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1659 // printf("opening '%s'\n", filename);
1663 void tcc_close(BufferedFile
*bf
)
1665 total_lines
+= bf
->line_num
;
1670 /* fill input buffer and peek next char */
1671 static int tcc_peekc_slow(BufferedFile
*bf
)
1674 /* only tries to read if really end of buffer */
1675 if (bf
->buf_ptr
>= bf
->buf_end
) {
1677 #if defined(PARSE_DEBUG)
1682 len
= read(bf
->fd
, bf
->buffer
, len
);
1689 bf
->buf_ptr
= bf
->buffer
;
1690 bf
->buf_end
= bf
->buffer
+ len
;
1691 *bf
->buf_end
= CH_EOB
;
1693 if (bf
->buf_ptr
< bf
->buf_end
) {
1694 return bf
->buf_ptr
[0];
1696 bf
->buf_ptr
= bf
->buf_end
;
1701 /* return the current character, handling end of block if necessary
1703 static int handle_eob(void)
1705 return tcc_peekc_slow(file
);
1708 /* read next char from current input file and handle end of input buffer */
1709 static inline void inp(void)
1711 ch
= *(++(file
->buf_ptr
));
1712 /* end of buffer/file handling */
1717 /* handle '\[\r]\n' */
1718 static void handle_stray(void)
1720 while (ch
== '\\') {
1725 } else if (ch
== '\r') {
1733 error("stray '\\' in program");
1738 /* skip the stray and handle the \\n case. Output an error if
1739 incorrect char after the stray */
1740 static int handle_stray1(uint8_t *p
)
1744 if (p
>= file
->buf_end
) {
1761 /* handle just the EOB case, but not stray */
1762 #define PEEKC_EOB(c, p)\
1773 /* handle the complicated stray case */
1774 #define PEEKC(c, p)\
1779 c = handle_stray1(p);\
1784 /* input with '\[\r]\n' handling. Note that this function cannot
1785 handle other characters after '\', so you cannot call it inside
1786 strings or comments */
1787 static void minp(void)
1795 /* single line C++ comments */
1796 static uint8_t *parse_line_comment(uint8_t *p
)
1803 if (c
== '\n' || c
== CH_EOF
) {
1805 } else if (c
== '\\') {
1810 } else if (c
== '\r') {
1825 static uint8_t *parse_comment(uint8_t *p
)
1831 /* fast skip loop */
1834 if (c
== '\n' || c
== '*' || c
== '\\')
1838 if (c
== '\n' || c
== '*' || c
== '\\')
1842 /* now we can handle all the cases */
1846 } else if (c
== '*') {
1852 } else if (c
== '/') {
1853 goto end_of_comment
;
1854 } else if (c
== '\\') {
1859 /* skip '\[\r]\n', otherwise just skip the stray */
1865 } else if (c
== '\r') {
1882 /* stray, eob or eof */
1887 error("unexpected end of file in comment");
1888 } else if (c
== '\\') {
1900 /* space exlcuding newline */
1901 static inline int is_space(int ch
)
1903 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
1906 static inline void skip_spaces(void)
1908 while (is_space(ch
))
1912 /* parse a string without interpreting escapes */
1913 static uint8_t *parse_pp_string(uint8_t *p
,
1914 int sep
, CString
*str
)
1922 } else if (c
== '\\') {
1927 unterminated_string
:
1928 /* XXX: indicate line number of start of string */
1929 error("missing terminating %c character", sep
);
1930 } else if (c
== '\\') {
1931 /* escape : just skip \[\r]\n */
1936 } else if (c
== '\r') {
1939 expect("'\n' after '\r'");
1942 } else if (c
== CH_EOF
) {
1943 goto unterminated_string
;
1946 cstr_ccat(str
, '\\');
1952 } else if (c
== '\n') {
1955 } else if (c
== '\r') {
1958 cstr_ccat(str
, '\r');
1974 /* skip block of text until #else, #elif or #endif. skip also pairs of
1976 void preprocess_skip(void)
1978 int a
, start_of_line
, c
;
2005 } else if (c
== '\\') {
2006 /* XXX: incorrect: should not give an error */
2007 ch
= file
->buf_ptr
[0];
2015 p
= parse_pp_string(p
, c
, NULL
);
2024 p
= parse_comment(p
);
2025 } else if (ch
== '/') {
2026 p
= parse_line_comment(p
);
2032 if (start_of_line
) {
2037 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2039 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2041 else if (tok
== TOK_ENDIF
)
2055 /* ParseState handling */
2057 /* XXX: currently, no include file info is stored. Thus, we cannot display
2058 accurate messages if the function or data definition spans multiple
2061 /* save current parse state in 's' */
2062 void save_parse_state(ParseState
*s
)
2064 s
->line_num
= file
->line_num
;
2065 s
->macro_ptr
= macro_ptr
;
2070 /* restore parse state from 's' */
2071 void restore_parse_state(ParseState
*s
)
2073 file
->line_num
= s
->line_num
;
2074 macro_ptr
= s
->macro_ptr
;
2079 /* return the number of additional 'ints' necessary to store the
2081 static inline int tok_ext_size(int t
)
2100 return LDOUBLE_SIZE
/ 4;
2106 /* token string handling */
2108 static inline void tok_str_new(TokenString
*s
)
2112 s
->allocated_len
= 0;
2113 s
->last_line_num
= -1;
2116 static void tok_str_free(int *str
)
2125 /* NOTE: we test zero separately so that GCC can generate a
2126 table for the following switch */
2141 /* XXX: use a macro to be portable on 64 bit ? */
2142 cstr
= (CString
*)p
[1];
2153 p
+= 1 + (LDOUBLE_SIZE
/ 4);
2163 static int *tok_str_realloc(TokenString
*s
)
2167 len
= s
->allocated_len
+ TOK_STR_ALLOC_INCR
;
2168 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2170 error("memory full");
2171 s
->allocated_len
= len
;
2176 static void tok_str_add(TokenString
*s
, int t
)
2182 if (len
>= s
->allocated_len
)
2183 str
= tok_str_realloc(s
);
2188 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2195 /* allocate space for worst case */
2196 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2197 str
= tok_str_realloc(s
);
2206 str
[len
++] = cv
->tab
[0];
2211 str
[len
++] = (int)cstr_dup(cv
->cstr
);
2216 str
[len
++] = cv
->tab
[0];
2217 str
[len
++] = cv
->tab
[1];
2220 #if LDOUBLE_SIZE == 12
2221 str
[len
++] = cv
->tab
[0];
2222 str
[len
++] = cv
->tab
[1];
2223 str
[len
++] = cv
->tab
[2];
2225 #error add long double size support
2234 /* add the current parse token in token string 's' */
2235 static void tok_str_add_tok(TokenString
*s
)
2239 /* save line number info */
2240 if (file
->line_num
!= s
->last_line_num
) {
2241 s
->last_line_num
= file
->line_num
;
2242 cval
.i
= s
->last_line_num
;
2243 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2245 tok_str_add2(s
, tok
, &tokc
);
2248 #if LDOUBLE_SIZE == 12
2249 #define LDOUBLE_GET(p, cv) \
2254 #error add long double size support
2258 /* get a token from an integer array and increment pointer
2259 accordingly. we code it as a macro to avoid pointer aliasing. */
2260 #define TOK_GET(t, p, cv) \
2282 case TOK_CLDOUBLE: \
2283 LDOUBLE_GET(p, cv); \
2284 p += LDOUBLE_SIZE / 4; \
2291 /* defines handling */
2292 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2296 s
= sym_push2(&define_stack
, v
, macro_type
, (int)str
);
2297 s
->next
= first_arg
;
2298 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2301 /* undefined a define symbol. Its name is just set to zero */
2302 static void define_undef(Sym
*s
)
2306 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2307 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2311 static inline Sym
*define_find(int v
)
2314 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2316 return table_ident
[v
]->sym_define
;
2319 /* free define stack until top reaches 'b' */
2320 static void free_defines(Sym
*b
)
2328 /* do not free args or predefined defines */
2330 tok_str_free((int *)top
->c
);
2332 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2333 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2341 static Sym
*label_find(int v
)
2344 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2346 return table_ident
[v
]->sym_label
;
2349 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2352 s
= sym_push2(ptop
, v
, 0, 0);
2354 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2355 if (ptop
== &global_label_stack
) {
2356 /* modify the top most local identifier, so that
2357 sym_identifier will point to 's' when popped */
2359 ps
= &(*ps
)->prev_tok
;
2366 /* pop labels until element last is reached. Look if any labels are
2367 undefined. Define symbols if '&&label' was used. */
2368 static void label_pop(Sym
**ptop
, Sym
*slast
)
2371 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2373 if (s
->r
== LABEL_DECLARED
) {
2374 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2375 } else if (s
->r
== LABEL_FORWARD
) {
2376 error("label '%s' used but not defined",
2377 get_tok_str(s
->v
, NULL
));
2380 /* define corresponding symbol. A size of
2382 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2386 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2392 /* eval an expression for #if/#elif */
2393 static int expr_preprocess(void)
2399 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2400 next(); /* do macro subst */
2401 if (tok
== TOK_DEFINED
) {
2406 c
= define_find(tok
) != 0;
2411 } else if (tok
>= TOK_IDENT
) {
2412 /* if undefined macro */
2416 tok_str_add_tok(&str
);
2418 tok_str_add(&str
, -1); /* simulate end of file */
2419 tok_str_add(&str
, 0);
2420 /* now evaluate C constant expression */
2421 macro_ptr
= str
.str
;
2425 tok_str_free(str
.str
);
2429 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2430 static void tok_print(int *str
)
2436 TOK_GET(t
, str
, cval
);
2439 printf(" %s", get_tok_str(t
, &cval
));
2445 /* parse after #define */
2446 static void parse_define(void)
2448 Sym
*s
, *first
, **ps
;
2449 int v
, t
, varg
, is_vaargs
, c
;
2454 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2455 /* XXX: should check if same macro (ANSI) */
2458 /* '(' must be just after macro definition for MACRO_FUNC */
2459 c
= file
->buf_ptr
[0];
2461 c
= handle_stray1(file
->buf_ptr
);
2466 while (tok
!= ')') {
2470 if (varg
== TOK_DOTS
) {
2471 varg
= TOK___VA_ARGS__
;
2473 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2477 if (varg
< TOK_IDENT
)
2478 error("badly punctuated parameter list");
2479 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2490 /* EOF testing necessary for '-D' handling */
2491 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2492 tok_str_add2(&str
, tok
, &tokc
);
2495 tok_str_add(&str
, 0);
2497 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2500 define_push(v
, t
, str
.str
, first
);
2503 /* XXX: use a token or a hash table to accelerate matching ? */
2504 static CachedInclude
*search_cached_include(TCCState
*s1
,
2505 int type
, const char *filename
)
2510 for(i
= 0;i
< s1
->nb_cached_includes
; i
++) {
2511 e
= s1
->cached_includes
[i
];
2512 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2518 static inline void add_cached_include(TCCState
*s1
, int type
,
2519 const char *filename
, int ifndef_macro
)
2523 if (search_cached_include(s1
, type
, filename
))
2526 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2528 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2532 strcpy(e
->filename
, filename
);
2533 e
->ifndef_macro
= ifndef_macro
;
2534 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2537 /* is_bof is true if first non space token at beginning of file */
2538 static void preprocess(int is_bof
)
2540 TCCState
*s1
= tcc_state
;
2541 int size
, i
, c
, n
, saved_parse_flags
;
2542 char buf
[1024], *q
, *p
;
2548 saved_parse_flags
= parse_flags
;
2549 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
2550 PARSE_FLAG_LINEFEED
;
2560 s
= define_find(tok
);
2561 /* undefine symbol by putting an invalid name */
2566 ch
= file
->buf_ptr
[0];
2567 /* XXX: incorrect if comments : use next_nomacro with a special mode */
2572 } else if (ch
== '\"') {
2575 /* XXX: better stray handling */
2578 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
2579 if ((q
- buf
) < sizeof(buf
) - 1)
2586 /* eat all spaces and comments after include */
2587 /* XXX: slightly incorrect */
2588 while (ch1
!= '\n' && ch1
!= CH_EOF
)
2592 /* computed #include : either we have only strings or
2593 we have anything enclosed in '<>' */
2596 if (tok
== TOK_STR
) {
2597 while (tok
!= TOK_LINEFEED
) {
2598 if (tok
!= TOK_STR
) {
2600 error("'#include' expects \"FILENAME\" or <FILENAME>");
2602 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
2608 while (tok
!= TOK_LINEFEED
) {
2609 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
2613 /* check syntax and remove '<>' */
2614 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
2615 goto include_syntax
;
2616 memmove(buf
, buf
+ 1, len
- 2);
2617 buf
[len
- 2] = '\0';
2622 e
= search_cached_include(s1
, c
, buf
);
2623 if (e
&& define_find(e
->ifndef_macro
)) {
2624 /* no need to parse the include because the 'ifndef macro'
2627 printf("%s: skipping %s\n", file
->filename
, buf
);
2631 /* first search in current dir if "header.h" */
2633 p
= strrchr(file
->filename
, '/');
2635 size
= p
+ 1 - file
->filename
;
2636 if (size
> sizeof(buf1
) - 1)
2637 size
= sizeof(buf1
) - 1;
2638 memcpy(buf1
, file
->filename
, size
);
2640 pstrcat(buf1
, sizeof(buf1
), buf
);
2641 f
= tcc_open(s1
, buf1
);
2645 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
2646 error("#include recursion too deep");
2647 /* now search in all the include paths */
2648 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
2649 for(i
= 0; i
< n
; i
++) {
2651 if (i
< s1
->nb_include_paths
)
2652 path
= s1
->include_paths
[i
];
2654 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
2655 pstrcpy(buf1
, sizeof(buf1
), path
);
2656 pstrcat(buf1
, sizeof(buf1
), "/");
2657 pstrcat(buf1
, sizeof(buf1
), buf
);
2658 f
= tcc_open(s1
, buf1
);
2662 error("include file '%s' not found", buf
);
2666 printf("%s: including %s\n", file
->filename
, buf1
);
2669 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
2670 /* push current file in stack */
2671 /* XXX: fix current line init */
2672 *s1
->include_stack_ptr
++ = file
;
2674 /* add include file debug info */
2676 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
2678 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
2679 ch
= file
->buf_ptr
[0];
2687 c
= expr_preprocess();
2693 if (tok
< TOK_IDENT
)
2694 error("invalid argument for '#if%sdef'", c
? "n" : "");
2698 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
2700 file
->ifndef_macro
= tok
;
2703 c
= (define_find(tok
) != 0) ^ c
;
2705 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
2706 error("memory full");
2707 *s1
->ifdef_stack_ptr
++ = c
;
2710 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2711 error("#else without matching #if");
2712 if (s1
->ifdef_stack_ptr
[-1] & 2)
2713 error("#else after #else");
2714 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
2717 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2718 error("#elif without matching #if");
2719 c
= s1
->ifdef_stack_ptr
[-1];
2721 error("#elif after #else");
2722 /* last #if/#elif expression was true: we skip */
2725 c
= expr_preprocess();
2726 s1
->ifdef_stack_ptr
[-1] = c
;
2736 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
2737 error("#endif without matching #if");
2738 s1
->ifdef_stack_ptr
--;
2739 /* '#ifndef macro' was at the start of file. Now we check if
2740 an '#endif' is exactly at the end of file */
2741 if (file
->ifndef_macro
&&
2742 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
2743 file
->ifndef_macro_saved
= file
->ifndef_macro
;
2744 /* need to set to zero to avoid false matches if another
2745 #ifndef at middle of file */
2746 file
->ifndef_macro
= 0;
2747 while (tok
!= TOK_LINEFEED
)
2749 tok_flags
|= TOK_FLAG_ENDIF
;
2755 if (tok
!= TOK_CINT
)
2757 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
2759 if (tok
!= TOK_LINEFEED
) {
2762 pstrcpy(file
->filename
, sizeof(file
->filename
),
2763 (char *)tokc
.cstr
->data
);
2769 ch
= file
->buf_ptr
[0];
2772 while (ch
!= '\n' && ch
!= CH_EOF
) {
2773 if ((q
- buf
) < sizeof(buf
) - 1)
2779 error("#error %s", buf
);
2781 warning("#warning %s", buf
);
2787 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
2788 /* '!' is ignored to allow C scripts. numbers are ignored
2789 to emulate cpp behaviour */
2791 error("invalid preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2795 /* ignore other preprocess commands or #! for C scripts */
2796 while (tok
!= TOK_LINEFEED
)
2799 parse_flags
= saved_parse_flags
;
2802 /* evaluate escape codes in a string. */
2803 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2818 case '0': case '1': case '2': case '3':
2819 case '4': case '5': case '6': case '7':
2820 /* at most three octal digits */
2825 n
= n
* 8 + c
- '0';
2829 n
= n
* 8 + c
- '0';
2834 goto add_char_nonext
;
2840 if (c
>= 'a' && c
<= 'f')
2842 else if (c
>= 'A' && c
<= 'F')
2852 goto add_char_nonext
;
2876 goto invalid_escape
;
2886 error("invalid escaped char");
2892 cstr_ccat(outstr
, c
);
2894 cstr_wccat(outstr
, c
);
2896 /* add a trailing '\0' */
2898 cstr_ccat(outstr
, '\0');
2900 cstr_wccat(outstr
, '\0');
2903 /* we use 64 bit numbers */
2906 /* bn = (bn << shift) | or_val */
2907 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2911 for(i
=0;i
<BN_SIZE
;i
++) {
2913 bn
[i
] = (v
<< shift
) | or_val
;
2914 or_val
= v
>> (32 - shift
);
2918 void bn_zero(unsigned int *bn
)
2921 for(i
=0;i
<BN_SIZE
;i
++) {
2926 /* parse number in null terminated string 'p' and return it in the
2928 void parse_number(const char *p
)
2930 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2932 unsigned int bn
[BN_SIZE
];
2943 goto float_frac_parse
;
2944 } else if (t
== '0') {
2945 if (ch
== 'x' || ch
== 'X') {
2949 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2955 /* parse all digits. cannot check octal numbers at this stage
2956 because of floating point constants */
2958 if (ch
>= 'a' && ch
<= 'f')
2960 else if (ch
>= 'A' && ch
<= 'F')
2968 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2970 error("number too long");
2976 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2977 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2979 /* NOTE: strtox should support that for hexa numbers, but
2980 non ISOC99 libcs do not support it, so we prefer to do
2982 /* hexadecimal or binary floats */
2983 /* XXX: handle overflows */
2995 } else if (t
>= 'a') {
2997 } else if (t
>= 'A') {
3002 bn_lshift(bn
, shift
, t
);
3009 if (t
>= 'a' && t
<= 'f') {
3011 } else if (t
>= 'A' && t
<= 'F') {
3013 } else if (t
>= '0' && t
<= '9') {
3019 error("invalid digit");
3020 bn_lshift(bn
, shift
, t
);
3025 if (ch
!= 'p' && ch
!= 'P')
3032 } else if (ch
== '-') {
3036 if (ch
< '0' || ch
> '9')
3037 expect("exponent digits");
3038 while (ch
>= '0' && ch
<= '9') {
3039 exp_val
= exp_val
* 10 + ch
- '0';
3042 exp_val
= exp_val
* s
;
3044 /* now we can generate the number */
3045 /* XXX: should patch directly float number */
3046 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3047 d
= ldexp(d
, exp_val
- frac_bits
);
3052 /* float : should handle overflow */
3054 } else if (t
== 'L') {
3057 /* XXX: not large enough */
3058 tokc
.ld
= (long double)d
;
3064 /* decimal floats */
3066 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3071 while (ch
>= '0' && ch
<= '9') {
3072 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3078 if (ch
== 'e' || ch
== 'E') {
3079 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3083 if (ch
== '-' || ch
== '+') {
3084 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3089 if (ch
< '0' || ch
> '9')
3090 expect("exponent digits");
3091 while (ch
>= '0' && ch
<= '9') {
3092 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3104 tokc
.f
= strtof(token_buf
, NULL
);
3105 } else if (t
== 'L') {
3108 tokc
.ld
= strtold(token_buf
, NULL
);
3111 tokc
.d
= strtod(token_buf
, NULL
);
3115 unsigned long long n
, n1
;
3118 /* integer number */
3121 if (b
== 10 && *q
== '0') {
3128 /* no need for checks except for base 10 / 8 errors */
3131 } else if (t
>= 'a') {
3133 } else if (t
>= 'A') {
3138 error("invalid digit");
3142 /* detect overflow */
3143 /* XXX: this test is not reliable */
3145 error("integer constant overflow");
3148 /* XXX: not exactly ANSI compliant */
3149 if ((n
& 0xffffffff00000000LL
) != 0) {
3154 } else if (n
> 0x7fffffff) {
3165 error("three 'l's in integer constant");
3168 if (tok
== TOK_CINT
)
3170 else if (tok
== TOK_CUINT
)
3174 } else if (t
== 'U') {
3176 error("two 'u's in integer constant");
3178 if (tok
== TOK_CINT
)
3180 else if (tok
== TOK_CLLONG
)
3187 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3195 #define PARSE2(c1, tok1, c2, tok2) \
3206 /* return next token without macro substitution */
3207 static inline void next_nomacro1(void)
3227 /* first look if it is in fact an end of buffer */
3228 if (p
>= file
->buf_end
) {
3232 if (p
>= file
->buf_end
)
3245 TCCState
*s1
= tcc_state
;
3246 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3248 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3249 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3250 /* no include left : end of file. */
3253 /* pop include file */
3255 /* test if previous '#endif' was after a #ifdef at
3257 if (tok_flags
& TOK_FLAG_ENDIF
) {
3259 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3261 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3262 file
->ifndef_macro_saved
);
3265 /* add end of include file debug info */
3267 put_stabd(N_EINCL
, 0, 0);
3269 /* pop include stack */
3271 s1
->include_stack_ptr
--;
3272 file
= *s1
->include_stack_ptr
;
3280 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3284 tok_flags
|= TOK_FLAG_BOL
;
3293 if ((tok_flags
& TOK_FLAG_BOL
) &&
3294 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3296 preprocess(tok_flags
& TOK_FLAG_BOF
);
3302 tok
= TOK_TWOSHARPS
;
3309 case 'a': case 'b': case 'c': case 'd':
3310 case 'e': case 'f': case 'g': case 'h':
3311 case 'i': case 'j': case 'k': case 'l':
3312 case 'm': case 'n': case 'o': case 'p':
3313 case 'q': case 'r': case 's': case 't':
3314 case 'u': case 'v': case 'w': case 'x':
3316 case 'A': case 'B': case 'C': case 'D':
3317 case 'E': case 'F': case 'G': case 'H':
3318 case 'I': case 'J': case 'K':
3319 case 'M': case 'N': case 'O': case 'P':
3320 case 'Q': case 'R': case 'S': case 'T':
3321 case 'U': case 'V': case 'W': case 'X':
3327 h
= TOK_HASH_FUNC(h
, c
);
3331 if (!isidnum_table
[c
])
3333 h
= TOK_HASH_FUNC(h
, c
);
3340 /* fast case : no stray found, so we have the full token
3341 and we have already hashed it */
3343 h
&= (TOK_HASH_SIZE
- 1);
3344 pts
= &hash_ident
[h
];
3349 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3351 pts
= &(ts
->hash_next
);
3353 ts
= tok_alloc_new(pts
, p1
, len
);
3357 cstr_reset(&tokcstr
);
3360 cstr_ccat(&tokcstr
, *p1
);
3366 while (isidnum_table
[c
]) {
3367 cstr_ccat(&tokcstr
, c
);
3370 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3376 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3378 goto parse_ident_fast
;
3381 if (c
== '\'' || c
== '\"') {
3385 cstr_reset(&tokcstr
);
3386 cstr_ccat(&tokcstr
, 'L');
3387 goto parse_ident_slow
;
3391 case '0': case '1': case '2': case '3':
3392 case '4': case '5': case '6': case '7':
3395 cstr_reset(&tokcstr
);
3396 /* after the first digit, accept digits, alpha, '.' or sign if
3397 prefixed by 'eEpP' */
3401 cstr_ccat(&tokcstr
, c
);
3403 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3404 ((c
== '+' || c
== '-') &&
3405 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3408 /* We add a trailing '\0' to ease parsing */
3409 cstr_ccat(&tokcstr
, '\0');
3410 tokc
.cstr
= &tokcstr
;
3414 /* special dot handling because it can also start a number */
3417 cstr_reset(&tokcstr
);
3418 cstr_ccat(&tokcstr
, '.');
3420 } else if (c
== '.') {
3440 /* parse the string */
3442 p
= parse_pp_string(p
, sep
, &str
);
3443 cstr_ccat(&str
, '\0');
3445 /* eval the escape (should be done as TOK_PPNUM) */
3446 cstr_reset(&tokcstr
);
3447 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3452 /* XXX: make it portable */
3456 char_size
= sizeof(int);
3457 if (tokcstr
.size
<= char_size
)
3458 error("empty character constant");
3459 if (tokcstr
.size
> 2 * char_size
)
3460 warning("multi-character character constant");
3462 tokc
.i
= *(int8_t *)tokcstr
.data
;
3465 tokc
.i
= *(int *)tokcstr
.data
;
3469 tokc
.cstr
= &tokcstr
;
3483 } else if (c
== '<') {
3501 } else if (c
== '>') {
3519 } else if (c
== '=') {
3532 } else if (c
== '=') {
3545 } else if (c
== '=') {
3558 } else if (c
== '=') {
3561 } else if (c
== '>') {
3569 PARSE2('!', '!', '=', TOK_NE
)
3570 PARSE2('=', '=', '=', TOK_EQ
)
3571 PARSE2('*', '*', '=', TOK_A_MUL
)
3572 PARSE2('%', '%', '=', TOK_A_MOD
)
3573 PARSE2('^', '^', '=', TOK_A_XOR
)
3575 /* comments or operator */
3579 p
= parse_comment(p
);
3581 } else if (c
== '/') {
3582 p
= parse_line_comment(p
);
3584 } else if (c
== '=') {
3604 case '$': /* only used in assembler */
3609 error("unrecognized character \\x%02x", c
);
3614 #if defined(PARSE_DEBUG)
3615 printf("token = %s\n", get_tok_str(tok
, &tokc
));
3619 /* return next token without macro substitution. Can read input from
3621 static void next_nomacro(void)
3627 TOK_GET(tok
, macro_ptr
, tokc
);
3628 if (tok
== TOK_LINENUM
) {
3629 file
->line_num
= tokc
.i
;
3638 /* substitute args in macro_str and return allocated string */
3639 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
3641 int *st
, last_tok
, t
, notfirst
;
3650 TOK_GET(t
, macro_str
, cval
);
3655 TOK_GET(t
, macro_str
, cval
);
3658 s
= sym_find2(args
, t
);
3665 cstr_ccat(&cstr
, ' ');
3666 TOK_GET(t
, st
, cval
);
3667 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
3670 cstr_ccat(&cstr
, '\0');
3672 printf("stringize: %s\n", (char *)cstr
.data
);
3676 tok_str_add2(&str
, TOK_STR
, &cval
);
3679 tok_str_add2(&str
, t
, &cval
);
3681 } else if (t
>= TOK_IDENT
) {
3682 s
= sym_find2(args
, t
);
3685 /* if '##' is present before or after, no arg substitution */
3686 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
3687 /* special case for var arg macros : ## eats the
3688 ',' if empty VA_ARGS variable. */
3689 /* XXX: test of the ',' is not 100%
3690 reliable. should fix it to avoid security
3692 if (gnu_ext
&& s
->type
.t
&&
3693 last_tok
== TOK_TWOSHARPS
&&
3694 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
3696 /* suppress ',' '##' */
3699 /* suppress '##' and add variable */
3707 TOK_GET(t1
, st
, cval
);
3710 tok_str_add2(&str
, t1
, &cval
);
3714 macro_subst(&str
, nested_list
, st
);
3717 tok_str_add(&str
, t
);
3720 tok_str_add2(&str
, t
, &cval
);
3724 tok_str_add(&str
, 0);
3728 static char const ab_month_name
[12][4] =
3730 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3731 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3734 /* do macro substitution of current token with macro 's' and add
3735 result to (tok_str,tok_len). 'nested_list' is the list of all
3736 macros we got inside to avoid recursing. Return non zero if no
3737 substitution needs to be done */
3738 static int macro_subst_tok(TokenString
*tok_str
,
3739 Sym
**nested_list
, Sym
*s
)
3741 Sym
*args
, *sa
, *sa1
;
3742 int mstr_allocated
, parlevel
, *mstr
, t
;
3748 /* if symbol is a macro, prepare substitution */
3750 /* special macros */
3751 if (tok
== TOK___LINE__
) {
3752 cval
.i
= file
->line_num
;
3753 tok_str_add2(tok_str
, TOK_CINT
, &cval
);
3754 } else if (tok
== TOK___FILE__
) {
3755 cstrval
= file
->filename
;
3757 tok_str_add2(tok_str
, TOK_STR
, &cval
);
3758 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3764 tm
= localtime(&ti
);
3765 if (tok
== TOK___DATE__
) {
3766 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3767 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3769 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3770 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3775 cstr_cat(&cstr
, cstrval
);
3776 cstr_ccat(&cstr
, '\0');
3778 tok_str_add2(tok_str
, TOK_STR
, &cval
);
3783 if (s
->type
.t
== MACRO_FUNC
) {
3784 /* NOTE: we do not use next_nomacro to avoid eating the
3785 next token. XXX: find better solution */
3789 /* end of macro stream: we must look at the token
3790 after in the file */
3796 /* XXX: incorrect with comments */
3797 ch
= file
->buf_ptr
[0];
3798 while (is_space(ch
) || ch
== '\n')
3802 if (t
!= '(') /* no macro subst */
3805 /* argument macro */
3810 /* NOTE: empty args are allowed, except if no args */
3812 /* handle '()' case */
3813 if (!args
&& tok
== ')')
3816 error("macro '%s' used with too many args",
3817 get_tok_str(s
->v
, 0));
3820 /* NOTE: non zero sa->t indicates VA_ARGS */
3821 while ((parlevel
> 0 ||
3823 (tok
!= ',' || sa
->type
.t
))) &&
3827 else if (tok
== ')')
3829 tok_str_add2(&str
, tok
, &tokc
);
3832 tok_str_add(&str
, 0);
3833 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (int)str
.str
);
3836 /* special case for gcc var args: add an empty
3837 var arg argument if it is omitted */
3838 if (sa
&& sa
->type
.t
&& gnu_ext
)
3848 error("macro '%s' used with too few args",
3849 get_tok_str(s
->v
, 0));
3852 /* now subst each arg */
3853 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3858 tok_str_free((int *)sa
->c
);
3864 sym_push2(nested_list
, s
->v
, 0, 0);
3865 macro_subst(tok_str
, nested_list
, mstr
);
3866 /* pop nested defined symbol */
3868 *nested_list
= sa1
->prev
;
3876 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3877 return the resulting string (which must be freed). */
3878 static inline int *macro_twosharps(const int *macro_str
)
3881 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
3883 const char *p1
, *p2
;
3885 TokenString macro_str1
;
3888 start_macro_ptr
= macro_str
;
3889 /* we search the first '##' */
3891 macro_ptr1
= macro_str
;
3892 TOK_GET(t
, macro_str
, cval
);
3893 /* nothing more to do if end of string */
3896 if (*macro_str
== TOK_TWOSHARPS
)
3900 /* we saw '##', so we need more processing to handle it */
3902 tok_str_new(¯o_str1
);
3906 /* add all tokens seen so far */
3907 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
3908 TOK_GET(t
, ptr
, cval
);
3909 tok_str_add2(¯o_str1
, t
, &cval
);
3911 saved_macro_ptr
= macro_ptr
;
3912 /* XXX: get rid of the use of macro_ptr here */
3913 macro_ptr
= (int *)macro_str
;
3915 while (*macro_ptr
== TOK_TWOSHARPS
) {
3917 macro_ptr1
= macro_ptr
;
3920 TOK_GET(t
, macro_ptr
, cval
);
3921 /* We concatenate the two tokens if we have an
3922 identifier or a preprocessing number */
3924 p1
= get_tok_str(tok
, &tokc
);
3925 cstr_cat(&cstr
, p1
);
3926 p2
= get_tok_str(t
, &cval
);
3927 cstr_cat(&cstr
, p2
);
3928 cstr_ccat(&cstr
, '\0');
3930 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
3931 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
3932 if (tok
== TOK_PPNUM
) {
3933 /* if number, then create a number token */
3934 /* NOTE: no need to allocate because
3935 tok_str_add2() does it */
3938 /* if identifier, we must do a test to
3939 validate we have a correct identifier */
3940 if (t
== TOK_PPNUM
) {
3950 if (!isnum(c
) && !isid(c
))
3954 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
3955 tok
= ts
->tok
; /* modify current token */
3958 const char *str
= cstr
.data
;
3959 const unsigned char *q
;
3961 /* we look for a valid token */
3962 /* XXX: do more extensive checks */
3963 if (!strcmp(str
, ">>=")) {
3965 } else if (!strcmp(str
, "<<=")) {
3967 } else if (strlen(str
) == 2) {
3968 /* search in two bytes table */
3973 if (q
[0] == str
[0] && q
[1] == str
[1])
3980 /* NOTE: because get_tok_str use a static buffer,
3983 p1
= get_tok_str(tok
, &tokc
);
3984 cstr_cat(&cstr
, p1
);
3985 cstr_ccat(&cstr
, '\0');
3986 p2
= get_tok_str(t
, &cval
);
3987 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
3988 /* cannot merge tokens: just add them separately */
3989 tok_str_add2(¯o_str1
, tok
, &tokc
);
3990 /* XXX: free associated memory ? */
3997 tok_str_add2(¯o_str1
, tok
, &tokc
);
4002 macro_ptr
= (int *)saved_macro_ptr
;
4004 tok_str_add(¯o_str1
, 0);
4005 return macro_str1
.str
;
4009 /* do macro substitution of macro_str and add result to
4010 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4011 inside to avoid recursing. */
4012 static void macro_subst(TokenString
*tok_str
,
4013 Sym
**nested_list
, const int *macro_str
)
4016 int *saved_macro_ptr
, *macro_str1
;
4021 /* first scan for '##' operator handling */
4023 macro_str1
= macro_twosharps(ptr
);
4027 /* NOTE: ptr == NULL can only happen if tokens are read from
4028 file stream due to a macro function call */
4031 TOK_GET(t
, ptr
, cval
);
4036 /* if nested substitution, do nothing */
4037 if (sym_find2(*nested_list
, t
))
4039 saved_macro_ptr
= macro_ptr
;
4040 macro_ptr
= (int *)ptr
;
4042 ret
= macro_subst_tok(tok_str
, nested_list
, s
);
4043 ptr
= (int *)macro_ptr
;
4044 macro_ptr
= saved_macro_ptr
;
4049 tok_str_add2(tok_str
, t
, &cval
);
4053 tok_str_free(macro_str1
);
4056 /* return next token with macro substitution */
4057 static void next(void)
4059 Sym
*nested_list
, *s
;
4065 /* if not reading from macro substituted string, then try
4066 to substitute macros */
4067 if (tok
>= TOK_IDENT
&&
4068 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4069 s
= define_find(tok
);
4071 /* we have a macro: we try to substitute */
4074 if (macro_subst_tok(&str
, &nested_list
, s
) == 0) {
4075 /* substitution done, NOTE: maybe empty */
4076 tok_str_add(&str
, 0);
4077 macro_ptr
= str
.str
;
4078 macro_ptr_allocated
= str
.str
;
4085 /* end of macro or end of unget buffer */
4086 if (unget_buffer_enabled
) {
4087 macro_ptr
= unget_saved_macro_ptr
;
4088 unget_buffer_enabled
= 0;
4090 /* end of macro string: free it */
4091 tok_str_free(macro_ptr_allocated
);
4098 /* convert preprocessor tokens into C tokens */
4099 if (tok
== TOK_PPNUM
&&
4100 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4101 parse_number((char *)tokc
.cstr
->data
);
4105 /* push back current token and set current token to 'last_tok'. Only
4106 identifier case handled for labels. */
4107 static inline void unget_tok(int last_tok
)
4111 unget_saved_macro_ptr
= macro_ptr
;
4112 unget_buffer_enabled
= 1;
4113 q
= unget_saved_buffer
;
4116 n
= tok_ext_size(tok
) - 1;
4119 *q
= 0; /* end of token string */
4124 void swap(int *p
, int *q
)
4132 void vsetc(CType
*type
, int r
, CValue
*vc
)
4136 if (vtop
>= vstack
+ VSTACK_SIZE
)
4137 error("memory full");
4138 /* cannot let cpu flags if other instruction are generated. Also
4139 avoid leaving VT_JMP anywhere except on the top of the stack
4140 because it would complicate the code generator. */
4141 if (vtop
>= vstack
) {
4142 v
= vtop
->r
& VT_VALMASK
;
4143 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4149 vtop
->r2
= VT_CONST
;
4153 /* push integer constant */
4158 vsetc(&int_type
, VT_CONST
, &cval
);
4161 /* Return a static symbol pointing to a section */
4162 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4163 unsigned long offset
, unsigned long size
)
4169 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4170 sym
->type
.ref
= type
->ref
;
4171 sym
->r
= VT_CONST
| VT_SYM
;
4172 put_extern_sym(sym
, sec
, offset
, size
);
4176 /* push a reference to a section offset by adding a dummy symbol */
4177 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4182 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4183 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4186 /* define a new external reference to a symbol 'v' of type 'u' */
4187 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4193 /* push forward reference */
4194 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4195 s
->type
.ref
= type
->ref
;
4196 s
->r
= r
| VT_CONST
| VT_SYM
;
4201 /* define a new external reference to a symbol 'v' of type 'u' */
4202 static Sym
*external_sym(int v
, CType
*type
, int r
)
4208 /* push forward reference */
4209 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4210 s
->type
.t
|= VT_EXTERN
;
4212 if (!is_compatible_types(&s
->type
, type
))
4213 error("incompatible types for redefinition of '%s'",
4214 get_tok_str(v
, NULL
));
4219 /* push a reference to global symbol v */
4220 static void vpush_global_sym(CType
*type
, int v
)
4225 sym
= external_global_sym(v
, type
, 0);
4227 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4231 void vset(CType
*type
, int r
, int v
)
4236 vsetc(type
, r
, &cval
);
4239 void vseti(int r
, int v
)
4255 void vpushv(SValue
*v
)
4257 if (vtop
>= vstack
+ VSTACK_SIZE
)
4258 error("memory full");
4268 /* save r to the memory stack, and mark it as being free */
4269 void save_reg(int r
)
4271 int l
, saved
, size
, align
;
4275 /* modify all stack values */
4278 for(p
=vstack
;p
<=vtop
;p
++) {
4279 if ((p
->r
& VT_VALMASK
) == r
||
4280 (p
->r2
& VT_VALMASK
) == r
) {
4281 /* must save value on stack if not already done */
4283 /* NOTE: must reload 'r' because r might be equal to r2 */
4284 r
= p
->r
& VT_VALMASK
;
4285 /* store register in the stack */
4287 if ((p
->r
& VT_LVAL
) ||
4288 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4290 size
= type_size(type
, &align
);
4291 loc
= (loc
- size
) & -align
;
4292 sv
.type
.t
= type
->t
;
4293 sv
.r
= VT_LOCAL
| VT_LVAL
;
4296 #ifdef TCC_TARGET_I386
4297 /* x86 specific: need to pop fp register ST0 if saved */
4298 if (r
== TREG_ST0
) {
4299 o(0xd9dd); /* fstp %st(1) */
4302 /* special long long case */
4303 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4310 /* mark that stack entry as being saved on the stack */
4311 if (p
->r
& VT_LVAL
) {
4312 /* also clear the bounded flag because the
4313 relocation address of the function was stored in
4315 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4317 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4325 /* find a free register of class 'rc'. If none, save one register */
4331 /* find a free register */
4332 for(r
=0;r
<NB_REGS
;r
++) {
4333 if (reg_classes
[r
] & rc
) {
4334 for(p
=vstack
;p
<=vtop
;p
++) {
4335 if ((p
->r
& VT_VALMASK
) == r
||
4336 (p
->r2
& VT_VALMASK
) == r
)
4344 /* no register left : free the first one on the stack (VERY
4345 IMPORTANT to start from the bottom to ensure that we don't
4346 spill registers used in gen_opi()) */
4347 for(p
=vstack
;p
<=vtop
;p
++) {
4348 r
= p
->r
& VT_VALMASK
;
4349 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4351 /* also look at second register (if long long) */
4352 r
= p
->r2
& VT_VALMASK
;
4353 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4359 /* Should never comes here */
4363 /* save registers up to (vtop - n) stack entry */
4364 void save_regs(int n
)
4369 for(p
= vstack
;p
<= p1
; p
++) {
4370 r
= p
->r
& VT_VALMASK
;
4377 /* move register 's' to 'r', and flush previous value of r to memory
4379 void move_reg(int r
, int s
)
4392 /* get address of vtop (vtop MUST BE an lvalue) */
4395 vtop
->r
&= ~VT_LVAL
;
4396 /* tricky: if saved lvalue, then we can go back to lvalue */
4397 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4398 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4401 #ifdef CONFIG_TCC_BCHECK
4402 /* generate lvalue bound code */
4408 vtop
->r
&= ~VT_MUSTBOUND
;
4409 /* if lvalue, then use checking code before dereferencing */
4410 if (vtop
->r
& VT_LVAL
) {
4411 /* if not VT_BOUNDED value, then make one */
4412 if (!(vtop
->r
& VT_BOUNDED
)) {
4413 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4414 /* must save type because we must set it to int to get pointer */
4416 vtop
->type
.t
= VT_INT
;
4419 gen_bounded_ptr_add();
4420 vtop
->r
|= lval_type
;
4423 /* then check for dereferencing */
4424 gen_bounded_ptr_deref();
4429 /* store vtop a register belonging to class 'rc'. lvalues are
4430 converted to values. Cannot be used if cannot be converted to
4431 register value (such as structures). */
4434 int r
, r2
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4435 unsigned long long ll
;
4437 /* NOTE: get_reg can modify vstack[] */
4438 if (vtop
->type
.t
& VT_BITFIELD
) {
4439 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4440 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4441 /* remove bit field info to avoid loops */
4442 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4443 /* generate shifts */
4444 vpushi(32 - (bit_pos
+ bit_size
));
4446 vpushi(32 - bit_size
);
4447 /* NOTE: transformed to SHR if unsigned */
4451 if (is_float(vtop
->type
.t
) &&
4452 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4455 unsigned long offset
;
4457 /* XXX: unify with initializers handling ? */
4458 /* CPUs usually cannot use float constants, so we store them
4459 generically in data segment */
4460 size
= type_size(&vtop
->type
, &align
);
4461 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
4462 data_section
->data_offset
= offset
;
4463 /* XXX: not portable yet */
4464 ptr
= section_ptr_add(data_section
, size
);
4467 ptr
[i
] = vtop
->c
.tab
[i
];
4468 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
4469 vtop
->r
|= VT_LVAL
| VT_SYM
;
4473 #ifdef CONFIG_TCC_BCHECK
4474 if (vtop
->r
& VT_MUSTBOUND
)
4478 r
= vtop
->r
& VT_VALMASK
;
4479 /* need to reload if:
4481 - lvalue (need to dereference pointer)
4482 - already a register, but not in the right class */
4483 if (r
>= VT_CONST
||
4484 (vtop
->r
& VT_LVAL
) ||
4485 !(reg_classes
[r
] & rc
) ||
4486 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
4487 !(reg_classes
[vtop
->r2
] & rc
))) {
4489 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
4490 /* two register type load : expand to two words
4492 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4495 vtop
->c
.ui
= ll
; /* first word */
4497 vtop
->r
= r
; /* save register value */
4498 vpushi(ll
>> 32); /* second word */
4499 } else if (r
>= VT_CONST
||
4500 (vtop
->r
& VT_LVAL
)) {
4501 /* load from memory */
4504 vtop
[-1].r
= r
; /* save register value */
4505 /* increment pointer to get second word */
4506 vtop
->type
.t
= VT_INT
;
4512 /* move registers */
4515 vtop
[-1].r
= r
; /* save register value */
4516 vtop
->r
= vtop
[-1].r2
;
4518 /* allocate second register */
4525 /* write second register */
4527 } else if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
4529 /* lvalue of scalar type : need to use lvalue type
4530 because of possible cast */
4533 /* compute memory access type */
4534 if (vtop
->r
& VT_LVAL_BYTE
)
4536 else if (vtop
->r
& VT_LVAL_SHORT
)
4538 if (vtop
->r
& VT_LVAL_UNSIGNED
)
4542 /* restore wanted type */
4545 /* one register type load */
4554 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
4555 void gv2(int rc1
, int rc2
)
4559 /* generate more generic register first. But VT_JMP or VT_CMP
4560 values must be generated first in all cases to avoid possible
4562 v
= vtop
[0].r
& VT_VALMASK
;
4563 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
4568 /* test if reload is needed for first register */
4569 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
4579 /* test if reload is needed for first register */
4580 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
4586 /* expand long long on stack in two int registers */
4591 u
= vtop
->type
.t
& VT_UNSIGNED
;
4594 vtop
[0].r
= vtop
[-1].r2
;
4595 vtop
[0].r2
= VT_CONST
;
4596 vtop
[-1].r2
= VT_CONST
;
4597 vtop
[0].type
.t
= VT_INT
| u
;
4598 vtop
[-1].type
.t
= VT_INT
| u
;
4601 /* build a long long from two ints */
4604 gv2(RC_INT
, RC_INT
);
4605 vtop
[-1].r2
= vtop
[0].r
;
4606 vtop
[-1].type
.t
= t
;
4610 /* rotate n first stack elements to the bottom
4611 I1 ... In -> I2 ... In I1 [top is right]
4619 for(i
=-n
+1;i
!=0;i
++)
4620 vtop
[i
] = vtop
[i
+1];
4624 /* rotate n first stack elements to the top
4625 I1 ... In -> In I1 ... I(n-1) [top is right]
4633 for(i
= 0;i
< n
- 1; i
++)
4634 vtop
[-i
] = vtop
[-i
- 1];
4638 /* pop stack value */
4642 v
= vtop
->r
& VT_VALMASK
;
4643 #ifdef TCC_TARGET_I386
4644 /* for x86, we need to pop the FP stack */
4645 if (v
== TREG_ST0
&& !nocode_wanted
) {
4646 o(0xd9dd); /* fstp %st(1) */
4649 if (v
== VT_JMP
|| v
== VT_JMPI
) {
4650 /* need to put correct jump if && or || without test */
4656 /* convert stack entry to register and duplicate its value in another
4664 if ((t
& VT_BTYPE
) == VT_LLONG
) {
4671 /* stack: H L L1 H1 */
4679 /* duplicate value */
4690 load(r1
, &sv
); /* move r to r1 */
4692 /* duplicates value */
4697 /* generate CPU independent (unsigned) long long operations */
4698 void gen_opl(int op
)
4700 int t
, a
, b
, op1
, c
, i
;
4707 func
= TOK___divdi3
;
4710 func
= TOK___udivdi3
;
4713 func
= TOK___moddi3
;
4716 func
= TOK___umoddi3
;
4718 /* call generic long long function */
4719 vpush_global_sym(&func_old_type
, func
);
4724 vtop
->r2
= REG_LRET
;
4737 /* stack: L1 H1 L2 H2 */
4742 vtop
[-2] = vtop
[-3];
4745 /* stack: H1 H2 L1 L2 */
4751 /* stack: H1 H2 L1 L2 ML MH */
4754 /* stack: ML MH H1 H2 L1 L2 */
4758 /* stack: ML MH H1 L2 H2 L1 */
4763 /* stack: ML MH M1 M2 */
4766 } else if (op
== '+' || op
== '-') {
4767 /* XXX: add non carry method too (for MIPS or alpha) */
4773 /* stack: H1 H2 (L1 op L2) */
4776 gen_op(op1
+ 1); /* TOK_xxxC2 */
4779 /* stack: H1 H2 (L1 op L2) */
4782 /* stack: (L1 op L2) H1 H2 */
4784 /* stack: (L1 op L2) (H1 op H2) */
4792 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
4793 t
= vtop
[-1].type
.t
;
4797 /* stack: L H shift */
4799 /* constant: simpler */
4800 /* NOTE: all comments are for SHL. the other cases are
4801 done by swaping words */
4812 if (op
!= TOK_SAR
) {
4845 /* XXX: should provide a faster fallback on x86 ? */
4848 func
= TOK___sardi3
;
4851 func
= TOK___shrdi3
;
4854 func
= TOK___shldi3
;
4860 /* compare operations */
4866 /* stack: L1 H1 L2 H2 */
4868 vtop
[-1] = vtop
[-2];
4870 /* stack: L1 L2 H1 H2 */
4873 /* when values are equal, we need to compare low words. since
4874 the jump is inverted, we invert the test too. */
4877 else if (op1
== TOK_GT
)
4879 else if (op1
== TOK_ULT
)
4881 else if (op1
== TOK_UGT
)
4886 if (op1
!= TOK_NE
) {
4890 /* generate non equal test */
4891 /* XXX: NOT PORTABLE yet */
4895 #ifdef TCC_TARGET_I386
4896 b
= psym(0x850f, 0);
4898 error("not implemented");
4902 /* compare low. Always unsigned */
4906 else if (op1
== TOK_LE
)
4908 else if (op1
== TOK_GT
)
4910 else if (op1
== TOK_GE
)
4920 /* handle integer constant optimizations and various machine
4922 void gen_opic(int op
)
4929 /* currently, we cannot do computations with forward symbols */
4930 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4931 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4935 case '+': v1
->c
.i
+= fc
; break;
4936 case '-': v1
->c
.i
-= fc
; break;
4937 case '&': v1
->c
.i
&= fc
; break;
4938 case '^': v1
->c
.i
^= fc
; break;
4939 case '|': v1
->c
.i
|= fc
; break;
4940 case '*': v1
->c
.i
*= fc
; break;
4947 /* if division by zero, generate explicit division */
4950 error("division by zero in constant");
4954 default: v1
->c
.i
/= fc
; break;
4955 case '%': v1
->c
.i
%= fc
; break;
4956 case TOK_UDIV
: v1
->c
.i
= (unsigned)v1
->c
.i
/ fc
; break;
4957 case TOK_UMOD
: v1
->c
.i
= (unsigned)v1
->c
.i
% fc
; break;
4960 case TOK_SHL
: v1
->c
.i
<<= fc
; break;
4961 case TOK_SHR
: v1
->c
.i
= (unsigned)v1
->c
.i
>> fc
; break;
4962 case TOK_SAR
: v1
->c
.i
>>= fc
; break;
4964 case TOK_ULT
: v1
->c
.i
= (unsigned)v1
->c
.i
< (unsigned)fc
; break;
4965 case TOK_UGE
: v1
->c
.i
= (unsigned)v1
->c
.i
>= (unsigned)fc
; break;
4966 case TOK_EQ
: v1
->c
.i
= v1
->c
.i
== fc
; break;
4967 case TOK_NE
: v1
->c
.i
= v1
->c
.i
!= fc
; break;
4968 case TOK_ULE
: v1
->c
.i
= (unsigned)v1
->c
.i
<= (unsigned)fc
; break;
4969 case TOK_UGT
: v1
->c
.i
= (unsigned)v1
->c
.i
> (unsigned)fc
; break;
4970 case TOK_LT
: v1
->c
.i
= v1
->c
.i
< fc
; break;
4971 case TOK_GE
: v1
->c
.i
= v1
->c
.i
>= fc
; break;
4972 case TOK_LE
: v1
->c
.i
= v1
->c
.i
<= fc
; break;
4973 case TOK_GT
: v1
->c
.i
= v1
->c
.i
> fc
; break;
4975 case TOK_LAND
: v1
->c
.i
= v1
->c
.i
&& fc
; break;
4976 case TOK_LOR
: v1
->c
.i
= v1
->c
.i
|| fc
; break;
4982 /* if commutative ops, put c2 as constant */
4983 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
4984 op
== '|' || op
== '*')) {
4989 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
4992 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
4993 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
4999 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
5000 /* try to use shifts instead of muls or divs */
5001 if (fc
> 0 && (fc
& (fc
- 1)) == 0) {
5010 else if (op
== TOK_PDIV
)
5016 } else if (c2
&& (op
== '+' || op
== '-') &&
5017 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5018 (VT_CONST
| VT_SYM
)) {
5019 /* symbol + constant case */
5026 if (!nocode_wanted
) {
5027 /* call low level op generator */
5036 /* generate a floating point operation with constant propagation */
5037 void gen_opif(int op
)
5045 /* currently, we cannot do computations with forward symbols */
5046 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5047 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5049 if (v1
->type
.t
== VT_FLOAT
) {
5052 } else if (v1
->type
.t
== VT_DOUBLE
) {
5060 /* NOTE: we only do constant propagation if finite number (not
5061 NaN or infinity) (ANSI spec) */
5062 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5066 case '+': f1
+= f2
; break;
5067 case '-': f1
-= f2
; break;
5068 case '*': f1
*= f2
; break;
5072 error("division by zero in constant");
5077 /* XXX: also handles tests ? */
5081 /* XXX: overflow test ? */
5082 if (v1
->type
.t
== VT_FLOAT
) {
5084 } else if (v1
->type
.t
== VT_DOUBLE
) {
5092 if (!nocode_wanted
) {
5100 static int pointed_size(CType
*type
)
5103 return type_size(pointed_type(type
), &align
);
5106 static inline int is_null_pointer(SValue
*p
)
5108 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5110 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5111 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5114 static inline int is_integer_btype(int bt
)
5116 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5117 bt
== VT_INT
|| bt
== VT_LLONG
);
5120 /* check types for comparison or substraction of pointers */
5121 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5123 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5126 /* null pointers are accepted for all comparisons as gcc */
5127 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5131 bt1
= type1
->t
& VT_BTYPE
;
5132 bt2
= type2
->t
& VT_BTYPE
;
5133 /* accept comparison between pointer and integer with a warning */
5134 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5135 warning("comparison between pointer and integer");
5139 /* both must be pointers or implicit function pointers */
5140 if (bt1
== VT_PTR
) {
5141 type1
= pointed_type(type1
);
5142 } else if (bt1
!= VT_FUNC
)
5143 goto invalid_operands
;
5145 if (bt2
== VT_PTR
) {
5146 type2
= pointed_type(type2
);
5147 } else if (bt2
!= VT_FUNC
) {
5149 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5151 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5152 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5156 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5157 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5158 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5159 /* gcc-like error if '-' is used */
5161 goto invalid_operands
;
5163 warning("comparison of distinct pointer types lacks a cast");
5167 /* generic gen_op: handles types problems */
5170 int u
, t1
, t2
, bt1
, bt2
, t
;
5173 t1
= vtop
[-1].type
.t
;
5174 t2
= vtop
[0].type
.t
;
5175 bt1
= t1
& VT_BTYPE
;
5176 bt2
= t2
& VT_BTYPE
;
5178 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5179 /* at least one operand is a pointer */
5180 /* relationnal op: must be both pointers */
5181 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5182 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5183 /* pointers are handled are unsigned */
5184 t
= VT_INT
| VT_UNSIGNED
;
5187 /* if both pointers, then it must be the '-' op */
5188 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5190 error("cannot use pointers here");
5191 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5192 /* XXX: check that types are compatible */
5193 u
= pointed_size(&vtop
[-1].type
);
5195 /* set to integer type */
5196 vtop
->type
.t
= VT_INT
;
5200 /* exactly one pointer : must be '+' or '-'. */
5201 if (op
!= '-' && op
!= '+')
5202 error("cannot use pointers here");
5203 /* Put pointer as first operand */
5204 if (bt2
== VT_PTR
) {
5208 type1
= vtop
[-1].type
;
5209 /* XXX: cast to int ? (long long case) */
5210 vpushi(pointed_size(&vtop
[-1].type
));
5212 #ifdef CONFIG_TCC_BCHECK
5213 /* if evaluating constant expression, no code should be
5214 generated, so no bound check */
5215 if (do_bounds_check
&& !const_wanted
) {
5216 /* if bounded pointers, we generate a special code to
5223 gen_bounded_ptr_add();
5229 /* put again type if gen_opic() swaped operands */
5232 } else if (is_float(bt1
) || is_float(bt2
)) {
5233 /* compute bigger type and do implicit casts */
5234 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5236 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5241 /* floats can only be used for a few operations */
5242 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5243 (op
< TOK_ULT
|| op
> TOK_GT
))
5244 error("invalid operands for binary operation");
5246 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5247 /* cast to biggest op */
5249 /* convert to unsigned if it does not fit in a long long */
5250 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5251 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5255 /* integer operations */
5257 /* convert to unsigned if it does not fit in an integer */
5258 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5259 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5262 /* XXX: currently, some unsigned operations are explicit, so
5263 we modify them here */
5264 if (t
& VT_UNSIGNED
) {
5271 else if (op
== TOK_LT
)
5273 else if (op
== TOK_GT
)
5275 else if (op
== TOK_LE
)
5277 else if (op
== TOK_GE
)
5284 /* special case for shifts and long long: we keep the shift as
5286 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5291 else if ((t
& VT_BTYPE
) == VT_LLONG
)
5295 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5296 /* relationnal op: the result is an int */
5297 vtop
->type
.t
= VT_INT
;
5304 /* generic itof for unsigned long long case */
5305 void gen_cvt_itof1(int t
)
5307 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
5308 (VT_LLONG
| VT_UNSIGNED
)) {
5311 vpush_global_sym(&func_old_type
, TOK___ulltof
);
5312 else if (t
== VT_DOUBLE
)
5313 vpush_global_sym(&func_old_type
, TOK___ulltod
);
5315 vpush_global_sym(&func_old_type
, TOK___ulltold
);
5325 /* generic ftoi for unsigned long long case */
5326 void gen_cvt_ftoi1(int t
)
5330 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
5331 /* not handled natively */
5332 st
= vtop
->type
.t
& VT_BTYPE
;
5334 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
5335 else if (st
== VT_DOUBLE
)
5336 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
5338 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
5343 vtop
->r2
= REG_LRET
;
5349 /* force char or short cast */
5350 void force_charshort_cast(int t
)
5354 /* XXX: add optimization if lvalue : just change type and offset */
5359 if (t
& VT_UNSIGNED
) {
5360 vpushi((1 << bits
) - 1);
5371 /* cast 'vtop' to 'type' */
5372 static void gen_cast(CType
*type
)
5374 int sbt
, dbt
, sf
, df
, c
;
5376 /* special delayed cast for char/short */
5377 /* XXX: in some cases (multiple cascaded casts), it may still
5379 if (vtop
->r
& VT_MUSTCAST
) {
5380 vtop
->r
&= ~VT_MUSTCAST
;
5381 force_charshort_cast(vtop
->type
.t
);
5384 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
5385 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
5387 if (sbt
!= dbt
&& !nocode_wanted
) {
5390 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5392 /* convert from fp to fp */
5394 /* constant case: we can do it now */
5395 /* XXX: in ISOC, cannot do it if error in convert */
5396 if (dbt
== VT_FLOAT
&& sbt
== VT_DOUBLE
)
5397 vtop
->c
.f
= (float)vtop
->c
.d
;
5398 else if (dbt
== VT_FLOAT
&& sbt
== VT_LDOUBLE
)
5399 vtop
->c
.f
= (float)vtop
->c
.ld
;
5400 else if (dbt
== VT_DOUBLE
&& sbt
== VT_FLOAT
)
5401 vtop
->c
.d
= (double)vtop
->c
.f
;
5402 else if (dbt
== VT_DOUBLE
&& sbt
== VT_LDOUBLE
)
5403 vtop
->c
.d
= (double)vtop
->c
.ld
;
5404 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_FLOAT
)
5405 vtop
->c
.ld
= (long double)vtop
->c
.f
;
5406 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_DOUBLE
)
5407 vtop
->c
.ld
= (long double)vtop
->c
.d
;
5409 /* non constant case: generate code */
5413 /* convert int to fp */
5416 case VT_LLONG
| VT_UNSIGNED
:
5418 /* XXX: add const cases for long long */
5420 case VT_INT
| VT_UNSIGNED
:
5422 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.ui
; break;
5423 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.ui
; break;
5424 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.ui
; break;
5429 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.i
; break;
5430 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.i
; break;
5431 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.i
; break;
5440 /* convert fp to int */
5441 /* we handle char/short/etc... with generic code */
5442 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
5443 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
5448 case VT_LLONG
| VT_UNSIGNED
:
5450 /* XXX: add const cases for long long */
5452 case VT_INT
| VT_UNSIGNED
:
5454 case VT_FLOAT
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5455 case VT_DOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5456 case VT_LDOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5462 case VT_FLOAT
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5463 case VT_DOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5464 case VT_LDOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5472 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
5473 /* additional cast for char/short/bool... */
5477 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
5478 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
5479 /* scalar to long long */
5481 if (sbt
== (VT_INT
| VT_UNSIGNED
))
5482 vtop
->c
.ll
= vtop
->c
.ui
;
5484 vtop
->c
.ll
= vtop
->c
.i
;
5486 /* machine independent conversion */
5488 /* generate high word */
5489 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
5497 /* patch second register */
5498 vtop
[-1].r2
= vtop
->r
;
5502 } else if (dbt
== VT_BOOL
) {
5503 /* scalar to bool */
5506 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
5507 (dbt
& VT_BTYPE
) == VT_SHORT
) {
5508 force_charshort_cast(dbt
);
5509 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
5511 if (sbt
== VT_LLONG
) {
5512 /* from long long: just take low order word */
5516 /* if lvalue and single word type, nothing to do because
5517 the lvalue already contains the real type size (see
5518 VT_LVAL_xxx constants) */
5524 /* return type size. Put alignment at 'a' */
5525 static int type_size(CType
*type
, int *a
)
5530 bt
= type
->t
& VT_BTYPE
;
5531 if (bt
== VT_STRUCT
) {
5536 } else if (bt
== VT_PTR
) {
5537 if (type
->t
& VT_ARRAY
) {
5539 return type_size(&s
->type
, a
) * s
->c
;
5544 } else if (bt
== VT_LDOUBLE
) {
5546 return LDOUBLE_SIZE
;
5547 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
5548 *a
= 4; /* XXX: i386 specific */
5550 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
5553 } else if (bt
== VT_SHORT
) {
5557 /* char, void, function, _Bool */
5563 /* return the pointed type of t */
5564 static inline CType
*pointed_type(CType
*type
)
5566 return &type
->ref
->type
;
5569 /* modify type so that its it is a pointer to type. */
5570 static void mk_pointer(CType
*type
)
5573 s
= sym_push(SYM_FIELD
, type
, 0, -1);
5574 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
5578 /* compare function types. OLD functions match any new functions */
5579 static int is_compatible_func(CType
*type1
, CType
*type2
)
5585 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5587 /* XXX: not complete */
5588 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
5592 while (s1
!= NULL
) {
5595 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5605 /* return true if type1 and type2 are exactly the same (including
5608 - enums are not checked as gcc __builtin_types_compatible_p ()
5610 static int is_compatible_types(CType
*type1
, CType
*type2
)
5614 t1
= type1
->t
& VT_TYPE
;
5615 t2
= type2
->t
& VT_TYPE
;
5616 /* XXX: bitfields ? */
5619 /* test more complicated cases */
5620 bt1
= t1
& VT_BTYPE
;
5621 if (bt1
== VT_PTR
) {
5622 type1
= pointed_type(type1
);
5623 type2
= pointed_type(type2
);
5624 return is_compatible_types(type1
, type2
);
5625 } else if (bt1
== VT_STRUCT
) {
5626 return (type1
->ref
== type2
->ref
);
5627 } else if (bt1
== VT_FUNC
) {
5628 return is_compatible_func(type1
, type2
);
5634 /* print a type. If 'varstr' is not NULL, then the variable is also
5635 printed in the type */
5637 /* XXX: add array and function pointers */
5638 void type_to_str(char *buf
, int buf_size
,
5639 CType
*type
, const char *varstr
)
5646 t
= type
->t
& VT_TYPE
;
5649 if (t
& VT_CONSTANT
)
5650 pstrcat(buf
, buf_size
, "const ");
5651 if (t
& VT_VOLATILE
)
5652 pstrcat(buf
, buf_size
, "volatile ");
5653 if (t
& VT_UNSIGNED
)
5654 pstrcat(buf
, buf_size
, "unsigned ");
5684 tstr
= "long double";
5686 pstrcat(buf
, buf_size
, tstr
);
5690 if (bt
== VT_STRUCT
)
5694 pstrcat(buf
, buf_size
, tstr
);
5695 v
= type
->ref
->v
& ~SYM_STRUCT
;
5696 if (v
>= SYM_FIRST_ANOM
)
5697 pstrcat(buf
, buf_size
, "<anonymous>");
5699 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
5703 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
5704 pstrcat(buf
, buf_size
, "(");
5706 while (sa
!= NULL
) {
5707 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
5708 pstrcat(buf
, buf_size
, buf1
);
5711 pstrcat(buf
, buf_size
, ", ");
5713 pstrcat(buf
, buf_size
, ")");
5717 pstrcpy(buf1
, sizeof(buf1
), "*");
5719 pstrcat(buf1
, sizeof(buf1
), varstr
);
5720 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
5724 pstrcat(buf
, buf_size
, " ");
5725 pstrcat(buf
, buf_size
, varstr
);
5730 /* verify type compatibility to store vtop in 'dt' type, and generate
5732 static void gen_assign_cast(CType
*dt
)
5734 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
5735 char buf1
[256], buf2
[256];
5738 st
= &vtop
->type
; /* source type */
5739 dbt
= dt
->t
& VT_BTYPE
;
5740 sbt
= st
->t
& VT_BTYPE
;
5741 if (dt
->t
& VT_CONSTANT
)
5742 warning("assignment of read-only location");
5745 /* special cases for pointers */
5746 /* '0' can also be a pointer */
5747 if (is_null_pointer(vtop
))
5749 /* accept implicit pointer to integer cast with warning */
5750 if (is_integer_btype(sbt
)) {
5751 warning("assignment makes pointer from integer without a cast");
5754 type1
= pointed_type(dt
);
5755 /* a function is implicitely a function pointer */
5756 if (sbt
== VT_FUNC
) {
5757 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
5758 !is_compatible_types(pointed_type(dt
), st
))
5765 type2
= pointed_type(st
);
5766 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5767 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
5768 /* void * can match anything */
5770 /* exact type match, except for unsigned */
5773 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5774 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5775 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
5778 /* check const and volatile */
5779 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
5780 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
5781 warning("assignment discards qualifiers from pointer target type");
5787 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
5788 warning("assignment makes integer from pointer without a cast");
5790 /* XXX: more tests */
5793 if (!is_compatible_types(dt
, st
)) {
5795 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
5796 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
5797 error("cannot cast '%s' to '%s'", buf1
, buf2
);
5805 /* store vtop in lvalue pushed on stack */
5808 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
5810 ft
= vtop
[-1].type
.t
;
5811 sbt
= vtop
->type
.t
& VT_BTYPE
;
5812 dbt
= ft
& VT_BTYPE
;
5813 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
5814 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
5815 /* optimize char/short casts */
5816 delayed_cast
= VT_MUSTCAST
;
5817 vtop
->type
.t
= ft
& VT_TYPE
;
5818 /* XXX: factorize */
5819 if (ft
& VT_CONSTANT
)
5820 warning("assignment of read-only location");
5823 gen_assign_cast(&vtop
[-1].type
);
5826 if (sbt
== VT_STRUCT
) {
5827 /* if structure, only generate pointer */
5828 /* structure assignment : generate memcpy */
5829 /* XXX: optimize if small size */
5830 if (!nocode_wanted
) {
5831 size
= type_size(&vtop
->type
, &align
);
5833 vpush_global_sym(&func_old_type
, TOK_memcpy
);
5837 vtop
->type
.t
= VT_INT
;
5841 vtop
->type
.t
= VT_INT
;
5853 /* leave source on stack */
5854 } else if (ft
& VT_BITFIELD
) {
5855 /* bitfield store handling */
5856 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
5857 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
5858 /* remove bit field info to avoid loops */
5859 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
5861 /* duplicate destination */
5863 vtop
[-1] = vtop
[-2];
5865 /* mask and shift source */
5866 vpushi((1 << bit_size
) - 1);
5870 /* load destination, mask and or with source */
5872 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
5878 #ifdef CONFIG_TCC_BCHECK
5879 /* bound check case */
5880 if (vtop
[-1].r
& VT_MUSTBOUND
) {
5886 if (!nocode_wanted
) {
5890 r
= gv(rc
); /* generate value */
5891 /* if lvalue was saved on stack, must read it */
5892 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
5894 t
= get_reg(RC_INT
);
5896 sv
.r
= VT_LOCAL
| VT_LVAL
;
5897 sv
.c
.ul
= vtop
[-1].c
.ul
;
5899 vtop
[-1].r
= t
| VT_LVAL
;
5902 /* two word case handling : store second register at word + 4 */
5903 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
5905 /* convert to int to increment easily */
5906 vtop
->type
.t
= VT_INT
;
5912 /* XXX: it works because r2 is spilled last ! */
5913 store(vtop
->r2
, vtop
- 1);
5917 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
5918 vtop
->r
|= delayed_cast
;
5922 /* post defines POST/PRE add. c is the token ++ or -- */
5923 void inc(int post
, int c
)
5926 vdup(); /* save lvalue */
5928 gv_dup(); /* duplicate value */
5933 vpushi(c
- TOK_MID
);
5935 vstore(); /* store value */
5937 vpop(); /* if post op, return saved value */
5940 /* Parse GNUC __attribute__ extension. Currently, the following
5941 extensions are recognized:
5942 - aligned(n) : set data/function alignment.
5943 - section(x) : generate data/code in this section.
5944 - unused : currently ignored, but may be used someday.
5946 static void parse_attribute(AttributeDef
*ad
)
5950 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
5954 while (tok
!= ')') {
5955 if (tok
< TOK_IDENT
)
5956 expect("attribute name");
5964 expect("section name");
5965 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
5974 if (n
<= 0 || (n
& (n
- 1)) != 0)
5975 error("alignment must be a positive power of two");
5984 /* currently, no need to handle it because tcc does not
5985 track unused objects */
5989 /* currently, no need to handle it because tcc does not
5990 track unused objects */
5995 ad
->func_call
= FUNC_CDECL
;
6000 ad
->func_call
= FUNC_STDCALL
;
6003 if (tcc_state
->warn_unsupported
)
6004 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6005 /* skip parameters */
6006 /* XXX: skip parenthesis too */
6009 while (tok
!= ')' && tok
!= -1)
6024 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6025 static void struct_decl(CType
*type
, int u
)
6027 int a
, v
, size
, align
, maxalign
, c
, offset
;
6028 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
;
6033 a
= tok
; /* save decl type */
6038 /* struct already defined ? return it */
6040 expect("struct/union/enum name");
6044 error("invalid type");
6051 /* we put an undefined size for struct/union */
6052 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6053 s
->r
= 0; /* default alignment is zero as gcc */
6054 /* put struct/union/enum name in type */
6062 error("struct/union/enum already defined");
6063 /* cannot be empty */
6065 /* non empty enums are not allowed */
6066 if (a
== TOK_ENUM
) {
6070 expect("identifier");
6076 /* enum symbols have static storage */
6077 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6078 ss
->type
.t
|= VT_STATIC
;
6083 /* NOTE: we accept a trailing comma */
6093 while (tok
!= '}') {
6094 parse_btype(&btype
, &ad
);
6100 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
);
6101 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6102 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6103 error("invalid type for '%s'",
6104 get_tok_str(v
, NULL
));
6108 bit_size
= expr_const();
6109 /* XXX: handle v = 0 case for messages */
6111 error("negative width in bit-field '%s'",
6112 get_tok_str(v
, NULL
));
6113 if (v
&& bit_size
== 0)
6114 error("zero width for bit-field '%s'",
6115 get_tok_str(v
, NULL
));
6117 size
= type_size(&type1
, &align
);
6119 if (bit_size
>= 0) {
6120 bt
= type1
.t
& VT_BTYPE
;
6125 error("bitfields must have scalar type");
6127 if (bit_size
> bsize
) {
6128 error("width of '%s' exceeds its type",
6129 get_tok_str(v
, NULL
));
6130 } else if (bit_size
== bsize
) {
6131 /* no need for bit fields */
6133 } else if (bit_size
== 0) {
6134 /* XXX: what to do if only padding in a
6136 /* zero size: means to pad */
6140 /* we do not have enough room ? */
6141 if ((bit_pos
+ bit_size
) > bsize
)
6144 /* XXX: handle LSB first */
6145 type1
.t
|= VT_BITFIELD
|
6146 (bit_pos
<< VT_STRUCT_SHIFT
) |
6147 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
6148 bit_pos
+= bit_size
;
6154 /* add new memory data only if starting
6156 if (lbit_pos
== 0) {
6157 if (a
== TOK_STRUCT
) {
6158 c
= (c
+ align
- 1) & -align
;
6166 if (align
> maxalign
)
6170 printf("add field %s offset=%d",
6171 get_tok_str(v
, NULL
), offset
);
6172 if (type1
.t
& VT_BITFIELD
) {
6173 printf(" pos=%d size=%d",
6174 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
6175 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
6179 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
6183 if (tok
== ';' || tok
== TOK_EOF
)
6190 /* store size and alignment */
6191 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
6197 /* return 0 if no type declaration. otherwise, return the basic type
6200 static int parse_btype(CType
*type
, AttributeDef
*ad
)
6202 int t
, u
, type_found
;
6206 memset(ad
, 0, sizeof(AttributeDef
));
6212 /* currently, we really ignore extension */
6222 if ((t
& VT_BTYPE
) != 0)
6223 error("too many basic types");
6237 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
6238 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6239 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
6240 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
6254 if ((t
& VT_BTYPE
) == VT_LONG
) {
6255 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6262 struct_decl(&type1
, VT_ENUM
);
6265 type
->ref
= type1
.ref
;
6269 struct_decl(&type1
, VT_STRUCT
);
6272 /* type modifiers */
6320 /* GNUC attribute */
6321 case TOK_ATTRIBUTE1
:
6322 case TOK_ATTRIBUTE2
:
6323 parse_attribute(ad
);
6330 parse_expr_type(&type1
);
6334 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
6336 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
6337 type
->ref
= s
->type
.ref
;
6344 /* long is never used as type */
6345 if ((t
& VT_BTYPE
) == VT_LONG
)
6346 t
= (t
& ~VT_BTYPE
) | VT_INT
;
6351 /* convert a function parameter type (array to pointer and function to
6352 function pointer) */
6353 static inline void convert_parameter_type(CType
*pt
)
6355 /* array must be transformed to pointer according to ANSI C */
6357 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
6362 static void post_type(CType
*type
, AttributeDef
*ad
)
6365 Sym
**plast
, *s
, *first
;
6370 /* function declaration */
6375 while (tok
!= ')') {
6376 /* read param name and compute offset */
6377 if (l
!= FUNC_OLD
) {
6378 if (!parse_btype(&pt
, &ad1
)) {
6380 error("invalid type");
6387 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
6389 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6390 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
6391 error("parameter declared as void");
6398 convert_parameter_type(&pt
);
6399 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
6404 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
6411 /* if no parameters, then old type prototype */
6415 t1
= type
->t
& VT_STORAGE
;
6416 /* NOTE: const is ignored in returned type as it has a special
6417 meaning in gcc / C++ */
6418 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
6419 post_type(type
, ad
);
6420 /* we push a anonymous symbol which will contain the function prototype */
6421 s
= sym_push(SYM_FIELD
, type
, ad
->func_call
, l
);
6423 type
->t
= t1
| VT_FUNC
;
6425 } else if (tok
== '[') {
6426 /* array definition */
6432 error("invalid array size");
6435 /* parse next post type */
6436 t1
= type
->t
& VT_STORAGE
;
6437 type
->t
&= ~VT_STORAGE
;
6438 post_type(type
, ad
);
6440 /* we push a anonymous symbol which will contain the array
6442 s
= sym_push(SYM_FIELD
, type
, 0, n
);
6443 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
6448 /* Parse a type declaration (except basic type), and return the type
6449 in 'type'. 'td' is a bitmask indicating which kind of type decl is
6450 expected. 'type' should contain the basic type. 'ad' is the
6451 attribute definition of the basic type. It can be modified by
6454 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
6457 CType type1
, *type2
;
6460 while (tok
== '*') {
6468 qualifiers
|= VT_CONSTANT
;
6473 qualifiers
|= VT_VOLATILE
;
6481 type
->t
|= qualifiers
;
6484 /* XXX: clarify attribute handling */
6485 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6486 parse_attribute(ad
);
6488 /* recursive type */
6489 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
6490 type1
.t
= 0; /* XXX: same as int */
6493 /* XXX: this is not correct to modify 'ad' at this point, but
6494 the syntax is not clear */
6495 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6496 parse_attribute(ad
);
6497 type_decl(&type1
, ad
, v
, td
);
6500 /* type identifier */
6501 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
6505 if (!(td
& TYPE_ABSTRACT
))
6506 expect("identifier");
6510 post_type(type
, ad
);
6511 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6512 parse_attribute(ad
);
6515 /* append type at the end of type1 */
6528 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
6529 static int lvalue_type(int t
)
6534 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
6536 else if (bt
== VT_SHORT
)
6540 if (t
& VT_UNSIGNED
)
6541 r
|= VT_LVAL_UNSIGNED
;
6545 /* indirection with full error checking and bound check */
6546 static void indir(void)
6548 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
6550 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
6552 vtop
->type
= *pointed_type(&vtop
->type
);
6553 /* an array is never an lvalue */
6554 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6555 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6556 /* if bound checking, the referenced pointer must be checked */
6557 if (do_bounds_check
)
6558 vtop
->r
|= VT_MUSTBOUND
;
6562 /* pass a parameter to a function and do type checking and casting */
6563 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
6568 func_type
= func
->c
;
6569 if (func_type
== FUNC_OLD
||
6570 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
6571 /* default casting : only need to convert float to double */
6572 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
6576 } else if (arg
== NULL
) {
6577 error("too many arguments to function");
6579 gen_assign_cast(&arg
->type
);
6583 /* parse an expression of the form '(type)' or '(expr)' and return its
6585 static void parse_expr_type(CType
*type
)
6591 if (parse_btype(type
, &ad
)) {
6592 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6599 static void parse_type(CType
*type
)
6604 if (!parse_btype(type
, &ad
)) {
6607 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6610 static void vpush_tokc(int t
)
6614 vsetc(&type
, VT_CONST
, &tokc
);
6617 static void unary(void)
6619 int n
, t
, align
, size
, r
;
6624 /* XXX: GCC 2.95.3 does not generate a table although it should be
6638 vpush_tokc(VT_INT
| VT_UNSIGNED
);
6642 vpush_tokc(VT_LLONG
);
6646 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
6650 vpush_tokc(VT_FLOAT
);
6654 vpush_tokc(VT_DOUBLE
);
6658 vpush_tokc(VT_LDOUBLE
);
6661 case TOK___FUNCTION__
:
6663 goto tok_identifier
;
6669 /* special function name identifier */
6670 len
= strlen(funcname
) + 1;
6671 /* generate char[len] type */
6676 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
6677 ptr
= section_ptr_add(data_section
, len
);
6678 memcpy(ptr
, funcname
, len
);
6686 /* string parsing */
6689 if (tcc_state
->warn_write_strings
)
6694 memset(&ad
, 0, sizeof(AttributeDef
));
6695 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
6700 if (parse_btype(&type
, &ad
)) {
6701 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
6703 /* check ISOC99 compound literal */
6705 /* data is allocated locally by default */
6710 /* all except arrays are lvalues */
6711 if (!(type
.t
& VT_ARRAY
))
6712 r
|= lvalue_type(type
.t
);
6713 memset(&ad
, 0, sizeof(AttributeDef
));
6714 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
6719 } else if (tok
== '{') {
6720 /* save all registers */
6722 /* statement expression : we do not accept break/continue
6723 inside as GCC does */
6724 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
6739 /* functions names must be treated as function pointers,
6740 except for unary '&' and sizeof. Since we consider that
6741 functions are not lvalues, we only have to handle it
6742 there and in function calls. */
6743 /* arrays can also be used although they are not lvalues */
6744 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
6745 !(vtop
->type
.t
& VT_ARRAY
))
6747 mk_pointer(&vtop
->type
);
6753 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
)
6754 vtop
->c
.i
= !vtop
->c
.i
;
6755 else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
6756 vtop
->c
.i
= vtop
->c
.i
^ 1;
6758 vseti(VT_JMP
, gtst(1, 0));
6768 /* in order to force cast, we add zero */
6770 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
6771 error("pointer not accepted for unary plus");
6781 parse_expr_type(&type
);
6785 size
= type_size(&type
, &align
);
6786 if (t
== TOK_SIZEOF
) {
6788 error("sizeof applied to an incomplete type");
6795 case TOK_builtin_types_compatible_p
:
6804 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6805 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6806 vpushi(is_compatible_types(&type1
, &type2
));
6809 case TOK_builtin_constant_p
:
6811 int saved_nocode_wanted
, res
;
6814 saved_nocode_wanted
= nocode_wanted
;
6817 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
6819 nocode_wanted
= saved_nocode_wanted
;
6839 goto tok_identifier
;
6841 /* allow to take the address of a label */
6842 if (tok
< TOK_UIDENT
)
6843 expect("label identifier");
6844 s
= label_find(tok
);
6846 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
6848 if (s
->r
== LABEL_DECLARED
)
6849 s
->r
= LABEL_FORWARD
;
6852 s
->type
.t
= VT_VOID
;
6853 mk_pointer(&s
->type
);
6854 s
->type
.t
|= VT_STATIC
;
6856 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
6865 expect("identifier");
6869 error("'%s' undeclared", get_tok_str(t
, NULL
));
6870 /* for simple function calls, we tolerate undeclared
6871 external reference to int() function */
6872 s
= external_global_sym(t
, &func_old_type
, 0);
6874 vset(&s
->type
, s
->r
, s
->c
);
6875 /* if forward reference, we must point to s */
6876 if (vtop
->r
& VT_SYM
) {
6883 /* post operations */
6885 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
6888 } else if (tok
== '.' || tok
== TOK_ARROW
) {
6890 if (tok
== TOK_ARROW
)
6895 /* expect pointer on structure */
6896 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
6897 expect("struct or union");
6901 while ((s
= s
->next
) != NULL
) {
6906 error("field not found");
6907 /* add field offset to pointer */
6908 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
6911 /* change type to field type, and set to lvalue */
6912 vtop
->type
= s
->type
;
6913 /* an array is never an lvalue */
6914 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6915 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6916 /* if bound checking, the referenced pointer must be checked */
6917 if (do_bounds_check
)
6918 vtop
->r
|= VT_MUSTBOUND
;
6921 } else if (tok
== '[') {
6927 } else if (tok
== '(') {
6933 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
6934 /* pointer test (no array accepted) */
6935 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
6936 vtop
->type
= *pointed_type(&vtop
->type
);
6937 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
6941 expect("function pointer");
6944 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
6946 /* get return type */
6949 sa
= s
->next
; /* first parameter */
6951 /* compute first implicit argument if a structure is returned */
6952 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
6953 /* get some space for the returned structure */
6954 size
= type_size(&s
->type
, &align
);
6955 loc
= (loc
- size
) & -align
;
6957 ret
.r
= VT_LOCAL
| VT_LVAL
;
6958 /* pass it as 'int' to avoid structure arg passing
6960 vseti(VT_LOCAL
, loc
);
6966 /* return in register */
6967 if (is_float(ret
.type
.t
)) {
6970 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
6979 gfunc_param_typed(s
, sa
);
6989 error("too few arguments to function");
6991 if (!nocode_wanted
) {
6992 gfunc_call(nb_args
);
6994 vtop
-= (nb_args
+ 1);
6997 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
7005 static void uneq(void)
7011 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
7012 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
7013 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
7028 static void expr_prod(void)
7033 while (tok
== '*' || tok
== '/' || tok
== '%') {
7041 static void expr_sum(void)
7046 while (tok
== '+' || tok
== '-') {
7054 static void expr_shift(void)
7059 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
7067 static void expr_cmp(void)
7072 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
7073 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
7081 static void expr_cmpeq(void)
7086 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
7094 static void expr_and(void)
7097 while (tok
== '&') {
7104 static void expr_xor(void)
7107 while (tok
== '^') {
7114 static void expr_or(void)
7117 while (tok
== '|') {
7124 /* XXX: fix this mess */
7125 static void expr_land_const(void)
7128 while (tok
== TOK_LAND
) {
7135 /* XXX: fix this mess */
7136 static void expr_lor_const(void)
7139 while (tok
== TOK_LOR
) {
7146 /* only used if non constant */
7147 static void expr_land(void)
7152 if (tok
== TOK_LAND
) {
7156 if (tok
!= TOK_LAND
) {
7166 static void expr_lor(void)
7171 if (tok
== TOK_LOR
) {
7175 if (tok
!= TOK_LOR
) {
7185 /* XXX: better constant handling */
7186 static void expr_eq(void)
7188 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
7190 CType type
, type1
, type2
;
7199 if (tok
== ':' && gnu_ext
) {
7215 if (vtop
!= vstack
) {
7216 /* needed to avoid having different registers saved in
7218 if (is_float(vtop
->type
.t
))
7225 if (tok
== ':' && gnu_ext
) {
7233 sv
= *vtop
; /* save value to handle it later */
7234 vtop
--; /* no vpop so that FP stack is not flushed */
7242 bt1
= t1
& VT_BTYPE
;
7244 bt2
= t2
& VT_BTYPE
;
7245 /* cast operands to correct type according to ISOC rules */
7246 if (is_float(bt1
) || is_float(bt2
)) {
7247 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
7248 type
.t
= VT_LDOUBLE
;
7249 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
7254 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
7255 /* cast to biggest op */
7257 /* convert to unsigned if it does not fit in a long long */
7258 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
7259 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
7260 type
.t
|= VT_UNSIGNED
;
7261 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
7262 /* XXX: test pointer compatibility */
7264 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
7265 /* XXX: test structure compatibility */
7267 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
7268 /* NOTE: as an extension, we accept void on only one side */
7271 /* integer operations */
7273 /* convert to unsigned if it does not fit in an integer */
7274 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
7275 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
7276 type
.t
|= VT_UNSIGNED
;
7279 /* now we convert second operand */
7282 if (is_float(type
.t
)) {
7284 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
7285 /* for long longs, we use fixed registers to avoid having
7286 to handle a complicated move */
7291 /* this is horrible, but we must also convert first
7295 /* put again first value and cast it */
7306 static void gexpr(void)
7317 /* parse an expression and return its type without any side effect. */
7318 static void expr_type(CType
*type
)
7320 int saved_nocode_wanted
;
7322 saved_nocode_wanted
= nocode_wanted
;
7327 nocode_wanted
= saved_nocode_wanted
;
7330 /* parse a unary expression and return its type without any side
7332 static void unary_type(CType
*type
)
7344 /* parse a constant expression and return value in vtop. */
7345 static void expr_const1(void)
7354 /* parse an integer constant and return its value. */
7355 static int expr_const(void)
7359 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
7360 expect("constant expression");
7366 /* return the label token if current token is a label, otherwise
7368 static int is_label(void)
7372 /* fast test first */
7373 if (tok
< TOK_UIDENT
)
7375 /* no need to save tokc because tok is an identifier */
7382 unget_tok(last_tok
);
7387 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
7388 int case_reg
, int is_expr
)
7393 /* generate line number info */
7395 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
7396 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
7398 last_line_num
= file
->line_num
;
7402 /* default return value is (void) */
7404 vtop
->type
.t
= VT_VOID
;
7407 if (tok
== TOK_IF
) {
7414 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7416 if (c
== TOK_ELSE
) {
7420 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7421 gsym(d
); /* patch else jmp */
7424 } else if (tok
== TOK_WHILE
) {
7432 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7436 } else if (tok
== '{') {
7440 /* record local declaration stack position */
7442 llabel
= local_label_stack
;
7443 /* handle local labels declarations */
7444 if (tok
== TOK_LABEL
) {
7447 if (tok
< TOK_UIDENT
)
7448 expect("label identifier");
7449 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
7459 while (tok
!= '}') {
7464 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7467 /* pop locally defined labels */
7468 label_pop(&local_label_stack
, llabel
);
7469 /* pop locally defined symbols */
7470 sym_pop(&local_stack
, s
);
7472 } else if (tok
== TOK_RETURN
) {
7476 gen_assign_cast(&func_vt
);
7477 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
7479 /* if returning structure, must copy it to implicit
7480 first pointer arg location */
7483 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
7486 /* copy structure value to pointer */
7488 } else if (is_float(func_vt
.t
)) {
7493 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
7496 rsym
= gjmp(rsym
); /* jmp */
7497 } else if (tok
== TOK_BREAK
) {
7500 error("cannot break");
7501 *bsym
= gjmp(*bsym
);
7504 } else if (tok
== TOK_CONTINUE
) {
7507 error("cannot continue");
7508 *csym
= gjmp(*csym
);
7511 } else if (tok
== TOK_FOR
) {
7538 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7543 if (tok
== TOK_DO
) {
7548 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7559 if (tok
== TOK_SWITCH
) {
7563 /* XXX: other types than integer */
7564 case_reg
= gv(RC_INT
);
7568 b
= gjmp(0); /* jump to first case */
7570 block(&a
, csym
, &b
, &c
, case_reg
, 0);
7571 /* if no default, jmp after switch */
7579 if (tok
== TOK_CASE
) {
7586 if (gnu_ext
&& tok
== TOK_DOTS
) {
7590 warning("empty case range");
7592 /* since a case is like a label, we must skip it with a jmp */
7599 *case_sym
= gtst(1, 0);
7602 *case_sym
= gtst(1, 0);
7606 *case_sym
= gtst(1, *case_sym
);
7611 goto block_after_label
;
7613 if (tok
== TOK_DEFAULT
) {
7619 error("too many 'default'");
7622 goto block_after_label
;
7624 if (tok
== TOK_GOTO
) {
7626 if (tok
== '*' && gnu_ext
) {
7630 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
7633 } else if (tok
>= TOK_UIDENT
) {
7634 s
= label_find(tok
);
7635 /* put forward definition if needed */
7637 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7639 if (s
->r
== LABEL_DECLARED
)
7640 s
->r
= LABEL_FORWARD
;
7642 /* label already defined */
7643 if (s
->r
& LABEL_FORWARD
)
7644 s
->next
= (void *)gjmp((long)s
->next
);
7646 gjmp_addr((long)s
->next
);
7649 expect("label identifier");
7652 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
7660 if (s
->r
== LABEL_DEFINED
)
7661 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
7662 gsym((long)s
->next
);
7663 s
->r
= LABEL_DEFINED
;
7665 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
7667 s
->next
= (void *)ind
;
7668 /* we accept this, but it is a mistake */
7671 warning("deprecated use of label at end of compound statement");
7675 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7678 /* expression case */
7693 /* t is the array or struct type. c is the array or struct
7694 address. cur_index/cur_field is the pointer to the current
7695 value. 'size_only' is true if only size info is needed (only used
7697 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
7698 int *cur_index
, Sym
**cur_field
,
7702 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
7708 if (gnu_ext
&& (l
= is_label()) != 0)
7710 while (tok
== '[' || tok
== '.') {
7712 if (!(type
->t
& VT_ARRAY
))
7713 expect("array type");
7716 index
= expr_const();
7717 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
7718 expect("invalid index");
7719 if (tok
== TOK_DOTS
&& gnu_ext
) {
7721 index_last
= expr_const();
7722 if (index_last
< 0 ||
7723 (s
->c
>= 0 && index_last
>= s
->c
) ||
7725 expect("invalid index");
7731 *cur_index
= index_last
;
7732 type
= pointed_type(type
);
7733 elem_size
= type_size(type
, &align
);
7734 c
+= index
* elem_size
;
7735 /* NOTE: we only support ranges for last designator */
7736 nb_elems
= index_last
- index
+ 1;
7737 if (nb_elems
!= 1) {
7746 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
7747 expect("struct/union type");
7760 /* XXX: fix this mess by using explicit storage field */
7762 type1
.t
|= (type
->t
& ~VT_TYPE
);
7776 if (type
->t
& VT_ARRAY
) {
7778 type
= pointed_type(type
);
7779 c
+= index
* type_size(type
, &align
);
7783 error("too many field init");
7784 /* XXX: fix this mess by using explicit storage field */
7786 type1
.t
|= (type
->t
& ~VT_TYPE
);
7791 decl_initializer(type
, sec
, c
, 0, size_only
);
7793 /* XXX: make it more general */
7794 if (!size_only
&& nb_elems
> 1) {
7795 unsigned long c_end
;
7800 error("range init not supported yet for dynamic storage");
7801 c_end
= c
+ nb_elems
* elem_size
;
7802 if (c_end
> sec
->data_allocated
)
7803 section_realloc(sec
, c_end
);
7804 src
= sec
->data
+ c
;
7806 for(i
= 1; i
< nb_elems
; i
++) {
7808 memcpy(dst
, src
, elem_size
);
7814 #define EXPR_CONST 1
7817 /* store a value or an expression directly in global data or in local array */
7818 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
7819 int v
, int expr_type
)
7821 int saved_global_expr
, bt
, bit_pos
, bit_size
;
7823 unsigned long long bit_mask
;
7831 /* compound literals must be allocated globally in this case */
7832 saved_global_expr
= global_expr
;
7835 global_expr
= saved_global_expr
;
7836 /* NOTE: symbols are accepted */
7837 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
7838 error("initializer element is not constant");
7846 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
7849 /* XXX: not portable */
7850 /* XXX: generate error if incorrect relocation */
7851 gen_assign_cast(&dtype
);
7852 bt
= type
->t
& VT_BTYPE
;
7853 ptr
= sec
->data
+ c
;
7854 /* XXX: make code faster ? */
7855 if (!(type
->t
& VT_BITFIELD
)) {
7860 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
7861 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
7862 bit_mask
= (1LL << bit_size
) - 1;
7864 if ((vtop
->r
& VT_SYM
) &&
7870 (bt
== VT_INT
&& bit_size
!= 32)))
7871 error("initializer element is not computable at load time");
7874 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7877 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7880 *(double *)ptr
= vtop
->c
.d
;
7883 *(long double *)ptr
= vtop
->c
.ld
;
7886 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
7889 if (vtop
->r
& VT_SYM
) {
7890 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
7892 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7897 vset(&dtype
, VT_LOCAL
, c
);
7904 /* put zeros for variable based init */
7905 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
7908 /* nothing to do because globals are already set to zero */
7910 vpush_global_sym(&func_old_type
, TOK_memset
);
7918 /* 't' contains the type and storage info. 'c' is the offset of the
7919 object in section 'sec'. If 'sec' is NULL, it means stack based
7920 allocation. 'first' is true if array '{' must be read (multi
7921 dimension implicit array init handling). 'size_only' is true if
7922 size only evaluation is wanted (only for arrays). */
7923 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
7924 int first
, int size_only
)
7926 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
7927 int size1
, align1
, expr_type
;
7931 if (type
->t
& VT_ARRAY
) {
7935 t1
= pointed_type(type
);
7936 size1
= type_size(t1
, &align1
);
7939 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
7945 /* only parse strings here if correct type (otherwise: handle
7946 them as ((w)char *) expressions */
7947 if ((tok
== TOK_LSTR
&&
7948 (t1
->t
& VT_BTYPE
) == VT_INT
) ||
7950 (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
7951 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
7956 /* compute maximum number of chars wanted */
7958 cstr_len
= cstr
->size
;
7960 cstr_len
= cstr
->size
/ sizeof(int);
7963 if (n
>= 0 && nb
> (n
- array_length
))
7964 nb
= n
- array_length
;
7967 warning("initializer-string for array is too long");
7968 /* in order to go faster for common case (char
7969 string in global variable, we handle it
7971 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
7972 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
7976 ch
= ((unsigned char *)cstr
->data
)[i
];
7978 ch
= ((int *)cstr
->data
)[i
];
7979 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
7987 /* only add trailing zero if enough storage (no
7988 warning in this case since it is standard) */
7989 if (n
< 0 || array_length
< n
) {
7991 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
7997 while (tok
!= '}') {
7998 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
7999 if (n
>= 0 && index
>= n
)
8000 error("index too large");
8001 /* must put zero in holes (note that doing it that way
8002 ensures that it even works with designators) */
8003 if (!size_only
&& array_length
< index
) {
8004 init_putz(t1
, sec
, c
+ array_length
* size1
,
8005 (index
- array_length
) * size1
);
8008 if (index
> array_length
)
8009 array_length
= index
;
8010 /* special test for multi dimensional arrays (may not
8011 be strictly correct if designators are used at the
8013 if (index
>= n
&& no_oblock
)
8022 /* put zeros at the end */
8023 if (!size_only
&& n
>= 0 && array_length
< n
) {
8024 init_putz(t1
, sec
, c
+ array_length
* size1
,
8025 (n
- array_length
) * size1
);
8027 /* patch type size if needed */
8029 s
->c
= array_length
;
8030 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
8031 (sec
|| !first
|| tok
== '{')) {
8034 /* NOTE: the previous test is a specific case for automatic
8035 struct/union init */
8036 /* XXX: union needs only one init */
8038 /* XXX: this test is incorrect for local initializers
8039 beginning with ( without {. It would be much more difficult
8040 to do it correctly (ideally, the expression parser should
8041 be used in all cases) */
8047 while (tok
== '(') {
8051 if (!parse_btype(&type1
, &ad1
))
8053 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
8055 if (!is_assignable_types(type
, &type1
))
8056 error("invalid type for cast");
8061 if (first
|| tok
== '{') {
8070 while (tok
!= '}') {
8071 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
8073 if (!size_only
&& array_length
< index
) {
8074 init_putz(type
, sec
, c
+ array_length
,
8075 index
- array_length
);
8077 index
= index
+ type_size(&f
->type
, &align1
);
8078 if (index
> array_length
)
8079 array_length
= index
;
8081 if (no_oblock
&& f
== NULL
)
8087 /* put zeros at the end */
8088 if (!size_only
&& array_length
< n
) {
8089 init_putz(type
, sec
, c
+ array_length
,
8098 } else if (tok
== '{') {
8100 decl_initializer(type
, sec
, c
, first
, size_only
);
8102 } else if (size_only
) {
8103 /* just skip expression */
8105 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
8109 else if (tok
== ')')
8114 /* currently, we always use constant expression for globals
8115 (may change for scripting case) */
8116 expr_type
= EXPR_CONST
;
8118 expr_type
= EXPR_ANY
;
8119 init_putv(type
, sec
, c
, 0, expr_type
);
8123 /* parse an initializer for type 't' if 'has_init' is non zero, and
8124 allocate space in local or global data space ('r' is either
8125 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
8126 variable 'v' of scope 'scope' is declared before initializers are
8127 parsed. If 'v' is zero, then a reference to the new object is put
8128 in the value stack. If 'has_init' is 2, a special parsing is done
8129 to handle string constants. */
8130 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
8131 int has_init
, int v
, int scope
)
8133 int size
, align
, addr
, data_offset
;
8135 ParseState saved_parse_state
;
8136 TokenString init_str
;
8139 size
= type_size(type
, &align
);
8140 /* If unknown size, we must evaluate it before
8141 evaluating initializers because
8142 initializers can generate global data too
8143 (e.g. string pointers or ISOC99 compound
8144 literals). It also simplifies local
8145 initializers handling */
8146 tok_str_new(&init_str
);
8149 error("unknown type size");
8150 /* get all init string */
8151 if (has_init
== 2) {
8152 /* only get strings */
8153 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8154 tok_str_add_tok(&init_str
);
8159 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
8161 error("unexpected end of file in initializer");
8162 tok_str_add_tok(&init_str
);
8165 else if (tok
== '}') {
8173 tok_str_add(&init_str
, -1);
8174 tok_str_add(&init_str
, 0);
8177 save_parse_state(&saved_parse_state
);
8179 macro_ptr
= init_str
.str
;
8181 decl_initializer(type
, NULL
, 0, 1, 1);
8182 /* prepare second initializer parsing */
8183 macro_ptr
= init_str
.str
;
8186 /* if still unknown size, error */
8187 size
= type_size(type
, &align
);
8189 error("unknown type size");
8191 /* take into account specified alignment if bigger */
8192 if (ad
->aligned
> align
)
8193 align
= ad
->aligned
;
8194 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
8196 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
8198 loc
= (loc
- size
) & -align
;
8200 /* handles bounds */
8201 /* XXX: currently, since we do only one pass, we cannot track
8202 '&' operators, so we add only arrays */
8203 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
8204 unsigned long *bounds_ptr
;
8205 /* add padding between regions */
8207 /* then add local bound info */
8208 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
8209 bounds_ptr
[0] = addr
;
8210 bounds_ptr
[1] = size
;
8213 /* local variable */
8214 sym_push(v
, type
, r
, addr
);
8216 /* push local reference */
8217 vset(type
, r
, addr
);
8223 if (v
&& scope
== VT_CONST
) {
8224 /* see if the symbol was already defined */
8227 if (!is_compatible_types(&sym
->type
, type
))
8228 error("incompatible types for redefinition of '%s'",
8229 get_tok_str(v
, NULL
));
8230 if (sym
->type
.t
& VT_EXTERN
) {
8231 /* if the variable is extern, it was not allocated */
8232 sym
->type
.t
&= ~VT_EXTERN
;
8234 /* we accept several definitions of the same
8235 global variable. this is tricky, because we
8236 must play with the SHN_COMMON type of the symbol */
8237 /* XXX: should check if the variable was already
8238 initialized. It is incorrect to initialized it
8240 /* no init data, we won't add more to the symbol */
8247 /* allocate symbol in corresponding section */
8254 data_offset
= sec
->data_offset
;
8255 data_offset
= (data_offset
+ align
- 1) & -align
;
8257 /* very important to increment global pointer at this time
8258 because initializers themselves can create new initializers */
8259 data_offset
+= size
;
8260 /* add padding if bound check */
8261 if (do_bounds_check
)
8263 sec
->data_offset
= data_offset
;
8264 /* allocate section space to put the data */
8265 if (sec
->sh_type
!= SHT_NOBITS
&&
8266 data_offset
> sec
->data_allocated
)
8267 section_realloc(sec
, data_offset
);
8269 addr
= 0; /* avoid warning */
8273 if (scope
== VT_CONST
) {
8278 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
8280 /* update symbol definition */
8282 put_extern_sym(sym
, sec
, addr
, size
);
8285 /* put a common area */
8286 put_extern_sym(sym
, NULL
, align
, size
);
8287 /* XXX: find a nicer way */
8288 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
8289 esym
->st_shndx
= SHN_COMMON
;
8294 /* push global reference */
8295 sym
= get_sym_ref(type
, sec
, addr
, size
);
8297 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
8301 /* handles bounds now because the symbol must be defined
8302 before for the relocation */
8303 if (do_bounds_check
) {
8304 unsigned long *bounds_ptr
;
8306 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
8307 /* then add global bound info */
8308 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
8309 bounds_ptr
[0] = 0; /* relocated */
8310 bounds_ptr
[1] = size
;
8314 decl_initializer(type
, sec
, addr
, 1, 0);
8315 /* restore parse state if needed */
8317 tok_str_free(init_str
.str
);
8318 restore_parse_state(&saved_parse_state
);
8324 void put_func_debug(Sym
*sym
)
8329 /* XXX: we put here a dummy type */
8330 snprintf(buf
, sizeof(buf
), "%s:%c1",
8331 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
8332 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
8333 cur_text_section
, sym
->c
);
8338 /* not finished : try to put some local vars in registers */
8339 //#define CONFIG_REG_VARS
8341 #ifdef CONFIG_REG_VARS
8342 void add_var_ref(int t
)
8344 printf("%s:%d: &%s\n",
8345 file
->filename
, file
->line_num
,
8346 get_tok_str(t
, NULL
));
8349 /* first pass on a function with heuristic to extract variable usage
8350 and pointer references to local variables for register allocation */
8351 void analyse_function(void)
8358 /* any symbol coming after '&' is considered as being a
8359 variable whose reference is taken. It is highly unaccurate
8360 but it is difficult to do better without a complete parse */
8363 /* if '& number', then no need to examine next tokens */
8364 if (tok
== TOK_CINT
||
8366 tok
== TOK_CLLONG
||
8367 tok
== TOK_CULLONG
) {
8369 } else if (tok
>= TOK_UIDENT
) {
8370 /* if '& ident [' or '& ident ->', then ident address
8374 if (tok
!= '[' && tok
!= TOK_ARROW
)
8378 while (tok
!= '}' && tok
!= ';' &&
8379 !((tok
== ',' || tok
== ')') && level
== 0)) {
8380 if (tok
>= TOK_UIDENT
) {
8382 } else if (tok
== '(') {
8384 } else if (tok
== ')') {
8397 /* parse an old style function declaration list */
8398 /* XXX: check multiple parameter */
8399 static void func_decl_list(Sym
*func_sym
)
8406 /* parse each declaration */
8407 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
8408 if (!parse_btype(&btype
, &ad
))
8409 expect("declaration list");
8410 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8411 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8413 /* we accept no variable after */
8417 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8418 /* find parameter in function parameter list */
8421 if ((s
->v
& ~SYM_FIELD
) == v
)
8425 error("declaration for parameter '%s' but no such parameter",
8426 get_tok_str(v
, NULL
));
8428 /* check that no storage specifier except 'register' was given */
8429 if (type
.t
& VT_STORAGE
)
8430 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
8431 convert_parameter_type(&type
);
8432 /* we can add the type (NOTE: it could be local to the function) */
8434 /* accept other parameters */
8445 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
8446 static void decl(int l
)
8454 if (!parse_btype(&btype
, &ad
)) {
8455 /* skip redundant ';' */
8456 /* XXX: find more elegant solution */
8461 /* special test for old K&R protos without explicit int
8462 type. Only accepted when defining global data */
8463 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
8467 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8468 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8470 /* we accept no variable after */
8474 while (1) { /* iterate thru each declaration */
8476 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8480 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
8481 printf("type = '%s'\n", buf
);
8484 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8485 /* if old style function prototype, we accept a
8488 if (sym
->c
== FUNC_OLD
)
8489 func_decl_list(sym
);
8493 #ifdef CONFIG_REG_VARS
8494 TokenString func_str
;
8495 ParseState saved_parse_state
;
8500 error("cannot use local functions");
8501 if (!(type
.t
& VT_FUNC
))
8502 expect("function definition");
8503 /* XXX: cannot do better now: convert extern line to static inline */
8504 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
8505 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
8507 #ifdef CONFIG_REG_VARS
8508 /* parse all function code and record it */
8510 tok_str_new(&func_str
);
8516 error("unexpected end of file");
8517 tok_str_add_tok(&func_str
);
8522 } else if (t
== '}') {
8524 if (block_level
== 0)
8528 tok_str_add(&func_str
, -1);
8529 tok_str_add(&func_str
, 0);
8531 save_parse_state(&saved_parse_state
);
8533 macro_ptr
= func_str
.str
;
8538 /* compute text section */
8539 cur_text_section
= ad
.section
;
8540 if (!cur_text_section
)
8541 cur_text_section
= text_section
;
8542 ind
= cur_text_section
->data_offset
;
8543 funcname
= get_tok_str(v
, NULL
);
8546 /* if symbol is already defined, then put complete type */
8549 /* put function symbol */
8550 sym
= global_identifier_push(v
, type
.t
, 0);
8551 sym
->type
.ref
= type
.ref
;
8553 /* NOTE: we patch the symbol size later */
8554 put_extern_sym(sym
, cur_text_section
, ind
, 0);
8556 sym
->r
= VT_SYM
| VT_CONST
;
8557 /* put debug symbol */
8559 put_func_debug(sym
);
8560 /* push a dummy symbol to enable local sym storage */
8561 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
8562 gfunc_prolog(&type
);
8565 #ifdef CONFIG_REG_VARS
8566 macro_ptr
= func_str
.str
;
8569 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
8572 cur_text_section
->data_offset
= ind
;
8573 label_pop(&global_label_stack
, NULL
);
8574 sym_pop(&local_stack
, NULL
); /* reset local stack */
8575 /* end of function */
8576 /* patch symbol size */
8577 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_size
=
8580 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
8582 funcname
= ""; /* for safety */
8583 func_vt
.t
= VT_VOID
; /* for safety */
8584 ind
= 0; /* for safety */
8586 #ifdef CONFIG_REG_VARS
8587 tok_str_free(func_str
.str
);
8588 restore_parse_state(&saved_parse_state
);
8592 if (btype
.t
& VT_TYPEDEF
) {
8593 /* save typedefed type */
8594 /* XXX: test storage specifiers ? */
8595 sym
= sym_push(v
, &type
, 0, 0);
8596 sym
->type
.t
|= VT_TYPEDEF
;
8597 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8598 /* external function definition */
8599 external_sym(v
, &type
, 0);
8601 /* not lvalue if array */
8603 if (!(type
.t
& VT_ARRAY
))
8604 r
|= lvalue_type(type
.t
);
8605 has_init
= (tok
== '=');
8606 if ((btype
.t
& VT_EXTERN
) ||
8607 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
8608 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
8609 /* external variable */
8610 /* NOTE: as GCC, uninitialized global static
8611 arrays of null size are considered as
8613 external_sym(v
, &type
, r
);
8615 if (type
.t
& VT_STATIC
)
8621 decl_initializer_alloc(&type
, &ad
, r
,
8635 /* better than nothing, but needs extension to handle '-E' option
8637 static void preprocess_init(TCCState
*s1
)
8639 s1
->include_stack_ptr
= s1
->include_stack
;
8640 /* XXX: move that before to avoid having to initialize
8641 file->ifdef_stack_ptr ? */
8642 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
8643 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
8645 /* XXX: not ANSI compliant: bound checking says error */
8649 /* compile the C file opened in 'file'. Return non zero if errors. */
8650 static int tcc_compile(TCCState
*s1
)
8654 volatile int section_sym
;
8657 printf("%s: **** new file\n", file
->filename
);
8659 preprocess_init(s1
);
8662 anon_sym
= SYM_FIRST_ANOM
;
8664 /* file info: full path + filename */
8665 section_sym
= 0; /* avoid warning */
8667 section_sym
= put_elf_sym(symtab_section
, 0, 0,
8668 ELF32_ST_INFO(STB_LOCAL
, STT_SECTION
), 0,
8669 text_section
->sh_num
, NULL
);
8670 getcwd(buf
, sizeof(buf
));
8671 pstrcat(buf
, sizeof(buf
), "/");
8672 put_stabs_r(buf
, N_SO
, 0, 0,
8673 text_section
->data_offset
, text_section
, section_sym
);
8674 put_stabs_r(file
->filename
, N_SO
, 0, 0,
8675 text_section
->data_offset
, text_section
, section_sym
);
8677 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
8678 symbols can be safely used */
8679 put_elf_sym(symtab_section
, 0, 0,
8680 ELF32_ST_INFO(STB_LOCAL
, STT_FILE
), 0,
8681 SHN_ABS
, file
->filename
);
8683 /* define some often used types */
8684 int_type
.t
= VT_INT
;
8686 char_pointer_type
.t
= VT_BYTE
;
8687 mk_pointer(&char_pointer_type
);
8689 func_old_type
.t
= VT_FUNC
;
8690 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
8693 /* define 'void *alloca(unsigned int)' builtin function */
8698 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
8699 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
8702 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
8706 define_start
= define_stack
;
8708 if (setjmp(s1
->error_jmp_buf
) == 0) {
8710 s1
->error_set_jmp_enabled
= 1;
8712 ch
= file
->buf_ptr
[0];
8713 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
8714 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
8718 expect("declaration");
8720 /* end of translation unit info */
8722 put_stabs_r(NULL
, N_SO
, 0, 0,
8723 text_section
->data_offset
, text_section
, section_sym
);
8726 s1
->error_set_jmp_enabled
= 0;
8728 /* reset define stack, but leave -Dsymbols (may be incorrect if
8729 they are undefined) */
8730 free_defines(define_start
);
8732 sym_pop(&global_stack
, NULL
);
8734 return s1
->nb_errors
!= 0 ? -1 : 0;
8738 int tcc_compile_string(TCCState
*s
, const char *str
)
8740 BufferedFile bf1
, *bf
= &bf1
;
8744 /* init file structure */
8746 /* XXX: avoid copying */
8748 buf
= tcc_malloc(len
+ 1);
8751 memcpy(buf
, str
, len
);
8754 bf
->buf_end
= buf
+ len
;
8755 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
8759 ret
= tcc_compile(s
);
8763 /* currently, no need to close */
8768 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
8769 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
8771 BufferedFile bf1
, *bf
= &bf1
;
8773 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
8774 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
8778 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
8780 /* init file structure */
8782 bf
->buf_ptr
= bf
->buffer
;
8783 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
8784 *bf
->buf_end
= CH_EOB
;
8785 bf
->filename
[0] = '\0';
8789 s1
->include_stack_ptr
= s1
->include_stack
;
8791 /* parse with define parser */
8792 ch
= file
->buf_ptr
[0];
8798 /* undefine a preprocessor symbol */
8799 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
8803 ts
= tok_alloc(sym
, strlen(sym
));
8804 s
= define_find(ts
->tok
);
8805 /* undefine symbol by putting an invalid name */
8810 #ifdef CONFIG_TCC_ASM
8812 #include "i386-asm.c"
8816 static void asm_instr(void)
8818 error("inline asm() not supported");
8824 /* print the position in the source file of PC value 'pc' by reading
8825 the stabs debug information */
8826 static void rt_printline(unsigned long wanted_pc
)
8828 Stab_Sym
*sym
, *sym_end
;
8829 char func_name
[128], last_func_name
[128];
8830 unsigned long func_addr
, last_pc
, pc
;
8831 const char *incl_files
[INCLUDE_STACK_SIZE
];
8832 int incl_index
, len
, last_line_num
, i
;
8833 const char *str
, *p
;
8835 fprintf(stderr
, "0x%08lx:", wanted_pc
);
8837 func_name
[0] = '\0';
8840 last_func_name
[0] = '\0';
8841 last_pc
= 0xffffffff;
8843 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
8844 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
8845 while (sym
< sym_end
) {
8846 switch(sym
->n_type
) {
8847 /* function start or end */
8849 if (sym
->n_strx
== 0) {
8850 /* we test if between last line and end of function */
8851 pc
= sym
->n_value
+ func_addr
;
8852 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
8854 func_name
[0] = '\0';
8857 str
= stabstr_section
->data
+ sym
->n_strx
;
8858 p
= strchr(str
, ':');
8860 pstrcpy(func_name
, sizeof(func_name
), str
);
8863 if (len
> sizeof(func_name
) - 1)
8864 len
= sizeof(func_name
) - 1;
8865 memcpy(func_name
, str
, len
);
8866 func_name
[len
] = '\0';
8868 func_addr
= sym
->n_value
;
8871 /* line number info */
8873 pc
= sym
->n_value
+ func_addr
;
8874 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
8877 last_line_num
= sym
->n_desc
;
8879 strcpy(last_func_name
, func_name
);
8883 str
= stabstr_section
->data
+ sym
->n_strx
;
8885 if (incl_index
< INCLUDE_STACK_SIZE
) {
8886 incl_files
[incl_index
++] = str
;
8894 if (sym
->n_strx
== 0) {
8895 incl_index
= 0; /* end of translation unit */
8897 str
= stabstr_section
->data
+ sym
->n_strx
;
8898 /* do not add path */
8900 if (len
> 0 && str
[len
- 1] != '/')
8908 /* second pass: we try symtab symbols (no line number info) */
8911 Elf32_Sym
*sym
, *sym_end
;
8914 sym_end
= (Elf32_Sym
*)(symtab_section
->data
+ symtab_section
->data_offset
);
8915 for(sym
= (Elf32_Sym
*)symtab_section
->data
+ 1;
8918 type
= ELF32_ST_TYPE(sym
->st_info
);
8919 if (type
== STT_FUNC
) {
8920 if (wanted_pc
>= sym
->st_value
&&
8921 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
8922 pstrcpy(last_func_name
, sizeof(last_func_name
),
8923 strtab_section
->data
+ sym
->st_name
);
8929 /* did not find any info: */
8930 fprintf(stderr
, " ???\n");
8933 if (last_func_name
[0] != '\0') {
8934 fprintf(stderr
, " %s()", last_func_name
);
8936 if (incl_index
> 0) {
8937 fprintf(stderr
, " (%s:%d",
8938 incl_files
[incl_index
- 1], last_line_num
);
8939 for(i
= incl_index
- 2; i
>= 0; i
--)
8940 fprintf(stderr
, ", included from %s", incl_files
[i
]);
8941 fprintf(stderr
, ")");
8943 fprintf(stderr
, "\n");
8950 /* fix for glibc 2.1 */
8956 /* return the PC at frame level 'level'. Return non zero if not found */
8957 static int rt_get_caller_pc(unsigned long *paddr
,
8958 ucontext_t
*uc
, int level
)
8965 *paddr
= uc
->uc_mcontext
.mc_eip
;
8967 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
8972 fp
= uc
->uc_mcontext
.mc_ebp
;
8974 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
8976 for(i
=1;i
<level
;i
++) {
8977 /* XXX: check address validity with program info */
8978 if (fp
<= 0x1000 || fp
>= 0xc0000000)
8980 fp
= ((unsigned long *)fp
)[0];
8982 *paddr
= ((unsigned long *)fp
)[1];
8987 #error add arch specific rt_get_caller_pc()
8990 /* emit a run time error at position 'pc' */
8991 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
8998 fprintf(stderr
, "Runtime error: ");
8999 vfprintf(stderr
, fmt
, ap
);
9000 fprintf(stderr
, "\n");
9001 for(i
=0;i
<num_callers
;i
++) {
9002 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
9005 fprintf(stderr
, "at ");
9007 fprintf(stderr
, "by ");
9014 /* signal handler for fatal errors */
9015 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
9017 ucontext_t
*uc
= puc
;
9021 switch(siginf
->si_code
) {
9024 rt_error(uc
, "division by zero");
9027 rt_error(uc
, "floating point exception");
9033 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
9034 rt_error(uc
, *rt_bound_error_msg
);
9036 rt_error(uc
, "dereferencing invalid pointer");
9039 rt_error(uc
, "illegal instruction");
9042 rt_error(uc
, "abort() called");
9045 rt_error(uc
, "caught signal %d", signum
);
9052 /* do all relocations (needed before using tcc_get_symbol()) */
9053 int tcc_relocate(TCCState
*s1
)
9060 tcc_add_runtime(s1
);
9062 relocate_common_syms();
9064 /* compute relocation address : section are relocated in place. We
9065 also alloc the bss space */
9066 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9067 s
= s1
->sections
[i
];
9068 if (s
->sh_flags
& SHF_ALLOC
) {
9069 if (s
->sh_type
== SHT_NOBITS
)
9070 s
->data
= tcc_mallocz(s
->data_offset
);
9071 s
->sh_addr
= (unsigned long)s
->data
;
9075 relocate_syms(s1
, 1);
9077 if (s1
->nb_errors
!= 0)
9080 /* relocate each section */
9081 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9082 s
= s1
->sections
[i
];
9084 relocate_section(s1
, s
);
9089 /* launch the compiled program with the given arguments */
9090 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
9092 int (*prog_main
)(int, char **);
9094 if (tcc_relocate(s1
) < 0)
9097 prog_main
= tcc_get_symbol(s1
, "main");
9101 error("debug mode currently not available for Windows");
9103 struct sigaction sigact
;
9104 /* install TCC signal handlers to print debug info on fatal
9106 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
9107 sigact
.sa_sigaction
= sig_error
;
9108 sigemptyset(&sigact
.sa_mask
);
9109 sigaction(SIGFPE
, &sigact
, NULL
);
9110 sigaction(SIGILL
, &sigact
, NULL
);
9111 sigaction(SIGSEGV
, &sigact
, NULL
);
9112 sigaction(SIGBUS
, &sigact
, NULL
);
9113 sigaction(SIGABRT
, &sigact
, NULL
);
9117 #ifdef CONFIG_TCC_BCHECK
9118 if (do_bounds_check
) {
9119 void (*bound_init
)(void);
9121 /* set error function */
9122 rt_bound_error_msg
= (void *)tcc_get_symbol(s1
, "__bound_error_msg");
9124 /* XXX: use .init section so that it also work in binary ? */
9125 bound_init
= (void *)tcc_get_symbol(s1
, "__bound_init");
9129 return (*prog_main
)(argc
, argv
);
9132 TCCState
*tcc_new(void)
9139 s
= tcc_mallocz(sizeof(TCCState
));
9143 s
->output_type
= TCC_OUTPUT_MEMORY
;
9145 /* init isid table */
9147 isidnum_table
[i
] = isid(i
) || isnum(i
);
9149 /* add all tokens */
9151 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
9153 tok_ident
= TOK_IDENT
;
9162 ts
= tok_alloc(p
, r
- p
- 1);
9166 /* we add dummy defines for some special macros to speed up tests
9167 and to have working defined() */
9168 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
9169 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
9170 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
9171 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
9173 /* standard defines */
9174 tcc_define_symbol(s
, "__STDC__", NULL
);
9175 #if defined(TCC_TARGET_I386)
9176 tcc_define_symbol(s
, "__i386__", NULL
);
9179 tcc_define_symbol(s
, "__linux__", NULL
);
9180 tcc_define_symbol(s
, "linux", NULL
);
9182 /* tiny C specific defines */
9183 tcc_define_symbol(s
, "__TINYC__", NULL
);
9185 /* tiny C & gcc defines */
9186 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
9187 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
9188 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
9190 /* default library paths */
9191 tcc_add_library_path(s
, "/usr/local/lib");
9192 tcc_add_library_path(s
, "/usr/lib");
9193 tcc_add_library_path(s
, "/lib");
9195 /* no section zero */
9196 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
9198 /* create standard sections */
9199 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
9200 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
9201 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
9203 /* symbols are always generated for linking stage */
9204 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
9206 ".hashtab", SHF_PRIVATE
);
9207 strtab_section
= symtab_section
->link
;
9209 /* private symbol table for dynamic symbols */
9210 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
9212 ".dynhashtab", SHF_PRIVATE
);
9213 s
->alacarte_link
= 1;
9217 void tcc_delete(TCCState
*s1
)
9221 /* free -D defines */
9225 n
= tok_ident
- TOK_IDENT
;
9226 for(i
= 0; i
< n
; i
++)
9227 tcc_free(table_ident
[i
]);
9228 tcc_free(table_ident
);
9230 /* free all sections */
9232 free_section(symtab_section
->hash
);
9234 free_section(s1
->dynsymtab_section
->hash
);
9235 free_section(s1
->dynsymtab_section
->link
);
9236 free_section(s1
->dynsymtab_section
);
9238 for(i
= 1; i
< s1
->nb_sections
; i
++)
9239 free_section(s1
->sections
[i
]);
9240 tcc_free(s1
->sections
);
9242 /* free loaded dlls array */
9243 for(i
= 0; i
< s1
->nb_loaded_dlls
; i
++)
9244 tcc_free(s1
->loaded_dlls
[i
]);
9245 tcc_free(s1
->loaded_dlls
);
9248 for(i
= 0; i
< s1
->nb_library_paths
; i
++)
9249 tcc_free(s1
->library_paths
[i
]);
9250 tcc_free(s1
->library_paths
);
9252 /* cached includes */
9253 for(i
= 0; i
< s1
->nb_cached_includes
; i
++)
9254 tcc_free(s1
->cached_includes
[i
]);
9255 tcc_free(s1
->cached_includes
);
9257 for(i
= 0; i
< s1
->nb_include_paths
; i
++)
9258 tcc_free(s1
->include_paths
[i
]);
9259 tcc_free(s1
->include_paths
);
9261 for(i
= 0; i
< s1
->nb_sysinclude_paths
; i
++)
9262 tcc_free(s1
->sysinclude_paths
[i
]);
9263 tcc_free(s1
->sysinclude_paths
);
9268 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
9272 pathname1
= tcc_strdup(pathname
);
9273 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
9277 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
9281 pathname1
= tcc_strdup(pathname
);
9282 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
9286 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
9288 const char *ext
, *filename1
;
9291 BufferedFile
*saved_file
;
9293 /* find source file type with extension */
9294 filename1
= strrchr(filename
, '/');
9298 filename1
= filename
;
9299 ext
= strrchr(filename1
, '.');
9305 file
= tcc_open(s1
, filename
);
9307 if (flags
& AFF_PRINT_ERROR
) {
9308 error_noabort("file '%s' not found", filename
);
9314 if (!ext
|| !strcmp(ext
, "c")) {
9315 /* C file assumed */
9316 ret
= tcc_compile(s1
);
9318 #ifdef CONFIG_TCC_ASM
9319 if (!strcmp(ext
, "S")) {
9320 /* preprocessed assembler */
9321 ret
= tcc_assemble(s1
, 1);
9322 } else if (!strcmp(ext
, "s")) {
9323 /* non preprocessed assembler */
9324 ret
= tcc_assemble(s1
, 0);
9329 /* assume executable format: auto guess file type */
9330 if (read(fd
, &ehdr
, sizeof(ehdr
)) != sizeof(ehdr
)) {
9331 error_noabort("could not read header");
9334 lseek(fd
, 0, SEEK_SET
);
9336 if (ehdr
.e_ident
[0] == ELFMAG0
&&
9337 ehdr
.e_ident
[1] == ELFMAG1
&&
9338 ehdr
.e_ident
[2] == ELFMAG2
&&
9339 ehdr
.e_ident
[3] == ELFMAG3
) {
9340 file
->line_num
= 0; /* do not display line number if error */
9341 if (ehdr
.e_type
== ET_REL
) {
9342 ret
= tcc_load_object_file(s1
, fd
, 0);
9343 } else if (ehdr
.e_type
== ET_DYN
) {
9344 ret
= tcc_load_dll(s1
, fd
, filename
,
9345 (flags
& AFF_REFERENCED_DLL
) != 0);
9347 error_noabort("unrecognized ELF file");
9350 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
9351 file
->line_num
= 0; /* do not display line number if error */
9352 ret
= tcc_load_archive(s1
, fd
);
9354 /* as GNU ld, consider it is an ld script if not recognized */
9355 ret
= tcc_load_ldscript(s1
);
9357 error_noabort("unrecognized file type");
9372 int tcc_add_file(TCCState
*s
, const char *filename
)
9374 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
9377 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
9381 pathname1
= tcc_strdup(pathname
);
9382 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
9386 /* find and load a dll. Return non zero if not found */
9387 /* XXX: add '-rpath' option support ? */
9388 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
9393 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9394 snprintf(buf
, sizeof(buf
), "%s/%s",
9395 s
->library_paths
[i
], filename
);
9396 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
9402 /* the library name is the same as the argument of the '-l' option */
9403 int tcc_add_library(TCCState
*s
, const char *libraryname
)
9409 /* first we look for the dynamic library if not static linking */
9410 if (!s
->static_link
) {
9411 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
9412 /* if we output to memory, then we simply we dlopen(). */
9413 if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
9414 /* Since the libc is already loaded, we don't need to load it again */
9415 if (!strcmp(libraryname
, "c"))
9417 h
= dlopen(buf
, RTLD_GLOBAL
| RTLD_LAZY
);
9421 if (tcc_add_dll(s
, buf
, 0) == 0)
9426 /* then we look for the static library */
9427 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9428 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
9429 s
->library_paths
[i
], libraryname
);
9430 if (tcc_add_file_internal(s
, buf
, 0) == 0)
9436 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
9438 add_elf_sym(symtab_section
, val
, 0,
9439 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
),
9444 int tcc_set_output_type(TCCState
*s
, int output_type
)
9448 s
->output_type
= output_type
;
9451 /* default include paths */
9452 /* XXX: reverse order needed if -isystem support */
9453 tcc_add_sysinclude_path(s
, "/usr/local/include");
9454 tcc_add_sysinclude_path(s
, "/usr/include");
9455 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
9456 tcc_add_sysinclude_path(s
, buf
);
9459 /* if bound checking, then add corresponding sections */
9460 #ifdef CONFIG_TCC_BCHECK
9461 if (do_bounds_check
) {
9463 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
9464 /* create bounds sections */
9465 bounds_section
= new_section(s
, ".bounds",
9466 SHT_PROGBITS
, SHF_ALLOC
);
9467 lbounds_section
= new_section(s
, ".lbounds",
9468 SHT_PROGBITS
, SHF_ALLOC
);
9472 /* add debug sections */
9475 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
9476 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
9477 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
9478 put_elf_str(stabstr_section
, "");
9479 stab_section
->link
= stabstr_section
;
9480 /* put first entry */
9481 put_stabs("", 0, 0, 0, 0);
9484 /* add libc crt1/crti objects */
9485 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
9487 if (output_type
!= TCC_OUTPUT_DLL
)
9488 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
9489 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
9494 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
9496 typedef struct WarningDef
{
9502 static const WarningDef warning_defs
[] = {
9503 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
9504 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
9505 { offsetof(TCCState
, warn_error
), 0, "error" },
9508 /* set/reset a warning */
9509 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
9512 const WarningDef
*p
;
9513 if (!strcmp(warning_name
, "all")) {
9514 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
9515 if (p
->flags
& WD_ALL
)
9516 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
9519 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
9520 if (!strcmp(warning_name
, p
->name
))
9525 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
9531 #if !defined(LIBTCC)
9533 /* extract the basename of a file */
9534 static const char *tcc_basename(const char *name
)
9537 p
= strrchr(name
, '/');
9540 p
= strrchr(name
, '\\');
9549 static int64_t getclock_us(void)
9554 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
9557 gettimeofday(&tv
, NULL
);
9558 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
9564 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2003 Fabrice Bellard\n"
9565 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
9566 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]\n"
9567 " [infile1 infile2...] [-run infile args...]\n"
9569 "General options:\n"
9570 " -v display current version\n"
9571 " -c compile only - generate an object file\n"
9572 " -o outfile set output filename\n"
9573 " -Bdir set tcc internal library path\n"
9574 " -bench output compilation statistics\n"
9575 " -run run compiled source\n"
9576 " -Wwarning set or reset (with 'no-' prefix) 'warning'\n"
9577 "Preprocessor options:\n"
9578 " -Idir add include path 'dir'\n"
9579 " -Dsym[=val] define 'sym' with value 'val'\n"
9580 " -Usym undefine 'sym'\n"
9582 " -Ldir add library path 'dir'\n"
9583 " -llib link with dynamic or static library 'lib'\n"
9584 " -shared generate a shared library\n"
9585 " -static static linking\n"
9586 " -r relocatable output\n"
9587 "Debugger options:\n"
9588 " -g generate runtime debug info\n"
9589 #ifdef CONFIG_TCC_BCHECK
9590 " -b compile with built-in memory and bounds checker (implies -g)\n"
9592 " -bt N show N callers in stack traces\n"
9596 #define TCC_OPTION_HAS_ARG 0x0001
9597 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
9599 typedef struct TCCOption
{
9626 TCC_OPTION_nostdinc
,
9627 TCC_OPTION_nostdlib
,
9628 TCC_OPTION_print_search_dirs
,
9629 TCC_OPTION_rdynamic
,
9634 static const TCCOption tcc_options
[] = {
9635 { "h", TCC_OPTION_HELP
, 0 },
9636 { "?", TCC_OPTION_HELP
, 0 },
9637 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
9638 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
9639 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
9640 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
9641 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
9642 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9643 { "bench", TCC_OPTION_bench
, 0 },
9644 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
9645 #ifdef CONFIG_TCC_BCHECK
9646 { "b", TCC_OPTION_b
, 0 },
9648 { "g", TCC_OPTION_g
, 0 },
9649 { "c", TCC_OPTION_c
, 0 },
9650 { "static", TCC_OPTION_static
, 0 },
9651 { "shared", TCC_OPTION_shared
, 0 },
9652 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
9653 { "run", TCC_OPTION_run
, 0 },
9654 { "rdynamic", TCC_OPTION_rdynamic
, 0 }, /* currently ignored */
9655 { "r", TCC_OPTION_r
, 0 },
9656 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9657 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9658 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
9659 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9660 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
9661 { "nostdlib", TCC_OPTION_nostdlib
, 0 },
9662 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
9663 { "v", TCC_OPTION_v
, 0 },
9667 int main(int argc
, char **argv
)
9670 int optind
, output_type
, multiple_files
, i
, reloc_output
;
9673 int nb_files
, nb_libraries
, nb_objfiles
, dminus
, ret
;
9674 char objfilename
[1024];
9675 int64_t start_time
= 0;
9676 const TCCOption
*popt
;
9677 const char *optarg
, *p1
, *r1
, *outfile
;
9678 int print_search_dirs
;
9681 output_type
= TCC_OUTPUT_EXE
;
9691 print_search_dirs
= 0;
9693 if (optind
>= argc
) {
9694 if (nb_files
== 0 && !print_search_dirs
)
9701 /* add a new file */
9702 dynarray_add((void ***)&files
, &nb_files
, r
);
9703 if (!multiple_files
) {
9705 /* argv[0] will be this file */
9709 /* find option in table (match only the first chars */
9714 error("invalid option -- '%s'", r
);
9727 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
9728 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
9732 error("argument to '%s' is missing", r
);
9733 optarg
= argv
[optind
++];
9741 switch(popt
->index
) {
9742 case TCC_OPTION_HELP
:
9747 if (tcc_add_include_path(s
, optarg
) < 0)
9748 error("too many include paths");
9753 sym
= (char *)optarg
;
9754 value
= strchr(sym
, '=');
9759 tcc_define_symbol(s
, sym
, value
);
9763 tcc_undefine_symbol(s
, optarg
);
9766 tcc_add_library_path(s
, optarg
);
9769 /* set tcc utilities path (mainly for tcc development) */
9770 tcc_lib_path
= optarg
;
9773 dynarray_add((void ***)&files
, &nb_files
, r
);
9776 case TCC_OPTION_bench
:
9780 num_callers
= atoi(optarg
);
9782 #ifdef CONFIG_TCC_BCHECK
9784 do_bounds_check
= 1;
9793 output_type
= TCC_OUTPUT_OBJ
;
9795 case TCC_OPTION_static
:
9798 case TCC_OPTION_shared
:
9799 output_type
= TCC_OUTPUT_DLL
;
9806 /* generate a .o merging several output files */
9808 output_type
= TCC_OUTPUT_OBJ
;
9810 case TCC_OPTION_nostdinc
:
9813 case TCC_OPTION_nostdlib
:
9816 case TCC_OPTION_print_search_dirs
:
9817 print_search_dirs
= 1;
9819 case TCC_OPTION_run
:
9821 output_type
= TCC_OUTPUT_MEMORY
;
9824 printf("tcc version %s\n", TCC_VERSION
);
9828 const char *p
= optarg
;
9831 if (p
[0] == 'n' && p
[1] == 'o' && p
[2] == '-') {
9835 if (tcc_set_warning(s
, p
, value
) < 0 && s
->warn_unsupported
)
9836 goto unsupported_option
;
9840 if (s
->warn_unsupported
) {
9842 warning("unsupported option '%s'", r
);
9848 if (print_search_dirs
) {
9849 /* enough for Linux kernel */
9850 printf("install: %s/\n", tcc_lib_path
);
9854 nb_objfiles
= nb_files
- nb_libraries
;
9856 /* if outfile provided without other options, we output an
9858 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
9859 output_type
= TCC_OUTPUT_EXE
;
9861 /* check -c consistency : only single file handled. XXX: checks file type */
9862 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
9863 /* accepts only a single input file */
9864 if (nb_objfiles
!= 1)
9865 error("cannot specify multiple files with -c");
9866 if (nb_libraries
!= 0)
9867 error("cannot specify libraries with -c");
9870 /* compute default outfile name */
9871 if (output_type
!= TCC_OUTPUT_MEMORY
&& !outfile
) {
9872 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
9875 pstrcpy(objfilename
, sizeof(objfilename
) - 1,
9876 tcc_basename(files
[0]));
9877 /* add .o extension */
9878 ext
= strrchr(objfilename
, '.');
9880 goto default_outfile
;
9881 strcpy(ext
+ 1, "o");
9884 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
9886 outfile
= objfilename
;
9890 start_time
= getclock_us();
9893 tcc_set_output_type(s
, output_type
);
9895 /* compile or add each files or library */
9896 for(i
= 0;i
< nb_files
; i
++) {
9897 const char *filename
;
9899 filename
= files
[i
];
9900 if (filename
[0] == '-') {
9901 if (tcc_add_library(s
, filename
+ 2) < 0)
9902 error("cannot find %s", filename
);
9904 if (tcc_add_file(s
, filename
) < 0) {
9911 /* free all files */
9916 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
9917 if (total_time
< 0.001)
9919 if (total_bytes
< 1)
9921 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
9922 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
9923 total_time
, (int)(total_lines
/ total_time
),
9924 total_bytes
/ total_time
/ 1000000.0);
9927 if (s
->output_type
!= TCC_OUTPUT_MEMORY
) {
9928 tcc_output_file(s
, outfile
);
9931 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
9934 /* XXX: cannot do it with bound checking because of the malloc hooks */
9935 if (!do_bounds_check
)
9940 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);