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
26 #define CONFIG_TCC_STATIC
43 #include <sys/timeb.h>
44 #define CONFIG_TCC_STATIC
48 #include <sys/ucontext.h>
51 #endif /* !CONFIG_TCCBOOT */
55 #ifndef CONFIG_TCC_STATIC
66 /* preprocessor debug */
68 /* include file debug */
76 /* target selection */
77 //#define TCC_TARGET_I386 /* i386 code generator */
78 //#define TCC_TARGET_ARM /* ARMv4 code generator */
79 //#define TCC_TARGET_C67 /* TMS320C67xx code generator */
81 /* default target is I386 */
82 #if !defined(TCC_TARGET_I386) && !defined(TCC_TARGET_ARM) && \
83 !defined(TCC_TARGET_C67)
84 #define TCC_TARGET_I386
87 #if !defined(WIN32) && !defined(TCC_UCLIBC) && !defined(TCC_TARGET_ARM) && \
88 !defined(TCC_TARGET_C67)
89 #define CONFIG_TCC_BCHECK /* enable bound checking code */
92 /* define it to include assembler support */
93 #if !defined(TCC_TARGET_ARM) && !defined(TCC_TARGET_C67)
94 #define CONFIG_TCC_ASM
97 /* object format selection */
98 #if defined(TCC_TARGET_C67)
99 #define TCC_TARGET_COFF
108 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
109 executables or dlls */
110 #define CONFIG_TCC_CRT_PREFIX "/usr/lib"
112 #define INCLUDE_STACK_SIZE 32
113 #define IFDEF_STACK_SIZE 64
114 #define VSTACK_SIZE 64
115 #define STRING_MAX_SIZE 1024
117 #define TOK_HASH_SIZE 8192 /* must be a power of two */
118 #define TOK_ALLOC_INCR 512 /* must be a power of two */
119 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
121 /* token symbol management */
122 typedef struct TokenSym
{
123 struct TokenSym
*hash_next
;
124 struct Sym
*sym_define
; /* direct pointer to define */
125 struct Sym
*sym_label
; /* direct pointer to label */
126 struct Sym
*sym_struct
; /* direct pointer to structure */
127 struct Sym
*sym_identifier
; /* direct pointer to identifier */
128 int tok
; /* token number */
133 typedef struct CString
{
134 int size
; /* size in bytes */
135 void *data
; /* either 'char *' or 'int *' */
137 void *data_allocated
; /* if non NULL, data has been malloced */
140 /* type definition */
141 typedef struct CType
{
147 typedef union CValue
{
153 unsigned int ul
; /* address (should be unsigned long on 64 bit cpu) */
155 unsigned long long ull
;
156 struct CString
*cstr
;
162 typedef struct SValue
{
163 CType type
; /* type */
164 unsigned short r
; /* register + flags */
165 unsigned short r2
; /* second register, used for 'long long'
166 type. If not used, set to VT_CONST */
167 CValue c
; /* constant, if VT_CONST */
168 struct Sym
*sym
; /* symbol, if (VT_SYM | VT_CONST) */
171 /* symbol management */
173 int v
; /* symbol token */
174 int r
; /* associated register */
175 int c
; /* associated number */
176 CType type
; /* associated type */
177 struct Sym
*next
; /* next related symbol */
178 struct Sym
*prev
; /* prev symbol in stack */
179 struct Sym
*prev_tok
; /* previous symbol for this token */
182 /* section definition */
183 /* XXX: use directly ELF structure for parameters ? */
184 /* special flag to indicate that the section should not be linked to
186 #define SHF_PRIVATE 0x80000000
188 typedef struct Section
{
189 unsigned long data_offset
; /* current data offset */
190 unsigned char *data
; /* section data */
191 unsigned long data_allocated
; /* used for realloc() handling */
192 int sh_name
; /* elf section name (only used during output) */
193 int sh_num
; /* elf section number */
194 int sh_type
; /* elf section type */
195 int sh_flags
; /* elf section flags */
196 int sh_info
; /* elf section info */
197 int sh_addralign
; /* elf section alignment */
198 int sh_entsize
; /* elf entry size */
199 unsigned long sh_size
; /* section size (only used during output) */
200 unsigned long sh_addr
; /* address at which the section is relocated */
201 unsigned long sh_offset
; /* address at which the section is relocated */
202 int nb_hashed_syms
; /* used to resize the hash table */
203 struct Section
*link
; /* link to another section */
204 struct Section
*reloc
; /* corresponding section for relocation, if any */
205 struct Section
*hash
; /* hash table for symbols */
206 struct Section
*next
;
207 char name
[1]; /* section name */
210 typedef struct DLLReference
{
215 /* GNUC attribute definition */
216 typedef struct AttributeDef
{
219 unsigned char func_call
; /* FUNC_CDECL, FUNC_STDCALL, FUNC_FASTCALLx */
222 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
223 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
224 #define SYM_FIRST_ANOM 0x10000000 /* first anonymous sym */
226 /* stored in 'Sym.c' field */
227 #define FUNC_NEW 1 /* ansi function prototype */
228 #define FUNC_OLD 2 /* old function prototype */
229 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
231 /* stored in 'Sym.r' field */
232 #define FUNC_CDECL 0 /* standard c call */
233 #define FUNC_STDCALL 1 /* pascal c call */
234 #define FUNC_FASTCALL1 2 /* first param in %eax */
235 #define FUNC_FASTCALL2 3 /* first parameters in %eax, %edx */
236 #define FUNC_FASTCALL3 4 /* first parameter in %eax, %edx, %ecx */
238 /* field 'Sym.t' for macros */
239 #define MACRO_OBJ 0 /* object like macro */
240 #define MACRO_FUNC 1 /* function like macro */
242 /* field 'Sym.r' for C labels */
243 #define LABEL_DEFINED 0 /* label is defined */
244 #define LABEL_FORWARD 1 /* label is forward defined */
245 #define LABEL_DECLARED 2 /* label is declared but never used */
247 /* type_decl() types */
248 #define TYPE_ABSTRACT 1 /* type without variable */
249 #define TYPE_DIRECT 2 /* type with variable */
251 #define IO_BUF_SIZE 8192
253 typedef struct BufferedFile
{
257 int line_num
; /* current line number - here to simplify code */
258 int ifndef_macro
; /* #ifndef macro / #endif search */
259 int ifndef_macro_saved
; /* saved ifndef_macro */
260 int *ifdef_stack_ptr
; /* ifdef_stack value at the start of the file */
261 char inc_type
; /* type of include */
262 char inc_filename
[512]; /* filename specified by the user */
263 char filename
[1024]; /* current filename - here to simplify code */
264 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
267 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
268 #define CH_EOF (-1) /* end of file */
270 /* parsing state (used to save parser state to reparse part of the
271 source several times) */
272 typedef struct ParseState
{
279 /* used to record tokens */
280 typedef struct TokenString
{
287 /* include file cache, used to find files faster and also to eliminate
288 inclusion if the include file is protected by #ifndef ... #endif */
289 typedef struct CachedInclude
{
291 char type
; /* '"' or '>' to give include type */
292 char filename
[1]; /* path specified in #include */
296 static struct BufferedFile
*file
;
299 static CString tokcstr
; /* current parsed string, if any */
300 /* additional informations about token */
301 static int tok_flags
;
302 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
303 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
304 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
306 static int *macro_ptr
, *macro_ptr_allocated
;
307 static int *unget_saved_macro_ptr
;
308 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
309 static int unget_buffer_enabled
;
310 static int parse_flags
;
311 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
312 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
313 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
314 token. line feed is also
316 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
318 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
319 static Section
*cur_text_section
; /* current section where function code is
321 static Section
*last_text_section
; /* to handle .previous asm directive */
322 /* bound check related sections */
323 static Section
*bounds_section
; /* contains global data bound description */
324 static Section
*lbounds_section
; /* contains local data bound description */
325 /* symbol sections */
326 static Section
*symtab_section
, *strtab_section
;
329 static Section
*stab_section
, *stabstr_section
;
331 /* loc : local variable index
332 ind : output code index
334 anon_sym: anonymous symbol index
336 static int rsym
, anon_sym
, ind
, loc
;
337 /* expression generation modifiers */
338 static int const_wanted
; /* true if constant wanted */
339 static int nocode_wanted
; /* true if no code generation wanted for an expression */
340 static int global_expr
; /* true if compound literals must be allocated
341 globally (used during initializers parsing */
342 static CType func_vt
; /* current function return type (used by return
345 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
346 static int tok_ident
;
347 static TokenSym
**table_ident
;
348 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
349 static char token_buf
[STRING_MAX_SIZE
+ 1];
350 static char *funcname
;
351 static Sym
*global_stack
, *local_stack
;
352 static Sym
*define_stack
;
353 static Sym
*global_label_stack
, *local_label_stack
;
355 static SValue vstack
[VSTACK_SIZE
], *vtop
;
356 /* some predefined types */
357 static CType char_pointer_type
, func_old_type
, int_type
;
358 /* true if isid(c) || isnum(c) */
359 static unsigned char isidnum_table
[256];
361 /* compile with debug symbol (and use them if error during execution) */
362 static int do_debug
= 0;
364 /* compile with built-in memory and bounds checker */
365 static int do_bounds_check
= 0;
367 /* display benchmark infos */
369 static int do_bench
= 0;
371 static int total_lines
;
372 static int total_bytes
;
374 /* use GNU C extensions */
375 static int gnu_ext
= 1;
377 /* use Tiny C extensions */
378 static int tcc_ext
= 1;
380 /* max number of callers shown if error */
381 static int num_callers
= 6;
382 static const char **rt_bound_error_msg
;
384 /* XXX: get rid of this ASAP */
385 static struct TCCState
*tcc_state
;
387 /* give the path of the tcc libraries */
388 static const char *tcc_lib_path
= CONFIG_TCC_LIBDIR
"/tcc";
393 BufferedFile
**include_stack_ptr
;
394 int *ifdef_stack_ptr
;
396 /* include file handling */
397 char **include_paths
;
398 int nb_include_paths
;
399 char **sysinclude_paths
;
400 int nb_sysinclude_paths
;
401 CachedInclude
**cached_includes
;
402 int nb_cached_includes
;
404 char **library_paths
;
405 int nb_library_paths
;
407 /* array of all loaded dlls (including those referenced by loaded
409 DLLReference
**loaded_dlls
;
414 int nb_sections
; /* number of sections, including first dummy section */
419 unsigned long *got_offsets
;
421 /* give the correspondance from symtab indexes to dynsym indexes */
422 int *symtab_to_dynsym
;
424 /* temporary dynamic symbol sections (for dll loading) */
425 Section
*dynsymtab_section
;
426 /* exported dynamic symbol section */
429 int nostdinc
; /* if true, no standard headers are added */
430 int nostdlib
; /* if true, no standard libraries are added */
432 int nocommon
; /* if true, do not use common symbols for .bss data */
434 /* if true, static linking is performed */
437 /* if true, all symbols are exported */
440 /* if true, only link in referenced objects from archive */
443 /* address of text section */
444 unsigned long text_addr
;
447 /* output format, see TCC_OUTPUT_FORMAT_xxx */
450 /* C language options */
451 int char_is_unsigned
;
453 /* warning switches */
454 int warn_write_strings
;
455 int warn_unsupported
;
458 int warn_implicit_function_declaration
;
462 void (*error_func
)(void *opaque
, const char *msg
);
463 int error_set_jmp_enabled
;
464 jmp_buf error_jmp_buf
;
467 /* tiny assembler state */
470 /* see include_stack_ptr */
471 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
473 /* see ifdef_stack_ptr */
474 int ifdef_stack
[IFDEF_STACK_SIZE
];
477 /* The current value can be: */
478 #define VT_VALMASK 0x00ff
479 #define VT_CONST 0x00f0 /* constant in vc
480 (must be first non register value) */
481 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
482 #define VT_LOCAL 0x00f2 /* offset on stack */
483 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
484 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
485 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
486 #define VT_LVAL 0x0100 /* var is an lvalue */
487 #define VT_SYM 0x0200 /* a symbol value is added */
488 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
489 char/short stored in integer registers) */
490 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
491 dereferencing value */
492 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
493 bounding function call point is in vc */
494 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
495 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
496 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
497 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
500 #define VT_INT 0 /* integer type */
501 #define VT_BYTE 1 /* signed byte type */
502 #define VT_SHORT 2 /* short type */
503 #define VT_VOID 3 /* void type */
504 #define VT_PTR 4 /* pointer */
505 #define VT_ENUM 5 /* enum definition */
506 #define VT_FUNC 6 /* function type */
507 #define VT_STRUCT 7 /* struct/union definition */
508 #define VT_FLOAT 8 /* IEEE float */
509 #define VT_DOUBLE 9 /* IEEE double */
510 #define VT_LDOUBLE 10 /* IEEE long double */
511 #define VT_BOOL 11 /* ISOC99 boolean type */
512 #define VT_LLONG 12 /* 64 bit integer */
513 #define VT_LONG 13 /* long integer (NEVER USED as type, only
515 #define VT_BTYPE 0x000f /* mask for basic type */
516 #define VT_UNSIGNED 0x0010 /* unsigned type */
517 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
518 #define VT_BITFIELD 0x0040 /* bitfield modifier */
519 #define VT_CONSTANT 0x0800 /* const modifier */
520 #define VT_VOLATILE 0x1000 /* volatile modifier */
521 #define VT_SIGNED 0x2000 /* signed type */
524 #define VT_EXTERN 0x00000080 /* extern definition */
525 #define VT_STATIC 0x00000100 /* static variable */
526 #define VT_TYPEDEF 0x00000200 /* typedef definition */
527 #define VT_INLINE 0x00000400 /* inline definition */
529 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
531 /* type mask (except storage) */
532 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
533 #define VT_TYPE (~(VT_STORAGE))
537 /* warning: the following compare tokens depend on i386 asm code */
549 #define TOK_LAND 0xa0
553 #define TOK_MID 0xa3 /* inc/dec, to void constant */
555 #define TOK_UDIV 0xb0 /* unsigned division */
556 #define TOK_UMOD 0xb1 /* unsigned modulo */
557 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
558 #define TOK_CINT 0xb3 /* number in tokc */
559 #define TOK_CCHAR 0xb4 /* char constant in tokc */
560 #define TOK_STR 0xb5 /* pointer to string in tokc */
561 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
562 #define TOK_LCHAR 0xb7
563 #define TOK_LSTR 0xb8
564 #define TOK_CFLOAT 0xb9 /* float constant */
565 #define TOK_LINENUM 0xba /* line number info */
566 #define TOK_CDOUBLE 0xc0 /* double constant */
567 #define TOK_CLDOUBLE 0xc1 /* long double constant */
568 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
569 #define TOK_ADDC1 0xc3 /* add with carry generation */
570 #define TOK_ADDC2 0xc4 /* add with carry use */
571 #define TOK_SUBC1 0xc5 /* add with carry generation */
572 #define TOK_SUBC2 0xc6 /* add with carry use */
573 #define TOK_CUINT 0xc8 /* unsigned int constant */
574 #define TOK_CLLONG 0xc9 /* long long constant */
575 #define TOK_CULLONG 0xca /* unsigned long long constant */
576 #define TOK_ARROW 0xcb
577 #define TOK_DOTS 0xcc /* three dots */
578 #define TOK_SHR 0xcd /* unsigned shift right */
579 #define TOK_PPNUM 0xce /* preprocessor number */
581 #define TOK_SHL 0x01 /* shift left */
582 #define TOK_SAR 0x02 /* signed shift right */
584 /* assignement operators : normal operator or 0x80 */
585 #define TOK_A_MOD 0xa5
586 #define TOK_A_AND 0xa6
587 #define TOK_A_MUL 0xaa
588 #define TOK_A_ADD 0xab
589 #define TOK_A_SUB 0xad
590 #define TOK_A_DIV 0xaf
591 #define TOK_A_XOR 0xde
592 #define TOK_A_OR 0xfc
593 #define TOK_A_SHL 0x81
594 #define TOK_A_SAR 0x82
597 #define offsetof(type, field) ((size_t) &((type *)0)->field)
601 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
604 /* WARNING: the content of this string encodes token numbers */
605 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";
607 #define TOK_EOF (-1) /* end of file */
608 #define TOK_LINEFEED 10 /* line feed */
610 /* all identificators and strings have token above that */
611 #define TOK_IDENT 256
613 /* only used for i386 asm opcodes definitions */
614 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
617 DEF(TOK_ASM_ ## x ## b, #x "b") \
618 DEF(TOK_ASM_ ## x ## w, #x "w") \
619 DEF(TOK_ASM_ ## x ## l, #x "l") \
620 DEF(TOK_ASM_ ## x, #x)
623 DEF(TOK_ASM_ ## x ## w, #x "w") \
624 DEF(TOK_ASM_ ## x ## l, #x "l") \
625 DEF(TOK_ASM_ ## x, #x)
628 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
629 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
630 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
631 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
634 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
635 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
638 #define DEF_ASMTEST(x) \
670 #define TOK_ASM_int TOK_INT
673 TOK_LAST
= TOK_IDENT
- 1,
674 #define DEF(id, str) id,
679 static const char tcc_keywords
[] =
680 #define DEF(id, str) str "\0"
685 #define TOK_UIDENT TOK_DEFINE
688 #define snprintf _snprintf
689 #define vsnprintf _vsnprintf
692 #if defined(WIN32) || defined(TCC_UCLIBC) || defined(__FreeBSD__)
693 /* currently incorrect */
694 long double strtold(const char *nptr
, char **endptr
)
696 return (long double)strtod(nptr
, endptr
);
698 float strtof(const char *nptr
, char **endptr
)
700 return (float)strtod(nptr
, endptr
);
703 /* XXX: need to define this to use them in non ISOC99 context */
704 extern float strtof (const char *__nptr
, char **__endptr
);
705 extern long double strtold (const char *__nptr
, char **__endptr
);
708 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
709 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
711 static void next(void);
712 static void next_nomacro(void);
713 static void parse_expr_type(CType
*type
);
714 static void expr_type(CType
*type
);
715 static void unary_type(CType
*type
);
716 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
717 int case_reg
, int is_expr
);
718 static int expr_const(void);
719 static void expr_eq(void);
720 static void gexpr(void);
721 static void gen_inline_functions(void);
722 static void decl(int l
);
723 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
724 int first
, int size_only
);
725 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
726 int has_init
, int v
, int scope
);
728 void gv2(int rc1
, int rc2
);
729 void move_reg(int r
, int s
);
730 void save_regs(int n
);
731 void save_reg(int r
);
736 int get_reg_ex(int rc
,int rc2
);
738 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
739 const int *macro_str
, int can_read_stream
);
741 void force_charshort_cast(int t
);
742 static void gen_cast(CType
*type
);
744 static Sym
*sym_find(int v
);
745 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
748 static int type_size(CType
*type
, int *a
);
749 static inline CType
*pointed_type(CType
*type
);
750 static int pointed_size(CType
*type
);
751 static int lvalue_type(int t
);
752 static int parse_btype(CType
*type
, AttributeDef
*ad
);
753 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
754 static int is_compatible_types(CType
*type1
, CType
*type2
);
756 int ieee_finite(double d
);
757 void error(const char *fmt
, ...);
761 void lexpand_nr(void);
762 static void vpush_global_sym(CType
*type
, int v
);
763 void vset(CType
*type
, int r
, int v
);
764 void type_to_str(char *buf
, int buf_size
,
765 CType
*type
, const char *varstr
);
766 char *get_tok_str(int v
, CValue
*cv
);
767 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
768 unsigned long offset
, unsigned long size
);
769 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
771 /* section generation */
772 static void section_realloc(Section
*sec
, unsigned long new_size
);
773 static void *section_ptr_add(Section
*sec
, unsigned long size
);
774 static void put_extern_sym(Sym
*sym
, Section
*section
,
775 unsigned long value
, unsigned long size
);
776 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
777 static int put_elf_str(Section
*s
, const char *sym
);
778 static int put_elf_sym(Section
*s
,
779 unsigned long value
, unsigned long size
,
780 int info
, int other
, int shndx
, const char *name
);
781 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
782 int info
, int sh_num
, const char *name
);
783 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
784 int type
, int symbol
);
785 static void put_stabs(const char *str
, int type
, int other
, int desc
,
786 unsigned long value
);
787 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
788 unsigned long value
, Section
*sec
, int sym_index
);
789 static void put_stabn(int type
, int other
, int desc
, int value
);
790 static void put_stabd(int type
, int other
, int desc
);
791 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
793 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
794 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
795 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
798 int tcc_output_coff(TCCState
*s1
, FILE *f
);
802 #ifdef CONFIG_TCC_ASM
804 typedef struct ExprValue
{
809 #define MAX_ASM_OPERANDS 30
811 typedef struct ASMOperand
{
812 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
814 char asm_str
[16]; /* computed asm string for operand */
815 SValue
*vt
; /* C value of the expression */
816 int ref_index
; /* if >= 0, gives reference to a output constraint */
817 int input_index
; /* if >= 0, gives reference to an input constraint */
818 int priority
; /* priority, used to assign registers */
819 int reg
; /* if >= 0, register number used for this operand */
820 int is_llong
; /* true if double register value */
821 int is_memory
; /* true if memory operand */
822 int is_rw
; /* for '+' modifier */
825 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
826 static int asm_int_expr(TCCState
*s1
);
827 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
828 const char *name
, const char **pp
);
830 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
834 static void asm_instr(void);
835 static void asm_global_instr(void);
837 /* true if float/double/long double type */
838 static inline int is_float(int t
)
842 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
845 #ifdef TCC_TARGET_I386
846 #include "i386-gen.c"
849 #ifdef TCC_TARGET_ARM
853 #ifdef TCC_TARGET_C67
857 #ifdef CONFIG_TCC_STATIC
859 #define RTLD_LAZY 0x001
860 #define RTLD_NOW 0x002
861 #define RTLD_GLOBAL 0x100
862 #define RTLD_DEFAULT NULL
864 /* dummy function for profiling */
865 void *dlopen(const char *filename
, int flag
)
870 const char *dlerror(void)
875 typedef struct TCCSyms
{
880 #define TCCSYM(a) { #a, &a, },
882 /* add the symbol you want here if no dynamic linking is done */
883 static TCCSyms tcc_syms
[] = {
884 #if !defined(CONFIG_TCCBOOT)
893 void *dlsym(void *handle
, const char *symbol
)
897 while (p
->str
!= NULL
) {
898 if (!strcmp(p
->str
, symbol
))
907 /********************************************************/
909 /* we use our own 'finite' function to avoid potential problems with
910 non standard math libs */
911 /* XXX: endianness dependent */
912 int ieee_finite(double d
)
915 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
918 /* copy a string and truncate it. */
919 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
926 q_end
= buf
+ buf_size
- 1;
938 /* strcat and truncate. */
939 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
944 pstrcpy(buf
+ len
, buf_size
- len
, s
);
948 static int strstart(const char *str
, const char *val
, const char **ptr
)
964 /* memory management */
970 static inline void tcc_free(void *ptr
)
973 mem_cur_size
-= malloc_usable_size(ptr
);
978 static void *tcc_malloc(unsigned long size
)
983 error("memory full");
985 mem_cur_size
+= malloc_usable_size(ptr
);
986 if (mem_cur_size
> mem_max_size
)
987 mem_max_size
= mem_cur_size
;
992 static void *tcc_mallocz(unsigned long size
)
995 ptr
= tcc_malloc(size
);
996 memset(ptr
, 0, size
);
1000 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
1004 mem_cur_size
-= malloc_usable_size(ptr
);
1006 ptr1
= realloc(ptr
, size
);
1008 /* NOTE: count not correct if alloc error, but not critical */
1009 mem_cur_size
+= malloc_usable_size(ptr1
);
1010 if (mem_cur_size
> mem_max_size
)
1011 mem_max_size
= mem_cur_size
;
1016 static char *tcc_strdup(const char *str
)
1019 ptr
= tcc_malloc(strlen(str
) + 1);
1024 #define free(p) use_tcc_free(p)
1025 #define malloc(s) use_tcc_malloc(s)
1026 #define realloc(p, s) use_tcc_realloc(p, s)
1028 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
1035 /* every power of two we double array size */
1036 if ((nb
& (nb
- 1)) == 0) {
1041 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
1043 error("memory full");
1050 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
1054 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
1055 strcpy(sec
->name
, name
);
1056 sec
->sh_type
= sh_type
;
1057 sec
->sh_flags
= sh_flags
;
1064 sec
->sh_addralign
= 4;
1067 sec
->sh_addralign
= 1;
1070 sec
->sh_addralign
= 32; /* default conservative alignment */
1074 /* only add section if not private */
1075 if (!(sh_flags
& SHF_PRIVATE
)) {
1076 sec
->sh_num
= s1
->nb_sections
;
1077 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
1082 static void free_section(Section
*s
)
1088 /* realloc section and set its content to zero */
1089 static void section_realloc(Section
*sec
, unsigned long new_size
)
1092 unsigned char *data
;
1094 size
= sec
->data_allocated
;
1097 while (size
< new_size
)
1099 data
= tcc_realloc(sec
->data
, size
);
1101 error("memory full");
1102 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1104 sec
->data_allocated
= size
;
1107 /* reserve at least 'size' bytes in section 'sec' from
1108 sec->data_offset. */
1109 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1111 unsigned long offset
, offset1
;
1113 offset
= sec
->data_offset
;
1114 offset1
= offset
+ size
;
1115 if (offset1
> sec
->data_allocated
)
1116 section_realloc(sec
, offset1
);
1117 sec
->data_offset
= offset1
;
1118 return sec
->data
+ offset
;
1121 /* return a reference to a section, and create it if it does not
1123 Section
*find_section(TCCState
*s1
, const char *name
)
1127 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1128 sec
= s1
->sections
[i
];
1129 if (!strcmp(name
, sec
->name
))
1132 /* sections are created as PROGBITS */
1133 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1136 #define SECTION_ABS ((void *)1)
1138 /* update sym->c so that it points to an external symbol in section
1139 'section' with value 'value' */
1140 static void put_extern_sym(Sym
*sym
, Section
*section
,
1141 unsigned long value
, unsigned long size
)
1143 int sym_type
, sym_bind
, sh_num
, info
;
1147 if (section
== NULL
)
1149 else if (section
== SECTION_ABS
)
1152 sh_num
= section
->sh_num
;
1154 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
)
1155 sym_type
= STT_FUNC
;
1157 sym_type
= STT_OBJECT
;
1158 if (sym
->type
.t
& VT_STATIC
)
1159 sym_bind
= STB_LOCAL
;
1161 sym_bind
= STB_GLOBAL
;
1163 name
= get_tok_str(sym
->v
, NULL
);
1164 #ifdef CONFIG_TCC_BCHECK
1165 if (do_bounds_check
) {
1168 /* XXX: avoid doing that for statics ? */
1169 /* if bound checking is activated, we change some function
1170 names by adding the "__bound" prefix */
1173 /* XXX: we rely only on malloc hooks */
1185 strcpy(buf
, "__bound_");
1192 info
= ELF32_ST_INFO(sym_bind
, sym_type
);
1193 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, sh_num
, name
);
1195 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
1196 esym
->st_value
= value
;
1197 esym
->st_size
= size
;
1198 esym
->st_shndx
= sh_num
;
1202 /* add a new relocation entry to symbol 'sym' in section 's' */
1203 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1206 put_extern_sym(sym
, NULL
, 0, 0);
1207 /* now we can add ELF relocation info */
1208 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1211 static inline int isid(int c
)
1213 return (c
>= 'a' && c
<= 'z') ||
1214 (c
>= 'A' && c
<= 'Z') ||
1218 static inline int isnum(int c
)
1220 return c
>= '0' && c
<= '9';
1223 static inline int isoct(int c
)
1225 return c
>= '0' && c
<= '7';
1228 static inline int toup(int c
)
1230 if (c
>= 'a' && c
<= 'z')
1231 return c
- 'a' + 'A';
1236 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1240 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1243 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1247 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1251 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1258 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1259 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1260 (*f
)->filename
, (*f
)->line_num
);
1261 if (file
->line_num
> 0) {
1262 strcat_printf(buf
, sizeof(buf
),
1263 "%s:%d: ", file
->filename
, file
->line_num
);
1265 strcat_printf(buf
, sizeof(buf
),
1266 "%s: ", file
->filename
);
1269 strcat_printf(buf
, sizeof(buf
),
1273 strcat_printf(buf
, sizeof(buf
), "warning: ");
1274 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1276 if (!s1
->error_func
) {
1277 /* default case: stderr */
1278 fprintf(stderr
, "%s\n", buf
);
1280 s1
->error_func(s1
->error_opaque
, buf
);
1282 if (!is_warning
|| s1
->warn_error
)
1287 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1288 void (*error_func
)(void *opaque
, const char *msg
))
1290 s
->error_opaque
= error_opaque
;
1291 s
->error_func
= error_func
;
1295 /* error without aborting current compilation */
1296 void error_noabort(const char *fmt
, ...)
1298 TCCState
*s1
= tcc_state
;
1302 error1(s1
, 0, fmt
, ap
);
1306 void error(const char *fmt
, ...)
1308 TCCState
*s1
= tcc_state
;
1312 error1(s1
, 0, fmt
, ap
);
1314 /* better than nothing: in some cases, we accept to handle errors */
1315 if (s1
->error_set_jmp_enabled
) {
1316 longjmp(s1
->error_jmp_buf
, 1);
1318 /* XXX: eliminate this someday */
1323 void expect(const char *msg
)
1325 error("%s expected", msg
);
1328 void warning(const char *fmt
, ...)
1330 TCCState
*s1
= tcc_state
;
1337 error1(s1
, 1, fmt
, ap
);
1344 error("'%c' expected", c
);
1348 static void test_lvalue(void)
1350 if (!(vtop
->r
& VT_LVAL
))
1354 /* allocate a new token */
1355 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1357 TokenSym
*ts
, **ptable
;
1360 if (tok_ident
>= SYM_FIRST_ANOM
)
1361 error("memory full");
1363 /* expand token table if needed */
1364 i
= tok_ident
- TOK_IDENT
;
1365 if ((i
% TOK_ALLOC_INCR
) == 0) {
1366 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1368 error("memory full");
1369 table_ident
= ptable
;
1372 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1373 table_ident
[i
] = ts
;
1374 ts
->tok
= tok_ident
++;
1375 ts
->sym_define
= NULL
;
1376 ts
->sym_label
= NULL
;
1377 ts
->sym_struct
= NULL
;
1378 ts
->sym_identifier
= NULL
;
1380 ts
->hash_next
= NULL
;
1381 memcpy(ts
->str
, str
, len
);
1382 ts
->str
[len
] = '\0';
1387 #define TOK_HASH_INIT 1
1388 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1390 /* find a token and add it if not found */
1391 static TokenSym
*tok_alloc(const char *str
, int len
)
1393 TokenSym
*ts
, **pts
;
1399 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1400 h
&= (TOK_HASH_SIZE
- 1);
1402 pts
= &hash_ident
[h
];
1407 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1409 pts
= &(ts
->hash_next
);
1411 return tok_alloc_new(pts
, str
, len
);
1414 /* CString handling */
1416 static void cstr_realloc(CString
*cstr
, int new_size
)
1421 size
= cstr
->size_allocated
;
1423 size
= 8; /* no need to allocate a too small first string */
1424 while (size
< new_size
)
1426 data
= tcc_realloc(cstr
->data_allocated
, size
);
1428 error("memory full");
1429 cstr
->data_allocated
= data
;
1430 cstr
->size_allocated
= size
;
1435 static void cstr_ccat(CString
*cstr
, int ch
)
1438 size
= cstr
->size
+ 1;
1439 if (size
> cstr
->size_allocated
)
1440 cstr_realloc(cstr
, size
);
1441 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1445 static void cstr_cat(CString
*cstr
, const char *str
)
1457 /* add a wide char */
1458 static void cstr_wccat(CString
*cstr
, int ch
)
1461 size
= cstr
->size
+ sizeof(int);
1462 if (size
> cstr
->size_allocated
)
1463 cstr_realloc(cstr
, size
);
1464 *(int *)(((unsigned char *)cstr
->data
) + size
- sizeof(int)) = ch
;
1468 static void cstr_new(CString
*cstr
)
1470 memset(cstr
, 0, sizeof(CString
));
1473 /* free string and reset it to NULL */
1474 static void cstr_free(CString
*cstr
)
1476 tcc_free(cstr
->data_allocated
);
1480 #define cstr_reset(cstr) cstr_free(cstr)
1482 static CString
*cstr_dup(CString
*cstr1
)
1487 cstr
= tcc_malloc(sizeof(CString
));
1490 cstr
->size_allocated
= size
;
1491 cstr
->data_allocated
= tcc_malloc(size
);
1492 cstr
->data
= cstr
->data_allocated
;
1493 memcpy(cstr
->data_allocated
, cstr1
->data_allocated
, size
);
1497 /* XXX: unicode ? */
1498 static void add_char(CString
*cstr
, int c
)
1500 if (c
== '\'' || c
== '\"' || c
== '\\') {
1501 /* XXX: could be more precise if char or string */
1502 cstr_ccat(cstr
, '\\');
1504 if (c
>= 32 && c
<= 126) {
1507 cstr_ccat(cstr
, '\\');
1509 cstr_ccat(cstr
, 'n');
1511 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1512 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1513 cstr_ccat(cstr
, '0' + (c
& 7));
1518 /* XXX: buffer overflow */
1519 /* XXX: float tokens */
1520 char *get_tok_str(int v
, CValue
*cv
)
1522 static char buf
[STRING_MAX_SIZE
+ 1];
1523 static CString cstr_buf
;
1529 /* NOTE: to go faster, we give a fixed buffer for small strings */
1530 cstr_reset(&cstr_buf
);
1531 cstr_buf
.data
= buf
;
1532 cstr_buf
.size_allocated
= sizeof(buf
);
1538 /* XXX: not quite exact, but only useful for testing */
1539 sprintf(p
, "%u", cv
->ui
);
1543 /* XXX: not quite exact, but only useful for testing */
1544 sprintf(p
, "%Lu", cv
->ull
);
1548 cstr_ccat(&cstr_buf
, '\'');
1549 add_char(&cstr_buf
, cv
->i
);
1550 cstr_ccat(&cstr_buf
, '\'');
1551 cstr_ccat(&cstr_buf
, '\0');
1555 len
= cstr
->size
- 1;
1557 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1558 cstr_ccat(&cstr_buf
, '\0');
1563 cstr_ccat(&cstr_buf
, '\"');
1565 len
= cstr
->size
- 1;
1567 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1569 len
= (cstr
->size
/ sizeof(int)) - 1;
1571 add_char(&cstr_buf
, ((int *)cstr
->data
)[i
]);
1573 cstr_ccat(&cstr_buf
, '\"');
1574 cstr_ccat(&cstr_buf
, '\0');
1583 return strcpy(p
, "<<=");
1585 return strcpy(p
, ">>=");
1587 if (v
< TOK_IDENT
) {
1588 /* search in two bytes table */
1602 } else if (v
< tok_ident
) {
1603 return table_ident
[v
- TOK_IDENT
]->str
;
1604 } else if (v
>= SYM_FIRST_ANOM
) {
1605 /* special name for anonymous symbol */
1606 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1608 /* should never happen */
1613 return cstr_buf
.data
;
1616 /* push, without hashing */
1617 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, int c
)
1620 s
= tcc_malloc(sizeof(Sym
));
1631 /* find a symbol and return its associated structure. 's' is the top
1632 of the symbol stack */
1633 static Sym
*sym_find2(Sym
*s
, int v
)
1643 /* structure lookup */
1644 static inline Sym
*struct_find(int v
)
1647 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1649 return table_ident
[v
]->sym_struct
;
1652 /* find an identifier */
1653 static inline Sym
*sym_find(int v
)
1656 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1658 return table_ident
[v
]->sym_identifier
;
1661 /* push a given symbol on the symbol stack */
1662 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1671 s
= sym_push2(ps
, v
, type
->t
, c
);
1672 s
->type
.ref
= type
->ref
;
1674 /* don't record fields or anonymous symbols */
1676 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1677 /* record symbol in token array */
1678 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1680 ps
= &ts
->sym_struct
;
1682 ps
= &ts
->sym_identifier
;
1689 /* push a global identifier */
1690 static Sym
*global_identifier_push(int v
, int t
, int c
)
1693 s
= sym_push2(&global_stack
, v
, t
, c
);
1694 /* don't record anonymous symbol */
1695 if (v
< SYM_FIRST_ANOM
) {
1696 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1697 /* modify the top most local identifier, so that
1698 sym_identifier will point to 's' when popped */
1700 ps
= &(*ps
)->prev_tok
;
1707 /* pop symbols until top reaches 'b' */
1708 static void sym_pop(Sym
**ptop
, Sym
*b
)
1718 /* remove symbol in token array */
1720 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1721 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1723 ps
= &ts
->sym_struct
;
1725 ps
= &ts
->sym_identifier
;
1736 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1741 fd
= open(filename
, O_RDONLY
| O_BINARY
);
1744 bf
= tcc_malloc(sizeof(BufferedFile
));
1750 bf
->buf_ptr
= bf
->buffer
;
1751 bf
->buf_end
= bf
->buffer
;
1752 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1753 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1755 bf
->ifndef_macro
= 0;
1756 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1757 // printf("opening '%s'\n", filename);
1761 void tcc_close(BufferedFile
*bf
)
1763 total_lines
+= bf
->line_num
;
1768 /* fill input buffer and peek next char */
1769 static int tcc_peekc_slow(BufferedFile
*bf
)
1772 /* only tries to read if really end of buffer */
1773 if (bf
->buf_ptr
>= bf
->buf_end
) {
1775 #if defined(PARSE_DEBUG)
1780 len
= read(bf
->fd
, bf
->buffer
, len
);
1787 bf
->buf_ptr
= bf
->buffer
;
1788 bf
->buf_end
= bf
->buffer
+ len
;
1789 *bf
->buf_end
= CH_EOB
;
1791 if (bf
->buf_ptr
< bf
->buf_end
) {
1792 return bf
->buf_ptr
[0];
1794 bf
->buf_ptr
= bf
->buf_end
;
1799 /* return the current character, handling end of block if necessary
1801 static int handle_eob(void)
1803 return tcc_peekc_slow(file
);
1806 /* read next char from current input file and handle end of input buffer */
1807 static inline void inp(void)
1809 ch
= *(++(file
->buf_ptr
));
1810 /* end of buffer/file handling */
1815 /* handle '\[\r]\n' */
1816 static void handle_stray(void)
1818 while (ch
== '\\') {
1823 } else if (ch
== '\r') {
1831 error("stray '\\' in program");
1836 /* skip the stray and handle the \\n case. Output an error if
1837 incorrect char after the stray */
1838 static int handle_stray1(uint8_t *p
)
1842 if (p
>= file
->buf_end
) {
1859 /* handle just the EOB case, but not stray */
1860 #define PEEKC_EOB(c, p)\
1871 /* handle the complicated stray case */
1872 #define PEEKC(c, p)\
1877 c = handle_stray1(p);\
1882 /* input with '\[\r]\n' handling. Note that this function cannot
1883 handle other characters after '\', so you cannot call it inside
1884 strings or comments */
1885 static void minp(void)
1893 /* single line C++ comments */
1894 static uint8_t *parse_line_comment(uint8_t *p
)
1902 if (c
== '\n' || c
== CH_EOF
) {
1904 } else if (c
== '\\') {
1913 } else if (c
== '\r') {
1931 static uint8_t *parse_comment(uint8_t *p
)
1937 /* fast skip loop */
1940 if (c
== '\n' || c
== '*' || c
== '\\')
1944 if (c
== '\n' || c
== '*' || c
== '\\')
1948 /* now we can handle all the cases */
1952 } else if (c
== '*') {
1958 } else if (c
== '/') {
1959 goto end_of_comment
;
1960 } else if (c
== '\\') {
1965 /* skip '\[\r]\n', otherwise just skip the stray */
1971 } else if (c
== '\r') {
1988 /* stray, eob or eof */
1993 error("unexpected end of file in comment");
1994 } else if (c
== '\\') {
2006 /* space exlcuding newline */
2007 static inline int is_space(int ch
)
2009 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
2012 static inline void skip_spaces(void)
2014 while (is_space(ch
))
2018 /* parse a string without interpreting escapes */
2019 static uint8_t *parse_pp_string(uint8_t *p
,
2020 int sep
, CString
*str
)
2028 } else if (c
== '\\') {
2033 unterminated_string
:
2034 /* XXX: indicate line number of start of string */
2035 error("missing terminating %c character", sep
);
2036 } else if (c
== '\\') {
2037 /* escape : just skip \[\r]\n */
2042 } else if (c
== '\r') {
2045 expect("'\n' after '\r'");
2048 } else if (c
== CH_EOF
) {
2049 goto unterminated_string
;
2052 cstr_ccat(str
, '\\');
2058 } else if (c
== '\n') {
2061 } else if (c
== '\r') {
2064 cstr_ccat(str
, '\r');
2080 /* skip block of text until #else, #elif or #endif. skip also pairs of
2082 void preprocess_skip(void)
2084 int a
, start_of_line
, c
;
2111 } else if (c
== '\\') {
2112 /* XXX: incorrect: should not give an error */
2113 ch
= file
->buf_ptr
[0];
2121 p
= parse_pp_string(p
, c
, NULL
);
2130 p
= parse_comment(p
);
2131 } else if (ch
== '/') {
2132 p
= parse_line_comment(p
);
2138 if (start_of_line
) {
2143 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2145 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2147 else if (tok
== TOK_ENDIF
)
2161 /* ParseState handling */
2163 /* XXX: currently, no include file info is stored. Thus, we cannot display
2164 accurate messages if the function or data definition spans multiple
2167 /* save current parse state in 's' */
2168 void save_parse_state(ParseState
*s
)
2170 s
->line_num
= file
->line_num
;
2171 s
->macro_ptr
= macro_ptr
;
2176 /* restore parse state from 's' */
2177 void restore_parse_state(ParseState
*s
)
2179 file
->line_num
= s
->line_num
;
2180 macro_ptr
= s
->macro_ptr
;
2185 /* return the number of additional 'ints' necessary to store the
2187 static inline int tok_ext_size(int t
)
2206 return LDOUBLE_SIZE
/ 4;
2212 /* token string handling */
2214 static inline void tok_str_new(TokenString
*s
)
2218 s
->allocated_len
= 0;
2219 s
->last_line_num
= -1;
2222 static void tok_str_free(int *str
)
2231 /* NOTE: we test zero separately so that GCC can generate a
2232 table for the following switch */
2247 /* XXX: use a macro to be portable on 64 bit ? */
2248 cstr
= (CString
*)p
[1];
2259 p
+= 1 + (LDOUBLE_SIZE
/ 4);
2269 static int *tok_str_realloc(TokenString
*s
)
2273 if (s
->allocated_len
== 0) {
2276 len
= s
->allocated_len
* 2;
2278 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2280 error("memory full");
2281 s
->allocated_len
= len
;
2286 static void tok_str_add(TokenString
*s
, int t
)
2292 if (len
>= s
->allocated_len
)
2293 str
= tok_str_realloc(s
);
2298 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2305 /* allocate space for worst case */
2306 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2307 str
= tok_str_realloc(s
);
2316 str
[len
++] = cv
->tab
[0];
2321 str
[len
++] = (int)cstr_dup(cv
->cstr
);
2326 #if LDOUBLE_SIZE == 8
2329 str
[len
++] = cv
->tab
[0];
2330 str
[len
++] = cv
->tab
[1];
2332 #if LDOUBLE_SIZE == 12
2334 str
[len
++] = cv
->tab
[0];
2335 str
[len
++] = cv
->tab
[1];
2336 str
[len
++] = cv
->tab
[2];
2337 #elif LDOUBLE_SIZE != 8
2338 #error add long double size support
2347 /* add the current parse token in token string 's' */
2348 static void tok_str_add_tok(TokenString
*s
)
2352 /* save line number info */
2353 if (file
->line_num
!= s
->last_line_num
) {
2354 s
->last_line_num
= file
->line_num
;
2355 cval
.i
= s
->last_line_num
;
2356 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2358 tok_str_add2(s
, tok
, &tokc
);
2361 #if LDOUBLE_SIZE == 12
2362 #define LDOUBLE_GET(p, cv) \
2366 #elif LDOUBLE_SIZE == 8
2367 #define LDOUBLE_GET(p, cv) \
2371 #error add long double size support
2375 /* get a token from an integer array and increment pointer
2376 accordingly. we code it as a macro to avoid pointer aliasing. */
2377 #define TOK_GET(t, p, cv) \
2399 case TOK_CLDOUBLE: \
2400 LDOUBLE_GET(p, cv); \
2401 p += LDOUBLE_SIZE / 4; \
2408 /* defines handling */
2409 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2413 s
= sym_push2(&define_stack
, v
, macro_type
, (int)str
);
2414 s
->next
= first_arg
;
2415 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2418 /* undefined a define symbol. Its name is just set to zero */
2419 static void define_undef(Sym
*s
)
2423 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2424 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2428 static inline Sym
*define_find(int v
)
2431 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2433 return table_ident
[v
]->sym_define
;
2436 /* free define stack until top reaches 'b' */
2437 static void free_defines(Sym
*b
)
2445 /* do not free args or predefined defines */
2447 tok_str_free((int *)top
->c
);
2449 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2450 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2458 static Sym
*label_find(int v
)
2461 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2463 return table_ident
[v
]->sym_label
;
2466 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2469 s
= sym_push2(ptop
, v
, 0, 0);
2471 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2472 if (ptop
== &global_label_stack
) {
2473 /* modify the top most local identifier, so that
2474 sym_identifier will point to 's' when popped */
2476 ps
= &(*ps
)->prev_tok
;
2483 /* pop labels until element last is reached. Look if any labels are
2484 undefined. Define symbols if '&&label' was used. */
2485 static void label_pop(Sym
**ptop
, Sym
*slast
)
2488 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2490 if (s
->r
== LABEL_DECLARED
) {
2491 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2492 } else if (s
->r
== LABEL_FORWARD
) {
2493 error("label '%s' used but not defined",
2494 get_tok_str(s
->v
, NULL
));
2497 /* define corresponding symbol. A size of
2499 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2503 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2509 /* eval an expression for #if/#elif */
2510 static int expr_preprocess(void)
2516 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2517 next(); /* do macro subst */
2518 if (tok
== TOK_DEFINED
) {
2523 c
= define_find(tok
) != 0;
2528 } else if (tok
>= TOK_IDENT
) {
2529 /* if undefined macro */
2533 tok_str_add_tok(&str
);
2535 tok_str_add(&str
, -1); /* simulate end of file */
2536 tok_str_add(&str
, 0);
2537 /* now evaluate C constant expression */
2538 macro_ptr
= str
.str
;
2542 tok_str_free(str
.str
);
2546 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2547 static void tok_print(int *str
)
2553 TOK_GET(t
, str
, cval
);
2556 printf(" %s", get_tok_str(t
, &cval
));
2562 /* parse after #define */
2563 static void parse_define(void)
2565 Sym
*s
, *first
, **ps
;
2566 int v
, t
, varg
, is_vaargs
, c
;
2571 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2572 /* XXX: should check if same macro (ANSI) */
2575 /* '(' must be just after macro definition for MACRO_FUNC */
2576 c
= file
->buf_ptr
[0];
2578 c
= handle_stray1(file
->buf_ptr
);
2583 while (tok
!= ')') {
2587 if (varg
== TOK_DOTS
) {
2588 varg
= TOK___VA_ARGS__
;
2590 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2594 if (varg
< TOK_IDENT
)
2595 error("badly punctuated parameter list");
2596 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2607 /* EOF testing necessary for '-D' handling */
2608 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2609 tok_str_add2(&str
, tok
, &tokc
);
2612 tok_str_add(&str
, 0);
2614 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2617 define_push(v
, t
, str
.str
, first
);
2620 /* XXX: use a token or a hash table to accelerate matching ? */
2621 static CachedInclude
*search_cached_include(TCCState
*s1
,
2622 int type
, const char *filename
)
2627 for(i
= 0;i
< s1
->nb_cached_includes
; i
++) {
2628 e
= s1
->cached_includes
[i
];
2629 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2635 static inline void add_cached_include(TCCState
*s1
, int type
,
2636 const char *filename
, int ifndef_macro
)
2640 if (search_cached_include(s1
, type
, filename
))
2643 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2645 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2649 strcpy(e
->filename
, filename
);
2650 e
->ifndef_macro
= ifndef_macro
;
2651 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2654 /* is_bof is true if first non space token at beginning of file */
2655 static void preprocess(int is_bof
)
2657 TCCState
*s1
= tcc_state
;
2658 int size
, i
, c
, n
, saved_parse_flags
;
2659 char buf
[1024], *q
, *p
;
2665 saved_parse_flags
= parse_flags
;
2666 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
2667 PARSE_FLAG_LINEFEED
;
2677 s
= define_find(tok
);
2678 /* undefine symbol by putting an invalid name */
2683 ch
= file
->buf_ptr
[0];
2684 /* XXX: incorrect if comments : use next_nomacro with a special mode */
2689 } else if (ch
== '\"') {
2692 /* XXX: better stray handling */
2695 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
2696 if ((q
- buf
) < sizeof(buf
) - 1)
2703 /* eat all spaces and comments after include */
2704 /* XXX: slightly incorrect */
2705 while (ch1
!= '\n' && ch1
!= CH_EOF
)
2709 /* computed #include : either we have only strings or
2710 we have anything enclosed in '<>' */
2713 if (tok
== TOK_STR
) {
2714 while (tok
!= TOK_LINEFEED
) {
2715 if (tok
!= TOK_STR
) {
2717 error("'#include' expects \"FILENAME\" or <FILENAME>");
2719 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
2725 while (tok
!= TOK_LINEFEED
) {
2726 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
2730 /* check syntax and remove '<>' */
2731 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
2732 goto include_syntax
;
2733 memmove(buf
, buf
+ 1, len
- 2);
2734 buf
[len
- 2] = '\0';
2739 e
= search_cached_include(s1
, c
, buf
);
2740 if (e
&& define_find(e
->ifndef_macro
)) {
2741 /* no need to parse the include because the 'ifndef macro'
2744 printf("%s: skipping %s\n", file
->filename
, buf
);
2748 /* first search in current dir if "header.h" */
2750 p
= strrchr(file
->filename
, '/');
2752 size
= p
+ 1 - file
->filename
;
2753 if (size
> sizeof(buf1
) - 1)
2754 size
= sizeof(buf1
) - 1;
2755 memcpy(buf1
, file
->filename
, size
);
2757 pstrcat(buf1
, sizeof(buf1
), buf
);
2758 f
= tcc_open(s1
, buf1
);
2762 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
2763 error("#include recursion too deep");
2764 /* now search in all the include paths */
2765 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
2766 for(i
= 0; i
< n
; i
++) {
2768 if (i
< s1
->nb_include_paths
)
2769 path
= s1
->include_paths
[i
];
2771 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
2772 pstrcpy(buf1
, sizeof(buf1
), path
);
2773 pstrcat(buf1
, sizeof(buf1
), "/");
2774 pstrcat(buf1
, sizeof(buf1
), buf
);
2775 f
= tcc_open(s1
, buf1
);
2779 error("include file '%s' not found", buf
);
2783 printf("%s: including %s\n", file
->filename
, buf1
);
2786 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
2787 /* push current file in stack */
2788 /* XXX: fix current line init */
2789 *s1
->include_stack_ptr
++ = file
;
2791 /* add include file debug info */
2793 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
2795 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
2796 ch
= file
->buf_ptr
[0];
2804 c
= expr_preprocess();
2810 if (tok
< TOK_IDENT
)
2811 error("invalid argument for '#if%sdef'", c
? "n" : "");
2815 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
2817 file
->ifndef_macro
= tok
;
2820 c
= (define_find(tok
) != 0) ^ c
;
2822 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
2823 error("memory full");
2824 *s1
->ifdef_stack_ptr
++ = c
;
2827 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2828 error("#else without matching #if");
2829 if (s1
->ifdef_stack_ptr
[-1] & 2)
2830 error("#else after #else");
2831 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
2834 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2835 error("#elif without matching #if");
2836 c
= s1
->ifdef_stack_ptr
[-1];
2838 error("#elif after #else");
2839 /* last #if/#elif expression was true: we skip */
2842 c
= expr_preprocess();
2843 s1
->ifdef_stack_ptr
[-1] = c
;
2853 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
2854 error("#endif without matching #if");
2855 s1
->ifdef_stack_ptr
--;
2856 /* '#ifndef macro' was at the start of file. Now we check if
2857 an '#endif' is exactly at the end of file */
2858 if (file
->ifndef_macro
&&
2859 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
2860 file
->ifndef_macro_saved
= file
->ifndef_macro
;
2861 /* need to set to zero to avoid false matches if another
2862 #ifndef at middle of file */
2863 file
->ifndef_macro
= 0;
2864 while (tok
!= TOK_LINEFEED
)
2866 tok_flags
|= TOK_FLAG_ENDIF
;
2872 if (tok
!= TOK_CINT
)
2874 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
2876 if (tok
!= TOK_LINEFEED
) {
2879 pstrcpy(file
->filename
, sizeof(file
->filename
),
2880 (char *)tokc
.cstr
->data
);
2886 ch
= file
->buf_ptr
[0];
2889 while (ch
!= '\n' && ch
!= CH_EOF
) {
2890 if ((q
- buf
) < sizeof(buf
) - 1)
2896 error("#error %s", buf
);
2898 warning("#warning %s", buf
);
2904 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
2905 /* '!' is ignored to allow C scripts. numbers are ignored
2906 to emulate cpp behaviour */
2908 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
2909 error("invalid preprocessing directive #%s", get_tok_str(tok
, &tokc
));
2913 /* ignore other preprocess commands or #! for C scripts */
2914 while (tok
!= TOK_LINEFEED
)
2917 parse_flags
= saved_parse_flags
;
2920 /* evaluate escape codes in a string. */
2921 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
2936 case '0': case '1': case '2': case '3':
2937 case '4': case '5': case '6': case '7':
2938 /* at most three octal digits */
2943 n
= n
* 8 + c
- '0';
2947 n
= n
* 8 + c
- '0';
2952 goto add_char_nonext
;
2958 if (c
>= 'a' && c
<= 'f')
2960 else if (c
>= 'A' && c
<= 'F')
2970 goto add_char_nonext
;
2994 goto invalid_escape
;
3004 if (c
>= '!' && c
<= '~')
3005 warning("unknown escape sequence: \'\\%c\'", c
);
3007 warning("unknown escape sequence: \'\\x%x\'", c
);
3014 cstr_ccat(outstr
, c
);
3016 cstr_wccat(outstr
, c
);
3018 /* add a trailing '\0' */
3020 cstr_ccat(outstr
, '\0');
3022 cstr_wccat(outstr
, '\0');
3025 /* we use 64 bit numbers */
3028 /* bn = (bn << shift) | or_val */
3029 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
3033 for(i
=0;i
<BN_SIZE
;i
++) {
3035 bn
[i
] = (v
<< shift
) | or_val
;
3036 or_val
= v
>> (32 - shift
);
3040 void bn_zero(unsigned int *bn
)
3043 for(i
=0;i
<BN_SIZE
;i
++) {
3048 /* parse number in null terminated string 'p' and return it in the
3050 void parse_number(const char *p
)
3052 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
3054 unsigned int bn
[BN_SIZE
];
3065 goto float_frac_parse
;
3066 } else if (t
== '0') {
3067 if (ch
== 'x' || ch
== 'X') {
3071 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
3077 /* parse all digits. cannot check octal numbers at this stage
3078 because of floating point constants */
3080 if (ch
>= 'a' && ch
<= 'f')
3082 else if (ch
>= 'A' && ch
<= 'F')
3090 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
3092 error("number too long");
3098 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
3099 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
3101 /* NOTE: strtox should support that for hexa numbers, but
3102 non ISOC99 libcs do not support it, so we prefer to do
3104 /* hexadecimal or binary floats */
3105 /* XXX: handle overflows */
3117 } else if (t
>= 'a') {
3119 } else if (t
>= 'A') {
3124 bn_lshift(bn
, shift
, t
);
3131 if (t
>= 'a' && t
<= 'f') {
3133 } else if (t
>= 'A' && t
<= 'F') {
3135 } else if (t
>= '0' && t
<= '9') {
3141 error("invalid digit");
3142 bn_lshift(bn
, shift
, t
);
3147 if (ch
!= 'p' && ch
!= 'P')
3154 } else if (ch
== '-') {
3158 if (ch
< '0' || ch
> '9')
3159 expect("exponent digits");
3160 while (ch
>= '0' && ch
<= '9') {
3161 exp_val
= exp_val
* 10 + ch
- '0';
3164 exp_val
= exp_val
* s
;
3166 /* now we can generate the number */
3167 /* XXX: should patch directly float number */
3168 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3169 d
= ldexp(d
, exp_val
- frac_bits
);
3174 /* float : should handle overflow */
3176 } else if (t
== 'L') {
3179 /* XXX: not large enough */
3180 tokc
.ld
= (long double)d
;
3186 /* decimal floats */
3188 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3193 while (ch
>= '0' && ch
<= '9') {
3194 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3200 if (ch
== 'e' || ch
== 'E') {
3201 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3205 if (ch
== '-' || ch
== '+') {
3206 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3211 if (ch
< '0' || ch
> '9')
3212 expect("exponent digits");
3213 while (ch
>= '0' && ch
<= '9') {
3214 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3226 tokc
.f
= strtof(token_buf
, NULL
);
3227 } else if (t
== 'L') {
3230 tokc
.ld
= strtold(token_buf
, NULL
);
3233 tokc
.d
= strtod(token_buf
, NULL
);
3237 unsigned long long n
, n1
;
3240 /* integer number */
3243 if (b
== 10 && *q
== '0') {
3250 /* no need for checks except for base 10 / 8 errors */
3253 } else if (t
>= 'a') {
3255 } else if (t
>= 'A') {
3260 error("invalid digit");
3264 /* detect overflow */
3265 /* XXX: this test is not reliable */
3267 error("integer constant overflow");
3270 /* XXX: not exactly ANSI compliant */
3271 if ((n
& 0xffffffff00000000LL
) != 0) {
3276 } else if (n
> 0x7fffffff) {
3287 error("three 'l's in integer constant");
3290 if (tok
== TOK_CINT
)
3292 else if (tok
== TOK_CUINT
)
3296 } else if (t
== 'U') {
3298 error("two 'u's in integer constant");
3300 if (tok
== TOK_CINT
)
3302 else if (tok
== TOK_CLLONG
)
3309 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3317 #define PARSE2(c1, tok1, c2, tok2) \
3328 /* return next token without macro substitution */
3329 static inline void next_nomacro1(void)
3349 /* first look if it is in fact an end of buffer */
3350 if (p
>= file
->buf_end
) {
3354 if (p
>= file
->buf_end
)
3367 TCCState
*s1
= tcc_state
;
3368 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3370 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3371 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3372 /* no include left : end of file. */
3375 /* pop include file */
3377 /* test if previous '#endif' was after a #ifdef at
3379 if (tok_flags
& TOK_FLAG_ENDIF
) {
3381 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3383 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3384 file
->ifndef_macro_saved
);
3387 /* add end of include file debug info */
3389 put_stabd(N_EINCL
, 0, 0);
3391 /* pop include stack */
3393 s1
->include_stack_ptr
--;
3394 file
= *s1
->include_stack_ptr
;
3402 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3406 tok_flags
|= TOK_FLAG_BOL
;
3415 if ((tok_flags
& TOK_FLAG_BOL
) &&
3416 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3418 preprocess(tok_flags
& TOK_FLAG_BOF
);
3424 tok
= TOK_TWOSHARPS
;
3426 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
3427 p
= parse_line_comment(p
- 1);
3436 case 'a': case 'b': case 'c': case 'd':
3437 case 'e': case 'f': case 'g': case 'h':
3438 case 'i': case 'j': case 'k': case 'l':
3439 case 'm': case 'n': case 'o': case 'p':
3440 case 'q': case 'r': case 's': case 't':
3441 case 'u': case 'v': case 'w': case 'x':
3443 case 'A': case 'B': case 'C': case 'D':
3444 case 'E': case 'F': case 'G': case 'H':
3445 case 'I': case 'J': case 'K':
3446 case 'M': case 'N': case 'O': case 'P':
3447 case 'Q': case 'R': case 'S': case 'T':
3448 case 'U': case 'V': case 'W': case 'X':
3454 h
= TOK_HASH_FUNC(h
, c
);
3458 if (!isidnum_table
[c
])
3460 h
= TOK_HASH_FUNC(h
, c
);
3467 /* fast case : no stray found, so we have the full token
3468 and we have already hashed it */
3470 h
&= (TOK_HASH_SIZE
- 1);
3471 pts
= &hash_ident
[h
];
3476 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3478 pts
= &(ts
->hash_next
);
3480 ts
= tok_alloc_new(pts
, p1
, len
);
3484 cstr_reset(&tokcstr
);
3487 cstr_ccat(&tokcstr
, *p1
);
3493 while (isidnum_table
[c
]) {
3494 cstr_ccat(&tokcstr
, c
);
3497 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3503 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3505 goto parse_ident_fast
;
3508 if (c
== '\'' || c
== '\"') {
3512 cstr_reset(&tokcstr
);
3513 cstr_ccat(&tokcstr
, 'L');
3514 goto parse_ident_slow
;
3518 case '0': case '1': case '2': case '3':
3519 case '4': case '5': case '6': case '7':
3522 cstr_reset(&tokcstr
);
3523 /* after the first digit, accept digits, alpha, '.' or sign if
3524 prefixed by 'eEpP' */
3528 cstr_ccat(&tokcstr
, c
);
3530 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3531 ((c
== '+' || c
== '-') &&
3532 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3535 /* We add a trailing '\0' to ease parsing */
3536 cstr_ccat(&tokcstr
, '\0');
3537 tokc
.cstr
= &tokcstr
;
3541 /* special dot handling because it can also start a number */
3544 cstr_reset(&tokcstr
);
3545 cstr_ccat(&tokcstr
, '.');
3547 } else if (c
== '.') {
3567 /* parse the string */
3569 p
= parse_pp_string(p
, sep
, &str
);
3570 cstr_ccat(&str
, '\0');
3572 /* eval the escape (should be done as TOK_PPNUM) */
3573 cstr_reset(&tokcstr
);
3574 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3579 /* XXX: make it portable */
3583 char_size
= sizeof(int);
3584 if (tokcstr
.size
<= char_size
)
3585 error("empty character constant");
3586 if (tokcstr
.size
> 2 * char_size
)
3587 warning("multi-character character constant");
3589 tokc
.i
= *(int8_t *)tokcstr
.data
;
3592 tokc
.i
= *(int *)tokcstr
.data
;
3596 tokc
.cstr
= &tokcstr
;
3610 } else if (c
== '<') {
3628 } else if (c
== '>') {
3646 } else if (c
== '=') {
3659 } else if (c
== '=') {
3672 } else if (c
== '=') {
3685 } else if (c
== '=') {
3688 } else if (c
== '>') {
3696 PARSE2('!', '!', '=', TOK_NE
)
3697 PARSE2('=', '=', '=', TOK_EQ
)
3698 PARSE2('*', '*', '=', TOK_A_MUL
)
3699 PARSE2('%', '%', '=', TOK_A_MOD
)
3700 PARSE2('^', '^', '=', TOK_A_XOR
)
3702 /* comments or operator */
3706 p
= parse_comment(p
);
3708 } else if (c
== '/') {
3709 p
= parse_line_comment(p
);
3711 } else if (c
== '=') {
3731 case '$': /* only used in assembler */
3736 error("unrecognized character \\x%02x", c
);
3741 #if defined(PARSE_DEBUG)
3742 printf("token = %s\n", get_tok_str(tok
, &tokc
));
3746 /* return next token without macro substitution. Can read input from
3748 static void next_nomacro(void)
3754 TOK_GET(tok
, macro_ptr
, tokc
);
3755 if (tok
== TOK_LINENUM
) {
3756 file
->line_num
= tokc
.i
;
3765 /* substitute args in macro_str and return allocated string */
3766 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
3768 int *st
, last_tok
, t
, notfirst
;
3777 TOK_GET(t
, macro_str
, cval
);
3782 TOK_GET(t
, macro_str
, cval
);
3785 s
= sym_find2(args
, t
);
3792 cstr_ccat(&cstr
, ' ');
3793 TOK_GET(t
, st
, cval
);
3794 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
3797 cstr_ccat(&cstr
, '\0');
3799 printf("stringize: %s\n", (char *)cstr
.data
);
3803 tok_str_add2(&str
, TOK_STR
, &cval
);
3806 tok_str_add2(&str
, t
, &cval
);
3808 } else if (t
>= TOK_IDENT
) {
3809 s
= sym_find2(args
, t
);
3812 /* if '##' is present before or after, no arg substitution */
3813 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
3814 /* special case for var arg macros : ## eats the
3815 ',' if empty VA_ARGS variable. */
3816 /* XXX: test of the ',' is not 100%
3817 reliable. should fix it to avoid security
3819 if (gnu_ext
&& s
->type
.t
&&
3820 last_tok
== TOK_TWOSHARPS
&&
3821 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
3823 /* suppress ',' '##' */
3826 /* suppress '##' and add variable */
3834 TOK_GET(t1
, st
, cval
);
3837 tok_str_add2(&str
, t1
, &cval
);
3841 /* NOTE: the stream cannot be read when macro
3842 substituing an argument */
3843 macro_subst(&str
, nested_list
, st
, 0);
3846 tok_str_add(&str
, t
);
3849 tok_str_add2(&str
, t
, &cval
);
3853 tok_str_add(&str
, 0);
3857 static char const ab_month_name
[12][4] =
3859 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3860 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3863 /* do macro substitution of current token with macro 's' and add
3864 result to (tok_str,tok_len). 'nested_list' is the list of all
3865 macros we got inside to avoid recursing. Return non zero if no
3866 substitution needs to be done */
3867 static int macro_subst_tok(TokenString
*tok_str
,
3868 Sym
**nested_list
, Sym
*s
, int can_read_stream
)
3870 Sym
*args
, *sa
, *sa1
;
3871 int mstr_allocated
, parlevel
, *mstr
, t
, t1
;
3878 /* if symbol is a macro, prepare substitution */
3879 /* special macros */
3880 if (tok
== TOK___LINE__
) {
3881 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
3885 } else if (tok
== TOK___FILE__
) {
3886 cstrval
= file
->filename
;
3888 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
3893 tm
= localtime(&ti
);
3894 if (tok
== TOK___DATE__
) {
3895 snprintf(buf
, sizeof(buf
), "%s %2d %d",
3896 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
3898 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
3899 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
3906 cstr_cat(&cstr
, cstrval
);
3907 cstr_ccat(&cstr
, '\0');
3909 tok_str_add2(tok_str
, t1
, &cval
);
3914 if (s
->type
.t
== MACRO_FUNC
) {
3915 /* NOTE: we do not use next_nomacro to avoid eating the
3916 next token. XXX: find better solution */
3919 if (t
== 0 && can_read_stream
) {
3920 /* end of macro stream: we must look at the token
3921 after in the file */
3927 /* XXX: incorrect with comments */
3928 ch
= file
->buf_ptr
[0];
3929 while (is_space(ch
) || ch
== '\n')
3933 if (t
!= '(') /* no macro subst */
3936 /* argument macro */
3941 /* NOTE: empty args are allowed, except if no args */
3943 /* handle '()' case */
3944 if (!args
&& !sa
&& tok
== ')')
3947 error("macro '%s' used with too many args",
3948 get_tok_str(s
->v
, 0));
3951 /* NOTE: non zero sa->t indicates VA_ARGS */
3952 while ((parlevel
> 0 ||
3954 (tok
!= ',' || sa
->type
.t
))) &&
3958 else if (tok
== ')')
3960 tok_str_add2(&str
, tok
, &tokc
);
3963 tok_str_add(&str
, 0);
3964 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (int)str
.str
);
3967 /* special case for gcc var args: add an empty
3968 var arg argument if it is omitted */
3969 if (sa
&& sa
->type
.t
&& gnu_ext
)
3979 error("macro '%s' used with too few args",
3980 get_tok_str(s
->v
, 0));
3983 /* now subst each arg */
3984 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
3989 tok_str_free((int *)sa
->c
);
3995 sym_push2(nested_list
, s
->v
, 0, 0);
3996 macro_subst(tok_str
, nested_list
, mstr
, 1);
3997 /* pop nested defined symbol */
3999 *nested_list
= sa1
->prev
;
4007 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4008 return the resulting string (which must be freed). */
4009 static inline int *macro_twosharps(const int *macro_str
)
4012 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
4014 const char *p1
, *p2
;
4016 TokenString macro_str1
;
4019 start_macro_ptr
= macro_str
;
4020 /* we search the first '##' */
4022 macro_ptr1
= macro_str
;
4023 TOK_GET(t
, macro_str
, cval
);
4024 /* nothing more to do if end of string */
4027 if (*macro_str
== TOK_TWOSHARPS
)
4031 /* we saw '##', so we need more processing to handle it */
4033 tok_str_new(¯o_str1
);
4037 /* add all tokens seen so far */
4038 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
4039 TOK_GET(t
, ptr
, cval
);
4040 tok_str_add2(¯o_str1
, t
, &cval
);
4042 saved_macro_ptr
= macro_ptr
;
4043 /* XXX: get rid of the use of macro_ptr here */
4044 macro_ptr
= (int *)macro_str
;
4046 while (*macro_ptr
== TOK_TWOSHARPS
) {
4048 macro_ptr1
= macro_ptr
;
4051 TOK_GET(t
, macro_ptr
, cval
);
4052 /* We concatenate the two tokens if we have an
4053 identifier or a preprocessing number */
4055 p1
= get_tok_str(tok
, &tokc
);
4056 cstr_cat(&cstr
, p1
);
4057 p2
= get_tok_str(t
, &cval
);
4058 cstr_cat(&cstr
, p2
);
4059 cstr_ccat(&cstr
, '\0');
4061 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
4062 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
4063 if (tok
== TOK_PPNUM
) {
4064 /* if number, then create a number token */
4065 /* NOTE: no need to allocate because
4066 tok_str_add2() does it */
4069 /* if identifier, we must do a test to
4070 validate we have a correct identifier */
4071 if (t
== TOK_PPNUM
) {
4081 if (!isnum(c
) && !isid(c
))
4085 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
4086 tok
= ts
->tok
; /* modify current token */
4089 const char *str
= cstr
.data
;
4090 const unsigned char *q
;
4092 /* we look for a valid token */
4093 /* XXX: do more extensive checks */
4094 if (!strcmp(str
, ">>=")) {
4096 } else if (!strcmp(str
, "<<=")) {
4098 } else if (strlen(str
) == 2) {
4099 /* search in two bytes table */
4104 if (q
[0] == str
[0] && q
[1] == str
[1])
4111 /* NOTE: because get_tok_str use a static buffer,
4114 p1
= get_tok_str(tok
, &tokc
);
4115 cstr_cat(&cstr
, p1
);
4116 cstr_ccat(&cstr
, '\0');
4117 p2
= get_tok_str(t
, &cval
);
4118 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
4119 /* cannot merge tokens: just add them separately */
4120 tok_str_add2(¯o_str1
, tok
, &tokc
);
4121 /* XXX: free associated memory ? */
4128 tok_str_add2(¯o_str1
, tok
, &tokc
);
4133 macro_ptr
= (int *)saved_macro_ptr
;
4135 tok_str_add(¯o_str1
, 0);
4136 return macro_str1
.str
;
4140 /* do macro substitution of macro_str and add result to
4141 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4142 inside to avoid recursing. */
4143 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
4144 const int *macro_str
, int can_read_stream
)
4147 int *saved_macro_ptr
, *macro_str1
;
4152 /* first scan for '##' operator handling */
4154 macro_str1
= macro_twosharps(ptr
);
4158 /* NOTE: ptr == NULL can only happen if tokens are read from
4159 file stream due to a macro function call */
4162 TOK_GET(t
, ptr
, cval
);
4167 /* if nested substitution, do nothing */
4168 if (sym_find2(*nested_list
, t
))
4170 saved_macro_ptr
= macro_ptr
;
4171 macro_ptr
= (int *)ptr
;
4173 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
4174 ptr
= (int *)macro_ptr
;
4175 macro_ptr
= saved_macro_ptr
;
4180 tok_str_add2(tok_str
, t
, &cval
);
4184 tok_str_free(macro_str1
);
4187 /* return next token with macro substitution */
4188 static void next(void)
4190 Sym
*nested_list
, *s
;
4196 /* if not reading from macro substituted string, then try
4197 to substitute macros */
4198 if (tok
>= TOK_IDENT
&&
4199 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4200 s
= define_find(tok
);
4202 /* we have a macro: we try to substitute */
4205 if (macro_subst_tok(&str
, &nested_list
, s
, 1) == 0) {
4206 /* substitution done, NOTE: maybe empty */
4207 tok_str_add(&str
, 0);
4208 macro_ptr
= str
.str
;
4209 macro_ptr_allocated
= str
.str
;
4216 /* end of macro or end of unget buffer */
4217 if (unget_buffer_enabled
) {
4218 macro_ptr
= unget_saved_macro_ptr
;
4219 unget_buffer_enabled
= 0;
4221 /* end of macro string: free it */
4222 tok_str_free(macro_ptr_allocated
);
4229 /* convert preprocessor tokens into C tokens */
4230 if (tok
== TOK_PPNUM
&&
4231 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4232 parse_number((char *)tokc
.cstr
->data
);
4236 /* push back current token and set current token to 'last_tok'. Only
4237 identifier case handled for labels. */
4238 static inline void unget_tok(int last_tok
)
4242 unget_saved_macro_ptr
= macro_ptr
;
4243 unget_buffer_enabled
= 1;
4244 q
= unget_saved_buffer
;
4247 n
= tok_ext_size(tok
) - 1;
4250 *q
= 0; /* end of token string */
4255 void swap(int *p
, int *q
)
4263 void vsetc(CType
*type
, int r
, CValue
*vc
)
4267 if (vtop
>= vstack
+ VSTACK_SIZE
)
4268 error("memory full");
4269 /* cannot let cpu flags if other instruction are generated. Also
4270 avoid leaving VT_JMP anywhere except on the top of the stack
4271 because it would complicate the code generator. */
4272 if (vtop
>= vstack
) {
4273 v
= vtop
->r
& VT_VALMASK
;
4274 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4280 vtop
->r2
= VT_CONST
;
4284 /* push integer constant */
4289 vsetc(&int_type
, VT_CONST
, &cval
);
4292 /* Return a static symbol pointing to a section */
4293 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4294 unsigned long offset
, unsigned long size
)
4300 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4301 sym
->type
.ref
= type
->ref
;
4302 sym
->r
= VT_CONST
| VT_SYM
;
4303 put_extern_sym(sym
, sec
, offset
, size
);
4307 /* push a reference to a section offset by adding a dummy symbol */
4308 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4313 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4314 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4317 /* define a new external reference to a symbol 'v' of type 'u' */
4318 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4324 /* push forward reference */
4325 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4326 s
->type
.ref
= type
->ref
;
4327 s
->r
= r
| VT_CONST
| VT_SYM
;
4332 /* define a new external reference to a symbol 'v' of type 'u' */
4333 static Sym
*external_sym(int v
, CType
*type
, int r
)
4339 /* push forward reference */
4340 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4341 s
->type
.t
|= VT_EXTERN
;
4343 if (!is_compatible_types(&s
->type
, type
))
4344 error("incompatible types for redefinition of '%s'",
4345 get_tok_str(v
, NULL
));
4350 /* push a reference to global symbol v */
4351 static void vpush_global_sym(CType
*type
, int v
)
4356 sym
= external_global_sym(v
, type
, 0);
4358 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4362 void vset(CType
*type
, int r
, int v
)
4367 vsetc(type
, r
, &cval
);
4370 void vseti(int r
, int v
)
4386 void vpushv(SValue
*v
)
4388 if (vtop
>= vstack
+ VSTACK_SIZE
)
4389 error("memory full");
4399 /* save r to the memory stack, and mark it as being free */
4400 void save_reg(int r
)
4402 int l
, saved
, size
, align
;
4406 /* modify all stack values */
4409 for(p
=vstack
;p
<=vtop
;p
++) {
4410 if ((p
->r
& VT_VALMASK
) == r
||
4411 (p
->r2
& VT_VALMASK
) == r
) {
4412 /* must save value on stack if not already done */
4414 /* NOTE: must reload 'r' because r might be equal to r2 */
4415 r
= p
->r
& VT_VALMASK
;
4416 /* store register in the stack */
4418 if ((p
->r
& VT_LVAL
) ||
4419 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4421 size
= type_size(type
, &align
);
4422 loc
= (loc
- size
) & -align
;
4423 sv
.type
.t
= type
->t
;
4424 sv
.r
= VT_LOCAL
| VT_LVAL
;
4427 #ifdef TCC_TARGET_I386
4428 /* x86 specific: need to pop fp register ST0 if saved */
4429 if (r
== TREG_ST0
) {
4430 o(0xd9dd); /* fstp %st(1) */
4433 /* special long long case */
4434 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4441 /* mark that stack entry as being saved on the stack */
4442 if (p
->r
& VT_LVAL
) {
4443 /* also clear the bounded flag because the
4444 relocation address of the function was stored in
4446 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4448 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4456 /* find a register of class 'rc2' with at most one reference on stack.
4457 * If none, call get_reg(rc) */
4458 int get_reg_ex(int rc
, int rc2
)
4463 for(r
=0;r
<NB_REGS
;r
++) {
4464 if (reg_classes
[r
] & rc2
) {
4467 for(p
= vstack
; p
<= vtop
; p
++) {
4468 if ((p
->r
& VT_VALMASK
) == r
||
4469 (p
->r2
& VT_VALMASK
) == r
)
4479 /* find a free register of class 'rc'. If none, save one register */
4485 /* find a free register */
4486 for(r
=0;r
<NB_REGS
;r
++) {
4487 if (reg_classes
[r
] & rc
) {
4488 for(p
=vstack
;p
<=vtop
;p
++) {
4489 if ((p
->r
& VT_VALMASK
) == r
||
4490 (p
->r2
& VT_VALMASK
) == r
)
4498 /* no register left : free the first one on the stack (VERY
4499 IMPORTANT to start from the bottom to ensure that we don't
4500 spill registers used in gen_opi()) */
4501 for(p
=vstack
;p
<=vtop
;p
++) {
4502 r
= p
->r
& VT_VALMASK
;
4503 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4505 /* also look at second register (if long long) */
4506 r
= p
->r2
& VT_VALMASK
;
4507 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4513 /* Should never comes here */
4517 /* save registers up to (vtop - n) stack entry */
4518 void save_regs(int n
)
4523 for(p
= vstack
;p
<= p1
; p
++) {
4524 r
= p
->r
& VT_VALMASK
;
4531 /* move register 's' to 'r', and flush previous value of r to memory
4533 void move_reg(int r
, int s
)
4546 /* get address of vtop (vtop MUST BE an lvalue) */
4549 vtop
->r
&= ~VT_LVAL
;
4550 /* tricky: if saved lvalue, then we can go back to lvalue */
4551 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4552 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4555 #ifdef CONFIG_TCC_BCHECK
4556 /* generate lvalue bound code */
4562 vtop
->r
&= ~VT_MUSTBOUND
;
4563 /* if lvalue, then use checking code before dereferencing */
4564 if (vtop
->r
& VT_LVAL
) {
4565 /* if not VT_BOUNDED value, then make one */
4566 if (!(vtop
->r
& VT_BOUNDED
)) {
4567 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4568 /* must save type because we must set it to int to get pointer */
4570 vtop
->type
.t
= VT_INT
;
4573 gen_bounded_ptr_add();
4574 vtop
->r
|= lval_type
;
4577 /* then check for dereferencing */
4578 gen_bounded_ptr_deref();
4583 /* store vtop a register belonging to class 'rc'. lvalues are
4584 converted to values. Cannot be used if cannot be converted to
4585 register value (such as structures). */
4588 int r
, r2
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4589 unsigned long long ll
;
4591 /* NOTE: get_reg can modify vstack[] */
4592 if (vtop
->type
.t
& VT_BITFIELD
) {
4593 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4594 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4595 /* remove bit field info to avoid loops */
4596 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4597 /* generate shifts */
4598 vpushi(32 - (bit_pos
+ bit_size
));
4600 vpushi(32 - bit_size
);
4601 /* NOTE: transformed to SHR if unsigned */
4605 if (is_float(vtop
->type
.t
) &&
4606 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4609 unsigned long offset
;
4611 /* XXX: unify with initializers handling ? */
4612 /* CPUs usually cannot use float constants, so we store them
4613 generically in data segment */
4614 size
= type_size(&vtop
->type
, &align
);
4615 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
4616 data_section
->data_offset
= offset
;
4617 /* XXX: not portable yet */
4618 ptr
= section_ptr_add(data_section
, size
);
4621 ptr
[i
] = vtop
->c
.tab
[i
];
4622 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
4623 vtop
->r
|= VT_LVAL
| VT_SYM
;
4627 #ifdef CONFIG_TCC_BCHECK
4628 if (vtop
->r
& VT_MUSTBOUND
)
4632 r
= vtop
->r
& VT_VALMASK
;
4633 /* need to reload if:
4635 - lvalue (need to dereference pointer)
4636 - already a register, but not in the right class */
4637 if (r
>= VT_CONST
||
4638 (vtop
->r
& VT_LVAL
) ||
4639 !(reg_classes
[r
] & rc
) ||
4640 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
4641 !(reg_classes
[vtop
->r2
] & rc
))) {
4643 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
4644 /* two register type load : expand to two words
4646 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4649 vtop
->c
.ui
= ll
; /* first word */
4651 vtop
->r
= r
; /* save register value */
4652 vpushi(ll
>> 32); /* second word */
4653 } else if (r
>= VT_CONST
|| /* XXX: test to VT_CONST incorrect ? */
4654 (vtop
->r
& VT_LVAL
)) {
4655 /* We do not want to modifier the long long
4656 pointer here, so the safest (and less
4657 efficient) is to save all the other registers
4658 in the stack. XXX: totally inefficient. */
4660 /* load from memory */
4663 vtop
[-1].r
= r
; /* save register value */
4664 /* increment pointer to get second word */
4665 vtop
->type
.t
= VT_INT
;
4671 /* move registers */
4674 vtop
[-1].r
= r
; /* save register value */
4675 vtop
->r
= vtop
[-1].r2
;
4677 /* allocate second register */
4684 /* write second register */
4686 } else if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
4688 /* lvalue of scalar type : need to use lvalue type
4689 because of possible cast */
4692 /* compute memory access type */
4693 if (vtop
->r
& VT_LVAL_BYTE
)
4695 else if (vtop
->r
& VT_LVAL_SHORT
)
4697 if (vtop
->r
& VT_LVAL_UNSIGNED
)
4701 /* restore wanted type */
4704 /* one register type load */
4709 #ifdef TCC_TARGET_C67
4710 /* uses register pairs for doubles */
4711 if ((vtop
->type
.t
& VT_BTYPE
) == VT_DOUBLE
)
4718 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
4719 void gv2(int rc1
, int rc2
)
4723 /* generate more generic register first. But VT_JMP or VT_CMP
4724 values must be generated first in all cases to avoid possible
4726 v
= vtop
[0].r
& VT_VALMASK
;
4727 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
4732 /* test if reload is needed for first register */
4733 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
4743 /* test if reload is needed for first register */
4744 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
4750 /* expand long long on stack in two int registers */
4755 u
= vtop
->type
.t
& VT_UNSIGNED
;
4758 vtop
[0].r
= vtop
[-1].r2
;
4759 vtop
[0].r2
= VT_CONST
;
4760 vtop
[-1].r2
= VT_CONST
;
4761 vtop
[0].type
.t
= VT_INT
| u
;
4762 vtop
[-1].type
.t
= VT_INT
| u
;
4765 #ifdef TCC_TARGET_ARM
4766 /* expand long long on stack */
4767 void lexpand_nr(void)
4771 u
= vtop
->type
.t
& VT_UNSIGNED
;
4773 vtop
->r2
= VT_CONST
;
4774 vtop
->type
.t
= VT_INT
| u
;
4775 v
=vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
);
4776 if (v
== VT_CONST
) {
4777 vtop
[-1].c
.ui
= vtop
->c
.ull
;
4778 vtop
->c
.ui
= vtop
->c
.ull
>> 32;
4780 } else if (v
== (VT_LVAL
|VT_CONST
) || v
== (VT_LVAL
|VT_LOCAL
)) {
4782 vtop
->r
= vtop
[-1].r
;
4783 } else if (v
> VT_CONST
) {
4787 vtop
->r
= vtop
[-1].r2
;
4788 vtop
[-1].r2
= VT_CONST
;
4789 vtop
[-1].type
.t
= VT_INT
| u
;
4793 /* build a long long from two ints */
4796 gv2(RC_INT
, RC_INT
);
4797 vtop
[-1].r2
= vtop
[0].r
;
4798 vtop
[-1].type
.t
= t
;
4802 /* rotate n first stack elements to the bottom
4803 I1 ... In -> I2 ... In I1 [top is right]
4811 for(i
=-n
+1;i
!=0;i
++)
4812 vtop
[i
] = vtop
[i
+1];
4816 /* rotate n first stack elements to the top
4817 I1 ... In -> In I1 ... I(n-1) [top is right]
4825 for(i
= 0;i
< n
- 1; i
++)
4826 vtop
[-i
] = vtop
[-i
- 1];
4830 #ifdef TCC_TARGET_ARM
4831 /* like vrott but in other direction
4832 In ... I1 -> I(n-1) ... I1 In [top is right]
4840 for(i
= n
- 1; i
> 0; i
--)
4841 vtop
[-i
] = vtop
[-i
+ 1];
4846 /* pop stack value */
4850 v
= vtop
->r
& VT_VALMASK
;
4851 #ifdef TCC_TARGET_I386
4852 /* for x86, we need to pop the FP stack */
4853 if (v
== TREG_ST0
&& !nocode_wanted
) {
4854 o(0xd9dd); /* fstp %st(1) */
4857 if (v
== VT_JMP
|| v
== VT_JMPI
) {
4858 /* need to put correct jump if && or || without test */
4864 /* convert stack entry to register and duplicate its value in another
4872 if ((t
& VT_BTYPE
) == VT_LLONG
) {
4879 /* stack: H L L1 H1 */
4887 /* duplicate value */
4898 load(r1
, &sv
); /* move r to r1 */
4900 /* duplicates value */
4905 /* generate CPU independent (unsigned) long long operations */
4906 void gen_opl(int op
)
4908 int t
, a
, b
, op1
, c
, i
;
4915 func
= TOK___divdi3
;
4918 func
= TOK___udivdi3
;
4921 func
= TOK___moddi3
;
4924 func
= TOK___umoddi3
;
4926 /* call generic long long function */
4927 vpush_global_sym(&func_old_type
, func
);
4932 vtop
->r2
= REG_LRET
;
4945 /* stack: L1 H1 L2 H2 */
4950 vtop
[-2] = vtop
[-3];
4953 /* stack: H1 H2 L1 L2 */
4959 /* stack: H1 H2 L1 L2 ML MH */
4962 /* stack: ML MH H1 H2 L1 L2 */
4966 /* stack: ML MH H1 L2 H2 L1 */
4971 /* stack: ML MH M1 M2 */
4974 } else if (op
== '+' || op
== '-') {
4975 /* XXX: add non carry method too (for MIPS or alpha) */
4981 /* stack: H1 H2 (L1 op L2) */
4984 gen_op(op1
+ 1); /* TOK_xxxC2 */
4987 /* stack: H1 H2 (L1 op L2) */
4990 /* stack: (L1 op L2) H1 H2 */
4992 /* stack: (L1 op L2) (H1 op H2) */
5000 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
5001 t
= vtop
[-1].type
.t
;
5005 /* stack: L H shift */
5007 /* constant: simpler */
5008 /* NOTE: all comments are for SHL. the other cases are
5009 done by swaping words */
5020 if (op
!= TOK_SAR
) {
5053 /* XXX: should provide a faster fallback on x86 ? */
5056 func
= TOK___sardi3
;
5059 func
= TOK___shrdi3
;
5062 func
= TOK___shldi3
;
5068 /* compare operations */
5074 /* stack: L1 H1 L2 H2 */
5076 vtop
[-1] = vtop
[-2];
5078 /* stack: L1 L2 H1 H2 */
5081 /* when values are equal, we need to compare low words. since
5082 the jump is inverted, we invert the test too. */
5085 else if (op1
== TOK_GT
)
5087 else if (op1
== TOK_ULT
)
5089 else if (op1
== TOK_UGT
)
5094 if (op1
!= TOK_NE
) {
5098 /* generate non equal test */
5099 /* XXX: NOT PORTABLE yet */
5103 #if defined(TCC_TARGET_I386)
5104 b
= psym(0x850f, 0);
5105 #elif defined(TCC_TARGET_ARM)
5107 o(0x1A000000 | encbranch(ind
, 0, 1));
5108 #elif defined(TCC_TARGET_C67)
5109 error("not implemented");
5111 #error not supported
5115 /* compare low. Always unsigned */
5119 else if (op1
== TOK_LE
)
5121 else if (op1
== TOK_GT
)
5123 else if (op1
== TOK_GE
)
5133 /* handle integer constant optimizations and various machine
5135 void gen_opic(int op
)
5142 /* currently, we cannot do computations with forward symbols */
5143 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5144 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5148 case '+': v1
->c
.i
+= fc
; break;
5149 case '-': v1
->c
.i
-= fc
; break;
5150 case '&': v1
->c
.i
&= fc
; break;
5151 case '^': v1
->c
.i
^= fc
; break;
5152 case '|': v1
->c
.i
|= fc
; break;
5153 case '*': v1
->c
.i
*= fc
; break;
5160 /* if division by zero, generate explicit division */
5163 error("division by zero in constant");
5167 default: v1
->c
.i
/= fc
; break;
5168 case '%': v1
->c
.i
%= fc
; break;
5169 case TOK_UDIV
: v1
->c
.i
= (unsigned)v1
->c
.i
/ fc
; break;
5170 case TOK_UMOD
: v1
->c
.i
= (unsigned)v1
->c
.i
% fc
; break;
5173 case TOK_SHL
: v1
->c
.i
<<= fc
; break;
5174 case TOK_SHR
: v1
->c
.i
= (unsigned)v1
->c
.i
>> fc
; break;
5175 case TOK_SAR
: v1
->c
.i
>>= fc
; break;
5177 case TOK_ULT
: v1
->c
.i
= (unsigned)v1
->c
.i
< (unsigned)fc
; break;
5178 case TOK_UGE
: v1
->c
.i
= (unsigned)v1
->c
.i
>= (unsigned)fc
; break;
5179 case TOK_EQ
: v1
->c
.i
= v1
->c
.i
== fc
; break;
5180 case TOK_NE
: v1
->c
.i
= v1
->c
.i
!= fc
; break;
5181 case TOK_ULE
: v1
->c
.i
= (unsigned)v1
->c
.i
<= (unsigned)fc
; break;
5182 case TOK_UGT
: v1
->c
.i
= (unsigned)v1
->c
.i
> (unsigned)fc
; break;
5183 case TOK_LT
: v1
->c
.i
= v1
->c
.i
< fc
; break;
5184 case TOK_GE
: v1
->c
.i
= v1
->c
.i
>= fc
; break;
5185 case TOK_LE
: v1
->c
.i
= v1
->c
.i
<= fc
; break;
5186 case TOK_GT
: v1
->c
.i
= v1
->c
.i
> fc
; break;
5188 case TOK_LAND
: v1
->c
.i
= v1
->c
.i
&& fc
; break;
5189 case TOK_LOR
: v1
->c
.i
= v1
->c
.i
|| fc
; break;
5195 /* if commutative ops, put c2 as constant */
5196 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
5197 op
== '|' || op
== '*')) {
5202 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
5205 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
5206 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
5212 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
5213 /* try to use shifts instead of muls or divs */
5214 if (fc
> 0 && (fc
& (fc
- 1)) == 0) {
5223 else if (op
== TOK_PDIV
)
5229 } else if (c2
&& (op
== '+' || op
== '-') &&
5230 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5231 (VT_CONST
| VT_SYM
)) {
5232 /* symbol + constant case */
5239 if (!nocode_wanted
) {
5240 /* call low level op generator */
5249 /* generate a floating point operation with constant propagation */
5250 void gen_opif(int op
)
5258 /* currently, we cannot do computations with forward symbols */
5259 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5260 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5262 if (v1
->type
.t
== VT_FLOAT
) {
5265 } else if (v1
->type
.t
== VT_DOUBLE
) {
5273 /* NOTE: we only do constant propagation if finite number (not
5274 NaN or infinity) (ANSI spec) */
5275 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5279 case '+': f1
+= f2
; break;
5280 case '-': f1
-= f2
; break;
5281 case '*': f1
*= f2
; break;
5285 error("division by zero in constant");
5290 /* XXX: also handles tests ? */
5294 /* XXX: overflow test ? */
5295 if (v1
->type
.t
== VT_FLOAT
) {
5297 } else if (v1
->type
.t
== VT_DOUBLE
) {
5305 if (!nocode_wanted
) {
5313 static int pointed_size(CType
*type
)
5316 return type_size(pointed_type(type
), &align
);
5319 static inline int is_null_pointer(SValue
*p
)
5321 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5323 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5324 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5327 static inline int is_integer_btype(int bt
)
5329 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5330 bt
== VT_INT
|| bt
== VT_LLONG
);
5333 /* check types for comparison or substraction of pointers */
5334 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5336 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5339 /* null pointers are accepted for all comparisons as gcc */
5340 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5344 bt1
= type1
->t
& VT_BTYPE
;
5345 bt2
= type2
->t
& VT_BTYPE
;
5346 /* accept comparison between pointer and integer with a warning */
5347 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5348 warning("comparison between pointer and integer");
5352 /* both must be pointers or implicit function pointers */
5353 if (bt1
== VT_PTR
) {
5354 type1
= pointed_type(type1
);
5355 } else if (bt1
!= VT_FUNC
)
5356 goto invalid_operands
;
5358 if (bt2
== VT_PTR
) {
5359 type2
= pointed_type(type2
);
5360 } else if (bt2
!= VT_FUNC
) {
5362 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5364 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5365 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5369 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5370 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5371 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5372 /* gcc-like error if '-' is used */
5374 goto invalid_operands
;
5376 warning("comparison of distinct pointer types lacks a cast");
5380 /* generic gen_op: handles types problems */
5383 int u
, t1
, t2
, bt1
, bt2
, t
;
5386 t1
= vtop
[-1].type
.t
;
5387 t2
= vtop
[0].type
.t
;
5388 bt1
= t1
& VT_BTYPE
;
5389 bt2
= t2
& VT_BTYPE
;
5391 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5392 /* at least one operand is a pointer */
5393 /* relationnal op: must be both pointers */
5394 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5395 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5396 /* pointers are handled are unsigned */
5397 t
= VT_INT
| VT_UNSIGNED
;
5400 /* if both pointers, then it must be the '-' op */
5401 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5403 error("cannot use pointers here");
5404 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5405 /* XXX: check that types are compatible */
5406 u
= pointed_size(&vtop
[-1].type
);
5408 /* set to integer type */
5409 vtop
->type
.t
= VT_INT
;
5413 /* exactly one pointer : must be '+' or '-'. */
5414 if (op
!= '-' && op
!= '+')
5415 error("cannot use pointers here");
5416 /* Put pointer as first operand */
5417 if (bt2
== VT_PTR
) {
5421 type1
= vtop
[-1].type
;
5422 /* XXX: cast to int ? (long long case) */
5423 vpushi(pointed_size(&vtop
[-1].type
));
5425 #ifdef CONFIG_TCC_BCHECK
5426 /* if evaluating constant expression, no code should be
5427 generated, so no bound check */
5428 if (do_bounds_check
&& !const_wanted
) {
5429 /* if bounded pointers, we generate a special code to
5436 gen_bounded_ptr_add();
5442 /* put again type if gen_opic() swaped operands */
5445 } else if (is_float(bt1
) || is_float(bt2
)) {
5446 /* compute bigger type and do implicit casts */
5447 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5449 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5454 /* floats can only be used for a few operations */
5455 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5456 (op
< TOK_ULT
|| op
> TOK_GT
))
5457 error("invalid operands for binary operation");
5459 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5460 /* cast to biggest op */
5462 /* convert to unsigned if it does not fit in a long long */
5463 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5464 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5468 /* integer operations */
5470 /* convert to unsigned if it does not fit in an integer */
5471 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5472 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5475 /* XXX: currently, some unsigned operations are explicit, so
5476 we modify them here */
5477 if (t
& VT_UNSIGNED
) {
5484 else if (op
== TOK_LT
)
5486 else if (op
== TOK_GT
)
5488 else if (op
== TOK_LE
)
5490 else if (op
== TOK_GE
)
5497 /* special case for shifts and long long: we keep the shift as
5499 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5504 else if ((t
& VT_BTYPE
) == VT_LLONG
)
5508 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5509 /* relationnal op: the result is an int */
5510 vtop
->type
.t
= VT_INT
;
5517 /* generic itof for unsigned long long case */
5518 void gen_cvt_itof1(int t
)
5520 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
5521 (VT_LLONG
| VT_UNSIGNED
)) {
5524 vpush_global_sym(&func_old_type
, TOK___ulltof
);
5525 else if (t
== VT_DOUBLE
)
5526 vpush_global_sym(&func_old_type
, TOK___ulltod
);
5528 vpush_global_sym(&func_old_type
, TOK___ulltold
);
5538 /* generic ftoi for unsigned long long case */
5539 void gen_cvt_ftoi1(int t
)
5543 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
5544 /* not handled natively */
5545 st
= vtop
->type
.t
& VT_BTYPE
;
5547 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
5548 else if (st
== VT_DOUBLE
)
5549 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
5551 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
5556 vtop
->r2
= REG_LRET
;
5562 /* force char or short cast */
5563 void force_charshort_cast(int t
)
5567 /* XXX: add optimization if lvalue : just change type and offset */
5572 if (t
& VT_UNSIGNED
) {
5573 vpushi((1 << bits
) - 1);
5584 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
5585 static void gen_cast(CType
*type
)
5587 int sbt
, dbt
, sf
, df
, c
;
5589 /* special delayed cast for char/short */
5590 /* XXX: in some cases (multiple cascaded casts), it may still
5592 if (vtop
->r
& VT_MUSTCAST
) {
5593 vtop
->r
&= ~VT_MUSTCAST
;
5594 force_charshort_cast(vtop
->type
.t
);
5597 /* bitfields first get cast to ints */
5598 if (vtop
->type
.t
& VT_BITFIELD
) {
5602 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
5603 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
5605 if (sbt
!= dbt
&& !nocode_wanted
) {
5608 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5610 /* convert from fp to fp */
5612 /* constant case: we can do it now */
5613 /* XXX: in ISOC, cannot do it if error in convert */
5614 if (dbt
== VT_FLOAT
&& sbt
== VT_DOUBLE
)
5615 vtop
->c
.f
= (float)vtop
->c
.d
;
5616 else if (dbt
== VT_FLOAT
&& sbt
== VT_LDOUBLE
)
5617 vtop
->c
.f
= (float)vtop
->c
.ld
;
5618 else if (dbt
== VT_DOUBLE
&& sbt
== VT_FLOAT
)
5619 vtop
->c
.d
= (double)vtop
->c
.f
;
5620 else if (dbt
== VT_DOUBLE
&& sbt
== VT_LDOUBLE
)
5621 vtop
->c
.d
= (double)vtop
->c
.ld
;
5622 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_FLOAT
)
5623 vtop
->c
.ld
= (long double)vtop
->c
.f
;
5624 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_DOUBLE
)
5625 vtop
->c
.ld
= (long double)vtop
->c
.d
;
5627 /* non constant case: generate code */
5631 /* convert int to fp */
5634 case VT_LLONG
| VT_UNSIGNED
:
5636 /* XXX: add const cases for long long */
5638 case VT_INT
| VT_UNSIGNED
:
5640 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.ui
; break;
5641 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.ui
; break;
5642 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.ui
; break;
5647 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.i
; break;
5648 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.i
; break;
5649 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.i
; break;
5655 #if !defined(TCC_TARGET_ARM)
5662 /* convert fp to int */
5663 /* we handle char/short/etc... with generic code */
5664 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
5665 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
5670 case VT_LLONG
| VT_UNSIGNED
:
5672 /* XXX: add const cases for long long */
5674 case VT_INT
| VT_UNSIGNED
:
5676 case VT_FLOAT
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5677 case VT_DOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5678 case VT_LDOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5684 case VT_FLOAT
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5685 case VT_DOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5686 case VT_LDOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5694 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
5695 /* additional cast for char/short/bool... */
5699 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
5700 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
5701 /* scalar to long long */
5703 if (sbt
== (VT_INT
| VT_UNSIGNED
))
5704 vtop
->c
.ll
= vtop
->c
.ui
;
5706 vtop
->c
.ll
= vtop
->c
.i
;
5708 /* machine independent conversion */
5710 /* generate high word */
5711 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
5719 /* patch second register */
5720 vtop
[-1].r2
= vtop
->r
;
5724 } else if (dbt
== VT_BOOL
) {
5725 /* scalar to bool */
5728 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
5729 (dbt
& VT_BTYPE
) == VT_SHORT
) {
5730 force_charshort_cast(dbt
);
5731 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
5733 if (sbt
== VT_LLONG
) {
5734 /* from long long: just take low order word */
5738 /* if lvalue and single word type, nothing to do because
5739 the lvalue already contains the real type size (see
5740 VT_LVAL_xxx constants) */
5746 /* return type size. Put alignment at 'a' */
5747 static int type_size(CType
*type
, int *a
)
5752 bt
= type
->t
& VT_BTYPE
;
5753 if (bt
== VT_STRUCT
) {
5758 } else if (bt
== VT_PTR
) {
5759 if (type
->t
& VT_ARRAY
) {
5761 return type_size(&s
->type
, a
) * s
->c
;
5766 } else if (bt
== VT_LDOUBLE
) {
5768 return LDOUBLE_SIZE
;
5769 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
5770 #ifdef TCC_TARGET_I386
5776 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
5779 } else if (bt
== VT_SHORT
) {
5783 /* char, void, function, _Bool */
5789 /* return the pointed type of t */
5790 static inline CType
*pointed_type(CType
*type
)
5792 return &type
->ref
->type
;
5795 /* modify type so that its it is a pointer to type. */
5796 static void mk_pointer(CType
*type
)
5799 s
= sym_push(SYM_FIELD
, type
, 0, -1);
5800 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
5804 /* compare function types. OLD functions match any new functions */
5805 static int is_compatible_func(CType
*type1
, CType
*type2
)
5811 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5813 /* check func_call */
5816 /* XXX: not complete */
5817 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
5821 while (s1
!= NULL
) {
5824 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5834 /* return true if type1 and type2 are exactly the same (including
5837 - enums are not checked as gcc __builtin_types_compatible_p ()
5839 static int is_compatible_types(CType
*type1
, CType
*type2
)
5843 t1
= type1
->t
& VT_TYPE
;
5844 t2
= type2
->t
& VT_TYPE
;
5845 /* XXX: bitfields ? */
5848 /* test more complicated cases */
5849 bt1
= t1
& VT_BTYPE
;
5850 if (bt1
== VT_PTR
) {
5851 type1
= pointed_type(type1
);
5852 type2
= pointed_type(type2
);
5853 return is_compatible_types(type1
, type2
);
5854 } else if (bt1
== VT_STRUCT
) {
5855 return (type1
->ref
== type2
->ref
);
5856 } else if (bt1
== VT_FUNC
) {
5857 return is_compatible_func(type1
, type2
);
5863 /* print a type. If 'varstr' is not NULL, then the variable is also
5864 printed in the type */
5866 /* XXX: add array and function pointers */
5867 void type_to_str(char *buf
, int buf_size
,
5868 CType
*type
, const char *varstr
)
5875 t
= type
->t
& VT_TYPE
;
5878 if (t
& VT_CONSTANT
)
5879 pstrcat(buf
, buf_size
, "const ");
5880 if (t
& VT_VOLATILE
)
5881 pstrcat(buf
, buf_size
, "volatile ");
5882 if (t
& VT_UNSIGNED
)
5883 pstrcat(buf
, buf_size
, "unsigned ");
5913 tstr
= "long double";
5915 pstrcat(buf
, buf_size
, tstr
);
5919 if (bt
== VT_STRUCT
)
5923 pstrcat(buf
, buf_size
, tstr
);
5924 v
= type
->ref
->v
& ~SYM_STRUCT
;
5925 if (v
>= SYM_FIRST_ANOM
)
5926 pstrcat(buf
, buf_size
, "<anonymous>");
5928 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
5932 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
5933 pstrcat(buf
, buf_size
, "(");
5935 while (sa
!= NULL
) {
5936 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
5937 pstrcat(buf
, buf_size
, buf1
);
5940 pstrcat(buf
, buf_size
, ", ");
5942 pstrcat(buf
, buf_size
, ")");
5946 pstrcpy(buf1
, sizeof(buf1
), "*");
5948 pstrcat(buf1
, sizeof(buf1
), varstr
);
5949 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
5953 pstrcat(buf
, buf_size
, " ");
5954 pstrcat(buf
, buf_size
, varstr
);
5959 /* verify type compatibility to store vtop in 'dt' type, and generate
5961 static void gen_assign_cast(CType
*dt
)
5963 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
5964 char buf1
[256], buf2
[256];
5967 st
= &vtop
->type
; /* source type */
5968 dbt
= dt
->t
& VT_BTYPE
;
5969 sbt
= st
->t
& VT_BTYPE
;
5970 if (dt
->t
& VT_CONSTANT
)
5971 warning("assignment of read-only location");
5974 /* special cases for pointers */
5975 /* '0' can also be a pointer */
5976 if (is_null_pointer(vtop
))
5978 /* accept implicit pointer to integer cast with warning */
5979 if (is_integer_btype(sbt
)) {
5980 warning("assignment makes pointer from integer without a cast");
5983 type1
= pointed_type(dt
);
5984 /* a function is implicitely a function pointer */
5985 if (sbt
== VT_FUNC
) {
5986 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
5987 !is_compatible_types(pointed_type(dt
), st
))
5994 type2
= pointed_type(st
);
5995 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5996 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
5997 /* void * can match anything */
5999 /* exact type match, except for unsigned */
6002 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6003 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6004 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
6007 /* check const and volatile */
6008 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
6009 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
6010 warning("assignment discards qualifiers from pointer target type");
6016 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
6017 warning("assignment makes integer from pointer without a cast");
6019 /* XXX: more tests */
6024 tmp_type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6025 tmp_type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6026 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
6028 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
6029 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
6030 error("cannot cast '%s' to '%s'", buf1
, buf2
);
6038 /* store vtop in lvalue pushed on stack */
6041 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
6043 ft
= vtop
[-1].type
.t
;
6044 sbt
= vtop
->type
.t
& VT_BTYPE
;
6045 dbt
= ft
& VT_BTYPE
;
6046 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
6047 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
6048 /* optimize char/short casts */
6049 delayed_cast
= VT_MUSTCAST
;
6050 vtop
->type
.t
= ft
& VT_TYPE
;
6051 /* XXX: factorize */
6052 if (ft
& VT_CONSTANT
)
6053 warning("assignment of read-only location");
6056 if (!(ft
& VT_BITFIELD
))
6057 gen_assign_cast(&vtop
[-1].type
);
6060 if (sbt
== VT_STRUCT
) {
6061 /* if structure, only generate pointer */
6062 /* structure assignment : generate memcpy */
6063 /* XXX: optimize if small size */
6064 if (!nocode_wanted
) {
6065 size
= type_size(&vtop
->type
, &align
);
6067 vpush_global_sym(&func_old_type
, TOK_memcpy
);
6071 vtop
->type
.t
= VT_INT
;
6075 vtop
->type
.t
= VT_INT
;
6087 /* leave source on stack */
6088 } else if (ft
& VT_BITFIELD
) {
6089 /* bitfield store handling */
6090 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
6091 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
6092 /* remove bit field info to avoid loops */
6093 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
6095 /* duplicate destination */
6097 vtop
[-1] = vtop
[-2];
6099 /* mask and shift source */
6100 vpushi((1 << bit_size
) - 1);
6104 /* load destination, mask and or with source */
6106 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
6112 #ifdef CONFIG_TCC_BCHECK
6113 /* bound check case */
6114 if (vtop
[-1].r
& VT_MUSTBOUND
) {
6120 if (!nocode_wanted
) {
6124 r
= gv(rc
); /* generate value */
6125 /* if lvalue was saved on stack, must read it */
6126 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
6128 t
= get_reg(RC_INT
);
6130 sv
.r
= VT_LOCAL
| VT_LVAL
;
6131 sv
.c
.ul
= vtop
[-1].c
.ul
;
6133 vtop
[-1].r
= t
| VT_LVAL
;
6136 /* two word case handling : store second register at word + 4 */
6137 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
6139 /* convert to int to increment easily */
6140 vtop
->type
.t
= VT_INT
;
6146 /* XXX: it works because r2 is spilled last ! */
6147 store(vtop
->r2
, vtop
- 1);
6151 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
6152 vtop
->r
|= delayed_cast
;
6156 /* post defines POST/PRE add. c is the token ++ or -- */
6157 void inc(int post
, int c
)
6160 vdup(); /* save lvalue */
6162 gv_dup(); /* duplicate value */
6167 vpushi(c
- TOK_MID
);
6169 vstore(); /* store value */
6171 vpop(); /* if post op, return saved value */
6174 /* Parse GNUC __attribute__ extension. Currently, the following
6175 extensions are recognized:
6176 - aligned(n) : set data/function alignment.
6177 - section(x) : generate data/code in this section.
6178 - unused : currently ignored, but may be used someday.
6180 static void parse_attribute(AttributeDef
*ad
)
6184 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
6188 while (tok
!= ')') {
6189 if (tok
< TOK_IDENT
)
6190 expect("attribute name");
6198 expect("section name");
6199 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
6208 if (n
<= 0 || (n
& (n
- 1)) != 0)
6209 error("alignment must be a positive power of two");
6218 /* currently, no need to handle it because tcc does not
6219 track unused objects */
6223 /* currently, no need to handle it because tcc does not
6224 track unused objects */
6229 ad
->func_call
= FUNC_CDECL
;
6234 ad
->func_call
= FUNC_STDCALL
;
6236 #ifdef TCC_TARGET_I386
6246 ad
->func_call
= FUNC_FASTCALL1
+ n
- 1;
6251 if (tcc_state
->warn_unsupported
)
6252 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6253 /* skip parameters */
6254 /* XXX: skip parenthesis too */
6257 while (tok
!= ')' && tok
!= -1)
6272 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6273 static void struct_decl(CType
*type
, int u
)
6275 int a
, v
, size
, align
, maxalign
, c
, offset
;
6276 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
;
6281 a
= tok
; /* save decl type */
6286 /* struct already defined ? return it */
6288 expect("struct/union/enum name");
6292 error("invalid type");
6299 /* we put an undefined size for struct/union */
6300 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6301 s
->r
= 0; /* default alignment is zero as gcc */
6302 /* put struct/union/enum name in type */
6310 error("struct/union/enum already defined");
6311 /* cannot be empty */
6313 /* non empty enums are not allowed */
6314 if (a
== TOK_ENUM
) {
6318 expect("identifier");
6324 /* enum symbols have static storage */
6325 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6326 ss
->type
.t
|= VT_STATIC
;
6331 /* NOTE: we accept a trailing comma */
6341 while (tok
!= '}') {
6342 parse_btype(&btype
, &ad
);
6348 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
);
6349 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6350 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6351 error("invalid type for '%s'",
6352 get_tok_str(v
, NULL
));
6356 bit_size
= expr_const();
6357 /* XXX: handle v = 0 case for messages */
6359 error("negative width in bit-field '%s'",
6360 get_tok_str(v
, NULL
));
6361 if (v
&& bit_size
== 0)
6362 error("zero width for bit-field '%s'",
6363 get_tok_str(v
, NULL
));
6365 size
= type_size(&type1
, &align
);
6366 if (align
< ad
.aligned
)
6369 if (bit_size
>= 0) {
6370 bt
= type1
.t
& VT_BTYPE
;
6375 error("bitfields must have scalar type");
6377 if (bit_size
> bsize
) {
6378 error("width of '%s' exceeds its type",
6379 get_tok_str(v
, NULL
));
6380 } else if (bit_size
== bsize
) {
6381 /* no need for bit fields */
6383 } else if (bit_size
== 0) {
6384 /* XXX: what to do if only padding in a
6386 /* zero size: means to pad */
6390 /* we do not have enough room ? */
6391 if ((bit_pos
+ bit_size
) > bsize
)
6394 /* XXX: handle LSB first */
6395 type1
.t
|= VT_BITFIELD
|
6396 (bit_pos
<< VT_STRUCT_SHIFT
) |
6397 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
6398 bit_pos
+= bit_size
;
6404 /* add new memory data only if starting
6406 if (lbit_pos
== 0) {
6407 if (a
== TOK_STRUCT
) {
6408 c
= (c
+ align
- 1) & -align
;
6416 if (align
> maxalign
)
6420 printf("add field %s offset=%d",
6421 get_tok_str(v
, NULL
), offset
);
6422 if (type1
.t
& VT_BITFIELD
) {
6423 printf(" pos=%d size=%d",
6424 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
6425 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
6429 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
6433 if (tok
== ';' || tok
== TOK_EOF
)
6440 /* store size and alignment */
6441 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
6447 /* return 0 if no type declaration. otherwise, return the basic type
6450 static int parse_btype(CType
*type
, AttributeDef
*ad
)
6452 int t
, u
, type_found
, typespec_found
;
6456 memset(ad
, 0, sizeof(AttributeDef
));
6463 /* currently, we really ignore extension */
6473 if ((t
& VT_BTYPE
) != 0)
6474 error("too many basic types");
6490 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
6491 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6492 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
6493 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
6507 if ((t
& VT_BTYPE
) == VT_LONG
) {
6508 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6515 struct_decl(&type1
, VT_ENUM
);
6518 type
->ref
= type1
.ref
;
6522 struct_decl(&type1
, VT_STRUCT
);
6525 /* type modifiers */
6578 /* GNUC attribute */
6579 case TOK_ATTRIBUTE1
:
6580 case TOK_ATTRIBUTE2
:
6581 parse_attribute(ad
);
6588 parse_expr_type(&type1
);
6594 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
6596 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
6597 type
->ref
= s
->type
.ref
;
6604 if ((t
& (VT_SIGNED
|VT_UNSIGNED
)) == (VT_SIGNED
|VT_UNSIGNED
))
6605 error("signed and unsigned modifier");
6606 if (tcc_state
->char_is_unsigned
) {
6607 if ((t
& (VT_SIGNED
|VT_UNSIGNED
|VT_BTYPE
)) == VT_BYTE
)
6612 /* long is never used as type */
6613 if ((t
& VT_BTYPE
) == VT_LONG
)
6614 t
= (t
& ~VT_BTYPE
) | VT_INT
;
6619 /* convert a function parameter type (array to pointer and function to
6620 function pointer) */
6621 static inline void convert_parameter_type(CType
*pt
)
6623 /* array must be transformed to pointer according to ANSI C */
6625 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
6630 static void post_type(CType
*type
, AttributeDef
*ad
)
6633 Sym
**plast
, *s
, *first
;
6638 /* function declaration */
6643 while (tok
!= ')') {
6644 /* read param name and compute offset */
6645 if (l
!= FUNC_OLD
) {
6646 if (!parse_btype(&pt
, &ad1
)) {
6648 error("invalid type");
6655 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
6657 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6658 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
6659 error("parameter declared as void");
6666 convert_parameter_type(&pt
);
6667 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
6672 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
6679 /* if no parameters, then old type prototype */
6683 t1
= type
->t
& VT_STORAGE
;
6684 /* NOTE: const is ignored in returned type as it has a special
6685 meaning in gcc / C++ */
6686 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
6687 post_type(type
, ad
);
6688 /* we push a anonymous symbol which will contain the function prototype */
6689 s
= sym_push(SYM_FIELD
, type
, ad
->func_call
, l
);
6691 type
->t
= t1
| VT_FUNC
;
6693 } else if (tok
== '[') {
6694 /* array definition */
6700 error("invalid array size");
6703 /* parse next post type */
6704 t1
= type
->t
& VT_STORAGE
;
6705 type
->t
&= ~VT_STORAGE
;
6706 post_type(type
, ad
);
6708 /* we push a anonymous symbol which will contain the array
6710 s
= sym_push(SYM_FIELD
, type
, 0, n
);
6711 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
6716 /* Parse a type declaration (except basic type), and return the type
6717 in 'type'. 'td' is a bitmask indicating which kind of type decl is
6718 expected. 'type' should contain the basic type. 'ad' is the
6719 attribute definition of the basic type. It can be modified by
6722 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
6725 CType type1
, *type2
;
6728 while (tok
== '*') {
6736 qualifiers
|= VT_CONSTANT
;
6741 qualifiers
|= VT_VOLATILE
;
6749 type
->t
|= qualifiers
;
6752 /* XXX: clarify attribute handling */
6753 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6754 parse_attribute(ad
);
6756 /* recursive type */
6757 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
6758 type1
.t
= 0; /* XXX: same as int */
6761 /* XXX: this is not correct to modify 'ad' at this point, but
6762 the syntax is not clear */
6763 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6764 parse_attribute(ad
);
6765 type_decl(&type1
, ad
, v
, td
);
6768 /* type identifier */
6769 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
6773 if (!(td
& TYPE_ABSTRACT
))
6774 expect("identifier");
6778 post_type(type
, ad
);
6779 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6780 parse_attribute(ad
);
6783 /* append type at the end of type1 */
6796 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
6797 static int lvalue_type(int t
)
6802 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
6804 else if (bt
== VT_SHORT
)
6808 if (t
& VT_UNSIGNED
)
6809 r
|= VT_LVAL_UNSIGNED
;
6813 /* indirection with full error checking and bound check */
6814 static void indir(void)
6816 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
6818 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
6820 vtop
->type
= *pointed_type(&vtop
->type
);
6821 /* an array is never an lvalue */
6822 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6823 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6824 /* if bound checking, the referenced pointer must be checked */
6825 if (do_bounds_check
)
6826 vtop
->r
|= VT_MUSTBOUND
;
6830 /* pass a parameter to a function and do type checking and casting */
6831 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
6836 func_type
= func
->c
;
6837 if (func_type
== FUNC_OLD
||
6838 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
6839 /* default casting : only need to convert float to double */
6840 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
6844 } else if (arg
== NULL
) {
6845 error("too many arguments to function");
6848 type
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
6849 gen_assign_cast(&type
);
6853 /* parse an expression of the form '(type)' or '(expr)' and return its
6855 static void parse_expr_type(CType
*type
)
6861 if (parse_btype(type
, &ad
)) {
6862 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6869 static void parse_type(CType
*type
)
6874 if (!parse_btype(type
, &ad
)) {
6877 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
6880 static void vpush_tokc(int t
)
6884 vsetc(&type
, VT_CONST
, &tokc
);
6887 static void unary(void)
6889 int n
, t
, align
, size
, r
;
6894 /* XXX: GCC 2.95.3 does not generate a table although it should be
6908 vpush_tokc(VT_INT
| VT_UNSIGNED
);
6912 vpush_tokc(VT_LLONG
);
6916 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
6920 vpush_tokc(VT_FLOAT
);
6924 vpush_tokc(VT_DOUBLE
);
6928 vpush_tokc(VT_LDOUBLE
);
6931 case TOK___FUNCTION__
:
6933 goto tok_identifier
;
6939 /* special function name identifier */
6940 len
= strlen(funcname
) + 1;
6941 /* generate char[len] type */
6946 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
6947 ptr
= section_ptr_add(data_section
, len
);
6948 memcpy(ptr
, funcname
, len
);
6956 /* string parsing */
6959 if (tcc_state
->warn_write_strings
)
6964 memset(&ad
, 0, sizeof(AttributeDef
));
6965 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
6970 if (parse_btype(&type
, &ad
)) {
6971 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
6973 /* check ISOC99 compound literal */
6975 /* data is allocated locally by default */
6980 /* all except arrays are lvalues */
6981 if (!(type
.t
& VT_ARRAY
))
6982 r
|= lvalue_type(type
.t
);
6983 memset(&ad
, 0, sizeof(AttributeDef
));
6984 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
6989 } else if (tok
== '{') {
6990 /* save all registers */
6992 /* statement expression : we do not accept break/continue
6993 inside as GCC does */
6994 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
7009 /* functions names must be treated as function pointers,
7010 except for unary '&' and sizeof. Since we consider that
7011 functions are not lvalues, we only have to handle it
7012 there and in function calls. */
7013 /* arrays can also be used although they are not lvalues */
7014 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
7015 !(vtop
->type
.t
& VT_ARRAY
))
7017 mk_pointer(&vtop
->type
);
7023 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
)
7024 vtop
->c
.i
= !vtop
->c
.i
;
7025 else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
7026 vtop
->c
.i
= vtop
->c
.i
^ 1;
7028 vseti(VT_JMP
, gtst(1, 0));
7038 /* in order to force cast, we add zero */
7040 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
7041 error("pointer not accepted for unary plus");
7051 parse_expr_type(&type
);
7055 size
= type_size(&type
, &align
);
7056 if (t
== TOK_SIZEOF
) {
7058 error("sizeof applied to an incomplete type");
7065 case TOK_builtin_types_compatible_p
:
7074 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7075 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7076 vpushi(is_compatible_types(&type1
, &type2
));
7079 case TOK_builtin_constant_p
:
7081 int saved_nocode_wanted
, res
;
7084 saved_nocode_wanted
= nocode_wanted
;
7087 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
7089 nocode_wanted
= saved_nocode_wanted
;
7109 goto tok_identifier
;
7111 /* allow to take the address of a label */
7112 if (tok
< TOK_UIDENT
)
7113 expect("label identifier");
7114 s
= label_find(tok
);
7116 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7118 if (s
->r
== LABEL_DECLARED
)
7119 s
->r
= LABEL_FORWARD
;
7122 s
->type
.t
= VT_VOID
;
7123 mk_pointer(&s
->type
);
7124 s
->type
.t
|= VT_STATIC
;
7126 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
7135 expect("identifier");
7139 error("'%s' undeclared", get_tok_str(t
, NULL
));
7140 /* for simple function calls, we tolerate undeclared
7141 external reference to int() function */
7142 if (tcc_state
->warn_implicit_function_declaration
)
7143 warning("implicit declaration of function '%s'",
7144 get_tok_str(t
, NULL
));
7145 s
= external_global_sym(t
, &func_old_type
, 0);
7147 if ((s
->type
.t
& (VT_STATIC
| VT_INLINE
| VT_BTYPE
)) ==
7148 (VT_STATIC
| VT_INLINE
| VT_FUNC
)) {
7149 /* if referencing an inline function, then we generate a
7150 symbol to it if not already done. It will have the
7151 effect to generate code for it at the end of the
7152 compilation unit. Inline function as always
7153 generated in the text section. */
7155 put_extern_sym(s
, text_section
, 0, 0);
7156 r
= VT_SYM
| VT_CONST
;
7160 vset(&s
->type
, r
, s
->c
);
7161 /* if forward reference, we must point to s */
7162 if (vtop
->r
& VT_SYM
) {
7169 /* post operations */
7171 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
7174 } else if (tok
== '.' || tok
== TOK_ARROW
) {
7176 if (tok
== TOK_ARROW
)
7181 /* expect pointer on structure */
7182 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
7183 expect("struct or union");
7187 while ((s
= s
->next
) != NULL
) {
7192 error("field not found");
7193 /* add field offset to pointer */
7194 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
7197 /* change type to field type, and set to lvalue */
7198 vtop
->type
= s
->type
;
7199 /* an array is never an lvalue */
7200 if (!(vtop
->type
.t
& VT_ARRAY
)) {
7201 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7202 /* if bound checking, the referenced pointer must be checked */
7203 if (do_bounds_check
)
7204 vtop
->r
|= VT_MUSTBOUND
;
7207 } else if (tok
== '[') {
7213 } else if (tok
== '(') {
7219 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7220 /* pointer test (no array accepted) */
7221 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
7222 vtop
->type
= *pointed_type(&vtop
->type
);
7223 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
7227 expect("function pointer");
7230 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
7232 /* get return type */
7235 sa
= s
->next
; /* first parameter */
7237 /* compute first implicit argument if a structure is returned */
7238 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
7239 /* get some space for the returned structure */
7240 size
= type_size(&s
->type
, &align
);
7241 loc
= (loc
- size
) & -align
;
7243 ret
.r
= VT_LOCAL
| VT_LVAL
;
7244 /* pass it as 'int' to avoid structure arg passing
7246 vseti(VT_LOCAL
, loc
);
7252 /* return in register */
7253 if (is_float(ret
.type
.t
)) {
7256 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
7265 gfunc_param_typed(s
, sa
);
7275 error("too few arguments to function");
7277 if (!nocode_wanted
) {
7278 gfunc_call(nb_args
);
7280 vtop
-= (nb_args
+ 1);
7283 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
7291 static void uneq(void)
7297 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
7298 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
7299 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
7314 static void expr_prod(void)
7319 while (tok
== '*' || tok
== '/' || tok
== '%') {
7327 static void expr_sum(void)
7332 while (tok
== '+' || tok
== '-') {
7340 static void expr_shift(void)
7345 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
7353 static void expr_cmp(void)
7358 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
7359 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
7367 static void expr_cmpeq(void)
7372 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
7380 static void expr_and(void)
7383 while (tok
== '&') {
7390 static void expr_xor(void)
7393 while (tok
== '^') {
7400 static void expr_or(void)
7403 while (tok
== '|') {
7410 /* XXX: fix this mess */
7411 static void expr_land_const(void)
7414 while (tok
== TOK_LAND
) {
7421 /* XXX: fix this mess */
7422 static void expr_lor_const(void)
7425 while (tok
== TOK_LOR
) {
7432 /* only used if non constant */
7433 static void expr_land(void)
7438 if (tok
== TOK_LAND
) {
7442 if (tok
!= TOK_LAND
) {
7452 static void expr_lor(void)
7457 if (tok
== TOK_LOR
) {
7461 if (tok
!= TOK_LOR
) {
7471 /* XXX: better constant handling */
7472 static void expr_eq(void)
7474 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
7476 CType type
, type1
, type2
;
7485 if (tok
== ':' && gnu_ext
) {
7501 if (vtop
!= vstack
) {
7502 /* needed to avoid having different registers saved in
7504 if (is_float(vtop
->type
.t
))
7511 if (tok
== ':' && gnu_ext
) {
7519 sv
= *vtop
; /* save value to handle it later */
7520 vtop
--; /* no vpop so that FP stack is not flushed */
7528 bt1
= t1
& VT_BTYPE
;
7530 bt2
= t2
& VT_BTYPE
;
7531 /* cast operands to correct type according to ISOC rules */
7532 if (is_float(bt1
) || is_float(bt2
)) {
7533 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
7534 type
.t
= VT_LDOUBLE
;
7535 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
7540 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
7541 /* cast to biggest op */
7543 /* convert to unsigned if it does not fit in a long long */
7544 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
7545 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
7546 type
.t
|= VT_UNSIGNED
;
7547 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
7548 /* XXX: test pointer compatibility */
7550 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
7551 /* XXX: test structure compatibility */
7553 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
7554 /* NOTE: as an extension, we accept void on only one side */
7557 /* integer operations */
7559 /* convert to unsigned if it does not fit in an integer */
7560 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
7561 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
7562 type
.t
|= VT_UNSIGNED
;
7565 /* now we convert second operand */
7568 if (is_float(type
.t
)) {
7570 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
7571 /* for long longs, we use fixed registers to avoid having
7572 to handle a complicated move */
7577 /* this is horrible, but we must also convert first
7581 /* put again first value and cast it */
7592 static void gexpr(void)
7603 /* parse an expression and return its type without any side effect. */
7604 static void expr_type(CType
*type
)
7606 int saved_nocode_wanted
;
7608 saved_nocode_wanted
= nocode_wanted
;
7613 nocode_wanted
= saved_nocode_wanted
;
7616 /* parse a unary expression and return its type without any side
7618 static void unary_type(CType
*type
)
7630 /* parse a constant expression and return value in vtop. */
7631 static void expr_const1(void)
7640 /* parse an integer constant and return its value. */
7641 static int expr_const(void)
7645 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
7646 expect("constant expression");
7652 /* return the label token if current token is a label, otherwise
7654 static int is_label(void)
7658 /* fast test first */
7659 if (tok
< TOK_UIDENT
)
7661 /* no need to save tokc because tok is an identifier */
7668 unget_tok(last_tok
);
7673 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
7674 int case_reg
, int is_expr
)
7679 /* generate line number info */
7681 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
7682 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
7684 last_line_num
= file
->line_num
;
7688 /* default return value is (void) */
7690 vtop
->type
.t
= VT_VOID
;
7693 if (tok
== TOK_IF
) {
7700 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7702 if (c
== TOK_ELSE
) {
7706 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7707 gsym(d
); /* patch else jmp */
7710 } else if (tok
== TOK_WHILE
) {
7718 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7722 } else if (tok
== '{') {
7726 /* record local declaration stack position */
7728 llabel
= local_label_stack
;
7729 /* handle local labels declarations */
7730 if (tok
== TOK_LABEL
) {
7733 if (tok
< TOK_UIDENT
)
7734 expect("label identifier");
7735 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
7745 while (tok
!= '}') {
7750 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7753 /* pop locally defined labels */
7754 label_pop(&local_label_stack
, llabel
);
7755 /* pop locally defined symbols */
7756 sym_pop(&local_stack
, s
);
7758 } else if (tok
== TOK_RETURN
) {
7762 gen_assign_cast(&func_vt
);
7763 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
7765 /* if returning structure, must copy it to implicit
7766 first pointer arg location */
7769 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
7772 /* copy structure value to pointer */
7774 } else if (is_float(func_vt
.t
)) {
7779 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
7782 rsym
= gjmp(rsym
); /* jmp */
7783 } else if (tok
== TOK_BREAK
) {
7786 error("cannot break");
7787 *bsym
= gjmp(*bsym
);
7790 } else if (tok
== TOK_CONTINUE
) {
7793 error("cannot continue");
7794 *csym
= gjmp(*csym
);
7797 } else if (tok
== TOK_FOR
) {
7824 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7829 if (tok
== TOK_DO
) {
7834 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7845 if (tok
== TOK_SWITCH
) {
7849 /* XXX: other types than integer */
7850 case_reg
= gv(RC_INT
);
7854 b
= gjmp(0); /* jump to first case */
7856 block(&a
, csym
, &b
, &c
, case_reg
, 0);
7857 /* if no default, jmp after switch */
7865 if (tok
== TOK_CASE
) {
7872 if (gnu_ext
&& tok
== TOK_DOTS
) {
7876 warning("empty case range");
7878 /* since a case is like a label, we must skip it with a jmp */
7885 *case_sym
= gtst(1, 0);
7888 *case_sym
= gtst(1, 0);
7892 *case_sym
= gtst(1, *case_sym
);
7897 goto block_after_label
;
7899 if (tok
== TOK_DEFAULT
) {
7905 error("too many 'default'");
7908 goto block_after_label
;
7910 if (tok
== TOK_GOTO
) {
7912 if (tok
== '*' && gnu_ext
) {
7916 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
7919 } else if (tok
>= TOK_UIDENT
) {
7920 s
= label_find(tok
);
7921 /* put forward definition if needed */
7923 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7925 if (s
->r
== LABEL_DECLARED
)
7926 s
->r
= LABEL_FORWARD
;
7928 /* label already defined */
7929 if (s
->r
& LABEL_FORWARD
)
7930 s
->next
= (void *)gjmp((long)s
->next
);
7932 gjmp_addr((long)s
->next
);
7935 expect("label identifier");
7938 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
7946 if (s
->r
== LABEL_DEFINED
)
7947 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
7948 gsym((long)s
->next
);
7949 s
->r
= LABEL_DEFINED
;
7951 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
7953 s
->next
= (void *)ind
;
7954 /* we accept this, but it is a mistake */
7957 warning("deprecated use of label at end of compound statement");
7961 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7964 /* expression case */
7979 /* t is the array or struct type. c is the array or struct
7980 address. cur_index/cur_field is the pointer to the current
7981 value. 'size_only' is true if only size info is needed (only used
7983 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
7984 int *cur_index
, Sym
**cur_field
,
7988 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
7994 if (gnu_ext
&& (l
= is_label()) != 0)
7996 while (tok
== '[' || tok
== '.') {
7998 if (!(type
->t
& VT_ARRAY
))
7999 expect("array type");
8002 index
= expr_const();
8003 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
8004 expect("invalid index");
8005 if (tok
== TOK_DOTS
&& gnu_ext
) {
8007 index_last
= expr_const();
8008 if (index_last
< 0 ||
8009 (s
->c
>= 0 && index_last
>= s
->c
) ||
8011 expect("invalid index");
8017 *cur_index
= index_last
;
8018 type
= pointed_type(type
);
8019 elem_size
= type_size(type
, &align
);
8020 c
+= index
* elem_size
;
8021 /* NOTE: we only support ranges for last designator */
8022 nb_elems
= index_last
- index
+ 1;
8023 if (nb_elems
!= 1) {
8032 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
8033 expect("struct/union type");
8046 /* XXX: fix this mess by using explicit storage field */
8048 type1
.t
|= (type
->t
& ~VT_TYPE
);
8062 if (type
->t
& VT_ARRAY
) {
8064 type
= pointed_type(type
);
8065 c
+= index
* type_size(type
, &align
);
8069 error("too many field init");
8070 /* XXX: fix this mess by using explicit storage field */
8072 type1
.t
|= (type
->t
& ~VT_TYPE
);
8077 decl_initializer(type
, sec
, c
, 0, size_only
);
8079 /* XXX: make it more general */
8080 if (!size_only
&& nb_elems
> 1) {
8081 unsigned long c_end
;
8086 error("range init not supported yet for dynamic storage");
8087 c_end
= c
+ nb_elems
* elem_size
;
8088 if (c_end
> sec
->data_allocated
)
8089 section_realloc(sec
, c_end
);
8090 src
= sec
->data
+ c
;
8092 for(i
= 1; i
< nb_elems
; i
++) {
8094 memcpy(dst
, src
, elem_size
);
8100 #define EXPR_CONST 1
8103 /* store a value or an expression directly in global data or in local array */
8104 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
8105 int v
, int expr_type
)
8107 int saved_global_expr
, bt
, bit_pos
, bit_size
;
8109 unsigned long long bit_mask
;
8117 /* compound literals must be allocated globally in this case */
8118 saved_global_expr
= global_expr
;
8121 global_expr
= saved_global_expr
;
8122 /* NOTE: symbols are accepted */
8123 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
8124 error("initializer element is not constant");
8132 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
8135 /* XXX: not portable */
8136 /* XXX: generate error if incorrect relocation */
8137 gen_assign_cast(&dtype
);
8138 bt
= type
->t
& VT_BTYPE
;
8139 ptr
= sec
->data
+ c
;
8140 /* XXX: make code faster ? */
8141 if (!(type
->t
& VT_BITFIELD
)) {
8146 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
8147 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
8148 bit_mask
= (1LL << bit_size
) - 1;
8150 if ((vtop
->r
& VT_SYM
) &&
8156 (bt
== VT_INT
&& bit_size
!= 32)))
8157 error("initializer element is not computable at load time");
8160 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8163 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8166 *(double *)ptr
= vtop
->c
.d
;
8169 *(long double *)ptr
= vtop
->c
.ld
;
8172 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
8175 if (vtop
->r
& VT_SYM
) {
8176 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
8178 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8183 vset(&dtype
, VT_LOCAL
, c
);
8190 /* put zeros for variable based init */
8191 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
8194 /* nothing to do because globals are already set to zero */
8196 vpush_global_sym(&func_old_type
, TOK_memset
);
8204 /* 't' contains the type and storage info. 'c' is the offset of the
8205 object in section 'sec'. If 'sec' is NULL, it means stack based
8206 allocation. 'first' is true if array '{' must be read (multi
8207 dimension implicit array init handling). 'size_only' is true if
8208 size only evaluation is wanted (only for arrays). */
8209 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
8210 int first
, int size_only
)
8212 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
8213 int size1
, align1
, expr_type
;
8217 if (type
->t
& VT_ARRAY
) {
8221 t1
= pointed_type(type
);
8222 size1
= type_size(t1
, &align1
);
8225 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
8231 /* only parse strings here if correct type (otherwise: handle
8232 them as ((w)char *) expressions */
8233 if ((tok
== TOK_LSTR
&&
8234 (t1
->t
& VT_BTYPE
) == VT_INT
) ||
8236 (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
8237 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8242 /* compute maximum number of chars wanted */
8244 cstr_len
= cstr
->size
;
8246 cstr_len
= cstr
->size
/ sizeof(int);
8249 if (n
>= 0 && nb
> (n
- array_length
))
8250 nb
= n
- array_length
;
8253 warning("initializer-string for array is too long");
8254 /* in order to go faster for common case (char
8255 string in global variable, we handle it
8257 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
8258 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
8262 ch
= ((unsigned char *)cstr
->data
)[i
];
8264 ch
= ((int *)cstr
->data
)[i
];
8265 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
8273 /* only add trailing zero if enough storage (no
8274 warning in this case since it is standard) */
8275 if (n
< 0 || array_length
< n
) {
8277 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
8283 while (tok
!= '}') {
8284 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
8285 if (n
>= 0 && index
>= n
)
8286 error("index too large");
8287 /* must put zero in holes (note that doing it that way
8288 ensures that it even works with designators) */
8289 if (!size_only
&& array_length
< index
) {
8290 init_putz(t1
, sec
, c
+ array_length
* size1
,
8291 (index
- array_length
) * size1
);
8294 if (index
> array_length
)
8295 array_length
= index
;
8296 /* special test for multi dimensional arrays (may not
8297 be strictly correct if designators are used at the
8299 if (index
>= n
&& no_oblock
)
8308 /* put zeros at the end */
8309 if (!size_only
&& n
>= 0 && array_length
< n
) {
8310 init_putz(t1
, sec
, c
+ array_length
* size1
,
8311 (n
- array_length
) * size1
);
8313 /* patch type size if needed */
8315 s
->c
= array_length
;
8316 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
8317 (sec
|| !first
|| tok
== '{')) {
8320 /* NOTE: the previous test is a specific case for automatic
8321 struct/union init */
8322 /* XXX: union needs only one init */
8324 /* XXX: this test is incorrect for local initializers
8325 beginning with ( without {. It would be much more difficult
8326 to do it correctly (ideally, the expression parser should
8327 be used in all cases) */
8333 while (tok
== '(') {
8337 if (!parse_btype(&type1
, &ad1
))
8339 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
8341 if (!is_assignable_types(type
, &type1
))
8342 error("invalid type for cast");
8347 if (first
|| tok
== '{') {
8356 while (tok
!= '}') {
8357 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
8359 if (!size_only
&& array_length
< index
) {
8360 init_putz(type
, sec
, c
+ array_length
,
8361 index
- array_length
);
8363 index
= index
+ type_size(&f
->type
, &align1
);
8364 if (index
> array_length
)
8365 array_length
= index
;
8367 if (no_oblock
&& f
== NULL
)
8373 /* put zeros at the end */
8374 if (!size_only
&& array_length
< n
) {
8375 init_putz(type
, sec
, c
+ array_length
,
8384 } else if (tok
== '{') {
8386 decl_initializer(type
, sec
, c
, first
, size_only
);
8388 } else if (size_only
) {
8389 /* just skip expression */
8391 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
8395 else if (tok
== ')')
8400 /* currently, we always use constant expression for globals
8401 (may change for scripting case) */
8402 expr_type
= EXPR_CONST
;
8404 expr_type
= EXPR_ANY
;
8405 init_putv(type
, sec
, c
, 0, expr_type
);
8409 /* parse an initializer for type 't' if 'has_init' is non zero, and
8410 allocate space in local or global data space ('r' is either
8411 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
8412 variable 'v' of scope 'scope' is declared before initializers are
8413 parsed. If 'v' is zero, then a reference to the new object is put
8414 in the value stack. If 'has_init' is 2, a special parsing is done
8415 to handle string constants. */
8416 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
8417 int has_init
, int v
, int scope
)
8419 int size
, align
, addr
, data_offset
;
8421 ParseState saved_parse_state
;
8422 TokenString init_str
;
8425 size
= type_size(type
, &align
);
8426 /* If unknown size, we must evaluate it before
8427 evaluating initializers because
8428 initializers can generate global data too
8429 (e.g. string pointers or ISOC99 compound
8430 literals). It also simplifies local
8431 initializers handling */
8432 tok_str_new(&init_str
);
8435 error("unknown type size");
8436 /* get all init string */
8437 if (has_init
== 2) {
8438 /* only get strings */
8439 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8440 tok_str_add_tok(&init_str
);
8445 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
8447 error("unexpected end of file in initializer");
8448 tok_str_add_tok(&init_str
);
8451 else if (tok
== '}') {
8459 tok_str_add(&init_str
, -1);
8460 tok_str_add(&init_str
, 0);
8463 save_parse_state(&saved_parse_state
);
8465 macro_ptr
= init_str
.str
;
8467 decl_initializer(type
, NULL
, 0, 1, 1);
8468 /* prepare second initializer parsing */
8469 macro_ptr
= init_str
.str
;
8472 /* if still unknown size, error */
8473 size
= type_size(type
, &align
);
8475 error("unknown type size");
8477 /* take into account specified alignment if bigger */
8478 if (ad
->aligned
> align
)
8479 align
= ad
->aligned
;
8480 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
8482 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
8484 loc
= (loc
- size
) & -align
;
8486 /* handles bounds */
8487 /* XXX: currently, since we do only one pass, we cannot track
8488 '&' operators, so we add only arrays */
8489 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
8490 unsigned long *bounds_ptr
;
8491 /* add padding between regions */
8493 /* then add local bound info */
8494 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
8495 bounds_ptr
[0] = addr
;
8496 bounds_ptr
[1] = size
;
8499 /* local variable */
8500 sym_push(v
, type
, r
, addr
);
8502 /* push local reference */
8503 vset(type
, r
, addr
);
8509 if (v
&& scope
== VT_CONST
) {
8510 /* see if the symbol was already defined */
8513 if (!is_compatible_types(&sym
->type
, type
))
8514 error("incompatible types for redefinition of '%s'",
8515 get_tok_str(v
, NULL
));
8516 if (sym
->type
.t
& VT_EXTERN
) {
8517 /* if the variable is extern, it was not allocated */
8518 sym
->type
.t
&= ~VT_EXTERN
;
8519 /* set array size if it was ommited in extern
8521 if ((sym
->type
.t
& VT_ARRAY
) &&
8522 sym
->type
.ref
->c
< 0 &&
8524 sym
->type
.ref
->c
= type
->ref
->c
;
8526 /* we accept several definitions of the same
8527 global variable. this is tricky, because we
8528 must play with the SHN_COMMON type of the symbol */
8529 /* XXX: should check if the variable was already
8530 initialized. It is incorrect to initialized it
8532 /* no init data, we won't add more to the symbol */
8539 /* allocate symbol in corresponding section */
8544 else if (tcc_state
->nocommon
)
8548 data_offset
= sec
->data_offset
;
8549 data_offset
= (data_offset
+ align
- 1) & -align
;
8551 /* very important to increment global pointer at this time
8552 because initializers themselves can create new initializers */
8553 data_offset
+= size
;
8554 /* add padding if bound check */
8555 if (do_bounds_check
)
8557 sec
->data_offset
= data_offset
;
8558 /* allocate section space to put the data */
8559 if (sec
->sh_type
!= SHT_NOBITS
&&
8560 data_offset
> sec
->data_allocated
)
8561 section_realloc(sec
, data_offset
);
8562 /* align section if needed */
8563 if (align
> sec
->sh_addralign
)
8564 sec
->sh_addralign
= align
;
8566 addr
= 0; /* avoid warning */
8570 if (scope
== VT_CONST
) {
8575 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
8577 /* update symbol definition */
8579 put_extern_sym(sym
, sec
, addr
, size
);
8582 /* put a common area */
8583 put_extern_sym(sym
, NULL
, align
, size
);
8584 /* XXX: find a nicer way */
8585 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
8586 esym
->st_shndx
= SHN_COMMON
;
8591 /* push global reference */
8592 sym
= get_sym_ref(type
, sec
, addr
, size
);
8594 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
8598 /* handles bounds now because the symbol must be defined
8599 before for the relocation */
8600 if (do_bounds_check
) {
8601 unsigned long *bounds_ptr
;
8603 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
8604 /* then add global bound info */
8605 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
8606 bounds_ptr
[0] = 0; /* relocated */
8607 bounds_ptr
[1] = size
;
8611 decl_initializer(type
, sec
, addr
, 1, 0);
8612 /* restore parse state if needed */
8614 tok_str_free(init_str
.str
);
8615 restore_parse_state(&saved_parse_state
);
8621 void put_func_debug(Sym
*sym
)
8626 /* XXX: we put here a dummy type */
8627 snprintf(buf
, sizeof(buf
), "%s:%c1",
8628 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
8629 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
8630 cur_text_section
, sym
->c
);
8635 /* parse an old style function declaration list */
8636 /* XXX: check multiple parameter */
8637 static void func_decl_list(Sym
*func_sym
)
8644 /* parse each declaration */
8645 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
8646 if (!parse_btype(&btype
, &ad
))
8647 expect("declaration list");
8648 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8649 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8651 /* we accept no variable after */
8655 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8656 /* find parameter in function parameter list */
8659 if ((s
->v
& ~SYM_FIELD
) == v
)
8663 error("declaration for parameter '%s' but no such parameter",
8664 get_tok_str(v
, NULL
));
8666 /* check that no storage specifier except 'register' was given */
8667 if (type
.t
& VT_STORAGE
)
8668 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
8669 convert_parameter_type(&type
);
8670 /* we can add the type (NOTE: it could be local to the function) */
8672 /* accept other parameters */
8683 /* parse a function defined by symbol 'sym' and generate its code in
8684 'cur_text_section' */
8685 static void gen_function(Sym
*sym
)
8687 ind
= cur_text_section
->data_offset
;
8688 /* NOTE: we patch the symbol size later */
8689 put_extern_sym(sym
, cur_text_section
, ind
, 0);
8690 funcname
= get_tok_str(sym
->v
, NULL
);
8692 /* put debug symbol */
8694 put_func_debug(sym
);
8695 /* push a dummy symbol to enable local sym storage */
8696 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
8697 gfunc_prolog(&sym
->type
);
8699 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
8702 cur_text_section
->data_offset
= ind
;
8703 label_pop(&global_label_stack
, NULL
);
8704 sym_pop(&local_stack
, NULL
); /* reset local stack */
8705 /* end of function */
8706 /* patch symbol size */
8707 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_size
=
8710 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
8712 funcname
= ""; /* for safety */
8713 func_vt
.t
= VT_VOID
; /* for safety */
8714 ind
= 0; /* for safety */
8717 static void gen_inline_functions(void)
8721 int *str
, inline_generated
;
8723 /* iterate while inline function are referenced */
8725 inline_generated
= 0;
8726 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
8728 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
8729 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
8730 (VT_STATIC
| VT_INLINE
) &&
8732 /* the function was used: generate its code and
8733 convert it to a normal function */
8734 str
= (int *)sym
->r
;
8735 sym
->r
= VT_SYM
| VT_CONST
;
8736 type
->t
&= ~VT_INLINE
;
8740 cur_text_section
= text_section
;
8742 macro_ptr
= NULL
; /* fail safe */
8745 inline_generated
= 1;
8748 if (!inline_generated
)
8752 /* free all remaining inline function tokens */
8753 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
8755 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
8756 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
8757 (VT_STATIC
| VT_INLINE
)) {
8758 str
= (int *)sym
->r
;
8760 sym
->r
= 0; /* fail safe */
8765 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
8766 static void decl(int l
)
8774 if (!parse_btype(&btype
, &ad
)) {
8775 /* skip redundant ';' */
8776 /* XXX: find more elegant solution */
8781 if (l
== VT_CONST
&&
8782 (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
)) {
8783 /* global asm block */
8787 /* special test for old K&R protos without explicit int
8788 type. Only accepted when defining global data */
8789 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
8793 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8794 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8796 /* we accept no variable after */
8800 while (1) { /* iterate thru each declaration */
8802 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8806 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
8807 printf("type = '%s'\n", buf
);
8810 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8811 /* if old style function prototype, we accept a
8814 if (sym
->c
== FUNC_OLD
)
8815 func_decl_list(sym
);
8820 error("cannot use local functions");
8821 if (!(type
.t
& VT_FUNC
))
8822 expect("function definition");
8824 /* reject abstract declarators in function definition */
8826 while ((sym
= sym
->next
) != NULL
)
8827 if (!(sym
->v
& ~SYM_FIELD
))
8828 expect("identifier");
8830 /* XXX: cannot do better now: convert extern line to static inline */
8831 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
8832 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
8836 if ((sym
->type
.t
& VT_BTYPE
) != VT_FUNC
)
8838 /* specific case: if not func_call defined, we put
8839 the one of the prototype */
8840 /* XXX: should have default value */
8841 if (sym
->type
.ref
->r
!= FUNC_CDECL
&&
8842 type
.ref
->r
== FUNC_CDECL
)
8843 type
.ref
->r
= sym
->type
.ref
->r
;
8844 if (!is_compatible_types(&sym
->type
, &type
)) {
8846 error("incompatible types for redefinition of '%s'",
8847 get_tok_str(v
, NULL
));
8849 /* if symbol is already defined, then put complete type */
8852 /* put function symbol */
8853 sym
= global_identifier_push(v
, type
.t
, 0);
8854 sym
->type
.ref
= type
.ref
;
8857 /* static inline functions are just recorded as a kind
8858 of macro. Their code will be emitted at the end of
8859 the compilation unit only if they are used */
8860 if ((type
.t
& (VT_INLINE
| VT_STATIC
)) ==
8861 (VT_INLINE
| VT_STATIC
)) {
8862 TokenString func_str
;
8865 tok_str_new(&func_str
);
8871 error("unexpected end of file");
8872 tok_str_add_tok(&func_str
);
8877 } else if (t
== '}') {
8879 if (block_level
== 0)
8883 tok_str_add(&func_str
, -1);
8884 tok_str_add(&func_str
, 0);
8885 sym
->r
= (int)func_str
.str
;
8887 /* compute text section */
8888 cur_text_section
= ad
.section
;
8889 if (!cur_text_section
)
8890 cur_text_section
= text_section
;
8891 sym
->r
= VT_SYM
| VT_CONST
;
8896 if (btype
.t
& VT_TYPEDEF
) {
8897 /* save typedefed type */
8898 /* XXX: test storage specifiers ? */
8899 sym
= sym_push(v
, &type
, 0, 0);
8900 sym
->type
.t
|= VT_TYPEDEF
;
8901 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8902 /* external function definition */
8903 /* specific case for func_call attribute */
8905 type
.ref
->r
= ad
.func_call
;
8906 external_sym(v
, &type
, 0);
8908 /* not lvalue if array */
8910 if (!(type
.t
& VT_ARRAY
))
8911 r
|= lvalue_type(type
.t
);
8912 has_init
= (tok
== '=');
8913 if ((btype
.t
& VT_EXTERN
) ||
8914 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
8915 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
8916 /* external variable */
8917 /* NOTE: as GCC, uninitialized global static
8918 arrays of null size are considered as
8920 external_sym(v
, &type
, r
);
8922 if (type
.t
& VT_STATIC
)
8928 decl_initializer_alloc(&type
, &ad
, r
,
8942 /* better than nothing, but needs extension to handle '-E' option
8944 static void preprocess_init(TCCState
*s1
)
8946 s1
->include_stack_ptr
= s1
->include_stack
;
8947 /* XXX: move that before to avoid having to initialize
8948 file->ifdef_stack_ptr ? */
8949 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
8950 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
8952 /* XXX: not ANSI compliant: bound checking says error */
8956 /* compile the C file opened in 'file'. Return non zero if errors. */
8957 static int tcc_compile(TCCState
*s1
)
8961 volatile int section_sym
;
8964 printf("%s: **** new file\n", file
->filename
);
8966 preprocess_init(s1
);
8969 anon_sym
= SYM_FIRST_ANOM
;
8971 /* file info: full path + filename */
8972 section_sym
= 0; /* avoid warning */
8974 section_sym
= put_elf_sym(symtab_section
, 0, 0,
8975 ELF32_ST_INFO(STB_LOCAL
, STT_SECTION
), 0,
8976 text_section
->sh_num
, NULL
);
8977 getcwd(buf
, sizeof(buf
));
8978 pstrcat(buf
, sizeof(buf
), "/");
8979 put_stabs_r(buf
, N_SO
, 0, 0,
8980 text_section
->data_offset
, text_section
, section_sym
);
8981 put_stabs_r(file
->filename
, N_SO
, 0, 0,
8982 text_section
->data_offset
, text_section
, section_sym
);
8984 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
8985 symbols can be safely used */
8986 put_elf_sym(symtab_section
, 0, 0,
8987 ELF32_ST_INFO(STB_LOCAL
, STT_FILE
), 0,
8988 SHN_ABS
, file
->filename
);
8990 /* define some often used types */
8991 int_type
.t
= VT_INT
;
8993 char_pointer_type
.t
= VT_BYTE
;
8994 mk_pointer(&char_pointer_type
);
8996 func_old_type
.t
= VT_FUNC
;
8997 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
9000 /* define 'void *alloca(unsigned int)' builtin function */
9005 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
9006 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
9009 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
9013 define_start
= define_stack
;
9015 if (setjmp(s1
->error_jmp_buf
) == 0) {
9017 s1
->error_set_jmp_enabled
= 1;
9019 ch
= file
->buf_ptr
[0];
9020 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9021 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
9025 expect("declaration");
9027 /* end of translation unit info */
9029 put_stabs_r(NULL
, N_SO
, 0, 0,
9030 text_section
->data_offset
, text_section
, section_sym
);
9033 s1
->error_set_jmp_enabled
= 0;
9035 /* reset define stack, but leave -Dsymbols (may be incorrect if
9036 they are undefined) */
9037 free_defines(define_start
);
9039 gen_inline_functions();
9041 sym_pop(&global_stack
, NULL
);
9043 return s1
->nb_errors
!= 0 ? -1 : 0;
9047 int tcc_compile_string(TCCState
*s
, const char *str
)
9049 BufferedFile bf1
, *bf
= &bf1
;
9053 /* init file structure */
9055 /* XXX: avoid copying */
9057 buf
= tcc_malloc(len
+ 1);
9060 memcpy(buf
, str
, len
);
9063 bf
->buf_end
= buf
+ len
;
9064 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
9068 ret
= tcc_compile(s
);
9072 /* currently, no need to close */
9077 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9078 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
9080 BufferedFile bf1
, *bf
= &bf1
;
9082 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
9083 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
9087 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
9089 /* init file structure */
9091 bf
->buf_ptr
= bf
->buffer
;
9092 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
9093 *bf
->buf_end
= CH_EOB
;
9094 bf
->filename
[0] = '\0';
9098 s1
->include_stack_ptr
= s1
->include_stack
;
9100 /* parse with define parser */
9101 ch
= file
->buf_ptr
[0];
9107 /* undefine a preprocessor symbol */
9108 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
9112 ts
= tok_alloc(sym
, strlen(sym
));
9113 s
= define_find(ts
->tok
);
9114 /* undefine symbol by putting an invalid name */
9119 #ifdef CONFIG_TCC_ASM
9121 #ifdef TCC_TARGET_I386
9122 #include "i386-asm.c"
9127 static void asm_instr(void)
9129 error("inline asm() not supported");
9131 static void asm_global_instr(void)
9133 error("inline asm() not supported");
9139 #ifdef TCC_TARGET_COFF
9140 #include "tcccoff.c"
9143 /* print the position in the source file of PC value 'pc' by reading
9144 the stabs debug information */
9145 static void rt_printline(unsigned long wanted_pc
)
9147 Stab_Sym
*sym
, *sym_end
;
9148 char func_name
[128], last_func_name
[128];
9149 unsigned long func_addr
, last_pc
, pc
;
9150 const char *incl_files
[INCLUDE_STACK_SIZE
];
9151 int incl_index
, len
, last_line_num
, i
;
9152 const char *str
, *p
;
9154 fprintf(stderr
, "0x%08lx:", wanted_pc
);
9156 func_name
[0] = '\0';
9159 last_func_name
[0] = '\0';
9160 last_pc
= 0xffffffff;
9162 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
9163 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
9164 while (sym
< sym_end
) {
9165 switch(sym
->n_type
) {
9166 /* function start or end */
9168 if (sym
->n_strx
== 0) {
9169 /* we test if between last line and end of function */
9170 pc
= sym
->n_value
+ func_addr
;
9171 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9173 func_name
[0] = '\0';
9176 str
= stabstr_section
->data
+ sym
->n_strx
;
9177 p
= strchr(str
, ':');
9179 pstrcpy(func_name
, sizeof(func_name
), str
);
9182 if (len
> sizeof(func_name
) - 1)
9183 len
= sizeof(func_name
) - 1;
9184 memcpy(func_name
, str
, len
);
9185 func_name
[len
] = '\0';
9187 func_addr
= sym
->n_value
;
9190 /* line number info */
9192 pc
= sym
->n_value
+ func_addr
;
9193 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9196 last_line_num
= sym
->n_desc
;
9198 strcpy(last_func_name
, func_name
);
9202 str
= stabstr_section
->data
+ sym
->n_strx
;
9204 if (incl_index
< INCLUDE_STACK_SIZE
) {
9205 incl_files
[incl_index
++] = str
;
9213 if (sym
->n_strx
== 0) {
9214 incl_index
= 0; /* end of translation unit */
9216 str
= stabstr_section
->data
+ sym
->n_strx
;
9217 /* do not add path */
9219 if (len
> 0 && str
[len
- 1] != '/')
9227 /* second pass: we try symtab symbols (no line number info) */
9230 Elf32_Sym
*sym
, *sym_end
;
9233 sym_end
= (Elf32_Sym
*)(symtab_section
->data
+ symtab_section
->data_offset
);
9234 for(sym
= (Elf32_Sym
*)symtab_section
->data
+ 1;
9237 type
= ELF32_ST_TYPE(sym
->st_info
);
9238 if (type
== STT_FUNC
) {
9239 if (wanted_pc
>= sym
->st_value
&&
9240 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
9241 pstrcpy(last_func_name
, sizeof(last_func_name
),
9242 strtab_section
->data
+ sym
->st_name
);
9248 /* did not find any info: */
9249 fprintf(stderr
, " ???\n");
9252 if (last_func_name
[0] != '\0') {
9253 fprintf(stderr
, " %s()", last_func_name
);
9255 if (incl_index
> 0) {
9256 fprintf(stderr
, " (%s:%d",
9257 incl_files
[incl_index
- 1], last_line_num
);
9258 for(i
= incl_index
- 2; i
>= 0; i
--)
9259 fprintf(stderr
, ", included from %s", incl_files
[i
]);
9260 fprintf(stderr
, ")");
9262 fprintf(stderr
, "\n");
9265 #if !defined(WIN32) && !defined(CONFIG_TCCBOOT)
9269 /* fix for glibc 2.1 */
9275 /* return the PC at frame level 'level'. Return non zero if not found */
9276 static int rt_get_caller_pc(unsigned long *paddr
,
9277 ucontext_t
*uc
, int level
)
9283 #if defined(__FreeBSD__)
9284 *paddr
= uc
->uc_mcontext
.mc_eip
;
9285 #elif defined(__dietlibc__)
9286 *paddr
= uc
->uc_mcontext
.eip
;
9288 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
9292 #if defined(__FreeBSD__)
9293 fp
= uc
->uc_mcontext
.mc_ebp
;
9294 #elif defined(__dietlibc__)
9295 fp
= uc
->uc_mcontext
.ebp
;
9297 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
9299 for(i
=1;i
<level
;i
++) {
9300 /* XXX: check address validity with program info */
9301 if (fp
<= 0x1000 || fp
>= 0xc0000000)
9303 fp
= ((unsigned long *)fp
)[0];
9305 *paddr
= ((unsigned long *)fp
)[1];
9311 #warning add arch specific rt_get_caller_pc()
9313 static int rt_get_caller_pc(unsigned long *paddr
,
9314 ucontext_t
*uc
, int level
)
9320 /* emit a run time error at position 'pc' */
9321 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
9328 fprintf(stderr
, "Runtime error: ");
9329 vfprintf(stderr
, fmt
, ap
);
9330 fprintf(stderr
, "\n");
9331 for(i
=0;i
<num_callers
;i
++) {
9332 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
9335 fprintf(stderr
, "at ");
9337 fprintf(stderr
, "by ");
9344 /* signal handler for fatal errors */
9345 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
9347 ucontext_t
*uc
= puc
;
9351 switch(siginf
->si_code
) {
9354 rt_error(uc
, "division by zero");
9357 rt_error(uc
, "floating point exception");
9363 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
9364 rt_error(uc
, *rt_bound_error_msg
);
9366 rt_error(uc
, "dereferencing invalid pointer");
9369 rt_error(uc
, "illegal instruction");
9372 rt_error(uc
, "abort() called");
9375 rt_error(uc
, "caught signal %d", signum
);
9382 /* do all relocations (needed before using tcc_get_symbol()) */
9383 int tcc_relocate(TCCState
*s1
)
9390 tcc_add_runtime(s1
);
9392 build_got_entries(s1
);
9394 relocate_common_syms();
9396 /* compute relocation address : section are relocated in place. We
9397 also alloc the bss space */
9398 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9399 s
= s1
->sections
[i
];
9400 if (s
->sh_flags
& SHF_ALLOC
) {
9401 if (s
->sh_type
== SHT_NOBITS
)
9402 s
->data
= tcc_mallocz(s
->data_offset
);
9403 s
->sh_addr
= (unsigned long)s
->data
;
9407 relocate_syms(s1
, 1);
9409 if (s1
->nb_errors
!= 0)
9412 /* relocate each section */
9413 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9414 s
= s1
->sections
[i
];
9416 relocate_section(s1
, s
);
9421 /* launch the compiled program with the given arguments */
9422 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
9424 int (*prog_main
)(int, char **);
9426 if (tcc_relocate(s1
) < 0)
9429 prog_main
= tcc_get_symbol_err(s1
, "main");
9432 #if defined(WIN32) || defined(CONFIG_TCCBOOT)
9433 error("debug mode currently not available for Windows");
9435 struct sigaction sigact
;
9436 /* install TCC signal handlers to print debug info on fatal
9438 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
9439 sigact
.sa_sigaction
= sig_error
;
9440 sigemptyset(&sigact
.sa_mask
);
9441 sigaction(SIGFPE
, &sigact
, NULL
);
9442 sigaction(SIGILL
, &sigact
, NULL
);
9443 sigaction(SIGSEGV
, &sigact
, NULL
);
9444 sigaction(SIGBUS
, &sigact
, NULL
);
9445 sigaction(SIGABRT
, &sigact
, NULL
);
9449 #ifdef CONFIG_TCC_BCHECK
9450 if (do_bounds_check
) {
9451 void (*bound_init
)(void);
9453 /* set error function */
9454 rt_bound_error_msg
= (void *)tcc_get_symbol_err(s1
,
9455 "__bound_error_msg");
9457 /* XXX: use .init section so that it also work in binary ? */
9458 bound_init
= (void *)tcc_get_symbol_err(s1
, "__bound_init");
9462 return (*prog_main
)(argc
, argv
);
9465 TCCState
*tcc_new(void)
9472 s
= tcc_mallocz(sizeof(TCCState
));
9476 s
->output_type
= TCC_OUTPUT_MEMORY
;
9478 /* init isid table */
9480 isidnum_table
[i
] = isid(i
) || isnum(i
);
9482 /* add all tokens */
9484 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
9486 tok_ident
= TOK_IDENT
;
9495 ts
= tok_alloc(p
, r
- p
- 1);
9499 /* we add dummy defines for some special macros to speed up tests
9500 and to have working defined() */
9501 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
9502 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
9503 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
9504 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
9506 /* standard defines */
9507 tcc_define_symbol(s
, "__STDC__", NULL
);
9508 #if defined(TCC_TARGET_I386)
9509 tcc_define_symbol(s
, "__i386__", NULL
);
9511 #if defined(TCC_TARGET_ARM)
9512 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
9513 tcc_define_symbol(s
, "__arm_elf__", NULL
);
9514 tcc_define_symbol(s
, "__arm_elf", NULL
);
9515 tcc_define_symbol(s
, "arm_elf", NULL
);
9516 tcc_define_symbol(s
, "__arm__", NULL
);
9517 tcc_define_symbol(s
, "__arm", NULL
);
9518 tcc_define_symbol(s
, "arm", NULL
);
9519 tcc_define_symbol(s
, "__APCS_32__", NULL
);
9522 tcc_define_symbol(s
, "__linux__", NULL
);
9523 tcc_define_symbol(s
, "linux", NULL
);
9525 /* tiny C specific defines */
9526 tcc_define_symbol(s
, "__TINYC__", NULL
);
9528 /* tiny C & gcc defines */
9529 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
9530 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
9531 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
9533 /* default library paths */
9534 tcc_add_library_path(s
, "/usr/local/lib");
9535 tcc_add_library_path(s
, "/usr/lib");
9536 tcc_add_library_path(s
, "/lib");
9538 /* no section zero */
9539 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
9541 /* create standard sections */
9542 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
9543 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
9544 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
9546 /* symbols are always generated for linking stage */
9547 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
9549 ".hashtab", SHF_PRIVATE
);
9550 strtab_section
= symtab_section
->link
;
9552 /* private symbol table for dynamic symbols */
9553 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
9555 ".dynhashtab", SHF_PRIVATE
);
9556 s
->alacarte_link
= 1;
9558 #ifdef CHAR_IS_UNSIGNED
9559 s
->char_is_unsigned
= 1;
9564 void tcc_delete(TCCState
*s1
)
9568 /* free -D defines */
9572 n
= tok_ident
- TOK_IDENT
;
9573 for(i
= 0; i
< n
; i
++)
9574 tcc_free(table_ident
[i
]);
9575 tcc_free(table_ident
);
9577 /* free all sections */
9579 free_section(symtab_section
->hash
);
9581 free_section(s1
->dynsymtab_section
->hash
);
9582 free_section(s1
->dynsymtab_section
->link
);
9583 free_section(s1
->dynsymtab_section
);
9585 for(i
= 1; i
< s1
->nb_sections
; i
++)
9586 free_section(s1
->sections
[i
]);
9587 tcc_free(s1
->sections
);
9589 /* free loaded dlls array */
9590 for(i
= 0; i
< s1
->nb_loaded_dlls
; i
++)
9591 tcc_free(s1
->loaded_dlls
[i
]);
9592 tcc_free(s1
->loaded_dlls
);
9595 for(i
= 0; i
< s1
->nb_library_paths
; i
++)
9596 tcc_free(s1
->library_paths
[i
]);
9597 tcc_free(s1
->library_paths
);
9599 /* cached includes */
9600 for(i
= 0; i
< s1
->nb_cached_includes
; i
++)
9601 tcc_free(s1
->cached_includes
[i
]);
9602 tcc_free(s1
->cached_includes
);
9604 for(i
= 0; i
< s1
->nb_include_paths
; i
++)
9605 tcc_free(s1
->include_paths
[i
]);
9606 tcc_free(s1
->include_paths
);
9608 for(i
= 0; i
< s1
->nb_sysinclude_paths
; i
++)
9609 tcc_free(s1
->sysinclude_paths
[i
]);
9610 tcc_free(s1
->sysinclude_paths
);
9615 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
9619 pathname1
= tcc_strdup(pathname
);
9620 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
9624 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
9628 pathname1
= tcc_strdup(pathname
);
9629 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
9633 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
9635 const char *ext
, *filename1
;
9638 BufferedFile
*saved_file
;
9640 /* find source file type with extension */
9641 filename1
= strrchr(filename
, '/');
9645 filename1
= filename
;
9646 ext
= strrchr(filename1
, '.');
9652 file
= tcc_open(s1
, filename
);
9654 if (flags
& AFF_PRINT_ERROR
) {
9655 error_noabort("file '%s' not found", filename
);
9661 if (!ext
|| !strcmp(ext
, "c")) {
9662 /* C file assumed */
9663 ret
= tcc_compile(s1
);
9665 #ifdef CONFIG_TCC_ASM
9666 if (!strcmp(ext
, "S")) {
9667 /* preprocessed assembler */
9668 ret
= tcc_assemble(s1
, 1);
9669 } else if (!strcmp(ext
, "s")) {
9670 /* non preprocessed assembler */
9671 ret
= tcc_assemble(s1
, 0);
9676 /* assume executable format: auto guess file type */
9677 ret
= read(fd
, &ehdr
, sizeof(ehdr
));
9678 lseek(fd
, 0, SEEK_SET
);
9680 error_noabort("could not read header");
9682 } else if (ret
!= sizeof(ehdr
)) {
9683 goto try_load_script
;
9686 if (ehdr
.e_ident
[0] == ELFMAG0
&&
9687 ehdr
.e_ident
[1] == ELFMAG1
&&
9688 ehdr
.e_ident
[2] == ELFMAG2
&&
9689 ehdr
.e_ident
[3] == ELFMAG3
) {
9690 file
->line_num
= 0; /* do not display line number if error */
9691 if (ehdr
.e_type
== ET_REL
) {
9692 ret
= tcc_load_object_file(s1
, fd
, 0);
9693 } else if (ehdr
.e_type
== ET_DYN
) {
9694 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
9696 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
9702 ret
= tcc_load_dll(s1
, fd
, filename
,
9703 (flags
& AFF_REFERENCED_DLL
) != 0);
9706 error_noabort("unrecognized ELF file");
9709 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
9710 file
->line_num
= 0; /* do not display line number if error */
9711 ret
= tcc_load_archive(s1
, fd
);
9713 #ifdef TCC_TARGET_COFF
9714 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
9715 ret
= tcc_load_coff(s1
, fd
);
9719 /* as GNU ld, consider it is an ld script if not recognized */
9721 ret
= tcc_load_ldscript(s1
);
9723 error_noabort("unrecognized file type");
9738 int tcc_add_file(TCCState
*s
, const char *filename
)
9740 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
9743 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
9747 pathname1
= tcc_strdup(pathname
);
9748 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
9752 /* find and load a dll. Return non zero if not found */
9753 /* XXX: add '-rpath' option support ? */
9754 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
9759 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9760 snprintf(buf
, sizeof(buf
), "%s/%s",
9761 s
->library_paths
[i
], filename
);
9762 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
9768 /* the library name is the same as the argument of the '-l' option */
9769 int tcc_add_library(TCCState
*s
, const char *libraryname
)
9774 /* first we look for the dynamic library if not static linking */
9775 if (!s
->static_link
) {
9776 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
9777 if (tcc_add_dll(s
, buf
, 0) == 0)
9781 /* then we look for the static library */
9782 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9783 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
9784 s
->library_paths
[i
], libraryname
);
9785 if (tcc_add_file_internal(s
, buf
, 0) == 0)
9791 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
9793 add_elf_sym(symtab_section
, val
, 0,
9794 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
),
9799 int tcc_set_output_type(TCCState
*s
, int output_type
)
9803 s
->output_type
= output_type
;
9806 /* default include paths */
9807 /* XXX: reverse order needed if -isystem support */
9808 tcc_add_sysinclude_path(s
, "/usr/local/include");
9809 tcc_add_sysinclude_path(s
, "/usr/include");
9810 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
9811 tcc_add_sysinclude_path(s
, buf
);
9814 /* if bound checking, then add corresponding sections */
9815 #ifdef CONFIG_TCC_BCHECK
9816 if (do_bounds_check
) {
9818 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
9819 /* create bounds sections */
9820 bounds_section
= new_section(s
, ".bounds",
9821 SHT_PROGBITS
, SHF_ALLOC
);
9822 lbounds_section
= new_section(s
, ".lbounds",
9823 SHT_PROGBITS
, SHF_ALLOC
);
9827 if (s
->char_is_unsigned
) {
9828 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
9831 /* add debug sections */
9834 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
9835 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
9836 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
9837 put_elf_str(stabstr_section
, "");
9838 stab_section
->link
= stabstr_section
;
9839 /* put first entry */
9840 put_stabs("", 0, 0, 0, 0);
9843 /* add libc crt1/crti objects */
9844 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
9846 if (output_type
!= TCC_OUTPUT_DLL
)
9847 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
9848 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
9853 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
9854 #define FD_INVERT 0x0002 /* invert value before storing */
9856 typedef struct FlagDef
{
9862 static const FlagDef warning_defs
[] = {
9863 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
9864 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
9865 { offsetof(TCCState
, warn_error
), 0, "error" },
9866 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
9867 "implicit-function-declaration" },
9870 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
9871 const char *name
, int value
)
9878 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
9882 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
9883 if (!strcmp(r
, p
->name
))
9888 if (p
->flags
& FD_INVERT
)
9890 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
9895 /* set/reset a warning */
9896 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
9901 if (!strcmp(warning_name
, "all")) {
9902 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
9903 if (p
->flags
& WD_ALL
)
9904 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
9908 return set_flag(s
, warning_defs
, countof(warning_defs
),
9909 warning_name
, value
);
9913 static const FlagDef flag_defs
[] = {
9914 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
9915 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
9916 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
9919 /* set/reset a flag */
9920 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
9922 return set_flag(s
, flag_defs
, countof(flag_defs
),
9926 #if !defined(LIBTCC)
9928 /* extract the basename of a file */
9929 static const char *tcc_basename(const char *name
)
9932 p
= strrchr(name
, '/');
9935 p
= strrchr(name
, '\\');
9944 static int64_t getclock_us(void)
9949 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
9952 gettimeofday(&tv
, NULL
);
9953 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
9959 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2003 Fabrice Bellard\n"
9960 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
9961 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]\n"
9962 " [infile1 infile2...] [-run infile args...]\n"
9964 "General options:\n"
9965 " -v display current version\n"
9966 " -c compile only - generate an object file\n"
9967 " -o outfile set output filename\n"
9968 " -Bdir set tcc internal library path\n"
9969 " -bench output compilation statistics\n"
9970 " -run run compiled source\n"
9971 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
9972 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
9973 " -w disable all warnings\n"
9974 "Preprocessor options:\n"
9975 " -Idir add include path 'dir'\n"
9976 " -Dsym[=val] define 'sym' with value 'val'\n"
9977 " -Usym undefine 'sym'\n"
9979 " -Ldir add library path 'dir'\n"
9980 " -llib link with dynamic or static library 'lib'\n"
9981 " -shared generate a shared library\n"
9982 " -static static linking\n"
9983 " -rdynamic export all global symbols to dynamic linker\n"
9984 " -r relocatable output\n"
9985 "Debugger options:\n"
9986 " -g generate runtime debug info\n"
9987 #ifdef CONFIG_TCC_BCHECK
9988 " -b compile with built-in memory and bounds checker (implies -g)\n"
9990 " -bt N show N callers in stack traces\n"
9994 #define TCC_OPTION_HAS_ARG 0x0001
9995 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
9997 typedef struct TCCOption
{
10025 TCC_OPTION_nostdinc
,
10026 TCC_OPTION_nostdlib
,
10027 TCC_OPTION_print_search_dirs
,
10028 TCC_OPTION_rdynamic
,
10034 static const TCCOption tcc_options
[] = {
10035 { "h", TCC_OPTION_HELP
, 0 },
10036 { "?", TCC_OPTION_HELP
, 0 },
10037 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
10038 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
10039 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
10040 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
10041 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
10042 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10043 { "bench", TCC_OPTION_bench
, 0 },
10044 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
10045 #ifdef CONFIG_TCC_BCHECK
10046 { "b", TCC_OPTION_b
, 0 },
10048 { "g", TCC_OPTION_g
, 0 },
10049 { "c", TCC_OPTION_c
, 0 },
10050 { "static", TCC_OPTION_static
, 0 },
10051 { "shared", TCC_OPTION_shared
, 0 },
10052 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
10053 { "run", TCC_OPTION_run
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10054 { "rdynamic", TCC_OPTION_rdynamic
, 0 },
10055 { "r", TCC_OPTION_r
, 0 },
10056 { "Wl,", TCC_OPTION_Wl
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10057 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10058 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10059 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
10060 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10061 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
10062 { "nostdlib", TCC_OPTION_nostdlib
, 0 },
10063 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
10064 { "v", TCC_OPTION_v
, 0 },
10065 { "w", TCC_OPTION_w
, 0 },
10069 /* convert 'str' into an array of space separated strings */
10070 static int expand_args(char ***pargv
, const char *str
)
10079 while (is_space(*str
))
10084 while (*str
!= '\0' && !is_space(*str
))
10087 arg
= tcc_malloc(len
+ 1);
10088 memcpy(arg
, s1
, len
);
10090 dynarray_add((void ***)&argv
, &argc
, arg
);
10096 static char **files
;
10097 static int nb_files
, nb_libraries
;
10098 static int multiple_files
;
10099 static int print_search_dirs
;
10100 static int output_type
;
10101 static int reloc_output
;
10102 static const char *outfile
;
10104 int parse_args(TCCState
*s
, int argc
, char **argv
)
10107 const TCCOption
*popt
;
10108 const char *optarg
, *p1
, *r1
;
10113 if (optind
>= argc
) {
10114 if (nb_files
== 0 && !print_search_dirs
)
10119 r
= argv
[optind
++];
10121 /* add a new file */
10122 dynarray_add((void ***)&files
, &nb_files
, r
);
10123 if (!multiple_files
) {
10125 /* argv[0] will be this file */
10129 /* find option in table (match only the first chars */
10130 popt
= tcc_options
;
10134 error("invalid option -- '%s'", r
);
10147 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
10148 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
10151 if (optind
>= argc
)
10152 error("argument to '%s' is missing", r
);
10153 optarg
= argv
[optind
++];
10161 switch(popt
->index
) {
10162 case TCC_OPTION_HELP
:
10167 if (tcc_add_include_path(s
, optarg
) < 0)
10168 error("too many include paths");
10173 sym
= (char *)optarg
;
10174 value
= strchr(sym
, '=');
10179 tcc_define_symbol(s
, sym
, value
);
10183 tcc_undefine_symbol(s
, optarg
);
10186 tcc_add_library_path(s
, optarg
);
10189 /* set tcc utilities path (mainly for tcc development) */
10190 tcc_lib_path
= optarg
;
10193 dynarray_add((void ***)&files
, &nb_files
, r
);
10196 case TCC_OPTION_bench
:
10199 case TCC_OPTION_bt
:
10200 num_callers
= atoi(optarg
);
10202 #ifdef CONFIG_TCC_BCHECK
10204 do_bounds_check
= 1;
10212 multiple_files
= 1;
10213 output_type
= TCC_OUTPUT_OBJ
;
10215 case TCC_OPTION_static
:
10216 s
->static_link
= 1;
10218 case TCC_OPTION_shared
:
10219 output_type
= TCC_OUTPUT_DLL
;
10222 multiple_files
= 1;
10226 /* generate a .o merging several output files */
10228 output_type
= TCC_OUTPUT_OBJ
;
10230 case TCC_OPTION_nostdinc
:
10233 case TCC_OPTION_nostdlib
:
10236 case TCC_OPTION_print_search_dirs
:
10237 print_search_dirs
= 1;
10239 case TCC_OPTION_run
:
10243 argc1
= expand_args(&argv1
, optarg
);
10245 parse_args(s
, argc1
, argv1
);
10247 multiple_files
= 0;
10248 output_type
= TCC_OUTPUT_MEMORY
;
10252 printf("tcc version %s\n", TCC_VERSION
);
10255 if (tcc_set_flag(s
, optarg
, 1) < 0 && s
->warn_unsupported
)
10256 goto unsupported_option
;
10259 if (tcc_set_warning(s
, optarg
, 1) < 0 &&
10260 s
->warn_unsupported
)
10261 goto unsupported_option
;
10266 case TCC_OPTION_rdynamic
:
10269 case TCC_OPTION_Wl
:
10272 if (strstart(optarg
, "-Ttext,", &p
)) {
10273 s
->text_addr
= strtoul(p
, NULL
, 16);
10274 s
->has_text_addr
= 1;
10275 } else if (strstart(optarg
, "--oformat,", &p
)) {
10276 if (strstart(p
, "elf32-", NULL
)) {
10277 s
->output_format
= TCC_OUTPUT_FORMAT_ELF
;
10278 } else if (!strcmp(p
, "binary")) {
10279 s
->output_format
= TCC_OUTPUT_FORMAT_BINARY
;
10281 #ifdef TCC_TARGET_COFF
10282 if (!strcmp(p
, "coff")) {
10283 s
->output_format
= TCC_OUTPUT_FORMAT_COFF
;
10287 error("target %s not found", p
);
10290 error("unsupported linker option '%s'", optarg
);
10295 if (s
->warn_unsupported
) {
10296 unsupported_option
:
10297 warning("unsupported option '%s'", r
);
10306 int main(int argc
, char **argv
)
10310 int nb_objfiles
, ret
, optind
;
10311 char objfilename
[1024];
10312 int64_t start_time
= 0;
10315 output_type
= TCC_OUTPUT_EXE
;
10317 multiple_files
= 1;
10322 print_search_dirs
= 0;
10324 optind
= parse_args(s
, argc
- 1, argv
+ 1) + 1;
10326 if (print_search_dirs
) {
10327 /* enough for Linux kernel */
10328 printf("install: %s/\n", tcc_lib_path
);
10332 nb_objfiles
= nb_files
- nb_libraries
;
10334 /* if outfile provided without other options, we output an
10336 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
10337 output_type
= TCC_OUTPUT_EXE
;
10339 /* check -c consistency : only single file handled. XXX: checks file type */
10340 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
10341 /* accepts only a single input file */
10342 if (nb_objfiles
!= 1)
10343 error("cannot specify multiple files with -c");
10344 if (nb_libraries
!= 0)
10345 error("cannot specify libraries with -c");
10348 /* compute default outfile name */
10349 if (output_type
!= TCC_OUTPUT_MEMORY
&& !outfile
) {
10350 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
10353 pstrcpy(objfilename
, sizeof(objfilename
) - 1,
10354 tcc_basename(files
[0]));
10355 /* add .o extension */
10356 ext
= strrchr(objfilename
, '.');
10358 goto default_outfile
;
10359 strcpy(ext
+ 1, "o");
10362 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
10364 outfile
= objfilename
;
10368 start_time
= getclock_us();
10371 tcc_set_output_type(s
, output_type
);
10373 /* compile or add each files or library */
10374 for(i
= 0;i
< nb_files
; i
++) {
10375 const char *filename
;
10377 filename
= files
[i
];
10378 if (filename
[0] == '-') {
10379 if (tcc_add_library(s
, filename
+ 2) < 0)
10380 error("cannot find %s", filename
);
10382 if (tcc_add_file(s
, filename
) < 0) {
10389 /* free all files */
10394 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
10395 if (total_time
< 0.001)
10396 total_time
= 0.001;
10397 if (total_bytes
< 1)
10399 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
10400 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
10401 total_time
, (int)(total_lines
/ total_time
),
10402 total_bytes
/ total_time
/ 1000000.0);
10405 if (s
->output_type
!= TCC_OUTPUT_MEMORY
) {
10406 tcc_output_file(s
, outfile
);
10409 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
10412 /* XXX: cannot do it with bound checking because of the malloc hooks */
10413 if (!do_bounds_check
)
10418 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);