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>
47 #include <sys/ucontext.h>
51 #endif /* !CONFIG_TCCBOOT */
68 /* preprocessor debug */
70 /* include file debug */
78 /* target selection */
79 //#define TCC_TARGET_I386 /* i386 code generator */
80 //#define TCC_TARGET_ARM /* ARMv4 code generator */
81 //#define TCC_TARGET_C67 /* TMS320C67xx code generator */
82 //#define TCC_TARGET_X86_64 /* x86-64 code generator */
84 /* default target is I386 */
85 #if !defined(TCC_TARGET_I386) && !defined(TCC_TARGET_ARM) && \
86 !defined(TCC_TARGET_C67) && !defined(TCC_TARGET_X86_64)
87 #define TCC_TARGET_I386
90 #if !defined(_WIN32) && !defined(TCC_UCLIBC) && !defined(TCC_TARGET_ARM) && \
91 !defined(TCC_TARGET_C67) && !defined(TCC_TARGET_X86_64)
92 #define CONFIG_TCC_BCHECK /* enable bound checking code */
95 #if defined(_WIN32) && !defined(TCC_TARGET_PE)
96 #define CONFIG_TCC_STATIC
99 /* define it to include assembler support */
100 #if !defined(TCC_TARGET_ARM) && !defined(TCC_TARGET_C67) && \
101 !defined(TCC_TARGET_X86_64)
102 #define CONFIG_TCC_ASM
105 /* object format selection */
106 #if defined(TCC_TARGET_C67)
107 #define TCC_TARGET_COFF
116 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
117 executables or dlls */
118 #define CONFIG_TCC_CRT_PREFIX CONFIG_SYSROOT "/usr/lib"
120 #define INCLUDE_STACK_SIZE 32
121 #define IFDEF_STACK_SIZE 64
122 #define VSTACK_SIZE 256
123 #define STRING_MAX_SIZE 1024
124 #define PACK_STACK_SIZE 8
126 #define TOK_HASH_SIZE 8192 /* must be a power of two */
127 #define TOK_ALLOC_INCR 512 /* must be a power of two */
128 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
130 /* token symbol management */
131 typedef struct TokenSym
{
132 struct TokenSym
*hash_next
;
133 struct Sym
*sym_define
; /* direct pointer to define */
134 struct Sym
*sym_label
; /* direct pointer to label */
135 struct Sym
*sym_struct
; /* direct pointer to structure */
136 struct Sym
*sym_identifier
; /* direct pointer to identifier */
137 int tok
; /* token number */
143 typedef unsigned short nwchar_t
;
145 typedef int nwchar_t
;
148 typedef struct CString
{
149 int size
; /* size in bytes */
150 void *data
; /* either 'char *' or 'nwchar_t *' */
152 void *data_allocated
; /* if non NULL, data has been malloced */
155 /* type definition */
156 typedef struct CType
{
162 typedef union CValue
{
168 unsigned int ul
; /* address (should be unsigned long on 64 bit cpu) */
170 unsigned long long ull
;
171 struct CString
*cstr
;
177 typedef struct SValue
{
178 CType type
; /* type */
179 unsigned short r
; /* register + flags */
180 unsigned short r2
; /* second register, used for 'long long'
181 type. If not used, set to VT_CONST */
182 CValue c
; /* constant, if VT_CONST */
183 struct Sym
*sym
; /* symbol, if (VT_SYM | VT_CONST) */
186 /* symbol management */
188 int v
; /* symbol token */
189 long r
; /* associated register */
190 long c
; /* associated number */
191 CType type
; /* associated type */
192 struct Sym
*next
; /* next related symbol */
193 struct Sym
*prev
; /* prev symbol in stack */
194 struct Sym
*prev_tok
; /* previous symbol for this token */
197 /* section definition */
198 /* XXX: use directly ELF structure for parameters ? */
199 /* special flag to indicate that the section should not be linked to
201 #define SHF_PRIVATE 0x80000000
203 typedef struct Section
{
204 unsigned long data_offset
; /* current data offset */
205 unsigned char *data
; /* section data */
206 unsigned long data_allocated
; /* used for realloc() handling */
207 int sh_name
; /* elf section name (only used during output) */
208 int sh_num
; /* elf section number */
209 int sh_type
; /* elf section type */
210 int sh_flags
; /* elf section flags */
211 int sh_info
; /* elf section info */
212 int sh_addralign
; /* elf section alignment */
213 int sh_entsize
; /* elf entry size */
214 unsigned long sh_size
; /* section size (only used during output) */
215 unsigned long sh_addr
; /* address at which the section is relocated */
216 unsigned long sh_offset
; /* file offset */
217 int nb_hashed_syms
; /* used to resize the hash table */
218 struct Section
*link
; /* link to another section */
219 struct Section
*reloc
; /* corresponding section for relocation, if any */
220 struct Section
*hash
; /* hash table for symbols */
221 struct Section
*next
;
222 char name
[1]; /* section name */
225 typedef struct DLLReference
{
231 /* GNUC attribute definition */
232 typedef struct AttributeDef
{
236 int func_attr
; /* calling convention, exports, ... */
239 /* -------------------------------------------------- */
240 /* gr: wrappers for casting sym->r for other purposes */
248 #define FUNC_CALL(r) (((func_attr_t*)&(r))->func_call)
249 #define FUNC_EXPORT(r) (((func_attr_t*)&(r))->func_export)
250 #define FUNC_ARGS(r) (((func_attr_t*)&(r))->func_args)
251 #define INLINE_DEF(r) (*(int **)&(r))
252 /* -------------------------------------------------- */
254 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
255 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
256 #define SYM_FIRST_ANOM 0x10000000 /* first anonymous sym */
258 /* stored in 'Sym.c' field */
259 #define FUNC_NEW 1 /* ansi function prototype */
260 #define FUNC_OLD 2 /* old function prototype */
261 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
263 /* stored in 'Sym.r' field */
264 #define FUNC_CDECL 0 /* standard c call */
265 #define FUNC_STDCALL 1 /* pascal c call */
266 #define FUNC_FASTCALL1 2 /* first param in %eax */
267 #define FUNC_FASTCALL2 3 /* first parameters in %eax, %edx */
268 #define FUNC_FASTCALL3 4 /* first parameter in %eax, %edx, %ecx */
269 #define FUNC_FASTCALLW 5 /* first parameter in %ecx, %edx */
271 /* field 'Sym.t' for macros */
272 #define MACRO_OBJ 0 /* object like macro */
273 #define MACRO_FUNC 1 /* function like macro */
275 /* field 'Sym.r' for C labels */
276 #define LABEL_DEFINED 0 /* label is defined */
277 #define LABEL_FORWARD 1 /* label is forward defined */
278 #define LABEL_DECLARED 2 /* label is declared but never used */
280 /* type_decl() types */
281 #define TYPE_ABSTRACT 1 /* type without variable */
282 #define TYPE_DIRECT 2 /* type with variable */
284 #define IO_BUF_SIZE 8192
286 typedef struct BufferedFile
{
290 int line_num
; /* current line number - here to simplify code */
291 int ifndef_macro
; /* #ifndef macro / #endif search */
292 int ifndef_macro_saved
; /* saved ifndef_macro */
293 int *ifdef_stack_ptr
; /* ifdef_stack value at the start of the file */
294 char inc_type
; /* type of include */
295 char inc_filename
[512]; /* filename specified by the user */
296 char filename
[1024]; /* current filename - here to simplify code */
297 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
300 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
301 #define CH_EOF (-1) /* end of file */
303 /* parsing state (used to save parser state to reparse part of the
304 source several times) */
305 typedef struct ParseState
{
312 /* used to record tokens */
313 typedef struct TokenString
{
320 /* include file cache, used to find files faster and also to eliminate
321 inclusion if the include file is protected by #ifndef ... #endif */
322 typedef struct CachedInclude
{
324 int hash_next
; /* -1 if none */
325 char type
; /* '"' or '>' to give include type */
326 char filename
[1]; /* path specified in #include */
329 #define CACHED_INCLUDES_HASH_SIZE 512
332 static struct BufferedFile
*file
;
334 static CString tok_spaces
; /* spaces before current token */
336 static CString tokcstr
; /* current parsed string, if any */
337 /* additional informations about token */
338 static int tok_flags
;
339 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
340 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
341 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
342 #define TOK_FLAG_EOF 0x0008 /* end of file */
344 static int *macro_ptr
, *macro_ptr_allocated
;
345 static int *unget_saved_macro_ptr
;
346 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
347 static int unget_buffer_enabled
;
348 static int parse_flags
;
349 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
350 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
351 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
352 token. line feed is also
354 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
356 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
357 static Section
*cur_text_section
; /* current section where function code is
359 #ifdef CONFIG_TCC_ASM
360 static Section
*last_text_section
; /* to handle .previous asm directive */
362 /* bound check related sections */
363 static Section
*bounds_section
; /* contains global data bound description */
364 static Section
*lbounds_section
; /* contains local data bound description */
365 /* symbol sections */
366 static Section
*symtab_section
, *strtab_section
;
369 static Section
*stab_section
, *stabstr_section
;
371 /* loc : local variable index
372 ind : output code index
374 anon_sym: anonymous symbol index
376 static int rsym
, anon_sym
, ind
, loc
;
377 /* expression generation modifiers */
378 static int const_wanted
; /* true if constant wanted */
379 static int nocode_wanted
; /* true if no code generation wanted for an expression */
380 static int global_expr
; /* true if compound literals must be allocated
381 globally (used during initializers parsing */
382 static CType func_vt
; /* current function return type (used by return
385 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
386 static int tok_ident
;
387 static TokenSym
**table_ident
;
388 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
389 static char token_buf
[STRING_MAX_SIZE
+ 1];
390 static char *funcname
;
391 static Sym
*global_stack
, *local_stack
;
392 static Sym
*define_stack
;
393 static Sym
*global_label_stack
, *local_label_stack
;
394 /* symbol allocator */
395 #define SYM_POOL_NB (8192 / sizeof(Sym))
396 static Sym
*sym_free_first
;
397 static void **sym_pools
;
398 static int nb_sym_pools
;
400 static SValue vstack
[VSTACK_SIZE
], *vtop
;
401 /* some predefined types */
402 static CType char_pointer_type
, func_old_type
, int_type
;
403 /* true if isid(c) || isnum(c) */
404 static unsigned char isidnum_table
[256-CH_EOF
];
406 /* display some information during compilation */
407 static int verbose
= 0;
409 /* compile with debug symbol (and use them if error during execution) */
410 static int do_debug
= 0;
412 /* compile with built-in memory and bounds checker */
413 static int do_bounds_check
= 0;
415 /* display benchmark infos */
417 static int do_bench
= 0;
419 static int total_lines
;
420 static int total_bytes
;
422 /* use GNU C extensions */
423 static int gnu_ext
= 1;
425 /* use Tiny C extensions */
426 static int tcc_ext
= 1;
428 /* max number of callers shown if error */
429 static int num_callers
= 6;
430 static const char **rt_bound_error_msg
;
432 /* XXX: get rid of this ASAP */
433 static struct TCCState
*tcc_state
;
435 /* give the path of the tcc libraries */
436 static const char *tcc_lib_path
= CONFIG_TCCDIR
;
441 BufferedFile
**include_stack_ptr
;
442 int *ifdef_stack_ptr
;
444 /* include file handling */
445 char **include_paths
;
446 int nb_include_paths
;
447 char **sysinclude_paths
;
448 int nb_sysinclude_paths
;
449 CachedInclude
**cached_includes
;
450 int nb_cached_includes
;
452 char **library_paths
;
453 int nb_library_paths
;
455 /* array of all loaded dlls (including those referenced by loaded
457 DLLReference
**loaded_dlls
;
462 int nb_sections
; /* number of sections, including first dummy section */
467 unsigned long *got_offsets
;
469 /* give the correspondance from symtab indexes to dynsym indexes */
470 int *symtab_to_dynsym
;
472 /* temporary dynamic symbol sections (for dll loading) */
473 Section
*dynsymtab_section
;
474 /* exported dynamic symbol section */
477 int nostdinc
; /* if true, no standard headers are added */
478 int nostdlib
; /* if true, no standard libraries are added */
480 int nocommon
; /* if true, do not use common symbols for .bss data */
482 /* if true, static linking is performed */
485 /* soname as specified on the command line (-soname) */
488 /* if true, all symbols are exported */
491 /* if true, only link in referenced objects from archive */
494 /* address of text section */
495 unsigned long text_addr
;
498 /* output format, see TCC_OUTPUT_FORMAT_xxx */
501 /* C language options */
502 int char_is_unsigned
;
503 int leading_underscore
;
505 /* warning switches */
506 int warn_write_strings
;
507 int warn_unsupported
;
510 int warn_implicit_function_declaration
;
514 void (*error_func
)(void *opaque
, const char *msg
);
515 int error_set_jmp_enabled
;
516 jmp_buf error_jmp_buf
;
519 /* tiny assembler state */
522 /* see include_stack_ptr */
523 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
525 /* see ifdef_stack_ptr */
526 int ifdef_stack
[IFDEF_STACK_SIZE
];
528 /* see cached_includes */
529 int cached_includes_hash
[CACHED_INCLUDES_HASH_SIZE
];
532 int pack_stack
[PACK_STACK_SIZE
];
535 /* output file for preprocessing */
538 #ifdef TCC_TARGET_X86_64
539 /* buffer to store jump tables */
545 /* The current value can be: */
546 #define VT_VALMASK 0x00ff
547 #define VT_CONST 0x00f0 /* constant in vc
548 (must be first non register value) */
549 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
550 #define VT_LOCAL 0x00f2 /* offset on stack */
551 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
552 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
553 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
554 #define VT_LVAL 0x0100 /* var is an lvalue */
555 #define VT_SYM 0x0200 /* a symbol value is added */
556 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
557 char/short stored in integer registers) */
558 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
559 dereferencing value */
560 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
561 bounding function call point is in vc */
562 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
563 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
564 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
565 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
568 #define VT_INT 0 /* integer type */
569 #define VT_BYTE 1 /* signed byte type */
570 #define VT_SHORT 2 /* short type */
571 #define VT_VOID 3 /* void type */
572 #define VT_PTR 4 /* pointer */
573 #define VT_ENUM 5 /* enum definition */
574 #define VT_FUNC 6 /* function type */
575 #define VT_STRUCT 7 /* struct/union definition */
576 #define VT_FLOAT 8 /* IEEE float */
577 #define VT_DOUBLE 9 /* IEEE double */
578 #define VT_LDOUBLE 10 /* IEEE long double */
579 #define VT_BOOL 11 /* ISOC99 boolean type */
580 #define VT_LLONG 12 /* 64 bit integer */
581 #define VT_LONG 13 /* long integer (NEVER USED as type, only
583 #define VT_BTYPE 0x000f /* mask for basic type */
584 #define VT_UNSIGNED 0x0010 /* unsigned type */
585 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
586 #define VT_BITFIELD 0x0040 /* bitfield modifier */
587 #define VT_CONSTANT 0x0800 /* const modifier */
588 #define VT_VOLATILE 0x1000 /* volatile modifier */
589 #define VT_SIGNED 0x2000 /* signed type */
592 #define VT_EXTERN 0x00000080 /* extern definition */
593 #define VT_STATIC 0x00000100 /* static variable */
594 #define VT_TYPEDEF 0x00000200 /* typedef definition */
595 #define VT_INLINE 0x00000400 /* inline definition */
597 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
599 /* type mask (except storage) */
600 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
601 #define VT_TYPE (~(VT_STORAGE))
605 /* warning: the following compare tokens depend on i386 asm code */
612 #define TOK_Nset 0x98
613 #define TOK_Nclear 0x99
619 #define TOK_LAND 0xa0
623 #define TOK_MID 0xa3 /* inc/dec, to void constant */
625 #define TOK_UDIV 0xb0 /* unsigned division */
626 #define TOK_UMOD 0xb1 /* unsigned modulo */
627 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
628 #define TOK_CINT 0xb3 /* number in tokc */
629 #define TOK_CCHAR 0xb4 /* char constant in tokc */
630 #define TOK_STR 0xb5 /* pointer to string in tokc */
631 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
632 #define TOK_LCHAR 0xb7
633 #define TOK_LSTR 0xb8
634 #define TOK_CFLOAT 0xb9 /* float constant */
635 #define TOK_LINENUM 0xba /* line number info */
636 #define TOK_CDOUBLE 0xc0 /* double constant */
637 #define TOK_CLDOUBLE 0xc1 /* long double constant */
638 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
639 #define TOK_ADDC1 0xc3 /* add with carry generation */
640 #define TOK_ADDC2 0xc4 /* add with carry use */
641 #define TOK_SUBC1 0xc5 /* add with carry generation */
642 #define TOK_SUBC2 0xc6 /* add with carry use */
643 #define TOK_CUINT 0xc8 /* unsigned int constant */
644 #define TOK_CLLONG 0xc9 /* long long constant */
645 #define TOK_CULLONG 0xca /* unsigned long long constant */
646 #define TOK_ARROW 0xcb
647 #define TOK_DOTS 0xcc /* three dots */
648 #define TOK_SHR 0xcd /* unsigned shift right */
649 #define TOK_PPNUM 0xce /* preprocessor number */
651 #define TOK_SHL 0x01 /* shift left */
652 #define TOK_SAR 0x02 /* signed shift right */
654 /* assignement operators : normal operator or 0x80 */
655 #define TOK_A_MOD 0xa5
656 #define TOK_A_AND 0xa6
657 #define TOK_A_MUL 0xaa
658 #define TOK_A_ADD 0xab
659 #define TOK_A_SUB 0xad
660 #define TOK_A_DIV 0xaf
661 #define TOK_A_XOR 0xde
662 #define TOK_A_OR 0xfc
663 #define TOK_A_SHL 0x81
664 #define TOK_A_SAR 0x82
667 #define offsetof(type, field) ((size_t) &((type *)0)->field)
671 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
674 /* WARNING: the content of this string encodes token numbers */
675 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";
677 #define TOK_EOF (-1) /* end of file */
678 #define TOK_LINEFEED 10 /* line feed */
680 /* all identificators and strings have token above that */
681 #define TOK_IDENT 256
683 /* only used for i386 asm opcodes definitions */
684 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
687 DEF(TOK_ASM_ ## x ## b, #x "b") \
688 DEF(TOK_ASM_ ## x ## w, #x "w") \
689 DEF(TOK_ASM_ ## x ## l, #x "l") \
690 DEF(TOK_ASM_ ## x, #x)
693 DEF(TOK_ASM_ ## x ## w, #x "w") \
694 DEF(TOK_ASM_ ## x ## l, #x "l") \
695 DEF(TOK_ASM_ ## x, #x)
698 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
699 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
700 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
701 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
704 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
705 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
708 #define DEF_ASMTEST(x) \
740 #define TOK_ASM_int TOK_INT
743 TOK_LAST
= TOK_IDENT
- 1,
744 #define DEF(id, str) id,
749 static const char tcc_keywords
[] =
750 #define DEF(id, str) str "\0"
755 #define TOK_UIDENT TOK_DEFINE
758 #define snprintf _snprintf
759 #define vsnprintf _vsnprintf
761 #define strtold (long double)strtod
762 #define strtof (float)strtod
763 #define strtoll (long long)strtol
765 #elif defined(TCC_UCLIBC) || defined(__FreeBSD__) || defined(__DragonFly__) \
766 || defined(__OpenBSD__)
767 /* currently incorrect */
768 long double strtold(const char *nptr
, char **endptr
)
770 return (long double)strtod(nptr
, endptr
);
772 float strtof(const char *nptr
, char **endptr
)
774 return (float)strtod(nptr
, endptr
);
777 /* XXX: need to define this to use them in non ISOC99 context */
778 extern float strtof (const char *__nptr
, char **__endptr
);
779 extern long double strtold (const char *__nptr
, char **__endptr
);
782 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
783 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
784 static char *tcc_basename(const char *name
);
785 static char *tcc_fileextension (const char *p
);
787 static void next(void);
788 static void next_nomacro(void);
789 static void parse_expr_type(CType
*type
);
790 static void expr_type(CType
*type
);
791 static void unary_type(CType
*type
);
792 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
793 int case_reg
, int is_expr
);
794 static int expr_const(void);
795 static void expr_eq(void);
796 static void gexpr(void);
797 static void gen_inline_functions(void);
798 static void decl(int l
);
799 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
800 int first
, int size_only
);
801 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
802 int has_init
, int v
, int scope
);
804 void gv2(int rc1
, int rc2
);
805 void move_reg(int r
, int s
);
806 void save_regs(int n
);
807 void save_reg(int r
);
812 int get_reg_ex(int rc
,int rc2
);
815 struct macro_level
*prev
;
819 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
820 const int *macro_str
, struct macro_level
**can_read_stream
);
822 void force_charshort_cast(int t
);
823 static void gen_cast(CType
*type
);
825 static Sym
*sym_find(int v
);
826 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
829 static int type_size(CType
*type
, int *a
);
830 static inline CType
*pointed_type(CType
*type
);
831 static int pointed_size(CType
*type
);
832 static int lvalue_type(int t
);
833 static int parse_btype(CType
*type
, AttributeDef
*ad
);
834 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
835 static int compare_types(CType
*type1
, CType
*type2
, int unqualified
);
836 static int is_compatible_types(CType
*type1
, CType
*type2
);
837 static int is_compatible_parameter_types(CType
*type1
, CType
*type2
);
839 int ieee_finite(double d
);
840 void error(const char *fmt
, ...);
844 void lexpand_nr(void);
845 static void vpush_global_sym(CType
*type
, int v
);
846 void vset(CType
*type
, int r
, int v
);
847 void type_to_str(char *buf
, int buf_size
,
848 CType
*type
, const char *varstr
);
849 char *get_tok_str(int v
, CValue
*cv
);
850 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
851 unsigned long offset
, unsigned long size
);
852 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
854 /* section generation */
855 static void section_realloc(Section
*sec
, unsigned long new_size
);
856 static void *section_ptr_add(Section
*sec
, unsigned long size
);
857 static void put_extern_sym(Sym
*sym
, Section
*section
,
858 unsigned long value
, unsigned long size
);
859 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
860 static int put_elf_str(Section
*s
, const char *sym
);
861 static int put_elf_sym(Section
*s
,
862 unsigned long value
, unsigned long size
,
863 int info
, int other
, int shndx
, const char *name
);
864 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
865 int info
, int other
, int sh_num
, const char *name
);
866 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
867 int type
, int symbol
);
868 static void put_stabs(const char *str
, int type
, int other
, int desc
,
869 unsigned long value
);
870 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
871 unsigned long value
, Section
*sec
, int sym_index
);
872 static void put_stabn(int type
, int other
, int desc
, int value
);
873 static void put_stabd(int type
, int other
, int desc
);
874 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
876 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
877 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
878 #define AFF_PREPROCESS 0x0004 /* preprocess file */
879 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
882 int tcc_output_coff(TCCState
*s1
, FILE *f
);
885 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
);
886 int pe_load_def_file(struct TCCState
*s1
, int fd
);
887 int pe_test_res_file(void *v
, int size
);
888 int pe_load_res_file(struct TCCState
*s1
, int fd
);
889 void pe_add_runtime(struct TCCState
*s1
);
890 void pe_guess_outfile(char *objfilename
, int output_type
);
891 int pe_output_file(struct TCCState
*s1
, const char *filename
);
895 #ifdef CONFIG_TCC_ASM
897 typedef struct ExprValue
{
902 #define MAX_ASM_OPERANDS 30
904 typedef struct ASMOperand
{
905 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
907 char asm_str
[16]; /* computed asm string for operand */
908 SValue
*vt
; /* C value of the expression */
909 int ref_index
; /* if >= 0, gives reference to a output constraint */
910 int input_index
; /* if >= 0, gives reference to an input constraint */
911 int priority
; /* priority, used to assign registers */
912 int reg
; /* if >= 0, register number used for this operand */
913 int is_llong
; /* true if double register value */
914 int is_memory
; /* true if memory operand */
915 int is_rw
; /* for '+' modifier */
918 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
919 static int asm_int_expr(TCCState
*s1
);
920 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
921 const char *name
, const char **pp
);
923 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
927 static void asm_instr(void);
928 static void asm_global_instr(void);
930 /* true if float/double/long double type */
931 static inline int is_float(int t
)
935 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
938 #ifdef TCC_TARGET_I386
939 #include "i386-gen.c"
942 #ifdef TCC_TARGET_ARM
946 #ifdef TCC_TARGET_C67
950 #ifdef TCC_TARGET_X86_64
951 #include "x86_64-gen.c"
954 #ifdef CONFIG_TCC_STATIC
956 #define RTLD_LAZY 0x001
957 #define RTLD_NOW 0x002
958 #define RTLD_GLOBAL 0x100
959 #define RTLD_DEFAULT NULL
961 /* dummy function for profiling */
962 void *dlopen(const char *filename
, int flag
)
967 const char *dlerror(void)
972 typedef struct TCCSyms
{
977 #define TCCSYM(a) { #a, &a, },
979 /* add the symbol you want here if no dynamic linking is done */
980 static TCCSyms tcc_syms
[] = {
981 #if !defined(CONFIG_TCCBOOT)
990 void *resolve_sym(TCCState
*s1
, const char *symbol
, int type
)
994 while (p
->str
!= NULL
) {
995 if (!strcmp(p
->str
, symbol
))
1002 #elif !defined(_WIN32)
1006 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
)
1008 return dlsym(RTLD_DEFAULT
, sym
);
1013 /********************************************************/
1015 /* we use our own 'finite' function to avoid potential problems with
1016 non standard math libs */
1017 /* XXX: endianness dependent */
1018 int ieee_finite(double d
)
1021 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
1024 /* copy a string and truncate it. */
1025 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
1032 q_end
= buf
+ buf_size
- 1;
1044 /* strcat and truncate. */
1045 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
1050 pstrcpy(buf
+ len
, buf_size
- len
, s
);
1055 static int strstart(const char *str
, const char *val
, const char **ptr
)
1060 while (*q
!= '\0') {
1072 /* extract the basename of a file */
1073 static char *tcc_basename(const char *name
)
1075 char *p
= strchr(name
, 0);
1086 static char *tcc_fileextension (const char *name
)
1088 char *b
= tcc_basename(name
);
1089 char *e
= strrchr(b
, '.');
1090 return e
? e
: strchr(b
, 0);
1094 char *normalize_slashes(char *path
)
1097 for (p
= path
; *p
; ++p
)
1103 char *w32_tcc_lib_path(void)
1105 /* on win32, we suppose the lib and includes are at the location
1107 char path
[1024], *p
;
1108 GetModuleFileNameA(NULL
, path
, sizeof path
);
1109 p
= tcc_basename(normalize_slashes(strlwr(path
)));
1110 if (p
- 5 > path
&& 0 == strncmp(p
- 5, "/bin/", 5))
1115 return strdup(path
);
1119 void set_pages_executable(void *ptr
, unsigned long length
)
1122 unsigned long old_protect
;
1123 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
1125 unsigned long start
, end
;
1126 start
= (unsigned long)ptr
& ~(PAGESIZE
- 1);
1127 end
= (unsigned long)ptr
+ length
;
1128 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
1129 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
1133 /* memory management */
1137 unsigned malloc_usable_size(void*);
1140 static inline void tcc_free(void *ptr
)
1143 mem_cur_size
-= malloc_usable_size(ptr
);
1148 static void *tcc_malloc(unsigned long size
)
1153 error("memory full");
1155 mem_cur_size
+= malloc_usable_size(ptr
);
1156 if (mem_cur_size
> mem_max_size
)
1157 mem_max_size
= mem_cur_size
;
1162 static void *tcc_mallocz(unsigned long size
)
1165 ptr
= tcc_malloc(size
);
1166 memset(ptr
, 0, size
);
1170 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
1174 mem_cur_size
-= malloc_usable_size(ptr
);
1176 ptr1
= realloc(ptr
, size
);
1178 /* NOTE: count not correct if alloc error, but not critical */
1179 mem_cur_size
+= malloc_usable_size(ptr1
);
1180 if (mem_cur_size
> mem_max_size
)
1181 mem_max_size
= mem_cur_size
;
1186 static char *tcc_strdup(const char *str
)
1189 ptr
= tcc_malloc(strlen(str
) + 1);
1194 #define free(p) use_tcc_free(p)
1195 #define malloc(s) use_tcc_malloc(s)
1196 #define realloc(p, s) use_tcc_realloc(p, s)
1198 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
1205 /* every power of two we double array size */
1206 if ((nb
& (nb
- 1)) == 0) {
1211 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
1213 error("memory full");
1220 static void dynarray_reset(void *pp
, int *n
)
1223 for (p
= *(void***)pp
; *n
; ++p
, --*n
)
1226 tcc_free(*(void**)pp
);
1230 /* symbol allocator */
1231 static Sym
*__sym_malloc(void)
1233 Sym
*sym_pool
, *sym
, *last_sym
;
1236 sym_pool
= tcc_malloc(SYM_POOL_NB
* sizeof(Sym
));
1237 dynarray_add(&sym_pools
, &nb_sym_pools
, sym_pool
);
1239 last_sym
= sym_free_first
;
1241 for(i
= 0; i
< SYM_POOL_NB
; i
++) {
1242 sym
->next
= last_sym
;
1246 sym_free_first
= last_sym
;
1250 static inline Sym
*sym_malloc(void)
1253 sym
= sym_free_first
;
1255 sym
= __sym_malloc();
1256 sym_free_first
= sym
->next
;
1260 static inline void sym_free(Sym
*sym
)
1262 sym
->next
= sym_free_first
;
1263 sym_free_first
= sym
;
1266 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
1270 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
1271 strcpy(sec
->name
, name
);
1272 sec
->sh_type
= sh_type
;
1273 sec
->sh_flags
= sh_flags
;
1281 sec
->sh_addralign
= 4;
1284 sec
->sh_addralign
= 1;
1287 sec
->sh_addralign
= 32; /* default conservative alignment */
1291 /* only add section if not private */
1292 if (!(sh_flags
& SHF_PRIVATE
)) {
1293 sec
->sh_num
= s1
->nb_sections
;
1294 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
1299 static void free_section(Section
*s
)
1301 if (s
->link
&& (s
->link
->sh_flags
& SHF_PRIVATE
))
1302 free_section(s
->link
);
1303 if (s
->hash
&& (s
->hash
->sh_flags
& SHF_PRIVATE
))
1304 s
->hash
->link
= NULL
, free_section(s
->hash
);
1309 /* realloc section and set its content to zero */
1310 static void section_realloc(Section
*sec
, unsigned long new_size
)
1313 unsigned char *data
;
1315 size
= sec
->data_allocated
;
1318 while (size
< new_size
)
1320 data
= tcc_realloc(sec
->data
, size
);
1322 error("memory full");
1323 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1325 sec
->data_allocated
= size
;
1328 /* reserve at least 'size' bytes in section 'sec' from
1329 sec->data_offset. */
1330 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1332 unsigned long offset
, offset1
;
1334 offset
= sec
->data_offset
;
1335 offset1
= offset
+ size
;
1336 if (offset1
> sec
->data_allocated
)
1337 section_realloc(sec
, offset1
);
1338 sec
->data_offset
= offset1
;
1339 return sec
->data
+ offset
;
1342 /* return a reference to a section, and create it if it does not
1344 Section
*find_section(TCCState
*s1
, const char *name
)
1348 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1349 sec
= s1
->sections
[i
];
1350 if (!strcmp(name
, sec
->name
))
1353 /* sections are created as PROGBITS */
1354 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1357 #define SECTION_ABS ((void *)1)
1359 /* update sym->c so that it points to an external symbol in section
1360 'section' with value 'value' */
1361 static void put_extern_sym2(Sym
*sym
, Section
*section
,
1362 unsigned long value
, unsigned long size
,
1363 int can_add_underscore
)
1365 int sym_type
, sym_bind
, sh_num
, info
, other
, attr
;
1370 if (section
== NULL
)
1372 else if (section
== SECTION_ABS
)
1375 sh_num
= section
->sh_num
;
1379 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
) {
1380 sym_type
= STT_FUNC
;
1381 #ifdef TCC_TARGET_PE
1383 attr
= sym
->type
.ref
->r
;
1384 if (FUNC_EXPORT(attr
))
1386 if (FUNC_CALL(attr
) == FUNC_STDCALL
)
1390 sym_type
= STT_OBJECT
;
1393 if (sym
->type
.t
& VT_STATIC
)
1394 sym_bind
= STB_LOCAL
;
1396 sym_bind
= STB_GLOBAL
;
1399 name
= get_tok_str(sym
->v
, NULL
);
1400 #ifdef CONFIG_TCC_BCHECK
1401 if (do_bounds_check
) {
1404 /* XXX: avoid doing that for statics ? */
1405 /* if bound checking is activated, we change some function
1406 names by adding the "__bound" prefix */
1409 /* XXX: we rely only on malloc hooks */
1422 strcpy(buf
, "__bound_");
1430 #ifdef TCC_TARGET_PE
1431 if ((other
& 2) && can_add_underscore
) {
1432 sprintf(buf1
, "_%s@%d", name
, FUNC_ARGS(attr
));
1436 if (tcc_state
->leading_underscore
&& can_add_underscore
) {
1438 pstrcpy(buf1
+ 1, sizeof(buf1
) - 1, name
);
1441 info
= ELFW(ST_INFO
)(sym_bind
, sym_type
);
1442 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, other
, sh_num
, name
);
1444 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
1445 esym
->st_value
= value
;
1446 esym
->st_size
= size
;
1447 esym
->st_shndx
= sh_num
;
1448 esym
->st_other
|= other
;
1452 static void put_extern_sym(Sym
*sym
, Section
*section
,
1453 unsigned long value
, unsigned long size
)
1455 put_extern_sym2(sym
, section
, value
, size
, 1);
1458 /* add a new relocation entry to symbol 'sym' in section 's' */
1459 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1462 put_extern_sym(sym
, NULL
, 0, 0);
1463 /* now we can add ELF relocation info */
1464 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1467 static inline int isid(int c
)
1469 return (c
>= 'a' && c
<= 'z') ||
1470 (c
>= 'A' && c
<= 'Z') ||
1474 static inline int isnum(int c
)
1476 return c
>= '0' && c
<= '9';
1479 static inline int isoct(int c
)
1481 return c
>= '0' && c
<= '7';
1484 static inline int toup(int c
)
1486 if (c
>= 'a' && c
<= 'z')
1487 return c
- 'a' + 'A';
1492 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1496 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1499 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1503 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1507 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1514 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1515 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1516 (*f
)->filename
, (*f
)->line_num
);
1517 if (file
->line_num
> 0) {
1518 strcat_printf(buf
, sizeof(buf
),
1519 "%s:%d: ", file
->filename
, file
->line_num
);
1521 strcat_printf(buf
, sizeof(buf
),
1522 "%s: ", file
->filename
);
1525 strcat_printf(buf
, sizeof(buf
),
1529 strcat_printf(buf
, sizeof(buf
), "warning: ");
1530 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1532 if (!s1
->error_func
) {
1533 /* default case: stderr */
1534 fprintf(stderr
, "%s\n", buf
);
1536 s1
->error_func(s1
->error_opaque
, buf
);
1538 if (!is_warning
|| s1
->warn_error
)
1543 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1544 void (*error_func
)(void *opaque
, const char *msg
))
1546 s
->error_opaque
= error_opaque
;
1547 s
->error_func
= error_func
;
1551 /* error without aborting current compilation */
1552 void error_noabort(const char *fmt
, ...)
1554 TCCState
*s1
= tcc_state
;
1558 error1(s1
, 0, fmt
, ap
);
1562 void error(const char *fmt
, ...)
1564 TCCState
*s1
= tcc_state
;
1568 error1(s1
, 0, fmt
, ap
);
1570 /* better than nothing: in some cases, we accept to handle errors */
1571 if (s1
->error_set_jmp_enabled
) {
1572 longjmp(s1
->error_jmp_buf
, 1);
1574 /* XXX: eliminate this someday */
1579 void expect(const char *msg
)
1581 error("%s expected", msg
);
1584 void warning(const char *fmt
, ...)
1586 TCCState
*s1
= tcc_state
;
1593 error1(s1
, 1, fmt
, ap
);
1600 error("'%c' expected", c
);
1604 static void test_lvalue(void)
1606 if (!(vtop
->r
& VT_LVAL
))
1610 /* allocate a new token */
1611 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1613 TokenSym
*ts
, **ptable
;
1616 if (tok_ident
>= SYM_FIRST_ANOM
)
1617 error("memory full");
1619 /* expand token table if needed */
1620 i
= tok_ident
- TOK_IDENT
;
1621 if ((i
% TOK_ALLOC_INCR
) == 0) {
1622 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1624 error("memory full");
1625 table_ident
= ptable
;
1628 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1629 table_ident
[i
] = ts
;
1630 ts
->tok
= tok_ident
++;
1631 ts
->sym_define
= NULL
;
1632 ts
->sym_label
= NULL
;
1633 ts
->sym_struct
= NULL
;
1634 ts
->sym_identifier
= NULL
;
1636 ts
->hash_next
= NULL
;
1637 memcpy(ts
->str
, str
, len
);
1638 ts
->str
[len
] = '\0';
1643 #define TOK_HASH_INIT 1
1644 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1646 /* find a token and add it if not found */
1647 static TokenSym
*tok_alloc(const char *str
, int len
)
1649 TokenSym
*ts
, **pts
;
1655 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1656 h
&= (TOK_HASH_SIZE
- 1);
1658 pts
= &hash_ident
[h
];
1663 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1665 pts
= &(ts
->hash_next
);
1667 return tok_alloc_new(pts
, str
, len
);
1670 /* CString handling */
1672 static void cstr_realloc(CString
*cstr
, int new_size
)
1677 size
= cstr
->size_allocated
;
1679 size
= 8; /* no need to allocate a too small first string */
1680 while (size
< new_size
)
1682 data
= tcc_realloc(cstr
->data_allocated
, size
);
1684 error("memory full");
1685 cstr
->data_allocated
= data
;
1686 cstr
->size_allocated
= size
;
1691 static inline void cstr_ccat(CString
*cstr
, int ch
)
1694 size
= cstr
->size
+ 1;
1695 if (size
> cstr
->size_allocated
)
1696 cstr_realloc(cstr
, size
);
1697 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1701 static void cstr_cat(CString
*cstr
, const char *str
)
1713 /* add a wide char */
1714 static void cstr_wccat(CString
*cstr
, int ch
)
1717 size
= cstr
->size
+ sizeof(nwchar_t
);
1718 if (size
> cstr
->size_allocated
)
1719 cstr_realloc(cstr
, size
);
1720 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
1724 static void cstr_new(CString
*cstr
)
1726 memset(cstr
, 0, sizeof(CString
));
1729 /* free string and reset it to NULL */
1730 static void cstr_free(CString
*cstr
)
1732 tcc_free(cstr
->data_allocated
);
1736 #define cstr_reset(cstr) cstr_free(cstr)
1738 /* XXX: unicode ? */
1739 static void add_char(CString
*cstr
, int c
)
1741 if (c
== '\'' || c
== '\"' || c
== '\\') {
1742 /* XXX: could be more precise if char or string */
1743 cstr_ccat(cstr
, '\\');
1745 if (c
>= 32 && c
<= 126) {
1748 cstr_ccat(cstr
, '\\');
1750 cstr_ccat(cstr
, 'n');
1752 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1753 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1754 cstr_ccat(cstr
, '0' + (c
& 7));
1759 /* XXX: buffer overflow */
1760 /* XXX: float tokens */
1761 char *get_tok_str(int v
, CValue
*cv
)
1763 static char buf
[STRING_MAX_SIZE
+ 1];
1764 static CString cstr_buf
;
1770 /* NOTE: to go faster, we give a fixed buffer for small strings */
1771 cstr_reset(&cstr_buf
);
1772 cstr_buf
.data
= buf
;
1773 cstr_buf
.size_allocated
= sizeof(buf
);
1779 /* XXX: not quite exact, but only useful for testing */
1780 sprintf(p
, "%u", cv
->ui
);
1784 /* XXX: not quite exact, but only useful for testing */
1785 sprintf(p
, "%Lu", cv
->ull
);
1788 cstr_ccat(&cstr_buf
, 'L');
1790 cstr_ccat(&cstr_buf
, '\'');
1791 add_char(&cstr_buf
, cv
->i
);
1792 cstr_ccat(&cstr_buf
, '\'');
1793 cstr_ccat(&cstr_buf
, '\0');
1797 len
= cstr
->size
- 1;
1799 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1800 cstr_ccat(&cstr_buf
, '\0');
1803 cstr_ccat(&cstr_buf
, 'L');
1806 cstr_ccat(&cstr_buf
, '\"');
1808 len
= cstr
->size
- 1;
1810 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1812 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
1814 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
1816 cstr_ccat(&cstr_buf
, '\"');
1817 cstr_ccat(&cstr_buf
, '\0');
1826 return strcpy(p
, "...");
1828 return strcpy(p
, "<<=");
1830 return strcpy(p
, ">>=");
1832 if (v
< TOK_IDENT
) {
1833 /* search in two bytes table */
1847 } else if (v
< tok_ident
) {
1848 return table_ident
[v
- TOK_IDENT
]->str
;
1849 } else if (v
>= SYM_FIRST_ANOM
) {
1850 /* special name for anonymous symbol */
1851 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1853 /* should never happen */
1858 return cstr_buf
.data
;
1861 /* push, without hashing */
1862 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, long c
)
1876 /* find a symbol and return its associated structure. 's' is the top
1877 of the symbol stack */
1878 static Sym
*sym_find2(Sym
*s
, int v
)
1888 /* structure lookup */
1889 static inline Sym
*struct_find(int v
)
1892 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1894 return table_ident
[v
]->sym_struct
;
1897 /* find an identifier */
1898 static inline Sym
*sym_find(int v
)
1901 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1903 return table_ident
[v
]->sym_identifier
;
1906 /* push a given symbol on the symbol stack */
1907 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1916 s
= sym_push2(ps
, v
, type
->t
, c
);
1917 s
->type
.ref
= type
->ref
;
1919 /* don't record fields or anonymous symbols */
1921 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1922 /* record symbol in token array */
1923 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1925 ps
= &ts
->sym_struct
;
1927 ps
= &ts
->sym_identifier
;
1934 /* push a global identifier */
1935 static Sym
*global_identifier_push(int v
, int t
, int c
)
1938 s
= sym_push2(&global_stack
, v
, t
, c
);
1939 /* don't record anonymous symbol */
1940 if (v
< SYM_FIRST_ANOM
) {
1941 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1942 /* modify the top most local identifier, so that
1943 sym_identifier will point to 's' when popped */
1945 ps
= &(*ps
)->prev_tok
;
1952 /* pop symbols until top reaches 'b' */
1953 static void sym_pop(Sym
**ptop
, Sym
*b
)
1963 /* remove symbol in token array */
1965 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1966 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1968 ps
= &ts
->sym_struct
;
1970 ps
= &ts
->sym_identifier
;
1981 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1986 if (strcmp(filename
, "-") == 0)
1987 fd
= 0, filename
= "stdin";
1989 fd
= open(filename
, O_RDONLY
| O_BINARY
);
1990 if ((verbose
== 2 && fd
>= 0) || verbose
== 3)
1991 printf("%s %*s%s\n", fd
< 0 ? "nf":"->",
1992 (s1
->include_stack_ptr
- s1
->include_stack
), "", filename
);
1995 bf
= tcc_malloc(sizeof(BufferedFile
));
1997 bf
->buf_ptr
= bf
->buffer
;
1998 bf
->buf_end
= bf
->buffer
;
1999 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
2000 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
2002 normalize_slashes(bf
->filename
);
2005 bf
->ifndef_macro
= 0;
2006 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
2007 // printf("opening '%s'\n", filename);
2011 void tcc_close(BufferedFile
*bf
)
2013 total_lines
+= bf
->line_num
;
2018 /* fill input buffer and peek next char */
2019 static int tcc_peekc_slow(BufferedFile
*bf
)
2022 /* only tries to read if really end of buffer */
2023 if (bf
->buf_ptr
>= bf
->buf_end
) {
2025 #if defined(PARSE_DEBUG)
2030 len
= read(bf
->fd
, bf
->buffer
, len
);
2037 bf
->buf_ptr
= bf
->buffer
;
2038 bf
->buf_end
= bf
->buffer
+ len
;
2039 *bf
->buf_end
= CH_EOB
;
2041 if (bf
->buf_ptr
< bf
->buf_end
) {
2042 return bf
->buf_ptr
[0];
2044 bf
->buf_ptr
= bf
->buf_end
;
2049 /* return the current character, handling end of block if necessary
2051 static int handle_eob(void)
2053 return tcc_peekc_slow(file
);
2056 /* read next char from current input file and handle end of input buffer */
2057 static inline void inp(void)
2059 ch
= *(++(file
->buf_ptr
));
2060 /* end of buffer/file handling */
2065 /* handle '\[\r]\n' */
2066 static int handle_stray_noerror(void)
2068 while (ch
== '\\') {
2073 } else if (ch
== '\r') {
2087 static void handle_stray(void)
2089 if (handle_stray_noerror())
2090 error("stray '\\' in program");
2093 /* skip the stray and handle the \\n case. Output an error if
2094 incorrect char after the stray */
2095 static int handle_stray1(uint8_t *p
)
2099 if (p
>= file
->buf_end
) {
2116 /* handle just the EOB case, but not stray */
2117 #define PEEKC_EOB(c, p)\
2128 /* handle the complicated stray case */
2129 #define PEEKC(c, p)\
2134 c = handle_stray1(p);\
2139 /* input with '\[\r]\n' handling. Note that this function cannot
2140 handle other characters after '\', so you cannot call it inside
2141 strings or comments */
2142 static void minp(void)
2150 /* single line C++ comments */
2151 static uint8_t *parse_line_comment(uint8_t *p
)
2159 if (c
== '\n' || c
== CH_EOF
) {
2161 } else if (c
== '\\') {
2170 } else if (c
== '\r') {
2188 static uint8_t *parse_comment(uint8_t *p
)
2194 /* fast skip loop */
2197 if (c
== '\n' || c
== '*' || c
== '\\')
2201 if (c
== '\n' || c
== '*' || c
== '\\')
2205 /* now we can handle all the cases */
2209 } else if (c
== '*') {
2215 } else if (c
== '/') {
2216 goto end_of_comment
;
2217 } else if (c
== '\\') {
2222 /* skip '\[\r]\n', otherwise just skip the stray */
2228 } else if (c
== '\r') {
2245 /* stray, eob or eof */
2250 error("unexpected end of file in comment");
2251 } else if (c
== '\\') {
2263 /* space exlcuding newline */
2264 static inline int is_space(int ch
)
2266 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
2269 static inline void skip_spaces(void)
2271 while (is_space(ch
))
2275 /* parse a string without interpreting escapes */
2276 static uint8_t *parse_pp_string(uint8_t *p
,
2277 int sep
, CString
*str
)
2285 } else if (c
== '\\') {
2290 unterminated_string
:
2291 /* XXX: indicate line number of start of string */
2292 error("missing terminating %c character", sep
);
2293 } else if (c
== '\\') {
2294 /* escape : just skip \[\r]\n */
2299 } else if (c
== '\r') {
2302 expect("'\n' after '\r'");
2305 } else if (c
== CH_EOF
) {
2306 goto unterminated_string
;
2309 cstr_ccat(str
, '\\');
2315 } else if (c
== '\n') {
2318 } else if (c
== '\r') {
2322 cstr_ccat(str
, '\r');
2338 /* skip block of text until #else, #elif or #endif. skip also pairs of
2340 void preprocess_skip(void)
2342 int a
, start_of_line
, c
, in_warn_or_error
;
2349 in_warn_or_error
= 0;
2370 } else if (c
== '\\') {
2371 ch
= file
->buf_ptr
[0];
2372 handle_stray_noerror();
2379 if (in_warn_or_error
)
2381 p
= parse_pp_string(p
, c
, NULL
);
2385 if (in_warn_or_error
)
2392 p
= parse_comment(p
);
2393 } else if (ch
== '/') {
2394 p
= parse_line_comment(p
);
2399 if (start_of_line
) {
2404 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2406 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2408 else if (tok
== TOK_ENDIF
)
2410 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
2411 in_warn_or_error
= 1;
2425 /* ParseState handling */
2427 /* XXX: currently, no include file info is stored. Thus, we cannot display
2428 accurate messages if the function or data definition spans multiple
2431 /* save current parse state in 's' */
2432 void save_parse_state(ParseState
*s
)
2434 s
->line_num
= file
->line_num
;
2435 s
->macro_ptr
= macro_ptr
;
2440 /* restore parse state from 's' */
2441 void restore_parse_state(ParseState
*s
)
2443 file
->line_num
= s
->line_num
;
2444 macro_ptr
= s
->macro_ptr
;
2449 /* return the number of additional 'ints' necessary to store the
2451 static inline int tok_ext_size(int t
)
2465 error("unsupported token");
2472 return LDOUBLE_SIZE
/ 4;
2478 /* token string handling */
2480 static inline void tok_str_new(TokenString
*s
)
2484 s
->allocated_len
= 0;
2485 s
->last_line_num
= -1;
2488 static void tok_str_free(int *str
)
2493 static int *tok_str_realloc(TokenString
*s
)
2497 if (s
->allocated_len
== 0) {
2500 len
= s
->allocated_len
* 2;
2502 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2504 error("memory full");
2505 s
->allocated_len
= len
;
2510 static void tok_str_add(TokenString
*s
, int t
)
2516 if (len
>= s
->allocated_len
)
2517 str
= tok_str_realloc(s
);
2522 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2529 /* allocate space for worst case */
2530 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2531 str
= tok_str_realloc(s
);
2540 str
[len
++] = cv
->tab
[0];
2549 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
2550 while ((len
+ nb_words
) > s
->allocated_len
)
2551 str
= tok_str_realloc(s
);
2552 cstr
= (CString
*)(str
+ len
);
2554 cstr
->size
= cv
->cstr
->size
;
2555 cstr
->data_allocated
= NULL
;
2556 cstr
->size_allocated
= cstr
->size
;
2557 memcpy((char *)cstr
+ sizeof(CString
),
2558 cv
->cstr
->data
, cstr
->size
);
2565 #if LDOUBLE_SIZE == 8
2568 str
[len
++] = cv
->tab
[0];
2569 str
[len
++] = cv
->tab
[1];
2571 #if LDOUBLE_SIZE == 12
2573 str
[len
++] = cv
->tab
[0];
2574 str
[len
++] = cv
->tab
[1];
2575 str
[len
++] = cv
->tab
[2];
2576 #elif LDOUBLE_SIZE == 16
2578 str
[len
++] = cv
->tab
[0];
2579 str
[len
++] = cv
->tab
[1];
2580 str
[len
++] = cv
->tab
[2];
2581 str
[len
++] = cv
->tab
[3];
2582 #elif LDOUBLE_SIZE != 8
2583 #error add long double size support
2592 /* add the current parse token in token string 's' */
2593 static void tok_str_add_tok(TokenString
*s
)
2597 /* save line number info */
2598 if (file
->line_num
!= s
->last_line_num
) {
2599 s
->last_line_num
= file
->line_num
;
2600 cval
.i
= s
->last_line_num
;
2601 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2603 tok_str_add2(s
, tok
, &tokc
);
2606 #if LDOUBLE_SIZE == 16
2607 #define LDOUBLE_GET(p, cv) \
2612 #elif LDOUBLE_SIZE == 12
2613 #define LDOUBLE_GET(p, cv) \
2617 #elif LDOUBLE_SIZE == 8
2618 #define LDOUBLE_GET(p, cv) \
2622 #error add long double size support
2626 /* get a token from an integer array and increment pointer
2627 accordingly. we code it as a macro to avoid pointer aliasing. */
2628 #define TOK_GET(t, p, cv) \
2643 cv.cstr = (CString *)p; \
2644 cv.cstr->data = (char *)p + sizeof(CString);\
2645 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
2654 case TOK_CLDOUBLE: \
2655 LDOUBLE_GET(p, cv); \
2656 p += LDOUBLE_SIZE / 4; \
2663 /* defines handling */
2664 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2668 s
= sym_push2(&define_stack
, v
, macro_type
, (long)str
);
2669 s
->next
= first_arg
;
2670 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2673 /* undefined a define symbol. Its name is just set to zero */
2674 static void define_undef(Sym
*s
)
2678 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2679 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2683 static inline Sym
*define_find(int v
)
2686 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2688 return table_ident
[v
]->sym_define
;
2691 /* free define stack until top reaches 'b' */
2692 static void free_defines(Sym
*b
)
2700 /* do not free args or predefined defines */
2702 tok_str_free((int *)top
->c
);
2704 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2705 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2713 static Sym
*label_find(int v
)
2716 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2718 return table_ident
[v
]->sym_label
;
2721 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2724 s
= sym_push2(ptop
, v
, 0, 0);
2726 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2727 if (ptop
== &global_label_stack
) {
2728 /* modify the top most local identifier, so that
2729 sym_identifier will point to 's' when popped */
2731 ps
= &(*ps
)->prev_tok
;
2738 /* pop labels until element last is reached. Look if any labels are
2739 undefined. Define symbols if '&&label' was used. */
2740 static void label_pop(Sym
**ptop
, Sym
*slast
)
2743 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2745 if (s
->r
== LABEL_DECLARED
) {
2746 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2747 } else if (s
->r
== LABEL_FORWARD
) {
2748 error("label '%s' used but not defined",
2749 get_tok_str(s
->v
, NULL
));
2752 /* define corresponding symbol. A size of
2754 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2758 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2764 /* eval an expression for #if/#elif */
2765 static int expr_preprocess(void)
2771 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2772 next(); /* do macro subst */
2773 if (tok
== TOK_DEFINED
) {
2778 c
= define_find(tok
) != 0;
2783 } else if (tok
>= TOK_IDENT
) {
2784 /* if undefined macro */
2788 tok_str_add_tok(&str
);
2790 tok_str_add(&str
, -1); /* simulate end of file */
2791 tok_str_add(&str
, 0);
2792 /* now evaluate C constant expression */
2793 macro_ptr
= str
.str
;
2797 tok_str_free(str
.str
);
2801 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2802 static void tok_print(int *str
)
2808 TOK_GET(t
, str
, cval
);
2811 printf(" %s", get_tok_str(t
, &cval
));
2817 /* parse after #define */
2818 static void parse_define(void)
2820 Sym
*s
, *first
, **ps
;
2821 int v
, t
, varg
, is_vaargs
, c
;
2826 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2827 /* XXX: should check if same macro (ANSI) */
2830 /* '(' must be just after macro definition for MACRO_FUNC */
2831 c
= file
->buf_ptr
[0];
2833 c
= handle_stray1(file
->buf_ptr
);
2838 while (tok
!= ')') {
2842 if (varg
== TOK_DOTS
) {
2843 varg
= TOK___VA_ARGS__
;
2845 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2849 if (varg
< TOK_IDENT
)
2850 error("badly punctuated parameter list");
2851 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2862 /* EOF testing necessary for '-D' handling */
2863 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2864 tok_str_add2(&str
, tok
, &tokc
);
2867 tok_str_add(&str
, 0);
2869 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2872 define_push(v
, t
, str
.str
, first
);
2875 static inline int hash_cached_include(int type
, const char *filename
)
2877 const unsigned char *s
;
2881 h
= TOK_HASH_FUNC(h
, type
);
2884 h
= TOK_HASH_FUNC(h
, *s
);
2887 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
2891 /* XXX: use a token or a hash table to accelerate matching ? */
2892 static CachedInclude
*search_cached_include(TCCState
*s1
,
2893 int type
, const char *filename
)
2897 h
= hash_cached_include(type
, filename
);
2898 i
= s1
->cached_includes_hash
[h
];
2902 e
= s1
->cached_includes
[i
- 1];
2903 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2910 static inline void add_cached_include(TCCState
*s1
, int type
,
2911 const char *filename
, int ifndef_macro
)
2916 if (search_cached_include(s1
, type
, filename
))
2919 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2921 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2925 strcpy(e
->filename
, filename
);
2926 e
->ifndef_macro
= ifndef_macro
;
2927 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2928 /* add in hash table */
2929 h
= hash_cached_include(type
, filename
);
2930 e
->hash_next
= s1
->cached_includes_hash
[h
];
2931 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
2934 static void pragma_parse(TCCState
*s1
)
2939 if (tok
== TOK_pack
) {
2942 #pragma pack(1) // set
2943 #pragma pack() // reset to default
2944 #pragma pack(push,1) // push & set
2945 #pragma pack(pop) // restore previous
2949 if (tok
== TOK_ASM_pop
) {
2951 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
2953 error("out of pack stack");
2955 s1
->pack_stack_ptr
--;
2959 if (tok
== TOK_ASM_push
) {
2961 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
2963 s1
->pack_stack_ptr
++;
2966 if (tok
!= TOK_CINT
) {
2968 error("invalid pack pragma");
2971 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
2975 *s1
->pack_stack_ptr
= val
;
2981 /* is_bof is true if first non space token at beginning of file */
2982 static void preprocess(int is_bof
)
2984 TCCState
*s1
= tcc_state
;
2985 int size
, i
, c
, n
, saved_parse_flags
;
2992 saved_parse_flags
= parse_flags
;
2993 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
2994 PARSE_FLAG_LINEFEED
;
3004 s
= define_find(tok
);
3005 /* undefine symbol by putting an invalid name */
3010 case TOK_INCLUDE_NEXT
:
3011 ch
= file
->buf_ptr
[0];
3012 /* XXX: incorrect if comments : use next_nomacro with a special mode */
3017 } else if (ch
== '\"') {
3022 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
3023 if ((q
- buf
) < sizeof(buf
) - 1)
3026 if (handle_stray_noerror() == 0)
3034 /* eat all spaces and comments after include */
3035 /* XXX: slightly incorrect */
3036 while (ch1
!= '\n' && ch1
!= CH_EOF
)
3040 /* computed #include : either we have only strings or
3041 we have anything enclosed in '<>' */
3044 if (tok
== TOK_STR
) {
3045 while (tok
!= TOK_LINEFEED
) {
3046 if (tok
!= TOK_STR
) {
3048 error("'#include' expects \"FILENAME\" or <FILENAME>");
3050 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
3056 while (tok
!= TOK_LINEFEED
) {
3057 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
3061 /* check syntax and remove '<>' */
3062 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
3063 goto include_syntax
;
3064 memmove(buf
, buf
+ 1, len
- 2);
3065 buf
[len
- 2] = '\0';
3070 e
= search_cached_include(s1
, c
, buf
);
3071 if (e
&& define_find(e
->ifndef_macro
)) {
3072 /* no need to parse the include because the 'ifndef macro'
3075 printf("%s: skipping %s\n", file
->filename
, buf
);
3078 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
3079 error("#include recursion too deep");
3080 /* push current file in stack */
3081 /* XXX: fix current line init */
3082 *s1
->include_stack_ptr
++ = file
;
3084 /* first search in current dir if "header.h" */
3085 size
= tcc_basename(file
->filename
) - file
->filename
;
3086 if (size
> sizeof(buf1
) - 1)
3087 size
= sizeof(buf1
) - 1;
3088 memcpy(buf1
, file
->filename
, size
);
3090 pstrcat(buf1
, sizeof(buf1
), buf
);
3091 f
= tcc_open(s1
, buf1
);
3093 if (tok
== TOK_INCLUDE_NEXT
)
3099 /* now search in all the include paths */
3100 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
3101 for(i
= 0; i
< n
; i
++) {
3103 if (i
< s1
->nb_include_paths
)
3104 path
= s1
->include_paths
[i
];
3106 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
3107 pstrcpy(buf1
, sizeof(buf1
), path
);
3108 pstrcat(buf1
, sizeof(buf1
), "/");
3109 pstrcat(buf1
, sizeof(buf1
), buf
);
3110 f
= tcc_open(s1
, buf1
);
3112 if (tok
== TOK_INCLUDE_NEXT
)
3118 --s1
->include_stack_ptr
;
3119 error("include file '%s' not found", buf
);
3123 printf("%s: including %s\n", file
->filename
, buf1
);
3126 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
3128 /* add include file debug info */
3130 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
3132 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
3133 ch
= file
->buf_ptr
[0];
3141 c
= expr_preprocess();
3147 if (tok
< TOK_IDENT
)
3148 error("invalid argument for '#if%sdef'", c
? "n" : "");
3152 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
3154 file
->ifndef_macro
= tok
;
3157 c
= (define_find(tok
) != 0) ^ c
;
3159 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
3160 error("memory full");
3161 *s1
->ifdef_stack_ptr
++ = c
;
3164 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
3165 error("#else without matching #if");
3166 if (s1
->ifdef_stack_ptr
[-1] & 2)
3167 error("#else after #else");
3168 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
3171 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
3172 error("#elif without matching #if");
3173 c
= s1
->ifdef_stack_ptr
[-1];
3175 error("#elif after #else");
3176 /* last #if/#elif expression was true: we skip */
3179 c
= expr_preprocess();
3180 s1
->ifdef_stack_ptr
[-1] = c
;
3190 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
3191 error("#endif without matching #if");
3192 s1
->ifdef_stack_ptr
--;
3193 /* '#ifndef macro' was at the start of file. Now we check if
3194 an '#endif' is exactly at the end of file */
3195 if (file
->ifndef_macro
&&
3196 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
3197 file
->ifndef_macro_saved
= file
->ifndef_macro
;
3198 /* need to set to zero to avoid false matches if another
3199 #ifndef at middle of file */
3200 file
->ifndef_macro
= 0;
3201 while (tok
!= TOK_LINEFEED
)
3203 tok_flags
|= TOK_FLAG_ENDIF
;
3209 if (tok
!= TOK_CINT
)
3211 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
3213 if (tok
!= TOK_LINEFEED
) {
3216 pstrcpy(file
->filename
, sizeof(file
->filename
),
3217 (char *)tokc
.cstr
->data
);
3223 ch
= file
->buf_ptr
[0];
3226 while (ch
!= '\n' && ch
!= CH_EOF
) {
3227 if ((q
- buf
) < sizeof(buf
) - 1)
3230 if (handle_stray_noerror() == 0)
3237 error("#error %s", buf
);
3239 warning("#warning %s", buf
);
3245 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
3246 /* '!' is ignored to allow C scripts. numbers are ignored
3247 to emulate cpp behaviour */
3249 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
3250 warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
3254 /* ignore other preprocess commands or #! for C scripts */
3255 while (tok
!= TOK_LINEFEED
)
3258 parse_flags
= saved_parse_flags
;
3261 /* evaluate escape codes in a string. */
3262 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
3277 case '0': case '1': case '2': case '3':
3278 case '4': case '5': case '6': case '7':
3279 /* at most three octal digits */
3284 n
= n
* 8 + c
- '0';
3288 n
= n
* 8 + c
- '0';
3293 goto add_char_nonext
;
3301 if (c
>= 'a' && c
<= 'f')
3303 else if (c
>= 'A' && c
<= 'F')
3313 goto add_char_nonext
;
3337 goto invalid_escape
;
3347 if (c
>= '!' && c
<= '~')
3348 warning("unknown escape sequence: \'\\%c\'", c
);
3350 warning("unknown escape sequence: \'\\x%x\'", c
);
3357 cstr_ccat(outstr
, c
);
3359 cstr_wccat(outstr
, c
);
3361 /* add a trailing '\0' */
3363 cstr_ccat(outstr
, '\0');
3365 cstr_wccat(outstr
, '\0');
3368 /* we use 64 bit numbers */
3371 /* bn = (bn << shift) | or_val */
3372 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
3376 for(i
=0;i
<BN_SIZE
;i
++) {
3378 bn
[i
] = (v
<< shift
) | or_val
;
3379 or_val
= v
>> (32 - shift
);
3383 void bn_zero(unsigned int *bn
)
3386 for(i
=0;i
<BN_SIZE
;i
++) {
3391 /* parse number in null terminated string 'p' and return it in the
3393 void parse_number(const char *p
)
3395 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
3397 unsigned int bn
[BN_SIZE
];
3408 goto float_frac_parse
;
3409 } else if (t
== '0') {
3410 if (ch
== 'x' || ch
== 'X') {
3414 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
3420 /* parse all digits. cannot check octal numbers at this stage
3421 because of floating point constants */
3423 if (ch
>= 'a' && ch
<= 'f')
3425 else if (ch
>= 'A' && ch
<= 'F')
3433 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
3435 error("number too long");
3441 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
3442 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
3444 /* NOTE: strtox should support that for hexa numbers, but
3445 non ISOC99 libcs do not support it, so we prefer to do
3447 /* hexadecimal or binary floats */
3448 /* XXX: handle overflows */
3460 } else if (t
>= 'a') {
3462 } else if (t
>= 'A') {
3467 bn_lshift(bn
, shift
, t
);
3474 if (t
>= 'a' && t
<= 'f') {
3476 } else if (t
>= 'A' && t
<= 'F') {
3478 } else if (t
>= '0' && t
<= '9') {
3484 error("invalid digit");
3485 bn_lshift(bn
, shift
, t
);
3490 if (ch
!= 'p' && ch
!= 'P')
3497 } else if (ch
== '-') {
3501 if (ch
< '0' || ch
> '9')
3502 expect("exponent digits");
3503 while (ch
>= '0' && ch
<= '9') {
3504 exp_val
= exp_val
* 10 + ch
- '0';
3507 exp_val
= exp_val
* s
;
3509 /* now we can generate the number */
3510 /* XXX: should patch directly float number */
3511 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3512 d
= ldexp(d
, exp_val
- frac_bits
);
3517 /* float : should handle overflow */
3519 } else if (t
== 'L') {
3522 /* XXX: not large enough */
3523 tokc
.ld
= (long double)d
;
3529 /* decimal floats */
3531 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3536 while (ch
>= '0' && ch
<= '9') {
3537 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3543 if (ch
== 'e' || ch
== 'E') {
3544 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3548 if (ch
== '-' || ch
== '+') {
3549 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3554 if (ch
< '0' || ch
> '9')
3555 expect("exponent digits");
3556 while (ch
>= '0' && ch
<= '9') {
3557 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3569 tokc
.f
= strtof(token_buf
, NULL
);
3570 } else if (t
== 'L') {
3573 tokc
.ld
= strtold(token_buf
, NULL
);
3576 tokc
.d
= strtod(token_buf
, NULL
);
3580 unsigned long long n
, n1
;
3583 /* integer number */
3586 if (b
== 10 && *q
== '0') {
3593 /* no need for checks except for base 10 / 8 errors */
3596 } else if (t
>= 'a') {
3598 } else if (t
>= 'A') {
3603 error("invalid digit");
3607 /* detect overflow */
3608 /* XXX: this test is not reliable */
3610 error("integer constant overflow");
3613 /* XXX: not exactly ANSI compliant */
3614 if ((n
& 0xffffffff00000000LL
) != 0) {
3619 } else if (n
> 0x7fffffff) {
3630 error("three 'l's in integer constant");
3633 if (tok
== TOK_CINT
)
3635 else if (tok
== TOK_CUINT
)
3639 } else if (t
== 'U') {
3641 error("two 'u's in integer constant");
3643 if (tok
== TOK_CINT
)
3645 else if (tok
== TOK_CLLONG
)
3652 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3660 #define PARSE2(c1, tok1, c2, tok2) \
3671 /* return next token without macro substitution */
3672 static inline void next_nomacro1(void)
3679 cstr_reset(&tok_spaces
);
3689 cstr_ccat(&tok_spaces
, c
);
3694 /* first look if it is in fact an end of buffer */
3695 if (p
>= file
->buf_end
) {
3699 if (p
>= file
->buf_end
)
3712 TCCState
*s1
= tcc_state
;
3713 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
3714 && !(tok_flags
& TOK_FLAG_EOF
)) {
3715 tok_flags
|= TOK_FLAG_EOF
;
3717 goto keep_tok_flags
;
3718 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3719 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3720 /* no include left : end of file. */
3723 tok_flags
&= ~TOK_FLAG_EOF
;
3724 /* pop include file */
3726 /* test if previous '#endif' was after a #ifdef at
3728 if (tok_flags
& TOK_FLAG_ENDIF
) {
3730 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3732 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3733 file
->ifndef_macro_saved
);
3736 /* add end of include file debug info */
3738 put_stabd(N_EINCL
, 0, 0);
3740 /* pop include stack */
3742 s1
->include_stack_ptr
--;
3743 file
= *s1
->include_stack_ptr
;
3752 tok_flags
|= TOK_FLAG_BOL
;
3754 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
3757 goto keep_tok_flags
;
3762 if ((tok_flags
& TOK_FLAG_BOL
) &&
3763 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3765 preprocess(tok_flags
& TOK_FLAG_BOF
);
3771 tok
= TOK_TWOSHARPS
;
3773 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
3774 p
= parse_line_comment(p
- 1);
3783 case 'a': case 'b': case 'c': case 'd':
3784 case 'e': case 'f': case 'g': case 'h':
3785 case 'i': case 'j': case 'k': case 'l':
3786 case 'm': case 'n': case 'o': case 'p':
3787 case 'q': case 'r': case 's': case 't':
3788 case 'u': case 'v': case 'w': case 'x':
3790 case 'A': case 'B': case 'C': case 'D':
3791 case 'E': case 'F': case 'G': case 'H':
3792 case 'I': case 'J': case 'K':
3793 case 'M': case 'N': case 'O': case 'P':
3794 case 'Q': case 'R': case 'S': case 'T':
3795 case 'U': case 'V': case 'W': case 'X':
3801 h
= TOK_HASH_FUNC(h
, c
);
3805 if (!isidnum_table
[c
-CH_EOF
])
3807 h
= TOK_HASH_FUNC(h
, c
);
3814 /* fast case : no stray found, so we have the full token
3815 and we have already hashed it */
3817 h
&= (TOK_HASH_SIZE
- 1);
3818 pts
= &hash_ident
[h
];
3823 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3825 pts
= &(ts
->hash_next
);
3827 ts
= tok_alloc_new(pts
, p1
, len
);
3831 cstr_reset(&tokcstr
);
3834 cstr_ccat(&tokcstr
, *p1
);
3840 while (isidnum_table
[c
-CH_EOF
]) {
3841 cstr_ccat(&tokcstr
, c
);
3844 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3850 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3852 goto parse_ident_fast
;
3855 if (c
== '\'' || c
== '\"') {
3859 cstr_reset(&tokcstr
);
3860 cstr_ccat(&tokcstr
, 'L');
3861 goto parse_ident_slow
;
3865 case '0': case '1': case '2': case '3':
3866 case '4': case '5': case '6': case '7':
3869 cstr_reset(&tokcstr
);
3870 /* after the first digit, accept digits, alpha, '.' or sign if
3871 prefixed by 'eEpP' */
3875 cstr_ccat(&tokcstr
, c
);
3877 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3878 ((c
== '+' || c
== '-') &&
3879 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3882 /* We add a trailing '\0' to ease parsing */
3883 cstr_ccat(&tokcstr
, '\0');
3884 tokc
.cstr
= &tokcstr
;
3888 /* special dot handling because it can also start a number */
3891 cstr_reset(&tokcstr
);
3892 cstr_ccat(&tokcstr
, '.');
3894 } else if (c
== '.') {
3914 /* parse the string */
3916 p
= parse_pp_string(p
, sep
, &str
);
3917 cstr_ccat(&str
, '\0');
3919 /* eval the escape (should be done as TOK_PPNUM) */
3920 cstr_reset(&tokcstr
);
3921 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3926 /* XXX: make it portable */
3930 char_size
= sizeof(nwchar_t
);
3931 if (tokcstr
.size
<= char_size
)
3932 error("empty character constant");
3933 if (tokcstr
.size
> 2 * char_size
)
3934 warning("multi-character character constant");
3936 tokc
.i
= *(int8_t *)tokcstr
.data
;
3939 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
3943 tokc
.cstr
= &tokcstr
;
3957 } else if (c
== '<') {
3975 } else if (c
== '>') {
3993 } else if (c
== '=') {
4006 } else if (c
== '=') {
4019 } else if (c
== '=') {
4032 } else if (c
== '=') {
4035 } else if (c
== '>') {
4043 PARSE2('!', '!', '=', TOK_NE
)
4044 PARSE2('=', '=', '=', TOK_EQ
)
4045 PARSE2('*', '*', '=', TOK_A_MUL
)
4046 PARSE2('%', '%', '=', TOK_A_MOD
)
4047 PARSE2('^', '^', '=', TOK_A_XOR
)
4049 /* comments or operator */
4053 p
= parse_comment(p
);
4055 } else if (c
== '/') {
4056 p
= parse_line_comment(p
);
4058 } else if (c
== '=') {
4078 case '$': /* only used in assembler */
4079 case '@': /* dito */
4084 error("unrecognized character \\x%02x", c
);
4090 #if defined(PARSE_DEBUG)
4091 printf("token = %s\n", get_tok_str(tok
, &tokc
));
4095 /* return next token without macro substitution. Can read input from
4097 static void next_nomacro(void)
4103 TOK_GET(tok
, macro_ptr
, tokc
);
4104 if (tok
== TOK_LINENUM
) {
4105 file
->line_num
= tokc
.i
;
4114 /* substitute args in macro_str and return allocated string */
4115 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
4117 int *st
, last_tok
, t
, notfirst
;
4126 TOK_GET(t
, macro_str
, cval
);
4131 TOK_GET(t
, macro_str
, cval
);
4134 s
= sym_find2(args
, t
);
4141 cstr_ccat(&cstr
, ' ');
4142 TOK_GET(t
, st
, cval
);
4143 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
4148 cstr_ccat(&cstr
, '\0');
4150 printf("stringize: %s\n", (char *)cstr
.data
);
4154 tok_str_add2(&str
, TOK_STR
, &cval
);
4157 tok_str_add2(&str
, t
, &cval
);
4159 } else if (t
>= TOK_IDENT
) {
4160 s
= sym_find2(args
, t
);
4163 /* if '##' is present before or after, no arg substitution */
4164 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
4165 /* special case for var arg macros : ## eats the
4166 ',' if empty VA_ARGS variable. */
4167 /* XXX: test of the ',' is not 100%
4168 reliable. should fix it to avoid security
4170 if (gnu_ext
&& s
->type
.t
&&
4171 last_tok
== TOK_TWOSHARPS
&&
4172 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
4174 /* suppress ',' '##' */
4177 /* suppress '##' and add variable */
4185 TOK_GET(t1
, st
, cval
);
4188 tok_str_add2(&str
, t1
, &cval
);
4192 /* NOTE: the stream cannot be read when macro
4193 substituing an argument */
4194 macro_subst(&str
, nested_list
, st
, NULL
);
4197 tok_str_add(&str
, t
);
4200 tok_str_add2(&str
, t
, &cval
);
4204 tok_str_add(&str
, 0);
4208 static char const ab_month_name
[12][4] =
4210 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
4211 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
4214 /* do macro substitution of current token with macro 's' and add
4215 result to (tok_str,tok_len). 'nested_list' is the list of all
4216 macros we got inside to avoid recursing. Return non zero if no
4217 substitution needs to be done */
4218 static int macro_subst_tok(TokenString
*tok_str
,
4219 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
4221 Sym
*args
, *sa
, *sa1
;
4222 int mstr_allocated
, parlevel
, *mstr
, t
, t1
;
4229 /* if symbol is a macro, prepare substitution */
4230 /* special macros */
4231 if (tok
== TOK___LINE__
) {
4232 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
4236 } else if (tok
== TOK___FILE__
) {
4237 cstrval
= file
->filename
;
4239 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
4244 tm
= localtime(&ti
);
4245 if (tok
== TOK___DATE__
) {
4246 snprintf(buf
, sizeof(buf
), "%s %2d %d",
4247 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
4249 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
4250 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
4257 cstr_cat(&cstr
, cstrval
);
4258 cstr_ccat(&cstr
, '\0');
4260 tok_str_add2(tok_str
, t1
, &cval
);
4265 if (s
->type
.t
== MACRO_FUNC
) {
4266 /* NOTE: we do not use next_nomacro to avoid eating the
4267 next token. XXX: find better solution */
4271 if (t
== 0 && can_read_stream
) {
4272 /* end of macro stream: we must look at the token
4273 after in the file */
4274 struct macro_level
*ml
= *can_read_stream
;
4280 *can_read_stream
= ml
-> prev
;
4285 /* XXX: incorrect with comments */
4286 ch
= file
->buf_ptr
[0];
4287 while (is_space(ch
) || ch
== '\n')
4291 if (t
!= '(') /* no macro subst */
4294 /* argument macro */
4299 /* NOTE: empty args are allowed, except if no args */
4301 /* handle '()' case */
4302 if (!args
&& !sa
&& tok
== ')')
4305 error("macro '%s' used with too many args",
4306 get_tok_str(s
->v
, 0));
4309 /* NOTE: non zero sa->t indicates VA_ARGS */
4310 while ((parlevel
> 0 ||
4312 (tok
!= ',' || sa
->type
.t
))) &&
4316 else if (tok
== ')')
4318 if (tok
!= TOK_LINEFEED
)
4319 tok_str_add2(&str
, tok
, &tokc
);
4322 tok_str_add(&str
, 0);
4323 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (long)str
.str
);
4326 /* special case for gcc var args: add an empty
4327 var arg argument if it is omitted */
4328 if (sa
&& sa
->type
.t
&& gnu_ext
)
4338 error("macro '%s' used with too few args",
4339 get_tok_str(s
->v
, 0));
4342 /* now subst each arg */
4343 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
4348 tok_str_free((int *)sa
->c
);
4354 sym_push2(nested_list
, s
->v
, 0, 0);
4355 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
4356 /* pop nested defined symbol */
4358 *nested_list
= sa1
->prev
;
4366 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4367 return the resulting string (which must be freed). */
4368 static inline int *macro_twosharps(const int *macro_str
)
4371 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
4373 const char *p1
, *p2
;
4375 TokenString macro_str1
;
4378 start_macro_ptr
= macro_str
;
4379 /* we search the first '##' */
4381 macro_ptr1
= macro_str
;
4382 TOK_GET(t
, macro_str
, cval
);
4383 /* nothing more to do if end of string */
4386 if (*macro_str
== TOK_TWOSHARPS
)
4390 /* we saw '##', so we need more processing to handle it */
4392 tok_str_new(¯o_str1
);
4396 /* add all tokens seen so far */
4397 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
4398 TOK_GET(t
, ptr
, cval
);
4399 tok_str_add2(¯o_str1
, t
, &cval
);
4401 saved_macro_ptr
= macro_ptr
;
4402 /* XXX: get rid of the use of macro_ptr here */
4403 macro_ptr
= (int *)macro_str
;
4405 while (*macro_ptr
== TOK_TWOSHARPS
) {
4407 macro_ptr1
= macro_ptr
;
4410 TOK_GET(t
, macro_ptr
, cval
);
4411 /* We concatenate the two tokens if we have an
4412 identifier or a preprocessing number */
4414 p1
= get_tok_str(tok
, &tokc
);
4415 cstr_cat(&cstr
, p1
);
4416 p2
= get_tok_str(t
, &cval
);
4417 cstr_cat(&cstr
, p2
);
4418 cstr_ccat(&cstr
, '\0');
4420 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
4421 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
4422 if (tok
== TOK_PPNUM
) {
4423 /* if number, then create a number token */
4424 /* NOTE: no need to allocate because
4425 tok_str_add2() does it */
4426 cstr_reset(&tokcstr
);
4429 tokc
.cstr
= &tokcstr
;
4431 /* if identifier, we must do a test to
4432 validate we have a correct identifier */
4433 if (t
== TOK_PPNUM
) {
4443 if (!isnum(c
) && !isid(c
))
4447 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
4448 tok
= ts
->tok
; /* modify current token */
4451 const char *str
= cstr
.data
;
4452 const unsigned char *q
;
4454 /* we look for a valid token */
4455 /* XXX: do more extensive checks */
4456 if (!strcmp(str
, ">>=")) {
4458 } else if (!strcmp(str
, "<<=")) {
4460 } else if (strlen(str
) == 2) {
4461 /* search in two bytes table */
4466 if (q
[0] == str
[0] && q
[1] == str
[1])
4473 /* NOTE: because get_tok_str use a static buffer,
4476 p1
= get_tok_str(tok
, &tokc
);
4477 cstr_cat(&cstr
, p1
);
4478 cstr_ccat(&cstr
, '\0');
4479 p2
= get_tok_str(t
, &cval
);
4480 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
4481 /* cannot merge tokens: just add them separately */
4482 tok_str_add2(¯o_str1
, tok
, &tokc
);
4483 /* XXX: free associated memory ? */
4490 tok_str_add2(¯o_str1
, tok
, &tokc
);
4495 macro_ptr
= (int *)saved_macro_ptr
;
4497 tok_str_add(¯o_str1
, 0);
4498 return macro_str1
.str
;
4502 /* do macro substitution of macro_str and add result to
4503 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4504 inside to avoid recursing. */
4505 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
4506 const int *macro_str
, struct macro_level
** can_read_stream
)
4513 struct macro_level ml
;
4515 /* first scan for '##' operator handling */
4517 macro_str1
= macro_twosharps(ptr
);
4521 /* NOTE: ptr == NULL can only happen if tokens are read from
4522 file stream due to a macro function call */
4525 TOK_GET(t
, ptr
, cval
);
4530 /* if nested substitution, do nothing */
4531 if (sym_find2(*nested_list
, t
))
4534 if (can_read_stream
)
4535 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
4536 macro_ptr
= (int *)ptr
;
4538 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
4539 ptr
= (int *)macro_ptr
;
4541 if (can_read_stream
&& *can_read_stream
== &ml
)
4542 *can_read_stream
= ml
.prev
;
4547 tok_str_add2(tok_str
, t
, &cval
);
4551 tok_str_free(macro_str1
);
4554 /* return next token with macro substitution */
4555 static void next(void)
4557 Sym
*nested_list
, *s
;
4559 struct macro_level
*ml
;
4564 /* if not reading from macro substituted string, then try
4565 to substitute macros */
4566 if (tok
>= TOK_IDENT
&&
4567 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4568 s
= define_find(tok
);
4570 /* we have a macro: we try to substitute */
4574 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
4575 /* substitution done, NOTE: maybe empty */
4576 tok_str_add(&str
, 0);
4577 macro_ptr
= str
.str
;
4578 macro_ptr_allocated
= str
.str
;
4585 /* end of macro or end of unget buffer */
4586 if (unget_buffer_enabled
) {
4587 macro_ptr
= unget_saved_macro_ptr
;
4588 unget_buffer_enabled
= 0;
4590 /* end of macro string: free it */
4591 tok_str_free(macro_ptr_allocated
);
4598 /* convert preprocessor tokens into C tokens */
4599 if (tok
== TOK_PPNUM
&&
4600 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4601 parse_number((char *)tokc
.cstr
->data
);
4605 /* push back current token and set current token to 'last_tok'. Only
4606 identifier case handled for labels. */
4607 static inline void unget_tok(int last_tok
)
4611 unget_saved_macro_ptr
= macro_ptr
;
4612 unget_buffer_enabled
= 1;
4613 q
= unget_saved_buffer
;
4616 n
= tok_ext_size(tok
) - 1;
4619 *q
= 0; /* end of token string */
4624 void swap(int *p
, int *q
)
4632 void vsetc(CType
*type
, int r
, CValue
*vc
)
4636 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4637 error("memory full");
4638 /* cannot let cpu flags if other instruction are generated. Also
4639 avoid leaving VT_JMP anywhere except on the top of the stack
4640 because it would complicate the code generator. */
4641 if (vtop
>= vstack
) {
4642 v
= vtop
->r
& VT_VALMASK
;
4643 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4649 vtop
->r2
= VT_CONST
;
4653 /* push integer constant */
4658 vsetc(&int_type
, VT_CONST
, &cval
);
4661 /* Return a static symbol pointing to a section */
4662 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4663 unsigned long offset
, unsigned long size
)
4669 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4670 sym
->type
.ref
= type
->ref
;
4671 sym
->r
= VT_CONST
| VT_SYM
;
4672 put_extern_sym(sym
, sec
, offset
, size
);
4676 /* push a reference to a section offset by adding a dummy symbol */
4677 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4682 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4683 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4686 /* define a new external reference to a symbol 'v' of type 'u' */
4687 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4693 /* push forward reference */
4694 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4695 s
->type
.ref
= type
->ref
;
4696 s
->r
= r
| VT_CONST
| VT_SYM
;
4701 /* define a new external reference to a symbol 'v' of type 'u' */
4702 static Sym
*external_sym(int v
, CType
*type
, int r
)
4708 /* push forward reference */
4709 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4710 s
->type
.t
|= VT_EXTERN
;
4712 if (!is_compatible_types(&s
->type
, type
))
4713 error("incompatible types for redefinition of '%s'",
4714 get_tok_str(v
, NULL
));
4719 /* push a reference to global symbol v */
4720 static void vpush_global_sym(CType
*type
, int v
)
4725 sym
= external_global_sym(v
, type
, 0);
4727 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4731 void vset(CType
*type
, int r
, int v
)
4736 vsetc(type
, r
, &cval
);
4739 void vseti(int r
, int v
)
4755 void vpushv(SValue
*v
)
4757 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4758 error("memory full");
4768 /* save r to the memory stack, and mark it as being free */
4769 void save_reg(int r
)
4771 int l
, saved
, size
, align
;
4775 /* modify all stack values */
4778 for(p
=vstack
;p
<=vtop
;p
++) {
4779 if ((p
->r
& VT_VALMASK
) == r
||
4780 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& (p
->r2
& VT_VALMASK
) == r
)) {
4781 /* must save value on stack if not already done */
4783 /* NOTE: must reload 'r' because r might be equal to r2 */
4784 r
= p
->r
& VT_VALMASK
;
4785 /* store register in the stack */
4787 #ifndef TCC_TARGET_X86_64
4788 if ((p
->r
& VT_LVAL
) ||
4789 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4793 type
= &char_pointer_type
;
4795 size
= type_size(type
, &align
);
4796 loc
= (loc
- size
) & -align
;
4797 sv
.type
.t
= type
->t
;
4798 sv
.r
= VT_LOCAL
| VT_LVAL
;
4801 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
4802 /* x86 specific: need to pop fp register ST0 if saved */
4803 if (r
== TREG_ST0
) {
4804 o(0xd9dd); /* fstp %st(1) */
4807 #ifndef TCC_TARGET_X86_64
4808 /* special long long case */
4809 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4817 /* mark that stack entry as being saved on the stack */
4818 if (p
->r
& VT_LVAL
) {
4819 /* also clear the bounded flag because the
4820 relocation address of the function was stored in
4822 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4824 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4832 /* find a register of class 'rc2' with at most one reference on stack.
4833 * If none, call get_reg(rc) */
4834 int get_reg_ex(int rc
, int rc2
)
4839 for(r
=0;r
<NB_REGS
;r
++) {
4840 if (reg_classes
[r
] & rc2
) {
4843 for(p
= vstack
; p
<= vtop
; p
++) {
4844 if ((p
->r
& VT_VALMASK
) == r
||
4845 (p
->r2
& VT_VALMASK
) == r
)
4855 /* find a free register of class 'rc'. If none, save one register */
4861 /* find a free register */
4862 for(r
=0;r
<NB_REGS
;r
++) {
4863 if (reg_classes
[r
] & rc
) {
4864 for(p
=vstack
;p
<=vtop
;p
++) {
4865 if ((p
->r
& VT_VALMASK
) == r
||
4866 (p
->r2
& VT_VALMASK
) == r
)
4874 /* no register left : free the first one on the stack (VERY
4875 IMPORTANT to start from the bottom to ensure that we don't
4876 spill registers used in gen_opi()) */
4877 for(p
=vstack
;p
<=vtop
;p
++) {
4878 r
= p
->r
& VT_VALMASK
;
4879 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4881 /* also look at second register (if long long) */
4882 r
= p
->r2
& VT_VALMASK
;
4883 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4889 /* Should never comes here */
4893 /* save registers up to (vtop - n) stack entry */
4894 void save_regs(int n
)
4899 for(p
= vstack
;p
<= p1
; p
++) {
4900 r
= p
->r
& VT_VALMASK
;
4907 /* move register 's' to 'r', and flush previous value of r to memory
4909 void move_reg(int r
, int s
)
4922 /* get address of vtop (vtop MUST BE an lvalue) */
4925 vtop
->r
&= ~VT_LVAL
;
4926 /* tricky: if saved lvalue, then we can go back to lvalue */
4927 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4928 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4931 #ifdef CONFIG_TCC_BCHECK
4932 /* generate lvalue bound code */
4938 vtop
->r
&= ~VT_MUSTBOUND
;
4939 /* if lvalue, then use checking code before dereferencing */
4940 if (vtop
->r
& VT_LVAL
) {
4941 /* if not VT_BOUNDED value, then make one */
4942 if (!(vtop
->r
& VT_BOUNDED
)) {
4943 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4944 /* must save type because we must set it to int to get pointer */
4946 vtop
->type
.t
= VT_INT
;
4949 gen_bounded_ptr_add();
4950 vtop
->r
|= lval_type
;
4953 /* then check for dereferencing */
4954 gen_bounded_ptr_deref();
4959 /* store vtop a register belonging to class 'rc'. lvalues are
4960 converted to values. Cannot be used if cannot be converted to
4961 register value (such as structures). */
4964 int r
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4966 /* NOTE: get_reg can modify vstack[] */
4967 if (vtop
->type
.t
& VT_BITFIELD
) {
4969 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4970 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4971 /* remove bit field info to avoid loops */
4972 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4973 /* cast to int to propagate signedness in following ops */
4975 if((vtop
->type
.t
& VT_UNSIGNED
) ||
4976 (vtop
->type
.t
& VT_BTYPE
) == VT_BOOL
)
4977 type
.t
|= VT_UNSIGNED
;
4979 /* generate shifts */
4980 vpushi(32 - (bit_pos
+ bit_size
));
4982 vpushi(32 - bit_size
);
4983 /* NOTE: transformed to SHR if unsigned */
4987 if (is_float(vtop
->type
.t
) &&
4988 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4991 unsigned long offset
;
4992 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
4996 /* XXX: unify with initializers handling ? */
4997 /* CPUs usually cannot use float constants, so we store them
4998 generically in data segment */
4999 size
= type_size(&vtop
->type
, &align
);
5000 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
5001 data_section
->data_offset
= offset
;
5002 /* XXX: not portable yet */
5003 #if defined(__i386__) || defined(__x86_64__)
5004 /* Zero pad x87 tenbyte long doubles */
5005 if (size
== LDOUBLE_SIZE
)
5006 vtop
->c
.tab
[2] &= 0xffff;
5008 ptr
= section_ptr_add(data_section
, size
);
5010 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5014 ptr
[i
] = vtop
->c
.tab
[size
-1-i
];
5018 ptr
[i
] = vtop
->c
.tab
[i
];
5019 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
5020 vtop
->r
|= VT_LVAL
| VT_SYM
;
5024 #ifdef CONFIG_TCC_BCHECK
5025 if (vtop
->r
& VT_MUSTBOUND
)
5029 r
= vtop
->r
& VT_VALMASK
;
5033 /* need to reload if:
5035 - lvalue (need to dereference pointer)
5036 - already a register, but not in the right class */
5037 if (r
>= VT_CONST
||
5038 (vtop
->r
& VT_LVAL
) ||
5039 !(reg_classes
[r
] & rc
) ||
5040 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
5041 !(reg_classes
[vtop
->r2
] & rc2
))) {
5043 #ifndef TCC_TARGET_X86_64
5044 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
5046 unsigned long long ll
;
5047 /* two register type load : expand to two words
5049 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
5052 vtop
->c
.ui
= ll
; /* first word */
5054 vtop
->r
= r
; /* save register value */
5055 vpushi(ll
>> 32); /* second word */
5056 } else if (r
>= VT_CONST
|| /* XXX: test to VT_CONST incorrect ? */
5057 (vtop
->r
& VT_LVAL
)) {
5058 /* We do not want to modifier the long long
5059 pointer here, so the safest (and less
5060 efficient) is to save all the other registers
5061 in the stack. XXX: totally inefficient. */
5063 /* load from memory */
5066 vtop
[-1].r
= r
; /* save register value */
5067 /* increment pointer to get second word */
5068 vtop
->type
.t
= VT_INT
;
5074 /* move registers */
5077 vtop
[-1].r
= r
; /* save register value */
5078 vtop
->r
= vtop
[-1].r2
;
5080 /* allocate second register */
5084 /* write second register */
5088 if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
5090 /* lvalue of scalar type : need to use lvalue type
5091 because of possible cast */
5094 /* compute memory access type */
5095 if (vtop
->r
& VT_LVAL_BYTE
)
5097 else if (vtop
->r
& VT_LVAL_SHORT
)
5099 if (vtop
->r
& VT_LVAL_UNSIGNED
)
5103 /* restore wanted type */
5106 /* one register type load */
5111 #ifdef TCC_TARGET_C67
5112 /* uses register pairs for doubles */
5113 if ((vtop
->type
.t
& VT_BTYPE
) == VT_DOUBLE
)
5120 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
5121 void gv2(int rc1
, int rc2
)
5125 /* generate more generic register first. But VT_JMP or VT_CMP
5126 values must be generated first in all cases to avoid possible
5128 v
= vtop
[0].r
& VT_VALMASK
;
5129 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
5134 /* test if reload is needed for first register */
5135 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
5145 /* test if reload is needed for first register */
5146 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
5152 /* expand long long on stack in two int registers */
5157 u
= vtop
->type
.t
& VT_UNSIGNED
;
5160 vtop
[0].r
= vtop
[-1].r2
;
5161 vtop
[0].r2
= VT_CONST
;
5162 vtop
[-1].r2
= VT_CONST
;
5163 vtop
[0].type
.t
= VT_INT
| u
;
5164 vtop
[-1].type
.t
= VT_INT
| u
;
5167 #ifdef TCC_TARGET_ARM
5168 /* expand long long on stack */
5169 void lexpand_nr(void)
5173 u
= vtop
->type
.t
& VT_UNSIGNED
;
5175 vtop
->r2
= VT_CONST
;
5176 vtop
->type
.t
= VT_INT
| u
;
5177 v
=vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
);
5178 if (v
== VT_CONST
) {
5179 vtop
[-1].c
.ui
= vtop
->c
.ull
;
5180 vtop
->c
.ui
= vtop
->c
.ull
>> 32;
5182 } else if (v
== (VT_LVAL
|VT_CONST
) || v
== (VT_LVAL
|VT_LOCAL
)) {
5184 vtop
->r
= vtop
[-1].r
;
5185 } else if (v
> VT_CONST
) {
5189 vtop
->r
= vtop
[-1].r2
;
5190 vtop
[-1].r2
= VT_CONST
;
5191 vtop
[-1].type
.t
= VT_INT
| u
;
5195 /* build a long long from two ints */
5198 gv2(RC_INT
, RC_INT
);
5199 vtop
[-1].r2
= vtop
[0].r
;
5200 vtop
[-1].type
.t
= t
;
5204 /* rotate n first stack elements to the bottom
5205 I1 ... In -> I2 ... In I1 [top is right]
5213 for(i
=-n
+1;i
!=0;i
++)
5214 vtop
[i
] = vtop
[i
+1];
5218 /* rotate n first stack elements to the top
5219 I1 ... In -> In I1 ... I(n-1) [top is right]
5227 for(i
= 0;i
< n
- 1; i
++)
5228 vtop
[-i
] = vtop
[-i
- 1];
5232 #ifdef TCC_TARGET_ARM
5233 /* like vrott but in other direction
5234 In ... I1 -> I(n-1) ... I1 In [top is right]
5242 for(i
= n
- 1; i
> 0; i
--)
5243 vtop
[-i
] = vtop
[-i
+ 1];
5248 /* pop stack value */
5252 v
= vtop
->r
& VT_VALMASK
;
5253 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
5254 /* for x86, we need to pop the FP stack */
5255 if (v
== TREG_ST0
&& !nocode_wanted
) {
5256 o(0xd9dd); /* fstp %st(1) */
5259 if (v
== VT_JMP
|| v
== VT_JMPI
) {
5260 /* need to put correct jump if && or || without test */
5266 /* convert stack entry to register and duplicate its value in another
5274 if ((t
& VT_BTYPE
) == VT_LLONG
) {
5281 /* stack: H L L1 H1 */
5289 /* duplicate value */
5294 #ifdef TCC_TARGET_X86_64
5295 if ((t
& VT_BTYPE
) == VT_LDOUBLE
) {
5305 load(r1
, &sv
); /* move r to r1 */
5307 /* duplicates value */
5312 #ifndef TCC_TARGET_X86_64
5313 /* generate CPU independent (unsigned) long long operations */
5314 void gen_opl(int op
)
5316 int t
, a
, b
, op1
, c
, i
;
5318 unsigned short reg_iret
= REG_IRET
;
5319 unsigned short reg_lret
= REG_LRET
;
5325 func
= TOK___divdi3
;
5328 func
= TOK___udivdi3
;
5331 func
= TOK___moddi3
;
5334 func
= TOK___umoddi3
;
5341 /* call generic long long function */
5342 vpush_global_sym(&func_old_type
, func
);
5347 vtop
->r2
= reg_lret
;
5360 /* stack: L1 H1 L2 H2 */
5365 vtop
[-2] = vtop
[-3];
5368 /* stack: H1 H2 L1 L2 */
5374 /* stack: H1 H2 L1 L2 ML MH */
5377 /* stack: ML MH H1 H2 L1 L2 */
5381 /* stack: ML MH H1 L2 H2 L1 */
5386 /* stack: ML MH M1 M2 */
5389 } else if (op
== '+' || op
== '-') {
5390 /* XXX: add non carry method too (for MIPS or alpha) */
5396 /* stack: H1 H2 (L1 op L2) */
5399 gen_op(op1
+ 1); /* TOK_xxxC2 */
5402 /* stack: H1 H2 (L1 op L2) */
5405 /* stack: (L1 op L2) H1 H2 */
5407 /* stack: (L1 op L2) (H1 op H2) */
5415 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
5416 t
= vtop
[-1].type
.t
;
5420 /* stack: L H shift */
5422 /* constant: simpler */
5423 /* NOTE: all comments are for SHL. the other cases are
5424 done by swaping words */
5435 if (op
!= TOK_SAR
) {
5468 /* XXX: should provide a faster fallback on x86 ? */
5471 func
= TOK___ashrdi3
;
5474 func
= TOK___lshrdi3
;
5477 func
= TOK___ashldi3
;
5483 /* compare operations */
5489 /* stack: L1 H1 L2 H2 */
5491 vtop
[-1] = vtop
[-2];
5493 /* stack: L1 L2 H1 H2 */
5496 /* when values are equal, we need to compare low words. since
5497 the jump is inverted, we invert the test too. */
5500 else if (op1
== TOK_GT
)
5502 else if (op1
== TOK_ULT
)
5504 else if (op1
== TOK_UGT
)
5509 if (op1
!= TOK_NE
) {
5513 /* generate non equal test */
5514 /* XXX: NOT PORTABLE yet */
5518 #if defined(TCC_TARGET_I386)
5519 b
= psym(0x850f, 0);
5520 #elif defined(TCC_TARGET_ARM)
5522 o(0x1A000000 | encbranch(ind
, 0, 1));
5523 #elif defined(TCC_TARGET_C67)
5524 error("not implemented");
5526 #error not supported
5530 /* compare low. Always unsigned */
5534 else if (op1
== TOK_LE
)
5536 else if (op1
== TOK_GT
)
5538 else if (op1
== TOK_GE
)
5549 /* handle integer constant optimizations and various machine
5551 void gen_opic(int op
)
5553 int c1
, c2
, t1
, t2
, n
;
5556 typedef unsigned long long U
;
5560 t1
= v1
->type
.t
& VT_BTYPE
;
5561 t2
= v2
->type
.t
& VT_BTYPE
;
5565 else if (v1
->type
.t
& VT_UNSIGNED
)
5572 else if (v2
->type
.t
& VT_UNSIGNED
)
5577 /* currently, we cannot do computations with forward symbols */
5578 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5579 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5582 case '+': l1
+= l2
; break;
5583 case '-': l1
-= l2
; break;
5584 case '&': l1
&= l2
; break;
5585 case '^': l1
^= l2
; break;
5586 case '|': l1
|= l2
; break;
5587 case '*': l1
*= l2
; break;
5594 /* if division by zero, generate explicit division */
5597 error("division by zero in constant");
5601 default: l1
/= l2
; break;
5602 case '%': l1
%= l2
; break;
5603 case TOK_UDIV
: l1
= (U
)l1
/ l2
; break;
5604 case TOK_UMOD
: l1
= (U
)l1
% l2
; break;
5607 case TOK_SHL
: l1
<<= l2
; break;
5608 case TOK_SHR
: l1
= (U
)l1
>> l2
; break;
5609 case TOK_SAR
: l1
>>= l2
; break;
5611 case TOK_ULT
: l1
= (U
)l1
< (U
)l2
; break;
5612 case TOK_UGE
: l1
= (U
)l1
>= (U
)l2
; break;
5613 case TOK_EQ
: l1
= l1
== l2
; break;
5614 case TOK_NE
: l1
= l1
!= l2
; break;
5615 case TOK_ULE
: l1
= (U
)l1
<= (U
)l2
; break;
5616 case TOK_UGT
: l1
= (U
)l1
> (U
)l2
; break;
5617 case TOK_LT
: l1
= l1
< l2
; break;
5618 case TOK_GE
: l1
= l1
>= l2
; break;
5619 case TOK_LE
: l1
= l1
<= l2
; break;
5620 case TOK_GT
: l1
= l1
> l2
; break;
5622 case TOK_LAND
: l1
= l1
&& l2
; break;
5623 case TOK_LOR
: l1
= l1
|| l2
; break;
5630 /* if commutative ops, put c2 as constant */
5631 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
5632 op
== '|' || op
== '*')) {
5634 c2
= c1
; //c = c1, c1 = c2, c2 = c;
5635 l2
= l1
; //l = l1, l1 = l2, l2 = l;
5637 /* Filter out NOP operations like x*1, x-0, x&-1... */
5638 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
5641 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
5642 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
5648 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
5649 /* try to use shifts instead of muls or divs */
5650 if (l2
> 0 && (l2
& (l2
- 1)) == 0) {
5659 else if (op
== TOK_PDIV
)
5665 } else if (c2
&& (op
== '+' || op
== '-') &&
5666 ((vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5667 (VT_CONST
| VT_SYM
) ||
5668 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
)) == VT_LOCAL
)) {
5669 /* symbol + constant case */
5676 if (!nocode_wanted
) {
5677 /* call low level op generator */
5678 if (t1
== VT_LLONG
|| t2
== VT_LLONG
)
5689 /* generate a floating point operation with constant propagation */
5690 void gen_opif(int op
)
5698 /* currently, we cannot do computations with forward symbols */
5699 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5700 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5702 if (v1
->type
.t
== VT_FLOAT
) {
5705 } else if (v1
->type
.t
== VT_DOUBLE
) {
5713 /* NOTE: we only do constant propagation if finite number (not
5714 NaN or infinity) (ANSI spec) */
5715 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5719 case '+': f1
+= f2
; break;
5720 case '-': f1
-= f2
; break;
5721 case '*': f1
*= f2
; break;
5725 error("division by zero in constant");
5730 /* XXX: also handles tests ? */
5734 /* XXX: overflow test ? */
5735 if (v1
->type
.t
== VT_FLOAT
) {
5737 } else if (v1
->type
.t
== VT_DOUBLE
) {
5745 if (!nocode_wanted
) {
5753 static int pointed_size(CType
*type
)
5756 return type_size(pointed_type(type
), &align
);
5759 static inline int is_null_pointer(SValue
*p
)
5761 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5763 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5764 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5767 static inline int is_integer_btype(int bt
)
5769 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5770 bt
== VT_INT
|| bt
== VT_LLONG
);
5773 /* check types for comparison or substraction of pointers */
5774 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5776 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5779 /* null pointers are accepted for all comparisons as gcc */
5780 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5784 bt1
= type1
->t
& VT_BTYPE
;
5785 bt2
= type2
->t
& VT_BTYPE
;
5786 /* accept comparison between pointer and integer with a warning */
5787 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5788 if (op
!= TOK_LOR
&& op
!= TOK_LAND
)
5789 warning("comparison between pointer and integer");
5793 /* both must be pointers or implicit function pointers */
5794 if (bt1
== VT_PTR
) {
5795 type1
= pointed_type(type1
);
5796 } else if (bt1
!= VT_FUNC
)
5797 goto invalid_operands
;
5799 if (bt2
== VT_PTR
) {
5800 type2
= pointed_type(type2
);
5801 } else if (bt2
!= VT_FUNC
) {
5803 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5805 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5806 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5810 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5811 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5812 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5813 /* gcc-like error if '-' is used */
5815 goto invalid_operands
;
5817 warning("comparison of distinct pointer types lacks a cast");
5821 /* generic gen_op: handles types problems */
5824 int u
, t1
, t2
, bt1
, bt2
, t
;
5827 t1
= vtop
[-1].type
.t
;
5828 t2
= vtop
[0].type
.t
;
5829 bt1
= t1
& VT_BTYPE
;
5830 bt2
= t2
& VT_BTYPE
;
5832 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5833 /* at least one operand is a pointer */
5834 /* relationnal op: must be both pointers */
5835 if (op
>= TOK_ULT
&& op
<= TOK_LOR
) {
5836 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5837 /* pointers are handled are unsigned */
5838 #ifdef TCC_TARGET_X86_64
5839 t
= VT_LLONG
| VT_UNSIGNED
;
5841 t
= VT_INT
| VT_UNSIGNED
;
5845 /* if both pointers, then it must be the '-' op */
5846 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5848 error("cannot use pointers here");
5849 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5850 /* XXX: check that types are compatible */
5851 u
= pointed_size(&vtop
[-1].type
);
5853 /* set to integer type */
5854 #ifdef TCC_TARGET_X86_64
5855 vtop
->type
.t
= VT_LLONG
;
5857 vtop
->type
.t
= VT_INT
;
5862 /* exactly one pointer : must be '+' or '-'. */
5863 if (op
!= '-' && op
!= '+')
5864 error("cannot use pointers here");
5865 /* Put pointer as first operand */
5866 if (bt2
== VT_PTR
) {
5870 type1
= vtop
[-1].type
;
5871 #ifdef TCC_TARGET_X86_64
5876 cval
.ull
= pointed_size(&vtop
[-1].type
);
5877 vsetc(&ctype
, VT_CONST
, &cval
);
5880 /* XXX: cast to int ? (long long case) */
5881 vpushi(pointed_size(&vtop
[-1].type
));
5884 #ifdef CONFIG_TCC_BCHECK
5885 /* if evaluating constant expression, no code should be
5886 generated, so no bound check */
5887 if (do_bounds_check
&& !const_wanted
) {
5888 /* if bounded pointers, we generate a special code to
5895 gen_bounded_ptr_add();
5901 /* put again type if gen_opic() swaped operands */
5904 } else if (is_float(bt1
) || is_float(bt2
)) {
5905 /* compute bigger type and do implicit casts */
5906 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5908 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5913 /* floats can only be used for a few operations */
5914 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5915 (op
< TOK_ULT
|| op
> TOK_GT
))
5916 error("invalid operands for binary operation");
5918 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5919 /* cast to biggest op */
5921 /* convert to unsigned if it does not fit in a long long */
5922 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5923 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5927 /* integer operations */
5929 /* convert to unsigned if it does not fit in an integer */
5930 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5931 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5934 /* XXX: currently, some unsigned operations are explicit, so
5935 we modify them here */
5936 if (t
& VT_UNSIGNED
) {
5943 else if (op
== TOK_LT
)
5945 else if (op
== TOK_GT
)
5947 else if (op
== TOK_LE
)
5949 else if (op
== TOK_GE
)
5956 /* special case for shifts and long long: we keep the shift as
5958 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5965 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5966 /* relationnal op: the result is an int */
5967 vtop
->type
.t
= VT_INT
;
5974 #ifndef TCC_TARGET_ARM
5975 /* generic itof for unsigned long long case */
5976 void gen_cvt_itof1(int t
)
5978 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
5979 (VT_LLONG
| VT_UNSIGNED
)) {
5982 vpush_global_sym(&func_old_type
, TOK___floatundisf
);
5983 #if LDOUBLE_SIZE != 8
5984 else if (t
== VT_LDOUBLE
)
5985 vpush_global_sym(&func_old_type
, TOK___floatundixf
);
5988 vpush_global_sym(&func_old_type
, TOK___floatundidf
);
5999 /* generic ftoi for unsigned long long case */
6000 void gen_cvt_ftoi1(int t
)
6004 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
6005 /* not handled natively */
6006 st
= vtop
->type
.t
& VT_BTYPE
;
6008 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
6009 #if LDOUBLE_SIZE != 8
6010 else if (st
== VT_LDOUBLE
)
6011 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
6014 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
6019 vtop
->r2
= REG_LRET
;
6025 /* force char or short cast */
6026 void force_charshort_cast(int t
)
6030 /* XXX: add optimization if lvalue : just change type and offset */
6035 if (t
& VT_UNSIGNED
) {
6036 vpushi((1 << bits
) - 1);
6042 /* result must be signed or the SAR is converted to an SHL
6043 This was not the case when "t" was a signed short
6044 and the last value on the stack was an unsigned int */
6045 vtop
->type
.t
&= ~VT_UNSIGNED
;
6051 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
6052 static void gen_cast(CType
*type
)
6054 int sbt
, dbt
, sf
, df
, c
, p
;
6056 /* special delayed cast for char/short */
6057 /* XXX: in some cases (multiple cascaded casts), it may still
6059 if (vtop
->r
& VT_MUSTCAST
) {
6060 vtop
->r
&= ~VT_MUSTCAST
;
6061 force_charshort_cast(vtop
->type
.t
);
6064 /* bitfields first get cast to ints */
6065 if (vtop
->type
.t
& VT_BITFIELD
) {
6069 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
6070 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
6075 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
6076 p
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == (VT_CONST
| VT_SYM
);
6078 /* constant case: we can do it now */
6079 /* XXX: in ISOC, cannot do it if error in convert */
6080 if (sbt
== VT_FLOAT
)
6081 vtop
->c
.ld
= vtop
->c
.f
;
6082 else if (sbt
== VT_DOUBLE
)
6083 vtop
->c
.ld
= vtop
->c
.d
;
6086 if ((sbt
& VT_BTYPE
) == VT_LLONG
) {
6087 if (sbt
& VT_UNSIGNED
)
6088 vtop
->c
.ld
= vtop
->c
.ull
;
6090 vtop
->c
.ld
= vtop
->c
.ll
;
6092 if (sbt
& VT_UNSIGNED
)
6093 vtop
->c
.ld
= vtop
->c
.ui
;
6095 vtop
->c
.ld
= vtop
->c
.i
;
6098 if (dbt
== VT_FLOAT
)
6099 vtop
->c
.f
= (float)vtop
->c
.ld
;
6100 else if (dbt
== VT_DOUBLE
)
6101 vtop
->c
.d
= (double)vtop
->c
.ld
;
6102 } else if (sf
&& dbt
== (VT_LLONG
|VT_UNSIGNED
)) {
6103 vtop
->c
.ull
= (unsigned long long)vtop
->c
.ld
;
6104 } else if (sf
&& dbt
== VT_BOOL
) {
6105 vtop
->c
.i
= (vtop
->c
.ld
!= 0);
6108 vtop
->c
.ll
= (long long)vtop
->c
.ld
;
6109 else if (sbt
== (VT_LLONG
|VT_UNSIGNED
))
6110 vtop
->c
.ll
= vtop
->c
.ull
;
6111 else if (sbt
& VT_UNSIGNED
)
6112 vtop
->c
.ll
= vtop
->c
.ui
;
6113 else if (sbt
!= VT_LLONG
)
6114 vtop
->c
.ll
= vtop
->c
.i
;
6116 if (dbt
== (VT_LLONG
|VT_UNSIGNED
))
6117 vtop
->c
.ull
= vtop
->c
.ll
;
6118 else if (dbt
== VT_BOOL
)
6119 vtop
->c
.i
= (vtop
->c
.ll
!= 0);
6120 else if (dbt
!= VT_LLONG
) {
6122 if ((dbt
& VT_BTYPE
) == VT_BYTE
)
6124 else if ((dbt
& VT_BTYPE
) == VT_SHORT
)
6127 if(dbt
& VT_UNSIGNED
)
6128 vtop
->c
.ui
= ((unsigned int)vtop
->c
.ll
<< s
) >> s
;
6130 vtop
->c
.i
= ((int)vtop
->c
.ll
<< s
) >> s
;
6133 } else if (p
&& dbt
== VT_BOOL
) {
6136 } else if (!nocode_wanted
) {
6137 /* non constant case: generate code */
6139 /* convert from fp to fp */
6142 /* convert int to fp */
6145 /* convert fp to int */
6146 if (dbt
== VT_BOOL
) {
6150 /* we handle char/short/etc... with generic code */
6151 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
6152 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
6156 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
6157 /* additional cast for char/short... */
6162 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
6163 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
6164 /* scalar to long long */
6165 #ifndef TCC_TARGET_X86_64
6166 /* machine independent conversion */
6168 /* generate high word */
6169 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
6177 /* patch second register */
6178 vtop
[-1].r2
= vtop
->r
;
6182 if (sbt
!= (VT_INT
| VT_UNSIGNED
)) {
6183 /* x86_64 specific: movslq */
6185 o(0xc0 + (REG_VALUE(r
) << 3) + REG_VALUE(r
));
6189 } else if (dbt
== VT_BOOL
) {
6190 /* scalar to bool */
6193 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
6194 (dbt
& VT_BTYPE
) == VT_SHORT
) {
6195 if (sbt
== VT_PTR
) {
6196 vtop
->type
.t
= VT_INT
;
6197 warning("nonportable conversion from pointer to char/short");
6199 force_charshort_cast(dbt
);
6200 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
6202 if (sbt
== VT_LLONG
) {
6203 /* from long long: just take low order word */
6207 /* if lvalue and single word type, nothing to do because
6208 the lvalue already contains the real type size (see
6209 VT_LVAL_xxx constants) */
6212 } else if ((dbt
& VT_BTYPE
) == VT_PTR
&& !(vtop
->r
& VT_LVAL
)) {
6213 /* if we are casting between pointer types,
6214 we must update the VT_LVAL_xxx size */
6215 vtop
->r
= (vtop
->r
& ~VT_LVAL_TYPE
)
6216 | (lvalue_type(type
->ref
->type
.t
) & VT_LVAL_TYPE
);
6221 /* return type size. Put alignment at 'a' */
6222 static int type_size(CType
*type
, int *a
)
6227 bt
= type
->t
& VT_BTYPE
;
6228 if (bt
== VT_STRUCT
) {
6233 } else if (bt
== VT_PTR
) {
6234 if (type
->t
& VT_ARRAY
) {
6238 ts
= type_size(&s
->type
, a
);
6240 if (ts
< 0 && s
->c
< 0)
6248 } else if (bt
== VT_LDOUBLE
) {
6250 return LDOUBLE_SIZE
;
6251 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
6252 #ifdef TCC_TARGET_I386
6254 #elif defined(TCC_TARGET_ARM)
6264 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
6267 } else if (bt
== VT_SHORT
) {
6271 /* char, void, function, _Bool */
6277 /* return the pointed type of t */
6278 static inline CType
*pointed_type(CType
*type
)
6280 return &type
->ref
->type
;
6283 /* modify type so that its it is a pointer to type. */
6284 static void mk_pointer(CType
*type
)
6287 s
= sym_push(SYM_FIELD
, type
, 0, -1);
6288 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
6292 /* compare function types. OLD functions match any new functions */
6293 static int is_compatible_func(CType
*type1
, CType
*type2
)
6299 if (!is_compatible_types(&s1
->type
, &s2
->type
))
6301 /* check func_call */
6302 if (FUNC_CALL(s1
->r
) != FUNC_CALL(s2
->r
))
6304 /* XXX: not complete */
6305 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
6309 while (s1
!= NULL
) {
6312 if (!is_compatible_parameter_types(&s1
->type
, &s2
->type
))
6322 /* return true if type1 and type2 are the same. If unqualified is
6323 true, qualifiers on the types are ignored.
6325 - enums are not checked as gcc __builtin_types_compatible_p ()
6327 static int compare_types(CType
*type1
, CType
*type2
, int unqualified
)
6331 t1
= type1
->t
& VT_TYPE
;
6332 t2
= type2
->t
& VT_TYPE
;
6334 /* strip qualifiers before comparing */
6335 t1
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6336 t2
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6338 /* XXX: bitfields ? */
6341 /* test more complicated cases */
6342 bt1
= t1
& VT_BTYPE
;
6343 if (bt1
== VT_PTR
) {
6344 type1
= pointed_type(type1
);
6345 type2
= pointed_type(type2
);
6346 return is_compatible_types(type1
, type2
);
6347 } else if (bt1
== VT_STRUCT
) {
6348 return (type1
->ref
== type2
->ref
);
6349 } else if (bt1
== VT_FUNC
) {
6350 return is_compatible_func(type1
, type2
);
6356 /* return true if type1 and type2 are exactly the same (including
6359 static int is_compatible_types(CType
*type1
, CType
*type2
)
6361 return compare_types(type1
,type2
,0);
6364 /* return true if type1 and type2 are the same (ignoring qualifiers).
6366 static int is_compatible_parameter_types(CType
*type1
, CType
*type2
)
6368 return compare_types(type1
,type2
,1);
6371 /* print a type. If 'varstr' is not NULL, then the variable is also
6372 printed in the type */
6374 /* XXX: add array and function pointers */
6375 void type_to_str(char *buf
, int buf_size
,
6376 CType
*type
, const char *varstr
)
6383 t
= type
->t
& VT_TYPE
;
6386 if (t
& VT_CONSTANT
)
6387 pstrcat(buf
, buf_size
, "const ");
6388 if (t
& VT_VOLATILE
)
6389 pstrcat(buf
, buf_size
, "volatile ");
6390 if (t
& VT_UNSIGNED
)
6391 pstrcat(buf
, buf_size
, "unsigned ");
6421 tstr
= "long double";
6423 pstrcat(buf
, buf_size
, tstr
);
6427 if (bt
== VT_STRUCT
)
6431 pstrcat(buf
, buf_size
, tstr
);
6432 v
= type
->ref
->v
& ~SYM_STRUCT
;
6433 if (v
>= SYM_FIRST_ANOM
)
6434 pstrcat(buf
, buf_size
, "<anonymous>");
6436 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
6440 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
6441 pstrcat(buf
, buf_size
, "(");
6443 while (sa
!= NULL
) {
6444 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
6445 pstrcat(buf
, buf_size
, buf1
);
6448 pstrcat(buf
, buf_size
, ", ");
6450 pstrcat(buf
, buf_size
, ")");
6454 pstrcpy(buf1
, sizeof(buf1
), "*");
6456 pstrcat(buf1
, sizeof(buf1
), varstr
);
6457 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
6461 pstrcat(buf
, buf_size
, " ");
6462 pstrcat(buf
, buf_size
, varstr
);
6467 /* verify type compatibility to store vtop in 'dt' type, and generate
6469 static void gen_assign_cast(CType
*dt
)
6471 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
6472 char buf1
[256], buf2
[256];
6475 st
= &vtop
->type
; /* source type */
6476 dbt
= dt
->t
& VT_BTYPE
;
6477 sbt
= st
->t
& VT_BTYPE
;
6478 if (dt
->t
& VT_CONSTANT
)
6479 warning("assignment of read-only location");
6482 /* special cases for pointers */
6483 /* '0' can also be a pointer */
6484 if (is_null_pointer(vtop
))
6486 /* accept implicit pointer to integer cast with warning */
6487 if (is_integer_btype(sbt
)) {
6488 warning("assignment makes pointer from integer without a cast");
6491 type1
= pointed_type(dt
);
6492 /* a function is implicitely a function pointer */
6493 if (sbt
== VT_FUNC
) {
6494 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
6495 !is_compatible_types(pointed_type(dt
), st
))
6502 type2
= pointed_type(st
);
6503 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
6504 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
6505 /* void * can match anything */
6507 /* exact type match, except for unsigned */
6510 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6511 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6512 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
6513 warning("assignment from incompatible pointer type");
6515 /* check const and volatile */
6516 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
6517 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
6518 warning("assignment discards qualifiers from pointer target type");
6524 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
6525 warning("assignment makes integer from pointer without a cast");
6527 /* XXX: more tests */
6532 tmp_type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6533 tmp_type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6534 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
6536 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
6537 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
6538 error("cannot cast '%s' to '%s'", buf1
, buf2
);
6546 /* store vtop in lvalue pushed on stack */
6549 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
6551 ft
= vtop
[-1].type
.t
;
6552 sbt
= vtop
->type
.t
& VT_BTYPE
;
6553 dbt
= ft
& VT_BTYPE
;
6554 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
6555 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
6556 /* optimize char/short casts */
6557 delayed_cast
= VT_MUSTCAST
;
6558 vtop
->type
.t
= ft
& (VT_TYPE
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
)));
6559 /* XXX: factorize */
6560 if (ft
& VT_CONSTANT
)
6561 warning("assignment of read-only location");
6564 if (!(ft
& VT_BITFIELD
))
6565 gen_assign_cast(&vtop
[-1].type
);
6568 if (sbt
== VT_STRUCT
) {
6569 /* if structure, only generate pointer */
6570 /* structure assignment : generate memcpy */
6571 /* XXX: optimize if small size */
6572 if (!nocode_wanted
) {
6573 size
= type_size(&vtop
->type
, &align
);
6577 vpush_global_sym(&func_old_type
, TOK_memcpy8
);
6578 else if(!(align
& 3))
6579 vpush_global_sym(&func_old_type
, TOK_memcpy4
);
6582 vpush_global_sym(&func_old_type
, TOK_memcpy
);
6586 vtop
->type
.t
= VT_INT
;
6590 vtop
->type
.t
= VT_INT
;
6602 /* leave source on stack */
6603 } else if (ft
& VT_BITFIELD
) {
6604 /* bitfield store handling */
6605 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
6606 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
6607 /* remove bit field info to avoid loops */
6608 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
6610 /* duplicate source into other register */
6615 if((ft
& VT_BTYPE
) == VT_BOOL
) {
6616 gen_cast(&vtop
[-1].type
);
6617 vtop
[-1].type
.t
= (vtop
[-1].type
.t
& ~VT_BTYPE
) | (VT_BYTE
| VT_UNSIGNED
);
6620 /* duplicate destination */
6622 vtop
[-1] = vtop
[-2];
6624 /* mask and shift source */
6625 if((ft
& VT_BTYPE
) != VT_BOOL
) {
6626 vpushi((1 << bit_size
) - 1);
6631 /* load destination, mask and or with source */
6633 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
6639 /* pop off shifted source from "duplicate source..." above */
6643 #ifdef CONFIG_TCC_BCHECK
6644 /* bound check case */
6645 if (vtop
[-1].r
& VT_MUSTBOUND
) {
6651 if (!nocode_wanted
) {
6655 #ifdef TCC_TARGET_X86_64
6656 if ((ft
& VT_BTYPE
) == VT_LDOUBLE
) {
6661 r
= gv(rc
); /* generate value */
6662 /* if lvalue was saved on stack, must read it */
6663 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
6665 t
= get_reg(RC_INT
);
6666 #ifdef TCC_TARGET_X86_64
6671 sv
.r
= VT_LOCAL
| VT_LVAL
;
6672 sv
.c
.ul
= vtop
[-1].c
.ul
;
6674 vtop
[-1].r
= t
| VT_LVAL
;
6677 #ifndef TCC_TARGET_X86_64
6678 /* two word case handling : store second register at word + 4 */
6679 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
6681 /* convert to int to increment easily */
6682 vtop
->type
.t
= VT_INT
;
6688 /* XXX: it works because r2 is spilled last ! */
6689 store(vtop
->r2
, vtop
- 1);
6694 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
6695 vtop
->r
|= delayed_cast
;
6699 /* post defines POST/PRE add. c is the token ++ or -- */
6700 void inc(int post
, int c
)
6703 vdup(); /* save lvalue */
6705 gv_dup(); /* duplicate value */
6710 vpushi(c
- TOK_MID
);
6712 vstore(); /* store value */
6714 vpop(); /* if post op, return saved value */
6717 /* Parse GNUC __attribute__ extension. Currently, the following
6718 extensions are recognized:
6719 - aligned(n) : set data/function alignment.
6720 - packed : force data alignment to 1
6721 - section(x) : generate data/code in this section.
6722 - unused : currently ignored, but may be used someday.
6723 - regparm(n) : pass function parameters in registers (i386 only)
6725 static void parse_attribute(AttributeDef
*ad
)
6729 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
6733 while (tok
!= ')') {
6734 if (tok
< TOK_IDENT
)
6735 expect("attribute name");
6743 expect("section name");
6744 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
6753 if (n
<= 0 || (n
& (n
- 1)) != 0)
6754 error("alignment must be a positive power of two");
6767 /* currently, no need to handle it because tcc does not
6768 track unused objects */
6772 /* currently, no need to handle it because tcc does not
6773 track unused objects */
6778 FUNC_CALL(ad
->func_attr
) = FUNC_CDECL
;
6783 FUNC_CALL(ad
->func_attr
) = FUNC_STDCALL
;
6785 #ifdef TCC_TARGET_I386
6795 FUNC_CALL(ad
->func_attr
) = FUNC_FASTCALL1
+ n
- 1;
6801 FUNC_CALL(ad
->func_attr
) = FUNC_FASTCALLW
;
6805 FUNC_EXPORT(ad
->func_attr
) = 1;
6808 if (tcc_state
->warn_unsupported
)
6809 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6810 /* skip parameters */
6812 int parenthesis
= 0;
6816 else if (tok
== ')')
6819 } while (parenthesis
&& tok
!= -1);
6832 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6833 static void struct_decl(CType
*type
, int u
)
6835 int a
, v
, size
, align
, maxalign
, c
, offset
;
6836 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
, prevbt
;
6837 Sym
*s
, *ss
, *ass
, **ps
;
6841 a
= tok
; /* save decl type */
6846 /* struct already defined ? return it */
6848 expect("struct/union/enum name");
6852 error("invalid type");
6859 /* we put an undefined size for struct/union */
6860 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6861 s
->r
= 0; /* default alignment is zero as gcc */
6862 /* put struct/union/enum name in type */
6870 error("struct/union/enum already defined");
6871 /* cannot be empty */
6873 /* non empty enums are not allowed */
6874 if (a
== TOK_ENUM
) {
6878 expect("identifier");
6884 /* enum symbols have static storage */
6885 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6886 ss
->type
.t
|= VT_STATIC
;
6891 /* NOTE: we accept a trailing comma */
6902 while (tok
!= '}') {
6903 parse_btype(&btype
, &ad
);
6909 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6910 if (v
== 0 && (type1
.t
& VT_BTYPE
) != VT_STRUCT
)
6911 expect("identifier");
6912 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6913 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6914 error("invalid type for '%s'",
6915 get_tok_str(v
, NULL
));
6919 bit_size
= expr_const();
6920 /* XXX: handle v = 0 case for messages */
6922 error("negative width in bit-field '%s'",
6923 get_tok_str(v
, NULL
));
6924 if (v
&& bit_size
== 0)
6925 error("zero width for bit-field '%s'",
6926 get_tok_str(v
, NULL
));
6928 size
= type_size(&type1
, &align
);
6930 if (align
< ad
.aligned
)
6932 } else if (ad
.packed
) {
6934 } else if (*tcc_state
->pack_stack_ptr
) {
6935 if (align
> *tcc_state
->pack_stack_ptr
)
6936 align
= *tcc_state
->pack_stack_ptr
;
6939 if (bit_size
>= 0) {
6940 bt
= type1
.t
& VT_BTYPE
;
6946 error("bitfields must have scalar type");
6948 if (bit_size
> bsize
) {
6949 error("width of '%s' exceeds its type",
6950 get_tok_str(v
, NULL
));
6951 } else if (bit_size
== bsize
) {
6952 /* no need for bit fields */
6954 } else if (bit_size
== 0) {
6955 /* XXX: what to do if only padding in a
6957 /* zero size: means to pad */
6960 /* we do not have enough room ?
6961 did the type change?
6963 if ((bit_pos
+ bit_size
) > bsize
||
6964 bt
!= prevbt
|| a
== TOK_UNION
)
6967 /* XXX: handle LSB first */
6968 type1
.t
|= VT_BITFIELD
|
6969 (bit_pos
<< VT_STRUCT_SHIFT
) |
6970 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
6971 bit_pos
+= bit_size
;
6977 if (v
!= 0 || (type1
.t
& VT_BTYPE
) == VT_STRUCT
) {
6978 /* add new memory data only if starting
6980 if (lbit_pos
== 0) {
6981 if (a
== TOK_STRUCT
) {
6982 c
= (c
+ align
- 1) & -align
;
6991 if (align
> maxalign
)
6995 printf("add field %s offset=%d",
6996 get_tok_str(v
, NULL
), offset
);
6997 if (type1
.t
& VT_BITFIELD
) {
6998 printf(" pos=%d size=%d",
6999 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
7000 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
7005 if (v
== 0 && (type1
.t
& VT_BTYPE
) == VT_STRUCT
) {
7007 while ((ass
= ass
->next
) != NULL
) {
7008 ss
= sym_push(ass
->v
, &ass
->type
, 0, offset
+ ass
->c
);
7013 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
7017 if (tok
== ';' || tok
== TOK_EOF
)
7024 /* store size and alignment */
7025 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
7031 /* return 0 if no type declaration. otherwise, return the basic type
7034 static int parse_btype(CType
*type
, AttributeDef
*ad
)
7036 int t
, u
, type_found
, typespec_found
, typedef_found
;
7040 memset(ad
, 0, sizeof(AttributeDef
));
7048 /* currently, we really ignore extension */
7058 if ((t
& VT_BTYPE
) != 0)
7059 error("too many basic types");
7075 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
7076 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
7077 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
7078 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
7092 if ((t
& VT_BTYPE
) == VT_LONG
) {
7093 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
7100 struct_decl(&type1
, VT_ENUM
);
7103 type
->ref
= type1
.ref
;
7107 struct_decl(&type1
, VT_STRUCT
);
7110 /* type modifiers */
7163 /* GNUC attribute */
7164 case TOK_ATTRIBUTE1
:
7165 case TOK_ATTRIBUTE2
:
7166 parse_attribute(ad
);
7173 parse_expr_type(&type1
);
7176 if (typespec_found
|| typedef_found
)
7179 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
7182 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
7183 type
->ref
= s
->type
.ref
;
7191 if ((t
& (VT_SIGNED
|VT_UNSIGNED
)) == (VT_SIGNED
|VT_UNSIGNED
))
7192 error("signed and unsigned modifier");
7193 if (tcc_state
->char_is_unsigned
) {
7194 if ((t
& (VT_SIGNED
|VT_UNSIGNED
|VT_BTYPE
)) == VT_BYTE
)
7199 /* long is never used as type */
7200 if ((t
& VT_BTYPE
) == VT_LONG
)
7201 #ifndef TCC_TARGET_X86_64
7202 t
= (t
& ~VT_BTYPE
) | VT_INT
;
7204 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
7210 /* convert a function parameter type (array to pointer and function to
7211 function pointer) */
7212 static inline void convert_parameter_type(CType
*pt
)
7214 /* remove const and volatile qualifiers (XXX: const could be used
7215 to indicate a const function parameter */
7216 pt
->t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7217 /* array must be transformed to pointer according to ANSI C */
7219 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
7224 static void post_type(CType
*type
, AttributeDef
*ad
)
7226 int n
, l
, t1
, arg_size
, align
;
7227 Sym
**plast
, *s
, *first
;
7232 /* function declaration */
7240 /* read param name and compute offset */
7241 if (l
!= FUNC_OLD
) {
7242 if (!parse_btype(&pt
, &ad1
)) {
7244 error("invalid type");
7251 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
7253 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
7254 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
7255 error("parameter declared as void");
7256 arg_size
+= (type_size(&pt
, &align
) + 3) & ~3;
7261 expect("identifier");
7265 convert_parameter_type(&pt
);
7266 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
7272 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
7279 /* if no parameters, then old type prototype */
7283 t1
= type
->t
& VT_STORAGE
;
7284 /* NOTE: const is ignored in returned type as it has a special
7285 meaning in gcc / C++ */
7286 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
7287 post_type(type
, ad
);
7288 /* we push a anonymous symbol which will contain the function prototype */
7289 FUNC_ARGS(ad
->func_attr
) = arg_size
;
7290 s
= sym_push(SYM_FIELD
, type
, ad
->func_attr
, l
);
7292 type
->t
= t1
| VT_FUNC
;
7294 } else if (tok
== '[') {
7295 /* array definition */
7301 error("invalid array size");
7304 /* parse next post type */
7305 t1
= type
->t
& VT_STORAGE
;
7306 type
->t
&= ~VT_STORAGE
;
7307 post_type(type
, ad
);
7309 /* we push a anonymous symbol which will contain the array
7311 s
= sym_push(SYM_FIELD
, type
, 0, n
);
7312 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
7317 /* Parse a type declaration (except basic type), and return the type
7318 in 'type'. 'td' is a bitmask indicating which kind of type decl is
7319 expected. 'type' should contain the basic type. 'ad' is the
7320 attribute definition of the basic type. It can be modified by
7323 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
7326 CType type1
, *type2
;
7329 while (tok
== '*') {
7337 qualifiers
|= VT_CONSTANT
;
7342 qualifiers
|= VT_VOLATILE
;
7350 type
->t
|= qualifiers
;
7353 /* XXX: clarify attribute handling */
7354 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7355 parse_attribute(ad
);
7357 /* recursive type */
7358 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
7359 type1
.t
= 0; /* XXX: same as int */
7362 /* XXX: this is not correct to modify 'ad' at this point, but
7363 the syntax is not clear */
7364 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7365 parse_attribute(ad
);
7366 type_decl(&type1
, ad
, v
, td
);
7369 /* type identifier */
7370 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
7374 if (!(td
& TYPE_ABSTRACT
))
7375 expect("identifier");
7379 post_type(type
, ad
);
7380 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7381 parse_attribute(ad
);
7384 /* append type at the end of type1 */
7397 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
7398 static int lvalue_type(int t
)
7403 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
7405 else if (bt
== VT_SHORT
)
7409 if (t
& VT_UNSIGNED
)
7410 r
|= VT_LVAL_UNSIGNED
;
7414 /* indirection with full error checking and bound check */
7415 static void indir(void)
7417 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
) {
7418 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FUNC
)
7422 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
7424 vtop
->type
= *pointed_type(&vtop
->type
);
7425 /* Arrays and functions are never lvalues */
7426 if (!(vtop
->type
.t
& VT_ARRAY
)
7427 && (vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7428 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7429 /* if bound checking, the referenced pointer must be checked */
7430 if (do_bounds_check
)
7431 vtop
->r
|= VT_MUSTBOUND
;
7435 /* pass a parameter to a function and do type checking and casting */
7436 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
7441 func_type
= func
->c
;
7442 if (func_type
== FUNC_OLD
||
7443 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
7444 /* default casting : only need to convert float to double */
7445 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
7449 } else if (arg
== NULL
) {
7450 error("too many arguments to function");
7453 type
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
7454 gen_assign_cast(&type
);
7458 /* parse an expression of the form '(type)' or '(expr)' and return its
7460 static void parse_expr_type(CType
*type
)
7466 if (parse_btype(type
, &ad
)) {
7467 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7474 static void parse_type(CType
*type
)
7479 if (!parse_btype(type
, &ad
)) {
7482 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7485 static void vpush_tokc(int t
)
7489 vsetc(&type
, VT_CONST
, &tokc
);
7492 static void unary(void)
7494 int n
, t
, align
, size
, r
;
7499 /* XXX: GCC 2.95.3 does not generate a table although it should be
7513 vpush_tokc(VT_INT
| VT_UNSIGNED
);
7517 vpush_tokc(VT_LLONG
);
7521 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
7525 vpush_tokc(VT_FLOAT
);
7529 vpush_tokc(VT_DOUBLE
);
7533 vpush_tokc(VT_LDOUBLE
);
7536 case TOK___FUNCTION__
:
7538 goto tok_identifier
;
7544 /* special function name identifier */
7545 len
= strlen(funcname
) + 1;
7546 /* generate char[len] type */
7551 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
7552 ptr
= section_ptr_add(data_section
, len
);
7553 memcpy(ptr
, funcname
, len
);
7558 #ifdef TCC_TARGET_PE
7559 t
= VT_SHORT
| VT_UNSIGNED
;
7565 /* string parsing */
7568 if (tcc_state
->warn_write_strings
)
7573 memset(&ad
, 0, sizeof(AttributeDef
));
7574 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
7579 if (parse_btype(&type
, &ad
)) {
7580 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
7582 /* check ISOC99 compound literal */
7584 /* data is allocated locally by default */
7589 /* all except arrays are lvalues */
7590 if (!(type
.t
& VT_ARRAY
))
7591 r
|= lvalue_type(type
.t
);
7592 memset(&ad
, 0, sizeof(AttributeDef
));
7593 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
7598 } else if (tok
== '{') {
7599 /* save all registers */
7601 /* statement expression : we do not accept break/continue
7602 inside as GCC does */
7603 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
7618 /* functions names must be treated as function pointers,
7619 except for unary '&' and sizeof. Since we consider that
7620 functions are not lvalues, we only have to handle it
7621 there and in function calls. */
7622 /* arrays can also be used although they are not lvalues */
7623 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
7624 !(vtop
->type
.t
& VT_ARRAY
) && !(vtop
->type
.t
& VT_LLOCAL
))
7626 mk_pointer(&vtop
->type
);
7632 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
7634 boolean
.t
= VT_BOOL
;
7636 vtop
->c
.i
= !vtop
->c
.i
;
7637 } else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
7638 vtop
->c
.i
= vtop
->c
.i
^ 1;
7641 vseti(VT_JMP
, gtst(1, 0));
7652 /* in order to force cast, we add zero */
7654 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
7655 error("pointer not accepted for unary plus");
7665 parse_expr_type(&type
);
7669 size
= type_size(&type
, &align
);
7670 if (t
== TOK_SIZEOF
) {
7672 error("sizeof applied to an incomplete type");
7677 vtop
->type
.t
|= VT_UNSIGNED
;
7680 case TOK_builtin_types_compatible_p
:
7689 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7690 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7691 vpushi(is_compatible_types(&type1
, &type2
));
7694 case TOK_builtin_constant_p
:
7696 int saved_nocode_wanted
, res
;
7699 saved_nocode_wanted
= nocode_wanted
;
7702 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
7704 nocode_wanted
= saved_nocode_wanted
;
7709 case TOK_builtin_frame_address
:
7714 if (tok
!= TOK_CINT
) {
7715 error("__builtin_frame_address only takes integers");
7718 error("TCC only supports __builtin_frame_address(0)");
7724 vset(&type
, VT_LOCAL
, 0);
7742 goto tok_identifier
;
7744 /* allow to take the address of a label */
7745 if (tok
< TOK_UIDENT
)
7746 expect("label identifier");
7747 s
= label_find(tok
);
7749 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7751 if (s
->r
== LABEL_DECLARED
)
7752 s
->r
= LABEL_FORWARD
;
7755 s
->type
.t
= VT_VOID
;
7756 mk_pointer(&s
->type
);
7757 s
->type
.t
|= VT_STATIC
;
7759 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
7768 expect("identifier");
7772 error("'%s' undeclared", get_tok_str(t
, NULL
));
7773 /* for simple function calls, we tolerate undeclared
7774 external reference to int() function */
7775 if (tcc_state
->warn_implicit_function_declaration
)
7776 warning("implicit declaration of function '%s'",
7777 get_tok_str(t
, NULL
));
7778 s
= external_global_sym(t
, &func_old_type
, 0);
7780 if ((s
->type
.t
& (VT_STATIC
| VT_INLINE
| VT_BTYPE
)) ==
7781 (VT_STATIC
| VT_INLINE
| VT_FUNC
)) {
7782 /* if referencing an inline function, then we generate a
7783 symbol to it if not already done. It will have the
7784 effect to generate code for it at the end of the
7785 compilation unit. Inline function as always
7786 generated in the text section. */
7788 put_extern_sym(s
, text_section
, 0, 0);
7789 r
= VT_SYM
| VT_CONST
;
7793 vset(&s
->type
, r
, s
->c
);
7794 /* if forward reference, we must point to s */
7795 if (vtop
->r
& VT_SYM
) {
7802 /* post operations */
7804 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
7807 } else if (tok
== '.' || tok
== TOK_ARROW
) {
7809 if (tok
== TOK_ARROW
)
7814 /* expect pointer on structure */
7815 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
7816 expect("struct or union");
7820 while ((s
= s
->next
) != NULL
) {
7825 error("field not found: %s", get_tok_str(tok
& ~SYM_FIELD
, NULL
));
7826 /* add field offset to pointer */
7827 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
7830 /* change type to field type, and set to lvalue */
7831 vtop
->type
= s
->type
;
7832 /* an array is never an lvalue */
7833 if (!(vtop
->type
.t
& VT_ARRAY
)) {
7834 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7835 /* if bound checking, the referenced pointer must be checked */
7836 if (do_bounds_check
)
7837 vtop
->r
|= VT_MUSTBOUND
;
7840 } else if (tok
== '[') {
7846 } else if (tok
== '(') {
7852 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7853 /* pointer test (no array accepted) */
7854 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
7855 vtop
->type
= *pointed_type(&vtop
->type
);
7856 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
7860 expect("function pointer");
7863 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
7865 /* get return type */
7868 sa
= s
->next
; /* first parameter */
7871 /* compute first implicit argument if a structure is returned */
7872 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
7873 /* get some space for the returned structure */
7874 size
= type_size(&s
->type
, &align
);
7875 loc
= (loc
- size
) & -align
;
7877 ret
.r
= VT_LOCAL
| VT_LVAL
;
7878 /* pass it as 'int' to avoid structure arg passing
7880 vseti(VT_LOCAL
, loc
);
7885 /* return in register */
7886 if (is_float(ret
.type
.t
)) {
7889 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
7898 gfunc_param_typed(s
, sa
);
7908 error("too few arguments to function");
7910 if (!nocode_wanted
) {
7911 gfunc_call(nb_args
);
7913 vtop
-= (nb_args
+ 1);
7916 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
7924 static void uneq(void)
7930 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
7931 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
7932 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
7947 static void expr_prod(void)
7952 while (tok
== '*' || tok
== '/' || tok
== '%') {
7960 static void expr_sum(void)
7965 while (tok
== '+' || tok
== '-') {
7973 static void expr_shift(void)
7978 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
7986 static void expr_cmp(void)
7991 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
7992 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
8000 static void expr_cmpeq(void)
8005 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
8013 static void expr_and(void)
8016 while (tok
== '&') {
8023 static void expr_xor(void)
8026 while (tok
== '^') {
8033 static void expr_or(void)
8036 while (tok
== '|') {
8043 /* XXX: fix this mess */
8044 static void expr_land_const(void)
8047 while (tok
== TOK_LAND
) {
8054 /* XXX: fix this mess */
8055 static void expr_lor_const(void)
8058 while (tok
== TOK_LOR
) {
8065 /* only used if non constant */
8066 static void expr_land(void)
8071 if (tok
== TOK_LAND
) {
8076 if (tok
!= TOK_LAND
) {
8086 static void expr_lor(void)
8091 if (tok
== TOK_LOR
) {
8096 if (tok
!= TOK_LOR
) {
8106 /* XXX: better constant handling */
8107 static void expr_eq(void)
8109 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
8111 CType type
, type1
, type2
;
8118 boolean
.t
= VT_BOOL
;
8124 if (tok
!= ':' || !gnu_ext
) {
8139 if (vtop
!= vstack
) {
8140 /* needed to avoid having different registers saved in
8142 if (is_float(vtop
->type
.t
)) {
8144 #ifdef TCC_TARGET_X86_64
8145 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LDOUBLE
) {
8155 if (tok
== ':' && gnu_ext
) {
8163 sv
= *vtop
; /* save value to handle it later */
8164 vtop
--; /* no vpop so that FP stack is not flushed */
8172 bt1
= t1
& VT_BTYPE
;
8174 bt2
= t2
& VT_BTYPE
;
8175 /* cast operands to correct type according to ISOC rules */
8176 if (is_float(bt1
) || is_float(bt2
)) {
8177 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
8178 type
.t
= VT_LDOUBLE
;
8179 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
8184 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
8185 /* cast to biggest op */
8187 /* convert to unsigned if it does not fit in a long long */
8188 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
8189 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
8190 type
.t
|= VT_UNSIGNED
;
8191 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
8192 /* XXX: test pointer compatibility */
8194 } else if (bt1
== VT_FUNC
|| bt2
== VT_FUNC
) {
8195 /* XXX: test function pointer compatibility */
8197 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
8198 /* XXX: test structure compatibility */
8200 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
8201 /* NOTE: as an extension, we accept void on only one side */
8204 /* integer operations */
8206 /* convert to unsigned if it does not fit in an integer */
8207 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
8208 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
8209 type
.t
|= VT_UNSIGNED
;
8212 /* now we convert second operand */
8214 if (VT_STRUCT
== (vtop
->type
.t
& VT_BTYPE
))
8217 if (is_float(type
.t
)) {
8219 #ifdef TCC_TARGET_X86_64
8220 if ((type
.t
& VT_BTYPE
) == VT_LDOUBLE
) {
8224 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
8225 /* for long longs, we use fixed registers to avoid having
8226 to handle a complicated move */
8231 /* this is horrible, but we must also convert first
8235 /* put again first value and cast it */
8238 if (VT_STRUCT
== (vtop
->type
.t
& VT_BTYPE
))
8248 static void gexpr(void)
8259 /* parse an expression and return its type without any side effect. */
8260 static void expr_type(CType
*type
)
8262 int saved_nocode_wanted
;
8264 saved_nocode_wanted
= nocode_wanted
;
8269 nocode_wanted
= saved_nocode_wanted
;
8272 /* parse a unary expression and return its type without any side
8274 static void unary_type(CType
*type
)
8286 /* parse a constant expression and return value in vtop. */
8287 static void expr_const1(void)
8296 /* parse an integer constant and return its value. */
8297 static int expr_const(void)
8301 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
8302 expect("constant expression");
8308 /* return the label token if current token is a label, otherwise
8310 static int is_label(void)
8314 /* fast test first */
8315 if (tok
< TOK_UIDENT
)
8317 /* no need to save tokc because tok is an identifier */
8324 unget_tok(last_tok
);
8329 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
8330 int case_reg
, int is_expr
)
8335 /* generate line number info */
8337 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
8338 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
8340 last_line_num
= file
->line_num
;
8344 /* default return value is (void) */
8346 vtop
->type
.t
= VT_VOID
;
8349 if (tok
== TOK_IF
) {
8356 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
8358 if (c
== TOK_ELSE
) {
8362 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
8363 gsym(d
); /* patch else jmp */
8366 } else if (tok
== TOK_WHILE
) {
8374 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8378 } else if (tok
== '{') {
8382 /* record local declaration stack position */
8384 llabel
= local_label_stack
;
8385 /* handle local labels declarations */
8386 if (tok
== TOK_LABEL
) {
8389 if (tok
< TOK_UIDENT
)
8390 expect("label identifier");
8391 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
8401 while (tok
!= '}') {
8406 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8409 /* pop locally defined labels */
8410 label_pop(&local_label_stack
, llabel
);
8411 /* pop locally defined symbols */
8413 /* XXX: this solution makes only valgrind happy...
8414 triggered by gcc.c-torture/execute/20000917-1.c */
8416 switch(vtop
->type
.t
& VT_BTYPE
) {
8421 for(p
=vtop
->type
.ref
;p
;p
=p
->prev
)
8423 error("unsupported expression type");
8426 sym_pop(&local_stack
, s
);
8428 } else if (tok
== TOK_RETURN
) {
8432 gen_assign_cast(&func_vt
);
8433 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
8435 /* if returning structure, must copy it to implicit
8436 first pointer arg location */
8439 size
= type_size(&func_vt
,&align
);
8442 if((vtop
->r
!= (VT_LOCAL
| VT_LVAL
) || (vtop
->c
.i
& 3))
8446 loc
= (loc
- size
) & -4;
8449 vset(&type
, VT_LOCAL
| VT_LVAL
, addr
);
8452 vset(&int_type
, VT_LOCAL
| VT_LVAL
, addr
);
8454 vtop
->type
= int_type
;
8460 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
8463 /* copy structure value to pointer */
8468 } else if (is_float(func_vt
.t
)) {
8473 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
8476 rsym
= gjmp(rsym
); /* jmp */
8477 } else if (tok
== TOK_BREAK
) {
8480 error("cannot break");
8481 *bsym
= gjmp(*bsym
);
8484 } else if (tok
== TOK_CONTINUE
) {
8487 error("cannot continue");
8488 *csym
= gjmp(*csym
);
8491 } else if (tok
== TOK_FOR
) {
8518 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8523 if (tok
== TOK_DO
) {
8528 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8539 if (tok
== TOK_SWITCH
) {
8543 /* XXX: other types than integer */
8544 case_reg
= gv(RC_INT
);
8548 b
= gjmp(0); /* jump to first case */
8550 block(&a
, csym
, &b
, &c
, case_reg
, 0);
8551 /* if no default, jmp after switch */
8559 if (tok
== TOK_CASE
) {
8566 if (gnu_ext
&& tok
== TOK_DOTS
) {
8570 warning("empty case range");
8572 /* since a case is like a label, we must skip it with a jmp */
8579 *case_sym
= gtst(1, 0);
8582 *case_sym
= gtst(1, 0);
8586 *case_sym
= gtst(1, *case_sym
);
8591 goto block_after_label
;
8593 if (tok
== TOK_DEFAULT
) {
8599 error("too many 'default'");
8602 goto block_after_label
;
8604 if (tok
== TOK_GOTO
) {
8606 if (tok
== '*' && gnu_ext
) {
8610 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
8613 } else if (tok
>= TOK_UIDENT
) {
8614 s
= label_find(tok
);
8615 /* put forward definition if needed */
8617 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
8619 if (s
->r
== LABEL_DECLARED
)
8620 s
->r
= LABEL_FORWARD
;
8622 /* label already defined */
8623 if (s
->r
& LABEL_FORWARD
)
8624 s
->next
= (void *)gjmp((long)s
->next
);
8626 gjmp_addr((long)s
->next
);
8629 expect("label identifier");
8632 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
8640 if (s
->r
== LABEL_DEFINED
)
8641 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
8642 gsym((long)s
->next
);
8643 s
->r
= LABEL_DEFINED
;
8645 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
8647 s
->next
= (void *)ind
;
8648 /* we accept this, but it is a mistake */
8651 warning("deprecated use of label at end of compound statement");
8655 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8658 /* expression case */
8673 /* t is the array or struct type. c is the array or struct
8674 address. cur_index/cur_field is the pointer to the current
8675 value. 'size_only' is true if only size info is needed (only used
8677 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
8678 int *cur_index
, Sym
**cur_field
,
8682 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
8688 if (gnu_ext
&& (l
= is_label()) != 0)
8690 while (tok
== '[' || tok
== '.') {
8692 if (!(type
->t
& VT_ARRAY
))
8693 expect("array type");
8696 index
= expr_const();
8697 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
8698 expect("invalid index");
8699 if (tok
== TOK_DOTS
&& gnu_ext
) {
8701 index_last
= expr_const();
8702 if (index_last
< 0 ||
8703 (s
->c
>= 0 && index_last
>= s
->c
) ||
8705 expect("invalid index");
8711 *cur_index
= index_last
;
8712 type
= pointed_type(type
);
8713 elem_size
= type_size(type
, &align
);
8714 c
+= index
* elem_size
;
8715 /* NOTE: we only support ranges for last designator */
8716 nb_elems
= index_last
- index
+ 1;
8717 if (nb_elems
!= 1) {
8726 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
8727 expect("struct/union type");
8740 /* XXX: fix this mess by using explicit storage field */
8742 type1
.t
|= (type
->t
& ~VT_TYPE
);
8756 if (type
->t
& VT_ARRAY
) {
8758 type
= pointed_type(type
);
8759 c
+= index
* type_size(type
, &align
);
8763 error("too many field init");
8764 /* XXX: fix this mess by using explicit storage field */
8766 type1
.t
|= (type
->t
& ~VT_TYPE
);
8771 decl_initializer(type
, sec
, c
, 0, size_only
);
8773 /* XXX: make it more general */
8774 if (!size_only
&& nb_elems
> 1) {
8775 unsigned long c_end
;
8780 error("range init not supported yet for dynamic storage");
8781 c_end
= c
+ nb_elems
* elem_size
;
8782 if (c_end
> sec
->data_allocated
)
8783 section_realloc(sec
, c_end
);
8784 src
= sec
->data
+ c
;
8786 for(i
= 1; i
< nb_elems
; i
++) {
8788 memcpy(dst
, src
, elem_size
);
8794 #define EXPR_CONST 1
8797 /* store a value or an expression directly in global data or in local array */
8798 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
8799 int v
, int expr_type
)
8801 int saved_global_expr
, bt
, bit_pos
, bit_size
;
8803 unsigned long long bit_mask
;
8811 /* compound literals must be allocated globally in this case */
8812 saved_global_expr
= global_expr
;
8815 global_expr
= saved_global_expr
;
8816 /* NOTE: symbols are accepted */
8817 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
8818 error("initializer element is not constant");
8826 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
8829 /* XXX: not portable */
8830 /* XXX: generate error if incorrect relocation */
8831 gen_assign_cast(&dtype
);
8832 bt
= type
->t
& VT_BTYPE
;
8833 /* we'll write at most 12 bytes */
8834 if (c
+ 12 > sec
->data_allocated
) {
8835 section_realloc(sec
, c
+ 12);
8837 ptr
= sec
->data
+ c
;
8838 /* XXX: make code faster ? */
8839 if (!(type
->t
& VT_BITFIELD
)) {
8844 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
8845 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
8846 bit_mask
= (1LL << bit_size
) - 1;
8848 if ((vtop
->r
& VT_SYM
) &&
8854 (bt
== VT_INT
&& bit_size
!= 32)))
8855 error("initializer element is not computable at load time");
8858 vtop
->c
.i
= (vtop
->c
.i
!= 0);
8860 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8863 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8866 *(double *)ptr
= vtop
->c
.d
;
8869 *(long double *)ptr
= vtop
->c
.ld
;
8872 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
8875 if (vtop
->r
& VT_SYM
) {
8876 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
8878 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8883 vset(&dtype
, VT_LOCAL
|VT_LVAL
, c
);
8890 /* put zeros for variable based init */
8891 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
8894 /* nothing to do because globals are already set to zero */
8896 vpush_global_sym(&func_old_type
, TOK_memset
);
8904 /* 't' contains the type and storage info. 'c' is the offset of the
8905 object in section 'sec'. If 'sec' is NULL, it means stack based
8906 allocation. 'first' is true if array '{' must be read (multi
8907 dimension implicit array init handling). 'size_only' is true if
8908 size only evaluation is wanted (only for arrays). */
8909 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
8910 int first
, int size_only
)
8912 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
8913 int size1
, align1
, expr_type
;
8917 if (type
->t
& VT_ARRAY
) {
8921 t1
= pointed_type(type
);
8922 size1
= type_size(t1
, &align1
);
8925 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
8931 /* only parse strings here if correct type (otherwise: handle
8932 them as ((w)char *) expressions */
8933 if ((tok
== TOK_LSTR
&&
8934 #ifdef TCC_TARGET_PE
8935 (t1
->t
& VT_BTYPE
) == VT_SHORT
&& (t1
->t
& VT_UNSIGNED
)
8937 (t1
->t
& VT_BTYPE
) == VT_INT
8939 ) || (tok
== TOK_STR
&& (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
8940 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8945 /* compute maximum number of chars wanted */
8947 cstr_len
= cstr
->size
;
8949 cstr_len
= cstr
->size
/ sizeof(nwchar_t
);
8952 if (n
>= 0 && nb
> (n
- array_length
))
8953 nb
= n
- array_length
;
8956 warning("initializer-string for array is too long");
8957 /* in order to go faster for common case (char
8958 string in global variable, we handle it
8960 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
8961 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
8965 ch
= ((unsigned char *)cstr
->data
)[i
];
8967 ch
= ((nwchar_t
*)cstr
->data
)[i
];
8968 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
8976 /* only add trailing zero if enough storage (no
8977 warning in this case since it is standard) */
8978 if (n
< 0 || array_length
< n
) {
8980 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
8986 while (tok
!= '}') {
8987 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
8988 if (n
>= 0 && index
>= n
)
8989 error("index too large");
8990 /* must put zero in holes (note that doing it that way
8991 ensures that it even works with designators) */
8992 if (!size_only
&& array_length
< index
) {
8993 init_putz(t1
, sec
, c
+ array_length
* size1
,
8994 (index
- array_length
) * size1
);
8997 if (index
> array_length
)
8998 array_length
= index
;
8999 /* special test for multi dimensional arrays (may not
9000 be strictly correct if designators are used at the
9002 if (index
>= n
&& no_oblock
)
9011 /* put zeros at the end */
9012 if (!size_only
&& n
>= 0 && array_length
< n
) {
9013 init_putz(t1
, sec
, c
+ array_length
* size1
,
9014 (n
- array_length
) * size1
);
9016 /* patch type size if needed */
9018 s
->c
= array_length
;
9019 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
9020 (sec
|| !first
|| tok
== '{')) {
9023 /* NOTE: the previous test is a specific case for automatic
9024 struct/union init */
9025 /* XXX: union needs only one init */
9027 /* XXX: this test is incorrect for local initializers
9028 beginning with ( without {. It would be much more difficult
9029 to do it correctly (ideally, the expression parser should
9030 be used in all cases) */
9036 while (tok
== '(') {
9040 if (!parse_btype(&type1
, &ad1
))
9042 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
9044 if (!is_assignable_types(type
, &type1
))
9045 error("invalid type for cast");
9050 if (first
|| tok
== '{') {
9059 while (tok
!= '}') {
9060 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
9062 if (!size_only
&& array_length
< index
) {
9063 init_putz(type
, sec
, c
+ array_length
,
9064 index
- array_length
);
9066 index
= index
+ type_size(&f
->type
, &align1
);
9067 if (index
> array_length
)
9068 array_length
= index
;
9070 if (no_oblock
&& f
== NULL
)
9076 /* put zeros at the end */
9077 if (!size_only
&& array_length
< n
) {
9078 init_putz(type
, sec
, c
+ array_length
,
9087 } else if (tok
== '{') {
9089 decl_initializer(type
, sec
, c
, first
, size_only
);
9091 } else if (size_only
) {
9092 /* just skip expression */
9094 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
9098 else if (tok
== ')')
9103 /* currently, we always use constant expression for globals
9104 (may change for scripting case) */
9105 expr_type
= EXPR_CONST
;
9107 expr_type
= EXPR_ANY
;
9108 init_putv(type
, sec
, c
, 0, expr_type
);
9112 /* parse an initializer for type 't' if 'has_init' is non zero, and
9113 allocate space in local or global data space ('r' is either
9114 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
9115 variable 'v' of scope 'scope' is declared before initializers are
9116 parsed. If 'v' is zero, then a reference to the new object is put
9117 in the value stack. If 'has_init' is 2, a special parsing is done
9118 to handle string constants. */
9119 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
9120 int has_init
, int v
, int scope
)
9122 int size
, align
, addr
, data_offset
;
9124 ParseState saved_parse_state
;
9125 TokenString init_str
;
9128 size
= type_size(type
, &align
);
9129 /* If unknown size, we must evaluate it before
9130 evaluating initializers because
9131 initializers can generate global data too
9132 (e.g. string pointers or ISOC99 compound
9133 literals). It also simplifies local
9134 initializers handling */
9135 tok_str_new(&init_str
);
9138 error("unknown type size");
9139 /* get all init string */
9140 if (has_init
== 2) {
9141 /* only get strings */
9142 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
9143 tok_str_add_tok(&init_str
);
9148 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
9150 error("unexpected end of file in initializer");
9151 tok_str_add_tok(&init_str
);
9154 else if (tok
== '}') {
9162 tok_str_add(&init_str
, -1);
9163 tok_str_add(&init_str
, 0);
9166 save_parse_state(&saved_parse_state
);
9168 macro_ptr
= init_str
.str
;
9170 decl_initializer(type
, NULL
, 0, 1, 1);
9171 /* prepare second initializer parsing */
9172 macro_ptr
= init_str
.str
;
9175 /* if still unknown size, error */
9176 size
= type_size(type
, &align
);
9178 error("unknown type size");
9180 /* take into account specified alignment if bigger */
9182 if (ad
->aligned
> align
)
9183 align
= ad
->aligned
;
9184 } else if (ad
->packed
) {
9187 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
9189 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
9191 loc
= (loc
- size
) & -align
;
9193 /* handles bounds */
9194 /* XXX: currently, since we do only one pass, we cannot track
9195 '&' operators, so we add only arrays */
9196 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
9197 unsigned long *bounds_ptr
;
9198 /* add padding between regions */
9200 /* then add local bound info */
9201 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
9202 bounds_ptr
[0] = addr
;
9203 bounds_ptr
[1] = size
;
9206 /* local variable */
9207 sym_push(v
, type
, r
, addr
);
9209 /* push local reference */
9210 vset(type
, r
, addr
);
9216 if (v
&& scope
== VT_CONST
) {
9217 /* see if the symbol was already defined */
9220 if (!is_compatible_types(&sym
->type
, type
))
9221 error("incompatible types for redefinition of '%s'",
9222 get_tok_str(v
, NULL
));
9223 if (sym
->type
.t
& VT_EXTERN
) {
9224 /* if the variable is extern, it was not allocated */
9225 sym
->type
.t
&= ~VT_EXTERN
;
9226 /* set array size if it was ommited in extern
9228 if ((sym
->type
.t
& VT_ARRAY
) &&
9229 sym
->type
.ref
->c
< 0 &&
9231 sym
->type
.ref
->c
= type
->ref
->c
;
9233 /* we accept several definitions of the same
9234 global variable. this is tricky, because we
9235 must play with the SHN_COMMON type of the symbol */
9236 /* XXX: should check if the variable was already
9237 initialized. It is incorrect to initialized it
9239 /* no init data, we won't add more to the symbol */
9246 /* allocate symbol in corresponding section */
9251 else if (tcc_state
->nocommon
)
9255 data_offset
= sec
->data_offset
;
9256 data_offset
= (data_offset
+ align
- 1) & -align
;
9258 /* very important to increment global pointer at this time
9259 because initializers themselves can create new initializers */
9260 data_offset
+= size
;
9261 /* add padding if bound check */
9262 if (do_bounds_check
)
9264 sec
->data_offset
= data_offset
;
9265 /* allocate section space to put the data */
9266 if (sec
->sh_type
!= SHT_NOBITS
&&
9267 data_offset
> sec
->data_allocated
)
9268 section_realloc(sec
, data_offset
);
9269 /* align section if needed */
9270 if (align
> sec
->sh_addralign
)
9271 sec
->sh_addralign
= align
;
9273 addr
= 0; /* avoid warning */
9277 if (scope
!= VT_CONST
|| !sym
) {
9278 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
9280 /* update symbol definition */
9282 put_extern_sym(sym
, sec
, addr
, size
);
9285 /* put a common area */
9286 put_extern_sym(sym
, NULL
, align
, size
);
9287 /* XXX: find a nicer way */
9288 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
9289 esym
->st_shndx
= SHN_COMMON
;
9294 /* push global reference */
9295 sym
= get_sym_ref(type
, sec
, addr
, size
);
9297 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
9301 /* handles bounds now because the symbol must be defined
9302 before for the relocation */
9303 if (do_bounds_check
) {
9304 unsigned long *bounds_ptr
;
9306 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
9307 /* then add global bound info */
9308 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
9309 bounds_ptr
[0] = 0; /* relocated */
9310 bounds_ptr
[1] = size
;
9314 decl_initializer(type
, sec
, addr
, 1, 0);
9315 /* restore parse state if needed */
9317 tok_str_free(init_str
.str
);
9318 restore_parse_state(&saved_parse_state
);
9324 void put_func_debug(Sym
*sym
)
9329 /* XXX: we put here a dummy type */
9330 snprintf(buf
, sizeof(buf
), "%s:%c1",
9331 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
9332 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
9333 cur_text_section
, sym
->c
);
9334 /* //gr gdb wants a line at the function */
9335 put_stabn(N_SLINE
, 0, file
->line_num
, 0);
9340 /* parse an old style function declaration list */
9341 /* XXX: check multiple parameter */
9342 static void func_decl_list(Sym
*func_sym
)
9349 /* parse each declaration */
9350 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
9351 if (!parse_btype(&btype
, &ad
))
9352 expect("declaration list");
9353 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
9354 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
9356 /* we accept no variable after */
9360 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
9361 /* find parameter in function parameter list */
9364 if ((s
->v
& ~SYM_FIELD
) == v
)
9368 error("declaration for parameter '%s' but no such parameter",
9369 get_tok_str(v
, NULL
));
9371 /* check that no storage specifier except 'register' was given */
9372 if (type
.t
& VT_STORAGE
)
9373 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
9374 convert_parameter_type(&type
);
9375 /* we can add the type (NOTE: it could be local to the function) */
9377 /* accept other parameters */
9388 /* parse a function defined by symbol 'sym' and generate its code in
9389 'cur_text_section' */
9390 static void gen_function(Sym
*sym
)
9392 int saved_nocode_wanted
= nocode_wanted
;
9394 ind
= cur_text_section
->data_offset
;
9395 /* NOTE: we patch the symbol size later */
9396 put_extern_sym(sym
, cur_text_section
, ind
, 0);
9397 funcname
= get_tok_str(sym
->v
, NULL
);
9399 /* put debug symbol */
9401 put_func_debug(sym
);
9402 /* push a dummy symbol to enable local sym storage */
9403 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
9404 gfunc_prolog(&sym
->type
);
9406 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
9409 cur_text_section
->data_offset
= ind
;
9410 label_pop(&global_label_stack
, NULL
);
9411 sym_pop(&local_stack
, NULL
); /* reset local stack */
9412 /* end of function */
9413 /* patch symbol size */
9414 ((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
].st_size
=
9417 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
9419 /* It's better to crash than to generate wrong code */
9420 cur_text_section
= NULL
;
9421 funcname
= ""; /* for safety */
9422 func_vt
.t
= VT_VOID
; /* for safety */
9423 ind
= 0; /* for safety */
9424 nocode_wanted
= saved_nocode_wanted
;
9427 static void gen_inline_functions(void)
9431 int *str
, inline_generated
;
9433 /* iterate while inline function are referenced */
9435 inline_generated
= 0;
9436 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
9438 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
9439 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
9440 (VT_STATIC
| VT_INLINE
) &&
9442 /* the function was used: generate its code and
9443 convert it to a normal function */
9444 str
= INLINE_DEF(sym
->r
);
9445 sym
->r
= VT_SYM
| VT_CONST
;
9446 sym
->type
.t
&= ~VT_INLINE
;
9450 cur_text_section
= text_section
;
9452 macro_ptr
= NULL
; /* fail safe */
9455 inline_generated
= 1;
9458 if (!inline_generated
)
9462 /* free all remaining inline function tokens */
9463 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
9465 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
9466 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
9467 (VT_STATIC
| VT_INLINE
)) {
9468 //gr printf("sym %d %s\n", sym->r, get_tok_str(sym->v, NULL));
9469 if (sym
->r
== (VT_SYM
| VT_CONST
)) //gr beware!
9471 str
= INLINE_DEF(sym
->r
);
9473 sym
->r
= 0; /* fail safe */
9478 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
9479 static void decl(int l
)
9487 if (!parse_btype(&btype
, &ad
)) {
9488 /* skip redundant ';' */
9489 /* XXX: find more elegant solution */
9494 if (l
== VT_CONST
&&
9495 (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
)) {
9496 /* global asm block */
9500 /* special test for old K&R protos without explicit int
9501 type. Only accepted when defining global data */
9502 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
9506 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
9507 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
9509 /* we accept no variable after */
9513 while (1) { /* iterate thru each declaration */
9515 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
9519 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
9520 printf("type = '%s'\n", buf
);
9523 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9524 /* if old style function prototype, we accept a
9527 if (sym
->c
== FUNC_OLD
)
9528 func_decl_list(sym
);
9533 error("cannot use local functions");
9534 if ((type
.t
& VT_BTYPE
) != VT_FUNC
)
9535 expect("function definition");
9537 /* reject abstract declarators in function definition */
9539 while ((sym
= sym
->next
) != NULL
)
9540 if (!(sym
->v
& ~SYM_FIELD
))
9541 expect("identifier");
9543 /* XXX: cannot do better now: convert extern line to static inline */
9544 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
9545 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
9549 if ((sym
->type
.t
& VT_BTYPE
) != VT_FUNC
)
9551 /* specific case: if not func_call defined, we put
9552 the one of the prototype */
9553 /* XXX: should have default value */
9554 r
= sym
->type
.ref
->r
;
9555 if (FUNC_CALL(r
) != FUNC_CDECL
9556 && FUNC_CALL(type
.ref
->r
) == FUNC_CDECL
)
9557 FUNC_CALL(type
.ref
->r
) = FUNC_CALL(r
);
9559 FUNC_EXPORT(type
.ref
->r
) = 1;
9561 if (!is_compatible_types(&sym
->type
, &type
)) {
9563 error("incompatible types for redefinition of '%s'",
9564 get_tok_str(v
, NULL
));
9566 /* if symbol is already defined, then put complete type */
9569 /* put function symbol */
9570 sym
= global_identifier_push(v
, type
.t
, 0);
9571 sym
->type
.ref
= type
.ref
;
9574 /* static inline functions are just recorded as a kind
9575 of macro. Their code will be emitted at the end of
9576 the compilation unit only if they are used */
9577 if ((type
.t
& (VT_INLINE
| VT_STATIC
)) ==
9578 (VT_INLINE
| VT_STATIC
)) {
9579 TokenString func_str
;
9582 tok_str_new(&func_str
);
9588 error("unexpected end of file");
9589 tok_str_add_tok(&func_str
);
9594 } else if (t
== '}') {
9596 if (block_level
== 0)
9600 tok_str_add(&func_str
, -1);
9601 tok_str_add(&func_str
, 0);
9602 INLINE_DEF(sym
->r
) = func_str
.str
;
9604 /* compute text section */
9605 cur_text_section
= ad
.section
;
9606 if (!cur_text_section
)
9607 cur_text_section
= text_section
;
9608 sym
->r
= VT_SYM
| VT_CONST
;
9613 if (btype
.t
& VT_TYPEDEF
) {
9614 /* save typedefed type */
9615 /* XXX: test storage specifiers ? */
9616 sym
= sym_push(v
, &type
, 0, 0);
9617 sym
->type
.t
|= VT_TYPEDEF
;
9618 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9619 /* external function definition */
9620 /* specific case for func_call attribute */
9622 type
.ref
->r
= ad
.func_attr
;
9623 external_sym(v
, &type
, 0);
9625 /* not lvalue if array */
9627 if (!(type
.t
& VT_ARRAY
))
9628 r
|= lvalue_type(type
.t
);
9629 has_init
= (tok
== '=');
9630 if ((btype
.t
& VT_EXTERN
) ||
9631 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
9632 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
9633 /* external variable */
9634 /* NOTE: as GCC, uninitialized global static
9635 arrays of null size are considered as
9637 external_sym(v
, &type
, r
);
9639 type
.t
|= (btype
.t
& VT_STATIC
); /* Retain "static". */
9640 if (type
.t
& VT_STATIC
)
9646 decl_initializer_alloc(&type
, &ad
, r
,
9660 /* better than nothing, but needs extension to handle '-E' option
9662 static void preprocess_init(TCCState
*s1
)
9664 s1
->include_stack_ptr
= s1
->include_stack
;
9665 /* XXX: move that before to avoid having to initialize
9666 file->ifdef_stack_ptr ? */
9667 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
9668 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
9670 /* XXX: not ANSI compliant: bound checking says error */
9672 s1
->pack_stack
[0] = 0;
9673 s1
->pack_stack_ptr
= s1
->pack_stack
;
9676 /* compile the C file opened in 'file'. Return non zero if errors. */
9677 static int tcc_compile(TCCState
*s1
)
9681 volatile int section_sym
;
9684 printf("%s: **** new file\n", file
->filename
);
9686 preprocess_init(s1
);
9688 cur_text_section
= NULL
;
9690 anon_sym
= SYM_FIRST_ANOM
;
9692 /* file info: full path + filename */
9693 section_sym
= 0; /* avoid warning */
9695 section_sym
= put_elf_sym(symtab_section
, 0, 0,
9696 ELFW(ST_INFO
)(STB_LOCAL
, STT_SECTION
), 0,
9697 text_section
->sh_num
, NULL
);
9698 getcwd(buf
, sizeof(buf
));
9700 normalize_slashes(buf
);
9702 pstrcat(buf
, sizeof(buf
), "/");
9703 put_stabs_r(buf
, N_SO
, 0, 0,
9704 text_section
->data_offset
, text_section
, section_sym
);
9705 put_stabs_r(file
->filename
, N_SO
, 0, 0,
9706 text_section
->data_offset
, text_section
, section_sym
);
9708 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
9709 symbols can be safely used */
9710 put_elf_sym(symtab_section
, 0, 0,
9711 ELFW(ST_INFO
)(STB_LOCAL
, STT_FILE
), 0,
9712 SHN_ABS
, file
->filename
);
9714 /* define some often used types */
9715 int_type
.t
= VT_INT
;
9717 char_pointer_type
.t
= VT_BYTE
;
9718 mk_pointer(&char_pointer_type
);
9720 func_old_type
.t
= VT_FUNC
;
9721 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
9723 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
9724 float_type
.t
= VT_FLOAT
;
9725 double_type
.t
= VT_DOUBLE
;
9727 func_float_type
.t
= VT_FUNC
;
9728 func_float_type
.ref
= sym_push(SYM_FIELD
, &float_type
, FUNC_CDECL
, FUNC_OLD
);
9729 func_double_type
.t
= VT_FUNC
;
9730 func_double_type
.ref
= sym_push(SYM_FIELD
, &double_type
, FUNC_CDECL
, FUNC_OLD
);
9734 /* define 'void *alloca(unsigned int)' builtin function */
9739 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
9740 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
9743 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
9747 define_start
= define_stack
;
9750 if (setjmp(s1
->error_jmp_buf
) == 0) {
9752 s1
->error_set_jmp_enabled
= 1;
9754 ch
= file
->buf_ptr
[0];
9755 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9756 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
9760 expect("declaration");
9762 /* end of translation unit info */
9764 put_stabs_r(NULL
, N_SO
, 0, 0,
9765 text_section
->data_offset
, text_section
, section_sym
);
9768 s1
->error_set_jmp_enabled
= 0;
9770 /* reset define stack, but leave -Dsymbols (may be incorrect if
9771 they are undefined) */
9772 free_defines(define_start
);
9774 gen_inline_functions();
9776 sym_pop(&global_stack
, NULL
);
9777 sym_pop(&local_stack
, NULL
);
9779 return s1
->nb_errors
!= 0 ? -1 : 0;
9782 /* Preprocess the current file */
9783 /* XXX: add line and file infos,
9784 * XXX: add options to preserve spaces (partly done, only spaces in macro are
9787 static int tcc_preprocess(TCCState
*s1
)
9790 BufferedFile
*file_ref
;
9791 int token_seen
, line_ref
;
9793 preprocess_init(s1
);
9794 define_start
= define_stack
;
9795 ch
= file
->buf_ptr
[0];
9797 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9798 parse_flags
= PARSE_FLAG_ASM_COMMENTS
| PARSE_FLAG_PREPROCESS
|
9799 PARSE_FLAG_LINEFEED
;
9807 if (tok
== TOK_EOF
) {
9809 } else if (tok
== TOK_LINEFEED
) {
9814 } else if (token_seen
) {
9815 fwrite(tok_spaces
.data
, tok_spaces
.size
, 1, s1
->outfile
);
9817 int d
= file
->line_num
- line_ref
;
9818 if (file
!= file_ref
|| d
< 0 || d
>= 8)
9819 fprintf(s1
->outfile
, "# %d \"%s\"\n", file
->line_num
, file
->filename
);
9822 fputs("\n", s1
->outfile
), --d
;
9823 line_ref
= (file_ref
= file
)->line_num
;
9826 fputs(get_tok_str(tok
, &tokc
), s1
->outfile
);
9828 free_defines(define_start
);
9833 int tcc_compile_string(TCCState
*s
, const char *str
)
9835 BufferedFile bf1
, *bf
= &bf1
;
9839 /* init file structure */
9841 /* XXX: avoid copying */
9843 buf
= tcc_malloc(len
+ 1);
9846 memcpy(buf
, str
, len
);
9849 bf
->buf_end
= buf
+ len
;
9850 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
9853 ret
= tcc_compile(s
);
9857 /* currently, no need to close */
9862 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9863 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
9865 BufferedFile bf1
, *bf
= &bf1
;
9867 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
9868 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
9872 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
9874 /* init file structure */
9876 bf
->buf_ptr
= bf
->buffer
;
9877 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
9878 *bf
->buf_end
= CH_EOB
;
9879 bf
->filename
[0] = '\0';
9883 s1
->include_stack_ptr
= s1
->include_stack
;
9885 /* parse with define parser */
9886 ch
= file
->buf_ptr
[0];
9892 /* undefine a preprocessor symbol */
9893 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
9897 ts
= tok_alloc(sym
, strlen(sym
));
9898 s
= define_find(ts
->tok
);
9899 /* undefine symbol by putting an invalid name */
9904 #ifdef CONFIG_TCC_ASM
9906 #ifdef TCC_TARGET_I386
9907 #include "i386-asm.c"
9912 static void asm_instr(void)
9914 error("inline asm() not supported");
9916 static void asm_global_instr(void)
9918 error("inline asm() not supported");
9924 #ifdef TCC_TARGET_COFF
9925 #include "tcccoff.c"
9928 #ifdef TCC_TARGET_PE
9932 /* print the position in the source file of PC value 'pc' by reading
9933 the stabs debug information */
9934 static void rt_printline(unsigned long wanted_pc
)
9936 Stab_Sym
*sym
, *sym_end
;
9937 char func_name
[128], last_func_name
[128];
9938 unsigned long func_addr
, last_pc
, pc
;
9939 const char *incl_files
[INCLUDE_STACK_SIZE
];
9940 int incl_index
, len
, last_line_num
, i
;
9941 const char *str
, *p
;
9943 fprintf(stderr
, "0x%08lx:", wanted_pc
);
9945 func_name
[0] = '\0';
9948 last_func_name
[0] = '\0';
9949 last_pc
= 0xffffffff;
9951 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
9952 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
9953 while (sym
< sym_end
) {
9954 switch(sym
->n_type
) {
9955 /* function start or end */
9957 if (sym
->n_strx
== 0) {
9958 /* we test if between last line and end of function */
9959 pc
= sym
->n_value
+ func_addr
;
9960 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9962 func_name
[0] = '\0';
9965 str
= stabstr_section
->data
+ sym
->n_strx
;
9966 p
= strchr(str
, ':');
9968 pstrcpy(func_name
, sizeof(func_name
), str
);
9971 if (len
> sizeof(func_name
) - 1)
9972 len
= sizeof(func_name
) - 1;
9973 memcpy(func_name
, str
, len
);
9974 func_name
[len
] = '\0';
9976 func_addr
= sym
->n_value
;
9979 /* line number info */
9981 pc
= sym
->n_value
+ func_addr
;
9982 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9985 last_line_num
= sym
->n_desc
;
9987 strcpy(last_func_name
, func_name
);
9991 str
= stabstr_section
->data
+ sym
->n_strx
;
9993 if (incl_index
< INCLUDE_STACK_SIZE
) {
9994 incl_files
[incl_index
++] = str
;
10002 if (sym
->n_strx
== 0) {
10003 incl_index
= 0; /* end of translation unit */
10005 str
= stabstr_section
->data
+ sym
->n_strx
;
10006 /* do not add path */
10008 if (len
> 0 && str
[len
- 1] != '/')
10016 /* second pass: we try symtab symbols (no line number info) */
10019 ElfW(Sym
) *sym
, *sym_end
;
10022 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
10023 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
10026 type
= ELFW(ST_TYPE
)(sym
->st_info
);
10027 if (type
== STT_FUNC
) {
10028 if (wanted_pc
>= sym
->st_value
&&
10029 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
10030 pstrcpy(last_func_name
, sizeof(last_func_name
),
10031 strtab_section
->data
+ sym
->st_name
);
10037 /* did not find any info: */
10038 fprintf(stderr
, " ???\n");
10041 if (last_func_name
[0] != '\0') {
10042 fprintf(stderr
, " %s()", last_func_name
);
10044 if (incl_index
> 0) {
10045 fprintf(stderr
, " (%s:%d",
10046 incl_files
[incl_index
- 1], last_line_num
);
10047 for(i
= incl_index
- 2; i
>= 0; i
--)
10048 fprintf(stderr
, ", included from %s", incl_files
[i
]);
10049 fprintf(stderr
, ")");
10051 fprintf(stderr
, "\n");
10054 #if !defined(_WIN32) && !defined(CONFIG_TCCBOOT)
10058 /* fix for glibc 2.1 */
10060 #define REG_EIP EIP
10061 #define REG_EBP EBP
10064 /* return the PC at frame level 'level'. Return non zero if not found */
10065 static int rt_get_caller_pc(unsigned long *paddr
,
10066 ucontext_t
*uc
, int level
)
10072 #if defined(__FreeBSD__)
10073 *paddr
= uc
->uc_mcontext
.mc_eip
;
10074 #elif defined(__dietlibc__)
10075 *paddr
= uc
->uc_mcontext
.eip
;
10077 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
10081 #if defined(__FreeBSD__)
10082 fp
= uc
->uc_mcontext
.mc_ebp
;
10083 #elif defined(__dietlibc__)
10084 fp
= uc
->uc_mcontext
.ebp
;
10086 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
10088 for(i
=1;i
<level
;i
++) {
10089 /* XXX: check address validity with program info */
10090 if (fp
<= 0x1000 || fp
>= 0xc0000000)
10092 fp
= ((unsigned long *)fp
)[0];
10094 *paddr
= ((unsigned long *)fp
)[1];
10098 #elif defined(__x86_64__)
10099 /* return the PC at frame level 'level'. Return non zero if not found */
10100 static int rt_get_caller_pc(unsigned long *paddr
,
10101 ucontext_t
*uc
, int level
)
10107 /* XXX: only support linux */
10108 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
10111 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
10112 for(i
=1;i
<level
;i
++) {
10113 /* XXX: check address validity with program info */
10114 if (fp
<= 0x1000 || fp
>= 0xc0000000)
10116 fp
= ((unsigned long *)fp
)[0];
10118 *paddr
= ((unsigned long *)fp
)[1];
10124 #warning add arch specific rt_get_caller_pc()
10126 static int rt_get_caller_pc(unsigned long *paddr
,
10127 ucontext_t
*uc
, int level
)
10133 /* emit a run time error at position 'pc' */
10134 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
10141 fprintf(stderr
, "Runtime error: ");
10142 vfprintf(stderr
, fmt
, ap
);
10143 fprintf(stderr
, "\n");
10144 for(i
=0;i
<num_callers
;i
++) {
10145 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
10148 fprintf(stderr
, "at ");
10150 fprintf(stderr
, "by ");
10157 /* signal handler for fatal errors */
10158 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
10160 ucontext_t
*uc
= puc
;
10164 switch(siginf
->si_code
) {
10167 rt_error(uc
, "division by zero");
10170 rt_error(uc
, "floating point exception");
10176 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
10177 rt_error(uc
, *rt_bound_error_msg
);
10179 rt_error(uc
, "dereferencing invalid pointer");
10182 rt_error(uc
, "illegal instruction");
10185 rt_error(uc
, "abort() called");
10188 rt_error(uc
, "caught signal %d", signum
);
10195 /* do all relocations (needed before using tcc_get_symbol()) */
10196 int tcc_relocate(TCCState
*s1
)
10203 #ifdef TCC_TARGET_PE
10204 pe_add_runtime(s1
);
10206 tcc_add_runtime(s1
);
10209 relocate_common_syms();
10211 tcc_add_linker_symbols(s1
);
10212 #ifndef TCC_TARGET_PE
10213 build_got_entries(s1
);
10215 /* compute relocation address : section are relocated in place. We
10216 also alloc the bss space */
10217 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10218 s
= s1
->sections
[i
];
10219 if (s
->sh_flags
& SHF_ALLOC
) {
10220 if (s
->sh_type
== SHT_NOBITS
)
10221 s
->data
= tcc_mallocz(s
->data_offset
);
10222 s
->sh_addr
= (unsigned long)s
->data
;
10226 relocate_syms(s1
, 1);
10228 if (s1
->nb_errors
!= 0)
10231 /* relocate each section */
10232 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10233 s
= s1
->sections
[i
];
10235 relocate_section(s1
, s
);
10238 /* mark executable sections as executable in memory */
10239 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10240 s
= s1
->sections
[i
];
10241 if ((s
->sh_flags
& (SHF_ALLOC
| SHF_EXECINSTR
)) ==
10242 (SHF_ALLOC
| SHF_EXECINSTR
))
10243 set_pages_executable(s
->data
, s
->data_offset
);
10248 /* launch the compiled program with the given arguments */
10249 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
10251 int (*prog_main
)(int, char **);
10253 if (tcc_relocate(s1
) < 0)
10256 prog_main
= tcc_get_symbol_err(s1
, "main");
10259 #if defined(_WIN32) || defined(CONFIG_TCCBOOT)
10260 error("debug mode currently not available for Windows");
10262 struct sigaction sigact
;
10263 /* install TCC signal handlers to print debug info on fatal
10265 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
10266 sigact
.sa_sigaction
= sig_error
;
10267 sigemptyset(&sigact
.sa_mask
);
10268 sigaction(SIGFPE
, &sigact
, NULL
);
10269 sigaction(SIGILL
, &sigact
, NULL
);
10270 sigaction(SIGSEGV
, &sigact
, NULL
);
10271 sigaction(SIGBUS
, &sigact
, NULL
);
10272 sigaction(SIGABRT
, &sigact
, NULL
);
10276 #ifdef CONFIG_TCC_BCHECK
10277 if (do_bounds_check
) {
10278 void (*bound_init
)(void);
10280 /* set error function */
10281 rt_bound_error_msg
= (void *)tcc_get_symbol_err(s1
,
10282 "__bound_error_msg");
10284 /* XXX: use .init section so that it also work in binary ? */
10285 bound_init
= (void *)tcc_get_symbol_err(s1
, "__bound_init");
10289 return (*prog_main
)(argc
, argv
);
10292 void tcc_memstats(void)
10295 printf("memory in use: %d\n", mem_cur_size
);
10299 static void tcc_cleanup(void)
10303 if (NULL
== tcc_state
)
10307 /* free -D defines */
10308 free_defines(NULL
);
10311 n
= tok_ident
- TOK_IDENT
;
10312 for(i
= 0; i
< n
; i
++)
10313 tcc_free(table_ident
[i
]);
10314 tcc_free(table_ident
);
10316 /* free sym_pools */
10317 dynarray_reset(&sym_pools
, &nb_sym_pools
);
10318 /* string buffer */
10319 cstr_free(&tokcstr
);
10320 /* reset symbol stack */
10321 sym_free_first
= NULL
;
10322 /* cleanup from error/setjmp */
10326 TCCState
*tcc_new(void)
10335 s
= tcc_mallocz(sizeof(TCCState
));
10339 s
->output_type
= TCC_OUTPUT_MEMORY
;
10341 /* init isid table */
10342 for(i
=CH_EOF
;i
<256;i
++)
10343 isidnum_table
[i
-CH_EOF
] = isid(i
) || isnum(i
);
10345 /* add all tokens */
10346 table_ident
= NULL
;
10347 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
10349 tok_ident
= TOK_IDENT
;
10358 ts
= tok_alloc(p
, r
- p
- 1);
10362 /* we add dummy defines for some special macros to speed up tests
10363 and to have working defined() */
10364 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
10365 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
10366 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
10367 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
10369 /* standard defines */
10370 tcc_define_symbol(s
, "__STDC__", NULL
);
10371 tcc_define_symbol(s
, "__STDC_VERSION__", "199901L");
10372 #if defined(TCC_TARGET_I386)
10373 tcc_define_symbol(s
, "__i386__", NULL
);
10375 #if defined(TCC_TARGET_X86_64)
10376 tcc_define_symbol(s
, "__x86_64__", NULL
);
10378 #if defined(TCC_TARGET_ARM)
10379 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
10380 tcc_define_symbol(s
, "__arm_elf__", NULL
);
10381 tcc_define_symbol(s
, "__arm_elf", NULL
);
10382 tcc_define_symbol(s
, "arm_elf", NULL
);
10383 tcc_define_symbol(s
, "__arm__", NULL
);
10384 tcc_define_symbol(s
, "__arm", NULL
);
10385 tcc_define_symbol(s
, "arm", NULL
);
10386 tcc_define_symbol(s
, "__APCS_32__", NULL
);
10388 #ifdef TCC_TARGET_PE
10389 tcc_define_symbol(s
, "_WIN32", NULL
);
10391 tcc_define_symbol(s
, "__unix__", NULL
);
10392 tcc_define_symbol(s
, "__unix", NULL
);
10393 #if defined(__linux)
10394 tcc_define_symbol(s
, "__linux__", NULL
);
10395 tcc_define_symbol(s
, "__linux", NULL
);
10398 /* tiny C specific defines */
10399 tcc_define_symbol(s
, "__TINYC__", NULL
);
10401 /* tiny C & gcc defines */
10402 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
10403 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
10404 #ifdef TCC_TARGET_PE
10405 tcc_define_symbol(s
, "__WCHAR_TYPE__", "unsigned short");
10407 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
10410 #ifndef TCC_TARGET_PE
10411 /* default library paths */
10412 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/local/lib");
10413 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/lib");
10414 tcc_add_library_path(s
, CONFIG_SYSROOT
"/lib");
10417 /* no section zero */
10418 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
10420 /* create standard sections */
10421 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
10422 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
10423 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
10425 /* symbols are always generated for linking stage */
10426 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
10428 ".hashtab", SHF_PRIVATE
);
10429 strtab_section
= symtab_section
->link
;
10431 /* private symbol table for dynamic symbols */
10432 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
10434 ".dynhashtab", SHF_PRIVATE
);
10435 s
->alacarte_link
= 1;
10437 #ifdef CHAR_IS_UNSIGNED
10438 s
->char_is_unsigned
= 1;
10440 #if defined(TCC_TARGET_PE) && 0
10441 /* XXX: currently the PE linker is not ready to support that */
10442 s
->leading_underscore
= 1;
10445 #ifdef TCC_TARGET_X86_64
10446 s
->jmp_table
= NULL
;
10451 void tcc_delete(TCCState
*s1
)
10457 /* free all sections */
10458 free_section(s1
->dynsymtab_section
);
10460 for(i
= 1; i
< s1
->nb_sections
; i
++)
10461 free_section(s1
->sections
[i
]);
10462 tcc_free(s1
->sections
);
10464 /* free any loaded DLLs */
10465 for ( i
= 0; i
< s1
->nb_loaded_dlls
; i
++)
10467 DLLReference
*ref
= s1
->loaded_dlls
[i
];
10469 dlclose(ref
->handle
);
10472 /* free loaded dlls array */
10473 dynarray_reset(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
);
10475 /* free library paths */
10476 dynarray_reset(&s1
->library_paths
, &s1
->nb_library_paths
);
10478 /* free include paths */
10479 dynarray_reset(&s1
->cached_includes
, &s1
->nb_cached_includes
);
10480 dynarray_reset(&s1
->include_paths
, &s1
->nb_include_paths
);
10481 dynarray_reset(&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
);
10483 #ifdef TCC_TARGET_X86_64
10484 tcc_free(s1
->jmp_table
);
10489 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
10493 pathname1
= tcc_strdup(pathname
);
10494 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
10498 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
10502 pathname1
= tcc_strdup(pathname
);
10503 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
10507 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
10512 BufferedFile
*saved_file
;
10514 /* find source file type with extension */
10515 ext
= tcc_fileextension(filename
);
10519 /* open the file */
10521 file
= tcc_open(s1
, filename
);
10523 if (flags
& AFF_PRINT_ERROR
) {
10524 error_noabort("file '%s' not found", filename
);
10530 if (flags
& AFF_PREPROCESS
) {
10531 ret
= tcc_preprocess(s1
);
10532 } else if (!ext
[0] || !strcmp(ext
, "c")) {
10533 /* C file assumed */
10534 ret
= tcc_compile(s1
);
10536 #ifdef CONFIG_TCC_ASM
10537 if (!strcmp(ext
, "S")) {
10538 /* preprocessed assembler */
10539 ret
= tcc_assemble(s1
, 1);
10540 } else if (!strcmp(ext
, "s")) {
10541 /* non preprocessed assembler */
10542 ret
= tcc_assemble(s1
, 0);
10545 #ifdef TCC_TARGET_PE
10546 if (!strcmp(ext
, "def")) {
10547 ret
= pe_load_def_file(s1
, file
->fd
);
10552 /* assume executable format: auto guess file type */
10553 ret
= read(fd
, &ehdr
, sizeof(ehdr
));
10554 lseek(fd
, 0, SEEK_SET
);
10556 error_noabort("could not read header");
10558 } else if (ret
!= sizeof(ehdr
)) {
10559 goto try_load_script
;
10562 if (ehdr
.e_ident
[0] == ELFMAG0
&&
10563 ehdr
.e_ident
[1] == ELFMAG1
&&
10564 ehdr
.e_ident
[2] == ELFMAG2
&&
10565 ehdr
.e_ident
[3] == ELFMAG3
) {
10566 file
->line_num
= 0; /* do not display line number if error */
10567 if (ehdr
.e_type
== ET_REL
) {
10568 ret
= tcc_load_object_file(s1
, fd
, 0);
10569 } else if (ehdr
.e_type
== ET_DYN
) {
10570 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
10571 #ifdef TCC_TARGET_PE
10575 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
10582 ret
= tcc_load_dll(s1
, fd
, filename
,
10583 (flags
& AFF_REFERENCED_DLL
) != 0);
10586 error_noabort("unrecognized ELF file");
10589 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
10590 file
->line_num
= 0; /* do not display line number if error */
10591 ret
= tcc_load_archive(s1
, fd
);
10593 #ifdef TCC_TARGET_COFF
10594 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
10595 ret
= tcc_load_coff(s1
, fd
);
10598 #ifdef TCC_TARGET_PE
10599 if (pe_test_res_file(&ehdr
, ret
)) {
10600 ret
= pe_load_res_file(s1
, fd
);
10604 /* as GNU ld, consider it is an ld script if not recognized */
10606 ret
= tcc_load_ldscript(s1
);
10608 error_noabort("unrecognized file type");
10623 int tcc_add_file(TCCState
*s
, const char *filename
)
10625 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
10628 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
10632 pathname1
= tcc_strdup(pathname
);
10633 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
10637 /* find and load a dll. Return non zero if not found */
10638 /* XXX: add '-rpath' option support ? */
10639 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
10644 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10645 snprintf(buf
, sizeof(buf
), "%s/%s",
10646 s
->library_paths
[i
], filename
);
10647 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
10653 /* the library name is the same as the argument of the '-l' option */
10654 int tcc_add_library(TCCState
*s
, const char *libraryname
)
10659 /* first we look for the dynamic library if not static linking */
10660 if (!s
->static_link
) {
10661 #ifdef TCC_TARGET_PE
10662 snprintf(buf
, sizeof(buf
), "%s.def", libraryname
);
10664 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
10666 if (tcc_add_dll(s
, buf
, 0) == 0)
10670 /* then we look for the static library */
10671 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10672 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
10673 s
->library_paths
[i
], libraryname
);
10674 if (tcc_add_file_internal(s
, buf
, 0) == 0)
10680 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
10682 add_elf_sym(symtab_section
, val
, 0,
10683 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
10688 int tcc_set_output_type(TCCState
*s
, int output_type
)
10692 s
->output_type
= output_type
;
10694 if (!s
->nostdinc
) {
10695 /* default include paths */
10696 /* XXX: reverse order needed if -isystem support */
10697 #ifndef TCC_TARGET_PE
10698 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/local/include");
10699 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/include");
10701 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
10702 tcc_add_sysinclude_path(s
, buf
);
10703 #ifdef TCC_TARGET_PE
10704 snprintf(buf
, sizeof(buf
), "%s/include/winapi", tcc_lib_path
);
10705 tcc_add_sysinclude_path(s
, buf
);
10709 /* if bound checking, then add corresponding sections */
10710 #ifdef CONFIG_TCC_BCHECK
10711 if (do_bounds_check
) {
10712 /* define symbol */
10713 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
10714 /* create bounds sections */
10715 bounds_section
= new_section(s
, ".bounds",
10716 SHT_PROGBITS
, SHF_ALLOC
);
10717 lbounds_section
= new_section(s
, ".lbounds",
10718 SHT_PROGBITS
, SHF_ALLOC
);
10722 if (s
->char_is_unsigned
) {
10723 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
10726 /* add debug sections */
10729 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
10730 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
10731 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
10732 put_elf_str(stabstr_section
, "");
10733 stab_section
->link
= stabstr_section
;
10734 /* put first entry */
10735 put_stabs("", 0, 0, 0, 0);
10738 /* add libc crt1/crti objects */
10739 #ifndef TCC_TARGET_PE
10740 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
10742 if (output_type
!= TCC_OUTPUT_DLL
)
10743 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
10744 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
10748 #ifdef TCC_TARGET_PE
10749 snprintf(buf
, sizeof(buf
), "%s/lib", tcc_lib_path
);
10750 tcc_add_library_path(s
, buf
);
10756 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
10757 #define FD_INVERT 0x0002 /* invert value before storing */
10759 typedef struct FlagDef
{
10765 static const FlagDef warning_defs
[] = {
10766 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
10767 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
10768 { offsetof(TCCState
, warn_error
), 0, "error" },
10769 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
10770 "implicit-function-declaration" },
10773 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
10774 const char *name
, int value
)
10781 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
10785 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
10786 if (!strcmp(r
, p
->name
))
10791 if (p
->flags
& FD_INVERT
)
10793 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
10798 /* set/reset a warning */
10799 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
10804 if (!strcmp(warning_name
, "all")) {
10805 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
10806 if (p
->flags
& WD_ALL
)
10807 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
10811 return set_flag(s
, warning_defs
, countof(warning_defs
),
10812 warning_name
, value
);
10816 static const FlagDef flag_defs
[] = {
10817 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
10818 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
10819 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
10820 { offsetof(TCCState
, leading_underscore
), 0, "leading-underscore" },
10823 /* set/reset a flag */
10824 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
10826 return set_flag(s
, flag_defs
, countof(flag_defs
),
10830 #if !defined(LIBTCC)
10832 static int64_t getclock_us(void)
10837 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
10840 gettimeofday(&tv
, NULL
);
10841 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
10847 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard\n"
10848 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
10849 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-soname name]\n"
10850 " [-static] [infile1 infile2...] [-run infile args...]\n"
10852 "General options:\n"
10853 " -v display current version, increase verbosity\n"
10854 " -c compile only - generate an object file\n"
10855 " -o outfile set output filename\n"
10856 " -Bdir set tcc internal library path\n"
10857 " -bench output compilation statistics\n"
10858 " -run run compiled source\n"
10859 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
10860 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
10861 " -w disable all warnings\n"
10862 "Preprocessor options:\n"
10863 " -E preprocess only\n"
10864 " -Idir add include path 'dir'\n"
10865 " -Dsym[=val] define 'sym' with value 'val'\n"
10866 " -Usym undefine 'sym'\n"
10867 "Linker options:\n"
10868 " -Ldir add library path 'dir'\n"
10869 " -llib link with dynamic or static library 'lib'\n"
10870 " -shared generate a shared library\n"
10871 " -soname set name for shared library to be used at runtime\n"
10872 " -static static linking\n"
10873 " -rdynamic export all global symbols to dynamic linker\n"
10874 " -r generate (relocatable) object file\n"
10875 "Debugger options:\n"
10876 " -g generate runtime debug info\n"
10877 #ifdef CONFIG_TCC_BCHECK
10878 " -b compile with built-in memory and bounds checker (implies -g)\n"
10880 " -bt N show N callers in stack traces\n"
10884 #define TCC_OPTION_HAS_ARG 0x0001
10885 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
10887 typedef struct TCCOption
{
10916 TCC_OPTION_nostdinc
,
10917 TCC_OPTION_nostdlib
,
10918 TCC_OPTION_print_search_dirs
,
10919 TCC_OPTION_rdynamic
,
10927 static const TCCOption tcc_options
[] = {
10928 { "h", TCC_OPTION_HELP
, 0 },
10929 { "?", TCC_OPTION_HELP
, 0 },
10930 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
10931 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
10932 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
10933 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
10934 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
10935 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10936 { "bench", TCC_OPTION_bench
, 0 },
10937 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
10938 #ifdef CONFIG_TCC_BCHECK
10939 { "b", TCC_OPTION_b
, 0 },
10941 { "g", TCC_OPTION_g
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10942 { "c", TCC_OPTION_c
, 0 },
10943 { "static", TCC_OPTION_static
, 0 },
10944 { "shared", TCC_OPTION_shared
, 0 },
10945 { "soname", TCC_OPTION_soname
, TCC_OPTION_HAS_ARG
},
10946 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
10947 { "run", TCC_OPTION_run
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10948 { "rdynamic", TCC_OPTION_rdynamic
, 0 },
10949 { "r", TCC_OPTION_r
, 0 },
10950 { "Wl,", TCC_OPTION_Wl
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10951 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10952 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10953 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
10954 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10955 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
10956 { "nostdlib", TCC_OPTION_nostdlib
, 0 },
10957 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
10958 { "v", TCC_OPTION_v
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10959 { "w", TCC_OPTION_w
, 0 },
10960 { "pipe", TCC_OPTION_pipe
, 0},
10961 { "E", TCC_OPTION_E
, 0},
10965 /* convert 'str' into an array of space separated strings */
10966 static int expand_args(char ***pargv
, const char *str
)
10975 while (is_space(*str
))
10980 while (*str
!= '\0' && !is_space(*str
))
10983 arg
= tcc_malloc(len
+ 1);
10984 memcpy(arg
, s1
, len
);
10986 dynarray_add((void ***)&argv
, &argc
, arg
);
10992 static char **files
;
10993 static int nb_files
, nb_libraries
;
10994 static int multiple_files
;
10995 static int print_search_dirs
;
10996 static int output_type
;
10997 static int reloc_output
;
10998 static const char *outfile
;
11000 int parse_args(TCCState
*s
, int argc
, char **argv
)
11003 const TCCOption
*popt
;
11004 const char *optarg
, *p1
, *r1
;
11008 while (optind
< argc
) {
11010 r
= argv
[optind
++];
11011 if (r
[0] != '-' || r
[1] == '\0') {
11012 /* add a new file */
11013 dynarray_add((void ***)&files
, &nb_files
, r
);
11014 if (!multiple_files
) {
11016 /* argv[0] will be this file */
11020 /* find option in table (match only the first chars */
11021 popt
= tcc_options
;
11025 error("invalid option -- '%s'", r
);
11038 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
11039 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
11042 if (optind
>= argc
)
11043 error("argument to '%s' is missing", r
);
11044 optarg
= argv
[optind
++];
11052 switch(popt
->index
) {
11053 case TCC_OPTION_HELP
:
11057 if (tcc_add_include_path(s
, optarg
) < 0)
11058 error("too many include paths");
11063 sym
= (char *)optarg
;
11064 value
= strchr(sym
, '=');
11069 tcc_define_symbol(s
, sym
, value
);
11073 tcc_undefine_symbol(s
, optarg
);
11076 tcc_add_library_path(s
, optarg
);
11079 /* set tcc utilities path (mainly for tcc development) */
11080 tcc_lib_path
= optarg
;
11083 dynarray_add((void ***)&files
, &nb_files
, r
);
11086 case TCC_OPTION_bench
:
11089 case TCC_OPTION_bt
:
11090 num_callers
= atoi(optarg
);
11092 #ifdef CONFIG_TCC_BCHECK
11094 do_bounds_check
= 1;
11102 multiple_files
= 1;
11103 output_type
= TCC_OUTPUT_OBJ
;
11105 case TCC_OPTION_static
:
11106 s
->static_link
= 1;
11108 case TCC_OPTION_shared
:
11109 output_type
= TCC_OUTPUT_DLL
;
11111 case TCC_OPTION_soname
:
11112 s
->soname
= optarg
;
11115 multiple_files
= 1;
11119 /* generate a .o merging several output files */
11121 output_type
= TCC_OUTPUT_OBJ
;
11123 case TCC_OPTION_nostdinc
:
11126 case TCC_OPTION_nostdlib
:
11129 case TCC_OPTION_print_search_dirs
:
11130 print_search_dirs
= 1;
11132 case TCC_OPTION_run
:
11136 argc1
= expand_args(&argv1
, optarg
);
11138 parse_args(s
, argc1
, argv1
);
11140 multiple_files
= 0;
11141 output_type
= TCC_OUTPUT_MEMORY
;
11146 if (0 == verbose
++)
11147 printf("tcc version %s\n", TCC_VERSION
);
11148 } while (*optarg
++ == 'v');
11151 if (tcc_set_flag(s
, optarg
, 1) < 0 && s
->warn_unsupported
)
11152 goto unsupported_option
;
11155 if (tcc_set_warning(s
, optarg
, 1) < 0 &&
11156 s
->warn_unsupported
)
11157 goto unsupported_option
;
11162 case TCC_OPTION_rdynamic
:
11165 case TCC_OPTION_Wl
:
11168 if (strstart(optarg
, "-Ttext,", &p
)) {
11169 s
->text_addr
= strtoul(p
, NULL
, 16);
11170 s
->has_text_addr
= 1;
11171 } else if (strstart(optarg
, "--oformat,", &p
)) {
11172 if (strstart(p
, "elf32-", NULL
)) {
11173 s
->output_format
= TCC_OUTPUT_FORMAT_ELF
;
11174 } else if (!strcmp(p
, "binary")) {
11175 s
->output_format
= TCC_OUTPUT_FORMAT_BINARY
;
11177 #ifdef TCC_TARGET_COFF
11178 if (!strcmp(p
, "coff")) {
11179 s
->output_format
= TCC_OUTPUT_FORMAT_COFF
;
11183 error("target %s not found", p
);
11186 error("unsupported linker option '%s'", optarg
);
11191 output_type
= TCC_OUTPUT_PREPROCESS
;
11194 if (s
->warn_unsupported
) {
11195 unsupported_option
:
11196 warning("unsupported option '%s'", r
);
11205 int main(int argc
, char **argv
)
11209 int nb_objfiles
, ret
, optind
;
11210 char objfilename
[1024];
11211 int64_t start_time
= 0;
11214 tcc_lib_path
= w32_tcc_lib_path();
11218 output_type
= TCC_OUTPUT_EXE
;
11220 multiple_files
= 1;
11225 print_search_dirs
= 0;
11228 optind
= parse_args(s
, argc
- 1, argv
+ 1);
11229 if (print_search_dirs
) {
11230 /* enough for Linux kernel */
11231 printf("install: %s/\n", tcc_lib_path
);
11234 if (optind
== 0 || nb_files
== 0) {
11235 if (optind
&& verbose
)
11241 nb_objfiles
= nb_files
- nb_libraries
;
11243 /* if outfile provided without other options, we output an
11245 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
11246 output_type
= TCC_OUTPUT_EXE
;
11248 /* check -c consistency : only single file handled. XXX: checks file type */
11249 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
11250 /* accepts only a single input file */
11251 if (nb_objfiles
!= 1)
11252 error("cannot specify multiple files with -c");
11253 if (nb_libraries
!= 0)
11254 error("cannot specify libraries with -c");
11258 if (output_type
== TCC_OUTPUT_PREPROCESS
) {
11260 s
->outfile
= stdout
;
11262 s
->outfile
= fopen(outfile
, "w");
11264 error("could not open '%s", outfile
);
11266 } else if (output_type
!= TCC_OUTPUT_MEMORY
) {
11268 /* compute default outfile name */
11271 strcmp(files
[0], "-") == 0 ? "a" : tcc_basename(files
[0]);
11272 pstrcpy(objfilename
, sizeof(objfilename
), name
);
11273 ext
= tcc_fileextension(objfilename
);
11274 #ifdef TCC_TARGET_PE
11275 if (output_type
== TCC_OUTPUT_DLL
)
11276 strcpy(ext
, ".dll");
11278 if (output_type
== TCC_OUTPUT_EXE
)
11279 strcpy(ext
, ".exe");
11282 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
&& *ext
)
11285 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
11286 outfile
= objfilename
;
11291 start_time
= getclock_us();
11294 tcc_set_output_type(s
, output_type
);
11296 /* compile or add each files or library */
11297 for(i
= 0; i
< nb_files
&& ret
== 0; i
++) {
11298 const char *filename
;
11300 filename
= files
[i
];
11301 if (output_type
== TCC_OUTPUT_PREPROCESS
) {
11302 if (tcc_add_file_internal(s
, filename
,
11303 AFF_PRINT_ERROR
| AFF_PREPROCESS
) < 0)
11305 } else if (filename
[0] == '-' && filename
[1]) {
11306 if (tcc_add_library(s
, filename
+ 2) < 0)
11307 error("cannot find %s", filename
);
11310 printf("-> %s\n", filename
);
11311 if (tcc_add_file(s
, filename
) < 0)
11316 /* free all files */
11324 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
11325 if (total_time
< 0.001)
11326 total_time
= 0.001;
11327 if (total_bytes
< 1)
11329 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
11330 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
11331 total_time
, (int)(total_lines
/ total_time
),
11332 total_bytes
/ total_time
/ 1000000.0);
11335 if (s
->output_type
== TCC_OUTPUT_PREPROCESS
) {
11337 fclose(s
->outfile
);
11338 } else if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
11339 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
11341 ret
= tcc_output_file(s
, outfile
) ? 1 : 0;
11343 /* XXX: cannot do it with bound checking because of the malloc hooks */
11344 if (!do_bounds_check
)
11349 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);