2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001, 2002, 2003 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
36 #include <sys/timeb.h>
40 #include <sys/ucontext.h>
44 #ifndef CONFIG_TCC_STATIC
52 /* preprocessor debug */
54 /* include file debug */
62 /* target selection */
63 //#define TCC_TARGET_I386 /* i386 code generator */
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, all symbols are exported */
404 /* if true, only link in referenced objects from archive */
407 /* warning switches */
408 int warn_write_strings
;
409 int warn_unsupported
;
414 void (*error_func
)(void *opaque
, const char *msg
);
415 int error_set_jmp_enabled
;
416 jmp_buf error_jmp_buf
;
419 /* tiny assembler state */
422 /* see include_stack_ptr */
423 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
425 /* see ifdef_stack_ptr */
426 int ifdef_stack
[IFDEF_STACK_SIZE
];
429 /* The current value can be: */
430 #define VT_VALMASK 0x00ff
431 #define VT_CONST 0x00f0 /* constant in vc
432 (must be first non register value) */
433 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
434 #define VT_LOCAL 0x00f2 /* offset on stack */
435 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
436 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
437 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
438 #define VT_LVAL 0x0100 /* var is an lvalue */
439 #define VT_SYM 0x0200 /* a symbol value is added */
440 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
441 char/short stored in integer registers) */
442 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
443 dereferencing value */
444 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
445 bounding function call point is in vc */
446 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
447 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
448 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
449 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
452 #define VT_INT 0 /* integer type */
453 #define VT_BYTE 1 /* signed byte type */
454 #define VT_SHORT 2 /* short type */
455 #define VT_VOID 3 /* void type */
456 #define VT_PTR 4 /* pointer */
457 #define VT_ENUM 5 /* enum definition */
458 #define VT_FUNC 6 /* function type */
459 #define VT_STRUCT 7 /* struct/union definition */
460 #define VT_FLOAT 8 /* IEEE float */
461 #define VT_DOUBLE 9 /* IEEE double */
462 #define VT_LDOUBLE 10 /* IEEE long double */
463 #define VT_BOOL 11 /* ISOC99 boolean type */
464 #define VT_LLONG 12 /* 64 bit integer */
465 #define VT_LONG 13 /* long integer (NEVER USED as type, only
467 #define VT_BTYPE 0x000f /* mask for basic type */
468 #define VT_UNSIGNED 0x0010 /* unsigned type */
469 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
470 #define VT_BITFIELD 0x0040 /* bitfield modifier */
471 #define VT_CONSTANT 0x0800 /* const modifier */
472 #define VT_VOLATILE 0x1000 /* volatile modifier */
475 #define VT_EXTERN 0x00000080 /* extern definition */
476 #define VT_STATIC 0x00000100 /* static variable */
477 #define VT_TYPEDEF 0x00000200 /* typedef definition */
478 #define VT_INLINE 0x00000400 /* inline definition */
480 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
482 /* type mask (except storage) */
483 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
484 #define VT_TYPE (~(VT_STORAGE))
488 /* warning: the following compare tokens depend on i386 asm code */
500 #define TOK_LAND 0xa0
504 #define TOK_MID 0xa3 /* inc/dec, to void constant */
506 #define TOK_UDIV 0xb0 /* unsigned division */
507 #define TOK_UMOD 0xb1 /* unsigned modulo */
508 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
509 #define TOK_CINT 0xb3 /* number in tokc */
510 #define TOK_CCHAR 0xb4 /* char constant in tokc */
511 #define TOK_STR 0xb5 /* pointer to string in tokc */
512 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
513 #define TOK_LCHAR 0xb7
514 #define TOK_LSTR 0xb8
515 #define TOK_CFLOAT 0xb9 /* float constant */
516 #define TOK_LINENUM 0xba /* line number info */
517 #define TOK_CDOUBLE 0xc0 /* double constant */
518 #define TOK_CLDOUBLE 0xc1 /* long double constant */
519 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
520 #define TOK_ADDC1 0xc3 /* add with carry generation */
521 #define TOK_ADDC2 0xc4 /* add with carry use */
522 #define TOK_SUBC1 0xc5 /* add with carry generation */
523 #define TOK_SUBC2 0xc6 /* add with carry use */
524 #define TOK_CUINT 0xc8 /* unsigned int constant */
525 #define TOK_CLLONG 0xc9 /* long long constant */
526 #define TOK_CULLONG 0xca /* unsigned long long constant */
527 #define TOK_ARROW 0xcb
528 #define TOK_DOTS 0xcc /* three dots */
529 #define TOK_SHR 0xcd /* unsigned shift right */
530 #define TOK_PPNUM 0xce /* preprocessor number */
532 #define TOK_SHL 0x01 /* shift left */
533 #define TOK_SAR 0x02 /* signed shift right */
535 /* assignement operators : normal operator or 0x80 */
536 #define TOK_A_MOD 0xa5
537 #define TOK_A_AND 0xa6
538 #define TOK_A_MUL 0xaa
539 #define TOK_A_ADD 0xab
540 #define TOK_A_SUB 0xad
541 #define TOK_A_DIV 0xaf
542 #define TOK_A_XOR 0xde
543 #define TOK_A_OR 0xfc
544 #define TOK_A_SHL 0x81
545 #define TOK_A_SAR 0x82
548 #define offsetof(type, field) ((size_t) &((type *)0)->field)
552 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
555 /* WARNING: the content of this string encodes token numbers */
556 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";
558 #define TOK_EOF (-1) /* end of file */
559 #define TOK_LINEFEED 10 /* line feed */
561 /* all identificators and strings have token above that */
562 #define TOK_IDENT 256
564 /* only used for i386 asm opcodes definitions */
565 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
568 DEF(TOK_ASM_ ## x ## b, #x "b") \
569 DEF(TOK_ASM_ ## x ## w, #x "w") \
570 DEF(TOK_ASM_ ## x ## l, #x "l") \
571 DEF(TOK_ASM_ ## x, #x)
574 DEF(TOK_ASM_ ## x ## w, #x "w") \
575 DEF(TOK_ASM_ ## x ## l, #x "l") \
576 DEF(TOK_ASM_ ## x, #x)
579 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
580 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
581 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
582 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
585 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
586 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
589 #define DEF_ASMTEST(x) \
621 #define TOK_ASM_int TOK_INT
624 TOK_LAST
= TOK_IDENT
- 1,
625 #define DEF(id, str) id,
630 static const char tcc_keywords
[] =
631 #define DEF(id, str) str "\0"
636 #define TOK_UIDENT TOK_DEFINE
639 #define snprintf _snprintf
640 #define vsnprintf _vsnprintf
643 #if defined(WIN32) || defined(TCC_UCLIBC) || defined(__FreeBSD__)
644 /* currently incorrect */
645 long double strtold(const char *nptr
, char **endptr
)
647 return (long double)strtod(nptr
, endptr
);
649 float strtof(const char *nptr
, char **endptr
)
651 return (float)strtod(nptr
, endptr
);
654 /* XXX: need to define this to use them in non ISOC99 context */
655 extern float strtof (const char *__nptr
, char **__endptr
);
656 extern long double strtold (const char *__nptr
, char **__endptr
);
659 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
660 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
662 static void next(void);
663 static void next_nomacro(void);
664 static void parse_expr_type(CType
*type
);
665 static void expr_type(CType
*type
);
666 static void unary_type(CType
*type
);
667 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
668 int case_reg
, int is_expr
);
669 static int expr_const(void);
670 static void expr_eq(void);
671 static void gexpr(void);
672 static void decl(int l
);
673 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
674 int first
, int size_only
);
675 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
676 int has_init
, int v
, int scope
);
678 void gv2(int rc1
, int rc2
);
679 void move_reg(int r
, int s
);
680 void save_regs(int n
);
681 void save_reg(int r
);
687 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
688 const int *macro_str
, int can_read_stream
);
689 int save_reg_forced(int r
);
691 void force_charshort_cast(int t
);
692 static void gen_cast(CType
*type
);
694 static Sym
*sym_find(int v
);
695 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
698 static int type_size(CType
*type
, int *a
);
699 static inline CType
*pointed_type(CType
*type
);
700 static int pointed_size(CType
*type
);
701 static int lvalue_type(int t
);
702 static int parse_btype(CType
*type
, AttributeDef
*ad
);
703 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
704 static int is_compatible_types(CType
*type1
, CType
*type2
);
706 void error(const char *fmt
, ...);
708 void vset(CType
*type
, int r
, int v
);
709 void type_to_str(char *buf
, int buf_size
,
710 CType
*type
, const char *varstr
);
711 char *get_tok_str(int v
, CValue
*cv
);
712 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
713 unsigned long offset
, unsigned long size
);
714 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
716 /* section generation */
717 static void section_realloc(Section
*sec
, unsigned long new_size
);
718 static void *section_ptr_add(Section
*sec
, unsigned long size
);
719 static void put_extern_sym(Sym
*sym
, Section
*section
,
720 unsigned long value
, unsigned long size
);
721 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
722 static int put_elf_str(Section
*s
, const char *sym
);
723 static int put_elf_sym(Section
*s
,
724 unsigned long value
, unsigned long size
,
725 int info
, int other
, int shndx
, const char *name
);
726 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
727 int info
, int sh_num
, const char *name
);
728 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
729 int type
, int symbol
);
730 static void put_stabs(const char *str
, int type
, int other
, int desc
,
731 unsigned long value
);
732 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
733 unsigned long value
, Section
*sec
, int sym_index
);
734 static void put_stabn(int type
, int other
, int desc
, int value
);
735 static void put_stabd(int type
, int other
, int desc
);
736 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
738 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
739 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
740 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
744 #ifdef CONFIG_TCC_ASM
746 typedef struct ExprValue
{
751 #define MAX_ASM_OPERANDS 30
753 typedef struct ASMOperand
{
754 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
756 char asm_str
[16]; /* computed asm string for operand */
757 SValue
*vt
; /* C value of the expression */
758 int ref_index
; /* if >= 0, gives reference to a output constraint */
759 int priority
; /* priority, used to assign registers */
760 int reg
; /* if >= 0, register number used for this operand */
761 int is_llong
; /* true if double register value */
764 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
765 static int asm_int_expr(TCCState
*s1
);
766 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
767 const char *name
, const char **pp
);
769 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
773 static void asm_instr(void);
775 /* true if float/double/long double type */
776 static inline int is_float(int t
)
780 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
783 #ifdef TCC_TARGET_I386
784 #include "i386-gen.c"
787 #ifdef CONFIG_TCC_STATIC
789 #define RTLD_LAZY 0x001
790 #define RTLD_NOW 0x002
791 #define RTLD_GLOBAL 0x100
792 #define RTLD_DEFAULT NULL
794 /* dummy function for profiling */
795 void *dlopen(const char *filename
, int flag
)
800 const char *dlerror(void)
805 typedef struct TCCSyms
{
810 #define TCCSYM(a) { #a, &a, },
812 /* add the symbol you want here if no dynamic linking is done */
813 static TCCSyms tcc_syms
[] = {
821 void *dlsym(void *handle
, const char *symbol
)
825 while (p
->str
!= NULL
) {
826 if (!strcmp(p
->str
, symbol
))
835 /********************************************************/
837 /* we use our own 'finite' function to avoid potential problems with
838 non standard math libs */
839 /* XXX: endianness dependent */
840 int ieee_finite(double d
)
843 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
846 /* copy a string and truncate it. */
847 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
854 q_end
= buf
+ buf_size
- 1;
866 /* strcat and truncate. */
867 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
872 pstrcpy(buf
+ len
, buf_size
- len
, s
);
876 /* memory management */
882 static inline void tcc_free(void *ptr
)
885 mem_cur_size
-= malloc_usable_size(ptr
);
890 static void *tcc_malloc(unsigned long size
)
895 error("memory full");
897 mem_cur_size
+= malloc_usable_size(ptr
);
898 if (mem_cur_size
> mem_max_size
)
899 mem_max_size
= mem_cur_size
;
904 static void *tcc_mallocz(unsigned long size
)
907 ptr
= tcc_malloc(size
);
908 memset(ptr
, 0, size
);
912 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
916 mem_cur_size
-= malloc_usable_size(ptr
);
918 ptr1
= realloc(ptr
, size
);
920 /* NOTE: count not correct if alloc error, but not critical */
921 mem_cur_size
+= malloc_usable_size(ptr1
);
922 if (mem_cur_size
> mem_max_size
)
923 mem_max_size
= mem_cur_size
;
928 static char *tcc_strdup(const char *str
)
931 ptr
= tcc_malloc(strlen(str
) + 1);
936 #define free(p) use_tcc_free(p)
937 #define malloc(s) use_tcc_malloc(s)
938 #define realloc(p, s) use_tcc_realloc(p, s)
940 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
947 /* every power of two we double array size */
948 if ((nb
& (nb
- 1)) == 0) {
953 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
955 error("memory full");
962 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
966 sec
= tcc_mallocz(sizeof(Section
));
967 pstrcpy(sec
->name
, sizeof(sec
->name
), name
);
968 sec
->sh_type
= sh_type
;
969 sec
->sh_flags
= sh_flags
;
976 sec
->sh_addralign
= 4;
979 sec
->sh_addralign
= 1;
982 sec
->sh_addralign
= 32; /* default conservative alignment */
986 /* only add section if not private */
987 if (!(sh_flags
& SHF_PRIVATE
)) {
988 sec
->sh_num
= s1
->nb_sections
;
989 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
994 static void free_section(Section
*s
)
1000 /* realloc section and set its content to zero */
1001 static void section_realloc(Section
*sec
, unsigned long new_size
)
1004 unsigned char *data
;
1006 size
= sec
->data_allocated
;
1009 while (size
< new_size
)
1011 data
= tcc_realloc(sec
->data
, size
);
1013 error("memory full");
1014 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1016 sec
->data_allocated
= size
;
1019 /* reserve at least 'size' bytes in section 'sec' from
1020 sec->data_offset. */
1021 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1023 unsigned long offset
, offset1
;
1025 offset
= sec
->data_offset
;
1026 offset1
= offset
+ size
;
1027 if (offset1
> sec
->data_allocated
)
1028 section_realloc(sec
, offset1
);
1029 sec
->data_offset
= offset1
;
1030 return sec
->data
+ offset
;
1033 /* return a reference to a section, and create it if it does not
1035 Section
*find_section(TCCState
*s1
, const char *name
)
1039 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1040 sec
= s1
->sections
[i
];
1041 if (!strcmp(name
, sec
->name
))
1044 /* sections are created as PROGBITS */
1045 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1048 /* update sym->c so that it points to an external symbol in section
1049 'section' with value 'value' */
1050 static void put_extern_sym(Sym
*sym
, Section
*section
,
1051 unsigned long value
, unsigned long size
)
1053 int sym_type
, sym_bind
, sh_num
, info
;
1058 sh_num
= section
->sh_num
;
1062 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
)
1063 sym_type
= STT_FUNC
;
1065 sym_type
= STT_OBJECT
;
1066 if (sym
->type
.t
& VT_STATIC
)
1067 sym_bind
= STB_LOCAL
;
1069 sym_bind
= STB_GLOBAL
;
1071 name
= get_tok_str(sym
->v
, NULL
);
1072 #ifdef CONFIG_TCC_BCHECK
1073 if (do_bounds_check
) {
1076 /* XXX: avoid doing that for statics ? */
1077 /* if bound checking is activated, we change some function
1078 names by adding the "__bound" prefix */
1081 /* XXX: we rely only on malloc hooks */
1093 strcpy(buf
, "__bound_");
1100 info
= ELF32_ST_INFO(sym_bind
, sym_type
);
1101 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, sh_num
, name
);
1103 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
1104 esym
->st_value
= value
;
1105 esym
->st_size
= size
;
1106 esym
->st_shndx
= sh_num
;
1110 /* add a new relocation entry to symbol 'sym' in section 's' */
1111 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1114 put_extern_sym(sym
, NULL
, 0, 0);
1115 /* now we can add ELF relocation info */
1116 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1119 static inline int isid(int c
)
1121 return (c
>= 'a' && c
<= 'z') ||
1122 (c
>= 'A' && c
<= 'Z') ||
1126 static inline int isnum(int c
)
1128 return c
>= '0' && c
<= '9';
1131 static inline int isoct(int c
)
1133 return c
>= '0' && c
<= '7';
1136 static inline int toup(int c
)
1138 if (c
>= 'a' && c
<= 'z')
1139 return c
- 'a' + 'A';
1144 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1148 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1151 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1155 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1159 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1166 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1167 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1168 (*f
)->filename
, (*f
)->line_num
);
1169 if (file
->line_num
> 0) {
1170 strcat_printf(buf
, sizeof(buf
),
1171 "%s:%d: ", file
->filename
, file
->line_num
);
1173 strcat_printf(buf
, sizeof(buf
),
1174 "%s: ", file
->filename
);
1177 strcat_printf(buf
, sizeof(buf
),
1181 strcat_printf(buf
, sizeof(buf
), "warning: ");
1182 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1184 if (!s1
->error_func
) {
1185 /* default case: stderr */
1186 fprintf(stderr
, "%s\n", buf
);
1188 s1
->error_func(s1
->error_opaque
, buf
);
1190 if (!is_warning
|| s1
->warn_error
)
1195 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1196 void (*error_func
)(void *opaque
, const char *msg
))
1198 s
->error_opaque
= error_opaque
;
1199 s
->error_func
= error_func
;
1203 /* error without aborting current compilation */
1204 void error_noabort(const char *fmt
, ...)
1206 TCCState
*s1
= tcc_state
;
1210 error1(s1
, 0, fmt
, ap
);
1214 void error(const char *fmt
, ...)
1216 TCCState
*s1
= tcc_state
;
1220 error1(s1
, 0, fmt
, ap
);
1222 /* better than nothing: in some cases, we accept to handle errors */
1223 if (s1
->error_set_jmp_enabled
) {
1224 longjmp(s1
->error_jmp_buf
, 1);
1226 /* XXX: eliminate this someday */
1231 void expect(const char *msg
)
1233 error("%s expected", msg
);
1236 void warning(const char *fmt
, ...)
1238 TCCState
*s1
= tcc_state
;
1242 error1(s1
, 1, fmt
, ap
);
1249 error("'%c' expected", c
);
1253 static void test_lvalue(void)
1255 if (!(vtop
->r
& VT_LVAL
))
1259 /* allocate a new token */
1260 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1262 TokenSym
*ts
, **ptable
;
1265 if (tok_ident
>= SYM_FIRST_ANOM
)
1266 error("memory full");
1268 /* expand token table if needed */
1269 i
= tok_ident
- TOK_IDENT
;
1270 if ((i
% TOK_ALLOC_INCR
) == 0) {
1271 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1273 error("memory full");
1274 table_ident
= ptable
;
1277 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1278 table_ident
[i
] = ts
;
1279 ts
->tok
= tok_ident
++;
1280 ts
->sym_define
= NULL
;
1281 ts
->sym_label
= NULL
;
1282 ts
->sym_struct
= NULL
;
1283 ts
->sym_identifier
= NULL
;
1285 ts
->hash_next
= NULL
;
1286 memcpy(ts
->str
, str
, len
);
1287 ts
->str
[len
] = '\0';
1292 #define TOK_HASH_INIT 1
1293 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1295 /* find a token and add it if not found */
1296 static TokenSym
*tok_alloc(const char *str
, int len
)
1298 TokenSym
*ts
, **pts
;
1304 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1305 h
&= (TOK_HASH_SIZE
- 1);
1307 pts
= &hash_ident
[h
];
1312 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1314 pts
= &(ts
->hash_next
);
1316 return tok_alloc_new(pts
, str
, len
);
1319 /* CString handling */
1321 static void cstr_realloc(CString
*cstr
, int new_size
)
1326 size
= cstr
->size_allocated
;
1328 size
= 8; /* no need to allocate a too small first string */
1329 while (size
< new_size
)
1331 data
= tcc_realloc(cstr
->data_allocated
, size
);
1333 error("memory full");
1334 cstr
->data_allocated
= data
;
1335 cstr
->size_allocated
= size
;
1340 static void cstr_ccat(CString
*cstr
, int ch
)
1343 size
= cstr
->size
+ 1;
1344 if (size
> cstr
->size_allocated
)
1345 cstr_realloc(cstr
, size
);
1346 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1350 static void cstr_cat(CString
*cstr
, const char *str
)
1362 /* add a wide char */
1363 static void cstr_wccat(CString
*cstr
, int ch
)
1366 size
= cstr
->size
+ sizeof(int);
1367 if (size
> cstr
->size_allocated
)
1368 cstr_realloc(cstr
, size
);
1369 *(int *)(((unsigned char *)cstr
->data
) + size
- sizeof(int)) = ch
;
1373 static void cstr_new(CString
*cstr
)
1375 memset(cstr
, 0, sizeof(CString
));
1378 /* free string and reset it to NULL */
1379 static void cstr_free(CString
*cstr
)
1381 tcc_free(cstr
->data_allocated
);
1385 #define cstr_reset(cstr) cstr_free(cstr)
1387 static CString
*cstr_dup(CString
*cstr1
)
1392 cstr
= tcc_malloc(sizeof(CString
));
1395 cstr
->size_allocated
= size
;
1396 cstr
->data_allocated
= tcc_malloc(size
);
1397 cstr
->data
= cstr
->data_allocated
;
1398 memcpy(cstr
->data_allocated
, cstr1
->data_allocated
, size
);
1402 /* XXX: unicode ? */
1403 static void add_char(CString
*cstr
, int c
)
1405 if (c
== '\'' || c
== '\"' || c
== '\\') {
1406 /* XXX: could be more precise if char or string */
1407 cstr_ccat(cstr
, '\\');
1409 if (c
>= 32 && c
<= 126) {
1412 cstr_ccat(cstr
, '\\');
1414 cstr_ccat(cstr
, 'n');
1416 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1417 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1418 cstr_ccat(cstr
, '0' + (c
& 7));
1423 /* XXX: buffer overflow */
1424 /* XXX: float tokens */
1425 char *get_tok_str(int v
, CValue
*cv
)
1427 static char buf
[STRING_MAX_SIZE
+ 1];
1428 static CString cstr_buf
;
1434 /* NOTE: to go faster, we give a fixed buffer for small strings */
1435 cstr_reset(&cstr_buf
);
1436 cstr_buf
.data
= buf
;
1437 cstr_buf
.size_allocated
= sizeof(buf
);
1443 /* XXX: not quite exact, but only useful for testing */
1444 sprintf(p
, "%u", cv
->ui
);
1448 /* XXX: not quite exact, but only useful for testing */
1449 sprintf(p
, "%Lu", cv
->ull
);
1453 cstr_ccat(&cstr_buf
, '\'');
1454 add_char(&cstr_buf
, cv
->i
);
1455 cstr_ccat(&cstr_buf
, '\'');
1456 cstr_ccat(&cstr_buf
, '\0');
1460 len
= cstr
->size
- 1;
1462 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1463 cstr_ccat(&cstr_buf
, '\0');
1468 cstr_ccat(&cstr_buf
, '\"');
1470 len
= cstr
->size
- 1;
1472 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1474 len
= (cstr
->size
/ sizeof(int)) - 1;
1476 add_char(&cstr_buf
, ((int *)cstr
->data
)[i
]);
1478 cstr_ccat(&cstr_buf
, '\"');
1479 cstr_ccat(&cstr_buf
, '\0');
1488 return strcpy(p
, "<<=");
1490 return strcpy(p
, ">>=");
1492 if (v
< TOK_IDENT
) {
1493 /* search in two bytes table */
1507 } else if (v
< tok_ident
) {
1508 return table_ident
[v
- TOK_IDENT
]->str
;
1509 } else if (v
>= SYM_FIRST_ANOM
) {
1510 /* special name for anonymous symbol */
1511 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1513 /* should never happen */
1518 return cstr_buf
.data
;
1521 /* push, without hashing */
1522 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, int c
)
1525 s
= tcc_malloc(sizeof(Sym
));
1536 /* find a symbol and return its associated structure. 's' is the top
1537 of the symbol stack */
1538 static Sym
*sym_find2(Sym
*s
, int v
)
1548 /* structure lookup */
1549 static inline Sym
*struct_find(int v
)
1552 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1554 return table_ident
[v
]->sym_struct
;
1557 /* find an identifier */
1558 static inline Sym
*sym_find(int v
)
1561 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1563 return table_ident
[v
]->sym_identifier
;
1566 /* push a given symbol on the symbol stack */
1567 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1576 s
= sym_push2(ps
, v
, type
->t
, c
);
1577 s
->type
.ref
= type
->ref
;
1579 /* don't record fields or anonymous symbols */
1581 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1582 /* record symbol in token array */
1583 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1585 ps
= &ts
->sym_struct
;
1587 ps
= &ts
->sym_identifier
;
1594 /* push a global identifier */
1595 static Sym
*global_identifier_push(int v
, int t
, int c
)
1598 s
= sym_push2(&global_stack
, v
, t
, c
);
1599 /* don't record anonymous symbol */
1600 if (v
< SYM_FIRST_ANOM
) {
1601 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1602 /* modify the top most local identifier, so that
1603 sym_identifier will point to 's' when popped */
1605 ps
= &(*ps
)->prev_tok
;
1612 /* pop symbols until top reaches 'b' */
1613 static void sym_pop(Sym
**ptop
, Sym
*b
)
1623 /* remove symbol in token array */
1625 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1626 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1628 ps
= &ts
->sym_struct
;
1630 ps
= &ts
->sym_identifier
;
1641 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1646 fd
= open(filename
, O_RDONLY
);
1649 bf
= tcc_malloc(sizeof(BufferedFile
));
1655 bf
->buf_ptr
= bf
->buffer
;
1656 bf
->buf_end
= bf
->buffer
;
1657 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1658 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1660 bf
->ifndef_macro
= 0;
1661 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1662 // printf("opening '%s'\n", filename);
1666 void tcc_close(BufferedFile
*bf
)
1668 total_lines
+= bf
->line_num
;
1673 /* fill input buffer and peek next char */
1674 static int tcc_peekc_slow(BufferedFile
*bf
)
1677 /* only tries to read if really end of buffer */
1678 if (bf
->buf_ptr
>= bf
->buf_end
) {
1680 #if defined(PARSE_DEBUG)
1685 len
= read(bf
->fd
, bf
->buffer
, len
);
1692 bf
->buf_ptr
= bf
->buffer
;
1693 bf
->buf_end
= bf
->buffer
+ len
;
1694 *bf
->buf_end
= CH_EOB
;
1696 if (bf
->buf_ptr
< bf
->buf_end
) {
1697 return bf
->buf_ptr
[0];
1699 bf
->buf_ptr
= bf
->buf_end
;
1704 /* return the current character, handling end of block if necessary
1706 static int handle_eob(void)
1708 return tcc_peekc_slow(file
);
1711 /* read next char from current input file and handle end of input buffer */
1712 static inline void inp(void)
1714 ch
= *(++(file
->buf_ptr
));
1715 /* end of buffer/file handling */
1720 /* handle '\[\r]\n' */
1721 static void handle_stray(void)
1723 while (ch
== '\\') {
1728 } else if (ch
== '\r') {
1736 error("stray '\\' in program");
1741 /* skip the stray and handle the \\n case. Output an error if
1742 incorrect char after the stray */
1743 static int handle_stray1(uint8_t *p
)
1747 if (p
>= file
->buf_end
) {
1764 /* handle just the EOB case, but not stray */
1765 #define PEEKC_EOB(c, p)\
1776 /* handle the complicated stray case */
1777 #define PEEKC(c, p)\
1782 c = handle_stray1(p);\
1787 /* input with '\[\r]\n' handling. Note that this function cannot
1788 handle other characters after '\', so you cannot call it inside
1789 strings or comments */
1790 static void minp(void)
1798 /* single line C++ comments */
1799 static uint8_t *parse_line_comment(uint8_t *p
)
1806 if (c
== '\n' || c
== CH_EOF
) {
1808 } else if (c
== '\\') {
1813 } else if (c
== '\r') {
1828 static uint8_t *parse_comment(uint8_t *p
)
1834 /* fast skip loop */
1837 if (c
== '\n' || c
== '*' || c
== '\\')
1841 if (c
== '\n' || c
== '*' || c
== '\\')
1845 /* now we can handle all the cases */
1849 } else if (c
== '*') {
1855 } else if (c
== '/') {
1856 goto end_of_comment
;
1857 } else if (c
== '\\') {
1862 /* skip '\[\r]\n', otherwise just skip the stray */
1868 } else if (c
== '\r') {
1885 /* stray, eob or eof */
1890 error("unexpected end of file in comment");
1891 } else if (c
== '\\') {
1903 /* space exlcuding newline */
1904 static inline int is_space(int ch
)
1906 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
1909 static inline void skip_spaces(void)
1911 while (is_space(ch
))
1915 /* parse a string without interpreting escapes */
1916 static uint8_t *parse_pp_string(uint8_t *p
,
1917 int sep
, CString
*str
)
1925 } else if (c
== '\\') {
1930 unterminated_string
:
1931 /* XXX: indicate line number of start of string */
1932 error("missing terminating %c character", sep
);
1933 } else if (c
== '\\') {
1934 /* escape : just skip \[\r]\n */
1939 } else if (c
== '\r') {
1942 expect("'\n' after '\r'");
1945 } else if (c
== CH_EOF
) {
1946 goto unterminated_string
;
1949 cstr_ccat(str
, '\\');
1955 } else if (c
== '\n') {
1958 } else if (c
== '\r') {
1961 cstr_ccat(str
, '\r');
1977 /* skip block of text until #else, #elif or #endif. skip also pairs of
1979 void preprocess_skip(void)
1981 int a
, start_of_line
, c
;
2008 } else if (c
== '\\') {
2009 /* XXX: incorrect: should not give an error */
2010 ch
= file
->buf_ptr
[0];
2018 p
= parse_pp_string(p
, c
, NULL
);
2027 p
= parse_comment(p
);
2028 } else if (ch
== '/') {
2029 p
= parse_line_comment(p
);
2035 if (start_of_line
) {
2040 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2042 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2044 else if (tok
== TOK_ENDIF
)
2058 /* ParseState handling */
2060 /* XXX: currently, no include file info is stored. Thus, we cannot display
2061 accurate messages if the function or data definition spans multiple
2064 /* save current parse state in 's' */
2065 void save_parse_state(ParseState
*s
)
2067 s
->line_num
= file
->line_num
;
2068 s
->macro_ptr
= macro_ptr
;
2073 /* restore parse state from 's' */
2074 void restore_parse_state(ParseState
*s
)
2076 file
->line_num
= s
->line_num
;
2077 macro_ptr
= s
->macro_ptr
;
2082 /* return the number of additional 'ints' necessary to store the
2084 static inline int tok_ext_size(int t
)
2103 return LDOUBLE_SIZE
/ 4;
2109 /* token string handling */
2111 static inline void tok_str_new(TokenString
*s
)
2115 s
->allocated_len
= 0;
2116 s
->last_line_num
= -1;
2119 static void tok_str_free(int *str
)
2128 /* NOTE: we test zero separately so that GCC can generate a
2129 table for the following switch */
2144 /* XXX: use a macro to be portable on 64 bit ? */
2145 cstr
= (CString
*)p
[1];
2156 p
+= 1 + (LDOUBLE_SIZE
/ 4);
2166 static int *tok_str_realloc(TokenString
*s
)
2170 len
= s
->allocated_len
+ TOK_STR_ALLOC_INCR
;
2171 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2173 error("memory full");
2174 s
->allocated_len
= len
;
2179 static void tok_str_add(TokenString
*s
, int t
)
2185 if (len
>= s
->allocated_len
)
2186 str
= tok_str_realloc(s
);
2191 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2198 /* allocate space for worst case */
2199 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2200 str
= tok_str_realloc(s
);
2209 str
[len
++] = cv
->tab
[0];
2214 str
[len
++] = (int)cstr_dup(cv
->cstr
);
2219 str
[len
++] = cv
->tab
[0];
2220 str
[len
++] = cv
->tab
[1];
2223 #if LDOUBLE_SIZE == 12
2224 str
[len
++] = cv
->tab
[0];
2225 str
[len
++] = cv
->tab
[1];
2226 str
[len
++] = cv
->tab
[2];
2228 #error add long double size support
2237 /* add the current parse token in token string 's' */
2238 static void tok_str_add_tok(TokenString
*s
)
2242 /* save line number info */
2243 if (file
->line_num
!= s
->last_line_num
) {
2244 s
->last_line_num
= file
->line_num
;
2245 cval
.i
= s
->last_line_num
;
2246 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2248 tok_str_add2(s
, tok
, &tokc
);
2251 #if LDOUBLE_SIZE == 12
2252 #define LDOUBLE_GET(p, cv) \
2257 #error add long double size support
2261 /* get a token from an integer array and increment pointer
2262 accordingly. we code it as a macro to avoid pointer aliasing. */
2263 #define TOK_GET(t, p, cv) \
2285 case TOK_CLDOUBLE: \
2286 LDOUBLE_GET(p, cv); \
2287 p += LDOUBLE_SIZE / 4; \
2294 /* defines handling */
2295 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2299 s
= sym_push2(&define_stack
, v
, macro_type
, (int)str
);
2300 s
->next
= first_arg
;
2301 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2304 /* undefined a define symbol. Its name is just set to zero */
2305 static void define_undef(Sym
*s
)
2309 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2310 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2314 static inline Sym
*define_find(int v
)
2317 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2319 return table_ident
[v
]->sym_define
;
2322 /* free define stack until top reaches 'b' */
2323 static void free_defines(Sym
*b
)
2331 /* do not free args or predefined defines */
2333 tok_str_free((int *)top
->c
);
2335 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2336 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2344 static Sym
*label_find(int v
)
2347 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2349 return table_ident
[v
]->sym_label
;
2352 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2355 s
= sym_push2(ptop
, v
, 0, 0);
2357 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2358 if (ptop
== &global_label_stack
) {
2359 /* modify the top most local identifier, so that
2360 sym_identifier will point to 's' when popped */
2362 ps
= &(*ps
)->prev_tok
;
2369 /* pop labels until element last is reached. Look if any labels are
2370 undefined. Define symbols if '&&label' was used. */
2371 static void label_pop(Sym
**ptop
, Sym
*slast
)
2374 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2376 if (s
->r
== LABEL_DECLARED
) {
2377 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2378 } else if (s
->r
== LABEL_FORWARD
) {
2379 error("label '%s' used but not defined",
2380 get_tok_str(s
->v
, NULL
));
2383 /* define corresponding symbol. A size of
2385 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2389 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2395 /* eval an expression for #if/#elif */
2396 static int expr_preprocess(void)
2402 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2403 next(); /* do macro subst */
2404 if (tok
== TOK_DEFINED
) {
2409 c
= define_find(tok
) != 0;
2414 } else if (tok
>= TOK_IDENT
) {
2415 /* if undefined macro */
2419 tok_str_add_tok(&str
);
2421 tok_str_add(&str
, -1); /* simulate end of file */
2422 tok_str_add(&str
, 0);
2423 /* now evaluate C constant expression */
2424 macro_ptr
= str
.str
;
2428 tok_str_free(str
.str
);
2432 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2433 static void tok_print(int *str
)
2439 TOK_GET(t
, str
, cval
);
2442 printf(" %s", get_tok_str(t
, &cval
));
2448 /* parse after #define */
2449 static void parse_define(void)
2451 Sym
*s
, *first
, **ps
;
2452 int v
, t
, varg
, is_vaargs
, c
;
2457 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2458 /* XXX: should check if same macro (ANSI) */
2461 /* '(' must be just after macro definition for MACRO_FUNC */
2462 c
= file
->buf_ptr
[0];
2464 c
= handle_stray1(file
->buf_ptr
);
2469 while (tok
!= ')') {
2473 if (varg
== TOK_DOTS
) {
2474 varg
= TOK___VA_ARGS__
;
2476 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2480 if (varg
< TOK_IDENT
)
2481 error("badly punctuated parameter list");
2482 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2493 /* EOF testing necessary for '-D' handling */
2494 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2495 tok_str_add2(&str
, tok
, &tokc
);
2498 tok_str_add(&str
, 0);
2500 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2503 define_push(v
, t
, str
.str
, first
);
2506 /* XXX: use a token or a hash table to accelerate matching ? */
2507 static CachedInclude
*search_cached_include(TCCState
*s1
,
2508 int type
, const char *filename
)
2513 for(i
= 0;i
< s1
->nb_cached_includes
; i
++) {
2514 e
= s1
->cached_includes
[i
];
2515 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2521 static inline void add_cached_include(TCCState
*s1
, int type
,
2522 const char *filename
, int ifndef_macro
)
2526 if (search_cached_include(s1
, type
, filename
))
2529 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2531 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2535 strcpy(e
->filename
, filename
);
2536 e
->ifndef_macro
= ifndef_macro
;
2537 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2540 /* is_bof is true if first non space token at beginning of file */
2541 static void preprocess(int is_bof
)
2543 TCCState
*s1
= tcc_state
;
2544 int size
, i
, c
, n
, saved_parse_flags
;
2545 char buf
[1024], *q
, *p
;
2551 saved_parse_flags
= parse_flags
;
2552 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
2553 PARSE_FLAG_LINEFEED
;
2563 s
= define_find(tok
);
2564 /* undefine symbol by putting an invalid name */
2569 ch
= file
->buf_ptr
[0];
2570 /* XXX: incorrect if comments : use next_nomacro with a special mode */
2575 } else if (ch
== '\"') {
2578 /* XXX: better stray handling */
2581 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
2582 if ((q
- buf
) < sizeof(buf
) - 1)
2589 /* eat all spaces and comments after include */
2590 /* XXX: slightly incorrect */
2591 while (ch1
!= '\n' && ch1
!= CH_EOF
)
2595 /* computed #include : either we have only strings or
2596 we have anything enclosed in '<>' */
2599 if (tok
== TOK_STR
) {
2600 while (tok
!= TOK_LINEFEED
) {
2601 if (tok
!= TOK_STR
) {
2603 error("'#include' expects \"FILENAME\" or <FILENAME>");
2605 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
2611 while (tok
!= TOK_LINEFEED
) {
2612 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
2616 /* check syntax and remove '<>' */
2617 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
2618 goto include_syntax
;
2619 memmove(buf
, buf
+ 1, len
- 2);
2620 buf
[len
- 2] = '\0';
2625 e
= search_cached_include(s1
, c
, buf
);
2626 if (e
&& define_find(e
->ifndef_macro
)) {
2627 /* no need to parse the include because the 'ifndef macro'
2630 printf("%s: skipping %s\n", file
->filename
, buf
);
2634 /* first search in current dir if "header.h" */
2636 p
= strrchr(file
->filename
, '/');
2638 size
= p
+ 1 - file
->filename
;
2639 if (size
> sizeof(buf1
) - 1)
2640 size
= sizeof(buf1
) - 1;
2641 memcpy(buf1
, file
->filename
, size
);
2643 pstrcat(buf1
, sizeof(buf1
), buf
);
2644 f
= tcc_open(s1
, buf1
);
2648 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
2649 error("#include recursion too deep");
2650 /* now search in all the include paths */
2651 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
2652 for(i
= 0; i
< n
; i
++) {
2654 if (i
< s1
->nb_include_paths
)
2655 path
= s1
->include_paths
[i
];
2657 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
2658 pstrcpy(buf1
, sizeof(buf1
), path
);
2659 pstrcat(buf1
, sizeof(buf1
), "/");
2660 pstrcat(buf1
, sizeof(buf1
), buf
);
2661 f
= tcc_open(s1
, buf1
);
2665 error("include file '%s' not found", buf
);
2669 printf("%s: including %s\n", file
->filename
, buf1
);
2672 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
2673 /* push current file in stack */
2674 /* XXX: fix current line init */
2675 *s1
->include_stack_ptr
++ = file
;
2677 /* add include file debug info */
2679 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
2681 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
2682 ch
= file
->buf_ptr
[0];
2690 c
= expr_preprocess();
2696 if (tok
< TOK_IDENT
)
2697 error("invalid argument for '#if%sdef'", c
? "n" : "");
2701 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
2703 file
->ifndef_macro
= tok
;
2706 c
= (define_find(tok
) != 0) ^ c
;
2708 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
2709 error("memory full");
2710 *s1
->ifdef_stack_ptr
++ = c
;
2713 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2714 error("#else without matching #if");
2715 if (s1
->ifdef_stack_ptr
[-1] & 2)
2716 error("#else after #else");
2717 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
2720 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2721 error("#elif without matching #if");
2722 c
= s1
->ifdef_stack_ptr
[-1];
2724 error("#elif after #else");
2725 /* last #if/#elif expression was true: we skip */
2728 c
= expr_preprocess();
2729 s1
->ifdef_stack_ptr
[-1] = c
;
2739 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
2740 error("#endif without matching #if");
2741 s1
->ifdef_stack_ptr
--;
2742 /* '#ifndef macro' was at the start of file. Now we check if
2743 an '#endif' is exactly at the end of file */
2744 if (file
->ifndef_macro
&&
2745 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
2746 file
->ifndef_macro_saved
= file
->ifndef_macro
;
2747 /* need to set to zero to avoid false matches if another
2748 #ifndef at middle of file */
2749 file
->ifndef_macro
= 0;
2750 while (tok
!= TOK_LINEFEED
)
2752 tok_flags
|= TOK_FLAG_ENDIF
;
2758 if (tok
!= TOK_CINT
)
2760 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
2762 if (tok
!= TOK_LINEFEED
) {
2765 pstrcpy(file
->filename
, sizeof(file
->filename
),
2766 (char *)tokc
.cstr
->data
);
2772 ch
= file
->buf_ptr
[0];
2775 while (ch
!= '\n' && ch
!= CH_EOF
) {
2776 if ((q
- buf
) < sizeof(buf
) - 1)
2782 error("#error %s", buf
);
2784 warning("#warning %s", buf
);
2790 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
2791 /* '!' is ignored to allow C scripts. numbers are ignored
2792 to emulate cpp behaviour */
2794 error("invalid preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2798 /* ignore other preprocess commands or #! for C scripts */
2799 while (tok
!= TOK_LINEFEED
)
2802 parse_flags
= saved_parse_flags
;
2805 /* evaluate escape codes in a string. */
2806 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2821 case '0': case '1': case '2': case '3':
2822 case '4': case '5': case '6': case '7':
2823 /* at most three octal digits */
2828 n
= n
* 8 + c
- '0';
2832 n
= n
* 8 + c
- '0';
2837 goto add_char_nonext
;
2843 if (c
>= 'a' && c
<= 'f')
2845 else if (c
>= 'A' && c
<= 'F')
2855 goto add_char_nonext
;
2879 goto invalid_escape
;
2889 error("invalid escaped char");
2895 cstr_ccat(outstr
, c
);
2897 cstr_wccat(outstr
, c
);
2899 /* add a trailing '\0' */
2901 cstr_ccat(outstr
, '\0');
2903 cstr_wccat(outstr
, '\0');
2906 /* we use 64 bit numbers */
2909 /* bn = (bn << shift) | or_val */
2910 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2914 for(i
=0;i
<BN_SIZE
;i
++) {
2916 bn
[i
] = (v
<< shift
) | or_val
;
2917 or_val
= v
>> (32 - shift
);
2921 void bn_zero(unsigned int *bn
)
2924 for(i
=0;i
<BN_SIZE
;i
++) {
2929 /* parse number in null terminated string 'p' and return it in the
2931 void parse_number(const char *p
)
2933 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
2935 unsigned int bn
[BN_SIZE
];
2946 goto float_frac_parse
;
2947 } else if (t
== '0') {
2948 if (ch
== 'x' || ch
== 'X') {
2952 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2958 /* parse all digits. cannot check octal numbers at this stage
2959 because of floating point constants */
2961 if (ch
>= 'a' && ch
<= 'f')
2963 else if (ch
>= 'A' && ch
<= 'F')
2971 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2973 error("number too long");
2979 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2980 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2982 /* NOTE: strtox should support that for hexa numbers, but
2983 non ISOC99 libcs do not support it, so we prefer to do
2985 /* hexadecimal or binary floats */
2986 /* XXX: handle overflows */
2998 } else if (t
>= 'a') {
3000 } else if (t
>= 'A') {
3005 bn_lshift(bn
, shift
, t
);
3012 if (t
>= 'a' && t
<= 'f') {
3014 } else if (t
>= 'A' && t
<= 'F') {
3016 } else if (t
>= '0' && t
<= '9') {
3022 error("invalid digit");
3023 bn_lshift(bn
, shift
, t
);
3028 if (ch
!= 'p' && ch
!= 'P')
3035 } else if (ch
== '-') {
3039 if (ch
< '0' || ch
> '9')
3040 expect("exponent digits");
3041 while (ch
>= '0' && ch
<= '9') {
3042 exp_val
= exp_val
* 10 + ch
- '0';
3045 exp_val
= exp_val
* s
;
3047 /* now we can generate the number */
3048 /* XXX: should patch directly float number */
3049 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3050 d
= ldexp(d
, exp_val
- frac_bits
);
3055 /* float : should handle overflow */
3057 } else if (t
== 'L') {
3060 /* XXX: not large enough */
3061 tokc
.ld
= (long double)d
;
3067 /* decimal floats */
3069 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3074 while (ch
>= '0' && ch
<= '9') {
3075 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3081 if (ch
== 'e' || ch
== 'E') {
3082 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3086 if (ch
== '-' || ch
== '+') {
3087 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3092 if (ch
< '0' || ch
> '9')
3093 expect("exponent digits");
3094 while (ch
>= '0' && ch
<= '9') {
3095 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3107 tokc
.f
= strtof(token_buf
, NULL
);
3108 } else if (t
== 'L') {
3111 tokc
.ld
= strtold(token_buf
, NULL
);
3114 tokc
.d
= strtod(token_buf
, NULL
);
3118 unsigned long long n
, n1
;
3121 /* integer number */
3124 if (b
== 10 && *q
== '0') {
3131 /* no need for checks except for base 10 / 8 errors */
3134 } else if (t
>= 'a') {
3136 } else if (t
>= 'A') {
3141 error("invalid digit");
3145 /* detect overflow */
3146 /* XXX: this test is not reliable */
3148 error("integer constant overflow");
3151 /* XXX: not exactly ANSI compliant */
3152 if ((n
& 0xffffffff00000000LL
) != 0) {
3157 } else if (n
> 0x7fffffff) {
3168 error("three 'l's in integer constant");
3171 if (tok
== TOK_CINT
)
3173 else if (tok
== TOK_CUINT
)
3177 } else if (t
== 'U') {
3179 error("two 'u's in integer constant");
3181 if (tok
== TOK_CINT
)
3183 else if (tok
== TOK_CLLONG
)
3190 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3198 #define PARSE2(c1, tok1, c2, tok2) \
3209 /* return next token without macro substitution */
3210 static inline void next_nomacro1(void)
3230 /* first look if it is in fact an end of buffer */
3231 if (p
>= file
->buf_end
) {
3235 if (p
>= file
->buf_end
)
3248 TCCState
*s1
= tcc_state
;
3249 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3251 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3252 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3253 /* no include left : end of file. */
3256 /* pop include file */
3258 /* test if previous '#endif' was after a #ifdef at
3260 if (tok_flags
& TOK_FLAG_ENDIF
) {
3262 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3264 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3265 file
->ifndef_macro_saved
);
3268 /* add end of include file debug info */
3270 put_stabd(N_EINCL
, 0, 0);
3272 /* pop include stack */
3274 s1
->include_stack_ptr
--;
3275 file
= *s1
->include_stack_ptr
;
3283 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3287 tok_flags
|= TOK_FLAG_BOL
;
3296 if ((tok_flags
& TOK_FLAG_BOL
) &&
3297 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3299 preprocess(tok_flags
& TOK_FLAG_BOF
);
3305 tok
= TOK_TWOSHARPS
;
3312 case 'a': case 'b': case 'c': case 'd':
3313 case 'e': case 'f': case 'g': case 'h':
3314 case 'i': case 'j': case 'k': case 'l':
3315 case 'm': case 'n': case 'o': case 'p':
3316 case 'q': case 'r': case 's': case 't':
3317 case 'u': case 'v': case 'w': case 'x':
3319 case 'A': case 'B': case 'C': case 'D':
3320 case 'E': case 'F': case 'G': case 'H':
3321 case 'I': case 'J': case 'K':
3322 case 'M': case 'N': case 'O': case 'P':
3323 case 'Q': case 'R': case 'S': case 'T':
3324 case 'U': case 'V': case 'W': case 'X':
3330 h
= TOK_HASH_FUNC(h
, c
);
3334 if (!isidnum_table
[c
])
3336 h
= TOK_HASH_FUNC(h
, c
);
3343 /* fast case : no stray found, so we have the full token
3344 and we have already hashed it */
3346 h
&= (TOK_HASH_SIZE
- 1);
3347 pts
= &hash_ident
[h
];
3352 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3354 pts
= &(ts
->hash_next
);
3356 ts
= tok_alloc_new(pts
, p1
, len
);
3360 cstr_reset(&tokcstr
);
3363 cstr_ccat(&tokcstr
, *p1
);
3369 while (isidnum_table
[c
]) {
3370 cstr_ccat(&tokcstr
, c
);
3373 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3379 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3381 goto parse_ident_fast
;
3384 if (c
== '\'' || c
== '\"') {
3388 cstr_reset(&tokcstr
);
3389 cstr_ccat(&tokcstr
, 'L');
3390 goto parse_ident_slow
;
3394 case '0': case '1': case '2': case '3':
3395 case '4': case '5': case '6': case '7':
3398 cstr_reset(&tokcstr
);
3399 /* after the first digit, accept digits, alpha, '.' or sign if
3400 prefixed by 'eEpP' */
3404 cstr_ccat(&tokcstr
, c
);
3406 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3407 ((c
== '+' || c
== '-') &&
3408 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3411 /* We add a trailing '\0' to ease parsing */
3412 cstr_ccat(&tokcstr
, '\0');
3413 tokc
.cstr
= &tokcstr
;
3417 /* special dot handling because it can also start a number */
3420 cstr_reset(&tokcstr
);
3421 cstr_ccat(&tokcstr
, '.');
3423 } else if (c
== '.') {
3443 /* parse the string */
3445 p
= parse_pp_string(p
, sep
, &str
);
3446 cstr_ccat(&str
, '\0');
3448 /* eval the escape (should be done as TOK_PPNUM) */
3449 cstr_reset(&tokcstr
);
3450 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3455 /* XXX: make it portable */
3459 char_size
= sizeof(int);
3460 if (tokcstr
.size
<= char_size
)
3461 error("empty character constant");
3462 if (tokcstr
.size
> 2 * char_size
)
3463 warning("multi-character character constant");
3465 tokc
.i
= *(int8_t *)tokcstr
.data
;
3468 tokc
.i
= *(int *)tokcstr
.data
;
3472 tokc
.cstr
= &tokcstr
;
3486 } else if (c
== '<') {
3504 } else if (c
== '>') {
3522 } else if (c
== '=') {
3535 } else if (c
== '=') {
3548 } else if (c
== '=') {
3561 } else if (c
== '=') {
3564 } else if (c
== '>') {
3572 PARSE2('!', '!', '=', TOK_NE
)
3573 PARSE2('=', '=', '=', TOK_EQ
)
3574 PARSE2('*', '*', '=', TOK_A_MUL
)
3575 PARSE2('%', '%', '=', TOK_A_MOD
)
3576 PARSE2('^', '^', '=', TOK_A_XOR
)
3578 /* comments or operator */
3582 p
= parse_comment(p
);
3584 } else if (c
== '/') {
3585 p
= parse_line_comment(p
);
3587 } else if (c
== '=') {
3607 case '$': /* only used in assembler */
3612 error("unrecognized character \\x%02x", c
);
3617 #if defined(PARSE_DEBUG)
3618 printf("token = %s\n", get_tok_str(tok
, &tokc
));
3622 /* return next token without macro substitution. Can read input from
3624 static void next_nomacro(void)
3630 TOK_GET(tok
, macro_ptr
, tokc
);
3631 if (tok
== TOK_LINENUM
) {
3632 file
->line_num
= tokc
.i
;
3641 /* substitute args in macro_str and return allocated string */
3642 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
3644 int *st
, last_tok
, t
, notfirst
;
3653 TOK_GET(t
, macro_str
, cval
);
3658 TOK_GET(t
, macro_str
, cval
);
3661 s
= sym_find2(args
, t
);
3668 cstr_ccat(&cstr
, ' ');
3669 TOK_GET(t
, st
, cval
);
3670 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
3673 cstr_ccat(&cstr
, '\0');
3675 printf("stringize: %s\n", (char *)cstr
.data
);
3679 tok_str_add2(&str
, TOK_STR
, &cval
);
3682 tok_str_add2(&str
, t
, &cval
);
3684 } else if (t
>= TOK_IDENT
) {
3685 s
= sym_find2(args
, t
);
3688 /* if '##' is present before or after, no arg substitution */
3689 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
3690 /* special case for var arg macros : ## eats the
3691 ',' if empty VA_ARGS variable. */
3692 /* XXX: test of the ',' is not 100%
3693 reliable. should fix it to avoid security
3695 if (gnu_ext
&& s
->type
.t
&&
3696 last_tok
== TOK_TWOSHARPS
&&
3697 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
3699 /* suppress ',' '##' */
3702 /* suppress '##' and add variable */
3710 TOK_GET(t1
, st
, cval
);
3713 tok_str_add2(&str
, t1
, &cval
);
3717 /* NOTE: the stream cannot be read when macro
3718 substituing an argument */
3719 macro_subst(&str
, nested_list
, st
, 0);
3722 tok_str_add(&str
, t
);
3725 tok_str_add2(&str
, t
, &cval
);
3729 tok_str_add(&str
, 0);
3733 static char const ab_month_name
[12][4] =
3735 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3736 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3739 /* do macro substitution of current token with macro 's' and add
3740 result to (tok_str,tok_len). 'nested_list' is the list of all
3741 macros we got inside to avoid recursing. Return non zero if no
3742 substitution needs to be done */
3743 static int macro_subst_tok(TokenString
*tok_str
,
3744 Sym
**nested_list
, Sym
*s
, int can_read_stream
)
3746 Sym
*args
, *sa
, *sa1
;
3747 int mstr_allocated
, parlevel
, *mstr
, t
;
3753 /* if symbol is a macro, prepare substitution */
3755 /* special macros */
3756 if (tok
== TOK___LINE__
) {
3757 cval
.i
= file
->line_num
;
3758 tok_str_add2(tok_str
, TOK_CINT
, &cval
);
3759 } else if (tok
== TOK___FILE__
) {
3760 cstrval
= file
->filename
;
3762 tok_str_add2(tok_str
, TOK_STR
, &cval
);
3763 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3769 tm
= localtime(&ti
);
3770 if (tok
== TOK___DATE__
) {
3771 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3772 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3774 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3775 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3780 cstr_cat(&cstr
, cstrval
);
3781 cstr_ccat(&cstr
, '\0');
3783 tok_str_add2(tok_str
, TOK_STR
, &cval
);
3788 if (s
->type
.t
== MACRO_FUNC
) {
3789 /* NOTE: we do not use next_nomacro to avoid eating the
3790 next token. XXX: find better solution */
3793 if (t
== 0 && can_read_stream
) {
3794 /* end of macro stream: we must look at the token
3795 after in the file */
3801 /* XXX: incorrect with comments */
3802 ch
= file
->buf_ptr
[0];
3803 while (is_space(ch
) || ch
== '\n')
3807 if (t
!= '(') /* no macro subst */
3810 /* argument macro */
3815 /* NOTE: empty args are allowed, except if no args */
3817 /* handle '()' case */
3818 if (!args
&& !sa
&& tok
== ')')
3821 error("macro '%s' used with too many args",
3822 get_tok_str(s
->v
, 0));
3825 /* NOTE: non zero sa->t indicates VA_ARGS */
3826 while ((parlevel
> 0 ||
3828 (tok
!= ',' || sa
->type
.t
))) &&
3832 else if (tok
== ')')
3834 tok_str_add2(&str
, tok
, &tokc
);
3837 tok_str_add(&str
, 0);
3838 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (int)str
.str
);
3841 /* special case for gcc var args: add an empty
3842 var arg argument if it is omitted */
3843 if (sa
&& sa
->type
.t
&& gnu_ext
)
3853 error("macro '%s' used with too few args",
3854 get_tok_str(s
->v
, 0));
3857 /* now subst each arg */
3858 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3863 tok_str_free((int *)sa
->c
);
3869 sym_push2(nested_list
, s
->v
, 0, 0);
3870 macro_subst(tok_str
, nested_list
, mstr
, 1);
3871 /* pop nested defined symbol */
3873 *nested_list
= sa1
->prev
;
3881 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
3882 return the resulting string (which must be freed). */
3883 static inline int *macro_twosharps(const int *macro_str
)
3886 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
3888 const char *p1
, *p2
;
3890 TokenString macro_str1
;
3893 start_macro_ptr
= macro_str
;
3894 /* we search the first '##' */
3896 macro_ptr1
= macro_str
;
3897 TOK_GET(t
, macro_str
, cval
);
3898 /* nothing more to do if end of string */
3901 if (*macro_str
== TOK_TWOSHARPS
)
3905 /* we saw '##', so we need more processing to handle it */
3907 tok_str_new(¯o_str1
);
3911 /* add all tokens seen so far */
3912 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
3913 TOK_GET(t
, ptr
, cval
);
3914 tok_str_add2(¯o_str1
, t
, &cval
);
3916 saved_macro_ptr
= macro_ptr
;
3917 /* XXX: get rid of the use of macro_ptr here */
3918 macro_ptr
= (int *)macro_str
;
3920 while (*macro_ptr
== TOK_TWOSHARPS
) {
3922 macro_ptr1
= macro_ptr
;
3925 TOK_GET(t
, macro_ptr
, cval
);
3926 /* We concatenate the two tokens if we have an
3927 identifier or a preprocessing number */
3929 p1
= get_tok_str(tok
, &tokc
);
3930 cstr_cat(&cstr
, p1
);
3931 p2
= get_tok_str(t
, &cval
);
3932 cstr_cat(&cstr
, p2
);
3933 cstr_ccat(&cstr
, '\0');
3935 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
3936 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
3937 if (tok
== TOK_PPNUM
) {
3938 /* if number, then create a number token */
3939 /* NOTE: no need to allocate because
3940 tok_str_add2() does it */
3943 /* if identifier, we must do a test to
3944 validate we have a correct identifier */
3945 if (t
== TOK_PPNUM
) {
3955 if (!isnum(c
) && !isid(c
))
3959 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
3960 tok
= ts
->tok
; /* modify current token */
3963 const char *str
= cstr
.data
;
3964 const unsigned char *q
;
3966 /* we look for a valid token */
3967 /* XXX: do more extensive checks */
3968 if (!strcmp(str
, ">>=")) {
3970 } else if (!strcmp(str
, "<<=")) {
3972 } else if (strlen(str
) == 2) {
3973 /* search in two bytes table */
3978 if (q
[0] == str
[0] && q
[1] == str
[1])
3985 /* NOTE: because get_tok_str use a static buffer,
3988 p1
= get_tok_str(tok
, &tokc
);
3989 cstr_cat(&cstr
, p1
);
3990 cstr_ccat(&cstr
, '\0');
3991 p2
= get_tok_str(t
, &cval
);
3992 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
3993 /* cannot merge tokens: just add them separately */
3994 tok_str_add2(¯o_str1
, tok
, &tokc
);
3995 /* XXX: free associated memory ? */
4002 tok_str_add2(¯o_str1
, tok
, &tokc
);
4007 macro_ptr
= (int *)saved_macro_ptr
;
4009 tok_str_add(¯o_str1
, 0);
4010 return macro_str1
.str
;
4014 /* do macro substitution of macro_str and add result to
4015 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4016 inside to avoid recursing. */
4017 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
4018 const int *macro_str
, int can_read_stream
)
4021 int *saved_macro_ptr
, *macro_str1
;
4026 /* first scan for '##' operator handling */
4028 macro_str1
= macro_twosharps(ptr
);
4032 /* NOTE: ptr == NULL can only happen if tokens are read from
4033 file stream due to a macro function call */
4036 TOK_GET(t
, ptr
, cval
);
4041 /* if nested substitution, do nothing */
4042 if (sym_find2(*nested_list
, t
))
4044 saved_macro_ptr
= macro_ptr
;
4045 macro_ptr
= (int *)ptr
;
4047 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
4048 ptr
= (int *)macro_ptr
;
4049 macro_ptr
= saved_macro_ptr
;
4054 tok_str_add2(tok_str
, t
, &cval
);
4058 tok_str_free(macro_str1
);
4061 /* return next token with macro substitution */
4062 static void next(void)
4064 Sym
*nested_list
, *s
;
4070 /* if not reading from macro substituted string, then try
4071 to substitute macros */
4072 if (tok
>= TOK_IDENT
&&
4073 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4074 s
= define_find(tok
);
4076 /* we have a macro: we try to substitute */
4079 if (macro_subst_tok(&str
, &nested_list
, s
, 1) == 0) {
4080 /* substitution done, NOTE: maybe empty */
4081 tok_str_add(&str
, 0);
4082 macro_ptr
= str
.str
;
4083 macro_ptr_allocated
= str
.str
;
4090 /* end of macro or end of unget buffer */
4091 if (unget_buffer_enabled
) {
4092 macro_ptr
= unget_saved_macro_ptr
;
4093 unget_buffer_enabled
= 0;
4095 /* end of macro string: free it */
4096 tok_str_free(macro_ptr_allocated
);
4103 /* convert preprocessor tokens into C tokens */
4104 if (tok
== TOK_PPNUM
&&
4105 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4106 parse_number((char *)tokc
.cstr
->data
);
4110 /* push back current token and set current token to 'last_tok'. Only
4111 identifier case handled for labels. */
4112 static inline void unget_tok(int last_tok
)
4116 unget_saved_macro_ptr
= macro_ptr
;
4117 unget_buffer_enabled
= 1;
4118 q
= unget_saved_buffer
;
4121 n
= tok_ext_size(tok
) - 1;
4124 *q
= 0; /* end of token string */
4129 void swap(int *p
, int *q
)
4137 void vsetc(CType
*type
, int r
, CValue
*vc
)
4141 if (vtop
>= vstack
+ VSTACK_SIZE
)
4142 error("memory full");
4143 /* cannot let cpu flags if other instruction are generated. Also
4144 avoid leaving VT_JMP anywhere except on the top of the stack
4145 because it would complicate the code generator. */
4146 if (vtop
>= vstack
) {
4147 v
= vtop
->r
& VT_VALMASK
;
4148 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4154 vtop
->r2
= VT_CONST
;
4158 /* push integer constant */
4163 vsetc(&int_type
, VT_CONST
, &cval
);
4166 /* Return a static symbol pointing to a section */
4167 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4168 unsigned long offset
, unsigned long size
)
4174 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4175 sym
->type
.ref
= type
->ref
;
4176 sym
->r
= VT_CONST
| VT_SYM
;
4177 put_extern_sym(sym
, sec
, offset
, size
);
4181 /* push a reference to a section offset by adding a dummy symbol */
4182 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4187 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4188 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4191 /* define a new external reference to a symbol 'v' of type 'u' */
4192 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4198 /* push forward reference */
4199 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4200 s
->type
.ref
= type
->ref
;
4201 s
->r
= r
| VT_CONST
| VT_SYM
;
4206 /* define a new external reference to a symbol 'v' of type 'u' */
4207 static Sym
*external_sym(int v
, CType
*type
, int r
)
4213 /* push forward reference */
4214 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4215 s
->type
.t
|= VT_EXTERN
;
4217 if (!is_compatible_types(&s
->type
, type
))
4218 error("incompatible types for redefinition of '%s'",
4219 get_tok_str(v
, NULL
));
4224 /* push a reference to global symbol v */
4225 static void vpush_global_sym(CType
*type
, int v
)
4230 sym
= external_global_sym(v
, type
, 0);
4232 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4236 void vset(CType
*type
, int r
, int v
)
4241 vsetc(type
, r
, &cval
);
4244 void vseti(int r
, int v
)
4260 void vpushv(SValue
*v
)
4262 if (vtop
>= vstack
+ VSTACK_SIZE
)
4263 error("memory full");
4273 /* save r to the memory stack, and mark it as being free */
4274 void save_reg(int r
)
4276 int l
, saved
, size
, align
;
4280 /* modify all stack values */
4283 for(p
=vstack
;p
<=vtop
;p
++) {
4284 if ((p
->r
& VT_VALMASK
) == r
||
4285 (p
->r2
& VT_VALMASK
) == r
) {
4286 /* must save value on stack if not already done */
4288 /* NOTE: must reload 'r' because r might be equal to r2 */
4289 r
= p
->r
& VT_VALMASK
;
4290 /* store register in the stack */
4292 if ((p
->r
& VT_LVAL
) ||
4293 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4295 size
= type_size(type
, &align
);
4296 loc
= (loc
- size
) & -align
;
4297 sv
.type
.t
= type
->t
;
4298 sv
.r
= VT_LOCAL
| VT_LVAL
;
4301 #ifdef TCC_TARGET_I386
4302 /* x86 specific: need to pop fp register ST0 if saved */
4303 if (r
== TREG_ST0
) {
4304 o(0xd9dd); /* fstp %st(1) */
4307 /* special long long case */
4308 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4315 /* mark that stack entry as being saved on the stack */
4316 if (p
->r
& VT_LVAL
) {
4317 /* also clear the bounded flag because the
4318 relocation address of the function was stored in
4320 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4322 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4330 /* find a free register of class 'rc'. If none, save one register */
4336 /* find a free register */
4337 for(r
=0;r
<NB_REGS
;r
++) {
4338 if (reg_classes
[r
] & rc
) {
4339 for(p
=vstack
;p
<=vtop
;p
++) {
4340 if ((p
->r
& VT_VALMASK
) == r
||
4341 (p
->r2
& VT_VALMASK
) == r
)
4349 /* no register left : free the first one on the stack (VERY
4350 IMPORTANT to start from the bottom to ensure that we don't
4351 spill registers used in gen_opi()) */
4352 for(p
=vstack
;p
<=vtop
;p
++) {
4353 r
= p
->r
& VT_VALMASK
;
4354 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4356 /* also look at second register (if long long) */
4357 r
= p
->r2
& VT_VALMASK
;
4358 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4364 /* Should never comes here */
4368 /* save registers up to (vtop - n) stack entry */
4369 void save_regs(int n
)
4374 for(p
= vstack
;p
<= p1
; p
++) {
4375 r
= p
->r
& VT_VALMASK
;
4382 /* move register 's' to 'r', and flush previous value of r to memory
4384 void move_reg(int r
, int s
)
4397 /* get address of vtop (vtop MUST BE an lvalue) */
4400 vtop
->r
&= ~VT_LVAL
;
4401 /* tricky: if saved lvalue, then we can go back to lvalue */
4402 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4403 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4406 #ifdef CONFIG_TCC_BCHECK
4407 /* generate lvalue bound code */
4413 vtop
->r
&= ~VT_MUSTBOUND
;
4414 /* if lvalue, then use checking code before dereferencing */
4415 if (vtop
->r
& VT_LVAL
) {
4416 /* if not VT_BOUNDED value, then make one */
4417 if (!(vtop
->r
& VT_BOUNDED
)) {
4418 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4419 /* must save type because we must set it to int to get pointer */
4421 vtop
->type
.t
= VT_INT
;
4424 gen_bounded_ptr_add();
4425 vtop
->r
|= lval_type
;
4428 /* then check for dereferencing */
4429 gen_bounded_ptr_deref();
4434 /* store vtop a register belonging to class 'rc'. lvalues are
4435 converted to values. Cannot be used if cannot be converted to
4436 register value (such as structures). */
4439 int r
, r2
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4440 unsigned long long ll
;
4442 /* NOTE: get_reg can modify vstack[] */
4443 if (vtop
->type
.t
& VT_BITFIELD
) {
4444 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4445 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4446 /* remove bit field info to avoid loops */
4447 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4448 /* generate shifts */
4449 vpushi(32 - (bit_pos
+ bit_size
));
4451 vpushi(32 - bit_size
);
4452 /* NOTE: transformed to SHR if unsigned */
4456 if (is_float(vtop
->type
.t
) &&
4457 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4460 unsigned long offset
;
4462 /* XXX: unify with initializers handling ? */
4463 /* CPUs usually cannot use float constants, so we store them
4464 generically in data segment */
4465 size
= type_size(&vtop
->type
, &align
);
4466 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
4467 data_section
->data_offset
= offset
;
4468 /* XXX: not portable yet */
4469 ptr
= section_ptr_add(data_section
, size
);
4472 ptr
[i
] = vtop
->c
.tab
[i
];
4473 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
4474 vtop
->r
|= VT_LVAL
| VT_SYM
;
4478 #ifdef CONFIG_TCC_BCHECK
4479 if (vtop
->r
& VT_MUSTBOUND
)
4483 r
= vtop
->r
& VT_VALMASK
;
4484 /* need to reload if:
4486 - lvalue (need to dereference pointer)
4487 - already a register, but not in the right class */
4488 if (r
>= VT_CONST
||
4489 (vtop
->r
& VT_LVAL
) ||
4490 !(reg_classes
[r
] & rc
) ||
4491 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
4492 !(reg_classes
[vtop
->r2
] & rc
))) {
4494 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
4495 /* two register type load : expand to two words
4497 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4500 vtop
->c
.ui
= ll
; /* first word */
4502 vtop
->r
= r
; /* save register value */
4503 vpushi(ll
>> 32); /* second word */
4504 } else if (r
>= VT_CONST
||
4505 (vtop
->r
& VT_LVAL
)) {
4506 /* load from memory */
4509 vtop
[-1].r
= r
; /* save register value */
4510 /* increment pointer to get second word */
4511 vtop
->type
.t
= VT_INT
;
4517 /* move registers */
4520 vtop
[-1].r
= r
; /* save register value */
4521 vtop
->r
= vtop
[-1].r2
;
4523 /* allocate second register */
4530 /* write second register */
4532 } else if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
4534 /* lvalue of scalar type : need to use lvalue type
4535 because of possible cast */
4538 /* compute memory access type */
4539 if (vtop
->r
& VT_LVAL_BYTE
)
4541 else if (vtop
->r
& VT_LVAL_SHORT
)
4543 if (vtop
->r
& VT_LVAL_UNSIGNED
)
4547 /* restore wanted type */
4550 /* one register type load */
4559 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
4560 void gv2(int rc1
, int rc2
)
4564 /* generate more generic register first. But VT_JMP or VT_CMP
4565 values must be generated first in all cases to avoid possible
4567 v
= vtop
[0].r
& VT_VALMASK
;
4568 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
4573 /* test if reload is needed for first register */
4574 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
4584 /* test if reload is needed for first register */
4585 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
4591 /* expand long long on stack in two int registers */
4596 u
= vtop
->type
.t
& VT_UNSIGNED
;
4599 vtop
[0].r
= vtop
[-1].r2
;
4600 vtop
[0].r2
= VT_CONST
;
4601 vtop
[-1].r2
= VT_CONST
;
4602 vtop
[0].type
.t
= VT_INT
| u
;
4603 vtop
[-1].type
.t
= VT_INT
| u
;
4606 /* build a long long from two ints */
4609 gv2(RC_INT
, RC_INT
);
4610 vtop
[-1].r2
= vtop
[0].r
;
4611 vtop
[-1].type
.t
= t
;
4615 /* rotate n first stack elements to the bottom
4616 I1 ... In -> I2 ... In I1 [top is right]
4624 for(i
=-n
+1;i
!=0;i
++)
4625 vtop
[i
] = vtop
[i
+1];
4629 /* rotate n first stack elements to the top
4630 I1 ... In -> In I1 ... I(n-1) [top is right]
4638 for(i
= 0;i
< n
- 1; i
++)
4639 vtop
[-i
] = vtop
[-i
- 1];
4643 /* pop stack value */
4647 v
= vtop
->r
& VT_VALMASK
;
4648 #ifdef TCC_TARGET_I386
4649 /* for x86, we need to pop the FP stack */
4650 if (v
== TREG_ST0
&& !nocode_wanted
) {
4651 o(0xd9dd); /* fstp %st(1) */
4654 if (v
== VT_JMP
|| v
== VT_JMPI
) {
4655 /* need to put correct jump if && or || without test */
4661 /* convert stack entry to register and duplicate its value in another
4669 if ((t
& VT_BTYPE
) == VT_LLONG
) {
4676 /* stack: H L L1 H1 */
4684 /* duplicate value */
4695 load(r1
, &sv
); /* move r to r1 */
4697 /* duplicates value */
4702 /* generate CPU independent (unsigned) long long operations */
4703 void gen_opl(int op
)
4705 int t
, a
, b
, op1
, c
, i
;
4712 func
= TOK___divdi3
;
4715 func
= TOK___udivdi3
;
4718 func
= TOK___moddi3
;
4721 func
= TOK___umoddi3
;
4723 /* call generic long long function */
4724 vpush_global_sym(&func_old_type
, func
);
4729 vtop
->r2
= REG_LRET
;
4742 /* stack: L1 H1 L2 H2 */
4747 vtop
[-2] = vtop
[-3];
4750 /* stack: H1 H2 L1 L2 */
4756 /* stack: H1 H2 L1 L2 ML MH */
4759 /* stack: ML MH H1 H2 L1 L2 */
4763 /* stack: ML MH H1 L2 H2 L1 */
4768 /* stack: ML MH M1 M2 */
4771 } else if (op
== '+' || op
== '-') {
4772 /* XXX: add non carry method too (for MIPS or alpha) */
4778 /* stack: H1 H2 (L1 op L2) */
4781 gen_op(op1
+ 1); /* TOK_xxxC2 */
4784 /* stack: H1 H2 (L1 op L2) */
4787 /* stack: (L1 op L2) H1 H2 */
4789 /* stack: (L1 op L2) (H1 op H2) */
4797 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
4798 t
= vtop
[-1].type
.t
;
4802 /* stack: L H shift */
4804 /* constant: simpler */
4805 /* NOTE: all comments are for SHL. the other cases are
4806 done by swaping words */
4817 if (op
!= TOK_SAR
) {
4850 /* XXX: should provide a faster fallback on x86 ? */
4853 func
= TOK___sardi3
;
4856 func
= TOK___shrdi3
;
4859 func
= TOK___shldi3
;
4865 /* compare operations */
4871 /* stack: L1 H1 L2 H2 */
4873 vtop
[-1] = vtop
[-2];
4875 /* stack: L1 L2 H1 H2 */
4878 /* when values are equal, we need to compare low words. since
4879 the jump is inverted, we invert the test too. */
4882 else if (op1
== TOK_GT
)
4884 else if (op1
== TOK_ULT
)
4886 else if (op1
== TOK_UGT
)
4891 if (op1
!= TOK_NE
) {
4895 /* generate non equal test */
4896 /* XXX: NOT PORTABLE yet */
4900 #ifdef TCC_TARGET_I386
4901 b
= psym(0x850f, 0);
4903 error("not implemented");
4907 /* compare low. Always unsigned */
4911 else if (op1
== TOK_LE
)
4913 else if (op1
== TOK_GT
)
4915 else if (op1
== TOK_GE
)
4925 /* handle integer constant optimizations and various machine
4927 void gen_opic(int op
)
4934 /* currently, we cannot do computations with forward symbols */
4935 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4936 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4940 case '+': v1
->c
.i
+= fc
; break;
4941 case '-': v1
->c
.i
-= fc
; break;
4942 case '&': v1
->c
.i
&= fc
; break;
4943 case '^': v1
->c
.i
^= fc
; break;
4944 case '|': v1
->c
.i
|= fc
; break;
4945 case '*': v1
->c
.i
*= fc
; break;
4952 /* if division by zero, generate explicit division */
4955 error("division by zero in constant");
4959 default: v1
->c
.i
/= fc
; break;
4960 case '%': v1
->c
.i
%= fc
; break;
4961 case TOK_UDIV
: v1
->c
.i
= (unsigned)v1
->c
.i
/ fc
; break;
4962 case TOK_UMOD
: v1
->c
.i
= (unsigned)v1
->c
.i
% fc
; break;
4965 case TOK_SHL
: v1
->c
.i
<<= fc
; break;
4966 case TOK_SHR
: v1
->c
.i
= (unsigned)v1
->c
.i
>> fc
; break;
4967 case TOK_SAR
: v1
->c
.i
>>= fc
; break;
4969 case TOK_ULT
: v1
->c
.i
= (unsigned)v1
->c
.i
< (unsigned)fc
; break;
4970 case TOK_UGE
: v1
->c
.i
= (unsigned)v1
->c
.i
>= (unsigned)fc
; break;
4971 case TOK_EQ
: v1
->c
.i
= v1
->c
.i
== fc
; break;
4972 case TOK_NE
: v1
->c
.i
= v1
->c
.i
!= fc
; break;
4973 case TOK_ULE
: v1
->c
.i
= (unsigned)v1
->c
.i
<= (unsigned)fc
; break;
4974 case TOK_UGT
: v1
->c
.i
= (unsigned)v1
->c
.i
> (unsigned)fc
; break;
4975 case TOK_LT
: v1
->c
.i
= v1
->c
.i
< fc
; break;
4976 case TOK_GE
: v1
->c
.i
= v1
->c
.i
>= fc
; break;
4977 case TOK_LE
: v1
->c
.i
= v1
->c
.i
<= fc
; break;
4978 case TOK_GT
: v1
->c
.i
= v1
->c
.i
> fc
; break;
4980 case TOK_LAND
: v1
->c
.i
= v1
->c
.i
&& fc
; break;
4981 case TOK_LOR
: v1
->c
.i
= v1
->c
.i
|| fc
; break;
4987 /* if commutative ops, put c2 as constant */
4988 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
4989 op
== '|' || op
== '*')) {
4994 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
4997 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
4998 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
5004 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
5005 /* try to use shifts instead of muls or divs */
5006 if (fc
> 0 && (fc
& (fc
- 1)) == 0) {
5015 else if (op
== TOK_PDIV
)
5021 } else if (c2
&& (op
== '+' || op
== '-') &&
5022 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5023 (VT_CONST
| VT_SYM
)) {
5024 /* symbol + constant case */
5031 if (!nocode_wanted
) {
5032 /* call low level op generator */
5041 /* generate a floating point operation with constant propagation */
5042 void gen_opif(int op
)
5050 /* currently, we cannot do computations with forward symbols */
5051 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5052 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5054 if (v1
->type
.t
== VT_FLOAT
) {
5057 } else if (v1
->type
.t
== VT_DOUBLE
) {
5065 /* NOTE: we only do constant propagation if finite number (not
5066 NaN or infinity) (ANSI spec) */
5067 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5071 case '+': f1
+= f2
; break;
5072 case '-': f1
-= f2
; break;
5073 case '*': f1
*= f2
; break;
5077 error("division by zero in constant");
5082 /* XXX: also handles tests ? */
5086 /* XXX: overflow test ? */
5087 if (v1
->type
.t
== VT_FLOAT
) {
5089 } else if (v1
->type
.t
== VT_DOUBLE
) {
5097 if (!nocode_wanted
) {
5105 static int pointed_size(CType
*type
)
5108 return type_size(pointed_type(type
), &align
);
5111 static inline int is_null_pointer(SValue
*p
)
5113 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5115 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5116 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5119 static inline int is_integer_btype(int bt
)
5121 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5122 bt
== VT_INT
|| bt
== VT_LLONG
);
5125 /* check types for comparison or substraction of pointers */
5126 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5128 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5131 /* null pointers are accepted for all comparisons as gcc */
5132 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5136 bt1
= type1
->t
& VT_BTYPE
;
5137 bt2
= type2
->t
& VT_BTYPE
;
5138 /* accept comparison between pointer and integer with a warning */
5139 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5140 warning("comparison between pointer and integer");
5144 /* both must be pointers or implicit function pointers */
5145 if (bt1
== VT_PTR
) {
5146 type1
= pointed_type(type1
);
5147 } else if (bt1
!= VT_FUNC
)
5148 goto invalid_operands
;
5150 if (bt2
== VT_PTR
) {
5151 type2
= pointed_type(type2
);
5152 } else if (bt2
!= VT_FUNC
) {
5154 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5156 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5157 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5161 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5162 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5163 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5164 /* gcc-like error if '-' is used */
5166 goto invalid_operands
;
5168 warning("comparison of distinct pointer types lacks a cast");
5172 /* generic gen_op: handles types problems */
5175 int u
, t1
, t2
, bt1
, bt2
, t
;
5178 t1
= vtop
[-1].type
.t
;
5179 t2
= vtop
[0].type
.t
;
5180 bt1
= t1
& VT_BTYPE
;
5181 bt2
= t2
& VT_BTYPE
;
5183 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5184 /* at least one operand is a pointer */
5185 /* relationnal op: must be both pointers */
5186 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5187 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5188 /* pointers are handled are unsigned */
5189 t
= VT_INT
| VT_UNSIGNED
;
5192 /* if both pointers, then it must be the '-' op */
5193 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5195 error("cannot use pointers here");
5196 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5197 /* XXX: check that types are compatible */
5198 u
= pointed_size(&vtop
[-1].type
);
5200 /* set to integer type */
5201 vtop
->type
.t
= VT_INT
;
5205 /* exactly one pointer : must be '+' or '-'. */
5206 if (op
!= '-' && op
!= '+')
5207 error("cannot use pointers here");
5208 /* Put pointer as first operand */
5209 if (bt2
== VT_PTR
) {
5213 type1
= vtop
[-1].type
;
5214 /* XXX: cast to int ? (long long case) */
5215 vpushi(pointed_size(&vtop
[-1].type
));
5217 #ifdef CONFIG_TCC_BCHECK
5218 /* if evaluating constant expression, no code should be
5219 generated, so no bound check */
5220 if (do_bounds_check
&& !const_wanted
) {
5221 /* if bounded pointers, we generate a special code to
5228 gen_bounded_ptr_add();
5234 /* put again type if gen_opic() swaped operands */
5237 } else if (is_float(bt1
) || is_float(bt2
)) {
5238 /* compute bigger type and do implicit casts */
5239 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5241 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5246 /* floats can only be used for a few operations */
5247 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5248 (op
< TOK_ULT
|| op
> TOK_GT
))
5249 error("invalid operands for binary operation");
5251 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5252 /* cast to biggest op */
5254 /* convert to unsigned if it does not fit in a long long */
5255 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5256 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5260 /* integer operations */
5262 /* convert to unsigned if it does not fit in an integer */
5263 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5264 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5267 /* XXX: currently, some unsigned operations are explicit, so
5268 we modify them here */
5269 if (t
& VT_UNSIGNED
) {
5276 else if (op
== TOK_LT
)
5278 else if (op
== TOK_GT
)
5280 else if (op
== TOK_LE
)
5282 else if (op
== TOK_GE
)
5289 /* special case for shifts and long long: we keep the shift as
5291 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5296 else if ((t
& VT_BTYPE
) == VT_LLONG
)
5300 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5301 /* relationnal op: the result is an int */
5302 vtop
->type
.t
= VT_INT
;
5309 /* generic itof for unsigned long long case */
5310 void gen_cvt_itof1(int t
)
5312 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
5313 (VT_LLONG
| VT_UNSIGNED
)) {
5316 vpush_global_sym(&func_old_type
, TOK___ulltof
);
5317 else if (t
== VT_DOUBLE
)
5318 vpush_global_sym(&func_old_type
, TOK___ulltod
);
5320 vpush_global_sym(&func_old_type
, TOK___ulltold
);
5330 /* generic ftoi for unsigned long long case */
5331 void gen_cvt_ftoi1(int t
)
5335 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
5336 /* not handled natively */
5337 st
= vtop
->type
.t
& VT_BTYPE
;
5339 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
5340 else if (st
== VT_DOUBLE
)
5341 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
5343 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
5348 vtop
->r2
= REG_LRET
;
5354 /* force char or short cast */
5355 void force_charshort_cast(int t
)
5359 /* XXX: add optimization if lvalue : just change type and offset */
5364 if (t
& VT_UNSIGNED
) {
5365 vpushi((1 << bits
) - 1);
5376 /* cast 'vtop' to 'type' */
5377 static void gen_cast(CType
*type
)
5379 int sbt
, dbt
, sf
, df
, c
;
5381 /* special delayed cast for char/short */
5382 /* XXX: in some cases (multiple cascaded casts), it may still
5384 if (vtop
->r
& VT_MUSTCAST
) {
5385 vtop
->r
&= ~VT_MUSTCAST
;
5386 force_charshort_cast(vtop
->type
.t
);
5389 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
5390 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
5392 if (sbt
!= dbt
&& !nocode_wanted
) {
5395 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5397 /* convert from fp to fp */
5399 /* constant case: we can do it now */
5400 /* XXX: in ISOC, cannot do it if error in convert */
5401 if (dbt
== VT_FLOAT
&& sbt
== VT_DOUBLE
)
5402 vtop
->c
.f
= (float)vtop
->c
.d
;
5403 else if (dbt
== VT_FLOAT
&& sbt
== VT_LDOUBLE
)
5404 vtop
->c
.f
= (float)vtop
->c
.ld
;
5405 else if (dbt
== VT_DOUBLE
&& sbt
== VT_FLOAT
)
5406 vtop
->c
.d
= (double)vtop
->c
.f
;
5407 else if (dbt
== VT_DOUBLE
&& sbt
== VT_LDOUBLE
)
5408 vtop
->c
.d
= (double)vtop
->c
.ld
;
5409 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_FLOAT
)
5410 vtop
->c
.ld
= (long double)vtop
->c
.f
;
5411 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_DOUBLE
)
5412 vtop
->c
.ld
= (long double)vtop
->c
.d
;
5414 /* non constant case: generate code */
5418 /* convert int to fp */
5421 case VT_LLONG
| VT_UNSIGNED
:
5423 /* XXX: add const cases for long long */
5425 case VT_INT
| VT_UNSIGNED
:
5427 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.ui
; break;
5428 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.ui
; break;
5429 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.ui
; break;
5434 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.i
; break;
5435 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.i
; break;
5436 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.i
; break;
5445 /* convert fp to int */
5446 /* we handle char/short/etc... with generic code */
5447 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
5448 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
5453 case VT_LLONG
| VT_UNSIGNED
:
5455 /* XXX: add const cases for long long */
5457 case VT_INT
| VT_UNSIGNED
:
5459 case VT_FLOAT
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5460 case VT_DOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5461 case VT_LDOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5467 case VT_FLOAT
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5468 case VT_DOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5469 case VT_LDOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5477 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
5478 /* additional cast for char/short/bool... */
5482 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
5483 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
5484 /* scalar to long long */
5486 if (sbt
== (VT_INT
| VT_UNSIGNED
))
5487 vtop
->c
.ll
= vtop
->c
.ui
;
5489 vtop
->c
.ll
= vtop
->c
.i
;
5491 /* machine independent conversion */
5493 /* generate high word */
5494 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
5502 /* patch second register */
5503 vtop
[-1].r2
= vtop
->r
;
5507 } else if (dbt
== VT_BOOL
) {
5508 /* scalar to bool */
5511 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
5512 (dbt
& VT_BTYPE
) == VT_SHORT
) {
5513 force_charshort_cast(dbt
);
5514 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
5516 if (sbt
== VT_LLONG
) {
5517 /* from long long: just take low order word */
5521 /* if lvalue and single word type, nothing to do because
5522 the lvalue already contains the real type size (see
5523 VT_LVAL_xxx constants) */
5529 /* return type size. Put alignment at 'a' */
5530 static int type_size(CType
*type
, int *a
)
5535 bt
= type
->t
& VT_BTYPE
;
5536 if (bt
== VT_STRUCT
) {
5541 } else if (bt
== VT_PTR
) {
5542 if (type
->t
& VT_ARRAY
) {
5544 return type_size(&s
->type
, a
) * s
->c
;
5549 } else if (bt
== VT_LDOUBLE
) {
5551 return LDOUBLE_SIZE
;
5552 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
5553 *a
= 4; /* XXX: i386 specific */
5555 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
5558 } else if (bt
== VT_SHORT
) {
5562 /* char, void, function, _Bool */
5568 /* return the pointed type of t */
5569 static inline CType
*pointed_type(CType
*type
)
5571 return &type
->ref
->type
;
5574 /* modify type so that its it is a pointer to type. */
5575 static void mk_pointer(CType
*type
)
5578 s
= sym_push(SYM_FIELD
, type
, 0, -1);
5579 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
5583 /* compare function types. OLD functions match any new functions */
5584 static int is_compatible_func(CType
*type1
, CType
*type2
)
5590 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5592 /* XXX: not complete */
5593 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
5597 while (s1
!= NULL
) {
5600 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5610 /* return true if type1 and type2 are exactly the same (including
5613 - enums are not checked as gcc __builtin_types_compatible_p ()
5615 static int is_compatible_types(CType
*type1
, CType
*type2
)
5619 t1
= type1
->t
& VT_TYPE
;
5620 t2
= type2
->t
& VT_TYPE
;
5621 /* XXX: bitfields ? */
5624 /* test more complicated cases */
5625 bt1
= t1
& VT_BTYPE
;
5626 if (bt1
== VT_PTR
) {
5627 type1
= pointed_type(type1
);
5628 type2
= pointed_type(type2
);
5629 return is_compatible_types(type1
, type2
);
5630 } else if (bt1
== VT_STRUCT
) {
5631 return (type1
->ref
== type2
->ref
);
5632 } else if (bt1
== VT_FUNC
) {
5633 return is_compatible_func(type1
, type2
);
5639 /* print a type. If 'varstr' is not NULL, then the variable is also
5640 printed in the type */
5642 /* XXX: add array and function pointers */
5643 void type_to_str(char *buf
, int buf_size
,
5644 CType
*type
, const char *varstr
)
5651 t
= type
->t
& VT_TYPE
;
5654 if (t
& VT_CONSTANT
)
5655 pstrcat(buf
, buf_size
, "const ");
5656 if (t
& VT_VOLATILE
)
5657 pstrcat(buf
, buf_size
, "volatile ");
5658 if (t
& VT_UNSIGNED
)
5659 pstrcat(buf
, buf_size
, "unsigned ");
5689 tstr
= "long double";
5691 pstrcat(buf
, buf_size
, tstr
);
5695 if (bt
== VT_STRUCT
)
5699 pstrcat(buf
, buf_size
, tstr
);
5700 v
= type
->ref
->v
& ~SYM_STRUCT
;
5701 if (v
>= SYM_FIRST_ANOM
)
5702 pstrcat(buf
, buf_size
, "<anonymous>");
5704 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
5708 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
5709 pstrcat(buf
, buf_size
, "(");
5711 while (sa
!= NULL
) {
5712 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
5713 pstrcat(buf
, buf_size
, buf1
);
5716 pstrcat(buf
, buf_size
, ", ");
5718 pstrcat(buf
, buf_size
, ")");
5722 pstrcpy(buf1
, sizeof(buf1
), "*");
5724 pstrcat(buf1
, sizeof(buf1
), varstr
);
5725 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
5729 pstrcat(buf
, buf_size
, " ");
5730 pstrcat(buf
, buf_size
, varstr
);
5735 /* verify type compatibility to store vtop in 'dt' type, and generate
5737 static void gen_assign_cast(CType
*dt
)
5739 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
5740 char buf1
[256], buf2
[256];
5743 st
= &vtop
->type
; /* source type */
5744 dbt
= dt
->t
& VT_BTYPE
;
5745 sbt
= st
->t
& VT_BTYPE
;
5746 if (dt
->t
& VT_CONSTANT
)
5747 warning("assignment of read-only location");
5750 /* special cases for pointers */
5751 /* '0' can also be a pointer */
5752 if (is_null_pointer(vtop
))
5754 /* accept implicit pointer to integer cast with warning */
5755 if (is_integer_btype(sbt
)) {
5756 warning("assignment makes pointer from integer without a cast");
5759 type1
= pointed_type(dt
);
5760 /* a function is implicitely a function pointer */
5761 if (sbt
== VT_FUNC
) {
5762 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
5763 !is_compatible_types(pointed_type(dt
), st
))
5770 type2
= pointed_type(st
);
5771 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5772 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
5773 /* void * can match anything */
5775 /* exact type match, except for unsigned */
5778 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5779 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5780 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
5783 /* check const and volatile */
5784 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
5785 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
5786 warning("assignment discards qualifiers from pointer target type");
5792 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
5793 warning("assignment makes integer from pointer without a cast");
5795 /* XXX: more tests */
5798 if (!is_compatible_types(dt
, st
)) {
5800 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
5801 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
5802 error("cannot cast '%s' to '%s'", buf1
, buf2
);
5810 /* store vtop in lvalue pushed on stack */
5813 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
5815 ft
= vtop
[-1].type
.t
;
5816 sbt
= vtop
->type
.t
& VT_BTYPE
;
5817 dbt
= ft
& VT_BTYPE
;
5818 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
5819 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
5820 /* optimize char/short casts */
5821 delayed_cast
= VT_MUSTCAST
;
5822 vtop
->type
.t
= ft
& VT_TYPE
;
5823 /* XXX: factorize */
5824 if (ft
& VT_CONSTANT
)
5825 warning("assignment of read-only location");
5828 gen_assign_cast(&vtop
[-1].type
);
5831 if (sbt
== VT_STRUCT
) {
5832 /* if structure, only generate pointer */
5833 /* structure assignment : generate memcpy */
5834 /* XXX: optimize if small size */
5835 if (!nocode_wanted
) {
5836 size
= type_size(&vtop
->type
, &align
);
5838 vpush_global_sym(&func_old_type
, TOK_memcpy
);
5842 vtop
->type
.t
= VT_INT
;
5846 vtop
->type
.t
= VT_INT
;
5858 /* leave source on stack */
5859 } else if (ft
& VT_BITFIELD
) {
5860 /* bitfield store handling */
5861 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
5862 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
5863 /* remove bit field info to avoid loops */
5864 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
5866 /* duplicate destination */
5868 vtop
[-1] = vtop
[-2];
5870 /* mask and shift source */
5871 vpushi((1 << bit_size
) - 1);
5875 /* load destination, mask and or with source */
5877 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
5883 #ifdef CONFIG_TCC_BCHECK
5884 /* bound check case */
5885 if (vtop
[-1].r
& VT_MUSTBOUND
) {
5891 if (!nocode_wanted
) {
5895 r
= gv(rc
); /* generate value */
5896 /* if lvalue was saved on stack, must read it */
5897 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
5899 t
= get_reg(RC_INT
);
5901 sv
.r
= VT_LOCAL
| VT_LVAL
;
5902 sv
.c
.ul
= vtop
[-1].c
.ul
;
5904 vtop
[-1].r
= t
| VT_LVAL
;
5907 /* two word case handling : store second register at word + 4 */
5908 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
5910 /* convert to int to increment easily */
5911 vtop
->type
.t
= VT_INT
;
5917 /* XXX: it works because r2 is spilled last ! */
5918 store(vtop
->r2
, vtop
- 1);
5922 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
5923 vtop
->r
|= delayed_cast
;
5927 /* post defines POST/PRE add. c is the token ++ or -- */
5928 void inc(int post
, int c
)
5931 vdup(); /* save lvalue */
5933 gv_dup(); /* duplicate value */
5938 vpushi(c
- TOK_MID
);
5940 vstore(); /* store value */
5942 vpop(); /* if post op, return saved value */
5945 /* Parse GNUC __attribute__ extension. Currently, the following
5946 extensions are recognized:
5947 - aligned(n) : set data/function alignment.
5948 - section(x) : generate data/code in this section.
5949 - unused : currently ignored, but may be used someday.
5951 static void parse_attribute(AttributeDef
*ad
)
5955 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
5959 while (tok
!= ')') {
5960 if (tok
< TOK_IDENT
)
5961 expect("attribute name");
5969 expect("section name");
5970 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
5979 if (n
<= 0 || (n
& (n
- 1)) != 0)
5980 error("alignment must be a positive power of two");
5989 /* currently, no need to handle it because tcc does not
5990 track unused objects */
5994 /* currently, no need to handle it because tcc does not
5995 track unused objects */
6000 ad
->func_call
= FUNC_CDECL
;
6005 ad
->func_call
= FUNC_STDCALL
;
6008 if (tcc_state
->warn_unsupported
)
6009 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6010 /* skip parameters */
6011 /* XXX: skip parenthesis too */
6014 while (tok
!= ')' && tok
!= -1)
6029 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6030 static void struct_decl(CType
*type
, int u
)
6032 int a
, v
, size
, align
, maxalign
, c
, offset
;
6033 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
;
6038 a
= tok
; /* save decl type */
6043 /* struct already defined ? return it */
6045 expect("struct/union/enum name");
6049 error("invalid type");
6056 /* we put an undefined size for struct/union */
6057 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6058 s
->r
= 0; /* default alignment is zero as gcc */
6059 /* put struct/union/enum name in type */
6067 error("struct/union/enum already defined");
6068 /* cannot be empty */
6070 /* non empty enums are not allowed */
6071 if (a
== TOK_ENUM
) {
6075 expect("identifier");
6081 /* enum symbols have static storage */
6082 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6083 ss
->type
.t
|= VT_STATIC
;
6088 /* NOTE: we accept a trailing comma */
6098 while (tok
!= '}') {
6099 parse_btype(&btype
, &ad
);
6105 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
);
6106 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6107 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6108 error("invalid type for '%s'",
6109 get_tok_str(v
, NULL
));
6113 bit_size
= expr_const();
6114 /* XXX: handle v = 0 case for messages */
6116 error("negative width in bit-field '%s'",
6117 get_tok_str(v
, NULL
));
6118 if (v
&& bit_size
== 0)
6119 error("zero width for bit-field '%s'",
6120 get_tok_str(v
, NULL
));
6122 size
= type_size(&type1
, &align
);
6124 if (bit_size
>= 0) {
6125 bt
= type1
.t
& VT_BTYPE
;
6130 error("bitfields must have scalar type");
6132 if (bit_size
> bsize
) {
6133 error("width of '%s' exceeds its type",
6134 get_tok_str(v
, NULL
));
6135 } else if (bit_size
== bsize
) {
6136 /* no need for bit fields */
6138 } else if (bit_size
== 0) {
6139 /* XXX: what to do if only padding in a
6141 /* zero size: means to pad */
6145 /* we do not have enough room ? */
6146 if ((bit_pos
+ bit_size
) > bsize
)
6149 /* XXX: handle LSB first */
6150 type1
.t
|= VT_BITFIELD
|
6151 (bit_pos
<< VT_STRUCT_SHIFT
) |
6152 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
6153 bit_pos
+= bit_size
;
6159 /* add new memory data only if starting
6161 if (lbit_pos
== 0) {
6162 if (a
== TOK_STRUCT
) {
6163 c
= (c
+ align
- 1) & -align
;
6171 if (align
> maxalign
)
6175 printf("add field %s offset=%d",
6176 get_tok_str(v
, NULL
), offset
);
6177 if (type1
.t
& VT_BITFIELD
) {
6178 printf(" pos=%d size=%d",
6179 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
6180 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
6184 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
6188 if (tok
== ';' || tok
== TOK_EOF
)
6195 /* store size and alignment */
6196 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
6202 /* return 0 if no type declaration. otherwise, return the basic type
6205 static int parse_btype(CType
*type
, AttributeDef
*ad
)
6207 int t
, u
, type_found
;
6211 memset(ad
, 0, sizeof(AttributeDef
));
6217 /* currently, we really ignore extension */
6227 if ((t
& VT_BTYPE
) != 0)
6228 error("too many basic types");
6242 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
6243 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6244 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
6245 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
6259 if ((t
& VT_BTYPE
) == VT_LONG
) {
6260 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6267 struct_decl(&type1
, VT_ENUM
);
6270 type
->ref
= type1
.ref
;
6274 struct_decl(&type1
, VT_STRUCT
);
6277 /* type modifiers */
6325 /* GNUC attribute */
6326 case TOK_ATTRIBUTE1
:
6327 case TOK_ATTRIBUTE2
:
6328 parse_attribute(ad
);
6335 parse_expr_type(&type1
);
6339 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
6341 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
6342 type
->ref
= s
->type
.ref
;
6349 /* long is never used as type */
6350 if ((t
& VT_BTYPE
) == VT_LONG
)
6351 t
= (t
& ~VT_BTYPE
) | VT_INT
;
6356 /* convert a function parameter type (array to pointer and function to
6357 function pointer) */
6358 static inline void convert_parameter_type(CType
*pt
)
6360 /* array must be transformed to pointer according to ANSI C */
6362 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
6367 static void post_type(CType
*type
, AttributeDef
*ad
)
6370 Sym
**plast
, *s
, *first
;
6375 /* function declaration */
6380 while (tok
!= ')') {
6381 /* read param name and compute offset */
6382 if (l
!= FUNC_OLD
) {
6383 if (!parse_btype(&pt
, &ad1
)) {
6385 error("invalid type");
6392 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
6394 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6395 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
6396 error("parameter declared as void");
6403 convert_parameter_type(&pt
);
6404 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
6409 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
6416 /* if no parameters, then old type prototype */
6420 t1
= type
->t
& VT_STORAGE
;
6421 /* NOTE: const is ignored in returned type as it has a special
6422 meaning in gcc / C++ */
6423 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
6424 post_type(type
, ad
);
6425 /* we push a anonymous symbol which will contain the function prototype */
6426 s
= sym_push(SYM_FIELD
, type
, ad
->func_call
, l
);
6428 type
->t
= t1
| VT_FUNC
;
6430 } else if (tok
== '[') {
6431 /* array definition */
6437 error("invalid array size");
6440 /* parse next post type */
6441 t1
= type
->t
& VT_STORAGE
;
6442 type
->t
&= ~VT_STORAGE
;
6443 post_type(type
, ad
);
6445 /* we push a anonymous symbol which will contain the array
6447 s
= sym_push(SYM_FIELD
, type
, 0, n
);
6448 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
6453 /* Parse a type declaration (except basic type), and return the type
6454 in 'type'. 'td' is a bitmask indicating which kind of type decl is
6455 expected. 'type' should contain the basic type. 'ad' is the
6456 attribute definition of the basic type. It can be modified by
6459 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
6462 CType type1
, *type2
;
6465 while (tok
== '*') {
6473 qualifiers
|= VT_CONSTANT
;
6478 qualifiers
|= VT_VOLATILE
;
6486 type
->t
|= qualifiers
;
6489 /* XXX: clarify attribute handling */
6490 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6491 parse_attribute(ad
);
6493 /* recursive type */
6494 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
6495 type1
.t
= 0; /* XXX: same as int */
6498 /* XXX: this is not correct to modify 'ad' at this point, but
6499 the syntax is not clear */
6500 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6501 parse_attribute(ad
);
6502 type_decl(&type1
, ad
, v
, td
);
6505 /* type identifier */
6506 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
6510 if (!(td
& TYPE_ABSTRACT
))
6511 expect("identifier");
6515 post_type(type
, ad
);
6516 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6517 parse_attribute(ad
);
6520 /* append type at the end of type1 */
6533 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
6534 static int lvalue_type(int t
)
6539 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
6541 else if (bt
== VT_SHORT
)
6545 if (t
& VT_UNSIGNED
)
6546 r
|= VT_LVAL_UNSIGNED
;
6550 /* indirection with full error checking and bound check */
6551 static void indir(void)
6553 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
6555 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
6557 vtop
->type
= *pointed_type(&vtop
->type
);
6558 /* an array is never an lvalue */
6559 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6560 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6561 /* if bound checking, the referenced pointer must be checked */
6562 if (do_bounds_check
)
6563 vtop
->r
|= VT_MUSTBOUND
;
6567 /* pass a parameter to a function and do type checking and casting */
6568 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
6573 func_type
= func
->c
;
6574 if (func_type
== FUNC_OLD
||
6575 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
6576 /* default casting : only need to convert float to double */
6577 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
6581 } else if (arg
== NULL
) {
6582 error("too many arguments to function");
6584 gen_assign_cast(&arg
->type
);
6588 /* parse an expression of the form '(type)' or '(expr)' and return its
6590 static void parse_expr_type(CType
*type
)
6596 if (parse_btype(type
, &ad
)) {
6597 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6604 static void parse_type(CType
*type
)
6609 if (!parse_btype(type
, &ad
)) {
6612 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6615 static void vpush_tokc(int t
)
6619 vsetc(&type
, VT_CONST
, &tokc
);
6622 static void unary(void)
6624 int n
, t
, align
, size
, r
;
6629 /* XXX: GCC 2.95.3 does not generate a table although it should be
6643 vpush_tokc(VT_INT
| VT_UNSIGNED
);
6647 vpush_tokc(VT_LLONG
);
6651 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
6655 vpush_tokc(VT_FLOAT
);
6659 vpush_tokc(VT_DOUBLE
);
6663 vpush_tokc(VT_LDOUBLE
);
6666 case TOK___FUNCTION__
:
6668 goto tok_identifier
;
6674 /* special function name identifier */
6675 len
= strlen(funcname
) + 1;
6676 /* generate char[len] type */
6681 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
6682 ptr
= section_ptr_add(data_section
, len
);
6683 memcpy(ptr
, funcname
, len
);
6691 /* string parsing */
6694 if (tcc_state
->warn_write_strings
)
6699 memset(&ad
, 0, sizeof(AttributeDef
));
6700 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
6705 if (parse_btype(&type
, &ad
)) {
6706 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
6708 /* check ISOC99 compound literal */
6710 /* data is allocated locally by default */
6715 /* all except arrays are lvalues */
6716 if (!(type
.t
& VT_ARRAY
))
6717 r
|= lvalue_type(type
.t
);
6718 memset(&ad
, 0, sizeof(AttributeDef
));
6719 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
6724 } else if (tok
== '{') {
6725 /* save all registers */
6727 /* statement expression : we do not accept break/continue
6728 inside as GCC does */
6729 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
6744 /* functions names must be treated as function pointers,
6745 except for unary '&' and sizeof. Since we consider that
6746 functions are not lvalues, we only have to handle it
6747 there and in function calls. */
6748 /* arrays can also be used although they are not lvalues */
6749 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
6750 !(vtop
->type
.t
& VT_ARRAY
))
6752 mk_pointer(&vtop
->type
);
6758 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
)
6759 vtop
->c
.i
= !vtop
->c
.i
;
6760 else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
6761 vtop
->c
.i
= vtop
->c
.i
^ 1;
6763 vseti(VT_JMP
, gtst(1, 0));
6773 /* in order to force cast, we add zero */
6775 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
6776 error("pointer not accepted for unary plus");
6786 parse_expr_type(&type
);
6790 size
= type_size(&type
, &align
);
6791 if (t
== TOK_SIZEOF
) {
6793 error("sizeof applied to an incomplete type");
6800 case TOK_builtin_types_compatible_p
:
6809 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6810 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6811 vpushi(is_compatible_types(&type1
, &type2
));
6814 case TOK_builtin_constant_p
:
6816 int saved_nocode_wanted
, res
;
6819 saved_nocode_wanted
= nocode_wanted
;
6822 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
6824 nocode_wanted
= saved_nocode_wanted
;
6844 goto tok_identifier
;
6846 /* allow to take the address of a label */
6847 if (tok
< TOK_UIDENT
)
6848 expect("label identifier");
6849 s
= label_find(tok
);
6851 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
6853 if (s
->r
== LABEL_DECLARED
)
6854 s
->r
= LABEL_FORWARD
;
6857 s
->type
.t
= VT_VOID
;
6858 mk_pointer(&s
->type
);
6859 s
->type
.t
|= VT_STATIC
;
6861 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
6870 expect("identifier");
6874 error("'%s' undeclared", get_tok_str(t
, NULL
));
6875 /* for simple function calls, we tolerate undeclared
6876 external reference to int() function */
6877 s
= external_global_sym(t
, &func_old_type
, 0);
6879 vset(&s
->type
, s
->r
, s
->c
);
6880 /* if forward reference, we must point to s */
6881 if (vtop
->r
& VT_SYM
) {
6888 /* post operations */
6890 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
6893 } else if (tok
== '.' || tok
== TOK_ARROW
) {
6895 if (tok
== TOK_ARROW
)
6900 /* expect pointer on structure */
6901 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
6902 expect("struct or union");
6906 while ((s
= s
->next
) != NULL
) {
6911 error("field not found");
6912 /* add field offset to pointer */
6913 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
6916 /* change type to field type, and set to lvalue */
6917 vtop
->type
= s
->type
;
6918 /* an array is never an lvalue */
6919 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6920 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6921 /* if bound checking, the referenced pointer must be checked */
6922 if (do_bounds_check
)
6923 vtop
->r
|= VT_MUSTBOUND
;
6926 } else if (tok
== '[') {
6932 } else if (tok
== '(') {
6938 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
6939 /* pointer test (no array accepted) */
6940 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
6941 vtop
->type
= *pointed_type(&vtop
->type
);
6942 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
6946 expect("function pointer");
6949 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
6951 /* get return type */
6954 sa
= s
->next
; /* first parameter */
6956 /* compute first implicit argument if a structure is returned */
6957 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
6958 /* get some space for the returned structure */
6959 size
= type_size(&s
->type
, &align
);
6960 loc
= (loc
- size
) & -align
;
6962 ret
.r
= VT_LOCAL
| VT_LVAL
;
6963 /* pass it as 'int' to avoid structure arg passing
6965 vseti(VT_LOCAL
, loc
);
6971 /* return in register */
6972 if (is_float(ret
.type
.t
)) {
6975 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
6984 gfunc_param_typed(s
, sa
);
6994 error("too few arguments to function");
6996 if (!nocode_wanted
) {
6997 gfunc_call(nb_args
);
6999 vtop
-= (nb_args
+ 1);
7002 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
7010 static void uneq(void)
7016 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
7017 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
7018 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
7033 static void expr_prod(void)
7038 while (tok
== '*' || tok
== '/' || tok
== '%') {
7046 static void expr_sum(void)
7051 while (tok
== '+' || tok
== '-') {
7059 static void expr_shift(void)
7064 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
7072 static void expr_cmp(void)
7077 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
7078 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
7086 static void expr_cmpeq(void)
7091 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
7099 static void expr_and(void)
7102 while (tok
== '&') {
7109 static void expr_xor(void)
7112 while (tok
== '^') {
7119 static void expr_or(void)
7122 while (tok
== '|') {
7129 /* XXX: fix this mess */
7130 static void expr_land_const(void)
7133 while (tok
== TOK_LAND
) {
7140 /* XXX: fix this mess */
7141 static void expr_lor_const(void)
7144 while (tok
== TOK_LOR
) {
7151 /* only used if non constant */
7152 static void expr_land(void)
7157 if (tok
== TOK_LAND
) {
7161 if (tok
!= TOK_LAND
) {
7171 static void expr_lor(void)
7176 if (tok
== TOK_LOR
) {
7180 if (tok
!= TOK_LOR
) {
7190 /* XXX: better constant handling */
7191 static void expr_eq(void)
7193 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
7195 CType type
, type1
, type2
;
7204 if (tok
== ':' && gnu_ext
) {
7220 if (vtop
!= vstack
) {
7221 /* needed to avoid having different registers saved in
7223 if (is_float(vtop
->type
.t
))
7230 if (tok
== ':' && gnu_ext
) {
7238 sv
= *vtop
; /* save value to handle it later */
7239 vtop
--; /* no vpop so that FP stack is not flushed */
7247 bt1
= t1
& VT_BTYPE
;
7249 bt2
= t2
& VT_BTYPE
;
7250 /* cast operands to correct type according to ISOC rules */
7251 if (is_float(bt1
) || is_float(bt2
)) {
7252 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
7253 type
.t
= VT_LDOUBLE
;
7254 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
7259 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
7260 /* cast to biggest op */
7262 /* convert to unsigned if it does not fit in a long long */
7263 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
7264 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
7265 type
.t
|= VT_UNSIGNED
;
7266 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
7267 /* XXX: test pointer compatibility */
7269 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
7270 /* XXX: test structure compatibility */
7272 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
7273 /* NOTE: as an extension, we accept void on only one side */
7276 /* integer operations */
7278 /* convert to unsigned if it does not fit in an integer */
7279 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
7280 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
7281 type
.t
|= VT_UNSIGNED
;
7284 /* now we convert second operand */
7287 if (is_float(type
.t
)) {
7289 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
7290 /* for long longs, we use fixed registers to avoid having
7291 to handle a complicated move */
7296 /* this is horrible, but we must also convert first
7300 /* put again first value and cast it */
7311 static void gexpr(void)
7322 /* parse an expression and return its type without any side effect. */
7323 static void expr_type(CType
*type
)
7325 int saved_nocode_wanted
;
7327 saved_nocode_wanted
= nocode_wanted
;
7332 nocode_wanted
= saved_nocode_wanted
;
7335 /* parse a unary expression and return its type without any side
7337 static void unary_type(CType
*type
)
7349 /* parse a constant expression and return value in vtop. */
7350 static void expr_const1(void)
7359 /* parse an integer constant and return its value. */
7360 static int expr_const(void)
7364 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
7365 expect("constant expression");
7371 /* return the label token if current token is a label, otherwise
7373 static int is_label(void)
7377 /* fast test first */
7378 if (tok
< TOK_UIDENT
)
7380 /* no need to save tokc because tok is an identifier */
7387 unget_tok(last_tok
);
7392 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
7393 int case_reg
, int is_expr
)
7398 /* generate line number info */
7400 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
7401 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
7403 last_line_num
= file
->line_num
;
7407 /* default return value is (void) */
7409 vtop
->type
.t
= VT_VOID
;
7412 if (tok
== TOK_IF
) {
7419 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7421 if (c
== TOK_ELSE
) {
7425 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7426 gsym(d
); /* patch else jmp */
7429 } else if (tok
== TOK_WHILE
) {
7437 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7441 } else if (tok
== '{') {
7445 /* record local declaration stack position */
7447 llabel
= local_label_stack
;
7448 /* handle local labels declarations */
7449 if (tok
== TOK_LABEL
) {
7452 if (tok
< TOK_UIDENT
)
7453 expect("label identifier");
7454 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
7464 while (tok
!= '}') {
7469 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7472 /* pop locally defined labels */
7473 label_pop(&local_label_stack
, llabel
);
7474 /* pop locally defined symbols */
7475 sym_pop(&local_stack
, s
);
7477 } else if (tok
== TOK_RETURN
) {
7481 gen_assign_cast(&func_vt
);
7482 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
7484 /* if returning structure, must copy it to implicit
7485 first pointer arg location */
7488 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
7491 /* copy structure value to pointer */
7493 } else if (is_float(func_vt
.t
)) {
7498 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
7501 rsym
= gjmp(rsym
); /* jmp */
7502 } else if (tok
== TOK_BREAK
) {
7505 error("cannot break");
7506 *bsym
= gjmp(*bsym
);
7509 } else if (tok
== TOK_CONTINUE
) {
7512 error("cannot continue");
7513 *csym
= gjmp(*csym
);
7516 } else if (tok
== TOK_FOR
) {
7543 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7548 if (tok
== TOK_DO
) {
7553 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7564 if (tok
== TOK_SWITCH
) {
7568 /* XXX: other types than integer */
7569 case_reg
= gv(RC_INT
);
7573 b
= gjmp(0); /* jump to first case */
7575 block(&a
, csym
, &b
, &c
, case_reg
, 0);
7576 /* if no default, jmp after switch */
7584 if (tok
== TOK_CASE
) {
7591 if (gnu_ext
&& tok
== TOK_DOTS
) {
7595 warning("empty case range");
7597 /* since a case is like a label, we must skip it with a jmp */
7604 *case_sym
= gtst(1, 0);
7607 *case_sym
= gtst(1, 0);
7611 *case_sym
= gtst(1, *case_sym
);
7616 goto block_after_label
;
7618 if (tok
== TOK_DEFAULT
) {
7624 error("too many 'default'");
7627 goto block_after_label
;
7629 if (tok
== TOK_GOTO
) {
7631 if (tok
== '*' && gnu_ext
) {
7635 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
7638 } else if (tok
>= TOK_UIDENT
) {
7639 s
= label_find(tok
);
7640 /* put forward definition if needed */
7642 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7644 if (s
->r
== LABEL_DECLARED
)
7645 s
->r
= LABEL_FORWARD
;
7647 /* label already defined */
7648 if (s
->r
& LABEL_FORWARD
)
7649 s
->next
= (void *)gjmp((long)s
->next
);
7651 gjmp_addr((long)s
->next
);
7654 expect("label identifier");
7657 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
7665 if (s
->r
== LABEL_DEFINED
)
7666 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
7667 gsym((long)s
->next
);
7668 s
->r
= LABEL_DEFINED
;
7670 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
7672 s
->next
= (void *)ind
;
7673 /* we accept this, but it is a mistake */
7676 warning("deprecated use of label at end of compound statement");
7680 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7683 /* expression case */
7698 /* t is the array or struct type. c is the array or struct
7699 address. cur_index/cur_field is the pointer to the current
7700 value. 'size_only' is true if only size info is needed (only used
7702 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
7703 int *cur_index
, Sym
**cur_field
,
7707 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
7713 if (gnu_ext
&& (l
= is_label()) != 0)
7715 while (tok
== '[' || tok
== '.') {
7717 if (!(type
->t
& VT_ARRAY
))
7718 expect("array type");
7721 index
= expr_const();
7722 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
7723 expect("invalid index");
7724 if (tok
== TOK_DOTS
&& gnu_ext
) {
7726 index_last
= expr_const();
7727 if (index_last
< 0 ||
7728 (s
->c
>= 0 && index_last
>= s
->c
) ||
7730 expect("invalid index");
7736 *cur_index
= index_last
;
7737 type
= pointed_type(type
);
7738 elem_size
= type_size(type
, &align
);
7739 c
+= index
* elem_size
;
7740 /* NOTE: we only support ranges for last designator */
7741 nb_elems
= index_last
- index
+ 1;
7742 if (nb_elems
!= 1) {
7751 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
7752 expect("struct/union type");
7765 /* XXX: fix this mess by using explicit storage field */
7767 type1
.t
|= (type
->t
& ~VT_TYPE
);
7781 if (type
->t
& VT_ARRAY
) {
7783 type
= pointed_type(type
);
7784 c
+= index
* type_size(type
, &align
);
7788 error("too many field init");
7789 /* XXX: fix this mess by using explicit storage field */
7791 type1
.t
|= (type
->t
& ~VT_TYPE
);
7796 decl_initializer(type
, sec
, c
, 0, size_only
);
7798 /* XXX: make it more general */
7799 if (!size_only
&& nb_elems
> 1) {
7800 unsigned long c_end
;
7805 error("range init not supported yet for dynamic storage");
7806 c_end
= c
+ nb_elems
* elem_size
;
7807 if (c_end
> sec
->data_allocated
)
7808 section_realloc(sec
, c_end
);
7809 src
= sec
->data
+ c
;
7811 for(i
= 1; i
< nb_elems
; i
++) {
7813 memcpy(dst
, src
, elem_size
);
7819 #define EXPR_CONST 1
7822 /* store a value or an expression directly in global data or in local array */
7823 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
7824 int v
, int expr_type
)
7826 int saved_global_expr
, bt
, bit_pos
, bit_size
;
7828 unsigned long long bit_mask
;
7836 /* compound literals must be allocated globally in this case */
7837 saved_global_expr
= global_expr
;
7840 global_expr
= saved_global_expr
;
7841 /* NOTE: symbols are accepted */
7842 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
7843 error("initializer element is not constant");
7851 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
7854 /* XXX: not portable */
7855 /* XXX: generate error if incorrect relocation */
7856 gen_assign_cast(&dtype
);
7857 bt
= type
->t
& VT_BTYPE
;
7858 ptr
= sec
->data
+ c
;
7859 /* XXX: make code faster ? */
7860 if (!(type
->t
& VT_BITFIELD
)) {
7865 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
7866 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
7867 bit_mask
= (1LL << bit_size
) - 1;
7869 if ((vtop
->r
& VT_SYM
) &&
7875 (bt
== VT_INT
&& bit_size
!= 32)))
7876 error("initializer element is not computable at load time");
7879 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7882 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7885 *(double *)ptr
= vtop
->c
.d
;
7888 *(long double *)ptr
= vtop
->c
.ld
;
7891 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
7894 if (vtop
->r
& VT_SYM
) {
7895 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
7897 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
7902 vset(&dtype
, VT_LOCAL
, c
);
7909 /* put zeros for variable based init */
7910 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
7913 /* nothing to do because globals are already set to zero */
7915 vpush_global_sym(&func_old_type
, TOK_memset
);
7923 /* 't' contains the type and storage info. 'c' is the offset of the
7924 object in section 'sec'. If 'sec' is NULL, it means stack based
7925 allocation. 'first' is true if array '{' must be read (multi
7926 dimension implicit array init handling). 'size_only' is true if
7927 size only evaluation is wanted (only for arrays). */
7928 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
7929 int first
, int size_only
)
7931 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
7932 int size1
, align1
, expr_type
;
7936 if (type
->t
& VT_ARRAY
) {
7940 t1
= pointed_type(type
);
7941 size1
= type_size(t1
, &align1
);
7944 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
7950 /* only parse strings here if correct type (otherwise: handle
7951 them as ((w)char *) expressions */
7952 if ((tok
== TOK_LSTR
&&
7953 (t1
->t
& VT_BTYPE
) == VT_INT
) ||
7955 (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
7956 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
7961 /* compute maximum number of chars wanted */
7963 cstr_len
= cstr
->size
;
7965 cstr_len
= cstr
->size
/ sizeof(int);
7968 if (n
>= 0 && nb
> (n
- array_length
))
7969 nb
= n
- array_length
;
7972 warning("initializer-string for array is too long");
7973 /* in order to go faster for common case (char
7974 string in global variable, we handle it
7976 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
7977 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
7981 ch
= ((unsigned char *)cstr
->data
)[i
];
7983 ch
= ((int *)cstr
->data
)[i
];
7984 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
7992 /* only add trailing zero if enough storage (no
7993 warning in this case since it is standard) */
7994 if (n
< 0 || array_length
< n
) {
7996 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
8002 while (tok
!= '}') {
8003 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
8004 if (n
>= 0 && index
>= n
)
8005 error("index too large");
8006 /* must put zero in holes (note that doing it that way
8007 ensures that it even works with designators) */
8008 if (!size_only
&& array_length
< index
) {
8009 init_putz(t1
, sec
, c
+ array_length
* size1
,
8010 (index
- array_length
) * size1
);
8013 if (index
> array_length
)
8014 array_length
= index
;
8015 /* special test for multi dimensional arrays (may not
8016 be strictly correct if designators are used at the
8018 if (index
>= n
&& no_oblock
)
8027 /* put zeros at the end */
8028 if (!size_only
&& n
>= 0 && array_length
< n
) {
8029 init_putz(t1
, sec
, c
+ array_length
* size1
,
8030 (n
- array_length
) * size1
);
8032 /* patch type size if needed */
8034 s
->c
= array_length
;
8035 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
8036 (sec
|| !first
|| tok
== '{')) {
8039 /* NOTE: the previous test is a specific case for automatic
8040 struct/union init */
8041 /* XXX: union needs only one init */
8043 /* XXX: this test is incorrect for local initializers
8044 beginning with ( without {. It would be much more difficult
8045 to do it correctly (ideally, the expression parser should
8046 be used in all cases) */
8052 while (tok
== '(') {
8056 if (!parse_btype(&type1
, &ad1
))
8058 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
8060 if (!is_assignable_types(type
, &type1
))
8061 error("invalid type for cast");
8066 if (first
|| tok
== '{') {
8075 while (tok
!= '}') {
8076 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
8078 if (!size_only
&& array_length
< index
) {
8079 init_putz(type
, sec
, c
+ array_length
,
8080 index
- array_length
);
8082 index
= index
+ type_size(&f
->type
, &align1
);
8083 if (index
> array_length
)
8084 array_length
= index
;
8086 if (no_oblock
&& f
== NULL
)
8092 /* put zeros at the end */
8093 if (!size_only
&& array_length
< n
) {
8094 init_putz(type
, sec
, c
+ array_length
,
8103 } else if (tok
== '{') {
8105 decl_initializer(type
, sec
, c
, first
, size_only
);
8107 } else if (size_only
) {
8108 /* just skip expression */
8110 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
8114 else if (tok
== ')')
8119 /* currently, we always use constant expression for globals
8120 (may change for scripting case) */
8121 expr_type
= EXPR_CONST
;
8123 expr_type
= EXPR_ANY
;
8124 init_putv(type
, sec
, c
, 0, expr_type
);
8128 /* parse an initializer for type 't' if 'has_init' is non zero, and
8129 allocate space in local or global data space ('r' is either
8130 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
8131 variable 'v' of scope 'scope' is declared before initializers are
8132 parsed. If 'v' is zero, then a reference to the new object is put
8133 in the value stack. If 'has_init' is 2, a special parsing is done
8134 to handle string constants. */
8135 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
8136 int has_init
, int v
, int scope
)
8138 int size
, align
, addr
, data_offset
;
8140 ParseState saved_parse_state
;
8141 TokenString init_str
;
8144 size
= type_size(type
, &align
);
8145 /* If unknown size, we must evaluate it before
8146 evaluating initializers because
8147 initializers can generate global data too
8148 (e.g. string pointers or ISOC99 compound
8149 literals). It also simplifies local
8150 initializers handling */
8151 tok_str_new(&init_str
);
8154 error("unknown type size");
8155 /* get all init string */
8156 if (has_init
== 2) {
8157 /* only get strings */
8158 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8159 tok_str_add_tok(&init_str
);
8164 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
8166 error("unexpected end of file in initializer");
8167 tok_str_add_tok(&init_str
);
8170 else if (tok
== '}') {
8178 tok_str_add(&init_str
, -1);
8179 tok_str_add(&init_str
, 0);
8182 save_parse_state(&saved_parse_state
);
8184 macro_ptr
= init_str
.str
;
8186 decl_initializer(type
, NULL
, 0, 1, 1);
8187 /* prepare second initializer parsing */
8188 macro_ptr
= init_str
.str
;
8191 /* if still unknown size, error */
8192 size
= type_size(type
, &align
);
8194 error("unknown type size");
8196 /* take into account specified alignment if bigger */
8197 if (ad
->aligned
> align
)
8198 align
= ad
->aligned
;
8199 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
8201 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
8203 loc
= (loc
- size
) & -align
;
8205 /* handles bounds */
8206 /* XXX: currently, since we do only one pass, we cannot track
8207 '&' operators, so we add only arrays */
8208 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
8209 unsigned long *bounds_ptr
;
8210 /* add padding between regions */
8212 /* then add local bound info */
8213 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
8214 bounds_ptr
[0] = addr
;
8215 bounds_ptr
[1] = size
;
8218 /* local variable */
8219 sym_push(v
, type
, r
, addr
);
8221 /* push local reference */
8222 vset(type
, r
, addr
);
8228 if (v
&& scope
== VT_CONST
) {
8229 /* see if the symbol was already defined */
8232 if (!is_compatible_types(&sym
->type
, type
))
8233 error("incompatible types for redefinition of '%s'",
8234 get_tok_str(v
, NULL
));
8235 if (sym
->type
.t
& VT_EXTERN
) {
8236 /* if the variable is extern, it was not allocated */
8237 sym
->type
.t
&= ~VT_EXTERN
;
8239 /* we accept several definitions of the same
8240 global variable. this is tricky, because we
8241 must play with the SHN_COMMON type of the symbol */
8242 /* XXX: should check if the variable was already
8243 initialized. It is incorrect to initialized it
8245 /* no init data, we won't add more to the symbol */
8252 /* allocate symbol in corresponding section */
8259 data_offset
= sec
->data_offset
;
8260 data_offset
= (data_offset
+ align
- 1) & -align
;
8262 /* very important to increment global pointer at this time
8263 because initializers themselves can create new initializers */
8264 data_offset
+= size
;
8265 /* add padding if bound check */
8266 if (do_bounds_check
)
8268 sec
->data_offset
= data_offset
;
8269 /* allocate section space to put the data */
8270 if (sec
->sh_type
!= SHT_NOBITS
&&
8271 data_offset
> sec
->data_allocated
)
8272 section_realloc(sec
, data_offset
);
8274 addr
= 0; /* avoid warning */
8278 if (scope
== VT_CONST
) {
8283 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
8285 /* update symbol definition */
8287 put_extern_sym(sym
, sec
, addr
, size
);
8290 /* put a common area */
8291 put_extern_sym(sym
, NULL
, align
, size
);
8292 /* XXX: find a nicer way */
8293 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
8294 esym
->st_shndx
= SHN_COMMON
;
8299 /* push global reference */
8300 sym
= get_sym_ref(type
, sec
, addr
, size
);
8302 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
8306 /* handles bounds now because the symbol must be defined
8307 before for the relocation */
8308 if (do_bounds_check
) {
8309 unsigned long *bounds_ptr
;
8311 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
8312 /* then add global bound info */
8313 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
8314 bounds_ptr
[0] = 0; /* relocated */
8315 bounds_ptr
[1] = size
;
8319 decl_initializer(type
, sec
, addr
, 1, 0);
8320 /* restore parse state if needed */
8322 tok_str_free(init_str
.str
);
8323 restore_parse_state(&saved_parse_state
);
8329 void put_func_debug(Sym
*sym
)
8334 /* XXX: we put here a dummy type */
8335 snprintf(buf
, sizeof(buf
), "%s:%c1",
8336 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
8337 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
8338 cur_text_section
, sym
->c
);
8343 /* not finished : try to put some local vars in registers */
8344 //#define CONFIG_REG_VARS
8346 #ifdef CONFIG_REG_VARS
8347 void add_var_ref(int t
)
8349 printf("%s:%d: &%s\n",
8350 file
->filename
, file
->line_num
,
8351 get_tok_str(t
, NULL
));
8354 /* first pass on a function with heuristic to extract variable usage
8355 and pointer references to local variables for register allocation */
8356 void analyse_function(void)
8363 /* any symbol coming after '&' is considered as being a
8364 variable whose reference is taken. It is highly unaccurate
8365 but it is difficult to do better without a complete parse */
8368 /* if '& number', then no need to examine next tokens */
8369 if (tok
== TOK_CINT
||
8371 tok
== TOK_CLLONG
||
8372 tok
== TOK_CULLONG
) {
8374 } else if (tok
>= TOK_UIDENT
) {
8375 /* if '& ident [' or '& ident ->', then ident address
8379 if (tok
!= '[' && tok
!= TOK_ARROW
)
8383 while (tok
!= '}' && tok
!= ';' &&
8384 !((tok
== ',' || tok
== ')') && level
== 0)) {
8385 if (tok
>= TOK_UIDENT
) {
8387 } else if (tok
== '(') {
8389 } else if (tok
== ')') {
8402 /* parse an old style function declaration list */
8403 /* XXX: check multiple parameter */
8404 static void func_decl_list(Sym
*func_sym
)
8411 /* parse each declaration */
8412 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
8413 if (!parse_btype(&btype
, &ad
))
8414 expect("declaration list");
8415 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8416 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8418 /* we accept no variable after */
8422 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8423 /* find parameter in function parameter list */
8426 if ((s
->v
& ~SYM_FIELD
) == v
)
8430 error("declaration for parameter '%s' but no such parameter",
8431 get_tok_str(v
, NULL
));
8433 /* check that no storage specifier except 'register' was given */
8434 if (type
.t
& VT_STORAGE
)
8435 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
8436 convert_parameter_type(&type
);
8437 /* we can add the type (NOTE: it could be local to the function) */
8439 /* accept other parameters */
8450 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
8451 static void decl(int l
)
8459 if (!parse_btype(&btype
, &ad
)) {
8460 /* skip redundant ';' */
8461 /* XXX: find more elegant solution */
8466 /* special test for old K&R protos without explicit int
8467 type. Only accepted when defining global data */
8468 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
8472 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8473 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8475 /* we accept no variable after */
8479 while (1) { /* iterate thru each declaration */
8481 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8485 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
8486 printf("type = '%s'\n", buf
);
8489 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8490 /* if old style function prototype, we accept a
8493 if (sym
->c
== FUNC_OLD
)
8494 func_decl_list(sym
);
8498 #ifdef CONFIG_REG_VARS
8499 TokenString func_str
;
8500 ParseState saved_parse_state
;
8505 error("cannot use local functions");
8506 if (!(type
.t
& VT_FUNC
))
8507 expect("function definition");
8508 /* XXX: cannot do better now: convert extern line to static inline */
8509 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
8510 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
8512 #ifdef CONFIG_REG_VARS
8513 /* parse all function code and record it */
8515 tok_str_new(&func_str
);
8521 error("unexpected end of file");
8522 tok_str_add_tok(&func_str
);
8527 } else if (t
== '}') {
8529 if (block_level
== 0)
8533 tok_str_add(&func_str
, -1);
8534 tok_str_add(&func_str
, 0);
8536 save_parse_state(&saved_parse_state
);
8538 macro_ptr
= func_str
.str
;
8543 /* compute text section */
8544 cur_text_section
= ad
.section
;
8545 if (!cur_text_section
)
8546 cur_text_section
= text_section
;
8547 ind
= cur_text_section
->data_offset
;
8548 funcname
= get_tok_str(v
, NULL
);
8551 /* if symbol is already defined, then put complete type */
8554 /* put function symbol */
8555 sym
= global_identifier_push(v
, type
.t
, 0);
8556 sym
->type
.ref
= type
.ref
;
8558 /* NOTE: we patch the symbol size later */
8559 put_extern_sym(sym
, cur_text_section
, ind
, 0);
8561 sym
->r
= VT_SYM
| VT_CONST
;
8562 /* put debug symbol */
8564 put_func_debug(sym
);
8565 /* push a dummy symbol to enable local sym storage */
8566 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
8567 gfunc_prolog(&type
);
8570 #ifdef CONFIG_REG_VARS
8571 macro_ptr
= func_str
.str
;
8574 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
8577 cur_text_section
->data_offset
= ind
;
8578 label_pop(&global_label_stack
, NULL
);
8579 sym_pop(&local_stack
, NULL
); /* reset local stack */
8580 /* end of function */
8581 /* patch symbol size */
8582 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_size
=
8585 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
8587 funcname
= ""; /* for safety */
8588 func_vt
.t
= VT_VOID
; /* for safety */
8589 ind
= 0; /* for safety */
8591 #ifdef CONFIG_REG_VARS
8592 tok_str_free(func_str
.str
);
8593 restore_parse_state(&saved_parse_state
);
8597 if (btype
.t
& VT_TYPEDEF
) {
8598 /* save typedefed type */
8599 /* XXX: test storage specifiers ? */
8600 sym
= sym_push(v
, &type
, 0, 0);
8601 sym
->type
.t
|= VT_TYPEDEF
;
8602 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8603 /* external function definition */
8604 external_sym(v
, &type
, 0);
8606 /* not lvalue if array */
8608 if (!(type
.t
& VT_ARRAY
))
8609 r
|= lvalue_type(type
.t
);
8610 has_init
= (tok
== '=');
8611 if ((btype
.t
& VT_EXTERN
) ||
8612 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
8613 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
8614 /* external variable */
8615 /* NOTE: as GCC, uninitialized global static
8616 arrays of null size are considered as
8618 external_sym(v
, &type
, r
);
8620 if (type
.t
& VT_STATIC
)
8626 decl_initializer_alloc(&type
, &ad
, r
,
8640 /* better than nothing, but needs extension to handle '-E' option
8642 static void preprocess_init(TCCState
*s1
)
8644 s1
->include_stack_ptr
= s1
->include_stack
;
8645 /* XXX: move that before to avoid having to initialize
8646 file->ifdef_stack_ptr ? */
8647 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
8648 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
8650 /* XXX: not ANSI compliant: bound checking says error */
8654 /* compile the C file opened in 'file'. Return non zero if errors. */
8655 static int tcc_compile(TCCState
*s1
)
8659 volatile int section_sym
;
8662 printf("%s: **** new file\n", file
->filename
);
8664 preprocess_init(s1
);
8667 anon_sym
= SYM_FIRST_ANOM
;
8669 /* file info: full path + filename */
8670 section_sym
= 0; /* avoid warning */
8672 section_sym
= put_elf_sym(symtab_section
, 0, 0,
8673 ELF32_ST_INFO(STB_LOCAL
, STT_SECTION
), 0,
8674 text_section
->sh_num
, NULL
);
8675 getcwd(buf
, sizeof(buf
));
8676 pstrcat(buf
, sizeof(buf
), "/");
8677 put_stabs_r(buf
, N_SO
, 0, 0,
8678 text_section
->data_offset
, text_section
, section_sym
);
8679 put_stabs_r(file
->filename
, N_SO
, 0, 0,
8680 text_section
->data_offset
, text_section
, section_sym
);
8682 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
8683 symbols can be safely used */
8684 put_elf_sym(symtab_section
, 0, 0,
8685 ELF32_ST_INFO(STB_LOCAL
, STT_FILE
), 0,
8686 SHN_ABS
, file
->filename
);
8688 /* define some often used types */
8689 int_type
.t
= VT_INT
;
8691 char_pointer_type
.t
= VT_BYTE
;
8692 mk_pointer(&char_pointer_type
);
8694 func_old_type
.t
= VT_FUNC
;
8695 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
8698 /* define 'void *alloca(unsigned int)' builtin function */
8703 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
8704 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
8707 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
8711 define_start
= define_stack
;
8713 if (setjmp(s1
->error_jmp_buf
) == 0) {
8715 s1
->error_set_jmp_enabled
= 1;
8717 ch
= file
->buf_ptr
[0];
8718 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
8719 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
8723 expect("declaration");
8725 /* end of translation unit info */
8727 put_stabs_r(NULL
, N_SO
, 0, 0,
8728 text_section
->data_offset
, text_section
, section_sym
);
8731 s1
->error_set_jmp_enabled
= 0;
8733 /* reset define stack, but leave -Dsymbols (may be incorrect if
8734 they are undefined) */
8735 free_defines(define_start
);
8737 sym_pop(&global_stack
, NULL
);
8739 return s1
->nb_errors
!= 0 ? -1 : 0;
8743 int tcc_compile_string(TCCState
*s
, const char *str
)
8745 BufferedFile bf1
, *bf
= &bf1
;
8749 /* init file structure */
8751 /* XXX: avoid copying */
8753 buf
= tcc_malloc(len
+ 1);
8756 memcpy(buf
, str
, len
);
8759 bf
->buf_end
= buf
+ len
;
8760 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
8764 ret
= tcc_compile(s
);
8768 /* currently, no need to close */
8773 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
8774 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
8776 BufferedFile bf1
, *bf
= &bf1
;
8778 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
8779 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
8783 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
8785 /* init file structure */
8787 bf
->buf_ptr
= bf
->buffer
;
8788 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
8789 *bf
->buf_end
= CH_EOB
;
8790 bf
->filename
[0] = '\0';
8794 s1
->include_stack_ptr
= s1
->include_stack
;
8796 /* parse with define parser */
8797 ch
= file
->buf_ptr
[0];
8803 /* undefine a preprocessor symbol */
8804 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
8808 ts
= tok_alloc(sym
, strlen(sym
));
8809 s
= define_find(ts
->tok
);
8810 /* undefine symbol by putting an invalid name */
8815 #ifdef CONFIG_TCC_ASM
8817 #include "i386-asm.c"
8821 static void asm_instr(void)
8823 error("inline asm() not supported");
8829 /* print the position in the source file of PC value 'pc' by reading
8830 the stabs debug information */
8831 static void rt_printline(unsigned long wanted_pc
)
8833 Stab_Sym
*sym
, *sym_end
;
8834 char func_name
[128], last_func_name
[128];
8835 unsigned long func_addr
, last_pc
, pc
;
8836 const char *incl_files
[INCLUDE_STACK_SIZE
];
8837 int incl_index
, len
, last_line_num
, i
;
8838 const char *str
, *p
;
8840 fprintf(stderr
, "0x%08lx:", wanted_pc
);
8842 func_name
[0] = '\0';
8845 last_func_name
[0] = '\0';
8846 last_pc
= 0xffffffff;
8848 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
8849 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
8850 while (sym
< sym_end
) {
8851 switch(sym
->n_type
) {
8852 /* function start or end */
8854 if (sym
->n_strx
== 0) {
8855 /* we test if between last line and end of function */
8856 pc
= sym
->n_value
+ func_addr
;
8857 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
8859 func_name
[0] = '\0';
8862 str
= stabstr_section
->data
+ sym
->n_strx
;
8863 p
= strchr(str
, ':');
8865 pstrcpy(func_name
, sizeof(func_name
), str
);
8868 if (len
> sizeof(func_name
) - 1)
8869 len
= sizeof(func_name
) - 1;
8870 memcpy(func_name
, str
, len
);
8871 func_name
[len
] = '\0';
8873 func_addr
= sym
->n_value
;
8876 /* line number info */
8878 pc
= sym
->n_value
+ func_addr
;
8879 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
8882 last_line_num
= sym
->n_desc
;
8884 strcpy(last_func_name
, func_name
);
8888 str
= stabstr_section
->data
+ sym
->n_strx
;
8890 if (incl_index
< INCLUDE_STACK_SIZE
) {
8891 incl_files
[incl_index
++] = str
;
8899 if (sym
->n_strx
== 0) {
8900 incl_index
= 0; /* end of translation unit */
8902 str
= stabstr_section
->data
+ sym
->n_strx
;
8903 /* do not add path */
8905 if (len
> 0 && str
[len
- 1] != '/')
8913 /* second pass: we try symtab symbols (no line number info) */
8916 Elf32_Sym
*sym
, *sym_end
;
8919 sym_end
= (Elf32_Sym
*)(symtab_section
->data
+ symtab_section
->data_offset
);
8920 for(sym
= (Elf32_Sym
*)symtab_section
->data
+ 1;
8923 type
= ELF32_ST_TYPE(sym
->st_info
);
8924 if (type
== STT_FUNC
) {
8925 if (wanted_pc
>= sym
->st_value
&&
8926 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
8927 pstrcpy(last_func_name
, sizeof(last_func_name
),
8928 strtab_section
->data
+ sym
->st_name
);
8934 /* did not find any info: */
8935 fprintf(stderr
, " ???\n");
8938 if (last_func_name
[0] != '\0') {
8939 fprintf(stderr
, " %s()", last_func_name
);
8941 if (incl_index
> 0) {
8942 fprintf(stderr
, " (%s:%d",
8943 incl_files
[incl_index
- 1], last_line_num
);
8944 for(i
= incl_index
- 2; i
>= 0; i
--)
8945 fprintf(stderr
, ", included from %s", incl_files
[i
]);
8946 fprintf(stderr
, ")");
8948 fprintf(stderr
, "\n");
8955 /* fix for glibc 2.1 */
8961 /* return the PC at frame level 'level'. Return non zero if not found */
8962 static int rt_get_caller_pc(unsigned long *paddr
,
8963 ucontext_t
*uc
, int level
)
8970 *paddr
= uc
->uc_mcontext
.mc_eip
;
8972 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
8977 fp
= uc
->uc_mcontext
.mc_ebp
;
8979 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
8981 for(i
=1;i
<level
;i
++) {
8982 /* XXX: check address validity with program info */
8983 if (fp
<= 0x1000 || fp
>= 0xc0000000)
8985 fp
= ((unsigned long *)fp
)[0];
8987 *paddr
= ((unsigned long *)fp
)[1];
8992 #error add arch specific rt_get_caller_pc()
8995 /* emit a run time error at position 'pc' */
8996 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
9003 fprintf(stderr
, "Runtime error: ");
9004 vfprintf(stderr
, fmt
, ap
);
9005 fprintf(stderr
, "\n");
9006 for(i
=0;i
<num_callers
;i
++) {
9007 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
9010 fprintf(stderr
, "at ");
9012 fprintf(stderr
, "by ");
9019 /* signal handler for fatal errors */
9020 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
9022 ucontext_t
*uc
= puc
;
9026 switch(siginf
->si_code
) {
9029 rt_error(uc
, "division by zero");
9032 rt_error(uc
, "floating point exception");
9038 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
9039 rt_error(uc
, *rt_bound_error_msg
);
9041 rt_error(uc
, "dereferencing invalid pointer");
9044 rt_error(uc
, "illegal instruction");
9047 rt_error(uc
, "abort() called");
9050 rt_error(uc
, "caught signal %d", signum
);
9057 /* do all relocations (needed before using tcc_get_symbol()) */
9058 int tcc_relocate(TCCState
*s1
)
9065 tcc_add_runtime(s1
);
9067 relocate_common_syms();
9069 /* compute relocation address : section are relocated in place. We
9070 also alloc the bss space */
9071 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9072 s
= s1
->sections
[i
];
9073 if (s
->sh_flags
& SHF_ALLOC
) {
9074 if (s
->sh_type
== SHT_NOBITS
)
9075 s
->data
= tcc_mallocz(s
->data_offset
);
9076 s
->sh_addr
= (unsigned long)s
->data
;
9080 relocate_syms(s1
, 1);
9082 if (s1
->nb_errors
!= 0)
9085 /* relocate each section */
9086 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9087 s
= s1
->sections
[i
];
9089 relocate_section(s1
, s
);
9094 /* launch the compiled program with the given arguments */
9095 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
9097 int (*prog_main
)(int, char **);
9099 if (tcc_relocate(s1
) < 0)
9102 prog_main
= tcc_get_symbol(s1
, "main");
9106 error("debug mode currently not available for Windows");
9108 struct sigaction sigact
;
9109 /* install TCC signal handlers to print debug info on fatal
9111 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
9112 sigact
.sa_sigaction
= sig_error
;
9113 sigemptyset(&sigact
.sa_mask
);
9114 sigaction(SIGFPE
, &sigact
, NULL
);
9115 sigaction(SIGILL
, &sigact
, NULL
);
9116 sigaction(SIGSEGV
, &sigact
, NULL
);
9117 sigaction(SIGBUS
, &sigact
, NULL
);
9118 sigaction(SIGABRT
, &sigact
, NULL
);
9122 #ifdef CONFIG_TCC_BCHECK
9123 if (do_bounds_check
) {
9124 void (*bound_init
)(void);
9126 /* set error function */
9127 rt_bound_error_msg
= (void *)tcc_get_symbol(s1
, "__bound_error_msg");
9129 /* XXX: use .init section so that it also work in binary ? */
9130 bound_init
= (void *)tcc_get_symbol(s1
, "__bound_init");
9134 return (*prog_main
)(argc
, argv
);
9137 TCCState
*tcc_new(void)
9144 s
= tcc_mallocz(sizeof(TCCState
));
9148 s
->output_type
= TCC_OUTPUT_MEMORY
;
9150 /* init isid table */
9152 isidnum_table
[i
] = isid(i
) || isnum(i
);
9154 /* add all tokens */
9156 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
9158 tok_ident
= TOK_IDENT
;
9167 ts
= tok_alloc(p
, r
- p
- 1);
9171 /* we add dummy defines for some special macros to speed up tests
9172 and to have working defined() */
9173 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
9174 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
9175 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
9176 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
9178 /* standard defines */
9179 tcc_define_symbol(s
, "__STDC__", NULL
);
9180 #if defined(TCC_TARGET_I386)
9181 tcc_define_symbol(s
, "__i386__", NULL
);
9184 tcc_define_symbol(s
, "__linux__", NULL
);
9185 tcc_define_symbol(s
, "linux", NULL
);
9187 /* tiny C specific defines */
9188 tcc_define_symbol(s
, "__TINYC__", NULL
);
9190 /* tiny C & gcc defines */
9191 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
9192 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
9193 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
9195 /* default library paths */
9196 tcc_add_library_path(s
, "/usr/local/lib");
9197 tcc_add_library_path(s
, "/usr/lib");
9198 tcc_add_library_path(s
, "/lib");
9200 /* no section zero */
9201 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
9203 /* create standard sections */
9204 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
9205 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
9206 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
9208 /* symbols are always generated for linking stage */
9209 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
9211 ".hashtab", SHF_PRIVATE
);
9212 strtab_section
= symtab_section
->link
;
9214 /* private symbol table for dynamic symbols */
9215 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
9217 ".dynhashtab", SHF_PRIVATE
);
9218 s
->alacarte_link
= 1;
9222 void tcc_delete(TCCState
*s1
)
9226 /* free -D defines */
9230 n
= tok_ident
- TOK_IDENT
;
9231 for(i
= 0; i
< n
; i
++)
9232 tcc_free(table_ident
[i
]);
9233 tcc_free(table_ident
);
9235 /* free all sections */
9237 free_section(symtab_section
->hash
);
9239 free_section(s1
->dynsymtab_section
->hash
);
9240 free_section(s1
->dynsymtab_section
->link
);
9241 free_section(s1
->dynsymtab_section
);
9243 for(i
= 1; i
< s1
->nb_sections
; i
++)
9244 free_section(s1
->sections
[i
]);
9245 tcc_free(s1
->sections
);
9247 /* free loaded dlls array */
9248 for(i
= 0; i
< s1
->nb_loaded_dlls
; i
++)
9249 tcc_free(s1
->loaded_dlls
[i
]);
9250 tcc_free(s1
->loaded_dlls
);
9253 for(i
= 0; i
< s1
->nb_library_paths
; i
++)
9254 tcc_free(s1
->library_paths
[i
]);
9255 tcc_free(s1
->library_paths
);
9257 /* cached includes */
9258 for(i
= 0; i
< s1
->nb_cached_includes
; i
++)
9259 tcc_free(s1
->cached_includes
[i
]);
9260 tcc_free(s1
->cached_includes
);
9262 for(i
= 0; i
< s1
->nb_include_paths
; i
++)
9263 tcc_free(s1
->include_paths
[i
]);
9264 tcc_free(s1
->include_paths
);
9266 for(i
= 0; i
< s1
->nb_sysinclude_paths
; i
++)
9267 tcc_free(s1
->sysinclude_paths
[i
]);
9268 tcc_free(s1
->sysinclude_paths
);
9273 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
9277 pathname1
= tcc_strdup(pathname
);
9278 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
9282 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
9286 pathname1
= tcc_strdup(pathname
);
9287 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
9291 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
9293 const char *ext
, *filename1
;
9296 BufferedFile
*saved_file
;
9298 /* find source file type with extension */
9299 filename1
= strrchr(filename
, '/');
9303 filename1
= filename
;
9304 ext
= strrchr(filename1
, '.');
9310 file
= tcc_open(s1
, filename
);
9312 if (flags
& AFF_PRINT_ERROR
) {
9313 error_noabort("file '%s' not found", filename
);
9319 if (!ext
|| !strcmp(ext
, "c")) {
9320 /* C file assumed */
9321 ret
= tcc_compile(s1
);
9323 #ifdef CONFIG_TCC_ASM
9324 if (!strcmp(ext
, "S")) {
9325 /* preprocessed assembler */
9326 ret
= tcc_assemble(s1
, 1);
9327 } else if (!strcmp(ext
, "s")) {
9328 /* non preprocessed assembler */
9329 ret
= tcc_assemble(s1
, 0);
9334 /* assume executable format: auto guess file type */
9335 if (read(fd
, &ehdr
, sizeof(ehdr
)) != sizeof(ehdr
)) {
9336 error_noabort("could not read header");
9339 lseek(fd
, 0, SEEK_SET
);
9341 if (ehdr
.e_ident
[0] == ELFMAG0
&&
9342 ehdr
.e_ident
[1] == ELFMAG1
&&
9343 ehdr
.e_ident
[2] == ELFMAG2
&&
9344 ehdr
.e_ident
[3] == ELFMAG3
) {
9345 file
->line_num
= 0; /* do not display line number if error */
9346 if (ehdr
.e_type
== ET_REL
) {
9347 ret
= tcc_load_object_file(s1
, fd
, 0);
9348 } else if (ehdr
.e_type
== ET_DYN
) {
9349 ret
= tcc_load_dll(s1
, fd
, filename
,
9350 (flags
& AFF_REFERENCED_DLL
) != 0);
9352 error_noabort("unrecognized ELF file");
9355 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
9356 file
->line_num
= 0; /* do not display line number if error */
9357 ret
= tcc_load_archive(s1
, fd
);
9359 /* as GNU ld, consider it is an ld script if not recognized */
9360 ret
= tcc_load_ldscript(s1
);
9362 error_noabort("unrecognized file type");
9377 int tcc_add_file(TCCState
*s
, const char *filename
)
9379 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
9382 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
9386 pathname1
= tcc_strdup(pathname
);
9387 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
9391 /* find and load a dll. Return non zero if not found */
9392 /* XXX: add '-rpath' option support ? */
9393 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
9398 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9399 snprintf(buf
, sizeof(buf
), "%s/%s",
9400 s
->library_paths
[i
], filename
);
9401 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
9407 /* the library name is the same as the argument of the '-l' option */
9408 int tcc_add_library(TCCState
*s
, const char *libraryname
)
9414 /* first we look for the dynamic library if not static linking */
9415 if (!s
->static_link
) {
9416 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
9417 /* if we output to memory, then we simply we dlopen(). */
9418 if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
9419 /* Since the libc is already loaded, we don't need to load it again */
9420 if (!strcmp(libraryname
, "c"))
9422 h
= dlopen(buf
, RTLD_GLOBAL
| RTLD_LAZY
);
9426 if (tcc_add_dll(s
, buf
, 0) == 0)
9431 /* then we look for the static library */
9432 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9433 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
9434 s
->library_paths
[i
], libraryname
);
9435 if (tcc_add_file_internal(s
, buf
, 0) == 0)
9441 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
9443 add_elf_sym(symtab_section
, val
, 0,
9444 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
),
9449 int tcc_set_output_type(TCCState
*s
, int output_type
)
9453 s
->output_type
= output_type
;
9456 /* default include paths */
9457 /* XXX: reverse order needed if -isystem support */
9458 tcc_add_sysinclude_path(s
, "/usr/local/include");
9459 tcc_add_sysinclude_path(s
, "/usr/include");
9460 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
9461 tcc_add_sysinclude_path(s
, buf
);
9464 /* if bound checking, then add corresponding sections */
9465 #ifdef CONFIG_TCC_BCHECK
9466 if (do_bounds_check
) {
9468 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
9469 /* create bounds sections */
9470 bounds_section
= new_section(s
, ".bounds",
9471 SHT_PROGBITS
, SHF_ALLOC
);
9472 lbounds_section
= new_section(s
, ".lbounds",
9473 SHT_PROGBITS
, SHF_ALLOC
);
9477 /* add debug sections */
9480 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
9481 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
9482 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
9483 put_elf_str(stabstr_section
, "");
9484 stab_section
->link
= stabstr_section
;
9485 /* put first entry */
9486 put_stabs("", 0, 0, 0, 0);
9489 /* add libc crt1/crti objects */
9490 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
9492 if (output_type
!= TCC_OUTPUT_DLL
)
9493 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
9494 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
9499 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
9501 typedef struct WarningDef
{
9507 static const WarningDef warning_defs
[] = {
9508 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
9509 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
9510 { offsetof(TCCState
, warn_error
), 0, "error" },
9513 /* set/reset a warning */
9514 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
9517 const WarningDef
*p
;
9518 if (!strcmp(warning_name
, "all")) {
9519 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
9520 if (p
->flags
& WD_ALL
)
9521 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
9524 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
9525 if (!strcmp(warning_name
, p
->name
))
9530 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
9536 #if !defined(LIBTCC)
9538 /* extract the basename of a file */
9539 static const char *tcc_basename(const char *name
)
9542 p
= strrchr(name
, '/');
9545 p
= strrchr(name
, '\\');
9554 static int64_t getclock_us(void)
9559 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
9562 gettimeofday(&tv
, NULL
);
9563 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
9569 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2003 Fabrice Bellard\n"
9570 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
9571 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]\n"
9572 " [infile1 infile2...] [-run infile args...]\n"
9574 "General options:\n"
9575 " -v display current version\n"
9576 " -c compile only - generate an object file\n"
9577 " -o outfile set output filename\n"
9578 " -Bdir set tcc internal library path\n"
9579 " -bench output compilation statistics\n"
9580 " -run run compiled source\n"
9581 " -Wwarning set or reset (with 'no-' prefix) 'warning'\n"
9582 "Preprocessor options:\n"
9583 " -Idir add include path 'dir'\n"
9584 " -Dsym[=val] define 'sym' with value 'val'\n"
9585 " -Usym undefine 'sym'\n"
9587 " -Ldir add library path 'dir'\n"
9588 " -llib link with dynamic or static library 'lib'\n"
9589 " -shared generate a shared library\n"
9590 " -static static linking\n"
9591 " -rdynamic export all global symbols to dynamic linker\n"
9592 " -r relocatable output\n"
9593 "Debugger options:\n"
9594 " -g generate runtime debug info\n"
9595 #ifdef CONFIG_TCC_BCHECK
9596 " -b compile with built-in memory and bounds checker (implies -g)\n"
9598 " -bt N show N callers in stack traces\n"
9602 #define TCC_OPTION_HAS_ARG 0x0001
9603 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
9605 typedef struct TCCOption
{
9632 TCC_OPTION_nostdinc
,
9633 TCC_OPTION_nostdlib
,
9634 TCC_OPTION_print_search_dirs
,
9635 TCC_OPTION_rdynamic
,
9640 static const TCCOption tcc_options
[] = {
9641 { "h", TCC_OPTION_HELP
, 0 },
9642 { "?", TCC_OPTION_HELP
, 0 },
9643 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
9644 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
9645 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
9646 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
9647 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
9648 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9649 { "bench", TCC_OPTION_bench
, 0 },
9650 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
9651 #ifdef CONFIG_TCC_BCHECK
9652 { "b", TCC_OPTION_b
, 0 },
9654 { "g", TCC_OPTION_g
, 0 },
9655 { "c", TCC_OPTION_c
, 0 },
9656 { "static", TCC_OPTION_static
, 0 },
9657 { "shared", TCC_OPTION_shared
, 0 },
9658 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
9659 { "run", TCC_OPTION_run
, 0 },
9660 { "rdynamic", TCC_OPTION_rdynamic
, 0 },
9661 { "r", TCC_OPTION_r
, 0 },
9662 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9663 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9664 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
9665 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
9666 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
9667 { "nostdlib", TCC_OPTION_nostdlib
, 0 },
9668 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
9669 { "v", TCC_OPTION_v
, 0 },
9673 int main(int argc
, char **argv
)
9676 int optind
, output_type
, multiple_files
, i
, reloc_output
;
9679 int nb_files
, nb_libraries
, nb_objfiles
, dminus
, ret
;
9680 char objfilename
[1024];
9681 int64_t start_time
= 0;
9682 const TCCOption
*popt
;
9683 const char *optarg
, *p1
, *r1
, *outfile
;
9684 int print_search_dirs
;
9687 output_type
= TCC_OUTPUT_EXE
;
9697 print_search_dirs
= 0;
9699 if (optind
>= argc
) {
9700 if (nb_files
== 0 && !print_search_dirs
)
9707 /* add a new file */
9708 dynarray_add((void ***)&files
, &nb_files
, r
);
9709 if (!multiple_files
) {
9711 /* argv[0] will be this file */
9715 /* find option in table (match only the first chars */
9720 error("invalid option -- '%s'", r
);
9733 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
9734 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
9738 error("argument to '%s' is missing", r
);
9739 optarg
= argv
[optind
++];
9747 switch(popt
->index
) {
9748 case TCC_OPTION_HELP
:
9753 if (tcc_add_include_path(s
, optarg
) < 0)
9754 error("too many include paths");
9759 sym
= (char *)optarg
;
9760 value
= strchr(sym
, '=');
9765 tcc_define_symbol(s
, sym
, value
);
9769 tcc_undefine_symbol(s
, optarg
);
9772 tcc_add_library_path(s
, optarg
);
9775 /* set tcc utilities path (mainly for tcc development) */
9776 tcc_lib_path
= optarg
;
9779 dynarray_add((void ***)&files
, &nb_files
, r
);
9782 case TCC_OPTION_bench
:
9786 num_callers
= atoi(optarg
);
9788 #ifdef CONFIG_TCC_BCHECK
9790 do_bounds_check
= 1;
9799 output_type
= TCC_OUTPUT_OBJ
;
9801 case TCC_OPTION_static
:
9804 case TCC_OPTION_shared
:
9805 output_type
= TCC_OUTPUT_DLL
;
9812 /* generate a .o merging several output files */
9814 output_type
= TCC_OUTPUT_OBJ
;
9816 case TCC_OPTION_nostdinc
:
9819 case TCC_OPTION_nostdlib
:
9822 case TCC_OPTION_print_search_dirs
:
9823 print_search_dirs
= 1;
9825 case TCC_OPTION_run
:
9827 output_type
= TCC_OUTPUT_MEMORY
;
9830 printf("tcc version %s\n", TCC_VERSION
);
9834 const char *p
= optarg
;
9837 if (p
[0] == 'n' && p
[1] == 'o' && p
[2] == '-') {
9841 if (tcc_set_warning(s
, p
, value
) < 0 && s
->warn_unsupported
)
9842 goto unsupported_option
;
9845 case TCC_OPTION_rdynamic
:
9849 if (s
->warn_unsupported
) {
9851 warning("unsupported option '%s'", r
);
9857 if (print_search_dirs
) {
9858 /* enough for Linux kernel */
9859 printf("install: %s/\n", tcc_lib_path
);
9863 nb_objfiles
= nb_files
- nb_libraries
;
9865 /* if outfile provided without other options, we output an
9867 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
9868 output_type
= TCC_OUTPUT_EXE
;
9870 /* check -c consistency : only single file handled. XXX: checks file type */
9871 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
9872 /* accepts only a single input file */
9873 if (nb_objfiles
!= 1)
9874 error("cannot specify multiple files with -c");
9875 if (nb_libraries
!= 0)
9876 error("cannot specify libraries with -c");
9879 /* compute default outfile name */
9880 if (output_type
!= TCC_OUTPUT_MEMORY
&& !outfile
) {
9881 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
9884 pstrcpy(objfilename
, sizeof(objfilename
) - 1,
9885 tcc_basename(files
[0]));
9886 /* add .o extension */
9887 ext
= strrchr(objfilename
, '.');
9889 goto default_outfile
;
9890 strcpy(ext
+ 1, "o");
9893 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
9895 outfile
= objfilename
;
9899 start_time
= getclock_us();
9902 tcc_set_output_type(s
, output_type
);
9904 /* compile or add each files or library */
9905 for(i
= 0;i
< nb_files
; i
++) {
9906 const char *filename
;
9908 filename
= files
[i
];
9909 if (filename
[0] == '-') {
9910 if (tcc_add_library(s
, filename
+ 2) < 0)
9911 error("cannot find %s", filename
);
9913 if (tcc_add_file(s
, filename
) < 0) {
9920 /* free all files */
9925 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
9926 if (total_time
< 0.001)
9928 if (total_bytes
< 1)
9930 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
9931 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
9932 total_time
, (int)(total_lines
/ total_time
),
9933 total_bytes
/ total_time
/ 1000000.0);
9936 if (s
->output_type
!= TCC_OUTPUT_MEMORY
) {
9937 tcc_output_file(s
, outfile
);
9940 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
9943 /* XXX: cannot do it with bound checking because of the malloc hooks */
9944 if (!do_bounds_check
)
9949 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);