2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001-2004 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
42 #include <sys/timeb.h>
46 #include <sys/ucontext.h>
49 #endif /* !CONFIG_TCCBOOT */
62 /* preprocessor debug */
64 /* include file debug */
72 /* target selection */
73 //#define TCC_TARGET_I386 /* i386 code generator */
74 //#define TCC_TARGET_ARM /* ARMv4 code generator */
75 //#define TCC_TARGET_C67 /* TMS320C67xx code generator */
77 /* default target is I386 */
78 #if !defined(TCC_TARGET_I386) && !defined(TCC_TARGET_ARM) && \
79 !defined(TCC_TARGET_C67)
80 #define TCC_TARGET_I386
83 #if !defined(WIN32) && !defined(TCC_UCLIBC) && !defined(TCC_TARGET_ARM) && \
84 !defined(TCC_TARGET_C67)
85 #define CONFIG_TCC_BCHECK /* enable bound checking code */
88 /* define it to include assembler support */
89 #if !defined(TCC_TARGET_ARM) && !defined(TCC_TARGET_C67)
90 #define CONFIG_TCC_ASM
93 /* object format selection */
94 #if defined(TCC_TARGET_C67)
95 #define TCC_TARGET_COFF
104 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
105 executables or dlls */
106 #define CONFIG_TCC_CRT_PREFIX "/usr/lib"
108 #define INCLUDE_STACK_SIZE 32
109 #define IFDEF_STACK_SIZE 64
110 #define VSTACK_SIZE 256
111 #define STRING_MAX_SIZE 1024
112 #define PACK_STACK_SIZE 8
114 #define TOK_HASH_SIZE 8192 /* must be a power of two */
115 #define TOK_ALLOC_INCR 512 /* must be a power of two */
116 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
118 /* token symbol management */
119 typedef struct TokenSym
{
120 struct TokenSym
*hash_next
;
121 struct Sym
*sym_define
; /* direct pointer to define */
122 struct Sym
*sym_label
; /* direct pointer to label */
123 struct Sym
*sym_struct
; /* direct pointer to structure */
124 struct Sym
*sym_identifier
; /* direct pointer to identifier */
125 int tok
; /* token number */
130 typedef struct CString
{
131 int size
; /* size in bytes */
132 void *data
; /* either 'char *' or 'int *' */
134 void *data_allocated
; /* if non NULL, data has been malloced */
137 /* type definition */
138 typedef struct CType
{
144 typedef union CValue
{
150 unsigned int ul
; /* address (should be unsigned long on 64 bit cpu) */
152 unsigned long long ull
;
153 struct CString
*cstr
;
159 typedef struct SValue
{
160 CType type
; /* type */
161 unsigned short r
; /* register + flags */
162 unsigned short r2
; /* second register, used for 'long long'
163 type. If not used, set to VT_CONST */
164 CValue c
; /* constant, if VT_CONST */
165 struct Sym
*sym
; /* symbol, if (VT_SYM | VT_CONST) */
168 /* symbol management */
170 int v
; /* symbol token */
171 int r
; /* associated register */
172 int c
; /* associated number */
173 CType type
; /* associated type */
174 struct Sym
*next
; /* next related symbol */
175 struct Sym
*prev
; /* prev symbol in stack */
176 struct Sym
*prev_tok
; /* previous symbol for this token */
179 /* section definition */
180 /* XXX: use directly ELF structure for parameters ? */
181 /* special flag to indicate that the section should not be linked to
183 #define SHF_PRIVATE 0x80000000
185 typedef struct Section
{
186 unsigned long data_offset
; /* current data offset */
187 unsigned char *data
; /* section data */
188 unsigned long data_allocated
; /* used for realloc() handling */
189 int sh_name
; /* elf section name (only used during output) */
190 int sh_num
; /* elf section number */
191 int sh_type
; /* elf section type */
192 int sh_flags
; /* elf section flags */
193 int sh_info
; /* elf section info */
194 int sh_addralign
; /* elf section alignment */
195 int sh_entsize
; /* elf entry size */
196 unsigned long sh_size
; /* section size (only used during output) */
197 unsigned long sh_addr
; /* address at which the section is relocated */
198 unsigned long sh_offset
; /* address at which the section is relocated */
199 int nb_hashed_syms
; /* used to resize the hash table */
200 struct Section
*link
; /* link to another section */
201 struct Section
*reloc
; /* corresponding section for relocation, if any */
202 struct Section
*hash
; /* hash table for symbols */
203 struct Section
*next
;
204 char name
[1]; /* section name */
207 typedef struct DLLReference
{
212 /* GNUC attribute definition */
213 typedef struct AttributeDef
{
217 unsigned char func_call
; /* FUNC_CDECL, FUNC_STDCALL, FUNC_FASTCALLx */
218 unsigned char dllexport
;
221 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
222 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
223 #define SYM_FIRST_ANOM 0x10000000 /* first anonymous sym */
225 /* stored in 'Sym.c' field */
226 #define FUNC_NEW 1 /* ansi function prototype */
227 #define FUNC_OLD 2 /* old function prototype */
228 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
230 /* stored in 'Sym.r' field */
231 #define FUNC_CDECL 0 /* standard c call */
232 #define FUNC_STDCALL 1 /* pascal c call */
233 #define FUNC_FASTCALL1 2 /* first param in %eax */
234 #define FUNC_FASTCALL2 3 /* first parameters in %eax, %edx */
235 #define FUNC_FASTCALL3 4 /* first parameter in %eax, %edx, %ecx */
237 /* field 'Sym.t' for macros */
238 #define MACRO_OBJ 0 /* object like macro */
239 #define MACRO_FUNC 1 /* function like macro */
241 /* field 'Sym.r' for C labels */
242 #define LABEL_DEFINED 0 /* label is defined */
243 #define LABEL_FORWARD 1 /* label is forward defined */
244 #define LABEL_DECLARED 2 /* label is declared but never used */
246 /* type_decl() types */
247 #define TYPE_ABSTRACT 1 /* type without variable */
248 #define TYPE_DIRECT 2 /* type with variable */
250 #define IO_BUF_SIZE 8192
252 typedef struct BufferedFile
{
256 int line_num
; /* current line number - here to simplify code */
257 int ifndef_macro
; /* #ifndef macro / #endif search */
258 int ifndef_macro_saved
; /* saved ifndef_macro */
259 int *ifdef_stack_ptr
; /* ifdef_stack value at the start of the file */
260 char inc_type
; /* type of include */
261 char inc_filename
[512]; /* filename specified by the user */
262 char filename
[1024]; /* current filename - here to simplify code */
263 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
266 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
267 #define CH_EOF (-1) /* end of file */
269 /* parsing state (used to save parser state to reparse part of the
270 source several times) */
271 typedef struct ParseState
{
278 /* used to record tokens */
279 typedef struct TokenString
{
286 /* include file cache, used to find files faster and also to eliminate
287 inclusion if the include file is protected by #ifndef ... #endif */
288 typedef struct CachedInclude
{
290 int hash_next
; /* -1 if none */
291 char type
; /* '"' or '>' to give include type */
292 char filename
[1]; /* path specified in #include */
295 #define CACHED_INCLUDES_HASH_SIZE 512
298 static struct BufferedFile
*file
;
301 static CString tokcstr
; /* current parsed string, if any */
302 /* additional informations about token */
303 static int tok_flags
;
304 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
305 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
306 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
308 static int *macro_ptr
, *macro_ptr_allocated
;
309 static int *unget_saved_macro_ptr
;
310 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
311 static int unget_buffer_enabled
;
312 static int parse_flags
;
313 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
314 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
315 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
316 token. line feed is also
318 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
320 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
321 static Section
*cur_text_section
; /* current section where function code is
323 #ifdef CONFIG_TCC_ASM
324 static Section
*last_text_section
; /* to handle .previous asm directive */
326 /* bound check related sections */
327 static Section
*bounds_section
; /* contains global data bound description */
328 static Section
*lbounds_section
; /* contains local data bound description */
329 /* symbol sections */
330 static Section
*symtab_section
, *strtab_section
;
333 static Section
*stab_section
, *stabstr_section
;
335 /* loc : local variable index
336 ind : output code index
338 anon_sym: anonymous symbol index
340 static int rsym
, anon_sym
, ind
, loc
;
341 /* expression generation modifiers */
342 static int const_wanted
; /* true if constant wanted */
343 static int nocode_wanted
; /* true if no code generation wanted for an expression */
344 static int global_expr
; /* true if compound literals must be allocated
345 globally (used during initializers parsing */
346 static CType func_vt
; /* current function return type (used by return
349 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
350 static int tok_ident
;
351 static TokenSym
**table_ident
;
352 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
353 static char token_buf
[STRING_MAX_SIZE
+ 1];
354 static char *funcname
;
355 static Sym
*global_stack
, *local_stack
;
356 static Sym
*define_stack
;
357 static Sym
*global_label_stack
, *local_label_stack
;
358 /* symbol allocator */
359 #define SYM_POOL_NB (8192 / sizeof(Sym))
360 static Sym
*sym_free_first
;
362 static SValue vstack
[VSTACK_SIZE
], *vtop
;
363 /* some predefined types */
364 static CType char_pointer_type
, func_old_type
, int_type
;
365 /* true if isid(c) || isnum(c) */
366 static unsigned char isidnum_table
[256];
368 /* compile with debug symbol (and use them if error during execution) */
369 static int do_debug
= 0;
371 /* compile with built-in memory and bounds checker */
372 static int do_bounds_check
= 0;
374 /* display benchmark infos */
376 static int do_bench
= 0;
378 static int total_lines
;
379 static int total_bytes
;
381 /* use GNU C extensions */
382 static int gnu_ext
= 1;
384 /* use Tiny C extensions */
385 static int tcc_ext
= 1;
387 /* max number of callers shown if error */
388 static int num_callers
= 6;
389 static const char **rt_bound_error_msg
;
391 /* XXX: get rid of this ASAP */
392 static struct TCCState
*tcc_state
;
394 /* give the path of the tcc libraries */
395 static const char *tcc_lib_path
= CONFIG_TCC_LIBDIR
"/tcc";
400 BufferedFile
**include_stack_ptr
;
401 int *ifdef_stack_ptr
;
403 /* include file handling */
404 char **include_paths
;
405 int nb_include_paths
;
406 char **sysinclude_paths
;
407 int nb_sysinclude_paths
;
408 CachedInclude
**cached_includes
;
409 int nb_cached_includes
;
411 char **library_paths
;
412 int nb_library_paths
;
414 /* array of all loaded dlls (including those referenced by loaded
416 DLLReference
**loaded_dlls
;
421 int nb_sections
; /* number of sections, including first dummy section */
426 unsigned long *got_offsets
;
428 /* give the correspondance from symtab indexes to dynsym indexes */
429 int *symtab_to_dynsym
;
431 /* temporary dynamic symbol sections (for dll loading) */
432 Section
*dynsymtab_section
;
433 /* exported dynamic symbol section */
436 int nostdinc
; /* if true, no standard headers are added */
437 int nostdlib
; /* if true, no standard libraries are added */
439 int nocommon
; /* if true, do not use common symbols for .bss data */
441 /* if true, static linking is performed */
444 /* if true, all symbols are exported */
447 /* if true, only link in referenced objects from archive */
450 /* address of text section */
451 unsigned long text_addr
;
454 /* output format, see TCC_OUTPUT_FORMAT_xxx */
457 /* C language options */
458 int char_is_unsigned
;
460 /* warning switches */
461 int warn_write_strings
;
462 int warn_unsupported
;
465 int warn_implicit_function_declaration
;
469 void (*error_func
)(void *opaque
, const char *msg
);
470 int error_set_jmp_enabled
;
471 jmp_buf error_jmp_buf
;
474 /* tiny assembler state */
477 /* see include_stack_ptr */
478 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
480 /* see ifdef_stack_ptr */
481 int ifdef_stack
[IFDEF_STACK_SIZE
];
483 /* see cached_includes */
484 int cached_includes_hash
[CACHED_INCLUDES_HASH_SIZE
];
487 int pack_stack
[PACK_STACK_SIZE
];
491 /* The current value can be: */
492 #define VT_VALMASK 0x00ff
493 #define VT_CONST 0x00f0 /* constant in vc
494 (must be first non register value) */
495 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
496 #define VT_LOCAL 0x00f2 /* offset on stack */
497 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
498 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
499 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
500 #define VT_LVAL 0x0100 /* var is an lvalue */
501 #define VT_SYM 0x0200 /* a symbol value is added */
502 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
503 char/short stored in integer registers) */
504 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
505 dereferencing value */
506 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
507 bounding function call point is in vc */
508 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
509 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
510 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
511 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
514 #define VT_INT 0 /* integer type */
515 #define VT_BYTE 1 /* signed byte type */
516 #define VT_SHORT 2 /* short type */
517 #define VT_VOID 3 /* void type */
518 #define VT_PTR 4 /* pointer */
519 #define VT_ENUM 5 /* enum definition */
520 #define VT_FUNC 6 /* function type */
521 #define VT_STRUCT 7 /* struct/union definition */
522 #define VT_FLOAT 8 /* IEEE float */
523 #define VT_DOUBLE 9 /* IEEE double */
524 #define VT_LDOUBLE 10 /* IEEE long double */
525 #define VT_BOOL 11 /* ISOC99 boolean type */
526 #define VT_LLONG 12 /* 64 bit integer */
527 #define VT_LONG 13 /* long integer (NEVER USED as type, only
529 #define VT_BTYPE 0x000f /* mask for basic type */
530 #define VT_UNSIGNED 0x0010 /* unsigned type */
531 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
532 #define VT_BITFIELD 0x0040 /* bitfield modifier */
533 #define VT_CONSTANT 0x0800 /* const modifier */
534 #define VT_VOLATILE 0x1000 /* volatile modifier */
535 #define VT_SIGNED 0x2000 /* signed type */
538 #define VT_EXTERN 0x00000080 /* extern definition */
539 #define VT_STATIC 0x00000100 /* static variable */
540 #define VT_TYPEDEF 0x00000200 /* typedef definition */
541 #define VT_INLINE 0x00000400 /* inline definition */
543 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
545 /* type mask (except storage) */
546 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
547 #define VT_TYPE (~(VT_STORAGE))
551 /* warning: the following compare tokens depend on i386 asm code */
563 #define TOK_LAND 0xa0
567 #define TOK_MID 0xa3 /* inc/dec, to void constant */
569 #define TOK_UDIV 0xb0 /* unsigned division */
570 #define TOK_UMOD 0xb1 /* unsigned modulo */
571 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
572 #define TOK_CINT 0xb3 /* number in tokc */
573 #define TOK_CCHAR 0xb4 /* char constant in tokc */
574 #define TOK_STR 0xb5 /* pointer to string in tokc */
575 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
576 #define TOK_LCHAR 0xb7
577 #define TOK_LSTR 0xb8
578 #define TOK_CFLOAT 0xb9 /* float constant */
579 #define TOK_LINENUM 0xba /* line number info */
580 #define TOK_CDOUBLE 0xc0 /* double constant */
581 #define TOK_CLDOUBLE 0xc1 /* long double constant */
582 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
583 #define TOK_ADDC1 0xc3 /* add with carry generation */
584 #define TOK_ADDC2 0xc4 /* add with carry use */
585 #define TOK_SUBC1 0xc5 /* add with carry generation */
586 #define TOK_SUBC2 0xc6 /* add with carry use */
587 #define TOK_CUINT 0xc8 /* unsigned int constant */
588 #define TOK_CLLONG 0xc9 /* long long constant */
589 #define TOK_CULLONG 0xca /* unsigned long long constant */
590 #define TOK_ARROW 0xcb
591 #define TOK_DOTS 0xcc /* three dots */
592 #define TOK_SHR 0xcd /* unsigned shift right */
593 #define TOK_PPNUM 0xce /* preprocessor number */
595 #define TOK_SHL 0x01 /* shift left */
596 #define TOK_SAR 0x02 /* signed shift right */
598 /* assignement operators : normal operator or 0x80 */
599 #define TOK_A_MOD 0xa5
600 #define TOK_A_AND 0xa6
601 #define TOK_A_MUL 0xaa
602 #define TOK_A_ADD 0xab
603 #define TOK_A_SUB 0xad
604 #define TOK_A_DIV 0xaf
605 #define TOK_A_XOR 0xde
606 #define TOK_A_OR 0xfc
607 #define TOK_A_SHL 0x81
608 #define TOK_A_SAR 0x82
611 #define offsetof(type, field) ((size_t) &((type *)0)->field)
615 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
618 /* WARNING: the content of this string encodes token numbers */
619 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";
621 #define TOK_EOF (-1) /* end of file */
622 #define TOK_LINEFEED 10 /* line feed */
624 /* all identificators and strings have token above that */
625 #define TOK_IDENT 256
627 /* only used for i386 asm opcodes definitions */
628 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
631 DEF(TOK_ASM_ ## x ## b, #x "b") \
632 DEF(TOK_ASM_ ## x ## w, #x "w") \
633 DEF(TOK_ASM_ ## x ## l, #x "l") \
634 DEF(TOK_ASM_ ## x, #x)
637 DEF(TOK_ASM_ ## x ## w, #x "w") \
638 DEF(TOK_ASM_ ## x ## l, #x "l") \
639 DEF(TOK_ASM_ ## x, #x)
642 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
643 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
644 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
645 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
648 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
649 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
652 #define DEF_ASMTEST(x) \
684 #define TOK_ASM_int TOK_INT
687 TOK_LAST
= TOK_IDENT
- 1,
688 #define DEF(id, str) id,
693 static const char tcc_keywords
[] =
694 #define DEF(id, str) str "\0"
699 #define TOK_UIDENT TOK_DEFINE
702 #define snprintf _snprintf
703 #define vsnprintf _vsnprintf
706 #if defined(WIN32) || defined(TCC_UCLIBC) || defined(__FreeBSD__)
707 /* currently incorrect */
708 long double strtold(const char *nptr
, char **endptr
)
710 return (long double)strtod(nptr
, endptr
);
712 float strtof(const char *nptr
, char **endptr
)
714 return (float)strtod(nptr
, endptr
);
717 /* XXX: need to define this to use them in non ISOC99 context */
718 extern float strtof (const char *__nptr
, char **__endptr
);
719 extern long double strtold (const char *__nptr
, char **__endptr
);
722 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
723 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
724 static const char *tcc_basename(const char *name
);
726 static void next(void);
727 static void next_nomacro(void);
728 static void parse_expr_type(CType
*type
);
729 static void expr_type(CType
*type
);
730 static void unary_type(CType
*type
);
731 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
732 int case_reg
, int is_expr
);
733 static int expr_const(void);
734 static void expr_eq(void);
735 static void gexpr(void);
736 static void gen_inline_functions(void);
737 static void decl(int l
);
738 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
739 int first
, int size_only
);
740 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
741 int has_init
, int v
, int scope
);
743 void gv2(int rc1
, int rc2
);
744 void move_reg(int r
, int s
);
745 void save_regs(int n
);
746 void save_reg(int r
);
751 int get_reg_ex(int rc
,int rc2
);
753 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
754 const int *macro_str
, int can_read_stream
);
756 void force_charshort_cast(int t
);
757 static void gen_cast(CType
*type
);
759 static Sym
*sym_find(int v
);
760 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
763 static int type_size(CType
*type
, int *a
);
764 static inline CType
*pointed_type(CType
*type
);
765 static int pointed_size(CType
*type
);
766 static int lvalue_type(int t
);
767 static int parse_btype(CType
*type
, AttributeDef
*ad
);
768 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
769 static int is_compatible_types(CType
*type1
, CType
*type2
);
771 int ieee_finite(double d
);
772 void error(const char *fmt
, ...);
776 void lexpand_nr(void);
777 static void vpush_global_sym(CType
*type
, int v
);
778 void vset(CType
*type
, int r
, int v
);
779 void type_to_str(char *buf
, int buf_size
,
780 CType
*type
, const char *varstr
);
781 char *get_tok_str(int v
, CValue
*cv
);
782 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
783 unsigned long offset
, unsigned long size
);
784 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
786 /* section generation */
787 static void section_realloc(Section
*sec
, unsigned long new_size
);
788 static void *section_ptr_add(Section
*sec
, unsigned long size
);
789 static void put_extern_sym(Sym
*sym
, Section
*section
,
790 unsigned long value
, unsigned long size
);
791 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
792 static int put_elf_str(Section
*s
, const char *sym
);
793 static int put_elf_sym(Section
*s
,
794 unsigned long value
, unsigned long size
,
795 int info
, int other
, int shndx
, const char *name
);
796 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
797 int info
, int other
, int sh_num
, const char *name
);
798 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
799 int type
, int symbol
);
800 static void put_stabs(const char *str
, int type
, int other
, int desc
,
801 unsigned long value
);
802 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
803 unsigned long value
, Section
*sec
, int sym_index
);
804 static void put_stabn(int type
, int other
, int desc
, int value
);
805 static void put_stabd(int type
, int other
, int desc
);
806 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
808 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
809 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
810 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
813 int tcc_output_coff(TCCState
*s1
, FILE *f
);
816 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
);
817 int pe_load_def_file(struct TCCState
*s1
, FILE *fp
);
818 void pe_setup_paths(struct TCCState
*s1
, int *p_output_type
, const char **p_outfile
, char *first_file
);
819 unsigned long pe_add_runtime(struct TCCState
*s1
);
820 int tcc_output_pe(struct TCCState
*s1
, const char *filename
);
824 #ifdef CONFIG_TCC_ASM
826 typedef struct ExprValue
{
831 #define MAX_ASM_OPERANDS 30
833 typedef struct ASMOperand
{
834 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
836 char asm_str
[16]; /* computed asm string for operand */
837 SValue
*vt
; /* C value of the expression */
838 int ref_index
; /* if >= 0, gives reference to a output constraint */
839 int input_index
; /* if >= 0, gives reference to an input constraint */
840 int priority
; /* priority, used to assign registers */
841 int reg
; /* if >= 0, register number used for this operand */
842 int is_llong
; /* true if double register value */
843 int is_memory
; /* true if memory operand */
844 int is_rw
; /* for '+' modifier */
847 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
848 static int asm_int_expr(TCCState
*s1
);
849 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
850 const char *name
, const char **pp
);
852 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
856 static void asm_instr(void);
857 static void asm_global_instr(void);
859 /* true if float/double/long double type */
860 static inline int is_float(int t
)
864 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
867 #ifdef TCC_TARGET_I386
868 #include "i386-gen.c"
871 #ifdef TCC_TARGET_ARM
875 #ifdef TCC_TARGET_C67
879 #ifdef CONFIG_TCC_STATIC
881 #define RTLD_LAZY 0x001
882 #define RTLD_NOW 0x002
883 #define RTLD_GLOBAL 0x100
884 #define RTLD_DEFAULT NULL
886 /* dummy function for profiling */
887 void *dlopen(const char *filename
, int flag
)
892 const char *dlerror(void)
897 typedef struct TCCSyms
{
902 #define TCCSYM(a) { #a, &a, },
904 /* add the symbol you want here if no dynamic linking is done */
905 static TCCSyms tcc_syms
[] = {
906 #if !defined(CONFIG_TCCBOOT)
915 void *resolve_sym(TCCState
*s1
, const char *symbol
, int type
)
919 while (p
->str
!= NULL
) {
920 if (!strcmp(p
->str
, symbol
))
927 #elif !defined(WIN32)
931 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
)
933 return dlsym(RTLD_DEFAULT
, sym
);
938 /********************************************************/
940 /* we use our own 'finite' function to avoid potential problems with
941 non standard math libs */
942 /* XXX: endianness dependent */
943 int ieee_finite(double d
)
946 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
949 /* copy a string and truncate it. */
950 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
957 q_end
= buf
+ buf_size
- 1;
969 /* strcat and truncate. */
970 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
975 pstrcpy(buf
+ len
, buf_size
- len
, s
);
979 static int strstart(const char *str
, const char *val
, const char **ptr
)
995 /* memory management */
1001 static inline void tcc_free(void *ptr
)
1004 mem_cur_size
-= malloc_usable_size(ptr
);
1009 static void *tcc_malloc(unsigned long size
)
1014 error("memory full");
1016 mem_cur_size
+= malloc_usable_size(ptr
);
1017 if (mem_cur_size
> mem_max_size
)
1018 mem_max_size
= mem_cur_size
;
1023 static void *tcc_mallocz(unsigned long size
)
1026 ptr
= tcc_malloc(size
);
1027 memset(ptr
, 0, size
);
1031 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
1035 mem_cur_size
-= malloc_usable_size(ptr
);
1037 ptr1
= realloc(ptr
, size
);
1039 /* NOTE: count not correct if alloc error, but not critical */
1040 mem_cur_size
+= malloc_usable_size(ptr1
);
1041 if (mem_cur_size
> mem_max_size
)
1042 mem_max_size
= mem_cur_size
;
1047 static char *tcc_strdup(const char *str
)
1050 ptr
= tcc_malloc(strlen(str
) + 1);
1055 #define free(p) use_tcc_free(p)
1056 #define malloc(s) use_tcc_malloc(s)
1057 #define realloc(p, s) use_tcc_realloc(p, s)
1059 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
1066 /* every power of two we double array size */
1067 if ((nb
& (nb
- 1)) == 0) {
1072 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
1074 error("memory full");
1081 /* symbol allocator */
1082 static Sym
*__sym_malloc(void)
1084 Sym
*sym_pool
, *sym
, *last_sym
;
1087 sym_pool
= tcc_malloc(SYM_POOL_NB
* sizeof(Sym
));
1089 last_sym
= sym_free_first
;
1091 for(i
= 0; i
< SYM_POOL_NB
; i
++) {
1092 sym
->next
= last_sym
;
1096 sym_free_first
= last_sym
;
1100 static inline Sym
*sym_malloc(void)
1103 sym
= sym_free_first
;
1105 sym
= __sym_malloc();
1106 sym_free_first
= sym
->next
;
1110 static inline void sym_free(Sym
*sym
)
1112 sym
->next
= sym_free_first
;
1113 sym_free_first
= sym
;
1116 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
1120 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
1121 strcpy(sec
->name
, name
);
1122 sec
->sh_type
= sh_type
;
1123 sec
->sh_flags
= sh_flags
;
1130 sec
->sh_addralign
= 4;
1133 sec
->sh_addralign
= 1;
1136 sec
->sh_addralign
= 32; /* default conservative alignment */
1140 /* only add section if not private */
1141 if (!(sh_flags
& SHF_PRIVATE
)) {
1142 sec
->sh_num
= s1
->nb_sections
;
1143 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
1148 static void free_section(Section
*s
)
1154 /* realloc section and set its content to zero */
1155 static void section_realloc(Section
*sec
, unsigned long new_size
)
1158 unsigned char *data
;
1160 size
= sec
->data_allocated
;
1163 while (size
< new_size
)
1165 data
= tcc_realloc(sec
->data
, size
);
1167 error("memory full");
1168 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1170 sec
->data_allocated
= size
;
1173 /* reserve at least 'size' bytes in section 'sec' from
1174 sec->data_offset. */
1175 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1177 unsigned long offset
, offset1
;
1179 offset
= sec
->data_offset
;
1180 offset1
= offset
+ size
;
1181 if (offset1
> sec
->data_allocated
)
1182 section_realloc(sec
, offset1
);
1183 sec
->data_offset
= offset1
;
1184 return sec
->data
+ offset
;
1187 /* return a reference to a section, and create it if it does not
1189 Section
*find_section(TCCState
*s1
, const char *name
)
1193 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1194 sec
= s1
->sections
[i
];
1195 if (!strcmp(name
, sec
->name
))
1198 /* sections are created as PROGBITS */
1199 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1202 #define SECTION_ABS ((void *)1)
1204 /* update sym->c so that it points to an external symbol in section
1205 'section' with value 'value' */
1206 static void put_extern_sym(Sym
*sym
, Section
*section
,
1207 unsigned long value
, unsigned long size
)
1209 int sym_type
, sym_bind
, sh_num
, info
;
1213 if (section
== NULL
)
1215 else if (section
== SECTION_ABS
)
1218 sh_num
= section
->sh_num
;
1220 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
)
1221 sym_type
= STT_FUNC
;
1223 sym_type
= STT_OBJECT
;
1224 if (sym
->type
.t
& VT_STATIC
)
1225 sym_bind
= STB_LOCAL
;
1227 sym_bind
= STB_GLOBAL
;
1229 name
= get_tok_str(sym
->v
, NULL
);
1230 #ifdef CONFIG_TCC_BCHECK
1231 if (do_bounds_check
) {
1234 /* XXX: avoid doing that for statics ? */
1235 /* if bound checking is activated, we change some function
1236 names by adding the "__bound" prefix */
1239 /* XXX: we rely only on malloc hooks */
1251 strcpy(buf
, "__bound_");
1258 info
= ELF32_ST_INFO(sym_bind
, sym_type
);
1259 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, 0, sh_num
, name
);
1261 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
1262 esym
->st_value
= value
;
1263 esym
->st_size
= size
;
1264 esym
->st_shndx
= sh_num
;
1268 /* add a new relocation entry to symbol 'sym' in section 's' */
1269 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1272 put_extern_sym(sym
, NULL
, 0, 0);
1273 /* now we can add ELF relocation info */
1274 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1277 static inline int isid(int c
)
1279 return (c
>= 'a' && c
<= 'z') ||
1280 (c
>= 'A' && c
<= 'Z') ||
1284 static inline int isnum(int c
)
1286 return c
>= '0' && c
<= '9';
1289 static inline int isoct(int c
)
1291 return c
>= '0' && c
<= '7';
1294 static inline int toup(int c
)
1296 if (c
>= 'a' && c
<= 'z')
1297 return c
- 'a' + 'A';
1302 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1306 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1309 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1313 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1317 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1324 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1325 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1326 (*f
)->filename
, (*f
)->line_num
);
1327 if (file
->line_num
> 0) {
1328 strcat_printf(buf
, sizeof(buf
),
1329 "%s:%d: ", file
->filename
, file
->line_num
);
1331 strcat_printf(buf
, sizeof(buf
),
1332 "%s: ", file
->filename
);
1335 strcat_printf(buf
, sizeof(buf
),
1339 strcat_printf(buf
, sizeof(buf
), "warning: ");
1340 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1342 if (!s1
->error_func
) {
1343 /* default case: stderr */
1344 fprintf(stderr
, "%s\n", buf
);
1346 s1
->error_func(s1
->error_opaque
, buf
);
1348 if (!is_warning
|| s1
->warn_error
)
1353 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1354 void (*error_func
)(void *opaque
, const char *msg
))
1356 s
->error_opaque
= error_opaque
;
1357 s
->error_func
= error_func
;
1361 /* error without aborting current compilation */
1362 void error_noabort(const char *fmt
, ...)
1364 TCCState
*s1
= tcc_state
;
1368 error1(s1
, 0, fmt
, ap
);
1372 void error(const char *fmt
, ...)
1374 TCCState
*s1
= tcc_state
;
1378 error1(s1
, 0, fmt
, ap
);
1380 /* better than nothing: in some cases, we accept to handle errors */
1381 if (s1
->error_set_jmp_enabled
) {
1382 longjmp(s1
->error_jmp_buf
, 1);
1384 /* XXX: eliminate this someday */
1389 void expect(const char *msg
)
1391 error("%s expected", msg
);
1394 void warning(const char *fmt
, ...)
1396 TCCState
*s1
= tcc_state
;
1403 error1(s1
, 1, fmt
, ap
);
1410 error("'%c' expected", c
);
1414 static void test_lvalue(void)
1416 if (!(vtop
->r
& VT_LVAL
))
1420 /* allocate a new token */
1421 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1423 TokenSym
*ts
, **ptable
;
1426 if (tok_ident
>= SYM_FIRST_ANOM
)
1427 error("memory full");
1429 /* expand token table if needed */
1430 i
= tok_ident
- TOK_IDENT
;
1431 if ((i
% TOK_ALLOC_INCR
) == 0) {
1432 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1434 error("memory full");
1435 table_ident
= ptable
;
1438 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1439 table_ident
[i
] = ts
;
1440 ts
->tok
= tok_ident
++;
1441 ts
->sym_define
= NULL
;
1442 ts
->sym_label
= NULL
;
1443 ts
->sym_struct
= NULL
;
1444 ts
->sym_identifier
= NULL
;
1446 ts
->hash_next
= NULL
;
1447 memcpy(ts
->str
, str
, len
);
1448 ts
->str
[len
] = '\0';
1453 #define TOK_HASH_INIT 1
1454 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1456 /* find a token and add it if not found */
1457 static TokenSym
*tok_alloc(const char *str
, int len
)
1459 TokenSym
*ts
, **pts
;
1465 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1466 h
&= (TOK_HASH_SIZE
- 1);
1468 pts
= &hash_ident
[h
];
1473 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1475 pts
= &(ts
->hash_next
);
1477 return tok_alloc_new(pts
, str
, len
);
1480 /* CString handling */
1482 static void cstr_realloc(CString
*cstr
, int new_size
)
1487 size
= cstr
->size_allocated
;
1489 size
= 8; /* no need to allocate a too small first string */
1490 while (size
< new_size
)
1492 data
= tcc_realloc(cstr
->data_allocated
, size
);
1494 error("memory full");
1495 cstr
->data_allocated
= data
;
1496 cstr
->size_allocated
= size
;
1501 static inline void cstr_ccat(CString
*cstr
, int ch
)
1504 size
= cstr
->size
+ 1;
1505 if (size
> cstr
->size_allocated
)
1506 cstr_realloc(cstr
, size
);
1507 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1511 static void cstr_cat(CString
*cstr
, const char *str
)
1523 /* add a wide char */
1524 static void cstr_wccat(CString
*cstr
, int ch
)
1527 size
= cstr
->size
+ sizeof(int);
1528 if (size
> cstr
->size_allocated
)
1529 cstr_realloc(cstr
, size
);
1530 *(int *)(((unsigned char *)cstr
->data
) + size
- sizeof(int)) = ch
;
1534 static void cstr_new(CString
*cstr
)
1536 memset(cstr
, 0, sizeof(CString
));
1539 /* free string and reset it to NULL */
1540 static void cstr_free(CString
*cstr
)
1542 tcc_free(cstr
->data_allocated
);
1546 #define cstr_reset(cstr) cstr_free(cstr)
1548 /* XXX: unicode ? */
1549 static void add_char(CString
*cstr
, int c
)
1551 if (c
== '\'' || c
== '\"' || c
== '\\') {
1552 /* XXX: could be more precise if char or string */
1553 cstr_ccat(cstr
, '\\');
1555 if (c
>= 32 && c
<= 126) {
1558 cstr_ccat(cstr
, '\\');
1560 cstr_ccat(cstr
, 'n');
1562 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1563 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1564 cstr_ccat(cstr
, '0' + (c
& 7));
1569 /* XXX: buffer overflow */
1570 /* XXX: float tokens */
1571 char *get_tok_str(int v
, CValue
*cv
)
1573 static char buf
[STRING_MAX_SIZE
+ 1];
1574 static CString cstr_buf
;
1580 /* NOTE: to go faster, we give a fixed buffer for small strings */
1581 cstr_reset(&cstr_buf
);
1582 cstr_buf
.data
= buf
;
1583 cstr_buf
.size_allocated
= sizeof(buf
);
1589 /* XXX: not quite exact, but only useful for testing */
1590 sprintf(p
, "%u", cv
->ui
);
1594 /* XXX: not quite exact, but only useful for testing */
1595 sprintf(p
, "%Lu", cv
->ull
);
1599 cstr_ccat(&cstr_buf
, '\'');
1600 add_char(&cstr_buf
, cv
->i
);
1601 cstr_ccat(&cstr_buf
, '\'');
1602 cstr_ccat(&cstr_buf
, '\0');
1606 len
= cstr
->size
- 1;
1608 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1609 cstr_ccat(&cstr_buf
, '\0');
1614 cstr_ccat(&cstr_buf
, '\"');
1616 len
= cstr
->size
- 1;
1618 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1620 len
= (cstr
->size
/ sizeof(int)) - 1;
1622 add_char(&cstr_buf
, ((int *)cstr
->data
)[i
]);
1624 cstr_ccat(&cstr_buf
, '\"');
1625 cstr_ccat(&cstr_buf
, '\0');
1634 return strcpy(p
, "<<=");
1636 return strcpy(p
, ">>=");
1638 if (v
< TOK_IDENT
) {
1639 /* search in two bytes table */
1653 } else if (v
< tok_ident
) {
1654 return table_ident
[v
- TOK_IDENT
]->str
;
1655 } else if (v
>= SYM_FIRST_ANOM
) {
1656 /* special name for anonymous symbol */
1657 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1659 /* should never happen */
1664 return cstr_buf
.data
;
1667 /* push, without hashing */
1668 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, int c
)
1682 /* find a symbol and return its associated structure. 's' is the top
1683 of the symbol stack */
1684 static Sym
*sym_find2(Sym
*s
, int v
)
1694 /* structure lookup */
1695 static inline Sym
*struct_find(int v
)
1698 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1700 return table_ident
[v
]->sym_struct
;
1703 /* find an identifier */
1704 static inline Sym
*sym_find(int v
)
1707 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1709 return table_ident
[v
]->sym_identifier
;
1712 /* push a given symbol on the symbol stack */
1713 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1722 s
= sym_push2(ps
, v
, type
->t
, c
);
1723 s
->type
.ref
= type
->ref
;
1725 /* don't record fields or anonymous symbols */
1727 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1728 /* record symbol in token array */
1729 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1731 ps
= &ts
->sym_struct
;
1733 ps
= &ts
->sym_identifier
;
1740 /* push a global identifier */
1741 static Sym
*global_identifier_push(int v
, int t
, int c
)
1744 s
= sym_push2(&global_stack
, v
, t
, c
);
1745 /* don't record anonymous symbol */
1746 if (v
< SYM_FIRST_ANOM
) {
1747 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1748 /* modify the top most local identifier, so that
1749 sym_identifier will point to 's' when popped */
1751 ps
= &(*ps
)->prev_tok
;
1758 /* pop symbols until top reaches 'b' */
1759 static void sym_pop(Sym
**ptop
, Sym
*b
)
1769 /* remove symbol in token array */
1771 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1772 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1774 ps
= &ts
->sym_struct
;
1776 ps
= &ts
->sym_identifier
;
1787 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1792 fd
= open(filename
, O_RDONLY
| O_BINARY
);
1795 bf
= tcc_malloc(sizeof(BufferedFile
));
1801 bf
->buf_ptr
= bf
->buffer
;
1802 bf
->buf_end
= bf
->buffer
;
1803 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1804 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1806 bf
->ifndef_macro
= 0;
1807 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1808 // printf("opening '%s'\n", filename);
1812 void tcc_close(BufferedFile
*bf
)
1814 total_lines
+= bf
->line_num
;
1819 /* fill input buffer and peek next char */
1820 static int tcc_peekc_slow(BufferedFile
*bf
)
1823 /* only tries to read if really end of buffer */
1824 if (bf
->buf_ptr
>= bf
->buf_end
) {
1826 #if defined(PARSE_DEBUG)
1831 len
= read(bf
->fd
, bf
->buffer
, len
);
1838 bf
->buf_ptr
= bf
->buffer
;
1839 bf
->buf_end
= bf
->buffer
+ len
;
1840 *bf
->buf_end
= CH_EOB
;
1842 if (bf
->buf_ptr
< bf
->buf_end
) {
1843 return bf
->buf_ptr
[0];
1845 bf
->buf_ptr
= bf
->buf_end
;
1850 /* return the current character, handling end of block if necessary
1852 static int handle_eob(void)
1854 return tcc_peekc_slow(file
);
1857 /* read next char from current input file and handle end of input buffer */
1858 static inline void inp(void)
1860 ch
= *(++(file
->buf_ptr
));
1861 /* end of buffer/file handling */
1866 /* handle '\[\r]\n' */
1867 static void handle_stray(void)
1869 while (ch
== '\\') {
1874 } else if (ch
== '\r') {
1882 error("stray '\\' in program");
1887 /* skip the stray and handle the \\n case. Output an error if
1888 incorrect char after the stray */
1889 static int handle_stray1(uint8_t *p
)
1893 if (p
>= file
->buf_end
) {
1910 /* handle just the EOB case, but not stray */
1911 #define PEEKC_EOB(c, p)\
1922 /* handle the complicated stray case */
1923 #define PEEKC(c, p)\
1928 c = handle_stray1(p);\
1933 /* input with '\[\r]\n' handling. Note that this function cannot
1934 handle other characters after '\', so you cannot call it inside
1935 strings or comments */
1936 static void minp(void)
1944 /* single line C++ comments */
1945 static uint8_t *parse_line_comment(uint8_t *p
)
1953 if (c
== '\n' || c
== CH_EOF
) {
1955 } else if (c
== '\\') {
1964 } else if (c
== '\r') {
1982 static uint8_t *parse_comment(uint8_t *p
)
1988 /* fast skip loop */
1991 if (c
== '\n' || c
== '*' || c
== '\\')
1995 if (c
== '\n' || c
== '*' || c
== '\\')
1999 /* now we can handle all the cases */
2003 } else if (c
== '*') {
2009 } else if (c
== '/') {
2010 goto end_of_comment
;
2011 } else if (c
== '\\') {
2016 /* skip '\[\r]\n', otherwise just skip the stray */
2022 } else if (c
== '\r') {
2039 /* stray, eob or eof */
2044 error("unexpected end of file in comment");
2045 } else if (c
== '\\') {
2057 /* space exlcuding newline */
2058 static inline int is_space(int ch
)
2060 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
2063 static inline void skip_spaces(void)
2065 while (is_space(ch
))
2069 /* parse a string without interpreting escapes */
2070 static uint8_t *parse_pp_string(uint8_t *p
,
2071 int sep
, CString
*str
)
2079 } else if (c
== '\\') {
2084 unterminated_string
:
2085 /* XXX: indicate line number of start of string */
2086 error("missing terminating %c character", sep
);
2087 } else if (c
== '\\') {
2088 /* escape : just skip \[\r]\n */
2093 } else if (c
== '\r') {
2096 expect("'\n' after '\r'");
2099 } else if (c
== CH_EOF
) {
2100 goto unterminated_string
;
2103 cstr_ccat(str
, '\\');
2109 } else if (c
== '\n') {
2112 } else if (c
== '\r') {
2116 cstr_ccat(str
, '\r');
2132 /* skip block of text until #else, #elif or #endif. skip also pairs of
2134 void preprocess_skip(void)
2136 int a
, start_of_line
, c
;
2163 } else if (c
== '\\') {
2164 /* XXX: incorrect: should not give an error */
2165 ch
= file
->buf_ptr
[0];
2173 p
= parse_pp_string(p
, c
, NULL
);
2182 p
= parse_comment(p
);
2183 } else if (ch
== '/') {
2184 p
= parse_line_comment(p
);
2190 if (start_of_line
) {
2195 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2197 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2199 else if (tok
== TOK_ENDIF
)
2213 /* ParseState handling */
2215 /* XXX: currently, no include file info is stored. Thus, we cannot display
2216 accurate messages if the function or data definition spans multiple
2219 /* save current parse state in 's' */
2220 void save_parse_state(ParseState
*s
)
2222 s
->line_num
= file
->line_num
;
2223 s
->macro_ptr
= macro_ptr
;
2228 /* restore parse state from 's' */
2229 void restore_parse_state(ParseState
*s
)
2231 file
->line_num
= s
->line_num
;
2232 macro_ptr
= s
->macro_ptr
;
2237 /* return the number of additional 'ints' necessary to store the
2239 static inline int tok_ext_size(int t
)
2253 error("unsupported token");
2260 return LDOUBLE_SIZE
/ 4;
2266 /* token string handling */
2268 static inline void tok_str_new(TokenString
*s
)
2272 s
->allocated_len
= 0;
2273 s
->last_line_num
= -1;
2276 static void tok_str_free(int *str
)
2281 static int *tok_str_realloc(TokenString
*s
)
2285 if (s
->allocated_len
== 0) {
2288 len
= s
->allocated_len
* 2;
2290 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2292 error("memory full");
2293 s
->allocated_len
= len
;
2298 static void tok_str_add(TokenString
*s
, int t
)
2304 if (len
>= s
->allocated_len
)
2305 str
= tok_str_realloc(s
);
2310 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2317 /* allocate space for worst case */
2318 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2319 str
= tok_str_realloc(s
);
2328 str
[len
++] = cv
->tab
[0];
2337 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
2338 while ((len
+ nb_words
) > s
->allocated_len
)
2339 str
= tok_str_realloc(s
);
2340 cstr
= (CString
*)(str
+ len
);
2342 cstr
->size
= cv
->cstr
->size
;
2343 cstr
->data_allocated
= NULL
;
2344 cstr
->size_allocated
= cstr
->size
;
2345 memcpy((char *)cstr
+ sizeof(CString
),
2346 cv
->cstr
->data
, cstr
->size
);
2353 #if LDOUBLE_SIZE == 8
2356 str
[len
++] = cv
->tab
[0];
2357 str
[len
++] = cv
->tab
[1];
2359 #if LDOUBLE_SIZE == 12
2361 str
[len
++] = cv
->tab
[0];
2362 str
[len
++] = cv
->tab
[1];
2363 str
[len
++] = cv
->tab
[2];
2364 #elif LDOUBLE_SIZE != 8
2365 #error add long double size support
2374 /* add the current parse token in token string 's' */
2375 static void tok_str_add_tok(TokenString
*s
)
2379 /* save line number info */
2380 if (file
->line_num
!= s
->last_line_num
) {
2381 s
->last_line_num
= file
->line_num
;
2382 cval
.i
= s
->last_line_num
;
2383 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2385 tok_str_add2(s
, tok
, &tokc
);
2388 #if LDOUBLE_SIZE == 12
2389 #define LDOUBLE_GET(p, cv) \
2393 #elif LDOUBLE_SIZE == 8
2394 #define LDOUBLE_GET(p, cv) \
2398 #error add long double size support
2402 /* get a token from an integer array and increment pointer
2403 accordingly. we code it as a macro to avoid pointer aliasing. */
2404 #define TOK_GET(t, p, cv) \
2419 cv.cstr = (CString *)p; \
2420 cv.cstr->data = (char *)p + sizeof(CString);\
2421 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
2430 case TOK_CLDOUBLE: \
2431 LDOUBLE_GET(p, cv); \
2432 p += LDOUBLE_SIZE / 4; \
2439 /* defines handling */
2440 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2444 s
= sym_push2(&define_stack
, v
, macro_type
, (int)str
);
2445 s
->next
= first_arg
;
2446 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2449 /* undefined a define symbol. Its name is just set to zero */
2450 static void define_undef(Sym
*s
)
2454 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2455 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2459 static inline Sym
*define_find(int v
)
2462 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2464 return table_ident
[v
]->sym_define
;
2467 /* free define stack until top reaches 'b' */
2468 static void free_defines(Sym
*b
)
2476 /* do not free args or predefined defines */
2478 tok_str_free((int *)top
->c
);
2480 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2481 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2489 static Sym
*label_find(int v
)
2492 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2494 return table_ident
[v
]->sym_label
;
2497 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2500 s
= sym_push2(ptop
, v
, 0, 0);
2502 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2503 if (ptop
== &global_label_stack
) {
2504 /* modify the top most local identifier, so that
2505 sym_identifier will point to 's' when popped */
2507 ps
= &(*ps
)->prev_tok
;
2514 /* pop labels until element last is reached. Look if any labels are
2515 undefined. Define symbols if '&&label' was used. */
2516 static void label_pop(Sym
**ptop
, Sym
*slast
)
2519 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2521 if (s
->r
== LABEL_DECLARED
) {
2522 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2523 } else if (s
->r
== LABEL_FORWARD
) {
2524 error("label '%s' used but not defined",
2525 get_tok_str(s
->v
, NULL
));
2528 /* define corresponding symbol. A size of
2530 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2534 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2540 /* eval an expression for #if/#elif */
2541 static int expr_preprocess(void)
2547 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2548 next(); /* do macro subst */
2549 if (tok
== TOK_DEFINED
) {
2554 c
= define_find(tok
) != 0;
2559 } else if (tok
>= TOK_IDENT
) {
2560 /* if undefined macro */
2564 tok_str_add_tok(&str
);
2566 tok_str_add(&str
, -1); /* simulate end of file */
2567 tok_str_add(&str
, 0);
2568 /* now evaluate C constant expression */
2569 macro_ptr
= str
.str
;
2573 tok_str_free(str
.str
);
2577 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2578 static void tok_print(int *str
)
2584 TOK_GET(t
, str
, cval
);
2587 printf(" %s", get_tok_str(t
, &cval
));
2593 /* parse after #define */
2594 static void parse_define(void)
2596 Sym
*s
, *first
, **ps
;
2597 int v
, t
, varg
, is_vaargs
, c
;
2602 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2603 /* XXX: should check if same macro (ANSI) */
2606 /* '(' must be just after macro definition for MACRO_FUNC */
2607 c
= file
->buf_ptr
[0];
2609 c
= handle_stray1(file
->buf_ptr
);
2614 while (tok
!= ')') {
2618 if (varg
== TOK_DOTS
) {
2619 varg
= TOK___VA_ARGS__
;
2621 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2625 if (varg
< TOK_IDENT
)
2626 error("badly punctuated parameter list");
2627 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2638 /* EOF testing necessary for '-D' handling */
2639 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2640 tok_str_add2(&str
, tok
, &tokc
);
2643 tok_str_add(&str
, 0);
2645 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2648 define_push(v
, t
, str
.str
, first
);
2651 static inline int hash_cached_include(int type
, const char *filename
)
2653 const unsigned char *s
;
2657 h
= TOK_HASH_FUNC(h
, type
);
2660 h
= TOK_HASH_FUNC(h
, *s
);
2663 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
2667 /* XXX: use a token or a hash table to accelerate matching ? */
2668 static CachedInclude
*search_cached_include(TCCState
*s1
,
2669 int type
, const char *filename
)
2673 h
= hash_cached_include(type
, filename
);
2674 i
= s1
->cached_includes_hash
[h
];
2678 e
= s1
->cached_includes
[i
- 1];
2679 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2686 static inline void add_cached_include(TCCState
*s1
, int type
,
2687 const char *filename
, int ifndef_macro
)
2692 if (search_cached_include(s1
, type
, filename
))
2695 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2697 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2701 strcpy(e
->filename
, filename
);
2702 e
->ifndef_macro
= ifndef_macro
;
2703 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2704 /* add in hash table */
2705 h
= hash_cached_include(type
, filename
);
2706 e
->hash_next
= s1
->cached_includes_hash
[h
];
2707 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
2710 static void pragma_parse(TCCState
*s1
)
2715 if (tok
== TOK_pack
) {
2718 #pragma pack(1) // set
2719 #pragma pack() // reset to default
2720 #pragma pack(push,1) // push & set
2721 #pragma pack(pop) // restore previous
2724 if (tok
== TOK_ASM_pop
) {
2726 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
2728 error("out of pack stack");
2730 s1
->pack_stack_ptr
--;
2734 if (tok
== TOK_ASM_push
) {
2736 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
2738 s1
->pack_stack_ptr
++;
2741 if (tok
!= TOK_CINT
) {
2743 error("invalid pack pragma");
2746 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
2750 *s1
->pack_stack_ptr
= val
;
2756 /* is_bof is true if first non space token at beginning of file */
2757 static void preprocess(int is_bof
)
2759 TCCState
*s1
= tcc_state
;
2760 int size
, i
, c
, n
, saved_parse_flags
;
2761 char buf
[1024], *q
, *p
;
2767 saved_parse_flags
= parse_flags
;
2768 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
2769 PARSE_FLAG_LINEFEED
;
2779 s
= define_find(tok
);
2780 /* undefine symbol by putting an invalid name */
2785 case TOK_INCLUDE_NEXT
:
2786 ch
= file
->buf_ptr
[0];
2787 /* XXX: incorrect if comments : use next_nomacro with a special mode */
2792 } else if (ch
== '\"') {
2795 /* XXX: better stray handling */
2798 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
2799 if ((q
- buf
) < sizeof(buf
) - 1)
2806 /* eat all spaces and comments after include */
2807 /* XXX: slightly incorrect */
2808 while (ch1
!= '\n' && ch1
!= CH_EOF
)
2812 /* computed #include : either we have only strings or
2813 we have anything enclosed in '<>' */
2816 if (tok
== TOK_STR
) {
2817 while (tok
!= TOK_LINEFEED
) {
2818 if (tok
!= TOK_STR
) {
2820 error("'#include' expects \"FILENAME\" or <FILENAME>");
2822 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
2828 while (tok
!= TOK_LINEFEED
) {
2829 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
2833 /* check syntax and remove '<>' */
2834 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
2835 goto include_syntax
;
2836 memmove(buf
, buf
+ 1, len
- 2);
2837 buf
[len
- 2] = '\0';
2842 e
= search_cached_include(s1
, c
, buf
);
2843 if (e
&& define_find(e
->ifndef_macro
)) {
2844 /* no need to parse the include because the 'ifndef macro'
2847 printf("%s: skipping %s\n", file
->filename
, buf
);
2851 /* first search in current dir if "header.h" */
2853 p
= strrchr(file
->filename
, '/');
2855 size
= p
+ 1 - file
->filename
;
2856 if (size
> sizeof(buf1
) - 1)
2857 size
= sizeof(buf1
) - 1;
2858 memcpy(buf1
, file
->filename
, size
);
2860 pstrcat(buf1
, sizeof(buf1
), buf
);
2861 f
= tcc_open(s1
, buf1
);
2863 if (tok
== TOK_INCLUDE_NEXT
)
2869 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
2870 error("#include recursion too deep");
2871 /* now search in all the include paths */
2872 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
2873 for(i
= 0; i
< n
; i
++) {
2875 if (i
< s1
->nb_include_paths
)
2876 path
= s1
->include_paths
[i
];
2878 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
2879 pstrcpy(buf1
, sizeof(buf1
), path
);
2880 pstrcat(buf1
, sizeof(buf1
), "/");
2881 pstrcat(buf1
, sizeof(buf1
), buf
);
2882 f
= tcc_open(s1
, buf1
);
2884 if (tok
== TOK_INCLUDE_NEXT
)
2890 error("include file '%s' not found", buf
);
2894 printf("%s: including %s\n", file
->filename
, buf1
);
2897 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
2898 /* push current file in stack */
2899 /* XXX: fix current line init */
2900 *s1
->include_stack_ptr
++ = file
;
2902 /* add include file debug info */
2904 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
2906 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
2907 ch
= file
->buf_ptr
[0];
2915 c
= expr_preprocess();
2921 if (tok
< TOK_IDENT
)
2922 error("invalid argument for '#if%sdef'", c
? "n" : "");
2926 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
2928 file
->ifndef_macro
= tok
;
2931 c
= (define_find(tok
) != 0) ^ c
;
2933 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
2934 error("memory full");
2935 *s1
->ifdef_stack_ptr
++ = c
;
2938 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2939 error("#else without matching #if");
2940 if (s1
->ifdef_stack_ptr
[-1] & 2)
2941 error("#else after #else");
2942 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
2945 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2946 error("#elif without matching #if");
2947 c
= s1
->ifdef_stack_ptr
[-1];
2949 error("#elif after #else");
2950 /* last #if/#elif expression was true: we skip */
2953 c
= expr_preprocess();
2954 s1
->ifdef_stack_ptr
[-1] = c
;
2964 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
2965 error("#endif without matching #if");
2966 s1
->ifdef_stack_ptr
--;
2967 /* '#ifndef macro' was at the start of file. Now we check if
2968 an '#endif' is exactly at the end of file */
2969 if (file
->ifndef_macro
&&
2970 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
2971 file
->ifndef_macro_saved
= file
->ifndef_macro
;
2972 /* need to set to zero to avoid false matches if another
2973 #ifndef at middle of file */
2974 file
->ifndef_macro
= 0;
2975 while (tok
!= TOK_LINEFEED
)
2977 tok_flags
|= TOK_FLAG_ENDIF
;
2983 if (tok
!= TOK_CINT
)
2985 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
2987 if (tok
!= TOK_LINEFEED
) {
2990 pstrcpy(file
->filename
, sizeof(file
->filename
),
2991 (char *)tokc
.cstr
->data
);
2997 ch
= file
->buf_ptr
[0];
3000 while (ch
!= '\n' && ch
!= CH_EOF
) {
3001 if ((q
- buf
) < sizeof(buf
) - 1)
3007 error("#error %s", buf
);
3009 warning("#warning %s", buf
);
3015 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
3016 /* '!' is ignored to allow C scripts. numbers are ignored
3017 to emulate cpp behaviour */
3019 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
3020 error("invalid preprocessing directive #%s", get_tok_str(tok
, &tokc
));
3024 /* ignore other preprocess commands or #! for C scripts */
3025 while (tok
!= TOK_LINEFEED
)
3028 parse_flags
= saved_parse_flags
;
3031 /* evaluate escape codes in a string. */
3032 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
3047 case '0': case '1': case '2': case '3':
3048 case '4': case '5': case '6': case '7':
3049 /* at most three octal digits */
3054 n
= n
* 8 + c
- '0';
3058 n
= n
* 8 + c
- '0';
3063 goto add_char_nonext
;
3069 if (c
>= 'a' && c
<= 'f')
3071 else if (c
>= 'A' && c
<= 'F')
3081 goto add_char_nonext
;
3105 goto invalid_escape
;
3115 if (c
>= '!' && c
<= '~')
3116 warning("unknown escape sequence: \'\\%c\'", c
);
3118 warning("unknown escape sequence: \'\\x%x\'", c
);
3125 cstr_ccat(outstr
, c
);
3127 cstr_wccat(outstr
, c
);
3129 /* add a trailing '\0' */
3131 cstr_ccat(outstr
, '\0');
3133 cstr_wccat(outstr
, '\0');
3136 /* we use 64 bit numbers */
3139 /* bn = (bn << shift) | or_val */
3140 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
3144 for(i
=0;i
<BN_SIZE
;i
++) {
3146 bn
[i
] = (v
<< shift
) | or_val
;
3147 or_val
= v
>> (32 - shift
);
3151 void bn_zero(unsigned int *bn
)
3154 for(i
=0;i
<BN_SIZE
;i
++) {
3159 /* parse number in null terminated string 'p' and return it in the
3161 void parse_number(const char *p
)
3163 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
3165 unsigned int bn
[BN_SIZE
];
3176 goto float_frac_parse
;
3177 } else if (t
== '0') {
3178 if (ch
== 'x' || ch
== 'X') {
3182 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
3188 /* parse all digits. cannot check octal numbers at this stage
3189 because of floating point constants */
3191 if (ch
>= 'a' && ch
<= 'f')
3193 else if (ch
>= 'A' && ch
<= 'F')
3201 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
3203 error("number too long");
3209 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
3210 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
3212 /* NOTE: strtox should support that for hexa numbers, but
3213 non ISOC99 libcs do not support it, so we prefer to do
3215 /* hexadecimal or binary floats */
3216 /* XXX: handle overflows */
3228 } else if (t
>= 'a') {
3230 } else if (t
>= 'A') {
3235 bn_lshift(bn
, shift
, t
);
3242 if (t
>= 'a' && t
<= 'f') {
3244 } else if (t
>= 'A' && t
<= 'F') {
3246 } else if (t
>= '0' && t
<= '9') {
3252 error("invalid digit");
3253 bn_lshift(bn
, shift
, t
);
3258 if (ch
!= 'p' && ch
!= 'P')
3265 } else if (ch
== '-') {
3269 if (ch
< '0' || ch
> '9')
3270 expect("exponent digits");
3271 while (ch
>= '0' && ch
<= '9') {
3272 exp_val
= exp_val
* 10 + ch
- '0';
3275 exp_val
= exp_val
* s
;
3277 /* now we can generate the number */
3278 /* XXX: should patch directly float number */
3279 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3280 d
= ldexp(d
, exp_val
- frac_bits
);
3285 /* float : should handle overflow */
3287 } else if (t
== 'L') {
3290 /* XXX: not large enough */
3291 tokc
.ld
= (long double)d
;
3297 /* decimal floats */
3299 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3304 while (ch
>= '0' && ch
<= '9') {
3305 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3311 if (ch
== 'e' || ch
== 'E') {
3312 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3316 if (ch
== '-' || ch
== '+') {
3317 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3322 if (ch
< '0' || ch
> '9')
3323 expect("exponent digits");
3324 while (ch
>= '0' && ch
<= '9') {
3325 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3337 tokc
.f
= strtof(token_buf
, NULL
);
3338 } else if (t
== 'L') {
3341 tokc
.ld
= strtold(token_buf
, NULL
);
3344 tokc
.d
= strtod(token_buf
, NULL
);
3348 unsigned long long n
, n1
;
3351 /* integer number */
3354 if (b
== 10 && *q
== '0') {
3361 /* no need for checks except for base 10 / 8 errors */
3364 } else if (t
>= 'a') {
3366 } else if (t
>= 'A') {
3371 error("invalid digit");
3375 /* detect overflow */
3376 /* XXX: this test is not reliable */
3378 error("integer constant overflow");
3381 /* XXX: not exactly ANSI compliant */
3382 if ((n
& 0xffffffff00000000LL
) != 0) {
3387 } else if (n
> 0x7fffffff) {
3398 error("three 'l's in integer constant");
3401 if (tok
== TOK_CINT
)
3403 else if (tok
== TOK_CUINT
)
3407 } else if (t
== 'U') {
3409 error("two 'u's in integer constant");
3411 if (tok
== TOK_CINT
)
3413 else if (tok
== TOK_CLLONG
)
3420 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3428 #define PARSE2(c1, tok1, c2, tok2) \
3439 /* return next token without macro substitution */
3440 static inline void next_nomacro1(void)
3460 /* first look if it is in fact an end of buffer */
3461 if (p
>= file
->buf_end
) {
3465 if (p
>= file
->buf_end
)
3478 TCCState
*s1
= tcc_state
;
3479 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3481 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3482 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3483 /* no include left : end of file. */
3486 /* pop include file */
3488 /* test if previous '#endif' was after a #ifdef at
3490 if (tok_flags
& TOK_FLAG_ENDIF
) {
3492 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3494 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3495 file
->ifndef_macro_saved
);
3498 /* add end of include file debug info */
3500 put_stabd(N_EINCL
, 0, 0);
3502 /* pop include stack */
3504 s1
->include_stack_ptr
--;
3505 file
= *s1
->include_stack_ptr
;
3513 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3517 tok_flags
|= TOK_FLAG_BOL
;
3526 if ((tok_flags
& TOK_FLAG_BOL
) &&
3527 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3529 preprocess(tok_flags
& TOK_FLAG_BOF
);
3535 tok
= TOK_TWOSHARPS
;
3537 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
3538 p
= parse_line_comment(p
- 1);
3547 case 'a': case 'b': case 'c': case 'd':
3548 case 'e': case 'f': case 'g': case 'h':
3549 case 'i': case 'j': case 'k': case 'l':
3550 case 'm': case 'n': case 'o': case 'p':
3551 case 'q': case 'r': case 's': case 't':
3552 case 'u': case 'v': case 'w': case 'x':
3554 case 'A': case 'B': case 'C': case 'D':
3555 case 'E': case 'F': case 'G': case 'H':
3556 case 'I': case 'J': case 'K':
3557 case 'M': case 'N': case 'O': case 'P':
3558 case 'Q': case 'R': case 'S': case 'T':
3559 case 'U': case 'V': case 'W': case 'X':
3565 h
= TOK_HASH_FUNC(h
, c
);
3569 if (!isidnum_table
[c
])
3571 h
= TOK_HASH_FUNC(h
, c
);
3578 /* fast case : no stray found, so we have the full token
3579 and we have already hashed it */
3581 h
&= (TOK_HASH_SIZE
- 1);
3582 pts
= &hash_ident
[h
];
3587 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3589 pts
= &(ts
->hash_next
);
3591 ts
= tok_alloc_new(pts
, p1
, len
);
3595 cstr_reset(&tokcstr
);
3598 cstr_ccat(&tokcstr
, *p1
);
3604 while (isidnum_table
[c
]) {
3605 cstr_ccat(&tokcstr
, c
);
3608 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3614 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3616 goto parse_ident_fast
;
3619 if (c
== '\'' || c
== '\"') {
3623 cstr_reset(&tokcstr
);
3624 cstr_ccat(&tokcstr
, 'L');
3625 goto parse_ident_slow
;
3629 case '0': case '1': case '2': case '3':
3630 case '4': case '5': case '6': case '7':
3633 cstr_reset(&tokcstr
);
3634 /* after the first digit, accept digits, alpha, '.' or sign if
3635 prefixed by 'eEpP' */
3639 cstr_ccat(&tokcstr
, c
);
3641 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3642 ((c
== '+' || c
== '-') &&
3643 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3646 /* We add a trailing '\0' to ease parsing */
3647 cstr_ccat(&tokcstr
, '\0');
3648 tokc
.cstr
= &tokcstr
;
3652 /* special dot handling because it can also start a number */
3655 cstr_reset(&tokcstr
);
3656 cstr_ccat(&tokcstr
, '.');
3658 } else if (c
== '.') {
3678 /* parse the string */
3680 p
= parse_pp_string(p
, sep
, &str
);
3681 cstr_ccat(&str
, '\0');
3683 /* eval the escape (should be done as TOK_PPNUM) */
3684 cstr_reset(&tokcstr
);
3685 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3690 /* XXX: make it portable */
3694 char_size
= sizeof(int);
3695 if (tokcstr
.size
<= char_size
)
3696 error("empty character constant");
3697 if (tokcstr
.size
> 2 * char_size
)
3698 warning("multi-character character constant");
3700 tokc
.i
= *(int8_t *)tokcstr
.data
;
3703 tokc
.i
= *(int *)tokcstr
.data
;
3707 tokc
.cstr
= &tokcstr
;
3721 } else if (c
== '<') {
3739 } else if (c
== '>') {
3757 } else if (c
== '=') {
3770 } else if (c
== '=') {
3783 } else if (c
== '=') {
3796 } else if (c
== '=') {
3799 } else if (c
== '>') {
3807 PARSE2('!', '!', '=', TOK_NE
)
3808 PARSE2('=', '=', '=', TOK_EQ
)
3809 PARSE2('*', '*', '=', TOK_A_MUL
)
3810 PARSE2('%', '%', '=', TOK_A_MOD
)
3811 PARSE2('^', '^', '=', TOK_A_XOR
)
3813 /* comments or operator */
3817 p
= parse_comment(p
);
3819 } else if (c
== '/') {
3820 p
= parse_line_comment(p
);
3822 } else if (c
== '=') {
3842 case '$': /* only used in assembler */
3847 error("unrecognized character \\x%02x", c
);
3852 #if defined(PARSE_DEBUG)
3853 printf("token = %s\n", get_tok_str(tok
, &tokc
));
3857 /* return next token without macro substitution. Can read input from
3859 static void next_nomacro(void)
3865 TOK_GET(tok
, macro_ptr
, tokc
);
3866 if (tok
== TOK_LINENUM
) {
3867 file
->line_num
= tokc
.i
;
3876 /* substitute args in macro_str and return allocated string */
3877 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
3879 int *st
, last_tok
, t
, notfirst
;
3888 TOK_GET(t
, macro_str
, cval
);
3893 TOK_GET(t
, macro_str
, cval
);
3896 s
= sym_find2(args
, t
);
3903 cstr_ccat(&cstr
, ' ');
3904 TOK_GET(t
, st
, cval
);
3905 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
3908 cstr_ccat(&cstr
, '\0');
3910 printf("stringize: %s\n", (char *)cstr
.data
);
3914 tok_str_add2(&str
, TOK_STR
, &cval
);
3917 tok_str_add2(&str
, t
, &cval
);
3919 } else if (t
>= TOK_IDENT
) {
3920 s
= sym_find2(args
, t
);
3923 /* if '##' is present before or after, no arg substitution */
3924 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
3925 /* special case for var arg macros : ## eats the
3926 ',' if empty VA_ARGS variable. */
3927 /* XXX: test of the ',' is not 100%
3928 reliable. should fix it to avoid security
3930 if (gnu_ext
&& s
->type
.t
&&
3931 last_tok
== TOK_TWOSHARPS
&&
3932 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
3934 /* suppress ',' '##' */
3937 /* suppress '##' and add variable */
3945 TOK_GET(t1
, st
, cval
);
3948 tok_str_add2(&str
, t1
, &cval
);
3952 /* NOTE: the stream cannot be read when macro
3953 substituing an argument */
3954 macro_subst(&str
, nested_list
, st
, 0);
3957 tok_str_add(&str
, t
);
3960 tok_str_add2(&str
, t
, &cval
);
3964 tok_str_add(&str
, 0);
3968 static char const ab_month_name
[12][4] =
3970 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3971 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3974 /* do macro substitution of current token with macro 's' and add
3975 result to (tok_str,tok_len). 'nested_list' is the list of all
3976 macros we got inside to avoid recursing. Return non zero if no
3977 substitution needs to be done */
3978 static int macro_subst_tok(TokenString
*tok_str
,
3979 Sym
**nested_list
, Sym
*s
, int can_read_stream
)
3981 Sym
*args
, *sa
, *sa1
;
3982 int mstr_allocated
, parlevel
, *mstr
, t
, t1
;
3989 /* if symbol is a macro, prepare substitution */
3990 /* special macros */
3991 if (tok
== TOK___LINE__
) {
3992 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
3996 } else if (tok
== TOK___FILE__
) {
3997 cstrval
= file
->filename
;
3999 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
4004 tm
= localtime(&ti
);
4005 if (tok
== TOK___DATE__
) {
4006 snprintf(buf
, sizeof(buf
), "%s %2d %d",
4007 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
4009 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
4010 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
4017 cstr_cat(&cstr
, cstrval
);
4018 cstr_ccat(&cstr
, '\0');
4020 tok_str_add2(tok_str
, t1
, &cval
);
4025 if (s
->type
.t
== MACRO_FUNC
) {
4026 /* NOTE: we do not use next_nomacro to avoid eating the
4027 next token. XXX: find better solution */
4030 if (t
== 0 && can_read_stream
) {
4031 /* end of macro stream: we must look at the token
4032 after in the file */
4038 /* XXX: incorrect with comments */
4039 ch
= file
->buf_ptr
[0];
4040 while (is_space(ch
) || ch
== '\n')
4044 if (t
!= '(') /* no macro subst */
4047 /* argument macro */
4052 /* NOTE: empty args are allowed, except if no args */
4054 /* handle '()' case */
4055 if (!args
&& !sa
&& tok
== ')')
4058 error("macro '%s' used with too many args",
4059 get_tok_str(s
->v
, 0));
4062 /* NOTE: non zero sa->t indicates VA_ARGS */
4063 while ((parlevel
> 0 ||
4065 (tok
!= ',' || sa
->type
.t
))) &&
4069 else if (tok
== ')')
4071 tok_str_add2(&str
, tok
, &tokc
);
4074 tok_str_add(&str
, 0);
4075 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (int)str
.str
);
4078 /* special case for gcc var args: add an empty
4079 var arg argument if it is omitted */
4080 if (sa
&& sa
->type
.t
&& gnu_ext
)
4090 error("macro '%s' used with too few args",
4091 get_tok_str(s
->v
, 0));
4094 /* now subst each arg */
4095 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
4100 tok_str_free((int *)sa
->c
);
4106 sym_push2(nested_list
, s
->v
, 0, 0);
4107 macro_subst(tok_str
, nested_list
, mstr
, 1);
4108 /* pop nested defined symbol */
4110 *nested_list
= sa1
->prev
;
4118 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4119 return the resulting string (which must be freed). */
4120 static inline int *macro_twosharps(const int *macro_str
)
4123 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
4125 const char *p1
, *p2
;
4127 TokenString macro_str1
;
4130 start_macro_ptr
= macro_str
;
4131 /* we search the first '##' */
4133 macro_ptr1
= macro_str
;
4134 TOK_GET(t
, macro_str
, cval
);
4135 /* nothing more to do if end of string */
4138 if (*macro_str
== TOK_TWOSHARPS
)
4142 /* we saw '##', so we need more processing to handle it */
4144 tok_str_new(¯o_str1
);
4148 /* add all tokens seen so far */
4149 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
4150 TOK_GET(t
, ptr
, cval
);
4151 tok_str_add2(¯o_str1
, t
, &cval
);
4153 saved_macro_ptr
= macro_ptr
;
4154 /* XXX: get rid of the use of macro_ptr here */
4155 macro_ptr
= (int *)macro_str
;
4157 while (*macro_ptr
== TOK_TWOSHARPS
) {
4159 macro_ptr1
= macro_ptr
;
4162 TOK_GET(t
, macro_ptr
, cval
);
4163 /* We concatenate the two tokens if we have an
4164 identifier or a preprocessing number */
4166 p1
= get_tok_str(tok
, &tokc
);
4167 cstr_cat(&cstr
, p1
);
4168 p2
= get_tok_str(t
, &cval
);
4169 cstr_cat(&cstr
, p2
);
4170 cstr_ccat(&cstr
, '\0');
4172 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
4173 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
4174 if (tok
== TOK_PPNUM
) {
4175 /* if number, then create a number token */
4176 /* NOTE: no need to allocate because
4177 tok_str_add2() does it */
4180 /* if identifier, we must do a test to
4181 validate we have a correct identifier */
4182 if (t
== TOK_PPNUM
) {
4192 if (!isnum(c
) && !isid(c
))
4196 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
4197 tok
= ts
->tok
; /* modify current token */
4200 const char *str
= cstr
.data
;
4201 const unsigned char *q
;
4203 /* we look for a valid token */
4204 /* XXX: do more extensive checks */
4205 if (!strcmp(str
, ">>=")) {
4207 } else if (!strcmp(str
, "<<=")) {
4209 } else if (strlen(str
) == 2) {
4210 /* search in two bytes table */
4215 if (q
[0] == str
[0] && q
[1] == str
[1])
4222 /* NOTE: because get_tok_str use a static buffer,
4225 p1
= get_tok_str(tok
, &tokc
);
4226 cstr_cat(&cstr
, p1
);
4227 cstr_ccat(&cstr
, '\0');
4228 p2
= get_tok_str(t
, &cval
);
4229 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
4230 /* cannot merge tokens: just add them separately */
4231 tok_str_add2(¯o_str1
, tok
, &tokc
);
4232 /* XXX: free associated memory ? */
4239 tok_str_add2(¯o_str1
, tok
, &tokc
);
4244 macro_ptr
= (int *)saved_macro_ptr
;
4246 tok_str_add(¯o_str1
, 0);
4247 return macro_str1
.str
;
4251 /* do macro substitution of macro_str and add result to
4252 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4253 inside to avoid recursing. */
4254 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
4255 const int *macro_str
, int can_read_stream
)
4258 int *saved_macro_ptr
, *macro_str1
;
4263 /* first scan for '##' operator handling */
4265 macro_str1
= macro_twosharps(ptr
);
4269 /* NOTE: ptr == NULL can only happen if tokens are read from
4270 file stream due to a macro function call */
4273 TOK_GET(t
, ptr
, cval
);
4278 /* if nested substitution, do nothing */
4279 if (sym_find2(*nested_list
, t
))
4281 saved_macro_ptr
= macro_ptr
;
4282 macro_ptr
= (int *)ptr
;
4284 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
4285 ptr
= (int *)macro_ptr
;
4286 macro_ptr
= saved_macro_ptr
;
4291 tok_str_add2(tok_str
, t
, &cval
);
4295 tok_str_free(macro_str1
);
4298 /* return next token with macro substitution */
4299 static void next(void)
4301 Sym
*nested_list
, *s
;
4307 /* if not reading from macro substituted string, then try
4308 to substitute macros */
4309 if (tok
>= TOK_IDENT
&&
4310 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4311 s
= define_find(tok
);
4313 /* we have a macro: we try to substitute */
4316 if (macro_subst_tok(&str
, &nested_list
, s
, 1) == 0) {
4317 /* substitution done, NOTE: maybe empty */
4318 tok_str_add(&str
, 0);
4319 macro_ptr
= str
.str
;
4320 macro_ptr_allocated
= str
.str
;
4327 /* end of macro or end of unget buffer */
4328 if (unget_buffer_enabled
) {
4329 macro_ptr
= unget_saved_macro_ptr
;
4330 unget_buffer_enabled
= 0;
4332 /* end of macro string: free it */
4333 tok_str_free(macro_ptr_allocated
);
4340 /* convert preprocessor tokens into C tokens */
4341 if (tok
== TOK_PPNUM
&&
4342 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4343 parse_number((char *)tokc
.cstr
->data
);
4347 /* push back current token and set current token to 'last_tok'. Only
4348 identifier case handled for labels. */
4349 static inline void unget_tok(int last_tok
)
4353 unget_saved_macro_ptr
= macro_ptr
;
4354 unget_buffer_enabled
= 1;
4355 q
= unget_saved_buffer
;
4358 n
= tok_ext_size(tok
) - 1;
4361 *q
= 0; /* end of token string */
4366 void swap(int *p
, int *q
)
4374 void vsetc(CType
*type
, int r
, CValue
*vc
)
4378 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4379 error("memory full");
4380 /* cannot let cpu flags if other instruction are generated. Also
4381 avoid leaving VT_JMP anywhere except on the top of the stack
4382 because it would complicate the code generator. */
4383 if (vtop
>= vstack
) {
4384 v
= vtop
->r
& VT_VALMASK
;
4385 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4391 vtop
->r2
= VT_CONST
;
4395 /* push integer constant */
4400 vsetc(&int_type
, VT_CONST
, &cval
);
4403 /* Return a static symbol pointing to a section */
4404 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4405 unsigned long offset
, unsigned long size
)
4411 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4412 sym
->type
.ref
= type
->ref
;
4413 sym
->r
= VT_CONST
| VT_SYM
;
4414 put_extern_sym(sym
, sec
, offset
, size
);
4418 /* push a reference to a section offset by adding a dummy symbol */
4419 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4424 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4425 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4428 /* define a new external reference to a symbol 'v' of type 'u' */
4429 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4435 /* push forward reference */
4436 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4437 s
->type
.ref
= type
->ref
;
4438 s
->r
= r
| VT_CONST
| VT_SYM
;
4443 /* define a new external reference to a symbol 'v' of type 'u' */
4444 static Sym
*external_sym(int v
, CType
*type
, int r
)
4450 /* push forward reference */
4451 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4452 s
->type
.t
|= VT_EXTERN
;
4454 if (!is_compatible_types(&s
->type
, type
))
4455 error("incompatible types for redefinition of '%s'",
4456 get_tok_str(v
, NULL
));
4461 /* push a reference to global symbol v */
4462 static void vpush_global_sym(CType
*type
, int v
)
4467 sym
= external_global_sym(v
, type
, 0);
4469 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4473 void vset(CType
*type
, int r
, int v
)
4478 vsetc(type
, r
, &cval
);
4481 void vseti(int r
, int v
)
4497 void vpushv(SValue
*v
)
4499 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4500 error("memory full");
4510 /* save r to the memory stack, and mark it as being free */
4511 void save_reg(int r
)
4513 int l
, saved
, size
, align
;
4517 /* modify all stack values */
4520 for(p
=vstack
;p
<=vtop
;p
++) {
4521 if ((p
->r
& VT_VALMASK
) == r
||
4522 (p
->r2
& VT_VALMASK
) == r
) {
4523 /* must save value on stack if not already done */
4525 /* NOTE: must reload 'r' because r might be equal to r2 */
4526 r
= p
->r
& VT_VALMASK
;
4527 /* store register in the stack */
4529 if ((p
->r
& VT_LVAL
) ||
4530 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4532 size
= type_size(type
, &align
);
4533 loc
= (loc
- size
) & -align
;
4534 sv
.type
.t
= type
->t
;
4535 sv
.r
= VT_LOCAL
| VT_LVAL
;
4538 #ifdef TCC_TARGET_I386
4539 /* x86 specific: need to pop fp register ST0 if saved */
4540 if (r
== TREG_ST0
) {
4541 o(0xd9dd); /* fstp %st(1) */
4544 /* special long long case */
4545 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4552 /* mark that stack entry as being saved on the stack */
4553 if (p
->r
& VT_LVAL
) {
4554 /* also clear the bounded flag because the
4555 relocation address of the function was stored in
4557 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4559 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4567 /* find a register of class 'rc2' with at most one reference on stack.
4568 * If none, call get_reg(rc) */
4569 int get_reg_ex(int rc
, int rc2
)
4574 for(r
=0;r
<NB_REGS
;r
++) {
4575 if (reg_classes
[r
] & rc2
) {
4578 for(p
= vstack
; p
<= vtop
; p
++) {
4579 if ((p
->r
& VT_VALMASK
) == r
||
4580 (p
->r2
& VT_VALMASK
) == r
)
4590 /* find a free register of class 'rc'. If none, save one register */
4596 /* find a free register */
4597 for(r
=0;r
<NB_REGS
;r
++) {
4598 if (reg_classes
[r
] & rc
) {
4599 for(p
=vstack
;p
<=vtop
;p
++) {
4600 if ((p
->r
& VT_VALMASK
) == r
||
4601 (p
->r2
& VT_VALMASK
) == r
)
4609 /* no register left : free the first one on the stack (VERY
4610 IMPORTANT to start from the bottom to ensure that we don't
4611 spill registers used in gen_opi()) */
4612 for(p
=vstack
;p
<=vtop
;p
++) {
4613 r
= p
->r
& VT_VALMASK
;
4614 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4616 /* also look at second register (if long long) */
4617 r
= p
->r2
& VT_VALMASK
;
4618 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4624 /* Should never comes here */
4628 /* save registers up to (vtop - n) stack entry */
4629 void save_regs(int n
)
4634 for(p
= vstack
;p
<= p1
; p
++) {
4635 r
= p
->r
& VT_VALMASK
;
4642 /* move register 's' to 'r', and flush previous value of r to memory
4644 void move_reg(int r
, int s
)
4657 /* get address of vtop (vtop MUST BE an lvalue) */
4660 vtop
->r
&= ~VT_LVAL
;
4661 /* tricky: if saved lvalue, then we can go back to lvalue */
4662 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4663 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4666 #ifdef CONFIG_TCC_BCHECK
4667 /* generate lvalue bound code */
4673 vtop
->r
&= ~VT_MUSTBOUND
;
4674 /* if lvalue, then use checking code before dereferencing */
4675 if (vtop
->r
& VT_LVAL
) {
4676 /* if not VT_BOUNDED value, then make one */
4677 if (!(vtop
->r
& VT_BOUNDED
)) {
4678 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4679 /* must save type because we must set it to int to get pointer */
4681 vtop
->type
.t
= VT_INT
;
4684 gen_bounded_ptr_add();
4685 vtop
->r
|= lval_type
;
4688 /* then check for dereferencing */
4689 gen_bounded_ptr_deref();
4694 /* store vtop a register belonging to class 'rc'. lvalues are
4695 converted to values. Cannot be used if cannot be converted to
4696 register value (such as structures). */
4699 int r
, r2
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4700 unsigned long long ll
;
4702 /* NOTE: get_reg can modify vstack[] */
4703 if (vtop
->type
.t
& VT_BITFIELD
) {
4704 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4705 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4706 /* remove bit field info to avoid loops */
4707 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4708 /* generate shifts */
4709 vpushi(32 - (bit_pos
+ bit_size
));
4711 vpushi(32 - bit_size
);
4712 /* NOTE: transformed to SHR if unsigned */
4716 if (is_float(vtop
->type
.t
) &&
4717 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4720 unsigned long offset
;
4722 /* XXX: unify with initializers handling ? */
4723 /* CPUs usually cannot use float constants, so we store them
4724 generically in data segment */
4725 size
= type_size(&vtop
->type
, &align
);
4726 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
4727 data_section
->data_offset
= offset
;
4728 /* XXX: not portable yet */
4729 ptr
= section_ptr_add(data_section
, size
);
4732 ptr
[i
] = vtop
->c
.tab
[i
];
4733 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
4734 vtop
->r
|= VT_LVAL
| VT_SYM
;
4738 #ifdef CONFIG_TCC_BCHECK
4739 if (vtop
->r
& VT_MUSTBOUND
)
4743 r
= vtop
->r
& VT_VALMASK
;
4744 /* need to reload if:
4746 - lvalue (need to dereference pointer)
4747 - already a register, but not in the right class */
4748 if (r
>= VT_CONST
||
4749 (vtop
->r
& VT_LVAL
) ||
4750 !(reg_classes
[r
] & rc
) ||
4751 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
4752 !(reg_classes
[vtop
->r2
] & rc
))) {
4754 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
4755 /* two register type load : expand to two words
4757 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4760 vtop
->c
.ui
= ll
; /* first word */
4762 vtop
->r
= r
; /* save register value */
4763 vpushi(ll
>> 32); /* second word */
4764 } else if (r
>= VT_CONST
|| /* XXX: test to VT_CONST incorrect ? */
4765 (vtop
->r
& VT_LVAL
)) {
4766 /* We do not want to modifier the long long
4767 pointer here, so the safest (and less
4768 efficient) is to save all the other registers
4769 in the stack. XXX: totally inefficient. */
4771 /* load from memory */
4774 vtop
[-1].r
= r
; /* save register value */
4775 /* increment pointer to get second word */
4776 vtop
->type
.t
= VT_INT
;
4782 /* move registers */
4785 vtop
[-1].r
= r
; /* save register value */
4786 vtop
->r
= vtop
[-1].r2
;
4788 /* allocate second register */
4795 /* write second register */
4797 } else if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
4799 /* lvalue of scalar type : need to use lvalue type
4800 because of possible cast */
4803 /* compute memory access type */
4804 if (vtop
->r
& VT_LVAL_BYTE
)
4806 else if (vtop
->r
& VT_LVAL_SHORT
)
4808 if (vtop
->r
& VT_LVAL_UNSIGNED
)
4812 /* restore wanted type */
4815 /* one register type load */
4820 #ifdef TCC_TARGET_C67
4821 /* uses register pairs for doubles */
4822 if ((vtop
->type
.t
& VT_BTYPE
) == VT_DOUBLE
)
4829 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
4830 void gv2(int rc1
, int rc2
)
4834 /* generate more generic register first. But VT_JMP or VT_CMP
4835 values must be generated first in all cases to avoid possible
4837 v
= vtop
[0].r
& VT_VALMASK
;
4838 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
4843 /* test if reload is needed for first register */
4844 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
4854 /* test if reload is needed for first register */
4855 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
4861 /* expand long long on stack in two int registers */
4866 u
= vtop
->type
.t
& VT_UNSIGNED
;
4869 vtop
[0].r
= vtop
[-1].r2
;
4870 vtop
[0].r2
= VT_CONST
;
4871 vtop
[-1].r2
= VT_CONST
;
4872 vtop
[0].type
.t
= VT_INT
| u
;
4873 vtop
[-1].type
.t
= VT_INT
| u
;
4876 #ifdef TCC_TARGET_ARM
4877 /* expand long long on stack */
4878 void lexpand_nr(void)
4882 u
= vtop
->type
.t
& VT_UNSIGNED
;
4884 vtop
->r2
= VT_CONST
;
4885 vtop
->type
.t
= VT_INT
| u
;
4886 v
=vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
);
4887 if (v
== VT_CONST
) {
4888 vtop
[-1].c
.ui
= vtop
->c
.ull
;
4889 vtop
->c
.ui
= vtop
->c
.ull
>> 32;
4891 } else if (v
== (VT_LVAL
|VT_CONST
) || v
== (VT_LVAL
|VT_LOCAL
)) {
4893 vtop
->r
= vtop
[-1].r
;
4894 } else if (v
> VT_CONST
) {
4898 vtop
->r
= vtop
[-1].r2
;
4899 vtop
[-1].r2
= VT_CONST
;
4900 vtop
[-1].type
.t
= VT_INT
| u
;
4904 /* build a long long from two ints */
4907 gv2(RC_INT
, RC_INT
);
4908 vtop
[-1].r2
= vtop
[0].r
;
4909 vtop
[-1].type
.t
= t
;
4913 /* rotate n first stack elements to the bottom
4914 I1 ... In -> I2 ... In I1 [top is right]
4922 for(i
=-n
+1;i
!=0;i
++)
4923 vtop
[i
] = vtop
[i
+1];
4927 /* rotate n first stack elements to the top
4928 I1 ... In -> In I1 ... I(n-1) [top is right]
4936 for(i
= 0;i
< n
- 1; i
++)
4937 vtop
[-i
] = vtop
[-i
- 1];
4941 #ifdef TCC_TARGET_ARM
4942 /* like vrott but in other direction
4943 In ... I1 -> I(n-1) ... I1 In [top is right]
4951 for(i
= n
- 1; i
> 0; i
--)
4952 vtop
[-i
] = vtop
[-i
+ 1];
4957 /* pop stack value */
4961 v
= vtop
->r
& VT_VALMASK
;
4962 #ifdef TCC_TARGET_I386
4963 /* for x86, we need to pop the FP stack */
4964 if (v
== TREG_ST0
&& !nocode_wanted
) {
4965 o(0xd9dd); /* fstp %st(1) */
4968 if (v
== VT_JMP
|| v
== VT_JMPI
) {
4969 /* need to put correct jump if && or || without test */
4975 /* convert stack entry to register and duplicate its value in another
4983 if ((t
& VT_BTYPE
) == VT_LLONG
) {
4990 /* stack: H L L1 H1 */
4998 /* duplicate value */
5009 load(r1
, &sv
); /* move r to r1 */
5011 /* duplicates value */
5016 /* generate CPU independent (unsigned) long long operations */
5017 void gen_opl(int op
)
5019 int t
, a
, b
, op1
, c
, i
;
5026 func
= TOK___divdi3
;
5029 func
= TOK___udivdi3
;
5032 func
= TOK___moddi3
;
5035 func
= TOK___umoddi3
;
5037 /* call generic long long function */
5038 vpush_global_sym(&func_old_type
, func
);
5043 vtop
->r2
= REG_LRET
;
5056 /* stack: L1 H1 L2 H2 */
5061 vtop
[-2] = vtop
[-3];
5064 /* stack: H1 H2 L1 L2 */
5070 /* stack: H1 H2 L1 L2 ML MH */
5073 /* stack: ML MH H1 H2 L1 L2 */
5077 /* stack: ML MH H1 L2 H2 L1 */
5082 /* stack: ML MH M1 M2 */
5085 } else if (op
== '+' || op
== '-') {
5086 /* XXX: add non carry method too (for MIPS or alpha) */
5092 /* stack: H1 H2 (L1 op L2) */
5095 gen_op(op1
+ 1); /* TOK_xxxC2 */
5098 /* stack: H1 H2 (L1 op L2) */
5101 /* stack: (L1 op L2) H1 H2 */
5103 /* stack: (L1 op L2) (H1 op H2) */
5111 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
5112 t
= vtop
[-1].type
.t
;
5116 /* stack: L H shift */
5118 /* constant: simpler */
5119 /* NOTE: all comments are for SHL. the other cases are
5120 done by swaping words */
5131 if (op
!= TOK_SAR
) {
5164 /* XXX: should provide a faster fallback on x86 ? */
5167 func
= TOK___sardi3
;
5170 func
= TOK___shrdi3
;
5173 func
= TOK___shldi3
;
5179 /* compare operations */
5185 /* stack: L1 H1 L2 H2 */
5187 vtop
[-1] = vtop
[-2];
5189 /* stack: L1 L2 H1 H2 */
5192 /* when values are equal, we need to compare low words. since
5193 the jump is inverted, we invert the test too. */
5196 else if (op1
== TOK_GT
)
5198 else if (op1
== TOK_ULT
)
5200 else if (op1
== TOK_UGT
)
5205 if (op1
!= TOK_NE
) {
5209 /* generate non equal test */
5210 /* XXX: NOT PORTABLE yet */
5214 #if defined(TCC_TARGET_I386)
5215 b
= psym(0x850f, 0);
5216 #elif defined(TCC_TARGET_ARM)
5218 o(0x1A000000 | encbranch(ind
, 0, 1));
5219 #elif defined(TCC_TARGET_C67)
5220 error("not implemented");
5222 #error not supported
5226 /* compare low. Always unsigned */
5230 else if (op1
== TOK_LE
)
5232 else if (op1
== TOK_GT
)
5234 else if (op1
== TOK_GE
)
5244 /* handle integer constant optimizations and various machine
5246 void gen_opic(int op
)
5253 /* currently, we cannot do computations with forward symbols */
5254 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5255 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5259 case '+': v1
->c
.i
+= fc
; break;
5260 case '-': v1
->c
.i
-= fc
; break;
5261 case '&': v1
->c
.i
&= fc
; break;
5262 case '^': v1
->c
.i
^= fc
; break;
5263 case '|': v1
->c
.i
|= fc
; break;
5264 case '*': v1
->c
.i
*= fc
; break;
5271 /* if division by zero, generate explicit division */
5274 error("division by zero in constant");
5278 default: v1
->c
.i
/= fc
; break;
5279 case '%': v1
->c
.i
%= fc
; break;
5280 case TOK_UDIV
: v1
->c
.i
= (unsigned)v1
->c
.i
/ fc
; break;
5281 case TOK_UMOD
: v1
->c
.i
= (unsigned)v1
->c
.i
% fc
; break;
5284 case TOK_SHL
: v1
->c
.i
<<= fc
; break;
5285 case TOK_SHR
: v1
->c
.i
= (unsigned)v1
->c
.i
>> fc
; break;
5286 case TOK_SAR
: v1
->c
.i
>>= fc
; break;
5288 case TOK_ULT
: v1
->c
.i
= (unsigned)v1
->c
.i
< (unsigned)fc
; break;
5289 case TOK_UGE
: v1
->c
.i
= (unsigned)v1
->c
.i
>= (unsigned)fc
; break;
5290 case TOK_EQ
: v1
->c
.i
= v1
->c
.i
== fc
; break;
5291 case TOK_NE
: v1
->c
.i
= v1
->c
.i
!= fc
; break;
5292 case TOK_ULE
: v1
->c
.i
= (unsigned)v1
->c
.i
<= (unsigned)fc
; break;
5293 case TOK_UGT
: v1
->c
.i
= (unsigned)v1
->c
.i
> (unsigned)fc
; break;
5294 case TOK_LT
: v1
->c
.i
= v1
->c
.i
< fc
; break;
5295 case TOK_GE
: v1
->c
.i
= v1
->c
.i
>= fc
; break;
5296 case TOK_LE
: v1
->c
.i
= v1
->c
.i
<= fc
; break;
5297 case TOK_GT
: v1
->c
.i
= v1
->c
.i
> fc
; break;
5299 case TOK_LAND
: v1
->c
.i
= v1
->c
.i
&& fc
; break;
5300 case TOK_LOR
: v1
->c
.i
= v1
->c
.i
|| fc
; break;
5306 /* if commutative ops, put c2 as constant */
5307 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
5308 op
== '|' || op
== '*')) {
5313 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
5316 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
5317 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
5323 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
5324 /* try to use shifts instead of muls or divs */
5325 if (fc
> 0 && (fc
& (fc
- 1)) == 0) {
5334 else if (op
== TOK_PDIV
)
5340 } else if (c2
&& (op
== '+' || op
== '-') &&
5341 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5342 (VT_CONST
| VT_SYM
)) {
5343 /* symbol + constant case */
5350 if (!nocode_wanted
) {
5351 /* call low level op generator */
5360 /* generate a floating point operation with constant propagation */
5361 void gen_opif(int op
)
5369 /* currently, we cannot do computations with forward symbols */
5370 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5371 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5373 if (v1
->type
.t
== VT_FLOAT
) {
5376 } else if (v1
->type
.t
== VT_DOUBLE
) {
5384 /* NOTE: we only do constant propagation if finite number (not
5385 NaN or infinity) (ANSI spec) */
5386 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5390 case '+': f1
+= f2
; break;
5391 case '-': f1
-= f2
; break;
5392 case '*': f1
*= f2
; break;
5396 error("division by zero in constant");
5401 /* XXX: also handles tests ? */
5405 /* XXX: overflow test ? */
5406 if (v1
->type
.t
== VT_FLOAT
) {
5408 } else if (v1
->type
.t
== VT_DOUBLE
) {
5416 if (!nocode_wanted
) {
5424 static int pointed_size(CType
*type
)
5427 return type_size(pointed_type(type
), &align
);
5430 static inline int is_null_pointer(SValue
*p
)
5432 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5434 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5435 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5438 static inline int is_integer_btype(int bt
)
5440 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5441 bt
== VT_INT
|| bt
== VT_LLONG
);
5444 /* check types for comparison or substraction of pointers */
5445 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5447 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5450 /* null pointers are accepted for all comparisons as gcc */
5451 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5455 bt1
= type1
->t
& VT_BTYPE
;
5456 bt2
= type2
->t
& VT_BTYPE
;
5457 /* accept comparison between pointer and integer with a warning */
5458 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5459 warning("comparison between pointer and integer");
5463 /* both must be pointers or implicit function pointers */
5464 if (bt1
== VT_PTR
) {
5465 type1
= pointed_type(type1
);
5466 } else if (bt1
!= VT_FUNC
)
5467 goto invalid_operands
;
5469 if (bt2
== VT_PTR
) {
5470 type2
= pointed_type(type2
);
5471 } else if (bt2
!= VT_FUNC
) {
5473 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5475 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5476 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5480 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5481 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5482 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5483 /* gcc-like error if '-' is used */
5485 goto invalid_operands
;
5487 warning("comparison of distinct pointer types lacks a cast");
5491 /* generic gen_op: handles types problems */
5494 int u
, t1
, t2
, bt1
, bt2
, t
;
5497 t1
= vtop
[-1].type
.t
;
5498 t2
= vtop
[0].type
.t
;
5499 bt1
= t1
& VT_BTYPE
;
5500 bt2
= t2
& VT_BTYPE
;
5502 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5503 /* at least one operand is a pointer */
5504 /* relationnal op: must be both pointers */
5505 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5506 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5507 /* pointers are handled are unsigned */
5508 t
= VT_INT
| VT_UNSIGNED
;
5511 /* if both pointers, then it must be the '-' op */
5512 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5514 error("cannot use pointers here");
5515 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5516 /* XXX: check that types are compatible */
5517 u
= pointed_size(&vtop
[-1].type
);
5519 /* set to integer type */
5520 vtop
->type
.t
= VT_INT
;
5524 /* exactly one pointer : must be '+' or '-'. */
5525 if (op
!= '-' && op
!= '+')
5526 error("cannot use pointers here");
5527 /* Put pointer as first operand */
5528 if (bt2
== VT_PTR
) {
5532 type1
= vtop
[-1].type
;
5533 /* XXX: cast to int ? (long long case) */
5534 vpushi(pointed_size(&vtop
[-1].type
));
5536 #ifdef CONFIG_TCC_BCHECK
5537 /* if evaluating constant expression, no code should be
5538 generated, so no bound check */
5539 if (do_bounds_check
&& !const_wanted
) {
5540 /* if bounded pointers, we generate a special code to
5547 gen_bounded_ptr_add();
5553 /* put again type if gen_opic() swaped operands */
5556 } else if (is_float(bt1
) || is_float(bt2
)) {
5557 /* compute bigger type and do implicit casts */
5558 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5560 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5565 /* floats can only be used for a few operations */
5566 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5567 (op
< TOK_ULT
|| op
> TOK_GT
))
5568 error("invalid operands for binary operation");
5570 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5571 /* cast to biggest op */
5573 /* convert to unsigned if it does not fit in a long long */
5574 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5575 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5579 /* integer operations */
5581 /* convert to unsigned if it does not fit in an integer */
5582 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5583 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5586 /* XXX: currently, some unsigned operations are explicit, so
5587 we modify them here */
5588 if (t
& VT_UNSIGNED
) {
5595 else if (op
== TOK_LT
)
5597 else if (op
== TOK_GT
)
5599 else if (op
== TOK_LE
)
5601 else if (op
== TOK_GE
)
5608 /* special case for shifts and long long: we keep the shift as
5610 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5615 else if ((t
& VT_BTYPE
) == VT_LLONG
)
5619 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5620 /* relationnal op: the result is an int */
5621 vtop
->type
.t
= VT_INT
;
5628 /* generic itof for unsigned long long case */
5629 void gen_cvt_itof1(int t
)
5631 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
5632 (VT_LLONG
| VT_UNSIGNED
)) {
5635 vpush_global_sym(&func_old_type
, TOK___ulltof
);
5636 else if (t
== VT_DOUBLE
)
5637 vpush_global_sym(&func_old_type
, TOK___ulltod
);
5639 vpush_global_sym(&func_old_type
, TOK___ulltold
);
5649 /* generic ftoi for unsigned long long case */
5650 void gen_cvt_ftoi1(int t
)
5654 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
5655 /* not handled natively */
5656 st
= vtop
->type
.t
& VT_BTYPE
;
5658 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
5659 else if (st
== VT_DOUBLE
)
5660 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
5662 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
5667 vtop
->r2
= REG_LRET
;
5673 /* force char or short cast */
5674 void force_charshort_cast(int t
)
5678 /* XXX: add optimization if lvalue : just change type and offset */
5683 if (t
& VT_UNSIGNED
) {
5684 vpushi((1 << bits
) - 1);
5695 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
5696 static void gen_cast(CType
*type
)
5698 int sbt
, dbt
, sf
, df
, c
;
5700 /* special delayed cast for char/short */
5701 /* XXX: in some cases (multiple cascaded casts), it may still
5703 if (vtop
->r
& VT_MUSTCAST
) {
5704 vtop
->r
&= ~VT_MUSTCAST
;
5705 force_charshort_cast(vtop
->type
.t
);
5708 /* bitfields first get cast to ints */
5709 if (vtop
->type
.t
& VT_BITFIELD
) {
5713 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
5714 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
5716 if (sbt
!= dbt
&& !nocode_wanted
) {
5719 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5721 /* convert from fp to fp */
5723 /* constant case: we can do it now */
5724 /* XXX: in ISOC, cannot do it if error in convert */
5725 if (dbt
== VT_FLOAT
&& sbt
== VT_DOUBLE
)
5726 vtop
->c
.f
= (float)vtop
->c
.d
;
5727 else if (dbt
== VT_FLOAT
&& sbt
== VT_LDOUBLE
)
5728 vtop
->c
.f
= (float)vtop
->c
.ld
;
5729 else if (dbt
== VT_DOUBLE
&& sbt
== VT_FLOAT
)
5730 vtop
->c
.d
= (double)vtop
->c
.f
;
5731 else if (dbt
== VT_DOUBLE
&& sbt
== VT_LDOUBLE
)
5732 vtop
->c
.d
= (double)vtop
->c
.ld
;
5733 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_FLOAT
)
5734 vtop
->c
.ld
= (long double)vtop
->c
.f
;
5735 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_DOUBLE
)
5736 vtop
->c
.ld
= (long double)vtop
->c
.d
;
5738 /* non constant case: generate code */
5742 /* convert int to fp */
5745 case VT_LLONG
| VT_UNSIGNED
:
5747 /* XXX: add const cases for long long */
5749 case VT_INT
| VT_UNSIGNED
:
5751 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.ui
; break;
5752 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.ui
; break;
5753 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.ui
; break;
5758 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.i
; break;
5759 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.i
; break;
5760 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.i
; break;
5766 #if !defined(TCC_TARGET_ARM)
5773 /* convert fp to int */
5774 /* we handle char/short/etc... with generic code */
5775 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
5776 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
5781 case VT_LLONG
| VT_UNSIGNED
:
5783 /* XXX: add const cases for long long */
5785 case VT_INT
| VT_UNSIGNED
:
5787 case VT_FLOAT
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5788 case VT_DOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5789 case VT_LDOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5795 case VT_FLOAT
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5796 case VT_DOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5797 case VT_LDOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5805 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
5806 /* additional cast for char/short/bool... */
5810 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
5811 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
5812 /* scalar to long long */
5814 if (sbt
== (VT_INT
| VT_UNSIGNED
))
5815 vtop
->c
.ll
= vtop
->c
.ui
;
5817 vtop
->c
.ll
= vtop
->c
.i
;
5819 /* machine independent conversion */
5821 /* generate high word */
5822 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
5830 /* patch second register */
5831 vtop
[-1].r2
= vtop
->r
;
5835 } else if (dbt
== VT_BOOL
) {
5836 /* scalar to bool */
5839 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
5840 (dbt
& VT_BTYPE
) == VT_SHORT
) {
5841 force_charshort_cast(dbt
);
5842 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
5844 if (sbt
== VT_LLONG
) {
5845 /* from long long: just take low order word */
5849 /* if lvalue and single word type, nothing to do because
5850 the lvalue already contains the real type size (see
5851 VT_LVAL_xxx constants) */
5857 /* return type size. Put alignment at 'a' */
5858 static int type_size(CType
*type
, int *a
)
5863 bt
= type
->t
& VT_BTYPE
;
5864 if (bt
== VT_STRUCT
) {
5869 } else if (bt
== VT_PTR
) {
5870 if (type
->t
& VT_ARRAY
) {
5872 return type_size(&s
->type
, a
) * s
->c
;
5877 } else if (bt
== VT_LDOUBLE
) {
5879 return LDOUBLE_SIZE
;
5880 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
5881 #ifdef TCC_TARGET_I386
5887 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
5890 } else if (bt
== VT_SHORT
) {
5894 /* char, void, function, _Bool */
5900 /* return the pointed type of t */
5901 static inline CType
*pointed_type(CType
*type
)
5903 return &type
->ref
->type
;
5906 /* modify type so that its it is a pointer to type. */
5907 static void mk_pointer(CType
*type
)
5910 s
= sym_push(SYM_FIELD
, type
, 0, -1);
5911 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
5915 /* compare function types. OLD functions match any new functions */
5916 static int is_compatible_func(CType
*type1
, CType
*type2
)
5922 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5924 /* check func_call */
5927 /* XXX: not complete */
5928 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
5932 while (s1
!= NULL
) {
5935 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5945 /* return true if type1 and type2 are exactly the same (including
5948 - enums are not checked as gcc __builtin_types_compatible_p ()
5950 static int is_compatible_types(CType
*type1
, CType
*type2
)
5954 t1
= type1
->t
& VT_TYPE
;
5955 t2
= type2
->t
& VT_TYPE
;
5956 /* XXX: bitfields ? */
5959 /* test more complicated cases */
5960 bt1
= t1
& VT_BTYPE
;
5961 if (bt1
== VT_PTR
) {
5962 type1
= pointed_type(type1
);
5963 type2
= pointed_type(type2
);
5964 return is_compatible_types(type1
, type2
);
5965 } else if (bt1
== VT_STRUCT
) {
5966 return (type1
->ref
== type2
->ref
);
5967 } else if (bt1
== VT_FUNC
) {
5968 return is_compatible_func(type1
, type2
);
5974 /* print a type. If 'varstr' is not NULL, then the variable is also
5975 printed in the type */
5977 /* XXX: add array and function pointers */
5978 void type_to_str(char *buf
, int buf_size
,
5979 CType
*type
, const char *varstr
)
5986 t
= type
->t
& VT_TYPE
;
5989 if (t
& VT_CONSTANT
)
5990 pstrcat(buf
, buf_size
, "const ");
5991 if (t
& VT_VOLATILE
)
5992 pstrcat(buf
, buf_size
, "volatile ");
5993 if (t
& VT_UNSIGNED
)
5994 pstrcat(buf
, buf_size
, "unsigned ");
6024 tstr
= "long double";
6026 pstrcat(buf
, buf_size
, tstr
);
6030 if (bt
== VT_STRUCT
)
6034 pstrcat(buf
, buf_size
, tstr
);
6035 v
= type
->ref
->v
& ~SYM_STRUCT
;
6036 if (v
>= SYM_FIRST_ANOM
)
6037 pstrcat(buf
, buf_size
, "<anonymous>");
6039 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
6043 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
6044 pstrcat(buf
, buf_size
, "(");
6046 while (sa
!= NULL
) {
6047 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
6048 pstrcat(buf
, buf_size
, buf1
);
6051 pstrcat(buf
, buf_size
, ", ");
6053 pstrcat(buf
, buf_size
, ")");
6057 pstrcpy(buf1
, sizeof(buf1
), "*");
6059 pstrcat(buf1
, sizeof(buf1
), varstr
);
6060 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
6064 pstrcat(buf
, buf_size
, " ");
6065 pstrcat(buf
, buf_size
, varstr
);
6070 /* verify type compatibility to store vtop in 'dt' type, and generate
6072 static void gen_assign_cast(CType
*dt
)
6074 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
6075 char buf1
[256], buf2
[256];
6078 st
= &vtop
->type
; /* source type */
6079 dbt
= dt
->t
& VT_BTYPE
;
6080 sbt
= st
->t
& VT_BTYPE
;
6081 if (dt
->t
& VT_CONSTANT
)
6082 warning("assignment of read-only location");
6085 /* special cases for pointers */
6086 /* '0' can also be a pointer */
6087 if (is_null_pointer(vtop
))
6089 /* accept implicit pointer to integer cast with warning */
6090 if (is_integer_btype(sbt
)) {
6091 warning("assignment makes pointer from integer without a cast");
6094 type1
= pointed_type(dt
);
6095 /* a function is implicitely a function pointer */
6096 if (sbt
== VT_FUNC
) {
6097 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
6098 !is_compatible_types(pointed_type(dt
), st
))
6105 type2
= pointed_type(st
);
6106 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
6107 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
6108 /* void * can match anything */
6110 /* exact type match, except for unsigned */
6113 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6114 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6115 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
6118 /* check const and volatile */
6119 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
6120 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
6121 warning("assignment discards qualifiers from pointer target type");
6127 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
6128 warning("assignment makes integer from pointer without a cast");
6130 /* XXX: more tests */
6135 tmp_type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6136 tmp_type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6137 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
6139 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
6140 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
6141 error("cannot cast '%s' to '%s'", buf1
, buf2
);
6149 /* store vtop in lvalue pushed on stack */
6152 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
6154 ft
= vtop
[-1].type
.t
;
6155 sbt
= vtop
->type
.t
& VT_BTYPE
;
6156 dbt
= ft
& VT_BTYPE
;
6157 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
6158 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
6159 /* optimize char/short casts */
6160 delayed_cast
= VT_MUSTCAST
;
6161 vtop
->type
.t
= ft
& VT_TYPE
;
6162 /* XXX: factorize */
6163 if (ft
& VT_CONSTANT
)
6164 warning("assignment of read-only location");
6167 if (!(ft
& VT_BITFIELD
))
6168 gen_assign_cast(&vtop
[-1].type
);
6171 if (sbt
== VT_STRUCT
) {
6172 /* if structure, only generate pointer */
6173 /* structure assignment : generate memcpy */
6174 /* XXX: optimize if small size */
6175 if (!nocode_wanted
) {
6176 size
= type_size(&vtop
->type
, &align
);
6178 vpush_global_sym(&func_old_type
, TOK_memcpy
);
6182 vtop
->type
.t
= VT_INT
;
6186 vtop
->type
.t
= VT_INT
;
6198 /* leave source on stack */
6199 } else if (ft
& VT_BITFIELD
) {
6200 /* bitfield store handling */
6201 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
6202 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
6203 /* remove bit field info to avoid loops */
6204 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
6206 /* duplicate destination */
6208 vtop
[-1] = vtop
[-2];
6210 /* mask and shift source */
6211 vpushi((1 << bit_size
) - 1);
6215 /* load destination, mask and or with source */
6217 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
6223 #ifdef CONFIG_TCC_BCHECK
6224 /* bound check case */
6225 if (vtop
[-1].r
& VT_MUSTBOUND
) {
6231 if (!nocode_wanted
) {
6235 r
= gv(rc
); /* generate value */
6236 /* if lvalue was saved on stack, must read it */
6237 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
6239 t
= get_reg(RC_INT
);
6241 sv
.r
= VT_LOCAL
| VT_LVAL
;
6242 sv
.c
.ul
= vtop
[-1].c
.ul
;
6244 vtop
[-1].r
= t
| VT_LVAL
;
6247 /* two word case handling : store second register at word + 4 */
6248 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
6250 /* convert to int to increment easily */
6251 vtop
->type
.t
= VT_INT
;
6257 /* XXX: it works because r2 is spilled last ! */
6258 store(vtop
->r2
, vtop
- 1);
6262 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
6263 vtop
->r
|= delayed_cast
;
6267 /* post defines POST/PRE add. c is the token ++ or -- */
6268 void inc(int post
, int c
)
6271 vdup(); /* save lvalue */
6273 gv_dup(); /* duplicate value */
6278 vpushi(c
- TOK_MID
);
6280 vstore(); /* store value */
6282 vpop(); /* if post op, return saved value */
6285 /* Parse GNUC __attribute__ extension. Currently, the following
6286 extensions are recognized:
6287 - aligned(n) : set data/function alignment.
6288 - packed : force data alignment to 1
6289 - section(x) : generate data/code in this section.
6290 - unused : currently ignored, but may be used someday.
6291 - regparm(n) : pass function parameters in registers (i386 only)
6293 static void parse_attribute(AttributeDef
*ad
)
6297 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
6301 while (tok
!= ')') {
6302 if (tok
< TOK_IDENT
)
6303 expect("attribute name");
6311 expect("section name");
6312 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
6321 if (n
<= 0 || (n
& (n
- 1)) != 0)
6322 error("alignment must be a positive power of two");
6335 /* currently, no need to handle it because tcc does not
6336 track unused objects */
6340 /* currently, no need to handle it because tcc does not
6341 track unused objects */
6346 ad
->func_call
= FUNC_CDECL
;
6351 ad
->func_call
= FUNC_STDCALL
;
6353 #ifdef TCC_TARGET_I386
6363 ad
->func_call
= FUNC_FASTCALL1
+ n
- 1;
6371 if (tcc_state
->warn_unsupported
)
6372 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6373 /* skip parameters */
6374 /* XXX: skip parenthesis too */
6377 while (tok
!= ')' && tok
!= -1)
6392 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6393 static void struct_decl(CType
*type
, int u
)
6395 int a
, v
, size
, align
, maxalign
, c
, offset
;
6396 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
;
6401 a
= tok
; /* save decl type */
6406 /* struct already defined ? return it */
6408 expect("struct/union/enum name");
6412 error("invalid type");
6419 /* we put an undefined size for struct/union */
6420 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6421 s
->r
= 0; /* default alignment is zero as gcc */
6422 /* put struct/union/enum name in type */
6430 error("struct/union/enum already defined");
6431 /* cannot be empty */
6433 /* non empty enums are not allowed */
6434 if (a
== TOK_ENUM
) {
6438 expect("identifier");
6444 /* enum symbols have static storage */
6445 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6446 ss
->type
.t
|= VT_STATIC
;
6451 /* NOTE: we accept a trailing comma */
6461 while (tok
!= '}') {
6462 parse_btype(&btype
, &ad
);
6468 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
);
6469 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6470 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6471 error("invalid type for '%s'",
6472 get_tok_str(v
, NULL
));
6476 bit_size
= expr_const();
6477 /* XXX: handle v = 0 case for messages */
6479 error("negative width in bit-field '%s'",
6480 get_tok_str(v
, NULL
));
6481 if (v
&& bit_size
== 0)
6482 error("zero width for bit-field '%s'",
6483 get_tok_str(v
, NULL
));
6485 size
= type_size(&type1
, &align
);
6487 if (align
< ad
.aligned
)
6489 } else if (ad
.packed
) {
6491 } else if (*tcc_state
->pack_stack_ptr
) {
6492 if (align
> *tcc_state
->pack_stack_ptr
)
6493 align
= *tcc_state
->pack_stack_ptr
;
6496 if (bit_size
>= 0) {
6497 bt
= type1
.t
& VT_BTYPE
;
6503 error("bitfields must have scalar type");
6505 if (bit_size
> bsize
) {
6506 error("width of '%s' exceeds its type",
6507 get_tok_str(v
, NULL
));
6508 } else if (bit_size
== bsize
) {
6509 /* no need for bit fields */
6511 } else if (bit_size
== 0) {
6512 /* XXX: what to do if only padding in a
6514 /* zero size: means to pad */
6518 /* we do not have enough room ? */
6519 if ((bit_pos
+ bit_size
) > bsize
)
6522 /* XXX: handle LSB first */
6523 type1
.t
|= VT_BITFIELD
|
6524 (bit_pos
<< VT_STRUCT_SHIFT
) |
6525 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
6526 bit_pos
+= bit_size
;
6532 /* add new memory data only if starting
6534 if (lbit_pos
== 0) {
6535 if (a
== TOK_STRUCT
) {
6536 c
= (c
+ align
- 1) & -align
;
6544 if (align
> maxalign
)
6548 printf("add field %s offset=%d",
6549 get_tok_str(v
, NULL
), offset
);
6550 if (type1
.t
& VT_BITFIELD
) {
6551 printf(" pos=%d size=%d",
6552 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
6553 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
6557 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
6561 if (tok
== ';' || tok
== TOK_EOF
)
6568 /* store size and alignment */
6569 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
6575 /* return 0 if no type declaration. otherwise, return the basic type
6578 static int parse_btype(CType
*type
, AttributeDef
*ad
)
6580 int t
, u
, type_found
, typespec_found
;
6584 memset(ad
, 0, sizeof(AttributeDef
));
6591 /* currently, we really ignore extension */
6601 if ((t
& VT_BTYPE
) != 0)
6602 error("too many basic types");
6618 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
6619 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6620 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
6621 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
6635 if ((t
& VT_BTYPE
) == VT_LONG
) {
6636 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6643 struct_decl(&type1
, VT_ENUM
);
6646 type
->ref
= type1
.ref
;
6650 struct_decl(&type1
, VT_STRUCT
);
6653 /* type modifiers */
6706 /* GNUC attribute */
6707 case TOK_ATTRIBUTE1
:
6708 case TOK_ATTRIBUTE2
:
6709 parse_attribute(ad
);
6716 parse_expr_type(&type1
);
6722 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
6724 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
6725 type
->ref
= s
->type
.ref
;
6732 if ((t
& (VT_SIGNED
|VT_UNSIGNED
)) == (VT_SIGNED
|VT_UNSIGNED
))
6733 error("signed and unsigned modifier");
6734 if (tcc_state
->char_is_unsigned
) {
6735 if ((t
& (VT_SIGNED
|VT_UNSIGNED
|VT_BTYPE
)) == VT_BYTE
)
6740 /* long is never used as type */
6741 if ((t
& VT_BTYPE
) == VT_LONG
)
6742 t
= (t
& ~VT_BTYPE
) | VT_INT
;
6747 /* convert a function parameter type (array to pointer and function to
6748 function pointer) */
6749 static inline void convert_parameter_type(CType
*pt
)
6751 /* remove const and volatile qualifiers (XXX: const could be used
6752 to indicate a const function parameter */
6753 pt
->t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6754 /* array must be transformed to pointer according to ANSI C */
6756 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
6761 static void post_type(CType
*type
, AttributeDef
*ad
)
6764 Sym
**plast
, *s
, *first
;
6769 /* function declaration */
6774 while (tok
!= ')') {
6775 /* read param name and compute offset */
6776 if (l
!= FUNC_OLD
) {
6777 if (!parse_btype(&pt
, &ad1
)) {
6779 error("invalid type");
6786 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
6788 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6789 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
6790 error("parameter declared as void");
6797 convert_parameter_type(&pt
);
6798 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
6803 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
6810 /* if no parameters, then old type prototype */
6814 t1
= type
->t
& VT_STORAGE
;
6815 /* NOTE: const is ignored in returned type as it has a special
6816 meaning in gcc / C++ */
6817 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
6818 post_type(type
, ad
);
6819 /* we push a anonymous symbol which will contain the function prototype */
6820 s
= sym_push(SYM_FIELD
, type
, ad
->func_call
, l
);
6822 type
->t
= t1
| VT_FUNC
;
6824 } else if (tok
== '[') {
6825 /* array definition */
6831 error("invalid array size");
6834 /* parse next post type */
6835 t1
= type
->t
& VT_STORAGE
;
6836 type
->t
&= ~VT_STORAGE
;
6837 post_type(type
, ad
);
6839 /* we push a anonymous symbol which will contain the array
6841 s
= sym_push(SYM_FIELD
, type
, 0, n
);
6842 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
6847 /* Parse a type declaration (except basic type), and return the type
6848 in 'type'. 'td' is a bitmask indicating which kind of type decl is
6849 expected. 'type' should contain the basic type. 'ad' is the
6850 attribute definition of the basic type. It can be modified by
6853 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
6856 CType type1
, *type2
;
6859 while (tok
== '*') {
6867 qualifiers
|= VT_CONSTANT
;
6872 qualifiers
|= VT_VOLATILE
;
6880 type
->t
|= qualifiers
;
6883 /* XXX: clarify attribute handling */
6884 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6885 parse_attribute(ad
);
6887 /* recursive type */
6888 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
6889 type1
.t
= 0; /* XXX: same as int */
6892 /* XXX: this is not correct to modify 'ad' at this point, but
6893 the syntax is not clear */
6894 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6895 parse_attribute(ad
);
6896 type_decl(&type1
, ad
, v
, td
);
6899 /* type identifier */
6900 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
6904 if (!(td
& TYPE_ABSTRACT
))
6905 expect("identifier");
6909 post_type(type
, ad
);
6910 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6911 parse_attribute(ad
);
6914 /* append type at the end of type1 */
6927 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
6928 static int lvalue_type(int t
)
6933 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
6935 else if (bt
== VT_SHORT
)
6939 if (t
& VT_UNSIGNED
)
6940 r
|= VT_LVAL_UNSIGNED
;
6944 /* indirection with full error checking and bound check */
6945 static void indir(void)
6947 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
6949 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
6951 vtop
->type
= *pointed_type(&vtop
->type
);
6952 /* an array is never an lvalue */
6953 if (!(vtop
->type
.t
& VT_ARRAY
)) {
6954 vtop
->r
|= lvalue_type(vtop
->type
.t
);
6955 /* if bound checking, the referenced pointer must be checked */
6956 if (do_bounds_check
)
6957 vtop
->r
|= VT_MUSTBOUND
;
6961 /* pass a parameter to a function and do type checking and casting */
6962 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
6967 func_type
= func
->c
;
6968 if (func_type
== FUNC_OLD
||
6969 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
6970 /* default casting : only need to convert float to double */
6971 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
6975 } else if (arg
== NULL
) {
6976 error("too many arguments to function");
6979 type
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
6980 gen_assign_cast(&type
);
6984 /* parse an expression of the form '(type)' or '(expr)' and return its
6986 static void parse_expr_type(CType
*type
)
6992 if (parse_btype(type
, &ad
)) {
6993 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7000 static void parse_type(CType
*type
)
7005 if (!parse_btype(type
, &ad
)) {
7008 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7011 static void vpush_tokc(int t
)
7015 vsetc(&type
, VT_CONST
, &tokc
);
7018 static void unary(void)
7020 int n
, t
, align
, size
, r
;
7025 /* XXX: GCC 2.95.3 does not generate a table although it should be
7039 vpush_tokc(VT_INT
| VT_UNSIGNED
);
7043 vpush_tokc(VT_LLONG
);
7047 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
7051 vpush_tokc(VT_FLOAT
);
7055 vpush_tokc(VT_DOUBLE
);
7059 vpush_tokc(VT_LDOUBLE
);
7062 case TOK___FUNCTION__
:
7064 goto tok_identifier
;
7070 /* special function name identifier */
7071 len
= strlen(funcname
) + 1;
7072 /* generate char[len] type */
7077 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
7078 ptr
= section_ptr_add(data_section
, len
);
7079 memcpy(ptr
, funcname
, len
);
7087 /* string parsing */
7090 if (tcc_state
->warn_write_strings
)
7095 memset(&ad
, 0, sizeof(AttributeDef
));
7096 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
7101 if (parse_btype(&type
, &ad
)) {
7102 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
7104 /* check ISOC99 compound literal */
7106 /* data is allocated locally by default */
7111 /* all except arrays are lvalues */
7112 if (!(type
.t
& VT_ARRAY
))
7113 r
|= lvalue_type(type
.t
);
7114 memset(&ad
, 0, sizeof(AttributeDef
));
7115 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
7120 } else if (tok
== '{') {
7121 /* save all registers */
7123 /* statement expression : we do not accept break/continue
7124 inside as GCC does */
7125 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
7140 /* functions names must be treated as function pointers,
7141 except for unary '&' and sizeof. Since we consider that
7142 functions are not lvalues, we only have to handle it
7143 there and in function calls. */
7144 /* arrays can also be used although they are not lvalues */
7145 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
7146 !(vtop
->type
.t
& VT_ARRAY
))
7148 mk_pointer(&vtop
->type
);
7154 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
)
7155 vtop
->c
.i
= !vtop
->c
.i
;
7156 else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
7157 vtop
->c
.i
= vtop
->c
.i
^ 1;
7159 vseti(VT_JMP
, gtst(1, 0));
7169 /* in order to force cast, we add zero */
7171 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
7172 error("pointer not accepted for unary plus");
7182 parse_expr_type(&type
);
7186 size
= type_size(&type
, &align
);
7187 if (t
== TOK_SIZEOF
) {
7189 error("sizeof applied to an incomplete type");
7196 case TOK_builtin_types_compatible_p
:
7205 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7206 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7207 vpushi(is_compatible_types(&type1
, &type2
));
7210 case TOK_builtin_constant_p
:
7212 int saved_nocode_wanted
, res
;
7215 saved_nocode_wanted
= nocode_wanted
;
7218 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
7220 nocode_wanted
= saved_nocode_wanted
;
7240 goto tok_identifier
;
7242 /* allow to take the address of a label */
7243 if (tok
< TOK_UIDENT
)
7244 expect("label identifier");
7245 s
= label_find(tok
);
7247 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7249 if (s
->r
== LABEL_DECLARED
)
7250 s
->r
= LABEL_FORWARD
;
7253 s
->type
.t
= VT_VOID
;
7254 mk_pointer(&s
->type
);
7255 s
->type
.t
|= VT_STATIC
;
7257 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
7266 expect("identifier");
7270 error("'%s' undeclared", get_tok_str(t
, NULL
));
7271 /* for simple function calls, we tolerate undeclared
7272 external reference to int() function */
7273 if (tcc_state
->warn_implicit_function_declaration
)
7274 warning("implicit declaration of function '%s'",
7275 get_tok_str(t
, NULL
));
7276 s
= external_global_sym(t
, &func_old_type
, 0);
7278 if ((s
->type
.t
& (VT_STATIC
| VT_INLINE
| VT_BTYPE
)) ==
7279 (VT_STATIC
| VT_INLINE
| VT_FUNC
)) {
7280 /* if referencing an inline function, then we generate a
7281 symbol to it if not already done. It will have the
7282 effect to generate code for it at the end of the
7283 compilation unit. Inline function as always
7284 generated in the text section. */
7286 put_extern_sym(s
, text_section
, 0, 0);
7287 r
= VT_SYM
| VT_CONST
;
7291 vset(&s
->type
, r
, s
->c
);
7292 /* if forward reference, we must point to s */
7293 if (vtop
->r
& VT_SYM
) {
7300 /* post operations */
7302 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
7305 } else if (tok
== '.' || tok
== TOK_ARROW
) {
7307 if (tok
== TOK_ARROW
)
7312 /* expect pointer on structure */
7313 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
7314 expect("struct or union");
7318 while ((s
= s
->next
) != NULL
) {
7323 error("field not found");
7324 /* add field offset to pointer */
7325 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
7328 /* change type to field type, and set to lvalue */
7329 vtop
->type
= s
->type
;
7330 /* an array is never an lvalue */
7331 if (!(vtop
->type
.t
& VT_ARRAY
)) {
7332 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7333 /* if bound checking, the referenced pointer must be checked */
7334 if (do_bounds_check
)
7335 vtop
->r
|= VT_MUSTBOUND
;
7338 } else if (tok
== '[') {
7344 } else if (tok
== '(') {
7350 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7351 /* pointer test (no array accepted) */
7352 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
7353 vtop
->type
= *pointed_type(&vtop
->type
);
7354 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
7358 expect("function pointer");
7361 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
7363 /* get return type */
7366 sa
= s
->next
; /* first parameter */
7368 /* compute first implicit argument if a structure is returned */
7369 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
7370 /* get some space for the returned structure */
7371 size
= type_size(&s
->type
, &align
);
7372 loc
= (loc
- size
) & -align
;
7374 ret
.r
= VT_LOCAL
| VT_LVAL
;
7375 /* pass it as 'int' to avoid structure arg passing
7377 vseti(VT_LOCAL
, loc
);
7383 /* return in register */
7384 if (is_float(ret
.type
.t
)) {
7387 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
7396 gfunc_param_typed(s
, sa
);
7406 error("too few arguments to function");
7408 if (!nocode_wanted
) {
7409 gfunc_call(nb_args
);
7411 vtop
-= (nb_args
+ 1);
7414 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
7422 static void uneq(void)
7428 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
7429 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
7430 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
7445 static void expr_prod(void)
7450 while (tok
== '*' || tok
== '/' || tok
== '%') {
7458 static void expr_sum(void)
7463 while (tok
== '+' || tok
== '-') {
7471 static void expr_shift(void)
7476 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
7484 static void expr_cmp(void)
7489 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
7490 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
7498 static void expr_cmpeq(void)
7503 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
7511 static void expr_and(void)
7514 while (tok
== '&') {
7521 static void expr_xor(void)
7524 while (tok
== '^') {
7531 static void expr_or(void)
7534 while (tok
== '|') {
7541 /* XXX: fix this mess */
7542 static void expr_land_const(void)
7545 while (tok
== TOK_LAND
) {
7552 /* XXX: fix this mess */
7553 static void expr_lor_const(void)
7556 while (tok
== TOK_LOR
) {
7563 /* only used if non constant */
7564 static void expr_land(void)
7569 if (tok
== TOK_LAND
) {
7573 if (tok
!= TOK_LAND
) {
7583 static void expr_lor(void)
7588 if (tok
== TOK_LOR
) {
7592 if (tok
!= TOK_LOR
) {
7602 /* XXX: better constant handling */
7603 static void expr_eq(void)
7605 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
7607 CType type
, type1
, type2
;
7616 if (tok
== ':' && gnu_ext
) {
7632 if (vtop
!= vstack
) {
7633 /* needed to avoid having different registers saved in
7635 if (is_float(vtop
->type
.t
))
7642 if (tok
== ':' && gnu_ext
) {
7650 sv
= *vtop
; /* save value to handle it later */
7651 vtop
--; /* no vpop so that FP stack is not flushed */
7659 bt1
= t1
& VT_BTYPE
;
7661 bt2
= t2
& VT_BTYPE
;
7662 /* cast operands to correct type according to ISOC rules */
7663 if (is_float(bt1
) || is_float(bt2
)) {
7664 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
7665 type
.t
= VT_LDOUBLE
;
7666 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
7671 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
7672 /* cast to biggest op */
7674 /* convert to unsigned if it does not fit in a long long */
7675 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
7676 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
7677 type
.t
|= VT_UNSIGNED
;
7678 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
7679 /* XXX: test pointer compatibility */
7681 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
7682 /* XXX: test structure compatibility */
7684 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
7685 /* NOTE: as an extension, we accept void on only one side */
7688 /* integer operations */
7690 /* convert to unsigned if it does not fit in an integer */
7691 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
7692 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
7693 type
.t
|= VT_UNSIGNED
;
7696 /* now we convert second operand */
7699 if (is_float(type
.t
)) {
7701 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
7702 /* for long longs, we use fixed registers to avoid having
7703 to handle a complicated move */
7708 /* this is horrible, but we must also convert first
7712 /* put again first value and cast it */
7723 static void gexpr(void)
7734 /* parse an expression and return its type without any side effect. */
7735 static void expr_type(CType
*type
)
7737 int saved_nocode_wanted
;
7739 saved_nocode_wanted
= nocode_wanted
;
7744 nocode_wanted
= saved_nocode_wanted
;
7747 /* parse a unary expression and return its type without any side
7749 static void unary_type(CType
*type
)
7761 /* parse a constant expression and return value in vtop. */
7762 static void expr_const1(void)
7771 /* parse an integer constant and return its value. */
7772 static int expr_const(void)
7776 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
7777 expect("constant expression");
7783 /* return the label token if current token is a label, otherwise
7785 static int is_label(void)
7789 /* fast test first */
7790 if (tok
< TOK_UIDENT
)
7792 /* no need to save tokc because tok is an identifier */
7799 unget_tok(last_tok
);
7804 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
7805 int case_reg
, int is_expr
)
7810 /* generate line number info */
7812 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
7813 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
7815 last_line_num
= file
->line_num
;
7819 /* default return value is (void) */
7821 vtop
->type
.t
= VT_VOID
;
7824 if (tok
== TOK_IF
) {
7831 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7833 if (c
== TOK_ELSE
) {
7837 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7838 gsym(d
); /* patch else jmp */
7841 } else if (tok
== TOK_WHILE
) {
7849 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7853 } else if (tok
== '{') {
7857 /* record local declaration stack position */
7859 llabel
= local_label_stack
;
7860 /* handle local labels declarations */
7861 if (tok
== TOK_LABEL
) {
7864 if (tok
< TOK_UIDENT
)
7865 expect("label identifier");
7866 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
7876 while (tok
!= '}') {
7881 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7884 /* pop locally defined labels */
7885 label_pop(&local_label_stack
, llabel
);
7886 /* pop locally defined symbols */
7887 sym_pop(&local_stack
, s
);
7889 } else if (tok
== TOK_RETURN
) {
7893 gen_assign_cast(&func_vt
);
7894 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
7896 /* if returning structure, must copy it to implicit
7897 first pointer arg location */
7900 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
7903 /* copy structure value to pointer */
7905 } else if (is_float(func_vt
.t
)) {
7910 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
7913 rsym
= gjmp(rsym
); /* jmp */
7914 } else if (tok
== TOK_BREAK
) {
7917 error("cannot break");
7918 *bsym
= gjmp(*bsym
);
7921 } else if (tok
== TOK_CONTINUE
) {
7924 error("cannot continue");
7925 *csym
= gjmp(*csym
);
7928 } else if (tok
== TOK_FOR
) {
7955 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7960 if (tok
== TOK_DO
) {
7965 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7976 if (tok
== TOK_SWITCH
) {
7980 /* XXX: other types than integer */
7981 case_reg
= gv(RC_INT
);
7985 b
= gjmp(0); /* jump to first case */
7987 block(&a
, csym
, &b
, &c
, case_reg
, 0);
7988 /* if no default, jmp after switch */
7996 if (tok
== TOK_CASE
) {
8003 if (gnu_ext
&& tok
== TOK_DOTS
) {
8007 warning("empty case range");
8009 /* since a case is like a label, we must skip it with a jmp */
8016 *case_sym
= gtst(1, 0);
8019 *case_sym
= gtst(1, 0);
8023 *case_sym
= gtst(1, *case_sym
);
8028 goto block_after_label
;
8030 if (tok
== TOK_DEFAULT
) {
8036 error("too many 'default'");
8039 goto block_after_label
;
8041 if (tok
== TOK_GOTO
) {
8043 if (tok
== '*' && gnu_ext
) {
8047 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
8050 } else if (tok
>= TOK_UIDENT
) {
8051 s
= label_find(tok
);
8052 /* put forward definition if needed */
8054 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
8056 if (s
->r
== LABEL_DECLARED
)
8057 s
->r
= LABEL_FORWARD
;
8059 /* label already defined */
8060 if (s
->r
& LABEL_FORWARD
)
8061 s
->next
= (void *)gjmp((long)s
->next
);
8063 gjmp_addr((long)s
->next
);
8066 expect("label identifier");
8069 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
8077 if (s
->r
== LABEL_DEFINED
)
8078 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
8079 gsym((long)s
->next
);
8080 s
->r
= LABEL_DEFINED
;
8082 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
8084 s
->next
= (void *)ind
;
8085 /* we accept this, but it is a mistake */
8088 warning("deprecated use of label at end of compound statement");
8092 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8095 /* expression case */
8110 /* t is the array or struct type. c is the array or struct
8111 address. cur_index/cur_field is the pointer to the current
8112 value. 'size_only' is true if only size info is needed (only used
8114 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
8115 int *cur_index
, Sym
**cur_field
,
8119 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
8125 if (gnu_ext
&& (l
= is_label()) != 0)
8127 while (tok
== '[' || tok
== '.') {
8129 if (!(type
->t
& VT_ARRAY
))
8130 expect("array type");
8133 index
= expr_const();
8134 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
8135 expect("invalid index");
8136 if (tok
== TOK_DOTS
&& gnu_ext
) {
8138 index_last
= expr_const();
8139 if (index_last
< 0 ||
8140 (s
->c
>= 0 && index_last
>= s
->c
) ||
8142 expect("invalid index");
8148 *cur_index
= index_last
;
8149 type
= pointed_type(type
);
8150 elem_size
= type_size(type
, &align
);
8151 c
+= index
* elem_size
;
8152 /* NOTE: we only support ranges for last designator */
8153 nb_elems
= index_last
- index
+ 1;
8154 if (nb_elems
!= 1) {
8163 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
8164 expect("struct/union type");
8177 /* XXX: fix this mess by using explicit storage field */
8179 type1
.t
|= (type
->t
& ~VT_TYPE
);
8193 if (type
->t
& VT_ARRAY
) {
8195 type
= pointed_type(type
);
8196 c
+= index
* type_size(type
, &align
);
8200 error("too many field init");
8201 /* XXX: fix this mess by using explicit storage field */
8203 type1
.t
|= (type
->t
& ~VT_TYPE
);
8208 decl_initializer(type
, sec
, c
, 0, size_only
);
8210 /* XXX: make it more general */
8211 if (!size_only
&& nb_elems
> 1) {
8212 unsigned long c_end
;
8217 error("range init not supported yet for dynamic storage");
8218 c_end
= c
+ nb_elems
* elem_size
;
8219 if (c_end
> sec
->data_allocated
)
8220 section_realloc(sec
, c_end
);
8221 src
= sec
->data
+ c
;
8223 for(i
= 1; i
< nb_elems
; i
++) {
8225 memcpy(dst
, src
, elem_size
);
8231 #define EXPR_CONST 1
8234 /* store a value or an expression directly in global data or in local array */
8235 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
8236 int v
, int expr_type
)
8238 int saved_global_expr
, bt
, bit_pos
, bit_size
;
8240 unsigned long long bit_mask
;
8248 /* compound literals must be allocated globally in this case */
8249 saved_global_expr
= global_expr
;
8252 global_expr
= saved_global_expr
;
8253 /* NOTE: symbols are accepted */
8254 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
8255 error("initializer element is not constant");
8263 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
8266 /* XXX: not portable */
8267 /* XXX: generate error if incorrect relocation */
8268 gen_assign_cast(&dtype
);
8269 bt
= type
->t
& VT_BTYPE
;
8270 ptr
= sec
->data
+ c
;
8271 /* XXX: make code faster ? */
8272 if (!(type
->t
& VT_BITFIELD
)) {
8277 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
8278 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
8279 bit_mask
= (1LL << bit_size
) - 1;
8281 if ((vtop
->r
& VT_SYM
) &&
8287 (bt
== VT_INT
&& bit_size
!= 32)))
8288 error("initializer element is not computable at load time");
8291 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8294 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8297 *(double *)ptr
= vtop
->c
.d
;
8300 *(long double *)ptr
= vtop
->c
.ld
;
8303 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
8306 if (vtop
->r
& VT_SYM
) {
8307 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
8309 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8314 vset(&dtype
, VT_LOCAL
, c
);
8321 /* put zeros for variable based init */
8322 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
8325 /* nothing to do because globals are already set to zero */
8327 vpush_global_sym(&func_old_type
, TOK_memset
);
8335 /* 't' contains the type and storage info. 'c' is the offset of the
8336 object in section 'sec'. If 'sec' is NULL, it means stack based
8337 allocation. 'first' is true if array '{' must be read (multi
8338 dimension implicit array init handling). 'size_only' is true if
8339 size only evaluation is wanted (only for arrays). */
8340 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
8341 int first
, int size_only
)
8343 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
8344 int size1
, align1
, expr_type
;
8348 if (type
->t
& VT_ARRAY
) {
8352 t1
= pointed_type(type
);
8353 size1
= type_size(t1
, &align1
);
8356 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
8362 /* only parse strings here if correct type (otherwise: handle
8363 them as ((w)char *) expressions */
8364 if ((tok
== TOK_LSTR
&&
8365 (t1
->t
& VT_BTYPE
) == VT_INT
) ||
8367 (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
8368 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8373 /* compute maximum number of chars wanted */
8375 cstr_len
= cstr
->size
;
8377 cstr_len
= cstr
->size
/ sizeof(int);
8380 if (n
>= 0 && nb
> (n
- array_length
))
8381 nb
= n
- array_length
;
8384 warning("initializer-string for array is too long");
8385 /* in order to go faster for common case (char
8386 string in global variable, we handle it
8388 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
8389 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
8393 ch
= ((unsigned char *)cstr
->data
)[i
];
8395 ch
= ((int *)cstr
->data
)[i
];
8396 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
8404 /* only add trailing zero if enough storage (no
8405 warning in this case since it is standard) */
8406 if (n
< 0 || array_length
< n
) {
8408 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
8414 while (tok
!= '}') {
8415 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
8416 if (n
>= 0 && index
>= n
)
8417 error("index too large");
8418 /* must put zero in holes (note that doing it that way
8419 ensures that it even works with designators) */
8420 if (!size_only
&& array_length
< index
) {
8421 init_putz(t1
, sec
, c
+ array_length
* size1
,
8422 (index
- array_length
) * size1
);
8425 if (index
> array_length
)
8426 array_length
= index
;
8427 /* special test for multi dimensional arrays (may not
8428 be strictly correct if designators are used at the
8430 if (index
>= n
&& no_oblock
)
8439 /* put zeros at the end */
8440 if (!size_only
&& n
>= 0 && array_length
< n
) {
8441 init_putz(t1
, sec
, c
+ array_length
* size1
,
8442 (n
- array_length
) * size1
);
8444 /* patch type size if needed */
8446 s
->c
= array_length
;
8447 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
8448 (sec
|| !first
|| tok
== '{')) {
8451 /* NOTE: the previous test is a specific case for automatic
8452 struct/union init */
8453 /* XXX: union needs only one init */
8455 /* XXX: this test is incorrect for local initializers
8456 beginning with ( without {. It would be much more difficult
8457 to do it correctly (ideally, the expression parser should
8458 be used in all cases) */
8464 while (tok
== '(') {
8468 if (!parse_btype(&type1
, &ad1
))
8470 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
8472 if (!is_assignable_types(type
, &type1
))
8473 error("invalid type for cast");
8478 if (first
|| tok
== '{') {
8487 while (tok
!= '}') {
8488 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
8490 if (!size_only
&& array_length
< index
) {
8491 init_putz(type
, sec
, c
+ array_length
,
8492 index
- array_length
);
8494 index
= index
+ type_size(&f
->type
, &align1
);
8495 if (index
> array_length
)
8496 array_length
= index
;
8498 if (no_oblock
&& f
== NULL
)
8504 /* put zeros at the end */
8505 if (!size_only
&& array_length
< n
) {
8506 init_putz(type
, sec
, c
+ array_length
,
8515 } else if (tok
== '{') {
8517 decl_initializer(type
, sec
, c
, first
, size_only
);
8519 } else if (size_only
) {
8520 /* just skip expression */
8522 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
8526 else if (tok
== ')')
8531 /* currently, we always use constant expression for globals
8532 (may change for scripting case) */
8533 expr_type
= EXPR_CONST
;
8535 expr_type
= EXPR_ANY
;
8536 init_putv(type
, sec
, c
, 0, expr_type
);
8540 /* parse an initializer for type 't' if 'has_init' is non zero, and
8541 allocate space in local or global data space ('r' is either
8542 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
8543 variable 'v' of scope 'scope' is declared before initializers are
8544 parsed. If 'v' is zero, then a reference to the new object is put
8545 in the value stack. If 'has_init' is 2, a special parsing is done
8546 to handle string constants. */
8547 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
8548 int has_init
, int v
, int scope
)
8550 int size
, align
, addr
, data_offset
;
8552 ParseState saved_parse_state
;
8553 TokenString init_str
;
8556 size
= type_size(type
, &align
);
8557 /* If unknown size, we must evaluate it before
8558 evaluating initializers because
8559 initializers can generate global data too
8560 (e.g. string pointers or ISOC99 compound
8561 literals). It also simplifies local
8562 initializers handling */
8563 tok_str_new(&init_str
);
8566 error("unknown type size");
8567 /* get all init string */
8568 if (has_init
== 2) {
8569 /* only get strings */
8570 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8571 tok_str_add_tok(&init_str
);
8576 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
8578 error("unexpected end of file in initializer");
8579 tok_str_add_tok(&init_str
);
8582 else if (tok
== '}') {
8590 tok_str_add(&init_str
, -1);
8591 tok_str_add(&init_str
, 0);
8594 save_parse_state(&saved_parse_state
);
8596 macro_ptr
= init_str
.str
;
8598 decl_initializer(type
, NULL
, 0, 1, 1);
8599 /* prepare second initializer parsing */
8600 macro_ptr
= init_str
.str
;
8603 /* if still unknown size, error */
8604 size
= type_size(type
, &align
);
8606 error("unknown type size");
8608 /* take into account specified alignment if bigger */
8610 if (ad
->aligned
> align
)
8611 align
= ad
->aligned
;
8612 } else if (ad
->packed
) {
8615 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
8617 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
8619 loc
= (loc
- size
) & -align
;
8621 /* handles bounds */
8622 /* XXX: currently, since we do only one pass, we cannot track
8623 '&' operators, so we add only arrays */
8624 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
8625 unsigned long *bounds_ptr
;
8626 /* add padding between regions */
8628 /* then add local bound info */
8629 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
8630 bounds_ptr
[0] = addr
;
8631 bounds_ptr
[1] = size
;
8634 /* local variable */
8635 sym_push(v
, type
, r
, addr
);
8637 /* push local reference */
8638 vset(type
, r
, addr
);
8644 if (v
&& scope
== VT_CONST
) {
8645 /* see if the symbol was already defined */
8648 if (!is_compatible_types(&sym
->type
, type
))
8649 error("incompatible types for redefinition of '%s'",
8650 get_tok_str(v
, NULL
));
8651 if (sym
->type
.t
& VT_EXTERN
) {
8652 /* if the variable is extern, it was not allocated */
8653 sym
->type
.t
&= ~VT_EXTERN
;
8654 /* set array size if it was ommited in extern
8656 if ((sym
->type
.t
& VT_ARRAY
) &&
8657 sym
->type
.ref
->c
< 0 &&
8659 sym
->type
.ref
->c
= type
->ref
->c
;
8661 /* we accept several definitions of the same
8662 global variable. this is tricky, because we
8663 must play with the SHN_COMMON type of the symbol */
8664 /* XXX: should check if the variable was already
8665 initialized. It is incorrect to initialized it
8667 /* no init data, we won't add more to the symbol */
8674 /* allocate symbol in corresponding section */
8679 else if (tcc_state
->nocommon
)
8683 data_offset
= sec
->data_offset
;
8684 data_offset
= (data_offset
+ align
- 1) & -align
;
8686 /* very important to increment global pointer at this time
8687 because initializers themselves can create new initializers */
8688 data_offset
+= size
;
8689 /* add padding if bound check */
8690 if (do_bounds_check
)
8692 sec
->data_offset
= data_offset
;
8693 /* allocate section space to put the data */
8694 if (sec
->sh_type
!= SHT_NOBITS
&&
8695 data_offset
> sec
->data_allocated
)
8696 section_realloc(sec
, data_offset
);
8697 /* align section if needed */
8698 if (align
> sec
->sh_addralign
)
8699 sec
->sh_addralign
= align
;
8701 addr
= 0; /* avoid warning */
8705 if (scope
== VT_CONST
) {
8710 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
8712 /* update symbol definition */
8714 put_extern_sym(sym
, sec
, addr
, size
);
8717 /* put a common area */
8718 put_extern_sym(sym
, NULL
, align
, size
);
8719 /* XXX: find a nicer way */
8720 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
8721 esym
->st_shndx
= SHN_COMMON
;
8726 /* push global reference */
8727 sym
= get_sym_ref(type
, sec
, addr
, size
);
8729 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
8733 /* handles bounds now because the symbol must be defined
8734 before for the relocation */
8735 if (do_bounds_check
) {
8736 unsigned long *bounds_ptr
;
8738 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
8739 /* then add global bound info */
8740 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
8741 bounds_ptr
[0] = 0; /* relocated */
8742 bounds_ptr
[1] = size
;
8746 decl_initializer(type
, sec
, addr
, 1, 0);
8747 /* restore parse state if needed */
8749 tok_str_free(init_str
.str
);
8750 restore_parse_state(&saved_parse_state
);
8756 void put_func_debug(Sym
*sym
)
8761 /* XXX: we put here a dummy type */
8762 snprintf(buf
, sizeof(buf
), "%s:%c1",
8763 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
8764 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
8765 cur_text_section
, sym
->c
);
8770 /* parse an old style function declaration list */
8771 /* XXX: check multiple parameter */
8772 static void func_decl_list(Sym
*func_sym
)
8779 /* parse each declaration */
8780 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
8781 if (!parse_btype(&btype
, &ad
))
8782 expect("declaration list");
8783 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8784 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8786 /* we accept no variable after */
8790 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8791 /* find parameter in function parameter list */
8794 if ((s
->v
& ~SYM_FIELD
) == v
)
8798 error("declaration for parameter '%s' but no such parameter",
8799 get_tok_str(v
, NULL
));
8801 /* check that no storage specifier except 'register' was given */
8802 if (type
.t
& VT_STORAGE
)
8803 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
8804 convert_parameter_type(&type
);
8805 /* we can add the type (NOTE: it could be local to the function) */
8807 /* accept other parameters */
8818 /* parse a function defined by symbol 'sym' and generate its code in
8819 'cur_text_section' */
8820 static void gen_function(Sym
*sym
)
8822 ind
= cur_text_section
->data_offset
;
8823 /* NOTE: we patch the symbol size later */
8824 put_extern_sym(sym
, cur_text_section
, ind
, 0);
8825 funcname
= get_tok_str(sym
->v
, NULL
);
8827 /* put debug symbol */
8829 put_func_debug(sym
);
8830 /* push a dummy symbol to enable local sym storage */
8831 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
8832 gfunc_prolog(&sym
->type
);
8834 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
8837 cur_text_section
->data_offset
= ind
;
8838 label_pop(&global_label_stack
, NULL
);
8839 sym_pop(&local_stack
, NULL
); /* reset local stack */
8840 /* end of function */
8841 /* patch symbol size */
8842 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_size
=
8845 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
8847 funcname
= ""; /* for safety */
8848 func_vt
.t
= VT_VOID
; /* for safety */
8849 ind
= 0; /* for safety */
8852 static void gen_inline_functions(void)
8856 int *str
, inline_generated
;
8858 /* iterate while inline function are referenced */
8860 inline_generated
= 0;
8861 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
8863 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
8864 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
8865 (VT_STATIC
| VT_INLINE
) &&
8867 /* the function was used: generate its code and
8868 convert it to a normal function */
8869 str
= (int *)sym
->r
;
8870 sym
->r
= VT_SYM
| VT_CONST
;
8871 type
->t
&= ~VT_INLINE
;
8875 cur_text_section
= text_section
;
8877 macro_ptr
= NULL
; /* fail safe */
8880 inline_generated
= 1;
8883 if (!inline_generated
)
8887 /* free all remaining inline function tokens */
8888 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
8890 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
8891 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
8892 (VT_STATIC
| VT_INLINE
)) {
8893 str
= (int *)sym
->r
;
8895 sym
->r
= 0; /* fail safe */
8900 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
8901 static void decl(int l
)
8909 if (!parse_btype(&btype
, &ad
)) {
8910 /* skip redundant ';' */
8911 /* XXX: find more elegant solution */
8916 if (l
== VT_CONST
&&
8917 (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
)) {
8918 /* global asm block */
8922 /* special test for old K&R protos without explicit int
8923 type. Only accepted when defining global data */
8924 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
8928 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8929 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8931 /* we accept no variable after */
8935 while (1) { /* iterate thru each declaration */
8937 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8941 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
8942 printf("type = '%s'\n", buf
);
8945 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
8946 /* if old style function prototype, we accept a
8949 if (sym
->c
== FUNC_OLD
)
8950 func_decl_list(sym
);
8955 error("cannot use local functions");
8956 if (!(type
.t
& VT_FUNC
))
8957 expect("function definition");
8959 /* reject abstract declarators in function definition */
8961 while ((sym
= sym
->next
) != NULL
)
8962 if (!(sym
->v
& ~SYM_FIELD
))
8963 expect("identifier");
8965 /* XXX: cannot do better now: convert extern line to static inline */
8966 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
8967 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
8971 if ((sym
->type
.t
& VT_BTYPE
) != VT_FUNC
)
8973 /* specific case: if not func_call defined, we put
8974 the one of the prototype */
8975 /* XXX: should have default value */
8976 if (sym
->type
.ref
->r
!= FUNC_CDECL
&&
8977 type
.ref
->r
== FUNC_CDECL
)
8978 type
.ref
->r
= sym
->type
.ref
->r
;
8979 if (!is_compatible_types(&sym
->type
, &type
)) {
8981 error("incompatible types for redefinition of '%s'",
8982 get_tok_str(v
, NULL
));
8984 /* if symbol is already defined, then put complete type */
8987 /* put function symbol */
8988 sym
= global_identifier_push(v
, type
.t
, 0);
8989 sym
->type
.ref
= type
.ref
;
8992 /* static inline functions are just recorded as a kind
8993 of macro. Their code will be emitted at the end of
8994 the compilation unit only if they are used */
8995 if ((type
.t
& (VT_INLINE
| VT_STATIC
)) ==
8996 (VT_INLINE
| VT_STATIC
)) {
8997 TokenString func_str
;
9000 tok_str_new(&func_str
);
9006 error("unexpected end of file");
9007 tok_str_add_tok(&func_str
);
9012 } else if (t
== '}') {
9014 if (block_level
== 0)
9018 tok_str_add(&func_str
, -1);
9019 tok_str_add(&func_str
, 0);
9020 sym
->r
= (int)func_str
.str
;
9022 /* compute text section */
9023 cur_text_section
= ad
.section
;
9024 if (!cur_text_section
)
9025 cur_text_section
= text_section
;
9026 sym
->r
= VT_SYM
| VT_CONST
;
9028 #ifdef TCC_TARGET_PE
9030 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_other
|= 1;
9036 if (btype
.t
& VT_TYPEDEF
) {
9037 /* save typedefed type */
9038 /* XXX: test storage specifiers ? */
9039 sym
= sym_push(v
, &type
, 0, 0);
9040 sym
->type
.t
|= VT_TYPEDEF
;
9041 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9042 /* external function definition */
9043 /* specific case for func_call attribute */
9045 type
.ref
->r
= ad
.func_call
;
9046 external_sym(v
, &type
, 0);
9048 /* not lvalue if array */
9050 if (!(type
.t
& VT_ARRAY
))
9051 r
|= lvalue_type(type
.t
);
9052 has_init
= (tok
== '=');
9053 if ((btype
.t
& VT_EXTERN
) ||
9054 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
9055 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
9056 /* external variable */
9057 /* NOTE: as GCC, uninitialized global static
9058 arrays of null size are considered as
9060 external_sym(v
, &type
, r
);
9062 if (type
.t
& VT_STATIC
)
9068 decl_initializer_alloc(&type
, &ad
, r
,
9082 /* better than nothing, but needs extension to handle '-E' option
9084 static void preprocess_init(TCCState
*s1
)
9086 s1
->include_stack_ptr
= s1
->include_stack
;
9087 /* XXX: move that before to avoid having to initialize
9088 file->ifdef_stack_ptr ? */
9089 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
9090 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
9092 /* XXX: not ANSI compliant: bound checking says error */
9094 s1
->pack_stack
[0] = 0;
9095 s1
->pack_stack_ptr
= s1
->pack_stack
;
9098 /* compile the C file opened in 'file'. Return non zero if errors. */
9099 static int tcc_compile(TCCState
*s1
)
9103 volatile int section_sym
;
9106 printf("%s: **** new file\n", file
->filename
);
9108 preprocess_init(s1
);
9111 anon_sym
= SYM_FIRST_ANOM
;
9113 /* file info: full path + filename */
9114 section_sym
= 0; /* avoid warning */
9116 section_sym
= put_elf_sym(symtab_section
, 0, 0,
9117 ELF32_ST_INFO(STB_LOCAL
, STT_SECTION
), 0,
9118 text_section
->sh_num
, NULL
);
9119 getcwd(buf
, sizeof(buf
));
9120 pstrcat(buf
, sizeof(buf
), "/");
9121 put_stabs_r(buf
, N_SO
, 0, 0,
9122 text_section
->data_offset
, text_section
, section_sym
);
9123 put_stabs_r(file
->filename
, N_SO
, 0, 0,
9124 text_section
->data_offset
, text_section
, section_sym
);
9126 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
9127 symbols can be safely used */
9128 put_elf_sym(symtab_section
, 0, 0,
9129 ELF32_ST_INFO(STB_LOCAL
, STT_FILE
), 0,
9130 SHN_ABS
, file
->filename
);
9132 /* define some often used types */
9133 int_type
.t
= VT_INT
;
9135 char_pointer_type
.t
= VT_BYTE
;
9136 mk_pointer(&char_pointer_type
);
9138 func_old_type
.t
= VT_FUNC
;
9139 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
9142 /* define 'void *alloca(unsigned int)' builtin function */
9147 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
9148 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
9151 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
9155 define_start
= define_stack
;
9157 if (setjmp(s1
->error_jmp_buf
) == 0) {
9159 s1
->error_set_jmp_enabled
= 1;
9161 ch
= file
->buf_ptr
[0];
9162 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9163 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
9167 expect("declaration");
9169 /* end of translation unit info */
9171 put_stabs_r(NULL
, N_SO
, 0, 0,
9172 text_section
->data_offset
, text_section
, section_sym
);
9175 s1
->error_set_jmp_enabled
= 0;
9177 /* reset define stack, but leave -Dsymbols (may be incorrect if
9178 they are undefined) */
9179 free_defines(define_start
);
9181 gen_inline_functions();
9183 sym_pop(&global_stack
, NULL
);
9185 return s1
->nb_errors
!= 0 ? -1 : 0;
9189 int tcc_compile_string(TCCState
*s
, const char *str
)
9191 BufferedFile bf1
, *bf
= &bf1
;
9195 /* init file structure */
9197 /* XXX: avoid copying */
9199 buf
= tcc_malloc(len
+ 1);
9202 memcpy(buf
, str
, len
);
9205 bf
->buf_end
= buf
+ len
;
9206 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
9210 ret
= tcc_compile(s
);
9214 /* currently, no need to close */
9219 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9220 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
9222 BufferedFile bf1
, *bf
= &bf1
;
9224 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
9225 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
9229 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
9231 /* init file structure */
9233 bf
->buf_ptr
= bf
->buffer
;
9234 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
9235 *bf
->buf_end
= CH_EOB
;
9236 bf
->filename
[0] = '\0';
9240 s1
->include_stack_ptr
= s1
->include_stack
;
9242 /* parse with define parser */
9243 ch
= file
->buf_ptr
[0];
9249 /* undefine a preprocessor symbol */
9250 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
9254 ts
= tok_alloc(sym
, strlen(sym
));
9255 s
= define_find(ts
->tok
);
9256 /* undefine symbol by putting an invalid name */
9261 #ifdef CONFIG_TCC_ASM
9263 #ifdef TCC_TARGET_I386
9264 #include "i386-asm.c"
9269 static void asm_instr(void)
9271 error("inline asm() not supported");
9273 static void asm_global_instr(void)
9275 error("inline asm() not supported");
9281 #ifdef TCC_TARGET_COFF
9282 #include "tcccoff.c"
9285 #ifdef TCC_TARGET_PE
9289 /* print the position in the source file of PC value 'pc' by reading
9290 the stabs debug information */
9291 static void rt_printline(unsigned long wanted_pc
)
9293 Stab_Sym
*sym
, *sym_end
;
9294 char func_name
[128], last_func_name
[128];
9295 unsigned long func_addr
, last_pc
, pc
;
9296 const char *incl_files
[INCLUDE_STACK_SIZE
];
9297 int incl_index
, len
, last_line_num
, i
;
9298 const char *str
, *p
;
9300 fprintf(stderr
, "0x%08lx:", wanted_pc
);
9302 func_name
[0] = '\0';
9305 last_func_name
[0] = '\0';
9306 last_pc
= 0xffffffff;
9308 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
9309 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
9310 while (sym
< sym_end
) {
9311 switch(sym
->n_type
) {
9312 /* function start or end */
9314 if (sym
->n_strx
== 0) {
9315 /* we test if between last line and end of function */
9316 pc
= sym
->n_value
+ func_addr
;
9317 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9319 func_name
[0] = '\0';
9322 str
= stabstr_section
->data
+ sym
->n_strx
;
9323 p
= strchr(str
, ':');
9325 pstrcpy(func_name
, sizeof(func_name
), str
);
9328 if (len
> sizeof(func_name
) - 1)
9329 len
= sizeof(func_name
) - 1;
9330 memcpy(func_name
, str
, len
);
9331 func_name
[len
] = '\0';
9333 func_addr
= sym
->n_value
;
9336 /* line number info */
9338 pc
= sym
->n_value
+ func_addr
;
9339 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9342 last_line_num
= sym
->n_desc
;
9344 strcpy(last_func_name
, func_name
);
9348 str
= stabstr_section
->data
+ sym
->n_strx
;
9350 if (incl_index
< INCLUDE_STACK_SIZE
) {
9351 incl_files
[incl_index
++] = str
;
9359 if (sym
->n_strx
== 0) {
9360 incl_index
= 0; /* end of translation unit */
9362 str
= stabstr_section
->data
+ sym
->n_strx
;
9363 /* do not add path */
9365 if (len
> 0 && str
[len
- 1] != '/')
9373 /* second pass: we try symtab symbols (no line number info) */
9376 Elf32_Sym
*sym
, *sym_end
;
9379 sym_end
= (Elf32_Sym
*)(symtab_section
->data
+ symtab_section
->data_offset
);
9380 for(sym
= (Elf32_Sym
*)symtab_section
->data
+ 1;
9383 type
= ELF32_ST_TYPE(sym
->st_info
);
9384 if (type
== STT_FUNC
) {
9385 if (wanted_pc
>= sym
->st_value
&&
9386 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
9387 pstrcpy(last_func_name
, sizeof(last_func_name
),
9388 strtab_section
->data
+ sym
->st_name
);
9394 /* did not find any info: */
9395 fprintf(stderr
, " ???\n");
9398 if (last_func_name
[0] != '\0') {
9399 fprintf(stderr
, " %s()", last_func_name
);
9401 if (incl_index
> 0) {
9402 fprintf(stderr
, " (%s:%d",
9403 incl_files
[incl_index
- 1], last_line_num
);
9404 for(i
= incl_index
- 2; i
>= 0; i
--)
9405 fprintf(stderr
, ", included from %s", incl_files
[i
]);
9406 fprintf(stderr
, ")");
9408 fprintf(stderr
, "\n");
9411 #if !defined(WIN32) && !defined(CONFIG_TCCBOOT)
9415 /* fix for glibc 2.1 */
9421 /* return the PC at frame level 'level'. Return non zero if not found */
9422 static int rt_get_caller_pc(unsigned long *paddr
,
9423 ucontext_t
*uc
, int level
)
9429 #if defined(__FreeBSD__)
9430 *paddr
= uc
->uc_mcontext
.mc_eip
;
9431 #elif defined(__dietlibc__)
9432 *paddr
= uc
->uc_mcontext
.eip
;
9434 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
9438 #if defined(__FreeBSD__)
9439 fp
= uc
->uc_mcontext
.mc_ebp
;
9440 #elif defined(__dietlibc__)
9441 fp
= uc
->uc_mcontext
.ebp
;
9443 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
9445 for(i
=1;i
<level
;i
++) {
9446 /* XXX: check address validity with program info */
9447 if (fp
<= 0x1000 || fp
>= 0xc0000000)
9449 fp
= ((unsigned long *)fp
)[0];
9451 *paddr
= ((unsigned long *)fp
)[1];
9457 #warning add arch specific rt_get_caller_pc()
9459 static int rt_get_caller_pc(unsigned long *paddr
,
9460 ucontext_t
*uc
, int level
)
9466 /* emit a run time error at position 'pc' */
9467 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
9474 fprintf(stderr
, "Runtime error: ");
9475 vfprintf(stderr
, fmt
, ap
);
9476 fprintf(stderr
, "\n");
9477 for(i
=0;i
<num_callers
;i
++) {
9478 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
9481 fprintf(stderr
, "at ");
9483 fprintf(stderr
, "by ");
9490 /* signal handler for fatal errors */
9491 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
9493 ucontext_t
*uc
= puc
;
9497 switch(siginf
->si_code
) {
9500 rt_error(uc
, "division by zero");
9503 rt_error(uc
, "floating point exception");
9509 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
9510 rt_error(uc
, *rt_bound_error_msg
);
9512 rt_error(uc
, "dereferencing invalid pointer");
9515 rt_error(uc
, "illegal instruction");
9518 rt_error(uc
, "abort() called");
9521 rt_error(uc
, "caught signal %d", signum
);
9528 /* do all relocations (needed before using tcc_get_symbol()) */
9529 int tcc_relocate(TCCState
*s1
)
9536 #ifdef TCC_TARGET_PE
9539 tcc_add_runtime(s1
);
9542 relocate_common_syms();
9544 tcc_add_linker_symbols(s1
);
9546 build_got_entries(s1
);
9548 /* compute relocation address : section are relocated in place. We
9549 also alloc the bss space */
9550 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9551 s
= s1
->sections
[i
];
9552 if (s
->sh_flags
& SHF_ALLOC
) {
9553 if (s
->sh_type
== SHT_NOBITS
)
9554 s
->data
= tcc_mallocz(s
->data_offset
);
9555 s
->sh_addr
= (unsigned long)s
->data
;
9559 relocate_syms(s1
, 1);
9561 if (s1
->nb_errors
!= 0)
9564 /* relocate each section */
9565 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9566 s
= s1
->sections
[i
];
9568 relocate_section(s1
, s
);
9573 /* launch the compiled program with the given arguments */
9574 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
9576 int (*prog_main
)(int, char **);
9578 if (tcc_relocate(s1
) < 0)
9581 prog_main
= tcc_get_symbol_err(s1
, "main");
9584 #if defined(WIN32) || defined(CONFIG_TCCBOOT)
9585 error("debug mode currently not available for Windows");
9587 struct sigaction sigact
;
9588 /* install TCC signal handlers to print debug info on fatal
9590 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
9591 sigact
.sa_sigaction
= sig_error
;
9592 sigemptyset(&sigact
.sa_mask
);
9593 sigaction(SIGFPE
, &sigact
, NULL
);
9594 sigaction(SIGILL
, &sigact
, NULL
);
9595 sigaction(SIGSEGV
, &sigact
, NULL
);
9596 sigaction(SIGBUS
, &sigact
, NULL
);
9597 sigaction(SIGABRT
, &sigact
, NULL
);
9601 #ifdef CONFIG_TCC_BCHECK
9602 if (do_bounds_check
) {
9603 void (*bound_init
)(void);
9605 /* set error function */
9606 rt_bound_error_msg
= (void *)tcc_get_symbol_err(s1
,
9607 "__bound_error_msg");
9609 /* XXX: use .init section so that it also work in binary ? */
9610 bound_init
= (void *)tcc_get_symbol_err(s1
, "__bound_init");
9614 return (*prog_main
)(argc
, argv
);
9617 TCCState
*tcc_new(void)
9624 s
= tcc_mallocz(sizeof(TCCState
));
9628 s
->output_type
= TCC_OUTPUT_MEMORY
;
9630 /* init isid table */
9632 isidnum_table
[i
] = isid(i
) || isnum(i
);
9634 /* add all tokens */
9636 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
9638 tok_ident
= TOK_IDENT
;
9647 ts
= tok_alloc(p
, r
- p
- 1);
9651 /* we add dummy defines for some special macros to speed up tests
9652 and to have working defined() */
9653 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
9654 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
9655 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
9656 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
9658 /* standard defines */
9659 tcc_define_symbol(s
, "__STDC__", NULL
);
9660 #if defined(TCC_TARGET_I386)
9661 tcc_define_symbol(s
, "__i386__", NULL
);
9663 #if defined(TCC_TARGET_ARM)
9664 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
9665 tcc_define_symbol(s
, "__arm_elf__", NULL
);
9666 tcc_define_symbol(s
, "__arm_elf", NULL
);
9667 tcc_define_symbol(s
, "arm_elf", NULL
);
9668 tcc_define_symbol(s
, "__arm__", NULL
);
9669 tcc_define_symbol(s
, "__arm", NULL
);
9670 tcc_define_symbol(s
, "arm", NULL
);
9671 tcc_define_symbol(s
, "__APCS_32__", NULL
);
9674 tcc_define_symbol(s
, "__linux__", NULL
);
9675 tcc_define_symbol(s
, "linux", NULL
);
9677 /* tiny C specific defines */
9678 tcc_define_symbol(s
, "__TINYC__", NULL
);
9680 /* tiny C & gcc defines */
9681 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
9682 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
9683 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
9685 /* default library paths */
9686 #ifdef TCC_TARGET_PE
9689 snprintf(buf
, sizeof(buf
), "%s/lib", tcc_lib_path
);
9690 tcc_add_library_path(s
, buf
);
9693 tcc_add_library_path(s
, "/usr/local/lib");
9694 tcc_add_library_path(s
, "/usr/lib");
9695 tcc_add_library_path(s
, "/lib");
9698 /* no section zero */
9699 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
9701 /* create standard sections */
9702 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
9703 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
9704 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
9706 /* symbols are always generated for linking stage */
9707 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
9709 ".hashtab", SHF_PRIVATE
);
9710 strtab_section
= symtab_section
->link
;
9712 /* private symbol table for dynamic symbols */
9713 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
9715 ".dynhashtab", SHF_PRIVATE
);
9716 s
->alacarte_link
= 1;
9718 #ifdef CHAR_IS_UNSIGNED
9719 s
->char_is_unsigned
= 1;
9724 void tcc_delete(TCCState
*s1
)
9728 /* free -D defines */
9732 n
= tok_ident
- TOK_IDENT
;
9733 for(i
= 0; i
< n
; i
++)
9734 tcc_free(table_ident
[i
]);
9735 tcc_free(table_ident
);
9737 /* free all sections */
9739 free_section(symtab_section
->hash
);
9741 free_section(s1
->dynsymtab_section
->hash
);
9742 free_section(s1
->dynsymtab_section
->link
);
9743 free_section(s1
->dynsymtab_section
);
9745 for(i
= 1; i
< s1
->nb_sections
; i
++)
9746 free_section(s1
->sections
[i
]);
9747 tcc_free(s1
->sections
);
9749 /* free loaded dlls array */
9750 for(i
= 0; i
< s1
->nb_loaded_dlls
; i
++)
9751 tcc_free(s1
->loaded_dlls
[i
]);
9752 tcc_free(s1
->loaded_dlls
);
9755 for(i
= 0; i
< s1
->nb_library_paths
; i
++)
9756 tcc_free(s1
->library_paths
[i
]);
9757 tcc_free(s1
->library_paths
);
9759 /* cached includes */
9760 for(i
= 0; i
< s1
->nb_cached_includes
; i
++)
9761 tcc_free(s1
->cached_includes
[i
]);
9762 tcc_free(s1
->cached_includes
);
9764 for(i
= 0; i
< s1
->nb_include_paths
; i
++)
9765 tcc_free(s1
->include_paths
[i
]);
9766 tcc_free(s1
->include_paths
);
9768 for(i
= 0; i
< s1
->nb_sysinclude_paths
; i
++)
9769 tcc_free(s1
->sysinclude_paths
[i
]);
9770 tcc_free(s1
->sysinclude_paths
);
9775 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
9779 pathname1
= tcc_strdup(pathname
);
9780 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
9784 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
9788 pathname1
= tcc_strdup(pathname
);
9789 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
9793 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
9795 const char *ext
, *filename1
;
9798 BufferedFile
*saved_file
;
9800 /* find source file type with extension */
9801 filename1
= strrchr(filename
, '/');
9805 filename1
= filename
;
9806 ext
= strrchr(filename1
, '.');
9812 file
= tcc_open(s1
, filename
);
9814 if (flags
& AFF_PRINT_ERROR
) {
9815 error_noabort("file '%s' not found", filename
);
9821 if (!ext
|| !strcmp(ext
, "c")) {
9822 /* C file assumed */
9823 ret
= tcc_compile(s1
);
9825 #ifdef CONFIG_TCC_ASM
9826 if (!strcmp(ext
, "S")) {
9827 /* preprocessed assembler */
9828 ret
= tcc_assemble(s1
, 1);
9829 } else if (!strcmp(ext
, "s")) {
9830 /* non preprocessed assembler */
9831 ret
= tcc_assemble(s1
, 0);
9834 #ifdef TCC_TARGET_PE
9835 if (!strcmp(ext
, "def")) {
9836 ret
= pe_load_def_file(s1
, fdopen(file
->fd
, "rb"));
9841 /* assume executable format: auto guess file type */
9842 ret
= read(fd
, &ehdr
, sizeof(ehdr
));
9843 lseek(fd
, 0, SEEK_SET
);
9845 error_noabort("could not read header");
9847 } else if (ret
!= sizeof(ehdr
)) {
9848 goto try_load_script
;
9851 if (ehdr
.e_ident
[0] == ELFMAG0
&&
9852 ehdr
.e_ident
[1] == ELFMAG1
&&
9853 ehdr
.e_ident
[2] == ELFMAG2
&&
9854 ehdr
.e_ident
[3] == ELFMAG3
) {
9855 file
->line_num
= 0; /* do not display line number if error */
9856 if (ehdr
.e_type
== ET_REL
) {
9857 ret
= tcc_load_object_file(s1
, fd
, 0);
9858 } else if (ehdr
.e_type
== ET_DYN
) {
9859 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
9860 #ifdef TCC_TARGET_PE
9864 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
9871 ret
= tcc_load_dll(s1
, fd
, filename
,
9872 (flags
& AFF_REFERENCED_DLL
) != 0);
9875 error_noabort("unrecognized ELF file");
9878 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
9879 file
->line_num
= 0; /* do not display line number if error */
9880 ret
= tcc_load_archive(s1
, fd
);
9882 #ifdef TCC_TARGET_COFF
9883 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
9884 ret
= tcc_load_coff(s1
, fd
);
9888 /* as GNU ld, consider it is an ld script if not recognized */
9890 ret
= tcc_load_ldscript(s1
);
9892 error_noabort("unrecognized file type");
9907 int tcc_add_file(TCCState
*s
, const char *filename
)
9909 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
9912 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
9916 pathname1
= tcc_strdup(pathname
);
9917 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
9921 /* find and load a dll. Return non zero if not found */
9922 /* XXX: add '-rpath' option support ? */
9923 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
9928 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9929 snprintf(buf
, sizeof(buf
), "%s/%s",
9930 s
->library_paths
[i
], filename
);
9931 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
9937 /* the library name is the same as the argument of the '-l' option */
9938 int tcc_add_library(TCCState
*s
, const char *libraryname
)
9943 /* first we look for the dynamic library if not static linking */
9944 if (!s
->static_link
) {
9945 #ifdef TCC_TARGET_PE
9946 snprintf(buf
, sizeof(buf
), "%s.def", libraryname
);
9948 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
9950 if (tcc_add_dll(s
, buf
, 0) == 0)
9954 /* then we look for the static library */
9955 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
9956 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
9957 s
->library_paths
[i
], libraryname
);
9958 if (tcc_add_file_internal(s
, buf
, 0) == 0)
9964 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
9966 add_elf_sym(symtab_section
, val
, 0,
9967 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
), 0,
9972 int tcc_set_output_type(TCCState
*s
, int output_type
)
9974 s
->output_type
= output_type
;
9979 /* default include paths */
9980 /* XXX: reverse order needed if -isystem support */
9981 #ifndef TCC_TARGET_PE
9982 tcc_add_sysinclude_path(s
, "/usr/local/include");
9983 tcc_add_sysinclude_path(s
, "/usr/include");
9985 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
9986 tcc_add_sysinclude_path(s
, buf
);
9987 #ifdef TCC_TARGET_PE
9988 snprintf(buf
, sizeof(buf
), "%s/include/winapi", tcc_lib_path
);
9989 tcc_add_sysinclude_path(s
, buf
);
9993 /* if bound checking, then add corresponding sections */
9994 #ifdef CONFIG_TCC_BCHECK
9995 if (do_bounds_check
) {
9997 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
9998 /* create bounds sections */
9999 bounds_section
= new_section(s
, ".bounds",
10000 SHT_PROGBITS
, SHF_ALLOC
);
10001 lbounds_section
= new_section(s
, ".lbounds",
10002 SHT_PROGBITS
, SHF_ALLOC
);
10006 if (s
->char_is_unsigned
) {
10007 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
10010 /* add debug sections */
10013 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
10014 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
10015 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
10016 put_elf_str(stabstr_section
, "");
10017 stab_section
->link
= stabstr_section
;
10018 /* put first entry */
10019 put_stabs("", 0, 0, 0, 0);
10022 /* add libc crt1/crti objects */
10023 #ifndef TCC_TARGET_PE
10024 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
10026 if (output_type
!= TCC_OUTPUT_DLL
)
10027 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
10028 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
10034 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
10035 #define FD_INVERT 0x0002 /* invert value before storing */
10037 typedef struct FlagDef
{
10043 static const FlagDef warning_defs
[] = {
10044 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
10045 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
10046 { offsetof(TCCState
, warn_error
), 0, "error" },
10047 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
10048 "implicit-function-declaration" },
10051 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
10052 const char *name
, int value
)
10059 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
10063 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
10064 if (!strcmp(r
, p
->name
))
10069 if (p
->flags
& FD_INVERT
)
10071 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
10076 /* set/reset a warning */
10077 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
10082 if (!strcmp(warning_name
, "all")) {
10083 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
10084 if (p
->flags
& WD_ALL
)
10085 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
10089 return set_flag(s
, warning_defs
, countof(warning_defs
),
10090 warning_name
, value
);
10094 static const FlagDef flag_defs
[] = {
10095 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
10096 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
10097 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
10100 /* set/reset a flag */
10101 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
10103 return set_flag(s
, flag_defs
, countof(flag_defs
),
10107 #if !defined(LIBTCC)
10109 /* extract the basename of a file */
10110 static const char *tcc_basename(const char *name
)
10113 p
= strrchr(name
, '/');
10116 p
= strrchr(name
, '\\');
10125 static int64_t getclock_us(void)
10130 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
10133 gettimeofday(&tv
, NULL
);
10134 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
10140 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2005 Fabrice Bellard\n"
10141 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
10142 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]\n"
10143 " [infile1 infile2...] [-run infile args...]\n"
10145 "General options:\n"
10146 " -v display current version\n"
10147 " -c compile only - generate an object file\n"
10148 " -o outfile set output filename\n"
10149 " -Bdir set tcc internal library path\n"
10150 " -bench output compilation statistics\n"
10151 " -run run compiled source\n"
10152 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
10153 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
10154 " -w disable all warnings\n"
10155 "Preprocessor options:\n"
10156 " -Idir add include path 'dir'\n"
10157 " -Dsym[=val] define 'sym' with value 'val'\n"
10158 " -Usym undefine 'sym'\n"
10159 "Linker options:\n"
10160 " -Ldir add library path 'dir'\n"
10161 " -llib link with dynamic or static library 'lib'\n"
10162 " -shared generate a shared library\n"
10163 " -static static linking\n"
10164 " -rdynamic export all global symbols to dynamic linker\n"
10165 " -r relocatable output\n"
10166 "Debugger options:\n"
10167 " -g generate runtime debug info\n"
10168 #ifdef CONFIG_TCC_BCHECK
10169 " -b compile with built-in memory and bounds checker (implies -g)\n"
10171 " -bt N show N callers in stack traces\n"
10175 #define TCC_OPTION_HAS_ARG 0x0001
10176 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
10178 typedef struct TCCOption
{
10206 TCC_OPTION_nostdinc
,
10207 TCC_OPTION_nostdlib
,
10208 TCC_OPTION_print_search_dirs
,
10209 TCC_OPTION_rdynamic
,
10216 static const TCCOption tcc_options
[] = {
10217 { "h", TCC_OPTION_HELP
, 0 },
10218 { "?", TCC_OPTION_HELP
, 0 },
10219 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
10220 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
10221 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
10222 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
10223 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
10224 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10225 { "bench", TCC_OPTION_bench
, 0 },
10226 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
10227 #ifdef CONFIG_TCC_BCHECK
10228 { "b", TCC_OPTION_b
, 0 },
10230 { "g", TCC_OPTION_g
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10231 { "c", TCC_OPTION_c
, 0 },
10232 { "static", TCC_OPTION_static
, 0 },
10233 { "shared", TCC_OPTION_shared
, 0 },
10234 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
10235 { "run", TCC_OPTION_run
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10236 { "rdynamic", TCC_OPTION_rdynamic
, 0 },
10237 { "r", TCC_OPTION_r
, 0 },
10238 { "Wl,", TCC_OPTION_Wl
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10239 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10240 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10241 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
10242 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10243 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
10244 { "nostdlib", TCC_OPTION_nostdlib
, 0 },
10245 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
10246 { "v", TCC_OPTION_v
, 0 },
10247 { "w", TCC_OPTION_w
, 0 },
10248 { "pipe", TCC_OPTION_pipe
, 0},
10252 /* convert 'str' into an array of space separated strings */
10253 static int expand_args(char ***pargv
, const char *str
)
10262 while (is_space(*str
))
10267 while (*str
!= '\0' && !is_space(*str
))
10270 arg
= tcc_malloc(len
+ 1);
10271 memcpy(arg
, s1
, len
);
10273 dynarray_add((void ***)&argv
, &argc
, arg
);
10279 static char **files
;
10280 static int nb_files
, nb_libraries
;
10281 static int multiple_files
;
10282 static int print_search_dirs
;
10283 static int output_type
;
10284 static int reloc_output
;
10285 static const char *outfile
;
10287 int parse_args(TCCState
*s
, int argc
, char **argv
)
10290 const TCCOption
*popt
;
10291 const char *optarg
, *p1
, *r1
;
10296 if (optind
>= argc
) {
10297 if (nb_files
== 0 && !print_search_dirs
)
10302 r
= argv
[optind
++];
10304 /* add a new file */
10305 dynarray_add((void ***)&files
, &nb_files
, r
);
10306 if (!multiple_files
) {
10308 /* argv[0] will be this file */
10312 /* find option in table (match only the first chars */
10313 popt
= tcc_options
;
10317 error("invalid option -- '%s'", r
);
10330 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
10331 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
10334 if (optind
>= argc
)
10335 error("argument to '%s' is missing", r
);
10336 optarg
= argv
[optind
++];
10344 switch(popt
->index
) {
10345 case TCC_OPTION_HELP
:
10350 if (tcc_add_include_path(s
, optarg
) < 0)
10351 error("too many include paths");
10356 sym
= (char *)optarg
;
10357 value
= strchr(sym
, '=');
10362 tcc_define_symbol(s
, sym
, value
);
10366 tcc_undefine_symbol(s
, optarg
);
10369 tcc_add_library_path(s
, optarg
);
10372 /* set tcc utilities path (mainly for tcc development) */
10373 tcc_lib_path
= optarg
;
10376 dynarray_add((void ***)&files
, &nb_files
, r
);
10379 case TCC_OPTION_bench
:
10382 case TCC_OPTION_bt
:
10383 num_callers
= atoi(optarg
);
10385 #ifdef CONFIG_TCC_BCHECK
10387 do_bounds_check
= 1;
10395 multiple_files
= 1;
10396 output_type
= TCC_OUTPUT_OBJ
;
10398 case TCC_OPTION_static
:
10399 s
->static_link
= 1;
10401 case TCC_OPTION_shared
:
10402 output_type
= TCC_OUTPUT_DLL
;
10405 multiple_files
= 1;
10409 /* generate a .o merging several output files */
10411 output_type
= TCC_OUTPUT_OBJ
;
10413 case TCC_OPTION_nostdinc
:
10416 case TCC_OPTION_nostdlib
:
10419 case TCC_OPTION_print_search_dirs
:
10420 print_search_dirs
= 1;
10422 case TCC_OPTION_run
:
10426 argc1
= expand_args(&argv1
, optarg
);
10428 parse_args(s
, argc1
, argv1
);
10430 multiple_files
= 0;
10431 output_type
= TCC_OUTPUT_MEMORY
;
10435 printf("tcc version %s\n", TCC_VERSION
);
10438 if (tcc_set_flag(s
, optarg
, 1) < 0 && s
->warn_unsupported
)
10439 goto unsupported_option
;
10442 if (tcc_set_warning(s
, optarg
, 1) < 0 &&
10443 s
->warn_unsupported
)
10444 goto unsupported_option
;
10449 case TCC_OPTION_rdynamic
:
10452 case TCC_OPTION_Wl
:
10455 if (strstart(optarg
, "-Ttext,", &p
)) {
10456 s
->text_addr
= strtoul(p
, NULL
, 16);
10457 s
->has_text_addr
= 1;
10458 } else if (strstart(optarg
, "--oformat,", &p
)) {
10459 if (strstart(p
, "elf32-", NULL
)) {
10460 s
->output_format
= TCC_OUTPUT_FORMAT_ELF
;
10461 } else if (!strcmp(p
, "binary")) {
10462 s
->output_format
= TCC_OUTPUT_FORMAT_BINARY
;
10464 #ifdef TCC_TARGET_COFF
10465 if (!strcmp(p
, "coff")) {
10466 s
->output_format
= TCC_OUTPUT_FORMAT_COFF
;
10470 error("target %s not found", p
);
10473 error("unsupported linker option '%s'", optarg
);
10478 if (s
->warn_unsupported
) {
10479 unsupported_option
:
10480 warning("unsupported option '%s'", r
);
10489 int main(int argc
, char **argv
)
10493 int nb_objfiles
, ret
, optind
;
10494 char objfilename
[1024];
10495 int64_t start_time
= 0;
10498 /* on win32, we suppose the lib and includes are at the location
10501 static char path
[1024];
10503 GetModuleFileNameA(NULL
, path
, sizeof path
);
10504 p
= d
= strlwr(path
);
10509 tcc_lib_path
= path
;
10514 output_type
= TCC_OUTPUT_EXE
;
10516 multiple_files
= 1;
10521 print_search_dirs
= 0;
10523 optind
= parse_args(s
, argc
- 1, argv
+ 1) + 1;
10525 if (print_search_dirs
) {
10526 /* enough for Linux kernel */
10527 printf("install: %s/\n", tcc_lib_path
);
10531 nb_objfiles
= nb_files
- nb_libraries
;
10533 /* if outfile provided without other options, we output an
10535 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
10536 output_type
= TCC_OUTPUT_EXE
;
10538 /* check -c consistency : only single file handled. XXX: checks file type */
10539 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
10540 /* accepts only a single input file */
10541 if (nb_objfiles
!= 1)
10542 error("cannot specify multiple files with -c");
10543 if (nb_libraries
!= 0)
10544 error("cannot specify libraries with -c");
10547 /* compute default outfile name */
10548 if (output_type
!= TCC_OUTPUT_MEMORY
&& !outfile
) {
10549 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
10552 pstrcpy(objfilename
, sizeof(objfilename
) - 1,
10553 tcc_basename(files
[0]));
10554 /* add .o extension */
10555 ext
= strrchr(objfilename
, '.');
10557 goto default_outfile
;
10558 strcpy(ext
+ 1, "o");
10561 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
10563 outfile
= objfilename
;
10567 start_time
= getclock_us();
10570 tcc_set_output_type(s
, output_type
);
10572 /* compile or add each files or library */
10573 for(i
= 0;i
< nb_files
; i
++) {
10574 const char *filename
;
10576 filename
= files
[i
];
10577 if (filename
[0] == '-') {
10578 if (tcc_add_library(s
, filename
+ 2) < 0)
10579 error("cannot find %s", filename
);
10581 if (tcc_add_file(s
, filename
) < 0) {
10588 /* free all files */
10593 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
10594 if (total_time
< 0.001)
10595 total_time
= 0.001;
10596 if (total_bytes
< 1)
10598 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
10599 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
10600 total_time
, (int)(total_lines
/ total_time
),
10601 total_bytes
/ total_time
/ 1000000.0);
10604 if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
10605 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
10607 #ifdef TCC_TARGET_PE
10608 if (s
->output_type
!= TCC_OUTPUT_OBJ
) {
10609 ret
= tcc_output_pe(s
, outfile
);
10613 tcc_output_file(s
, outfile
);
10617 /* XXX: cannot do it with bound checking because of the malloc hooks */
10618 if (!do_bounds_check
)
10623 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);