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
43 #include <sys/timeb.h>
45 #define inline __inline
52 #include <sys/ucontext.h>
56 #endif /* !CONFIG_TCCBOOT */
73 /* preprocessor debug */
75 /* include file debug */
83 /* target selection */
84 //#define TCC_TARGET_I386 /* i386 code generator */
85 //#define TCC_TARGET_ARM /* ARMv4 code generator */
86 //#define TCC_TARGET_C67 /* TMS320C67xx code generator */
87 //#define TCC_TARGET_X86_64 /* x86-64 code generator */
89 /* default target is I386 */
90 #if !defined(TCC_TARGET_I386) && !defined(TCC_TARGET_ARM) && \
91 !defined(TCC_TARGET_C67) && !defined(TCC_TARGET_X86_64)
92 #define TCC_TARGET_I386
95 #if !defined(_WIN32) && !defined(TCC_UCLIBC) && !defined(TCC_TARGET_ARM) && \
96 !defined(TCC_TARGET_C67) && !defined(TCC_TARGET_X86_64)
97 #define CONFIG_TCC_BCHECK /* enable bound checking code */
100 #if defined(_WIN32) && !defined(TCC_TARGET_PE)
101 #define CONFIG_TCC_STATIC
104 /* define it to include assembler support */
105 #if !defined(TCC_TARGET_ARM) && !defined(TCC_TARGET_C67) && \
106 !defined(TCC_TARGET_X86_64)
107 #define CONFIG_TCC_ASM
110 /* object format selection */
111 #if defined(TCC_TARGET_C67)
112 #define TCC_TARGET_COFF
121 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
122 executables or dlls */
123 #define CONFIG_TCC_CRT_PREFIX CONFIG_SYSROOT "/usr/lib"
125 #define INCLUDE_STACK_SIZE 32
126 #define IFDEF_STACK_SIZE 64
127 #define VSTACK_SIZE 256
128 #define STRING_MAX_SIZE 1024
129 #define PACK_STACK_SIZE 8
131 #define TOK_HASH_SIZE 8192 /* must be a power of two */
132 #define TOK_ALLOC_INCR 512 /* must be a power of two */
133 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
135 /* token symbol management */
136 typedef struct TokenSym
{
137 struct TokenSym
*hash_next
;
138 struct Sym
*sym_define
; /* direct pointer to define */
139 struct Sym
*sym_label
; /* direct pointer to label */
140 struct Sym
*sym_struct
; /* direct pointer to structure */
141 struct Sym
*sym_identifier
; /* direct pointer to identifier */
142 int tok
; /* token number */
148 typedef unsigned short nwchar_t
;
150 typedef int nwchar_t
;
153 typedef struct CString
{
154 int size
; /* size in bytes */
155 void *data
; /* either 'char *' or 'nwchar_t *' */
157 void *data_allocated
; /* if non NULL, data has been malloced */
160 /* type definition */
161 typedef struct CType
{
167 typedef union CValue
{
173 unsigned int ul
; /* address (should be unsigned long on 64 bit cpu) */
175 unsigned long long ull
;
176 struct CString
*cstr
;
182 typedef struct SValue
{
183 CType type
; /* type */
184 unsigned short r
; /* register + flags */
185 unsigned short r2
; /* second register, used for 'long long'
186 type. If not used, set to VT_CONST */
187 CValue c
; /* constant, if VT_CONST */
188 struct Sym
*sym
; /* symbol, if (VT_SYM | VT_CONST) */
191 /* symbol management */
193 int v
; /* symbol token */
194 long r
; /* associated register */
195 long c
; /* associated number */
196 CType type
; /* associated type */
197 struct Sym
*next
; /* next related symbol */
198 struct Sym
*prev
; /* prev symbol in stack */
199 struct Sym
*prev_tok
; /* previous symbol for this token */
202 /* section definition */
203 /* XXX: use directly ELF structure for parameters ? */
204 /* special flag to indicate that the section should not be linked to
206 #define SHF_PRIVATE 0x80000000
208 typedef struct Section
{
209 unsigned long data_offset
; /* current data offset */
210 unsigned char *data
; /* section data */
211 unsigned long data_allocated
; /* used for realloc() handling */
212 int sh_name
; /* elf section name (only used during output) */
213 int sh_num
; /* elf section number */
214 int sh_type
; /* elf section type */
215 int sh_flags
; /* elf section flags */
216 int sh_info
; /* elf section info */
217 int sh_addralign
; /* elf section alignment */
218 int sh_entsize
; /* elf entry size */
219 unsigned long sh_size
; /* section size (only used during output) */
220 unsigned long sh_addr
; /* address at which the section is relocated */
221 unsigned long sh_offset
; /* file offset */
222 int nb_hashed_syms
; /* used to resize the hash table */
223 struct Section
*link
; /* link to another section */
224 struct Section
*reloc
; /* corresponding section for relocation, if any */
225 struct Section
*hash
; /* hash table for symbols */
226 struct Section
*next
;
227 char name
[1]; /* section name */
230 typedef struct DLLReference
{
236 /* GNUC attribute definition */
237 typedef struct AttributeDef
{
241 int func_attr
; /* calling convention, exports, ... */
244 /* -------------------------------------------------- */
245 /* gr: wrappers for casting sym->r for other purposes */
253 #define FUNC_CALL(r) (((func_attr_t*)&(r))->func_call)
254 #define FUNC_EXPORT(r) (((func_attr_t*)&(r))->func_export)
255 #define FUNC_ARGS(r) (((func_attr_t*)&(r))->func_args)
256 #define INLINE_DEF(r) (*(int **)&(r))
257 /* -------------------------------------------------- */
259 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
260 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
261 #define SYM_FIRST_ANOM 0x10000000 /* first anonymous sym */
263 /* stored in 'Sym.c' field */
264 #define FUNC_NEW 1 /* ansi function prototype */
265 #define FUNC_OLD 2 /* old function prototype */
266 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
268 /* stored in 'Sym.r' field */
269 #define FUNC_CDECL 0 /* standard c call */
270 #define FUNC_STDCALL 1 /* pascal c call */
271 #define FUNC_FASTCALL1 2 /* first param in %eax */
272 #define FUNC_FASTCALL2 3 /* first parameters in %eax, %edx */
273 #define FUNC_FASTCALL3 4 /* first parameter in %eax, %edx, %ecx */
274 #define FUNC_FASTCALLW 5 /* first parameter in %ecx, %edx */
276 /* field 'Sym.t' for macros */
277 #define MACRO_OBJ 0 /* object like macro */
278 #define MACRO_FUNC 1 /* function like macro */
280 /* field 'Sym.r' for C labels */
281 #define LABEL_DEFINED 0 /* label is defined */
282 #define LABEL_FORWARD 1 /* label is forward defined */
283 #define LABEL_DECLARED 2 /* label is declared but never used */
285 /* type_decl() types */
286 #define TYPE_ABSTRACT 1 /* type without variable */
287 #define TYPE_DIRECT 2 /* type with variable */
289 #define IO_BUF_SIZE 8192
291 typedef struct BufferedFile
{
295 int line_num
; /* current line number - here to simplify code */
296 int ifndef_macro
; /* #ifndef macro / #endif search */
297 int ifndef_macro_saved
; /* saved ifndef_macro */
298 int *ifdef_stack_ptr
; /* ifdef_stack value at the start of the file */
299 char inc_type
; /* type of include */
300 char inc_filename
[512]; /* filename specified by the user */
301 char filename
[1024]; /* current filename - here to simplify code */
302 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
305 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
306 #define CH_EOF (-1) /* end of file */
308 /* parsing state (used to save parser state to reparse part of the
309 source several times) */
310 typedef struct ParseState
{
317 /* used to record tokens */
318 typedef struct TokenString
{
325 /* include file cache, used to find files faster and also to eliminate
326 inclusion if the include file is protected by #ifndef ... #endif */
327 typedef struct CachedInclude
{
329 int hash_next
; /* -1 if none */
330 char type
; /* '"' or '>' to give include type */
331 char filename
[1]; /* path specified in #include */
334 #define CACHED_INCLUDES_HASH_SIZE 512
337 static struct BufferedFile
*file
;
339 static CString tok_spaces
; /* spaces before current token */
341 static CString tokcstr
; /* current parsed string, if any */
342 /* additional informations about token */
343 static int tok_flags
;
344 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
345 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
346 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
347 #define TOK_FLAG_EOF 0x0008 /* end of file */
349 static int *macro_ptr
, *macro_ptr_allocated
;
350 static int *unget_saved_macro_ptr
;
351 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
352 static int unget_buffer_enabled
;
353 static int parse_flags
;
354 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
355 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
356 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
357 token. line feed is also
359 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
361 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
362 static Section
*cur_text_section
; /* current section where function code is
364 #ifdef CONFIG_TCC_ASM
365 static Section
*last_text_section
; /* to handle .previous asm directive */
367 /* bound check related sections */
368 static Section
*bounds_section
; /* contains global data bound description */
369 static Section
*lbounds_section
; /* contains local data bound description */
370 /* symbol sections */
371 static Section
*symtab_section
, *strtab_section
;
374 static Section
*stab_section
, *stabstr_section
;
376 /* loc : local variable index
377 ind : output code index
379 anon_sym: anonymous symbol index
381 static int rsym
, anon_sym
, ind
, loc
;
382 /* expression generation modifiers */
383 static int const_wanted
; /* true if constant wanted */
384 static int nocode_wanted
; /* true if no code generation wanted for an expression */
385 static int global_expr
; /* true if compound literals must be allocated
386 globally (used during initializers parsing */
387 static CType func_vt
; /* current function return type (used by return
390 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
391 static int tok_ident
;
392 static TokenSym
**table_ident
;
393 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
394 static char token_buf
[STRING_MAX_SIZE
+ 1];
395 static char *funcname
;
396 static Sym
*global_stack
, *local_stack
;
397 static Sym
*define_stack
;
398 static Sym
*global_label_stack
, *local_label_stack
;
399 /* symbol allocator */
400 #define SYM_POOL_NB (8192 / sizeof(Sym))
401 static Sym
*sym_free_first
;
402 static void **sym_pools
;
403 static int nb_sym_pools
;
405 static SValue vstack
[VSTACK_SIZE
], *vtop
;
406 /* some predefined types */
407 static CType char_pointer_type
, func_old_type
, int_type
;
408 /* true if isid(c) || isnum(c) */
409 static unsigned char isidnum_table
[256-CH_EOF
];
411 /* display some information during compilation */
412 static int verbose
= 0;
414 /* compile with debug symbol (and use them if error during execution) */
415 static int do_debug
= 0;
417 /* compile with built-in memory and bounds checker */
418 static int do_bounds_check
= 0;
420 /* display benchmark infos */
422 static int do_bench
= 0;
424 static int total_lines
;
425 static int total_bytes
;
427 /* use GNU C extensions */
428 static int gnu_ext
= 1;
430 /* use Tiny C extensions */
431 static int tcc_ext
= 1;
433 /* max number of callers shown if error */
434 static int num_callers
= 6;
435 static const char **rt_bound_error_msg
;
437 /* XXX: get rid of this ASAP */
438 static struct TCCState
*tcc_state
;
440 /* give the path of the tcc libraries */
441 static const char *tcc_lib_path
= CONFIG_TCCDIR
;
446 BufferedFile
**include_stack_ptr
;
447 int *ifdef_stack_ptr
;
449 /* include file handling */
450 char **include_paths
;
451 int nb_include_paths
;
452 char **sysinclude_paths
;
453 int nb_sysinclude_paths
;
454 CachedInclude
**cached_includes
;
455 int nb_cached_includes
;
457 char **library_paths
;
458 int nb_library_paths
;
460 /* array of all loaded dlls (including those referenced by loaded
462 DLLReference
**loaded_dlls
;
467 int nb_sections
; /* number of sections, including first dummy section */
469 Section
**priv_sections
;
470 int nb_priv_sections
; /* number of private sections */
475 unsigned long *got_offsets
;
477 /* give the correspondance from symtab indexes to dynsym indexes */
478 int *symtab_to_dynsym
;
480 /* temporary dynamic symbol sections (for dll loading) */
481 Section
*dynsymtab_section
;
482 /* exported dynamic symbol section */
485 int nostdinc
; /* if true, no standard headers are added */
486 int nostdlib
; /* if true, no standard libraries are added */
488 int nocommon
; /* if true, do not use common symbols for .bss data */
490 /* if true, static linking is performed */
493 /* soname as specified on the command line (-soname) */
496 /* if true, all symbols are exported */
499 /* if true, only link in referenced objects from archive */
502 /* address of text section */
503 unsigned long text_addr
;
506 /* output format, see TCC_OUTPUT_FORMAT_xxx */
509 /* C language options */
510 int char_is_unsigned
;
511 int leading_underscore
;
513 /* warning switches */
514 int warn_write_strings
;
515 int warn_unsupported
;
518 int warn_implicit_function_declaration
;
522 void (*error_func
)(void *opaque
, const char *msg
);
523 int error_set_jmp_enabled
;
524 jmp_buf error_jmp_buf
;
527 /* tiny assembler state */
530 /* see include_stack_ptr */
531 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
533 /* see ifdef_stack_ptr */
534 int ifdef_stack
[IFDEF_STACK_SIZE
];
536 /* see cached_includes */
537 int cached_includes_hash
[CACHED_INCLUDES_HASH_SIZE
];
540 int pack_stack
[PACK_STACK_SIZE
];
543 /* output file for preprocessing */
546 #ifdef TCC_TARGET_X86_64
547 /* buffer to store jump tables used when the output is memory */
550 /* buffer to store got tables used when the output is memory */
556 /* The current value can be: */
557 #define VT_VALMASK 0x00ff
558 #define VT_CONST 0x00f0 /* constant in vc
559 (must be first non register value) */
560 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
561 #define VT_LOCAL 0x00f2 /* offset on stack */
562 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
563 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
564 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
565 #define VT_LVAL 0x0100 /* var is an lvalue */
566 #define VT_SYM 0x0200 /* a symbol value is added */
567 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
568 char/short stored in integer registers) */
569 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
570 dereferencing value */
571 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
572 bounding function call point is in vc */
573 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
574 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
575 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
576 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
579 #define VT_INT 0 /* integer type */
580 #define VT_BYTE 1 /* signed byte type */
581 #define VT_SHORT 2 /* short type */
582 #define VT_VOID 3 /* void type */
583 #define VT_PTR 4 /* pointer */
584 #define VT_ENUM 5 /* enum definition */
585 #define VT_FUNC 6 /* function type */
586 #define VT_STRUCT 7 /* struct/union definition */
587 #define VT_FLOAT 8 /* IEEE float */
588 #define VT_DOUBLE 9 /* IEEE double */
589 #define VT_LDOUBLE 10 /* IEEE long double */
590 #define VT_BOOL 11 /* ISOC99 boolean type */
591 #define VT_LLONG 12 /* 64 bit integer */
592 #define VT_LONG 13 /* long integer (NEVER USED as type, only
594 #define VT_BTYPE 0x000f /* mask for basic type */
595 #define VT_UNSIGNED 0x0010 /* unsigned type */
596 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
597 #define VT_BITFIELD 0x0040 /* bitfield modifier */
598 #define VT_CONSTANT 0x0800 /* const modifier */
599 #define VT_VOLATILE 0x1000 /* volatile modifier */
600 #define VT_SIGNED 0x2000 /* signed type */
603 #define VT_EXTERN 0x00000080 /* extern definition */
604 #define VT_STATIC 0x00000100 /* static variable */
605 #define VT_TYPEDEF 0x00000200 /* typedef definition */
606 #define VT_INLINE 0x00000400 /* inline definition */
608 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
610 /* type mask (except storage) */
611 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
612 #define VT_TYPE (~(VT_STORAGE))
616 /* warning: the following compare tokens depend on i386 asm code */
623 #define TOK_Nset 0x98
624 #define TOK_Nclear 0x99
630 #define TOK_LAND 0xa0
634 #define TOK_MID 0xa3 /* inc/dec, to void constant */
636 #define TOK_UDIV 0xb0 /* unsigned division */
637 #define TOK_UMOD 0xb1 /* unsigned modulo */
638 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
639 #define TOK_CINT 0xb3 /* number in tokc */
640 #define TOK_CCHAR 0xb4 /* char constant in tokc */
641 #define TOK_STR 0xb5 /* pointer to string in tokc */
642 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
643 #define TOK_LCHAR 0xb7
644 #define TOK_LSTR 0xb8
645 #define TOK_CFLOAT 0xb9 /* float constant */
646 #define TOK_LINENUM 0xba /* line number info */
647 #define TOK_CDOUBLE 0xc0 /* double constant */
648 #define TOK_CLDOUBLE 0xc1 /* long double constant */
649 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
650 #define TOK_ADDC1 0xc3 /* add with carry generation */
651 #define TOK_ADDC2 0xc4 /* add with carry use */
652 #define TOK_SUBC1 0xc5 /* add with carry generation */
653 #define TOK_SUBC2 0xc6 /* add with carry use */
654 #define TOK_CUINT 0xc8 /* unsigned int constant */
655 #define TOK_CLLONG 0xc9 /* long long constant */
656 #define TOK_CULLONG 0xca /* unsigned long long constant */
657 #define TOK_ARROW 0xcb
658 #define TOK_DOTS 0xcc /* three dots */
659 #define TOK_SHR 0xcd /* unsigned shift right */
660 #define TOK_PPNUM 0xce /* preprocessor number */
662 #define TOK_SHL 0x01 /* shift left */
663 #define TOK_SAR 0x02 /* signed shift right */
665 /* assignement operators : normal operator or 0x80 */
666 #define TOK_A_MOD 0xa5
667 #define TOK_A_AND 0xa6
668 #define TOK_A_MUL 0xaa
669 #define TOK_A_ADD 0xab
670 #define TOK_A_SUB 0xad
671 #define TOK_A_DIV 0xaf
672 #define TOK_A_XOR 0xde
673 #define TOK_A_OR 0xfc
674 #define TOK_A_SHL 0x81
675 #define TOK_A_SAR 0x82
678 #define offsetof(type, field) ((size_t) &((type *)0)->field)
682 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
685 /* WARNING: the content of this string encodes token numbers */
686 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";
688 #define TOK_EOF (-1) /* end of file */
689 #define TOK_LINEFEED 10 /* line feed */
691 /* all identificators and strings have token above that */
692 #define TOK_IDENT 256
694 /* only used for i386 asm opcodes definitions */
695 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
698 DEF(TOK_ASM_ ## x ## b, #x "b") \
699 DEF(TOK_ASM_ ## x ## w, #x "w") \
700 DEF(TOK_ASM_ ## x ## l, #x "l") \
701 DEF(TOK_ASM_ ## x, #x)
704 DEF(TOK_ASM_ ## x ## w, #x "w") \
705 DEF(TOK_ASM_ ## x ## l, #x "l") \
706 DEF(TOK_ASM_ ## x, #x)
709 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
710 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
711 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
712 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
715 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
716 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
719 #define DEF_ASMTEST(x) \
751 #define TOK_ASM_int TOK_INT
754 TOK_LAST
= TOK_IDENT
- 1,
755 #define DEF(id, str) id,
760 static const char tcc_keywords
[] =
761 #define DEF(id, str) str "\0"
766 #define TOK_UIDENT TOK_DEFINE
769 #define snprintf _snprintf
770 #define vsnprintf _vsnprintf
772 #define strtold (long double)strtod
773 #define strtof (float)strtod
774 #define strtoll (long long)strtol
776 #elif defined(TCC_UCLIBC) || defined(__FreeBSD__) || defined(__DragonFly__) \
777 || defined(__OpenBSD__)
778 /* currently incorrect */
779 long double strtold(const char *nptr
, char **endptr
)
781 return (long double)strtod(nptr
, endptr
);
783 float strtof(const char *nptr
, char **endptr
)
785 return (float)strtod(nptr
, endptr
);
788 /* XXX: need to define this to use them in non ISOC99 context */
789 extern float strtof (const char *__nptr
, char **__endptr
);
790 extern long double strtold (const char *__nptr
, char **__endptr
);
793 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
794 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
795 static char *tcc_basename(const char *name
);
796 static char *tcc_fileextension (const char *p
);
798 static void next(void);
799 static void next_nomacro(void);
800 static void parse_expr_type(CType
*type
);
801 static void expr_type(CType
*type
);
802 static void unary_type(CType
*type
);
803 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
804 int case_reg
, int is_expr
);
805 static int expr_const(void);
806 static void expr_eq(void);
807 static void gexpr(void);
808 static void gen_inline_functions(void);
809 static void decl(int l
);
810 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
811 int first
, int size_only
);
812 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
813 int has_init
, int v
, int scope
);
815 void gv2(int rc1
, int rc2
);
816 void move_reg(int r
, int s
);
817 void save_regs(int n
);
818 void save_reg(int r
);
823 int get_reg_ex(int rc
,int rc2
);
826 struct macro_level
*prev
;
830 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
831 const int *macro_str
, struct macro_level
**can_read_stream
);
833 void force_charshort_cast(int t
);
834 static void gen_cast(CType
*type
);
836 static Sym
*sym_find(int v
);
837 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
840 static int type_size(CType
*type
, int *a
);
841 static inline CType
*pointed_type(CType
*type
);
842 static int pointed_size(CType
*type
);
843 static int lvalue_type(int t
);
844 static int parse_btype(CType
*type
, AttributeDef
*ad
);
845 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
846 static int compare_types(CType
*type1
, CType
*type2
, int unqualified
);
847 static int is_compatible_types(CType
*type1
, CType
*type2
);
848 static int is_compatible_parameter_types(CType
*type1
, CType
*type2
);
850 int ieee_finite(double d
);
851 void error(const char *fmt
, ...);
853 void vpushll(long long v
);
856 void lexpand_nr(void);
857 static void vpush_global_sym(CType
*type
, int v
);
858 void vset(CType
*type
, int r
, int v
);
859 void type_to_str(char *buf
, int buf_size
,
860 CType
*type
, const char *varstr
);
861 char *get_tok_str(int v
, CValue
*cv
);
862 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
863 unsigned long offset
, unsigned long size
);
864 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
866 /* section generation */
867 static void section_realloc(Section
*sec
, unsigned long new_size
);
868 static void *section_ptr_add(Section
*sec
, unsigned long size
);
869 static void put_extern_sym(Sym
*sym
, Section
*section
,
870 unsigned long value
, unsigned long size
);
871 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
872 static int put_elf_str(Section
*s
, const char *sym
);
873 static int put_elf_sym(Section
*s
,
874 unsigned long value
, unsigned long size
,
875 int info
, int other
, int shndx
, const char *name
);
876 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
877 int info
, int other
, int sh_num
, const char *name
);
878 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
879 int type
, int symbol
);
880 static void put_stabs(const char *str
, int type
, int other
, int desc
,
881 unsigned long value
);
882 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
883 unsigned long value
, Section
*sec
, int sym_index
);
884 static void put_stabn(int type
, int other
, int desc
, int value
);
885 static void put_stabd(int type
, int other
, int desc
);
886 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
888 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
889 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
890 #define AFF_PREPROCESS 0x0004 /* preprocess file */
891 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
894 int tcc_output_coff(TCCState
*s1
, FILE *f
);
897 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
);
898 int pe_load_def_file(struct TCCState
*s1
, int fd
);
899 int pe_test_res_file(void *v
, int size
);
900 int pe_load_res_file(struct TCCState
*s1
, int fd
);
901 void pe_add_runtime(struct TCCState
*s1
);
902 void pe_guess_outfile(char *objfilename
, int output_type
);
903 int pe_output_file(struct TCCState
*s1
, const char *filename
);
907 #ifdef CONFIG_TCC_ASM
909 typedef struct ExprValue
{
914 #define MAX_ASM_OPERANDS 30
916 typedef struct ASMOperand
{
917 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
919 char asm_str
[16]; /* computed asm string for operand */
920 SValue
*vt
; /* C value of the expression */
921 int ref_index
; /* if >= 0, gives reference to a output constraint */
922 int input_index
; /* if >= 0, gives reference to an input constraint */
923 int priority
; /* priority, used to assign registers */
924 int reg
; /* if >= 0, register number used for this operand */
925 int is_llong
; /* true if double register value */
926 int is_memory
; /* true if memory operand */
927 int is_rw
; /* for '+' modifier */
930 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
931 static int asm_int_expr(TCCState
*s1
);
932 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
933 const char *name
, const char **pp
);
935 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
939 static void asm_instr(void);
940 static void asm_global_instr(void);
942 /* true if float/double/long double type */
943 static inline int is_float(int t
)
947 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
950 #ifdef TCC_TARGET_I386
951 #include "i386-gen.c"
954 #ifdef TCC_TARGET_ARM
958 #ifdef TCC_TARGET_C67
962 #ifdef TCC_TARGET_X86_64
963 #include "x86_64-gen.c"
966 #ifdef CONFIG_TCC_STATIC
968 #define RTLD_LAZY 0x001
969 #define RTLD_NOW 0x002
970 #define RTLD_GLOBAL 0x100
971 #define RTLD_DEFAULT NULL
973 /* dummy function for profiling */
974 void *dlopen(const char *filename
, int flag
)
979 const char *dlerror(void)
984 typedef struct TCCSyms
{
989 #define TCCSYM(a) { #a, &a, },
991 /* add the symbol you want here if no dynamic linking is done */
992 static TCCSyms tcc_syms
[] = {
993 #if !defined(CONFIG_TCCBOOT)
1002 void *resolve_sym(TCCState
*s1
, const char *symbol
, int type
)
1006 while (p
->str
!= NULL
) {
1007 if (!strcmp(p
->str
, symbol
))
1014 #elif !defined(_WIN32)
1018 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
)
1020 return dlsym(RTLD_DEFAULT
, sym
);
1025 /********************************************************/
1027 /* we use our own 'finite' function to avoid potential problems with
1028 non standard math libs */
1029 /* XXX: endianness dependent */
1030 int ieee_finite(double d
)
1033 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
1036 /* copy a string and truncate it. */
1037 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
1044 q_end
= buf
+ buf_size
- 1;
1056 /* strcat and truncate. */
1057 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
1062 pstrcpy(buf
+ len
, buf_size
- len
, s
);
1067 static int strstart(const char *str
, const char *val
, const char **ptr
)
1072 while (*q
!= '\0') {
1085 #define IS_PATHSEP(c) (c == '/' || c == '\\')
1086 #define IS_ABSPATH(p) (IS_PATHSEP(p[0]) || (p[0] && p[1] == ':' && IS_PATHSEP(p[2])))
1088 #define IS_PATHSEP(c) (c == '/')
1089 #define IS_ABSPATH(p) IS_PATHSEP(p[0])
1092 /* extract the basename of a file */
1093 static char *tcc_basename(const char *name
)
1095 char *p
= strchr(name
, 0);
1096 while (p
> name
&& !IS_PATHSEP(p
[-1]))
1101 static char *tcc_fileextension (const char *name
)
1103 char *b
= tcc_basename(name
);
1104 char *e
= strrchr(b
, '.');
1105 return e
? e
: strchr(b
, 0);
1109 char *normalize_slashes(char *path
)
1112 for (p
= path
; *p
; ++p
)
1118 char *w32_tcc_lib_path(void)
1120 /* on win32, we suppose the lib and includes are at the location
1122 char path
[1024], *p
;
1123 GetModuleFileNameA(NULL
, path
, sizeof path
);
1124 p
= tcc_basename(normalize_slashes(strlwr(path
)));
1125 if (p
- 5 > path
&& 0 == strncmp(p
- 5, "/bin/", 5))
1130 return strdup(path
);
1134 void set_pages_executable(void *ptr
, unsigned long length
)
1137 unsigned long old_protect
;
1138 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
1140 unsigned long start
, end
;
1141 start
= (unsigned long)ptr
& ~(PAGESIZE
- 1);
1142 end
= (unsigned long)ptr
+ length
;
1143 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
1144 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
1148 /* memory management */
1152 unsigned malloc_usable_size(void*);
1155 static inline void tcc_free(void *ptr
)
1158 mem_cur_size
-= malloc_usable_size(ptr
);
1163 static void *tcc_malloc(unsigned long size
)
1168 error("memory full");
1170 mem_cur_size
+= malloc_usable_size(ptr
);
1171 if (mem_cur_size
> mem_max_size
)
1172 mem_max_size
= mem_cur_size
;
1177 static void *tcc_mallocz(unsigned long size
)
1180 ptr
= tcc_malloc(size
);
1181 memset(ptr
, 0, size
);
1185 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
1189 mem_cur_size
-= malloc_usable_size(ptr
);
1191 ptr1
= realloc(ptr
, size
);
1193 /* NOTE: count not correct if alloc error, but not critical */
1194 mem_cur_size
+= malloc_usable_size(ptr1
);
1195 if (mem_cur_size
> mem_max_size
)
1196 mem_max_size
= mem_cur_size
;
1201 static char *tcc_strdup(const char *str
)
1204 ptr
= tcc_malloc(strlen(str
) + 1);
1209 #define free(p) use_tcc_free(p)
1210 #define malloc(s) use_tcc_malloc(s)
1211 #define realloc(p, s) use_tcc_realloc(p, s)
1213 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
1220 /* every power of two we double array size */
1221 if ((nb
& (nb
- 1)) == 0) {
1226 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
1228 error("memory full");
1235 static void dynarray_reset(void *pp
, int *n
)
1238 for (p
= *(void***)pp
; *n
; ++p
, --*n
)
1241 tcc_free(*(void**)pp
);
1245 /* symbol allocator */
1246 static Sym
*__sym_malloc(void)
1248 Sym
*sym_pool
, *sym
, *last_sym
;
1251 sym_pool
= tcc_malloc(SYM_POOL_NB
* sizeof(Sym
));
1252 dynarray_add(&sym_pools
, &nb_sym_pools
, sym_pool
);
1254 last_sym
= sym_free_first
;
1256 for(i
= 0; i
< SYM_POOL_NB
; i
++) {
1257 sym
->next
= last_sym
;
1261 sym_free_first
= last_sym
;
1265 static inline Sym
*sym_malloc(void)
1268 sym
= sym_free_first
;
1270 sym
= __sym_malloc();
1271 sym_free_first
= sym
->next
;
1275 static inline void sym_free(Sym
*sym
)
1277 sym
->next
= sym_free_first
;
1278 sym_free_first
= sym
;
1281 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
1285 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
1286 strcpy(sec
->name
, name
);
1287 sec
->sh_type
= sh_type
;
1288 sec
->sh_flags
= sh_flags
;
1296 sec
->sh_addralign
= 4;
1299 sec
->sh_addralign
= 1;
1302 sec
->sh_addralign
= 32; /* default conservative alignment */
1306 if (sh_flags
& SHF_PRIVATE
) {
1307 dynarray_add((void ***)&s1
->priv_sections
, &s1
->nb_priv_sections
, sec
);
1309 sec
->sh_num
= s1
->nb_sections
;
1310 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
1316 static void free_section(Section
*s
)
1321 /* realloc section and set its content to zero */
1322 static void section_realloc(Section
*sec
, unsigned long new_size
)
1325 unsigned char *data
;
1327 size
= sec
->data_allocated
;
1330 while (size
< new_size
)
1332 data
= tcc_realloc(sec
->data
, size
);
1334 error("memory full");
1335 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1337 sec
->data_allocated
= size
;
1340 /* reserve at least 'size' bytes in section 'sec' from
1341 sec->data_offset. */
1342 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1344 unsigned long offset
, offset1
;
1346 offset
= sec
->data_offset
;
1347 offset1
= offset
+ size
;
1348 if (offset1
> sec
->data_allocated
)
1349 section_realloc(sec
, offset1
);
1350 sec
->data_offset
= offset1
;
1351 return sec
->data
+ offset
;
1354 /* return a reference to a section, and create it if it does not
1356 Section
*find_section(TCCState
*s1
, const char *name
)
1360 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1361 sec
= s1
->sections
[i
];
1362 if (!strcmp(name
, sec
->name
))
1365 /* sections are created as PROGBITS */
1366 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1369 #define SECTION_ABS ((void *)1)
1371 /* update sym->c so that it points to an external symbol in section
1372 'section' with value 'value' */
1373 static void put_extern_sym2(Sym
*sym
, Section
*section
,
1374 unsigned long value
, unsigned long size
,
1375 int can_add_underscore
)
1377 int sym_type
, sym_bind
, sh_num
, info
, other
, attr
;
1382 if (section
== NULL
)
1384 else if (section
== SECTION_ABS
)
1387 sh_num
= section
->sh_num
;
1391 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
) {
1392 sym_type
= STT_FUNC
;
1393 #ifdef TCC_TARGET_PE
1395 attr
= sym
->type
.ref
->r
;
1396 if (FUNC_EXPORT(attr
))
1398 if (FUNC_CALL(attr
) == FUNC_STDCALL
)
1402 sym_type
= STT_OBJECT
;
1405 if (sym
->type
.t
& VT_STATIC
)
1406 sym_bind
= STB_LOCAL
;
1408 sym_bind
= STB_GLOBAL
;
1411 name
= get_tok_str(sym
->v
, NULL
);
1412 #ifdef CONFIG_TCC_BCHECK
1413 if (do_bounds_check
) {
1416 /* XXX: avoid doing that for statics ? */
1417 /* if bound checking is activated, we change some function
1418 names by adding the "__bound" prefix */
1421 /* XXX: we rely only on malloc hooks */
1434 strcpy(buf
, "__bound_");
1442 #ifdef TCC_TARGET_PE
1443 if ((other
& 2) && can_add_underscore
) {
1444 sprintf(buf1
, "_%s@%d", name
, FUNC_ARGS(attr
));
1448 if (tcc_state
->leading_underscore
&& can_add_underscore
) {
1450 pstrcpy(buf1
+ 1, sizeof(buf1
) - 1, name
);
1453 info
= ELFW(ST_INFO
)(sym_bind
, sym_type
);
1454 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, other
, sh_num
, name
);
1456 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
1457 esym
->st_value
= value
;
1458 esym
->st_size
= size
;
1459 esym
->st_shndx
= sh_num
;
1460 esym
->st_other
|= other
;
1464 static void put_extern_sym(Sym
*sym
, Section
*section
,
1465 unsigned long value
, unsigned long size
)
1467 put_extern_sym2(sym
, section
, value
, size
, 1);
1470 /* add a new relocation entry to symbol 'sym' in section 's' */
1471 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1474 put_extern_sym(sym
, NULL
, 0, 0);
1475 /* now we can add ELF relocation info */
1476 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1479 static inline int isid(int c
)
1481 return (c
>= 'a' && c
<= 'z') ||
1482 (c
>= 'A' && c
<= 'Z') ||
1486 static inline int isnum(int c
)
1488 return c
>= '0' && c
<= '9';
1491 static inline int isoct(int c
)
1493 return c
>= '0' && c
<= '7';
1496 static inline int toup(int c
)
1498 if (c
>= 'a' && c
<= 'z')
1499 return c
- 'a' + 'A';
1504 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1508 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1511 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1515 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1519 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1526 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1527 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1528 (*f
)->filename
, (*f
)->line_num
);
1529 if (file
->line_num
> 0) {
1530 strcat_printf(buf
, sizeof(buf
),
1531 "%s:%d: ", file
->filename
, file
->line_num
);
1533 strcat_printf(buf
, sizeof(buf
),
1534 "%s: ", file
->filename
);
1537 strcat_printf(buf
, sizeof(buf
),
1541 strcat_printf(buf
, sizeof(buf
), "warning: ");
1542 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1544 if (!s1
->error_func
) {
1545 /* default case: stderr */
1546 fprintf(stderr
, "%s\n", buf
);
1548 s1
->error_func(s1
->error_opaque
, buf
);
1550 if (!is_warning
|| s1
->warn_error
)
1555 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1556 void (*error_func
)(void *opaque
, const char *msg
))
1558 s
->error_opaque
= error_opaque
;
1559 s
->error_func
= error_func
;
1563 /* error without aborting current compilation */
1564 void error_noabort(const char *fmt
, ...)
1566 TCCState
*s1
= tcc_state
;
1570 error1(s1
, 0, fmt
, ap
);
1574 void error(const char *fmt
, ...)
1576 TCCState
*s1
= tcc_state
;
1580 error1(s1
, 0, fmt
, ap
);
1582 /* better than nothing: in some cases, we accept to handle errors */
1583 if (s1
->error_set_jmp_enabled
) {
1584 longjmp(s1
->error_jmp_buf
, 1);
1586 /* XXX: eliminate this someday */
1591 void expect(const char *msg
)
1593 error("%s expected", msg
);
1596 void warning(const char *fmt
, ...)
1598 TCCState
*s1
= tcc_state
;
1605 error1(s1
, 1, fmt
, ap
);
1612 error("'%c' expected", c
);
1616 static void test_lvalue(void)
1618 if (!(vtop
->r
& VT_LVAL
))
1622 /* allocate a new token */
1623 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1625 TokenSym
*ts
, **ptable
;
1628 if (tok_ident
>= SYM_FIRST_ANOM
)
1629 error("memory full");
1631 /* expand token table if needed */
1632 i
= tok_ident
- TOK_IDENT
;
1633 if ((i
% TOK_ALLOC_INCR
) == 0) {
1634 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1636 error("memory full");
1637 table_ident
= ptable
;
1640 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1641 table_ident
[i
] = ts
;
1642 ts
->tok
= tok_ident
++;
1643 ts
->sym_define
= NULL
;
1644 ts
->sym_label
= NULL
;
1645 ts
->sym_struct
= NULL
;
1646 ts
->sym_identifier
= NULL
;
1648 ts
->hash_next
= NULL
;
1649 memcpy(ts
->str
, str
, len
);
1650 ts
->str
[len
] = '\0';
1655 #define TOK_HASH_INIT 1
1656 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1658 /* find a token and add it if not found */
1659 static TokenSym
*tok_alloc(const char *str
, int len
)
1661 TokenSym
*ts
, **pts
;
1667 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1668 h
&= (TOK_HASH_SIZE
- 1);
1670 pts
= &hash_ident
[h
];
1675 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1677 pts
= &(ts
->hash_next
);
1679 return tok_alloc_new(pts
, str
, len
);
1682 /* CString handling */
1684 static void cstr_realloc(CString
*cstr
, int new_size
)
1689 size
= cstr
->size_allocated
;
1691 size
= 8; /* no need to allocate a too small first string */
1692 while (size
< new_size
)
1694 data
= tcc_realloc(cstr
->data_allocated
, size
);
1696 error("memory full");
1697 cstr
->data_allocated
= data
;
1698 cstr
->size_allocated
= size
;
1703 static inline void cstr_ccat(CString
*cstr
, int ch
)
1706 size
= cstr
->size
+ 1;
1707 if (size
> cstr
->size_allocated
)
1708 cstr_realloc(cstr
, size
);
1709 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1713 static void cstr_cat(CString
*cstr
, const char *str
)
1725 /* add a wide char */
1726 static void cstr_wccat(CString
*cstr
, int ch
)
1729 size
= cstr
->size
+ sizeof(nwchar_t
);
1730 if (size
> cstr
->size_allocated
)
1731 cstr_realloc(cstr
, size
);
1732 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
1736 static void cstr_new(CString
*cstr
)
1738 memset(cstr
, 0, sizeof(CString
));
1741 /* free string and reset it to NULL */
1742 static void cstr_free(CString
*cstr
)
1744 tcc_free(cstr
->data_allocated
);
1748 #define cstr_reset(cstr) cstr_free(cstr)
1750 /* XXX: unicode ? */
1751 static void add_char(CString
*cstr
, int c
)
1753 if (c
== '\'' || c
== '\"' || c
== '\\') {
1754 /* XXX: could be more precise if char or string */
1755 cstr_ccat(cstr
, '\\');
1757 if (c
>= 32 && c
<= 126) {
1760 cstr_ccat(cstr
, '\\');
1762 cstr_ccat(cstr
, 'n');
1764 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1765 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1766 cstr_ccat(cstr
, '0' + (c
& 7));
1771 /* XXX: buffer overflow */
1772 /* XXX: float tokens */
1773 char *get_tok_str(int v
, CValue
*cv
)
1775 static char buf
[STRING_MAX_SIZE
+ 1];
1776 static CString cstr_buf
;
1782 /* NOTE: to go faster, we give a fixed buffer for small strings */
1783 cstr_reset(&cstr_buf
);
1784 cstr_buf
.data
= buf
;
1785 cstr_buf
.size_allocated
= sizeof(buf
);
1791 /* XXX: not quite exact, but only useful for testing */
1792 sprintf(p
, "%u", cv
->ui
);
1796 /* XXX: not quite exact, but only useful for testing */
1797 sprintf(p
, "%Lu", cv
->ull
);
1800 cstr_ccat(&cstr_buf
, 'L');
1802 cstr_ccat(&cstr_buf
, '\'');
1803 add_char(&cstr_buf
, cv
->i
);
1804 cstr_ccat(&cstr_buf
, '\'');
1805 cstr_ccat(&cstr_buf
, '\0');
1809 len
= cstr
->size
- 1;
1811 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1812 cstr_ccat(&cstr_buf
, '\0');
1815 cstr_ccat(&cstr_buf
, 'L');
1818 cstr_ccat(&cstr_buf
, '\"');
1820 len
= cstr
->size
- 1;
1822 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1824 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
1826 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
1828 cstr_ccat(&cstr_buf
, '\"');
1829 cstr_ccat(&cstr_buf
, '\0');
1838 return strcpy(p
, "...");
1840 return strcpy(p
, "<<=");
1842 return strcpy(p
, ">>=");
1844 if (v
< TOK_IDENT
) {
1845 /* search in two bytes table */
1859 } else if (v
< tok_ident
) {
1860 return table_ident
[v
- TOK_IDENT
]->str
;
1861 } else if (v
>= SYM_FIRST_ANOM
) {
1862 /* special name for anonymous symbol */
1863 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1865 /* should never happen */
1870 return cstr_buf
.data
;
1873 /* push, without hashing */
1874 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, long c
)
1888 /* find a symbol and return its associated structure. 's' is the top
1889 of the symbol stack */
1890 static Sym
*sym_find2(Sym
*s
, int v
)
1900 /* structure lookup */
1901 static inline Sym
*struct_find(int v
)
1904 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1906 return table_ident
[v
]->sym_struct
;
1909 /* find an identifier */
1910 static inline Sym
*sym_find(int v
)
1913 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1915 return table_ident
[v
]->sym_identifier
;
1918 /* push a given symbol on the symbol stack */
1919 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1928 s
= sym_push2(ps
, v
, type
->t
, c
);
1929 s
->type
.ref
= type
->ref
;
1931 /* don't record fields or anonymous symbols */
1933 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1934 /* record symbol in token array */
1935 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1937 ps
= &ts
->sym_struct
;
1939 ps
= &ts
->sym_identifier
;
1946 /* push a global identifier */
1947 static Sym
*global_identifier_push(int v
, int t
, int c
)
1950 s
= sym_push2(&global_stack
, v
, t
, c
);
1951 /* don't record anonymous symbol */
1952 if (v
< SYM_FIRST_ANOM
) {
1953 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1954 /* modify the top most local identifier, so that
1955 sym_identifier will point to 's' when popped */
1957 ps
= &(*ps
)->prev_tok
;
1964 /* pop symbols until top reaches 'b' */
1965 static void sym_pop(Sym
**ptop
, Sym
*b
)
1975 /* remove symbol in token array */
1977 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1978 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1980 ps
= &ts
->sym_struct
;
1982 ps
= &ts
->sym_identifier
;
1993 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1998 if (strcmp(filename
, "-") == 0)
1999 fd
= 0, filename
= "stdin";
2001 fd
= open(filename
, O_RDONLY
| O_BINARY
);
2002 if ((verbose
== 2 && fd
>= 0) || verbose
== 3)
2003 printf("%s %*s%s\n", fd
< 0 ? "nf":"->",
2004 (s1
->include_stack_ptr
- s1
->include_stack
), "", filename
);
2007 bf
= tcc_malloc(sizeof(BufferedFile
));
2009 bf
->buf_ptr
= bf
->buffer
;
2010 bf
->buf_end
= bf
->buffer
;
2011 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
2012 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
2014 normalize_slashes(bf
->filename
);
2017 bf
->ifndef_macro
= 0;
2018 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
2019 // printf("opening '%s'\n", filename);
2023 void tcc_close(BufferedFile
*bf
)
2025 total_lines
+= bf
->line_num
;
2030 /* fill input buffer and peek next char */
2031 static int tcc_peekc_slow(BufferedFile
*bf
)
2034 /* only tries to read if really end of buffer */
2035 if (bf
->buf_ptr
>= bf
->buf_end
) {
2037 #if defined(PARSE_DEBUG)
2042 len
= read(bf
->fd
, bf
->buffer
, len
);
2049 bf
->buf_ptr
= bf
->buffer
;
2050 bf
->buf_end
= bf
->buffer
+ len
;
2051 *bf
->buf_end
= CH_EOB
;
2053 if (bf
->buf_ptr
< bf
->buf_end
) {
2054 return bf
->buf_ptr
[0];
2056 bf
->buf_ptr
= bf
->buf_end
;
2061 /* return the current character, handling end of block if necessary
2063 static int handle_eob(void)
2065 return tcc_peekc_slow(file
);
2068 /* read next char from current input file and handle end of input buffer */
2069 static inline void inp(void)
2071 ch
= *(++(file
->buf_ptr
));
2072 /* end of buffer/file handling */
2077 /* handle '\[\r]\n' */
2078 static int handle_stray_noerror(void)
2080 while (ch
== '\\') {
2085 } else if (ch
== '\r') {
2099 static void handle_stray(void)
2101 if (handle_stray_noerror())
2102 error("stray '\\' in program");
2105 /* skip the stray and handle the \\n case. Output an error if
2106 incorrect char after the stray */
2107 static int handle_stray1(uint8_t *p
)
2111 if (p
>= file
->buf_end
) {
2128 /* handle just the EOB case, but not stray */
2129 #define PEEKC_EOB(c, p)\
2140 /* handle the complicated stray case */
2141 #define PEEKC(c, p)\
2146 c = handle_stray1(p);\
2151 /* input with '\[\r]\n' handling. Note that this function cannot
2152 handle other characters after '\', so you cannot call it inside
2153 strings or comments */
2154 static void minp(void)
2162 /* single line C++ comments */
2163 static uint8_t *parse_line_comment(uint8_t *p
)
2171 if (c
== '\n' || c
== CH_EOF
) {
2173 } else if (c
== '\\') {
2182 } else if (c
== '\r') {
2200 static uint8_t *parse_comment(uint8_t *p
)
2206 /* fast skip loop */
2209 if (c
== '\n' || c
== '*' || c
== '\\')
2213 if (c
== '\n' || c
== '*' || c
== '\\')
2217 /* now we can handle all the cases */
2221 } else if (c
== '*') {
2227 } else if (c
== '/') {
2228 goto end_of_comment
;
2229 } else if (c
== '\\') {
2234 /* skip '\[\r]\n', otherwise just skip the stray */
2240 } else if (c
== '\r') {
2257 /* stray, eob or eof */
2262 error("unexpected end of file in comment");
2263 } else if (c
== '\\') {
2275 /* space exlcuding newline */
2276 static inline int is_space(int ch
)
2278 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
2281 static inline void skip_spaces(void)
2283 while (is_space(ch
))
2287 /* parse a string without interpreting escapes */
2288 static uint8_t *parse_pp_string(uint8_t *p
,
2289 int sep
, CString
*str
)
2297 } else if (c
== '\\') {
2302 unterminated_string
:
2303 /* XXX: indicate line number of start of string */
2304 error("missing terminating %c character", sep
);
2305 } else if (c
== '\\') {
2306 /* escape : just skip \[\r]\n */
2311 } else if (c
== '\r') {
2314 expect("'\n' after '\r'");
2317 } else if (c
== CH_EOF
) {
2318 goto unterminated_string
;
2321 cstr_ccat(str
, '\\');
2327 } else if (c
== '\n') {
2330 } else if (c
== '\r') {
2334 cstr_ccat(str
, '\r');
2350 /* skip block of text until #else, #elif or #endif. skip also pairs of
2352 void preprocess_skip(void)
2354 int a
, start_of_line
, c
, in_warn_or_error
;
2361 in_warn_or_error
= 0;
2382 } else if (c
== '\\') {
2383 ch
= file
->buf_ptr
[0];
2384 handle_stray_noerror();
2391 if (in_warn_or_error
)
2393 p
= parse_pp_string(p
, c
, NULL
);
2397 if (in_warn_or_error
)
2404 p
= parse_comment(p
);
2405 } else if (ch
== '/') {
2406 p
= parse_line_comment(p
);
2411 if (start_of_line
) {
2416 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2418 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2420 else if (tok
== TOK_ENDIF
)
2422 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
2423 in_warn_or_error
= 1;
2437 /* ParseState handling */
2439 /* XXX: currently, no include file info is stored. Thus, we cannot display
2440 accurate messages if the function or data definition spans multiple
2443 /* save current parse state in 's' */
2444 void save_parse_state(ParseState
*s
)
2446 s
->line_num
= file
->line_num
;
2447 s
->macro_ptr
= macro_ptr
;
2452 /* restore parse state from 's' */
2453 void restore_parse_state(ParseState
*s
)
2455 file
->line_num
= s
->line_num
;
2456 macro_ptr
= s
->macro_ptr
;
2461 /* return the number of additional 'ints' necessary to store the
2463 static inline int tok_ext_size(int t
)
2477 error("unsupported token");
2484 return LDOUBLE_SIZE
/ 4;
2490 /* token string handling */
2492 static inline void tok_str_new(TokenString
*s
)
2496 s
->allocated_len
= 0;
2497 s
->last_line_num
= -1;
2500 static void tok_str_free(int *str
)
2505 static int *tok_str_realloc(TokenString
*s
)
2509 if (s
->allocated_len
== 0) {
2512 len
= s
->allocated_len
* 2;
2514 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2516 error("memory full");
2517 s
->allocated_len
= len
;
2522 static void tok_str_add(TokenString
*s
, int t
)
2528 if (len
>= s
->allocated_len
)
2529 str
= tok_str_realloc(s
);
2534 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2541 /* allocate space for worst case */
2542 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2543 str
= tok_str_realloc(s
);
2552 str
[len
++] = cv
->tab
[0];
2561 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
2562 while ((len
+ nb_words
) > s
->allocated_len
)
2563 str
= tok_str_realloc(s
);
2564 cstr
= (CString
*)(str
+ len
);
2566 cstr
->size
= cv
->cstr
->size
;
2567 cstr
->data_allocated
= NULL
;
2568 cstr
->size_allocated
= cstr
->size
;
2569 memcpy((char *)cstr
+ sizeof(CString
),
2570 cv
->cstr
->data
, cstr
->size
);
2577 #if LDOUBLE_SIZE == 8
2580 str
[len
++] = cv
->tab
[0];
2581 str
[len
++] = cv
->tab
[1];
2583 #if LDOUBLE_SIZE == 12
2585 str
[len
++] = cv
->tab
[0];
2586 str
[len
++] = cv
->tab
[1];
2587 str
[len
++] = cv
->tab
[2];
2588 #elif LDOUBLE_SIZE == 16
2590 str
[len
++] = cv
->tab
[0];
2591 str
[len
++] = cv
->tab
[1];
2592 str
[len
++] = cv
->tab
[2];
2593 str
[len
++] = cv
->tab
[3];
2594 #elif LDOUBLE_SIZE != 8
2595 #error add long double size support
2604 /* add the current parse token in token string 's' */
2605 static void tok_str_add_tok(TokenString
*s
)
2609 /* save line number info */
2610 if (file
->line_num
!= s
->last_line_num
) {
2611 s
->last_line_num
= file
->line_num
;
2612 cval
.i
= s
->last_line_num
;
2613 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2615 tok_str_add2(s
, tok
, &tokc
);
2618 #if LDOUBLE_SIZE == 16
2619 #define LDOUBLE_GET(p, cv) \
2624 #elif LDOUBLE_SIZE == 12
2625 #define LDOUBLE_GET(p, cv) \
2629 #elif LDOUBLE_SIZE == 8
2630 #define LDOUBLE_GET(p, cv) \
2634 #error add long double size support
2638 /* get a token from an integer array and increment pointer
2639 accordingly. we code it as a macro to avoid pointer aliasing. */
2640 #define TOK_GET(t, p, cv) \
2655 cv.cstr = (CString *)p; \
2656 cv.cstr->data = (char *)p + sizeof(CString);\
2657 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
2666 case TOK_CLDOUBLE: \
2667 LDOUBLE_GET(p, cv); \
2668 p += LDOUBLE_SIZE / 4; \
2675 /* defines handling */
2676 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2680 s
= sym_push2(&define_stack
, v
, macro_type
, (long)str
);
2681 s
->next
= first_arg
;
2682 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2685 /* undefined a define symbol. Its name is just set to zero */
2686 static void define_undef(Sym
*s
)
2690 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2691 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2695 static inline Sym
*define_find(int v
)
2698 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2700 return table_ident
[v
]->sym_define
;
2703 /* free define stack until top reaches 'b' */
2704 static void free_defines(Sym
*b
)
2712 /* do not free args or predefined defines */
2714 tok_str_free((int *)top
->c
);
2716 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2717 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2725 static Sym
*label_find(int v
)
2728 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2730 return table_ident
[v
]->sym_label
;
2733 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2736 s
= sym_push2(ptop
, v
, 0, 0);
2738 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2739 if (ptop
== &global_label_stack
) {
2740 /* modify the top most local identifier, so that
2741 sym_identifier will point to 's' when popped */
2743 ps
= &(*ps
)->prev_tok
;
2750 /* pop labels until element last is reached. Look if any labels are
2751 undefined. Define symbols if '&&label' was used. */
2752 static void label_pop(Sym
**ptop
, Sym
*slast
)
2755 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2757 if (s
->r
== LABEL_DECLARED
) {
2758 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2759 } else if (s
->r
== LABEL_FORWARD
) {
2760 error("label '%s' used but not defined",
2761 get_tok_str(s
->v
, NULL
));
2764 /* define corresponding symbol. A size of
2766 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2770 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2776 /* eval an expression for #if/#elif */
2777 static int expr_preprocess(void)
2783 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2784 next(); /* do macro subst */
2785 if (tok
== TOK_DEFINED
) {
2790 c
= define_find(tok
) != 0;
2795 } else if (tok
>= TOK_IDENT
) {
2796 /* if undefined macro */
2800 tok_str_add_tok(&str
);
2802 tok_str_add(&str
, -1); /* simulate end of file */
2803 tok_str_add(&str
, 0);
2804 /* now evaluate C constant expression */
2805 macro_ptr
= str
.str
;
2809 tok_str_free(str
.str
);
2813 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2814 static void tok_print(int *str
)
2820 TOK_GET(t
, str
, cval
);
2823 printf(" %s", get_tok_str(t
, &cval
));
2829 /* parse after #define */
2830 static void parse_define(void)
2832 Sym
*s
, *first
, **ps
;
2833 int v
, t
, varg
, is_vaargs
, c
;
2838 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2839 /* XXX: should check if same macro (ANSI) */
2842 /* '(' must be just after macro definition for MACRO_FUNC */
2843 c
= file
->buf_ptr
[0];
2845 c
= handle_stray1(file
->buf_ptr
);
2850 while (tok
!= ')') {
2854 if (varg
== TOK_DOTS
) {
2855 varg
= TOK___VA_ARGS__
;
2857 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2861 if (varg
< TOK_IDENT
)
2862 error("badly punctuated parameter list");
2863 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2874 /* EOF testing necessary for '-D' handling */
2875 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2876 tok_str_add2(&str
, tok
, &tokc
);
2879 tok_str_add(&str
, 0);
2881 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2884 define_push(v
, t
, str
.str
, first
);
2887 static inline int hash_cached_include(int type
, const char *filename
)
2889 const unsigned char *s
;
2893 h
= TOK_HASH_FUNC(h
, type
);
2896 h
= TOK_HASH_FUNC(h
, *s
);
2899 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
2903 /* XXX: use a token or a hash table to accelerate matching ? */
2904 static CachedInclude
*search_cached_include(TCCState
*s1
,
2905 int type
, const char *filename
)
2909 h
= hash_cached_include(type
, filename
);
2910 i
= s1
->cached_includes_hash
[h
];
2914 e
= s1
->cached_includes
[i
- 1];
2915 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2922 static inline void add_cached_include(TCCState
*s1
, int type
,
2923 const char *filename
, int ifndef_macro
)
2928 if (search_cached_include(s1
, type
, filename
))
2931 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2933 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2937 strcpy(e
->filename
, filename
);
2938 e
->ifndef_macro
= ifndef_macro
;
2939 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2940 /* add in hash table */
2941 h
= hash_cached_include(type
, filename
);
2942 e
->hash_next
= s1
->cached_includes_hash
[h
];
2943 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
2946 static void pragma_parse(TCCState
*s1
)
2951 if (tok
== TOK_pack
) {
2954 #pragma pack(1) // set
2955 #pragma pack() // reset to default
2956 #pragma pack(push,1) // push & set
2957 #pragma pack(pop) // restore previous
2961 if (tok
== TOK_ASM_pop
) {
2963 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
2965 error("out of pack stack");
2967 s1
->pack_stack_ptr
--;
2971 if (tok
== TOK_ASM_push
) {
2973 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
2975 s1
->pack_stack_ptr
++;
2978 if (tok
!= TOK_CINT
) {
2980 error("invalid pack pragma");
2983 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
2987 *s1
->pack_stack_ptr
= val
;
2993 /* is_bof is true if first non space token at beginning of file */
2994 static void preprocess(int is_bof
)
2996 TCCState
*s1
= tcc_state
;
2997 int size
, i
, c
, n
, saved_parse_flags
;
3004 saved_parse_flags
= parse_flags
;
3005 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
3006 PARSE_FLAG_LINEFEED
;
3016 s
= define_find(tok
);
3017 /* undefine symbol by putting an invalid name */
3022 case TOK_INCLUDE_NEXT
:
3023 ch
= file
->buf_ptr
[0];
3024 /* XXX: incorrect if comments : use next_nomacro with a special mode */
3029 } else if (ch
== '\"') {
3034 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
3035 if ((q
- buf
) < sizeof(buf
) - 1)
3038 if (handle_stray_noerror() == 0)
3046 /* eat all spaces and comments after include */
3047 /* XXX: slightly incorrect */
3048 while (ch1
!= '\n' && ch1
!= CH_EOF
)
3052 /* computed #include : either we have only strings or
3053 we have anything enclosed in '<>' */
3056 if (tok
== TOK_STR
) {
3057 while (tok
!= TOK_LINEFEED
) {
3058 if (tok
!= TOK_STR
) {
3060 error("'#include' expects \"FILENAME\" or <FILENAME>");
3062 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
3068 while (tok
!= TOK_LINEFEED
) {
3069 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
3073 /* check syntax and remove '<>' */
3074 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
3075 goto include_syntax
;
3076 memmove(buf
, buf
+ 1, len
- 2);
3077 buf
[len
- 2] = '\0';
3082 e
= search_cached_include(s1
, c
, buf
);
3083 if (e
&& define_find(e
->ifndef_macro
)) {
3084 /* no need to parse the include because the 'ifndef macro'
3087 printf("%s: skipping %s\n", file
->filename
, buf
);
3090 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
3091 error("#include recursion too deep");
3092 /* push current file in stack */
3093 /* XXX: fix current line init */
3094 *s1
->include_stack_ptr
++ = file
;
3096 /* check absolute include path */
3097 if (IS_ABSPATH(buf
)) {
3098 f
= tcc_open(s1
, buf
);
3103 /* first search in current dir if "header.h" */
3104 size
= tcc_basename(file
->filename
) - file
->filename
;
3105 if (size
> sizeof(buf1
) - 1)
3106 size
= sizeof(buf1
) - 1;
3107 memcpy(buf1
, file
->filename
, size
);
3109 pstrcat(buf1
, sizeof(buf1
), buf
);
3110 f
= tcc_open(s1
, buf1
);
3112 if (tok
== TOK_INCLUDE_NEXT
)
3118 /* now search in all the include paths */
3119 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
3120 for(i
= 0; i
< n
; i
++) {
3122 if (i
< s1
->nb_include_paths
)
3123 path
= s1
->include_paths
[i
];
3125 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
3126 pstrcpy(buf1
, sizeof(buf1
), path
);
3127 pstrcat(buf1
, sizeof(buf1
), "/");
3128 pstrcat(buf1
, sizeof(buf1
), buf
);
3129 f
= tcc_open(s1
, buf1
);
3131 if (tok
== TOK_INCLUDE_NEXT
)
3137 --s1
->include_stack_ptr
;
3138 error("include file '%s' not found", buf
);
3142 printf("%s: including %s\n", file
->filename
, buf1
);
3145 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
3147 /* add include file debug info */
3149 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
3151 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
3152 ch
= file
->buf_ptr
[0];
3160 c
= expr_preprocess();
3166 if (tok
< TOK_IDENT
)
3167 error("invalid argument for '#if%sdef'", c
? "n" : "");
3171 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
3173 file
->ifndef_macro
= tok
;
3176 c
= (define_find(tok
) != 0) ^ c
;
3178 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
3179 error("memory full");
3180 *s1
->ifdef_stack_ptr
++ = c
;
3183 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
3184 error("#else without matching #if");
3185 if (s1
->ifdef_stack_ptr
[-1] & 2)
3186 error("#else after #else");
3187 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
3190 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
3191 error("#elif without matching #if");
3192 c
= s1
->ifdef_stack_ptr
[-1];
3194 error("#elif after #else");
3195 /* last #if/#elif expression was true: we skip */
3198 c
= expr_preprocess();
3199 s1
->ifdef_stack_ptr
[-1] = c
;
3209 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
3210 error("#endif without matching #if");
3211 s1
->ifdef_stack_ptr
--;
3212 /* '#ifndef macro' was at the start of file. Now we check if
3213 an '#endif' is exactly at the end of file */
3214 if (file
->ifndef_macro
&&
3215 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
3216 file
->ifndef_macro_saved
= file
->ifndef_macro
;
3217 /* need to set to zero to avoid false matches if another
3218 #ifndef at middle of file */
3219 file
->ifndef_macro
= 0;
3220 while (tok
!= TOK_LINEFEED
)
3222 tok_flags
|= TOK_FLAG_ENDIF
;
3228 if (tok
!= TOK_CINT
)
3230 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
3232 if (tok
!= TOK_LINEFEED
) {
3235 pstrcpy(file
->filename
, sizeof(file
->filename
),
3236 (char *)tokc
.cstr
->data
);
3242 ch
= file
->buf_ptr
[0];
3245 while (ch
!= '\n' && ch
!= CH_EOF
) {
3246 if ((q
- buf
) < sizeof(buf
) - 1)
3249 if (handle_stray_noerror() == 0)
3256 error("#error %s", buf
);
3258 warning("#warning %s", buf
);
3264 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
3265 /* '!' is ignored to allow C scripts. numbers are ignored
3266 to emulate cpp behaviour */
3268 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
3269 warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
3273 /* ignore other preprocess commands or #! for C scripts */
3274 while (tok
!= TOK_LINEFEED
)
3277 parse_flags
= saved_parse_flags
;
3280 /* evaluate escape codes in a string. */
3281 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
3296 case '0': case '1': case '2': case '3':
3297 case '4': case '5': case '6': case '7':
3298 /* at most three octal digits */
3303 n
= n
* 8 + c
- '0';
3307 n
= n
* 8 + c
- '0';
3312 goto add_char_nonext
;
3320 if (c
>= 'a' && c
<= 'f')
3322 else if (c
>= 'A' && c
<= 'F')
3332 goto add_char_nonext
;
3356 goto invalid_escape
;
3366 if (c
>= '!' && c
<= '~')
3367 warning("unknown escape sequence: \'\\%c\'", c
);
3369 warning("unknown escape sequence: \'\\x%x\'", c
);
3376 cstr_ccat(outstr
, c
);
3378 cstr_wccat(outstr
, c
);
3380 /* add a trailing '\0' */
3382 cstr_ccat(outstr
, '\0');
3384 cstr_wccat(outstr
, '\0');
3387 /* we use 64 bit numbers */
3390 /* bn = (bn << shift) | or_val */
3391 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
3395 for(i
=0;i
<BN_SIZE
;i
++) {
3397 bn
[i
] = (v
<< shift
) | or_val
;
3398 or_val
= v
>> (32 - shift
);
3402 void bn_zero(unsigned int *bn
)
3405 for(i
=0;i
<BN_SIZE
;i
++) {
3410 /* parse number in null terminated string 'p' and return it in the
3412 void parse_number(const char *p
)
3414 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
3416 unsigned int bn
[BN_SIZE
];
3427 goto float_frac_parse
;
3428 } else if (t
== '0') {
3429 if (ch
== 'x' || ch
== 'X') {
3433 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
3439 /* parse all digits. cannot check octal numbers at this stage
3440 because of floating point constants */
3442 if (ch
>= 'a' && ch
<= 'f')
3444 else if (ch
>= 'A' && ch
<= 'F')
3452 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
3454 error("number too long");
3460 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
3461 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
3463 /* NOTE: strtox should support that for hexa numbers, but
3464 non ISOC99 libcs do not support it, so we prefer to do
3466 /* hexadecimal or binary floats */
3467 /* XXX: handle overflows */
3479 } else if (t
>= 'a') {
3481 } else if (t
>= 'A') {
3486 bn_lshift(bn
, shift
, t
);
3493 if (t
>= 'a' && t
<= 'f') {
3495 } else if (t
>= 'A' && t
<= 'F') {
3497 } else if (t
>= '0' && t
<= '9') {
3503 error("invalid digit");
3504 bn_lshift(bn
, shift
, t
);
3509 if (ch
!= 'p' && ch
!= 'P')
3516 } else if (ch
== '-') {
3520 if (ch
< '0' || ch
> '9')
3521 expect("exponent digits");
3522 while (ch
>= '0' && ch
<= '9') {
3523 exp_val
= exp_val
* 10 + ch
- '0';
3526 exp_val
= exp_val
* s
;
3528 /* now we can generate the number */
3529 /* XXX: should patch directly float number */
3530 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3531 d
= ldexp(d
, exp_val
- frac_bits
);
3536 /* float : should handle overflow */
3538 } else if (t
== 'L') {
3541 /* XXX: not large enough */
3542 tokc
.ld
= (long double)d
;
3548 /* decimal floats */
3550 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3555 while (ch
>= '0' && ch
<= '9') {
3556 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3562 if (ch
== 'e' || ch
== 'E') {
3563 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3567 if (ch
== '-' || ch
== '+') {
3568 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3573 if (ch
< '0' || ch
> '9')
3574 expect("exponent digits");
3575 while (ch
>= '0' && ch
<= '9') {
3576 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3588 tokc
.f
= strtof(token_buf
, NULL
);
3589 } else if (t
== 'L') {
3592 tokc
.ld
= strtold(token_buf
, NULL
);
3595 tokc
.d
= strtod(token_buf
, NULL
);
3599 unsigned long long n
, n1
;
3602 /* integer number */
3605 if (b
== 10 && *q
== '0') {
3612 /* no need for checks except for base 10 / 8 errors */
3615 } else if (t
>= 'a') {
3617 } else if (t
>= 'A') {
3622 error("invalid digit");
3626 /* detect overflow */
3627 /* XXX: this test is not reliable */
3629 error("integer constant overflow");
3632 /* XXX: not exactly ANSI compliant */
3633 if ((n
& 0xffffffff00000000LL
) != 0) {
3638 } else if (n
> 0x7fffffff) {
3649 error("three 'l's in integer constant");
3652 if (tok
== TOK_CINT
)
3654 else if (tok
== TOK_CUINT
)
3658 } else if (t
== 'U') {
3660 error("two 'u's in integer constant");
3662 if (tok
== TOK_CINT
)
3664 else if (tok
== TOK_CLLONG
)
3671 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3677 error("invalid number\n");
3681 #define PARSE2(c1, tok1, c2, tok2) \
3692 /* return next token without macro substitution */
3693 static inline void next_nomacro1(void)
3700 cstr_reset(&tok_spaces
);
3710 cstr_ccat(&tok_spaces
, c
);
3715 /* first look if it is in fact an end of buffer */
3716 if (p
>= file
->buf_end
) {
3720 if (p
>= file
->buf_end
)
3733 TCCState
*s1
= tcc_state
;
3734 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
3735 && !(tok_flags
& TOK_FLAG_EOF
)) {
3736 tok_flags
|= TOK_FLAG_EOF
;
3738 goto keep_tok_flags
;
3739 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3740 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3741 /* no include left : end of file. */
3744 tok_flags
&= ~TOK_FLAG_EOF
;
3745 /* pop include file */
3747 /* test if previous '#endif' was after a #ifdef at
3749 if (tok_flags
& TOK_FLAG_ENDIF
) {
3751 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3753 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3754 file
->ifndef_macro_saved
);
3757 /* add end of include file debug info */
3759 put_stabd(N_EINCL
, 0, 0);
3761 /* pop include stack */
3763 s1
->include_stack_ptr
--;
3764 file
= *s1
->include_stack_ptr
;
3773 tok_flags
|= TOK_FLAG_BOL
;
3775 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
3778 goto keep_tok_flags
;
3783 if ((tok_flags
& TOK_FLAG_BOL
) &&
3784 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3786 preprocess(tok_flags
& TOK_FLAG_BOF
);
3792 tok
= TOK_TWOSHARPS
;
3794 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
3795 p
= parse_line_comment(p
- 1);
3804 case 'a': case 'b': case 'c': case 'd':
3805 case 'e': case 'f': case 'g': case 'h':
3806 case 'i': case 'j': case 'k': case 'l':
3807 case 'm': case 'n': case 'o': case 'p':
3808 case 'q': case 'r': case 's': case 't':
3809 case 'u': case 'v': case 'w': case 'x':
3811 case 'A': case 'B': case 'C': case 'D':
3812 case 'E': case 'F': case 'G': case 'H':
3813 case 'I': case 'J': case 'K':
3814 case 'M': case 'N': case 'O': case 'P':
3815 case 'Q': case 'R': case 'S': case 'T':
3816 case 'U': case 'V': case 'W': case 'X':
3822 h
= TOK_HASH_FUNC(h
, c
);
3826 if (!isidnum_table
[c
-CH_EOF
])
3828 h
= TOK_HASH_FUNC(h
, c
);
3835 /* fast case : no stray found, so we have the full token
3836 and we have already hashed it */
3838 h
&= (TOK_HASH_SIZE
- 1);
3839 pts
= &hash_ident
[h
];
3844 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3846 pts
= &(ts
->hash_next
);
3848 ts
= tok_alloc_new(pts
, p1
, len
);
3852 cstr_reset(&tokcstr
);
3855 cstr_ccat(&tokcstr
, *p1
);
3861 while (isidnum_table
[c
-CH_EOF
]) {
3862 cstr_ccat(&tokcstr
, c
);
3865 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3871 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3873 goto parse_ident_fast
;
3876 if (c
== '\'' || c
== '\"') {
3880 cstr_reset(&tokcstr
);
3881 cstr_ccat(&tokcstr
, 'L');
3882 goto parse_ident_slow
;
3886 case '0': case '1': case '2': case '3':
3887 case '4': case '5': case '6': case '7':
3890 cstr_reset(&tokcstr
);
3891 /* after the first digit, accept digits, alpha, '.' or sign if
3892 prefixed by 'eEpP' */
3896 cstr_ccat(&tokcstr
, c
);
3898 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3899 ((c
== '+' || c
== '-') &&
3900 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3903 /* We add a trailing '\0' to ease parsing */
3904 cstr_ccat(&tokcstr
, '\0');
3905 tokc
.cstr
= &tokcstr
;
3909 /* special dot handling because it can also start a number */
3912 cstr_reset(&tokcstr
);
3913 cstr_ccat(&tokcstr
, '.');
3915 } else if (c
== '.') {
3935 /* parse the string */
3937 p
= parse_pp_string(p
, sep
, &str
);
3938 cstr_ccat(&str
, '\0');
3940 /* eval the escape (should be done as TOK_PPNUM) */
3941 cstr_reset(&tokcstr
);
3942 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3947 /* XXX: make it portable */
3951 char_size
= sizeof(nwchar_t
);
3952 if (tokcstr
.size
<= char_size
)
3953 error("empty character constant");
3954 if (tokcstr
.size
> 2 * char_size
)
3955 warning("multi-character character constant");
3957 tokc
.i
= *(int8_t *)tokcstr
.data
;
3960 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
3964 tokc
.cstr
= &tokcstr
;
3978 } else if (c
== '<') {
3996 } else if (c
== '>') {
4014 } else if (c
== '=') {
4027 } else if (c
== '=') {
4040 } else if (c
== '=') {
4053 } else if (c
== '=') {
4056 } else if (c
== '>') {
4064 PARSE2('!', '!', '=', TOK_NE
)
4065 PARSE2('=', '=', '=', TOK_EQ
)
4066 PARSE2('*', '*', '=', TOK_A_MUL
)
4067 PARSE2('%', '%', '=', TOK_A_MOD
)
4068 PARSE2('^', '^', '=', TOK_A_XOR
)
4070 /* comments or operator */
4074 p
= parse_comment(p
);
4076 } else if (c
== '/') {
4077 p
= parse_line_comment(p
);
4079 } else if (c
== '=') {
4099 case '$': /* only used in assembler */
4100 case '@': /* dito */
4105 error("unrecognized character \\x%02x", c
);
4111 #if defined(PARSE_DEBUG)
4112 printf("token = %s\n", get_tok_str(tok
, &tokc
));
4116 /* return next token without macro substitution. Can read input from
4118 static void next_nomacro(void)
4124 TOK_GET(tok
, macro_ptr
, tokc
);
4125 if (tok
== TOK_LINENUM
) {
4126 file
->line_num
= tokc
.i
;
4135 /* substitute args in macro_str and return allocated string */
4136 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
4138 int *st
, last_tok
, t
, notfirst
;
4147 TOK_GET(t
, macro_str
, cval
);
4152 TOK_GET(t
, macro_str
, cval
);
4155 s
= sym_find2(args
, t
);
4162 cstr_ccat(&cstr
, ' ');
4163 TOK_GET(t
, st
, cval
);
4164 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
4169 cstr_ccat(&cstr
, '\0');
4171 printf("stringize: %s\n", (char *)cstr
.data
);
4175 tok_str_add2(&str
, TOK_STR
, &cval
);
4178 tok_str_add2(&str
, t
, &cval
);
4180 } else if (t
>= TOK_IDENT
) {
4181 s
= sym_find2(args
, t
);
4184 /* if '##' is present before or after, no arg substitution */
4185 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
4186 /* special case for var arg macros : ## eats the
4187 ',' if empty VA_ARGS variable. */
4188 /* XXX: test of the ',' is not 100%
4189 reliable. should fix it to avoid security
4191 if (gnu_ext
&& s
->type
.t
&&
4192 last_tok
== TOK_TWOSHARPS
&&
4193 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
4195 /* suppress ',' '##' */
4198 /* suppress '##' and add variable */
4206 TOK_GET(t1
, st
, cval
);
4209 tok_str_add2(&str
, t1
, &cval
);
4213 /* NOTE: the stream cannot be read when macro
4214 substituing an argument */
4215 macro_subst(&str
, nested_list
, st
, NULL
);
4218 tok_str_add(&str
, t
);
4221 tok_str_add2(&str
, t
, &cval
);
4225 tok_str_add(&str
, 0);
4229 static char const ab_month_name
[12][4] =
4231 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
4232 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
4235 /* do macro substitution of current token with macro 's' and add
4236 result to (tok_str,tok_len). 'nested_list' is the list of all
4237 macros we got inside to avoid recursing. Return non zero if no
4238 substitution needs to be done */
4239 static int macro_subst_tok(TokenString
*tok_str
,
4240 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
4242 Sym
*args
, *sa
, *sa1
;
4243 int mstr_allocated
, parlevel
, *mstr
, t
, t1
;
4250 /* if symbol is a macro, prepare substitution */
4251 /* special macros */
4252 if (tok
== TOK___LINE__
) {
4253 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
4257 } else if (tok
== TOK___FILE__
) {
4258 cstrval
= file
->filename
;
4260 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
4265 tm
= localtime(&ti
);
4266 if (tok
== TOK___DATE__
) {
4267 snprintf(buf
, sizeof(buf
), "%s %2d %d",
4268 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
4270 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
4271 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
4278 cstr_cat(&cstr
, cstrval
);
4279 cstr_ccat(&cstr
, '\0');
4281 tok_str_add2(tok_str
, t1
, &cval
);
4286 if (s
->type
.t
== MACRO_FUNC
) {
4287 /* NOTE: we do not use next_nomacro to avoid eating the
4288 next token. XXX: find better solution */
4292 if (t
== 0 && can_read_stream
) {
4293 /* end of macro stream: we must look at the token
4294 after in the file */
4295 struct macro_level
*ml
= *can_read_stream
;
4301 *can_read_stream
= ml
-> prev
;
4306 /* XXX: incorrect with comments */
4307 ch
= file
->buf_ptr
[0];
4308 while (is_space(ch
) || ch
== '\n')
4312 if (t
!= '(') /* no macro subst */
4315 /* argument macro */
4320 /* NOTE: empty args are allowed, except if no args */
4322 /* handle '()' case */
4323 if (!args
&& !sa
&& tok
== ')')
4326 error("macro '%s' used with too many args",
4327 get_tok_str(s
->v
, 0));
4330 /* NOTE: non zero sa->t indicates VA_ARGS */
4331 while ((parlevel
> 0 ||
4333 (tok
!= ',' || sa
->type
.t
))) &&
4337 else if (tok
== ')')
4339 if (tok
!= TOK_LINEFEED
)
4340 tok_str_add2(&str
, tok
, &tokc
);
4343 tok_str_add(&str
, 0);
4344 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (long)str
.str
);
4347 /* special case for gcc var args: add an empty
4348 var arg argument if it is omitted */
4349 if (sa
&& sa
->type
.t
&& gnu_ext
)
4359 error("macro '%s' used with too few args",
4360 get_tok_str(s
->v
, 0));
4363 /* now subst each arg */
4364 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
4369 tok_str_free((int *)sa
->c
);
4375 sym_push2(nested_list
, s
->v
, 0, 0);
4376 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
4377 /* pop nested defined symbol */
4379 *nested_list
= sa1
->prev
;
4387 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4388 return the resulting string (which must be freed). */
4389 static inline int *macro_twosharps(const int *macro_str
)
4392 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
4394 const char *p1
, *p2
;
4396 TokenString macro_str1
;
4399 start_macro_ptr
= macro_str
;
4400 /* we search the first '##' */
4402 macro_ptr1
= macro_str
;
4403 TOK_GET(t
, macro_str
, cval
);
4404 /* nothing more to do if end of string */
4407 if (*macro_str
== TOK_TWOSHARPS
)
4411 /* we saw '##', so we need more processing to handle it */
4413 tok_str_new(¯o_str1
);
4417 /* add all tokens seen so far */
4418 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
4419 TOK_GET(t
, ptr
, cval
);
4420 tok_str_add2(¯o_str1
, t
, &cval
);
4422 saved_macro_ptr
= macro_ptr
;
4423 /* XXX: get rid of the use of macro_ptr here */
4424 macro_ptr
= (int *)macro_str
;
4426 while (*macro_ptr
== TOK_TWOSHARPS
) {
4428 macro_ptr1
= macro_ptr
;
4431 TOK_GET(t
, macro_ptr
, cval
);
4432 /* We concatenate the two tokens if we have an
4433 identifier or a preprocessing number */
4435 p1
= get_tok_str(tok
, &tokc
);
4436 cstr_cat(&cstr
, p1
);
4437 p2
= get_tok_str(t
, &cval
);
4438 cstr_cat(&cstr
, p2
);
4439 cstr_ccat(&cstr
, '\0');
4441 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
4442 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
4443 if (tok
== TOK_PPNUM
) {
4444 /* if number, then create a number token */
4445 /* NOTE: no need to allocate because
4446 tok_str_add2() does it */
4447 cstr_reset(&tokcstr
);
4450 tokc
.cstr
= &tokcstr
;
4452 /* if identifier, we must do a test to
4453 validate we have a correct identifier */
4454 if (t
== TOK_PPNUM
) {
4464 if (!isnum(c
) && !isid(c
))
4468 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
4469 tok
= ts
->tok
; /* modify current token */
4472 const char *str
= cstr
.data
;
4473 const unsigned char *q
;
4475 /* we look for a valid token */
4476 /* XXX: do more extensive checks */
4477 if (!strcmp(str
, ">>=")) {
4479 } else if (!strcmp(str
, "<<=")) {
4481 } else if (strlen(str
) == 2) {
4482 /* search in two bytes table */
4487 if (q
[0] == str
[0] && q
[1] == str
[1])
4494 /* NOTE: because get_tok_str use a static buffer,
4497 p1
= get_tok_str(tok
, &tokc
);
4498 cstr_cat(&cstr
, p1
);
4499 cstr_ccat(&cstr
, '\0');
4500 p2
= get_tok_str(t
, &cval
);
4501 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
4502 /* cannot merge tokens: just add them separately */
4503 tok_str_add2(¯o_str1
, tok
, &tokc
);
4504 /* XXX: free associated memory ? */
4511 tok_str_add2(¯o_str1
, tok
, &tokc
);
4516 macro_ptr
= (int *)saved_macro_ptr
;
4518 tok_str_add(¯o_str1
, 0);
4519 return macro_str1
.str
;
4523 /* do macro substitution of macro_str and add result to
4524 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4525 inside to avoid recursing. */
4526 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
4527 const int *macro_str
, struct macro_level
** can_read_stream
)
4534 struct macro_level ml
;
4536 /* first scan for '##' operator handling */
4538 macro_str1
= macro_twosharps(ptr
);
4542 /* NOTE: ptr == NULL can only happen if tokens are read from
4543 file stream due to a macro function call */
4546 TOK_GET(t
, ptr
, cval
);
4551 /* if nested substitution, do nothing */
4552 if (sym_find2(*nested_list
, t
))
4555 if (can_read_stream
)
4556 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
4557 macro_ptr
= (int *)ptr
;
4559 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
4560 ptr
= (int *)macro_ptr
;
4562 if (can_read_stream
&& *can_read_stream
== &ml
)
4563 *can_read_stream
= ml
.prev
;
4568 tok_str_add2(tok_str
, t
, &cval
);
4572 tok_str_free(macro_str1
);
4575 /* return next token with macro substitution */
4576 static void next(void)
4578 Sym
*nested_list
, *s
;
4580 struct macro_level
*ml
;
4585 /* if not reading from macro substituted string, then try
4586 to substitute macros */
4587 if (tok
>= TOK_IDENT
&&
4588 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4589 s
= define_find(tok
);
4591 /* we have a macro: we try to substitute */
4595 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
4596 /* substitution done, NOTE: maybe empty */
4597 tok_str_add(&str
, 0);
4598 macro_ptr
= str
.str
;
4599 macro_ptr_allocated
= str
.str
;
4606 /* end of macro or end of unget buffer */
4607 if (unget_buffer_enabled
) {
4608 macro_ptr
= unget_saved_macro_ptr
;
4609 unget_buffer_enabled
= 0;
4611 /* end of macro string: free it */
4612 tok_str_free(macro_ptr_allocated
);
4619 /* convert preprocessor tokens into C tokens */
4620 if (tok
== TOK_PPNUM
&&
4621 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4622 parse_number((char *)tokc
.cstr
->data
);
4626 /* push back current token and set current token to 'last_tok'. Only
4627 identifier case handled for labels. */
4628 static inline void unget_tok(int last_tok
)
4632 unget_saved_macro_ptr
= macro_ptr
;
4633 unget_buffer_enabled
= 1;
4634 q
= unget_saved_buffer
;
4637 n
= tok_ext_size(tok
) - 1;
4640 *q
= 0; /* end of token string */
4645 void swap(int *p
, int *q
)
4653 void vsetc(CType
*type
, int r
, CValue
*vc
)
4657 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4658 error("memory full");
4659 /* cannot let cpu flags if other instruction are generated. Also
4660 avoid leaving VT_JMP anywhere except on the top of the stack
4661 because it would complicate the code generator. */
4662 if (vtop
>= vstack
) {
4663 v
= vtop
->r
& VT_VALMASK
;
4664 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4670 vtop
->r2
= VT_CONST
;
4674 /* push integer constant */
4679 vsetc(&int_type
, VT_CONST
, &cval
);
4682 /* push long long constant */
4683 void vpushll(long long v
)
4689 vsetc(&ctype
, VT_CONST
, &cval
);
4692 /* Return a static symbol pointing to a section */
4693 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4694 unsigned long offset
, unsigned long size
)
4700 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4701 sym
->type
.ref
= type
->ref
;
4702 sym
->r
= VT_CONST
| VT_SYM
;
4703 put_extern_sym(sym
, sec
, offset
, size
);
4707 /* push a reference to a section offset by adding a dummy symbol */
4708 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4713 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4714 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4717 /* define a new external reference to a symbol 'v' of type 'u' */
4718 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4724 /* push forward reference */
4725 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4726 s
->type
.ref
= type
->ref
;
4727 s
->r
= r
| VT_CONST
| VT_SYM
;
4732 /* define a new external reference to a symbol 'v' of type 'u' */
4733 static Sym
*external_sym(int v
, CType
*type
, int r
)
4739 /* push forward reference */
4740 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4741 s
->type
.t
|= VT_EXTERN
;
4743 if (!is_compatible_types(&s
->type
, type
))
4744 error("incompatible types for redefinition of '%s'",
4745 get_tok_str(v
, NULL
));
4750 /* push a reference to global symbol v */
4751 static void vpush_global_sym(CType
*type
, int v
)
4756 sym
= external_global_sym(v
, type
, 0);
4758 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4762 void vset(CType
*type
, int r
, int v
)
4767 vsetc(type
, r
, &cval
);
4770 void vseti(int r
, int v
)
4786 void vpushv(SValue
*v
)
4788 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4789 error("memory full");
4799 /* save r to the memory stack, and mark it as being free */
4800 void save_reg(int r
)
4802 int l
, saved
, size
, align
;
4806 /* modify all stack values */
4809 for(p
=vstack
;p
<=vtop
;p
++) {
4810 if ((p
->r
& VT_VALMASK
) == r
||
4811 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& (p
->r2
& VT_VALMASK
) == r
)) {
4812 /* must save value on stack if not already done */
4814 /* NOTE: must reload 'r' because r might be equal to r2 */
4815 r
= p
->r
& VT_VALMASK
;
4816 /* store register in the stack */
4818 if ((p
->r
& VT_LVAL
) ||
4819 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4820 #ifdef TCC_TARGET_X86_64
4821 type
= &char_pointer_type
;
4825 size
= type_size(type
, &align
);
4826 loc
= (loc
- size
) & -align
;
4827 sv
.type
.t
= type
->t
;
4828 sv
.r
= VT_LOCAL
| VT_LVAL
;
4831 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
4832 /* x86 specific: need to pop fp register ST0 if saved */
4833 if (r
== TREG_ST0
) {
4834 o(0xd9dd); /* fstp %st(1) */
4837 #ifndef TCC_TARGET_X86_64
4838 /* special long long case */
4839 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4847 /* mark that stack entry as being saved on the stack */
4848 if (p
->r
& VT_LVAL
) {
4849 /* also clear the bounded flag because the
4850 relocation address of the function was stored in
4852 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4854 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4862 /* find a register of class 'rc2' with at most one reference on stack.
4863 * If none, call get_reg(rc) */
4864 int get_reg_ex(int rc
, int rc2
)
4869 for(r
=0;r
<NB_REGS
;r
++) {
4870 if (reg_classes
[r
] & rc2
) {
4873 for(p
= vstack
; p
<= vtop
; p
++) {
4874 if ((p
->r
& VT_VALMASK
) == r
||
4875 (p
->r2
& VT_VALMASK
) == r
)
4885 /* find a free register of class 'rc'. If none, save one register */
4891 /* find a free register */
4892 for(r
=0;r
<NB_REGS
;r
++) {
4893 if (reg_classes
[r
] & rc
) {
4894 for(p
=vstack
;p
<=vtop
;p
++) {
4895 if ((p
->r
& VT_VALMASK
) == r
||
4896 (p
->r2
& VT_VALMASK
) == r
)
4904 /* no register left : free the first one on the stack (VERY
4905 IMPORTANT to start from the bottom to ensure that we don't
4906 spill registers used in gen_opi()) */
4907 for(p
=vstack
;p
<=vtop
;p
++) {
4908 r
= p
->r
& VT_VALMASK
;
4909 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4911 /* also look at second register (if long long) */
4912 r
= p
->r2
& VT_VALMASK
;
4913 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4919 /* Should never comes here */
4923 /* save registers up to (vtop - n) stack entry */
4924 void save_regs(int n
)
4929 for(p
= vstack
;p
<= p1
; p
++) {
4930 r
= p
->r
& VT_VALMASK
;
4937 /* move register 's' to 'r', and flush previous value of r to memory
4939 void move_reg(int r
, int s
)
4952 /* get address of vtop (vtop MUST BE an lvalue) */
4955 vtop
->r
&= ~VT_LVAL
;
4956 /* tricky: if saved lvalue, then we can go back to lvalue */
4957 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4958 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4961 #ifdef CONFIG_TCC_BCHECK
4962 /* generate lvalue bound code */
4968 vtop
->r
&= ~VT_MUSTBOUND
;
4969 /* if lvalue, then use checking code before dereferencing */
4970 if (vtop
->r
& VT_LVAL
) {
4971 /* if not VT_BOUNDED value, then make one */
4972 if (!(vtop
->r
& VT_BOUNDED
)) {
4973 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4974 /* must save type because we must set it to int to get pointer */
4976 vtop
->type
.t
= VT_INT
;
4979 gen_bounded_ptr_add();
4980 vtop
->r
|= lval_type
;
4983 /* then check for dereferencing */
4984 gen_bounded_ptr_deref();
4989 /* store vtop a register belonging to class 'rc'. lvalues are
4990 converted to values. Cannot be used if cannot be converted to
4991 register value (such as structures). */
4994 int r
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4996 /* NOTE: get_reg can modify vstack[] */
4997 if (vtop
->type
.t
& VT_BITFIELD
) {
5000 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
5001 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
5002 /* remove bit field info to avoid loops */
5003 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
5004 /* cast to int to propagate signedness in following ops */
5005 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
5010 if((vtop
->type
.t
& VT_UNSIGNED
) ||
5011 (vtop
->type
.t
& VT_BTYPE
) == VT_BOOL
)
5012 type
.t
|= VT_UNSIGNED
;
5014 /* generate shifts */
5015 vpushi(bits
- (bit_pos
+ bit_size
));
5017 vpushi(bits
- bit_size
);
5018 /* NOTE: transformed to SHR if unsigned */
5022 if (is_float(vtop
->type
.t
) &&
5023 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
5026 unsigned long offset
;
5027 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5031 /* XXX: unify with initializers handling ? */
5032 /* CPUs usually cannot use float constants, so we store them
5033 generically in data segment */
5034 size
= type_size(&vtop
->type
, &align
);
5035 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
5036 data_section
->data_offset
= offset
;
5037 /* XXX: not portable yet */
5038 #if defined(__i386__) || defined(__x86_64__)
5039 /* Zero pad x87 tenbyte long doubles */
5040 if (size
== LDOUBLE_SIZE
)
5041 vtop
->c
.tab
[2] &= 0xffff;
5043 ptr
= section_ptr_add(data_section
, size
);
5045 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5049 ptr
[i
] = vtop
->c
.tab
[size
-1-i
];
5053 ptr
[i
] = vtop
->c
.tab
[i
];
5054 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
5055 vtop
->r
|= VT_LVAL
| VT_SYM
;
5059 #ifdef CONFIG_TCC_BCHECK
5060 if (vtop
->r
& VT_MUSTBOUND
)
5064 r
= vtop
->r
& VT_VALMASK
;
5068 /* need to reload if:
5070 - lvalue (need to dereference pointer)
5071 - already a register, but not in the right class */
5072 if (r
>= VT_CONST
||
5073 (vtop
->r
& VT_LVAL
) ||
5074 !(reg_classes
[r
] & rc
) ||
5075 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
5076 !(reg_classes
[vtop
->r2
] & rc2
))) {
5078 #ifndef TCC_TARGET_X86_64
5079 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
5081 unsigned long long ll
;
5082 /* two register type load : expand to two words
5084 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
5087 vtop
->c
.ui
= ll
; /* first word */
5089 vtop
->r
= r
; /* save register value */
5090 vpushi(ll
>> 32); /* second word */
5091 } else if (r
>= VT_CONST
|| /* XXX: test to VT_CONST incorrect ? */
5092 (vtop
->r
& VT_LVAL
)) {
5093 /* We do not want to modifier the long long
5094 pointer here, so the safest (and less
5095 efficient) is to save all the other registers
5096 in the stack. XXX: totally inefficient. */
5098 /* load from memory */
5101 vtop
[-1].r
= r
; /* save register value */
5102 /* increment pointer to get second word */
5103 vtop
->type
.t
= VT_INT
;
5109 /* move registers */
5112 vtop
[-1].r
= r
; /* save register value */
5113 vtop
->r
= vtop
[-1].r2
;
5115 /* allocate second register */
5119 /* write second register */
5123 if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
5125 /* lvalue of scalar type : need to use lvalue type
5126 because of possible cast */
5129 /* compute memory access type */
5130 if (vtop
->r
& VT_LVAL_BYTE
)
5132 else if (vtop
->r
& VT_LVAL_SHORT
)
5134 if (vtop
->r
& VT_LVAL_UNSIGNED
)
5138 /* restore wanted type */
5141 /* one register type load */
5146 #ifdef TCC_TARGET_C67
5147 /* uses register pairs for doubles */
5148 if ((vtop
->type
.t
& VT_BTYPE
) == VT_DOUBLE
)
5155 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
5156 void gv2(int rc1
, int rc2
)
5160 /* generate more generic register first. But VT_JMP or VT_CMP
5161 values must be generated first in all cases to avoid possible
5163 v
= vtop
[0].r
& VT_VALMASK
;
5164 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
5169 /* test if reload is needed for first register */
5170 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
5180 /* test if reload is needed for first register */
5181 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
5187 /* expand long long on stack in two int registers */
5192 u
= vtop
->type
.t
& VT_UNSIGNED
;
5195 vtop
[0].r
= vtop
[-1].r2
;
5196 vtop
[0].r2
= VT_CONST
;
5197 vtop
[-1].r2
= VT_CONST
;
5198 vtop
[0].type
.t
= VT_INT
| u
;
5199 vtop
[-1].type
.t
= VT_INT
| u
;
5202 #ifdef TCC_TARGET_ARM
5203 /* expand long long on stack */
5204 void lexpand_nr(void)
5208 u
= vtop
->type
.t
& VT_UNSIGNED
;
5210 vtop
->r2
= VT_CONST
;
5211 vtop
->type
.t
= VT_INT
| u
;
5212 v
=vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
);
5213 if (v
== VT_CONST
) {
5214 vtop
[-1].c
.ui
= vtop
->c
.ull
;
5215 vtop
->c
.ui
= vtop
->c
.ull
>> 32;
5217 } else if (v
== (VT_LVAL
|VT_CONST
) || v
== (VT_LVAL
|VT_LOCAL
)) {
5219 vtop
->r
= vtop
[-1].r
;
5220 } else if (v
> VT_CONST
) {
5224 vtop
->r
= vtop
[-1].r2
;
5225 vtop
[-1].r2
= VT_CONST
;
5226 vtop
[-1].type
.t
= VT_INT
| u
;
5230 /* build a long long from two ints */
5233 gv2(RC_INT
, RC_INT
);
5234 vtop
[-1].r2
= vtop
[0].r
;
5235 vtop
[-1].type
.t
= t
;
5239 /* rotate n first stack elements to the bottom
5240 I1 ... In -> I2 ... In I1 [top is right]
5248 for(i
=-n
+1;i
!=0;i
++)
5249 vtop
[i
] = vtop
[i
+1];
5253 /* rotate n first stack elements to the top
5254 I1 ... In -> In I1 ... I(n-1) [top is right]
5262 for(i
= 0;i
< n
- 1; i
++)
5263 vtop
[-i
] = vtop
[-i
- 1];
5267 #ifdef TCC_TARGET_ARM
5268 /* like vrott but in other direction
5269 In ... I1 -> I(n-1) ... I1 In [top is right]
5277 for(i
= n
- 1; i
> 0; i
--)
5278 vtop
[-i
] = vtop
[-i
+ 1];
5283 /* pop stack value */
5287 v
= vtop
->r
& VT_VALMASK
;
5288 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
5289 /* for x86, we need to pop the FP stack */
5290 if (v
== TREG_ST0
&& !nocode_wanted
) {
5291 o(0xd9dd); /* fstp %st(1) */
5294 if (v
== VT_JMP
|| v
== VT_JMPI
) {
5295 /* need to put correct jump if && or || without test */
5301 /* convert stack entry to register and duplicate its value in another
5309 if ((t
& VT_BTYPE
) == VT_LLONG
) {
5316 /* stack: H L L1 H1 */
5324 /* duplicate value */
5329 #ifdef TCC_TARGET_X86_64
5330 if ((t
& VT_BTYPE
) == VT_LDOUBLE
) {
5340 load(r1
, &sv
); /* move r to r1 */
5342 /* duplicates value */
5347 #ifndef TCC_TARGET_X86_64
5348 /* generate CPU independent (unsigned) long long operations */
5349 void gen_opl(int op
)
5351 int t
, a
, b
, op1
, c
, i
;
5353 unsigned short reg_iret
= REG_IRET
;
5354 unsigned short reg_lret
= REG_LRET
;
5360 func
= TOK___divdi3
;
5363 func
= TOK___udivdi3
;
5366 func
= TOK___moddi3
;
5369 func
= TOK___umoddi3
;
5376 /* call generic long long function */
5377 vpush_global_sym(&func_old_type
, func
);
5382 vtop
->r2
= reg_lret
;
5395 /* stack: L1 H1 L2 H2 */
5400 vtop
[-2] = vtop
[-3];
5403 /* stack: H1 H2 L1 L2 */
5409 /* stack: H1 H2 L1 L2 ML MH */
5412 /* stack: ML MH H1 H2 L1 L2 */
5416 /* stack: ML MH H1 L2 H2 L1 */
5421 /* stack: ML MH M1 M2 */
5424 } else if (op
== '+' || op
== '-') {
5425 /* XXX: add non carry method too (for MIPS or alpha) */
5431 /* stack: H1 H2 (L1 op L2) */
5434 gen_op(op1
+ 1); /* TOK_xxxC2 */
5437 /* stack: H1 H2 (L1 op L2) */
5440 /* stack: (L1 op L2) H1 H2 */
5442 /* stack: (L1 op L2) (H1 op H2) */
5450 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
5451 t
= vtop
[-1].type
.t
;
5455 /* stack: L H shift */
5457 /* constant: simpler */
5458 /* NOTE: all comments are for SHL. the other cases are
5459 done by swaping words */
5470 if (op
!= TOK_SAR
) {
5503 /* XXX: should provide a faster fallback on x86 ? */
5506 func
= TOK___ashrdi3
;
5509 func
= TOK___lshrdi3
;
5512 func
= TOK___ashldi3
;
5518 /* compare operations */
5524 /* stack: L1 H1 L2 H2 */
5526 vtop
[-1] = vtop
[-2];
5528 /* stack: L1 L2 H1 H2 */
5531 /* when values are equal, we need to compare low words. since
5532 the jump is inverted, we invert the test too. */
5535 else if (op1
== TOK_GT
)
5537 else if (op1
== TOK_ULT
)
5539 else if (op1
== TOK_UGT
)
5544 if (op1
!= TOK_NE
) {
5548 /* generate non equal test */
5549 /* XXX: NOT PORTABLE yet */
5553 #if defined(TCC_TARGET_I386)
5554 b
= psym(0x850f, 0);
5555 #elif defined(TCC_TARGET_ARM)
5557 o(0x1A000000 | encbranch(ind
, 0, 1));
5558 #elif defined(TCC_TARGET_C67)
5559 error("not implemented");
5561 #error not supported
5565 /* compare low. Always unsigned */
5569 else if (op1
== TOK_LE
)
5571 else if (op1
== TOK_GT
)
5573 else if (op1
== TOK_GE
)
5584 /* handle integer constant optimizations and various machine
5586 void gen_opic(int op
)
5588 int c1
, c2
, t1
, t2
, n
;
5591 typedef unsigned long long U
;
5595 t1
= v1
->type
.t
& VT_BTYPE
;
5596 t2
= v2
->type
.t
& VT_BTYPE
;
5600 else if (v1
->type
.t
& VT_UNSIGNED
)
5607 else if (v2
->type
.t
& VT_UNSIGNED
)
5612 /* currently, we cannot do computations with forward symbols */
5613 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5614 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5617 case '+': l1
+= l2
; break;
5618 case '-': l1
-= l2
; break;
5619 case '&': l1
&= l2
; break;
5620 case '^': l1
^= l2
; break;
5621 case '|': l1
|= l2
; break;
5622 case '*': l1
*= l2
; break;
5629 /* if division by zero, generate explicit division */
5632 error("division by zero in constant");
5636 default: l1
/= l2
; break;
5637 case '%': l1
%= l2
; break;
5638 case TOK_UDIV
: l1
= (U
)l1
/ l2
; break;
5639 case TOK_UMOD
: l1
= (U
)l1
% l2
; break;
5642 case TOK_SHL
: l1
<<= l2
; break;
5643 case TOK_SHR
: l1
= (U
)l1
>> l2
; break;
5644 case TOK_SAR
: l1
>>= l2
; break;
5646 case TOK_ULT
: l1
= (U
)l1
< (U
)l2
; break;
5647 case TOK_UGE
: l1
= (U
)l1
>= (U
)l2
; break;
5648 case TOK_EQ
: l1
= l1
== l2
; break;
5649 case TOK_NE
: l1
= l1
!= l2
; break;
5650 case TOK_ULE
: l1
= (U
)l1
<= (U
)l2
; break;
5651 case TOK_UGT
: l1
= (U
)l1
> (U
)l2
; break;
5652 case TOK_LT
: l1
= l1
< l2
; break;
5653 case TOK_GE
: l1
= l1
>= l2
; break;
5654 case TOK_LE
: l1
= l1
<= l2
; break;
5655 case TOK_GT
: l1
= l1
> l2
; break;
5657 case TOK_LAND
: l1
= l1
&& l2
; break;
5658 case TOK_LOR
: l1
= l1
|| l2
; break;
5665 /* if commutative ops, put c2 as constant */
5666 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
5667 op
== '|' || op
== '*')) {
5669 c2
= c1
; //c = c1, c1 = c2, c2 = c;
5670 l2
= l1
; //l = l1, l1 = l2, l2 = l;
5672 /* Filter out NOP operations like x*1, x-0, x&-1... */
5673 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
5676 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
5677 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
5683 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
5684 /* try to use shifts instead of muls or divs */
5685 if (l2
> 0 && (l2
& (l2
- 1)) == 0) {
5694 else if (op
== TOK_PDIV
)
5700 } else if (c2
&& (op
== '+' || op
== '-') &&
5701 ((vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5702 (VT_CONST
| VT_SYM
) ||
5703 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
)) == VT_LOCAL
)) {
5704 /* symbol + constant case */
5711 if (!nocode_wanted
) {
5712 /* call low level op generator */
5713 if (t1
== VT_LLONG
|| t2
== VT_LLONG
)
5724 /* generate a floating point operation with constant propagation */
5725 void gen_opif(int op
)
5733 /* currently, we cannot do computations with forward symbols */
5734 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5735 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5737 if (v1
->type
.t
== VT_FLOAT
) {
5740 } else if (v1
->type
.t
== VT_DOUBLE
) {
5748 /* NOTE: we only do constant propagation if finite number (not
5749 NaN or infinity) (ANSI spec) */
5750 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5754 case '+': f1
+= f2
; break;
5755 case '-': f1
-= f2
; break;
5756 case '*': f1
*= f2
; break;
5760 error("division by zero in constant");
5765 /* XXX: also handles tests ? */
5769 /* XXX: overflow test ? */
5770 if (v1
->type
.t
== VT_FLOAT
) {
5772 } else if (v1
->type
.t
== VT_DOUBLE
) {
5780 if (!nocode_wanted
) {
5788 static int pointed_size(CType
*type
)
5791 return type_size(pointed_type(type
), &align
);
5794 static inline int is_null_pointer(SValue
*p
)
5796 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5798 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5799 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5802 static inline int is_integer_btype(int bt
)
5804 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5805 bt
== VT_INT
|| bt
== VT_LLONG
);
5808 /* check types for comparison or substraction of pointers */
5809 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5811 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5814 /* null pointers are accepted for all comparisons as gcc */
5815 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5819 bt1
= type1
->t
& VT_BTYPE
;
5820 bt2
= type2
->t
& VT_BTYPE
;
5821 /* accept comparison between pointer and integer with a warning */
5822 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5823 if (op
!= TOK_LOR
&& op
!= TOK_LAND
)
5824 warning("comparison between pointer and integer");
5828 /* both must be pointers or implicit function pointers */
5829 if (bt1
== VT_PTR
) {
5830 type1
= pointed_type(type1
);
5831 } else if (bt1
!= VT_FUNC
)
5832 goto invalid_operands
;
5834 if (bt2
== VT_PTR
) {
5835 type2
= pointed_type(type2
);
5836 } else if (bt2
!= VT_FUNC
) {
5838 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5840 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5841 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5845 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5846 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5847 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5848 /* gcc-like error if '-' is used */
5850 goto invalid_operands
;
5852 warning("comparison of distinct pointer types lacks a cast");
5856 /* generic gen_op: handles types problems */
5859 int u
, t1
, t2
, bt1
, bt2
, t
;
5862 t1
= vtop
[-1].type
.t
;
5863 t2
= vtop
[0].type
.t
;
5864 bt1
= t1
& VT_BTYPE
;
5865 bt2
= t2
& VT_BTYPE
;
5867 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5868 /* at least one operand is a pointer */
5869 /* relationnal op: must be both pointers */
5870 if (op
>= TOK_ULT
&& op
<= TOK_LOR
) {
5871 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5872 /* pointers are handled are unsigned */
5873 #ifdef TCC_TARGET_X86_64
5874 t
= VT_LLONG
| VT_UNSIGNED
;
5876 t
= VT_INT
| VT_UNSIGNED
;
5880 /* if both pointers, then it must be the '-' op */
5881 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5883 error("cannot use pointers here");
5884 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5885 /* XXX: check that types are compatible */
5886 u
= pointed_size(&vtop
[-1].type
);
5888 /* set to integer type */
5889 #ifdef TCC_TARGET_X86_64
5890 vtop
->type
.t
= VT_LLONG
;
5892 vtop
->type
.t
= VT_INT
;
5897 /* exactly one pointer : must be '+' or '-'. */
5898 if (op
!= '-' && op
!= '+')
5899 error("cannot use pointers here");
5900 /* Put pointer as first operand */
5901 if (bt2
== VT_PTR
) {
5905 type1
= vtop
[-1].type
;
5906 #ifdef TCC_TARGET_X86_64
5907 vpushll(pointed_size(&vtop
[-1].type
));
5909 /* XXX: cast to int ? (long long case) */
5910 vpushi(pointed_size(&vtop
[-1].type
));
5913 #ifdef CONFIG_TCC_BCHECK
5914 /* if evaluating constant expression, no code should be
5915 generated, so no bound check */
5916 if (do_bounds_check
&& !const_wanted
) {
5917 /* if bounded pointers, we generate a special code to
5924 gen_bounded_ptr_add();
5930 /* put again type if gen_opic() swaped operands */
5933 } else if (is_float(bt1
) || is_float(bt2
)) {
5934 /* compute bigger type and do implicit casts */
5935 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5937 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5942 /* floats can only be used for a few operations */
5943 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5944 (op
< TOK_ULT
|| op
> TOK_GT
))
5945 error("invalid operands for binary operation");
5947 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5948 /* cast to biggest op */
5950 /* convert to unsigned if it does not fit in a long long */
5951 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5952 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5956 /* integer operations */
5958 /* convert to unsigned if it does not fit in an integer */
5959 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5960 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5963 /* XXX: currently, some unsigned operations are explicit, so
5964 we modify them here */
5965 if (t
& VT_UNSIGNED
) {
5972 else if (op
== TOK_LT
)
5974 else if (op
== TOK_GT
)
5976 else if (op
== TOK_LE
)
5978 else if (op
== TOK_GE
)
5985 /* special case for shifts and long long: we keep the shift as
5987 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5994 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5995 /* relationnal op: the result is an int */
5996 vtop
->type
.t
= VT_INT
;
6003 #ifndef TCC_TARGET_ARM
6004 /* generic itof for unsigned long long case */
6005 void gen_cvt_itof1(int t
)
6007 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
6008 (VT_LLONG
| VT_UNSIGNED
)) {
6011 vpush_global_sym(&func_old_type
, TOK___floatundisf
);
6012 #if LDOUBLE_SIZE != 8
6013 else if (t
== VT_LDOUBLE
)
6014 vpush_global_sym(&func_old_type
, TOK___floatundixf
);
6017 vpush_global_sym(&func_old_type
, TOK___floatundidf
);
6028 /* generic ftoi for unsigned long long case */
6029 void gen_cvt_ftoi1(int t
)
6033 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
6034 /* not handled natively */
6035 st
= vtop
->type
.t
& VT_BTYPE
;
6037 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
6038 #if LDOUBLE_SIZE != 8
6039 else if (st
== VT_LDOUBLE
)
6040 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
6043 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
6048 vtop
->r2
= REG_LRET
;
6054 /* force char or short cast */
6055 void force_charshort_cast(int t
)
6059 /* XXX: add optimization if lvalue : just change type and offset */
6064 if (t
& VT_UNSIGNED
) {
6065 vpushi((1 << bits
) - 1);
6071 /* result must be signed or the SAR is converted to an SHL
6072 This was not the case when "t" was a signed short
6073 and the last value on the stack was an unsigned int */
6074 vtop
->type
.t
&= ~VT_UNSIGNED
;
6080 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
6081 static void gen_cast(CType
*type
)
6083 int sbt
, dbt
, sf
, df
, c
, p
;
6085 /* special delayed cast for char/short */
6086 /* XXX: in some cases (multiple cascaded casts), it may still
6088 if (vtop
->r
& VT_MUSTCAST
) {
6089 vtop
->r
&= ~VT_MUSTCAST
;
6090 force_charshort_cast(vtop
->type
.t
);
6093 /* bitfields first get cast to ints */
6094 if (vtop
->type
.t
& VT_BITFIELD
) {
6098 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
6099 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
6104 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
6105 p
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == (VT_CONST
| VT_SYM
);
6107 /* constant case: we can do it now */
6108 /* XXX: in ISOC, cannot do it if error in convert */
6109 if (sbt
== VT_FLOAT
)
6110 vtop
->c
.ld
= vtop
->c
.f
;
6111 else if (sbt
== VT_DOUBLE
)
6112 vtop
->c
.ld
= vtop
->c
.d
;
6115 if ((sbt
& VT_BTYPE
) == VT_LLONG
) {
6116 if (sbt
& VT_UNSIGNED
)
6117 vtop
->c
.ld
= vtop
->c
.ull
;
6119 vtop
->c
.ld
= vtop
->c
.ll
;
6121 if (sbt
& VT_UNSIGNED
)
6122 vtop
->c
.ld
= vtop
->c
.ui
;
6124 vtop
->c
.ld
= vtop
->c
.i
;
6127 if (dbt
== VT_FLOAT
)
6128 vtop
->c
.f
= (float)vtop
->c
.ld
;
6129 else if (dbt
== VT_DOUBLE
)
6130 vtop
->c
.d
= (double)vtop
->c
.ld
;
6131 } else if (sf
&& dbt
== (VT_LLONG
|VT_UNSIGNED
)) {
6132 vtop
->c
.ull
= (unsigned long long)vtop
->c
.ld
;
6133 } else if (sf
&& dbt
== VT_BOOL
) {
6134 vtop
->c
.i
= (vtop
->c
.ld
!= 0);
6137 vtop
->c
.ll
= (long long)vtop
->c
.ld
;
6138 else if (sbt
== (VT_LLONG
|VT_UNSIGNED
))
6139 vtop
->c
.ll
= vtop
->c
.ull
;
6140 else if (sbt
& VT_UNSIGNED
)
6141 vtop
->c
.ll
= vtop
->c
.ui
;
6142 else if (sbt
!= VT_LLONG
)
6143 vtop
->c
.ll
= vtop
->c
.i
;
6145 if (dbt
== (VT_LLONG
|VT_UNSIGNED
))
6146 vtop
->c
.ull
= vtop
->c
.ll
;
6147 else if (dbt
== VT_BOOL
)
6148 vtop
->c
.i
= (vtop
->c
.ll
!= 0);
6149 else if (dbt
!= VT_LLONG
) {
6151 if ((dbt
& VT_BTYPE
) == VT_BYTE
)
6153 else if ((dbt
& VT_BTYPE
) == VT_SHORT
)
6156 if(dbt
& VT_UNSIGNED
)
6157 vtop
->c
.ui
= ((unsigned int)vtop
->c
.ll
<< s
) >> s
;
6159 vtop
->c
.i
= ((int)vtop
->c
.ll
<< s
) >> s
;
6162 } else if (p
&& dbt
== VT_BOOL
) {
6165 } else if (!nocode_wanted
) {
6166 /* non constant case: generate code */
6168 /* convert from fp to fp */
6171 /* convert int to fp */
6174 /* convert fp to int */
6175 if (dbt
== VT_BOOL
) {
6179 /* we handle char/short/etc... with generic code */
6180 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
6181 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
6185 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
6186 /* additional cast for char/short... */
6191 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
6192 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
6193 /* scalar to long long */
6194 #ifndef TCC_TARGET_X86_64
6195 /* machine independent conversion */
6197 /* generate high word */
6198 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
6206 /* patch second register */
6207 vtop
[-1].r2
= vtop
->r
;
6211 if (sbt
!= (VT_INT
| VT_UNSIGNED
)) {
6212 /* x86_64 specific: movslq */
6214 o(0xc0 + (REG_VALUE(r
) << 3) + REG_VALUE(r
));
6218 } else if (dbt
== VT_BOOL
) {
6219 /* scalar to bool */
6222 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
6223 (dbt
& VT_BTYPE
) == VT_SHORT
) {
6224 if (sbt
== VT_PTR
) {
6225 vtop
->type
.t
= VT_INT
;
6226 warning("nonportable conversion from pointer to char/short");
6228 force_charshort_cast(dbt
);
6229 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
6231 if (sbt
== VT_LLONG
) {
6232 /* from long long: just take low order word */
6236 /* if lvalue and single word type, nothing to do because
6237 the lvalue already contains the real type size (see
6238 VT_LVAL_xxx constants) */
6241 } else if ((dbt
& VT_BTYPE
) == VT_PTR
&& !(vtop
->r
& VT_LVAL
)) {
6242 /* if we are casting between pointer types,
6243 we must update the VT_LVAL_xxx size */
6244 vtop
->r
= (vtop
->r
& ~VT_LVAL_TYPE
)
6245 | (lvalue_type(type
->ref
->type
.t
) & VT_LVAL_TYPE
);
6250 /* return type size. Put alignment at 'a' */
6251 static int type_size(CType
*type
, int *a
)
6256 bt
= type
->t
& VT_BTYPE
;
6257 if (bt
== VT_STRUCT
) {
6262 } else if (bt
== VT_PTR
) {
6263 if (type
->t
& VT_ARRAY
) {
6267 ts
= type_size(&s
->type
, a
);
6269 if (ts
< 0 && s
->c
< 0)
6277 } else if (bt
== VT_LDOUBLE
) {
6279 return LDOUBLE_SIZE
;
6280 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
6281 #ifdef TCC_TARGET_I386
6282 #ifdef TCC_TARGET_PE
6287 #elif defined(TCC_TARGET_ARM)
6297 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
6300 } else if (bt
== VT_SHORT
) {
6304 /* char, void, function, _Bool */
6310 /* return the pointed type of t */
6311 static inline CType
*pointed_type(CType
*type
)
6313 return &type
->ref
->type
;
6316 /* modify type so that its it is a pointer to type. */
6317 static void mk_pointer(CType
*type
)
6320 s
= sym_push(SYM_FIELD
, type
, 0, -1);
6321 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
6325 /* compare function types. OLD functions match any new functions */
6326 static int is_compatible_func(CType
*type1
, CType
*type2
)
6332 if (!is_compatible_types(&s1
->type
, &s2
->type
))
6334 /* check func_call */
6335 if (FUNC_CALL(s1
->r
) != FUNC_CALL(s2
->r
))
6337 /* XXX: not complete */
6338 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
6342 while (s1
!= NULL
) {
6345 if (!is_compatible_parameter_types(&s1
->type
, &s2
->type
))
6355 /* return true if type1 and type2 are the same. If unqualified is
6356 true, qualifiers on the types are ignored.
6358 - enums are not checked as gcc __builtin_types_compatible_p ()
6360 static int compare_types(CType
*type1
, CType
*type2
, int unqualified
)
6364 t1
= type1
->t
& VT_TYPE
;
6365 t2
= type2
->t
& VT_TYPE
;
6367 /* strip qualifiers before comparing */
6368 t1
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6369 t2
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6371 /* XXX: bitfields ? */
6374 /* test more complicated cases */
6375 bt1
= t1
& VT_BTYPE
;
6376 if (bt1
== VT_PTR
) {
6377 type1
= pointed_type(type1
);
6378 type2
= pointed_type(type2
);
6379 return is_compatible_types(type1
, type2
);
6380 } else if (bt1
== VT_STRUCT
) {
6381 return (type1
->ref
== type2
->ref
);
6382 } else if (bt1
== VT_FUNC
) {
6383 return is_compatible_func(type1
, type2
);
6389 /* return true if type1 and type2 are exactly the same (including
6392 static int is_compatible_types(CType
*type1
, CType
*type2
)
6394 return compare_types(type1
,type2
,0);
6397 /* return true if type1 and type2 are the same (ignoring qualifiers).
6399 static int is_compatible_parameter_types(CType
*type1
, CType
*type2
)
6401 return compare_types(type1
,type2
,1);
6404 /* print a type. If 'varstr' is not NULL, then the variable is also
6405 printed in the type */
6407 /* XXX: add array and function pointers */
6408 void type_to_str(char *buf
, int buf_size
,
6409 CType
*type
, const char *varstr
)
6416 t
= type
->t
& VT_TYPE
;
6419 if (t
& VT_CONSTANT
)
6420 pstrcat(buf
, buf_size
, "const ");
6421 if (t
& VT_VOLATILE
)
6422 pstrcat(buf
, buf_size
, "volatile ");
6423 if (t
& VT_UNSIGNED
)
6424 pstrcat(buf
, buf_size
, "unsigned ");
6454 tstr
= "long double";
6456 pstrcat(buf
, buf_size
, tstr
);
6460 if (bt
== VT_STRUCT
)
6464 pstrcat(buf
, buf_size
, tstr
);
6465 v
= type
->ref
->v
& ~SYM_STRUCT
;
6466 if (v
>= SYM_FIRST_ANOM
)
6467 pstrcat(buf
, buf_size
, "<anonymous>");
6469 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
6473 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
6474 pstrcat(buf
, buf_size
, "(");
6476 while (sa
!= NULL
) {
6477 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
6478 pstrcat(buf
, buf_size
, buf1
);
6481 pstrcat(buf
, buf_size
, ", ");
6483 pstrcat(buf
, buf_size
, ")");
6487 pstrcpy(buf1
, sizeof(buf1
), "*");
6489 pstrcat(buf1
, sizeof(buf1
), varstr
);
6490 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
6494 pstrcat(buf
, buf_size
, " ");
6495 pstrcat(buf
, buf_size
, varstr
);
6500 /* verify type compatibility to store vtop in 'dt' type, and generate
6502 static void gen_assign_cast(CType
*dt
)
6504 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
6505 char buf1
[256], buf2
[256];
6508 st
= &vtop
->type
; /* source type */
6509 dbt
= dt
->t
& VT_BTYPE
;
6510 sbt
= st
->t
& VT_BTYPE
;
6511 if (dt
->t
& VT_CONSTANT
)
6512 warning("assignment of read-only location");
6515 /* special cases for pointers */
6516 /* '0' can also be a pointer */
6517 if (is_null_pointer(vtop
))
6519 /* accept implicit pointer to integer cast with warning */
6520 if (is_integer_btype(sbt
)) {
6521 warning("assignment makes pointer from integer without a cast");
6524 type1
= pointed_type(dt
);
6525 /* a function is implicitely a function pointer */
6526 if (sbt
== VT_FUNC
) {
6527 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
6528 !is_compatible_types(pointed_type(dt
), st
))
6535 type2
= pointed_type(st
);
6536 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
6537 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
6538 /* void * can match anything */
6540 /* exact type match, except for unsigned */
6543 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6544 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6545 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
6546 warning("assignment from incompatible pointer type");
6548 /* check const and volatile */
6549 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
6550 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
6551 warning("assignment discards qualifiers from pointer target type");
6557 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
6558 warning("assignment makes integer from pointer without a cast");
6560 /* XXX: more tests */
6565 tmp_type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6566 tmp_type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6567 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
6569 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
6570 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
6571 error("cannot cast '%s' to '%s'", buf1
, buf2
);
6579 /* store vtop in lvalue pushed on stack */
6582 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
6584 ft
= vtop
[-1].type
.t
;
6585 sbt
= vtop
->type
.t
& VT_BTYPE
;
6586 dbt
= ft
& VT_BTYPE
;
6587 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
6588 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
6589 /* optimize char/short casts */
6590 delayed_cast
= VT_MUSTCAST
;
6591 vtop
->type
.t
= ft
& (VT_TYPE
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
)));
6592 /* XXX: factorize */
6593 if (ft
& VT_CONSTANT
)
6594 warning("assignment of read-only location");
6597 if (!(ft
& VT_BITFIELD
))
6598 gen_assign_cast(&vtop
[-1].type
);
6601 if (sbt
== VT_STRUCT
) {
6602 /* if structure, only generate pointer */
6603 /* structure assignment : generate memcpy */
6604 /* XXX: optimize if small size */
6605 if (!nocode_wanted
) {
6606 size
= type_size(&vtop
->type
, &align
);
6610 vpush_global_sym(&func_old_type
, TOK_memcpy8
);
6611 else if(!(align
& 3))
6612 vpush_global_sym(&func_old_type
, TOK_memcpy4
);
6615 vpush_global_sym(&func_old_type
, TOK_memcpy
);
6619 vtop
->type
.t
= VT_INT
;
6623 vtop
->type
.t
= VT_INT
;
6635 /* leave source on stack */
6636 } else if (ft
& VT_BITFIELD
) {
6637 /* bitfield store handling */
6638 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
6639 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
6640 /* remove bit field info to avoid loops */
6641 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
6643 /* duplicate source into other register */
6648 if((ft
& VT_BTYPE
) == VT_BOOL
) {
6649 gen_cast(&vtop
[-1].type
);
6650 vtop
[-1].type
.t
= (vtop
[-1].type
.t
& ~VT_BTYPE
) | (VT_BYTE
| VT_UNSIGNED
);
6653 /* duplicate destination */
6655 vtop
[-1] = vtop
[-2];
6657 /* mask and shift source */
6658 if((ft
& VT_BTYPE
) != VT_BOOL
) {
6659 if((ft
& VT_BTYPE
) == VT_LLONG
) {
6660 vpushll((1ULL << bit_size
) - 1ULL);
6662 vpushi((1 << bit_size
) - 1);
6668 /* load destination, mask and or with source */
6670 if((ft
& VT_BTYPE
) == VT_LLONG
) {
6671 vpushll(~(((1ULL << bit_size
) - 1ULL) << bit_pos
));
6673 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
6680 /* pop off shifted source from "duplicate source..." above */
6684 #ifdef CONFIG_TCC_BCHECK
6685 /* bound check case */
6686 if (vtop
[-1].r
& VT_MUSTBOUND
) {
6692 if (!nocode_wanted
) {
6696 #ifdef TCC_TARGET_X86_64
6697 if ((ft
& VT_BTYPE
) == VT_LDOUBLE
) {
6702 r
= gv(rc
); /* generate value */
6703 /* if lvalue was saved on stack, must read it */
6704 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
6706 t
= get_reg(RC_INT
);
6707 #ifdef TCC_TARGET_X86_64
6712 sv
.r
= VT_LOCAL
| VT_LVAL
;
6713 sv
.c
.ul
= vtop
[-1].c
.ul
;
6715 vtop
[-1].r
= t
| VT_LVAL
;
6718 #ifndef TCC_TARGET_X86_64
6719 /* two word case handling : store second register at word + 4 */
6720 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
6722 /* convert to int to increment easily */
6723 vtop
->type
.t
= VT_INT
;
6729 /* XXX: it works because r2 is spilled last ! */
6730 store(vtop
->r2
, vtop
- 1);
6735 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
6736 vtop
->r
|= delayed_cast
;
6740 /* post defines POST/PRE add. c is the token ++ or -- */
6741 void inc(int post
, int c
)
6744 vdup(); /* save lvalue */
6746 gv_dup(); /* duplicate value */
6751 vpushi(c
- TOK_MID
);
6753 vstore(); /* store value */
6755 vpop(); /* if post op, return saved value */
6758 /* Parse GNUC __attribute__ extension. Currently, the following
6759 extensions are recognized:
6760 - aligned(n) : set data/function alignment.
6761 - packed : force data alignment to 1
6762 - section(x) : generate data/code in this section.
6763 - unused : currently ignored, but may be used someday.
6764 - regparm(n) : pass function parameters in registers (i386 only)
6766 static void parse_attribute(AttributeDef
*ad
)
6770 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
6774 while (tok
!= ')') {
6775 if (tok
< TOK_IDENT
)
6776 expect("attribute name");
6784 expect("section name");
6785 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
6794 if (n
<= 0 || (n
& (n
- 1)) != 0)
6795 error("alignment must be a positive power of two");
6808 /* currently, no need to handle it because tcc does not
6809 track unused objects */
6813 /* currently, no need to handle it because tcc does not
6814 track unused objects */
6819 FUNC_CALL(ad
->func_attr
) = FUNC_CDECL
;
6824 FUNC_CALL(ad
->func_attr
) = FUNC_STDCALL
;
6826 #ifdef TCC_TARGET_I386
6836 FUNC_CALL(ad
->func_attr
) = FUNC_FASTCALL1
+ n
- 1;
6842 FUNC_CALL(ad
->func_attr
) = FUNC_FASTCALLW
;
6846 FUNC_EXPORT(ad
->func_attr
) = 1;
6849 if (tcc_state
->warn_unsupported
)
6850 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6851 /* skip parameters */
6853 int parenthesis
= 0;
6857 else if (tok
== ')')
6860 } while (parenthesis
&& tok
!= -1);
6873 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6874 static void struct_decl(CType
*type
, int u
)
6876 int a
, v
, size
, align
, maxalign
, c
, offset
;
6877 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
, prevbt
;
6878 Sym
*s
, *ss
, *ass
, **ps
;
6882 a
= tok
; /* save decl type */
6887 /* struct already defined ? return it */
6889 expect("struct/union/enum name");
6893 error("invalid type");
6900 /* we put an undefined size for struct/union */
6901 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6902 s
->r
= 0; /* default alignment is zero as gcc */
6903 /* put struct/union/enum name in type */
6911 error("struct/union/enum already defined");
6912 /* cannot be empty */
6914 /* non empty enums are not allowed */
6915 if (a
== TOK_ENUM
) {
6919 expect("identifier");
6925 /* enum symbols have static storage */
6926 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6927 ss
->type
.t
|= VT_STATIC
;
6932 /* NOTE: we accept a trailing comma */
6943 while (tok
!= '}') {
6944 parse_btype(&btype
, &ad
);
6950 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6951 if (v
== 0 && (type1
.t
& VT_BTYPE
) != VT_STRUCT
)
6952 expect("identifier");
6953 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6954 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6955 error("invalid type for '%s'",
6956 get_tok_str(v
, NULL
));
6960 bit_size
= expr_const();
6961 /* XXX: handle v = 0 case for messages */
6963 error("negative width in bit-field '%s'",
6964 get_tok_str(v
, NULL
));
6965 if (v
&& bit_size
== 0)
6966 error("zero width for bit-field '%s'",
6967 get_tok_str(v
, NULL
));
6969 size
= type_size(&type1
, &align
);
6971 if (align
< ad
.aligned
)
6973 } else if (ad
.packed
) {
6975 } else if (*tcc_state
->pack_stack_ptr
) {
6976 if (align
> *tcc_state
->pack_stack_ptr
)
6977 align
= *tcc_state
->pack_stack_ptr
;
6980 if (bit_size
>= 0) {
6981 bt
= type1
.t
& VT_BTYPE
;
6988 error("bitfields must have scalar type");
6990 if (bit_size
> bsize
) {
6991 error("width of '%s' exceeds its type",
6992 get_tok_str(v
, NULL
));
6993 } else if (bit_size
== bsize
) {
6994 /* no need for bit fields */
6996 } else if (bit_size
== 0) {
6997 /* XXX: what to do if only padding in a
6999 /* zero size: means to pad */
7002 /* we do not have enough room ?
7003 did the type change?
7005 if ((bit_pos
+ bit_size
) > bsize
||
7006 bt
!= prevbt
|| a
== TOK_UNION
)
7009 /* XXX: handle LSB first */
7010 type1
.t
|= VT_BITFIELD
|
7011 (bit_pos
<< VT_STRUCT_SHIFT
) |
7012 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
7013 bit_pos
+= bit_size
;
7019 if (v
!= 0 || (type1
.t
& VT_BTYPE
) == VT_STRUCT
) {
7020 /* add new memory data only if starting
7022 if (lbit_pos
== 0) {
7023 if (a
== TOK_STRUCT
) {
7024 c
= (c
+ align
- 1) & -align
;
7033 if (align
> maxalign
)
7037 printf("add field %s offset=%d",
7038 get_tok_str(v
, NULL
), offset
);
7039 if (type1
.t
& VT_BITFIELD
) {
7040 printf(" pos=%d size=%d",
7041 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
7042 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
7047 if (v
== 0 && (type1
.t
& VT_BTYPE
) == VT_STRUCT
) {
7049 while ((ass
= ass
->next
) != NULL
) {
7050 ss
= sym_push(ass
->v
, &ass
->type
, 0, offset
+ ass
->c
);
7055 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
7059 if (tok
== ';' || tok
== TOK_EOF
)
7066 /* store size and alignment */
7067 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
7073 /* return 0 if no type declaration. otherwise, return the basic type
7076 static int parse_btype(CType
*type
, AttributeDef
*ad
)
7078 int t
, u
, type_found
, typespec_found
, typedef_found
;
7082 memset(ad
, 0, sizeof(AttributeDef
));
7090 /* currently, we really ignore extension */
7100 if ((t
& VT_BTYPE
) != 0)
7101 error("too many basic types");
7117 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
7118 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
7119 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
7120 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
7134 if ((t
& VT_BTYPE
) == VT_LONG
) {
7135 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
7142 struct_decl(&type1
, VT_ENUM
);
7145 type
->ref
= type1
.ref
;
7149 struct_decl(&type1
, VT_STRUCT
);
7152 /* type modifiers */
7205 /* GNUC attribute */
7206 case TOK_ATTRIBUTE1
:
7207 case TOK_ATTRIBUTE2
:
7208 parse_attribute(ad
);
7215 parse_expr_type(&type1
);
7218 if (typespec_found
|| typedef_found
)
7221 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
7224 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
7225 type
->ref
= s
->type
.ref
;
7233 if ((t
& (VT_SIGNED
|VT_UNSIGNED
)) == (VT_SIGNED
|VT_UNSIGNED
))
7234 error("signed and unsigned modifier");
7235 if (tcc_state
->char_is_unsigned
) {
7236 if ((t
& (VT_SIGNED
|VT_UNSIGNED
|VT_BTYPE
)) == VT_BYTE
)
7241 /* long is never used as type */
7242 if ((t
& VT_BTYPE
) == VT_LONG
)
7243 #ifndef TCC_TARGET_X86_64
7244 t
= (t
& ~VT_BTYPE
) | VT_INT
;
7246 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
7252 /* convert a function parameter type (array to pointer and function to
7253 function pointer) */
7254 static inline void convert_parameter_type(CType
*pt
)
7256 /* remove const and volatile qualifiers (XXX: const could be used
7257 to indicate a const function parameter */
7258 pt
->t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7259 /* array must be transformed to pointer according to ANSI C */
7261 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
7266 static void post_type(CType
*type
, AttributeDef
*ad
)
7268 int n
, l
, t1
, arg_size
, align
;
7269 Sym
**plast
, *s
, *first
;
7274 /* function declaration */
7282 /* read param name and compute offset */
7283 if (l
!= FUNC_OLD
) {
7284 if (!parse_btype(&pt
, &ad1
)) {
7286 error("invalid type");
7293 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
7295 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
7296 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
7297 error("parameter declared as void");
7298 arg_size
+= (type_size(&pt
, &align
) + 3) & ~3;
7303 expect("identifier");
7307 convert_parameter_type(&pt
);
7308 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
7314 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
7321 /* if no parameters, then old type prototype */
7325 t1
= type
->t
& VT_STORAGE
;
7326 /* NOTE: const is ignored in returned type as it has a special
7327 meaning in gcc / C++ */
7328 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
7329 post_type(type
, ad
);
7330 /* we push a anonymous symbol which will contain the function prototype */
7331 FUNC_ARGS(ad
->func_attr
) = arg_size
;
7332 s
= sym_push(SYM_FIELD
, type
, ad
->func_attr
, l
);
7334 type
->t
= t1
| VT_FUNC
;
7336 } else if (tok
== '[') {
7337 /* array definition */
7339 if (tok
== TOK_RESTRICT1
)
7345 error("invalid array size");
7348 /* parse next post type */
7349 t1
= type
->t
& VT_STORAGE
;
7350 type
->t
&= ~VT_STORAGE
;
7351 post_type(type
, ad
);
7353 /* we push a anonymous symbol which will contain the array
7355 s
= sym_push(SYM_FIELD
, type
, 0, n
);
7356 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
7361 /* Parse a type declaration (except basic type), and return the type
7362 in 'type'. 'td' is a bitmask indicating which kind of type decl is
7363 expected. 'type' should contain the basic type. 'ad' is the
7364 attribute definition of the basic type. It can be modified by
7367 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
7370 CType type1
, *type2
;
7373 while (tok
== '*') {
7381 qualifiers
|= VT_CONSTANT
;
7386 qualifiers
|= VT_VOLATILE
;
7394 type
->t
|= qualifiers
;
7397 /* XXX: clarify attribute handling */
7398 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7399 parse_attribute(ad
);
7401 /* recursive type */
7402 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
7403 type1
.t
= 0; /* XXX: same as int */
7406 /* XXX: this is not correct to modify 'ad' at this point, but
7407 the syntax is not clear */
7408 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7409 parse_attribute(ad
);
7410 type_decl(&type1
, ad
, v
, td
);
7413 /* type identifier */
7414 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
7418 if (!(td
& TYPE_ABSTRACT
))
7419 expect("identifier");
7423 post_type(type
, ad
);
7424 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7425 parse_attribute(ad
);
7428 /* append type at the end of type1 */
7441 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
7442 static int lvalue_type(int t
)
7447 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
7449 else if (bt
== VT_SHORT
)
7453 if (t
& VT_UNSIGNED
)
7454 r
|= VT_LVAL_UNSIGNED
;
7458 /* indirection with full error checking and bound check */
7459 static void indir(void)
7461 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
) {
7462 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FUNC
)
7466 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
7468 vtop
->type
= *pointed_type(&vtop
->type
);
7469 /* Arrays and functions are never lvalues */
7470 if (!(vtop
->type
.t
& VT_ARRAY
)
7471 && (vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7472 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7473 /* if bound checking, the referenced pointer must be checked */
7474 if (do_bounds_check
)
7475 vtop
->r
|= VT_MUSTBOUND
;
7479 /* pass a parameter to a function and do type checking and casting */
7480 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
7485 func_type
= func
->c
;
7486 if (func_type
== FUNC_OLD
||
7487 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
7488 /* default casting : only need to convert float to double */
7489 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
7493 } else if (arg
== NULL
) {
7494 error("too many arguments to function");
7497 type
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
7498 gen_assign_cast(&type
);
7502 /* parse an expression of the form '(type)' or '(expr)' and return its
7504 static void parse_expr_type(CType
*type
)
7510 if (parse_btype(type
, &ad
)) {
7511 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7518 static void parse_type(CType
*type
)
7523 if (!parse_btype(type
, &ad
)) {
7526 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7529 static void vpush_tokc(int t
)
7533 vsetc(&type
, VT_CONST
, &tokc
);
7536 static void unary(void)
7538 int n
, t
, align
, size
, r
;
7543 /* XXX: GCC 2.95.3 does not generate a table although it should be
7557 vpush_tokc(VT_INT
| VT_UNSIGNED
);
7561 vpush_tokc(VT_LLONG
);
7565 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
7569 vpush_tokc(VT_FLOAT
);
7573 vpush_tokc(VT_DOUBLE
);
7577 vpush_tokc(VT_LDOUBLE
);
7580 case TOK___FUNCTION__
:
7582 goto tok_identifier
;
7588 /* special function name identifier */
7589 len
= strlen(funcname
) + 1;
7590 /* generate char[len] type */
7595 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
7596 ptr
= section_ptr_add(data_section
, len
);
7597 memcpy(ptr
, funcname
, len
);
7602 #ifdef TCC_TARGET_PE
7603 t
= VT_SHORT
| VT_UNSIGNED
;
7609 /* string parsing */
7612 if (tcc_state
->warn_write_strings
)
7617 memset(&ad
, 0, sizeof(AttributeDef
));
7618 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
7623 if (parse_btype(&type
, &ad
)) {
7624 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
7626 /* check ISOC99 compound literal */
7628 /* data is allocated locally by default */
7633 /* all except arrays are lvalues */
7634 if (!(type
.t
& VT_ARRAY
))
7635 r
|= lvalue_type(type
.t
);
7636 memset(&ad
, 0, sizeof(AttributeDef
));
7637 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
7642 } else if (tok
== '{') {
7643 /* save all registers */
7645 /* statement expression : we do not accept break/continue
7646 inside as GCC does */
7647 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
7662 /* functions names must be treated as function pointers,
7663 except for unary '&' and sizeof. Since we consider that
7664 functions are not lvalues, we only have to handle it
7665 there and in function calls. */
7666 /* arrays can also be used although they are not lvalues */
7667 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
7668 !(vtop
->type
.t
& VT_ARRAY
) && !(vtop
->type
.t
& VT_LLOCAL
))
7670 mk_pointer(&vtop
->type
);
7676 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
7678 boolean
.t
= VT_BOOL
;
7680 vtop
->c
.i
= !vtop
->c
.i
;
7681 } else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
7682 vtop
->c
.i
= vtop
->c
.i
^ 1;
7685 vseti(VT_JMP
, gtst(1, 0));
7696 /* in order to force cast, we add zero */
7698 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
7699 error("pointer not accepted for unary plus");
7709 parse_expr_type(&type
);
7713 size
= type_size(&type
, &align
);
7714 if (t
== TOK_SIZEOF
) {
7716 error("sizeof applied to an incomplete type");
7721 vtop
->type
.t
|= VT_UNSIGNED
;
7724 case TOK_builtin_types_compatible_p
:
7733 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7734 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7735 vpushi(is_compatible_types(&type1
, &type2
));
7738 case TOK_builtin_constant_p
:
7740 int saved_nocode_wanted
, res
;
7743 saved_nocode_wanted
= nocode_wanted
;
7746 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
7748 nocode_wanted
= saved_nocode_wanted
;
7753 case TOK_builtin_frame_address
:
7758 if (tok
!= TOK_CINT
) {
7759 error("__builtin_frame_address only takes integers");
7762 error("TCC only supports __builtin_frame_address(0)");
7768 vset(&type
, VT_LOCAL
, 0);
7771 #ifdef TCC_TARGET_X86_64
7772 case TOK_builtin_malloc
:
7774 char *p
= file
->buf_ptr
;
7775 file
->buf_ptr
= "malloc";
7778 goto tok_identifier
;
7780 case TOK_builtin_free
:
7782 char *p
= file
->buf_ptr
;
7783 file
->buf_ptr
= "free";
7786 goto tok_identifier
;
7804 goto tok_identifier
;
7806 /* allow to take the address of a label */
7807 if (tok
< TOK_UIDENT
)
7808 expect("label identifier");
7809 s
= label_find(tok
);
7811 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7813 if (s
->r
== LABEL_DECLARED
)
7814 s
->r
= LABEL_FORWARD
;
7817 s
->type
.t
= VT_VOID
;
7818 mk_pointer(&s
->type
);
7819 s
->type
.t
|= VT_STATIC
;
7821 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
7830 expect("identifier");
7834 error("'%s' undeclared", get_tok_str(t
, NULL
));
7835 /* for simple function calls, we tolerate undeclared
7836 external reference to int() function */
7837 if (tcc_state
->warn_implicit_function_declaration
)
7838 warning("implicit declaration of function '%s'",
7839 get_tok_str(t
, NULL
));
7840 s
= external_global_sym(t
, &func_old_type
, 0);
7842 if ((s
->type
.t
& (VT_STATIC
| VT_INLINE
| VT_BTYPE
)) ==
7843 (VT_STATIC
| VT_INLINE
| VT_FUNC
)) {
7844 /* if referencing an inline function, then we generate a
7845 symbol to it if not already done. It will have the
7846 effect to generate code for it at the end of the
7847 compilation unit. Inline function as always
7848 generated in the text section. */
7850 put_extern_sym(s
, text_section
, 0, 0);
7851 r
= VT_SYM
| VT_CONST
;
7855 vset(&s
->type
, r
, s
->c
);
7856 /* if forward reference, we must point to s */
7857 if (vtop
->r
& VT_SYM
) {
7864 /* post operations */
7866 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
7869 } else if (tok
== '.' || tok
== TOK_ARROW
) {
7871 if (tok
== TOK_ARROW
)
7876 /* expect pointer on structure */
7877 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
7878 expect("struct or union");
7882 while ((s
= s
->next
) != NULL
) {
7887 error("field not found: %s", get_tok_str(tok
& ~SYM_FIELD
, NULL
));
7888 /* add field offset to pointer */
7889 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
7892 /* change type to field type, and set to lvalue */
7893 vtop
->type
= s
->type
;
7894 /* an array is never an lvalue */
7895 if (!(vtop
->type
.t
& VT_ARRAY
)) {
7896 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7897 /* if bound checking, the referenced pointer must be checked */
7898 if (do_bounds_check
)
7899 vtop
->r
|= VT_MUSTBOUND
;
7902 } else if (tok
== '[') {
7908 } else if (tok
== '(') {
7914 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7915 /* pointer test (no array accepted) */
7916 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
7917 vtop
->type
= *pointed_type(&vtop
->type
);
7918 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
7922 expect("function pointer");
7925 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
7927 /* get return type */
7930 sa
= s
->next
; /* first parameter */
7933 /* compute first implicit argument if a structure is returned */
7934 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
7935 /* get some space for the returned structure */
7936 size
= type_size(&s
->type
, &align
);
7937 loc
= (loc
- size
) & -align
;
7939 ret
.r
= VT_LOCAL
| VT_LVAL
;
7940 /* pass it as 'int' to avoid structure arg passing
7942 vseti(VT_LOCAL
, loc
);
7947 /* return in register */
7948 if (is_float(ret
.type
.t
)) {
7951 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
7960 gfunc_param_typed(s
, sa
);
7970 error("too few arguments to function");
7972 if (!nocode_wanted
) {
7973 gfunc_call(nb_args
);
7975 vtop
-= (nb_args
+ 1);
7978 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
7986 static void uneq(void)
7992 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
7993 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
7994 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
8009 static void expr_prod(void)
8014 while (tok
== '*' || tok
== '/' || tok
== '%') {
8022 static void expr_sum(void)
8027 while (tok
== '+' || tok
== '-') {
8035 static void expr_shift(void)
8040 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
8048 static void expr_cmp(void)
8053 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
8054 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
8062 static void expr_cmpeq(void)
8067 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
8075 static void expr_and(void)
8078 while (tok
== '&') {
8085 static void expr_xor(void)
8088 while (tok
== '^') {
8095 static void expr_or(void)
8098 while (tok
== '|') {
8105 /* XXX: fix this mess */
8106 static void expr_land_const(void)
8109 while (tok
== TOK_LAND
) {
8116 /* XXX: fix this mess */
8117 static void expr_lor_const(void)
8120 while (tok
== TOK_LOR
) {
8127 /* only used if non constant */
8128 static void expr_land(void)
8133 if (tok
== TOK_LAND
) {
8138 if (tok
!= TOK_LAND
) {
8148 static void expr_lor(void)
8153 if (tok
== TOK_LOR
) {
8158 if (tok
!= TOK_LOR
) {
8168 /* XXX: better constant handling */
8169 static void expr_eq(void)
8171 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
8173 CType type
, type1
, type2
;
8180 boolean
.t
= VT_BOOL
;
8186 if (tok
!= ':' || !gnu_ext
) {
8201 if (vtop
!= vstack
) {
8202 /* needed to avoid having different registers saved in
8204 if (is_float(vtop
->type
.t
)) {
8206 #ifdef TCC_TARGET_X86_64
8207 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LDOUBLE
) {
8217 if (tok
== ':' && gnu_ext
) {
8225 sv
= *vtop
; /* save value to handle it later */
8226 vtop
--; /* no vpop so that FP stack is not flushed */
8234 bt1
= t1
& VT_BTYPE
;
8236 bt2
= t2
& VT_BTYPE
;
8237 /* cast operands to correct type according to ISOC rules */
8238 if (is_float(bt1
) || is_float(bt2
)) {
8239 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
8240 type
.t
= VT_LDOUBLE
;
8241 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
8246 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
8247 /* cast to biggest op */
8249 /* convert to unsigned if it does not fit in a long long */
8250 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
8251 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
8252 type
.t
|= VT_UNSIGNED
;
8253 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
8254 /* XXX: test pointer compatibility */
8256 } else if (bt1
== VT_FUNC
|| bt2
== VT_FUNC
) {
8257 /* XXX: test function pointer compatibility */
8259 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
8260 /* XXX: test structure compatibility */
8262 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
8263 /* NOTE: as an extension, we accept void on only one side */
8266 /* integer operations */
8268 /* convert to unsigned if it does not fit in an integer */
8269 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
8270 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
8271 type
.t
|= VT_UNSIGNED
;
8274 /* now we convert second operand */
8276 if (VT_STRUCT
== (vtop
->type
.t
& VT_BTYPE
))
8279 if (is_float(type
.t
)) {
8281 #ifdef TCC_TARGET_X86_64
8282 if ((type
.t
& VT_BTYPE
) == VT_LDOUBLE
) {
8286 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
8287 /* for long longs, we use fixed registers to avoid having
8288 to handle a complicated move */
8293 /* this is horrible, but we must also convert first
8297 /* put again first value and cast it */
8300 if (VT_STRUCT
== (vtop
->type
.t
& VT_BTYPE
))
8310 static void gexpr(void)
8321 /* parse an expression and return its type without any side effect. */
8322 static void expr_type(CType
*type
)
8324 int saved_nocode_wanted
;
8326 saved_nocode_wanted
= nocode_wanted
;
8331 nocode_wanted
= saved_nocode_wanted
;
8334 /* parse a unary expression and return its type without any side
8336 static void unary_type(CType
*type
)
8348 /* parse a constant expression and return value in vtop. */
8349 static void expr_const1(void)
8358 /* parse an integer constant and return its value. */
8359 static int expr_const(void)
8363 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
8364 expect("constant expression");
8370 /* return the label token if current token is a label, otherwise
8372 static int is_label(void)
8376 /* fast test first */
8377 if (tok
< TOK_UIDENT
)
8379 /* no need to save tokc because tok is an identifier */
8386 unget_tok(last_tok
);
8391 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
8392 int case_reg
, int is_expr
)
8397 /* generate line number info */
8399 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
8400 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
8402 last_line_num
= file
->line_num
;
8406 /* default return value is (void) */
8408 vtop
->type
.t
= VT_VOID
;
8411 if (tok
== TOK_IF
) {
8418 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
8420 if (c
== TOK_ELSE
) {
8424 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
8425 gsym(d
); /* patch else jmp */
8428 } else if (tok
== TOK_WHILE
) {
8436 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8440 } else if (tok
== '{') {
8444 /* record local declaration stack position */
8446 llabel
= local_label_stack
;
8447 /* handle local labels declarations */
8448 if (tok
== TOK_LABEL
) {
8451 if (tok
< TOK_UIDENT
)
8452 expect("label identifier");
8453 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
8463 while (tok
!= '}') {
8468 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8471 /* pop locally defined labels */
8472 label_pop(&local_label_stack
, llabel
);
8473 /* pop locally defined symbols */
8475 /* XXX: this solution makes only valgrind happy...
8476 triggered by gcc.c-torture/execute/20000917-1.c */
8478 switch(vtop
->type
.t
& VT_BTYPE
) {
8483 for(p
=vtop
->type
.ref
;p
;p
=p
->prev
)
8485 error("unsupported expression type");
8488 sym_pop(&local_stack
, s
);
8490 } else if (tok
== TOK_RETURN
) {
8494 gen_assign_cast(&func_vt
);
8495 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
8497 /* if returning structure, must copy it to implicit
8498 first pointer arg location */
8501 size
= type_size(&func_vt
,&align
);
8504 if((vtop
->r
!= (VT_LOCAL
| VT_LVAL
) || (vtop
->c
.i
& 3))
8508 loc
= (loc
- size
) & -4;
8511 vset(&type
, VT_LOCAL
| VT_LVAL
, addr
);
8514 vset(&int_type
, VT_LOCAL
| VT_LVAL
, addr
);
8516 vtop
->type
= int_type
;
8522 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
8525 /* copy structure value to pointer */
8530 } else if (is_float(func_vt
.t
)) {
8535 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
8538 rsym
= gjmp(rsym
); /* jmp */
8539 } else if (tok
== TOK_BREAK
) {
8542 error("cannot break");
8543 *bsym
= gjmp(*bsym
);
8546 } else if (tok
== TOK_CONTINUE
) {
8549 error("cannot continue");
8550 *csym
= gjmp(*csym
);
8553 } else if (tok
== TOK_FOR
) {
8580 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8585 if (tok
== TOK_DO
) {
8590 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8601 if (tok
== TOK_SWITCH
) {
8605 /* XXX: other types than integer */
8606 case_reg
= gv(RC_INT
);
8610 b
= gjmp(0); /* jump to first case */
8612 block(&a
, csym
, &b
, &c
, case_reg
, 0);
8613 /* if no default, jmp after switch */
8621 if (tok
== TOK_CASE
) {
8628 if (gnu_ext
&& tok
== TOK_DOTS
) {
8632 warning("empty case range");
8634 /* since a case is like a label, we must skip it with a jmp */
8641 *case_sym
= gtst(1, 0);
8644 *case_sym
= gtst(1, 0);
8648 *case_sym
= gtst(1, *case_sym
);
8653 goto block_after_label
;
8655 if (tok
== TOK_DEFAULT
) {
8661 error("too many 'default'");
8664 goto block_after_label
;
8666 if (tok
== TOK_GOTO
) {
8668 if (tok
== '*' && gnu_ext
) {
8672 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
8675 } else if (tok
>= TOK_UIDENT
) {
8676 s
= label_find(tok
);
8677 /* put forward definition if needed */
8679 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
8681 if (s
->r
== LABEL_DECLARED
)
8682 s
->r
= LABEL_FORWARD
;
8684 /* label already defined */
8685 if (s
->r
& LABEL_FORWARD
)
8686 s
->next
= (void *)gjmp((long)s
->next
);
8688 gjmp_addr((long)s
->next
);
8691 expect("label identifier");
8694 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
8702 if (s
->r
== LABEL_DEFINED
)
8703 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
8704 gsym((long)s
->next
);
8705 s
->r
= LABEL_DEFINED
;
8707 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
8709 s
->next
= (void *)ind
;
8710 /* we accept this, but it is a mistake */
8713 warning("deprecated use of label at end of compound statement");
8717 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8720 /* expression case */
8735 /* t is the array or struct type. c is the array or struct
8736 address. cur_index/cur_field is the pointer to the current
8737 value. 'size_only' is true if only size info is needed (only used
8739 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
8740 int *cur_index
, Sym
**cur_field
,
8744 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
8750 if (gnu_ext
&& (l
= is_label()) != 0)
8752 while (tok
== '[' || tok
== '.') {
8754 if (!(type
->t
& VT_ARRAY
))
8755 expect("array type");
8758 index
= expr_const();
8759 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
8760 expect("invalid index");
8761 if (tok
== TOK_DOTS
&& gnu_ext
) {
8763 index_last
= expr_const();
8764 if (index_last
< 0 ||
8765 (s
->c
>= 0 && index_last
>= s
->c
) ||
8767 expect("invalid index");
8773 *cur_index
= index_last
;
8774 type
= pointed_type(type
);
8775 elem_size
= type_size(type
, &align
);
8776 c
+= index
* elem_size
;
8777 /* NOTE: we only support ranges for last designator */
8778 nb_elems
= index_last
- index
+ 1;
8779 if (nb_elems
!= 1) {
8788 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
8789 expect("struct/union type");
8802 /* XXX: fix this mess by using explicit storage field */
8804 type1
.t
|= (type
->t
& ~VT_TYPE
);
8818 if (type
->t
& VT_ARRAY
) {
8820 type
= pointed_type(type
);
8821 c
+= index
* type_size(type
, &align
);
8825 error("too many field init");
8826 /* XXX: fix this mess by using explicit storage field */
8828 type1
.t
|= (type
->t
& ~VT_TYPE
);
8833 decl_initializer(type
, sec
, c
, 0, size_only
);
8835 /* XXX: make it more general */
8836 if (!size_only
&& nb_elems
> 1) {
8837 unsigned long c_end
;
8842 error("range init not supported yet for dynamic storage");
8843 c_end
= c
+ nb_elems
* elem_size
;
8844 if (c_end
> sec
->data_allocated
)
8845 section_realloc(sec
, c_end
);
8846 src
= sec
->data
+ c
;
8848 for(i
= 1; i
< nb_elems
; i
++) {
8850 memcpy(dst
, src
, elem_size
);
8856 #define EXPR_CONST 1
8859 /* store a value or an expression directly in global data or in local array */
8860 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
8861 int v
, int expr_type
)
8863 int saved_global_expr
, bt
, bit_pos
, bit_size
;
8865 unsigned long long bit_mask
;
8873 /* compound literals must be allocated globally in this case */
8874 saved_global_expr
= global_expr
;
8877 global_expr
= saved_global_expr
;
8878 /* NOTE: symbols are accepted */
8879 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
8880 error("initializer element is not constant");
8888 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
8891 /* XXX: not portable */
8892 /* XXX: generate error if incorrect relocation */
8893 gen_assign_cast(&dtype
);
8894 bt
= type
->t
& VT_BTYPE
;
8895 /* we'll write at most 12 bytes */
8896 if (c
+ 12 > sec
->data_allocated
) {
8897 section_realloc(sec
, c
+ 12);
8899 ptr
= sec
->data
+ c
;
8900 /* XXX: make code faster ? */
8901 if (!(type
->t
& VT_BITFIELD
)) {
8906 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
8907 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
8908 bit_mask
= (1LL << bit_size
) - 1;
8910 if ((vtop
->r
& VT_SYM
) &&
8916 (bt
== VT_INT
&& bit_size
!= 32)))
8917 error("initializer element is not computable at load time");
8920 vtop
->c
.i
= (vtop
->c
.i
!= 0);
8922 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8925 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8928 *(double *)ptr
= vtop
->c
.d
;
8931 *(long double *)ptr
= vtop
->c
.ld
;
8934 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
8937 if (vtop
->r
& VT_SYM
) {
8938 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
8940 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8945 vset(&dtype
, VT_LOCAL
|VT_LVAL
, c
);
8952 /* put zeros for variable based init */
8953 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
8956 /* nothing to do because globals are already set to zero */
8958 vpush_global_sym(&func_old_type
, TOK_memset
);
8966 /* 't' contains the type and storage info. 'c' is the offset of the
8967 object in section 'sec'. If 'sec' is NULL, it means stack based
8968 allocation. 'first' is true if array '{' must be read (multi
8969 dimension implicit array init handling). 'size_only' is true if
8970 size only evaluation is wanted (only for arrays). */
8971 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
8972 int first
, int size_only
)
8974 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
8975 int size1
, align1
, expr_type
;
8979 if (type
->t
& VT_ARRAY
) {
8983 t1
= pointed_type(type
);
8984 size1
= type_size(t1
, &align1
);
8987 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
8993 /* only parse strings here if correct type (otherwise: handle
8994 them as ((w)char *) expressions */
8995 if ((tok
== TOK_LSTR
&&
8996 #ifdef TCC_TARGET_PE
8997 (t1
->t
& VT_BTYPE
) == VT_SHORT
&& (t1
->t
& VT_UNSIGNED
)
8999 (t1
->t
& VT_BTYPE
) == VT_INT
9001 ) || (tok
== TOK_STR
&& (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
9002 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
9007 /* compute maximum number of chars wanted */
9009 cstr_len
= cstr
->size
;
9011 cstr_len
= cstr
->size
/ sizeof(nwchar_t
);
9014 if (n
>= 0 && nb
> (n
- array_length
))
9015 nb
= n
- array_length
;
9018 warning("initializer-string for array is too long");
9019 /* in order to go faster for common case (char
9020 string in global variable, we handle it
9022 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
9023 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
9027 ch
= ((unsigned char *)cstr
->data
)[i
];
9029 ch
= ((nwchar_t
*)cstr
->data
)[i
];
9030 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
9038 /* only add trailing zero if enough storage (no
9039 warning in this case since it is standard) */
9040 if (n
< 0 || array_length
< n
) {
9042 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
9048 while (tok
!= '}') {
9049 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
9050 if (n
>= 0 && index
>= n
)
9051 error("index too large");
9052 /* must put zero in holes (note that doing it that way
9053 ensures that it even works with designators) */
9054 if (!size_only
&& array_length
< index
) {
9055 init_putz(t1
, sec
, c
+ array_length
* size1
,
9056 (index
- array_length
) * size1
);
9059 if (index
> array_length
)
9060 array_length
= index
;
9061 /* special test for multi dimensional arrays (may not
9062 be strictly correct if designators are used at the
9064 if (index
>= n
&& no_oblock
)
9073 /* put zeros at the end */
9074 if (!size_only
&& n
>= 0 && array_length
< n
) {
9075 init_putz(t1
, sec
, c
+ array_length
* size1
,
9076 (n
- array_length
) * size1
);
9078 /* patch type size if needed */
9080 s
->c
= array_length
;
9081 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
9082 (sec
|| !first
|| tok
== '{')) {
9085 /* NOTE: the previous test is a specific case for automatic
9086 struct/union init */
9087 /* XXX: union needs only one init */
9089 /* XXX: this test is incorrect for local initializers
9090 beginning with ( without {. It would be much more difficult
9091 to do it correctly (ideally, the expression parser should
9092 be used in all cases) */
9098 while (tok
== '(') {
9102 if (!parse_btype(&type1
, &ad1
))
9104 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
9106 if (!is_assignable_types(type
, &type1
))
9107 error("invalid type for cast");
9112 if (first
|| tok
== '{') {
9121 while (tok
!= '}') {
9122 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
9124 if (!size_only
&& array_length
< index
) {
9125 init_putz(type
, sec
, c
+ array_length
,
9126 index
- array_length
);
9128 index
= index
+ type_size(&f
->type
, &align1
);
9129 if (index
> array_length
)
9130 array_length
= index
;
9132 if (no_oblock
&& f
== NULL
)
9138 /* put zeros at the end */
9139 if (!size_only
&& array_length
< n
) {
9140 init_putz(type
, sec
, c
+ array_length
,
9149 } else if (tok
== '{') {
9151 decl_initializer(type
, sec
, c
, first
, size_only
);
9153 } else if (size_only
) {
9154 /* just skip expression */
9156 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
9160 else if (tok
== ')')
9165 /* currently, we always use constant expression for globals
9166 (may change for scripting case) */
9167 expr_type
= EXPR_CONST
;
9169 expr_type
= EXPR_ANY
;
9170 init_putv(type
, sec
, c
, 0, expr_type
);
9174 /* parse an initializer for type 't' if 'has_init' is non zero, and
9175 allocate space in local or global data space ('r' is either
9176 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
9177 variable 'v' of scope 'scope' is declared before initializers are
9178 parsed. If 'v' is zero, then a reference to the new object is put
9179 in the value stack. If 'has_init' is 2, a special parsing is done
9180 to handle string constants. */
9181 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
9182 int has_init
, int v
, int scope
)
9184 int size
, align
, addr
, data_offset
;
9186 ParseState saved_parse_state
;
9187 TokenString init_str
;
9190 size
= type_size(type
, &align
);
9191 /* If unknown size, we must evaluate it before
9192 evaluating initializers because
9193 initializers can generate global data too
9194 (e.g. string pointers or ISOC99 compound
9195 literals). It also simplifies local
9196 initializers handling */
9197 tok_str_new(&init_str
);
9200 error("unknown type size");
9201 /* get all init string */
9202 if (has_init
== 2) {
9203 /* only get strings */
9204 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
9205 tok_str_add_tok(&init_str
);
9210 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
9212 error("unexpected end of file in initializer");
9213 tok_str_add_tok(&init_str
);
9216 else if (tok
== '}') {
9226 tok_str_add(&init_str
, -1);
9227 tok_str_add(&init_str
, 0);
9230 save_parse_state(&saved_parse_state
);
9232 macro_ptr
= init_str
.str
;
9234 decl_initializer(type
, NULL
, 0, 1, 1);
9235 /* prepare second initializer parsing */
9236 macro_ptr
= init_str
.str
;
9239 /* if still unknown size, error */
9240 size
= type_size(type
, &align
);
9242 error("unknown type size");
9244 /* take into account specified alignment if bigger */
9246 if (ad
->aligned
> align
)
9247 align
= ad
->aligned
;
9248 } else if (ad
->packed
) {
9251 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
9253 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
9255 loc
= (loc
- size
) & -align
;
9257 /* handles bounds */
9258 /* XXX: currently, since we do only one pass, we cannot track
9259 '&' operators, so we add only arrays */
9260 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
9261 unsigned long *bounds_ptr
;
9262 /* add padding between regions */
9264 /* then add local bound info */
9265 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
9266 bounds_ptr
[0] = addr
;
9267 bounds_ptr
[1] = size
;
9270 /* local variable */
9271 sym_push(v
, type
, r
, addr
);
9273 /* push local reference */
9274 vset(type
, r
, addr
);
9280 if (v
&& scope
== VT_CONST
) {
9281 /* see if the symbol was already defined */
9284 if (!is_compatible_types(&sym
->type
, type
))
9285 error("incompatible types for redefinition of '%s'",
9286 get_tok_str(v
, NULL
));
9287 if (sym
->type
.t
& VT_EXTERN
) {
9288 /* if the variable is extern, it was not allocated */
9289 sym
->type
.t
&= ~VT_EXTERN
;
9290 /* set array size if it was ommited in extern
9292 if ((sym
->type
.t
& VT_ARRAY
) &&
9293 sym
->type
.ref
->c
< 0 &&
9295 sym
->type
.ref
->c
= type
->ref
->c
;
9297 /* we accept several definitions of the same
9298 global variable. this is tricky, because we
9299 must play with the SHN_COMMON type of the symbol */
9300 /* XXX: should check if the variable was already
9301 initialized. It is incorrect to initialized it
9303 /* no init data, we won't add more to the symbol */
9310 /* allocate symbol in corresponding section */
9315 else if (tcc_state
->nocommon
)
9319 data_offset
= sec
->data_offset
;
9320 data_offset
= (data_offset
+ align
- 1) & -align
;
9322 /* very important to increment global pointer at this time
9323 because initializers themselves can create new initializers */
9324 data_offset
+= size
;
9325 /* add padding if bound check */
9326 if (do_bounds_check
)
9328 sec
->data_offset
= data_offset
;
9329 /* allocate section space to put the data */
9330 if (sec
->sh_type
!= SHT_NOBITS
&&
9331 data_offset
> sec
->data_allocated
)
9332 section_realloc(sec
, data_offset
);
9333 /* align section if needed */
9334 if (align
> sec
->sh_addralign
)
9335 sec
->sh_addralign
= align
;
9337 addr
= 0; /* avoid warning */
9341 if (scope
!= VT_CONST
|| !sym
) {
9342 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
9344 /* update symbol definition */
9346 put_extern_sym(sym
, sec
, addr
, size
);
9349 /* put a common area */
9350 put_extern_sym(sym
, NULL
, align
, size
);
9351 /* XXX: find a nicer way */
9352 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
9353 esym
->st_shndx
= SHN_COMMON
;
9358 /* push global reference */
9359 sym
= get_sym_ref(type
, sec
, addr
, size
);
9361 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
9365 /* handles bounds now because the symbol must be defined
9366 before for the relocation */
9367 if (do_bounds_check
) {
9368 unsigned long *bounds_ptr
;
9370 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
9371 /* then add global bound info */
9372 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
9373 bounds_ptr
[0] = 0; /* relocated */
9374 bounds_ptr
[1] = size
;
9378 decl_initializer(type
, sec
, addr
, 1, 0);
9379 /* restore parse state if needed */
9381 tok_str_free(init_str
.str
);
9382 restore_parse_state(&saved_parse_state
);
9388 void put_func_debug(Sym
*sym
)
9393 /* XXX: we put here a dummy type */
9394 snprintf(buf
, sizeof(buf
), "%s:%c1",
9395 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
9396 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
9397 cur_text_section
, sym
->c
);
9398 /* //gr gdb wants a line at the function */
9399 put_stabn(N_SLINE
, 0, file
->line_num
, 0);
9404 /* parse an old style function declaration list */
9405 /* XXX: check multiple parameter */
9406 static void func_decl_list(Sym
*func_sym
)
9413 /* parse each declaration */
9414 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
9415 if (!parse_btype(&btype
, &ad
))
9416 expect("declaration list");
9417 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
9418 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
9420 /* we accept no variable after */
9424 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
9425 /* find parameter in function parameter list */
9428 if ((s
->v
& ~SYM_FIELD
) == v
)
9432 error("declaration for parameter '%s' but no such parameter",
9433 get_tok_str(v
, NULL
));
9435 /* check that no storage specifier except 'register' was given */
9436 if (type
.t
& VT_STORAGE
)
9437 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
9438 convert_parameter_type(&type
);
9439 /* we can add the type (NOTE: it could be local to the function) */
9441 /* accept other parameters */
9452 /* parse a function defined by symbol 'sym' and generate its code in
9453 'cur_text_section' */
9454 static void gen_function(Sym
*sym
)
9456 int saved_nocode_wanted
= nocode_wanted
;
9458 ind
= cur_text_section
->data_offset
;
9459 /* NOTE: we patch the symbol size later */
9460 put_extern_sym(sym
, cur_text_section
, ind
, 0);
9461 funcname
= get_tok_str(sym
->v
, NULL
);
9463 /* put debug symbol */
9465 put_func_debug(sym
);
9466 /* push a dummy symbol to enable local sym storage */
9467 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
9468 gfunc_prolog(&sym
->type
);
9470 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
9473 cur_text_section
->data_offset
= ind
;
9474 label_pop(&global_label_stack
, NULL
);
9475 sym_pop(&local_stack
, NULL
); /* reset local stack */
9476 /* end of function */
9477 /* patch symbol size */
9478 ((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
].st_size
=
9481 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
9483 /* It's better to crash than to generate wrong code */
9484 cur_text_section
= NULL
;
9485 funcname
= ""; /* for safety */
9486 func_vt
.t
= VT_VOID
; /* for safety */
9487 ind
= 0; /* for safety */
9488 nocode_wanted
= saved_nocode_wanted
;
9491 static void gen_inline_functions(void)
9495 int *str
, inline_generated
;
9497 /* iterate while inline function are referenced */
9499 inline_generated
= 0;
9500 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
9502 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
9503 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
9504 (VT_STATIC
| VT_INLINE
) &&
9506 /* the function was used: generate its code and
9507 convert it to a normal function */
9508 str
= INLINE_DEF(sym
->r
);
9509 sym
->r
= VT_SYM
| VT_CONST
;
9510 sym
->type
.t
&= ~VT_INLINE
;
9514 cur_text_section
= text_section
;
9516 macro_ptr
= NULL
; /* fail safe */
9519 inline_generated
= 1;
9522 if (!inline_generated
)
9526 /* free all remaining inline function tokens */
9527 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
9529 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
9530 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
9531 (VT_STATIC
| VT_INLINE
)) {
9532 //gr printf("sym %d %s\n", sym->r, get_tok_str(sym->v, NULL));
9533 if (sym
->r
== (VT_SYM
| VT_CONST
)) //gr beware!
9535 str
= INLINE_DEF(sym
->r
);
9537 sym
->r
= 0; /* fail safe */
9542 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
9543 static void decl(int l
)
9551 if (!parse_btype(&btype
, &ad
)) {
9552 /* skip redundant ';' */
9553 /* XXX: find more elegant solution */
9558 if (l
== VT_CONST
&&
9559 (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
)) {
9560 /* global asm block */
9564 /* special test for old K&R protos without explicit int
9565 type. Only accepted when defining global data */
9566 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
9570 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
9571 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
9573 /* we accept no variable after */
9577 while (1) { /* iterate thru each declaration */
9579 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
9583 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
9584 printf("type = '%s'\n", buf
);
9587 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9588 /* if old style function prototype, we accept a
9591 if (sym
->c
== FUNC_OLD
)
9592 func_decl_list(sym
);
9597 error("cannot use local functions");
9598 if ((type
.t
& VT_BTYPE
) != VT_FUNC
)
9599 expect("function definition");
9601 /* reject abstract declarators in function definition */
9603 while ((sym
= sym
->next
) != NULL
)
9604 if (!(sym
->v
& ~SYM_FIELD
))
9605 expect("identifier");
9607 /* XXX: cannot do better now: convert extern line to static inline */
9608 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
9609 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
9613 if ((sym
->type
.t
& VT_BTYPE
) != VT_FUNC
)
9615 /* specific case: if not func_call defined, we put
9616 the one of the prototype */
9617 /* XXX: should have default value */
9618 r
= sym
->type
.ref
->r
;
9619 if (FUNC_CALL(r
) != FUNC_CDECL
9620 && FUNC_CALL(type
.ref
->r
) == FUNC_CDECL
)
9621 FUNC_CALL(type
.ref
->r
) = FUNC_CALL(r
);
9623 FUNC_EXPORT(type
.ref
->r
) = 1;
9625 if (!is_compatible_types(&sym
->type
, &type
)) {
9627 error("incompatible types for redefinition of '%s'",
9628 get_tok_str(v
, NULL
));
9630 /* if symbol is already defined, then put complete type */
9633 /* put function symbol */
9634 sym
= global_identifier_push(v
, type
.t
, 0);
9635 sym
->type
.ref
= type
.ref
;
9638 /* static inline functions are just recorded as a kind
9639 of macro. Their code will be emitted at the end of
9640 the compilation unit only if they are used */
9641 if ((type
.t
& (VT_INLINE
| VT_STATIC
)) ==
9642 (VT_INLINE
| VT_STATIC
)) {
9643 TokenString func_str
;
9646 tok_str_new(&func_str
);
9652 error("unexpected end of file");
9653 tok_str_add_tok(&func_str
);
9658 } else if (t
== '}') {
9660 if (block_level
== 0)
9664 tok_str_add(&func_str
, -1);
9665 tok_str_add(&func_str
, 0);
9666 INLINE_DEF(sym
->r
) = func_str
.str
;
9668 /* compute text section */
9669 cur_text_section
= ad
.section
;
9670 if (!cur_text_section
)
9671 cur_text_section
= text_section
;
9672 sym
->r
= VT_SYM
| VT_CONST
;
9677 if (btype
.t
& VT_TYPEDEF
) {
9678 /* save typedefed type */
9679 /* XXX: test storage specifiers ? */
9680 sym
= sym_push(v
, &type
, 0, 0);
9681 sym
->type
.t
|= VT_TYPEDEF
;
9682 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9683 /* external function definition */
9684 /* specific case for func_call attribute */
9686 type
.ref
->r
= ad
.func_attr
;
9687 external_sym(v
, &type
, 0);
9689 /* not lvalue if array */
9691 if (!(type
.t
& VT_ARRAY
))
9692 r
|= lvalue_type(type
.t
);
9693 has_init
= (tok
== '=');
9694 if ((btype
.t
& VT_EXTERN
) ||
9695 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
9696 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
9697 /* external variable */
9698 /* NOTE: as GCC, uninitialized global static
9699 arrays of null size are considered as
9701 external_sym(v
, &type
, r
);
9703 type
.t
|= (btype
.t
& VT_STATIC
); /* Retain "static". */
9704 if (type
.t
& VT_STATIC
)
9710 decl_initializer_alloc(&type
, &ad
, r
,
9724 /* better than nothing, but needs extension to handle '-E' option
9726 static void preprocess_init(TCCState
*s1
)
9728 s1
->include_stack_ptr
= s1
->include_stack
;
9729 /* XXX: move that before to avoid having to initialize
9730 file->ifdef_stack_ptr ? */
9731 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
9732 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
9734 /* XXX: not ANSI compliant: bound checking says error */
9736 s1
->pack_stack
[0] = 0;
9737 s1
->pack_stack_ptr
= s1
->pack_stack
;
9740 /* compile the C file opened in 'file'. Return non zero if errors. */
9741 static int tcc_compile(TCCState
*s1
)
9745 volatile int section_sym
;
9748 printf("%s: **** new file\n", file
->filename
);
9750 preprocess_init(s1
);
9752 cur_text_section
= NULL
;
9754 anon_sym
= SYM_FIRST_ANOM
;
9756 /* file info: full path + filename */
9757 section_sym
= 0; /* avoid warning */
9759 section_sym
= put_elf_sym(symtab_section
, 0, 0,
9760 ELFW(ST_INFO
)(STB_LOCAL
, STT_SECTION
), 0,
9761 text_section
->sh_num
, NULL
);
9762 getcwd(buf
, sizeof(buf
));
9764 normalize_slashes(buf
);
9766 pstrcat(buf
, sizeof(buf
), "/");
9767 put_stabs_r(buf
, N_SO
, 0, 0,
9768 text_section
->data_offset
, text_section
, section_sym
);
9769 put_stabs_r(file
->filename
, N_SO
, 0, 0,
9770 text_section
->data_offset
, text_section
, section_sym
);
9772 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
9773 symbols can be safely used */
9774 put_elf_sym(symtab_section
, 0, 0,
9775 ELFW(ST_INFO
)(STB_LOCAL
, STT_FILE
), 0,
9776 SHN_ABS
, file
->filename
);
9778 /* define some often used types */
9779 int_type
.t
= VT_INT
;
9781 char_pointer_type
.t
= VT_BYTE
;
9782 mk_pointer(&char_pointer_type
);
9784 func_old_type
.t
= VT_FUNC
;
9785 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
9787 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
9788 float_type
.t
= VT_FLOAT
;
9789 double_type
.t
= VT_DOUBLE
;
9791 func_float_type
.t
= VT_FUNC
;
9792 func_float_type
.ref
= sym_push(SYM_FIELD
, &float_type
, FUNC_CDECL
, FUNC_OLD
);
9793 func_double_type
.t
= VT_FUNC
;
9794 func_double_type
.ref
= sym_push(SYM_FIELD
, &double_type
, FUNC_CDECL
, FUNC_OLD
);
9798 /* define 'void *alloca(unsigned int)' builtin function */
9803 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
9804 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
9807 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
9811 define_start
= define_stack
;
9814 if (setjmp(s1
->error_jmp_buf
) == 0) {
9816 s1
->error_set_jmp_enabled
= 1;
9818 ch
= file
->buf_ptr
[0];
9819 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9820 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
9824 expect("declaration");
9826 /* end of translation unit info */
9828 put_stabs_r(NULL
, N_SO
, 0, 0,
9829 text_section
->data_offset
, text_section
, section_sym
);
9832 s1
->error_set_jmp_enabled
= 0;
9834 /* reset define stack, but leave -Dsymbols (may be incorrect if
9835 they are undefined) */
9836 free_defines(define_start
);
9838 gen_inline_functions();
9840 sym_pop(&global_stack
, NULL
);
9841 sym_pop(&local_stack
, NULL
);
9843 return s1
->nb_errors
!= 0 ? -1 : 0;
9846 /* Preprocess the current file */
9847 /* XXX: add line and file infos,
9848 * XXX: add options to preserve spaces (partly done, only spaces in macro are
9851 static int tcc_preprocess(TCCState
*s1
)
9854 BufferedFile
*file_ref
;
9855 int token_seen
, line_ref
;
9857 preprocess_init(s1
);
9858 define_start
= define_stack
;
9859 ch
= file
->buf_ptr
[0];
9861 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9862 parse_flags
= PARSE_FLAG_ASM_COMMENTS
| PARSE_FLAG_PREPROCESS
|
9863 PARSE_FLAG_LINEFEED
;
9871 if (tok
== TOK_EOF
) {
9873 } else if (tok
== TOK_LINEFEED
) {
9878 } else if (token_seen
) {
9879 fwrite(tok_spaces
.data
, tok_spaces
.size
, 1, s1
->outfile
);
9881 int d
= file
->line_num
- line_ref
;
9882 if (file
!= file_ref
|| d
< 0 || d
>= 8)
9883 fprintf(s1
->outfile
, "# %d \"%s\"\n", file
->line_num
, file
->filename
);
9886 fputs("\n", s1
->outfile
), --d
;
9887 line_ref
= (file_ref
= file
)->line_num
;
9890 fputs(get_tok_str(tok
, &tokc
), s1
->outfile
);
9892 free_defines(define_start
);
9897 int tcc_compile_string(TCCState
*s
, const char *str
)
9899 BufferedFile bf1
, *bf
= &bf1
;
9903 /* init file structure */
9905 /* XXX: avoid copying */
9907 buf
= tcc_malloc(len
+ 1);
9910 memcpy(buf
, str
, len
);
9913 bf
->buf_end
= buf
+ len
;
9914 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
9917 ret
= tcc_compile(s
);
9921 /* currently, no need to close */
9926 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9927 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
9929 BufferedFile bf1
, *bf
= &bf1
;
9931 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
9932 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
9936 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
9938 /* init file structure */
9940 bf
->buf_ptr
= bf
->buffer
;
9941 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
9942 *bf
->buf_end
= CH_EOB
;
9943 bf
->filename
[0] = '\0';
9947 s1
->include_stack_ptr
= s1
->include_stack
;
9949 /* parse with define parser */
9950 ch
= file
->buf_ptr
[0];
9956 /* undefine a preprocessor symbol */
9957 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
9961 ts
= tok_alloc(sym
, strlen(sym
));
9962 s
= define_find(ts
->tok
);
9963 /* undefine symbol by putting an invalid name */
9968 #ifdef CONFIG_TCC_ASM
9970 #ifdef TCC_TARGET_I386
9971 #include "i386-asm.c"
9976 static void asm_instr(void)
9978 error("inline asm() not supported");
9980 static void asm_global_instr(void)
9982 error("inline asm() not supported");
9988 #ifdef TCC_TARGET_COFF
9989 #include "tcccoff.c"
9992 #ifdef TCC_TARGET_PE
9996 /* print the position in the source file of PC value 'pc' by reading
9997 the stabs debug information */
9998 static void rt_printline(unsigned long wanted_pc
)
10000 Stab_Sym
*sym
, *sym_end
;
10001 char func_name
[128], last_func_name
[128];
10002 unsigned long func_addr
, last_pc
, pc
;
10003 const char *incl_files
[INCLUDE_STACK_SIZE
];
10004 int incl_index
, len
, last_line_num
, i
;
10005 const char *str
, *p
;
10007 fprintf(stderr
, "0x%08lx:", wanted_pc
);
10009 func_name
[0] = '\0';
10012 last_func_name
[0] = '\0';
10013 last_pc
= 0xffffffff;
10015 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
10016 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
10017 while (sym
< sym_end
) {
10018 switch(sym
->n_type
) {
10019 /* function start or end */
10021 if (sym
->n_strx
== 0) {
10022 /* we test if between last line and end of function */
10023 pc
= sym
->n_value
+ func_addr
;
10024 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
10026 func_name
[0] = '\0';
10029 str
= stabstr_section
->data
+ sym
->n_strx
;
10030 p
= strchr(str
, ':');
10032 pstrcpy(func_name
, sizeof(func_name
), str
);
10035 if (len
> sizeof(func_name
) - 1)
10036 len
= sizeof(func_name
) - 1;
10037 memcpy(func_name
, str
, len
);
10038 func_name
[len
] = '\0';
10040 func_addr
= sym
->n_value
;
10043 /* line number info */
10045 pc
= sym
->n_value
+ func_addr
;
10046 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
10049 last_line_num
= sym
->n_desc
;
10051 strcpy(last_func_name
, func_name
);
10053 /* include files */
10055 str
= stabstr_section
->data
+ sym
->n_strx
;
10057 if (incl_index
< INCLUDE_STACK_SIZE
) {
10058 incl_files
[incl_index
++] = str
;
10062 if (incl_index
> 1)
10066 if (sym
->n_strx
== 0) {
10067 incl_index
= 0; /* end of translation unit */
10069 str
= stabstr_section
->data
+ sym
->n_strx
;
10070 /* do not add path */
10072 if (len
> 0 && str
[len
- 1] != '/')
10080 /* second pass: we try symtab symbols (no line number info) */
10083 ElfW(Sym
) *sym
, *sym_end
;
10086 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
10087 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
10090 type
= ELFW(ST_TYPE
)(sym
->st_info
);
10091 if (type
== STT_FUNC
) {
10092 if (wanted_pc
>= sym
->st_value
&&
10093 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
10094 pstrcpy(last_func_name
, sizeof(last_func_name
),
10095 strtab_section
->data
+ sym
->st_name
);
10101 /* did not find any info: */
10102 fprintf(stderr
, " ???\n");
10105 if (last_func_name
[0] != '\0') {
10106 fprintf(stderr
, " %s()", last_func_name
);
10108 if (incl_index
> 0) {
10109 fprintf(stderr
, " (%s:%d",
10110 incl_files
[incl_index
- 1], last_line_num
);
10111 for(i
= incl_index
- 2; i
>= 0; i
--)
10112 fprintf(stderr
, ", included from %s", incl_files
[i
]);
10113 fprintf(stderr
, ")");
10115 fprintf(stderr
, "\n");
10118 #if !defined(_WIN32) && !defined(CONFIG_TCCBOOT)
10122 /* fix for glibc 2.1 */
10124 #define REG_EIP EIP
10125 #define REG_EBP EBP
10128 /* return the PC at frame level 'level'. Return non zero if not found */
10129 static int rt_get_caller_pc(unsigned long *paddr
,
10130 ucontext_t
*uc
, int level
)
10136 #if defined(__FreeBSD__)
10137 *paddr
= uc
->uc_mcontext
.mc_eip
;
10138 #elif defined(__dietlibc__)
10139 *paddr
= uc
->uc_mcontext
.eip
;
10141 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
10145 #if defined(__FreeBSD__)
10146 fp
= uc
->uc_mcontext
.mc_ebp
;
10147 #elif defined(__dietlibc__)
10148 fp
= uc
->uc_mcontext
.ebp
;
10150 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
10152 for(i
=1;i
<level
;i
++) {
10153 /* XXX: check address validity with program info */
10154 if (fp
<= 0x1000 || fp
>= 0xc0000000)
10156 fp
= ((unsigned long *)fp
)[0];
10158 *paddr
= ((unsigned long *)fp
)[1];
10162 #elif defined(__x86_64__)
10163 /* return the PC at frame level 'level'. Return non zero if not found */
10164 static int rt_get_caller_pc(unsigned long *paddr
,
10165 ucontext_t
*uc
, int level
)
10171 /* XXX: only support linux */
10172 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
10175 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
10176 for(i
=1;i
<level
;i
++) {
10177 /* XXX: check address validity with program info */
10178 if (fp
<= 0x1000 || fp
>= 0xc0000000)
10180 fp
= ((unsigned long *)fp
)[0];
10182 *paddr
= ((unsigned long *)fp
)[1];
10188 #warning add arch specific rt_get_caller_pc()
10190 static int rt_get_caller_pc(unsigned long *paddr
,
10191 ucontext_t
*uc
, int level
)
10197 /* emit a run time error at position 'pc' */
10198 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
10205 fprintf(stderr
, "Runtime error: ");
10206 vfprintf(stderr
, fmt
, ap
);
10207 fprintf(stderr
, "\n");
10208 for(i
=0;i
<num_callers
;i
++) {
10209 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
10212 fprintf(stderr
, "at ");
10214 fprintf(stderr
, "by ");
10221 /* signal handler for fatal errors */
10222 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
10224 ucontext_t
*uc
= puc
;
10228 switch(siginf
->si_code
) {
10231 rt_error(uc
, "division by zero");
10234 rt_error(uc
, "floating point exception");
10240 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
10241 rt_error(uc
, *rt_bound_error_msg
);
10243 rt_error(uc
, "dereferencing invalid pointer");
10246 rt_error(uc
, "illegal instruction");
10249 rt_error(uc
, "abort() called");
10252 rt_error(uc
, "caught signal %d", signum
);
10259 /* do all relocations (needed before using tcc_get_symbol()) */
10260 int tcc_relocate(TCCState
*s1
)
10267 #ifdef TCC_TARGET_PE
10268 pe_add_runtime(s1
);
10270 tcc_add_runtime(s1
);
10273 relocate_common_syms();
10275 tcc_add_linker_symbols(s1
);
10276 #ifndef TCC_TARGET_PE
10277 build_got_entries(s1
);
10279 /* compute relocation address : section are relocated in place. We
10280 also alloc the bss space */
10281 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10282 s
= s1
->sections
[i
];
10283 if (s
->sh_flags
& SHF_ALLOC
) {
10284 if (s
->sh_type
== SHT_NOBITS
)
10285 s
->data
= tcc_mallocz(s
->data_offset
);
10286 s
->sh_addr
= (unsigned long)s
->data
;
10290 relocate_syms(s1
, 1);
10292 if (s1
->nb_errors
!= 0)
10295 /* relocate each section */
10296 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10297 s
= s1
->sections
[i
];
10299 relocate_section(s1
, s
);
10302 /* mark executable sections as executable in memory */
10303 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10304 s
= s1
->sections
[i
];
10305 if ((s
->sh_flags
& (SHF_ALLOC
| SHF_EXECINSTR
)) ==
10306 (SHF_ALLOC
| SHF_EXECINSTR
))
10307 set_pages_executable(s
->data
, s
->data_offset
);
10312 /* launch the compiled program with the given arguments */
10313 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
10315 int (*prog_main
)(int, char **);
10317 if (tcc_relocate(s1
) < 0)
10320 prog_main
= tcc_get_symbol_err(s1
, "main");
10323 #if defined(_WIN32) || defined(CONFIG_TCCBOOT)
10324 error("debug mode currently not available for Windows");
10326 struct sigaction sigact
;
10327 /* install TCC signal handlers to print debug info on fatal
10329 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
10330 sigact
.sa_sigaction
= sig_error
;
10331 sigemptyset(&sigact
.sa_mask
);
10332 sigaction(SIGFPE
, &sigact
, NULL
);
10333 sigaction(SIGILL
, &sigact
, NULL
);
10334 sigaction(SIGSEGV
, &sigact
, NULL
);
10335 sigaction(SIGBUS
, &sigact
, NULL
);
10336 sigaction(SIGABRT
, &sigact
, NULL
);
10340 #ifdef CONFIG_TCC_BCHECK
10341 if (do_bounds_check
) {
10342 void (*bound_init
)(void);
10344 /* set error function */
10345 rt_bound_error_msg
= (void *)tcc_get_symbol_err(s1
,
10346 "__bound_error_msg");
10348 /* XXX: use .init section so that it also work in binary ? */
10349 bound_init
= (void *)tcc_get_symbol_err(s1
, "__bound_init");
10353 return (*prog_main
)(argc
, argv
);
10356 void tcc_memstats(void)
10359 printf("memory in use: %d\n", mem_cur_size
);
10363 static void tcc_cleanup(void)
10367 if (NULL
== tcc_state
)
10371 /* free -D defines */
10372 free_defines(NULL
);
10375 n
= tok_ident
- TOK_IDENT
;
10376 for(i
= 0; i
< n
; i
++)
10377 tcc_free(table_ident
[i
]);
10378 tcc_free(table_ident
);
10380 /* free sym_pools */
10381 dynarray_reset(&sym_pools
, &nb_sym_pools
);
10382 /* string buffer */
10383 cstr_free(&tokcstr
);
10384 /* reset symbol stack */
10385 sym_free_first
= NULL
;
10386 /* cleanup from error/setjmp */
10390 TCCState
*tcc_new(void)
10399 s
= tcc_mallocz(sizeof(TCCState
));
10403 s
->output_type
= TCC_OUTPUT_MEMORY
;
10405 /* init isid table */
10406 for(i
=CH_EOF
;i
<256;i
++)
10407 isidnum_table
[i
-CH_EOF
] = isid(i
) || isnum(i
);
10409 /* add all tokens */
10410 table_ident
= NULL
;
10411 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
10413 tok_ident
= TOK_IDENT
;
10422 ts
= tok_alloc(p
, r
- p
- 1);
10426 /* we add dummy defines for some special macros to speed up tests
10427 and to have working defined() */
10428 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
10429 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
10430 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
10431 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
10433 /* standard defines */
10434 tcc_define_symbol(s
, "__STDC__", NULL
);
10435 tcc_define_symbol(s
, "__STDC_VERSION__", "199901L");
10436 #if defined(TCC_TARGET_I386)
10437 tcc_define_symbol(s
, "__i386__", NULL
);
10439 #if defined(TCC_TARGET_X86_64)
10440 tcc_define_symbol(s
, "__x86_64__", NULL
);
10442 #if defined(TCC_TARGET_ARM)
10443 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
10444 tcc_define_symbol(s
, "__arm_elf__", NULL
);
10445 tcc_define_symbol(s
, "__arm_elf", NULL
);
10446 tcc_define_symbol(s
, "arm_elf", NULL
);
10447 tcc_define_symbol(s
, "__arm__", NULL
);
10448 tcc_define_symbol(s
, "__arm", NULL
);
10449 tcc_define_symbol(s
, "arm", NULL
);
10450 tcc_define_symbol(s
, "__APCS_32__", NULL
);
10452 #ifdef TCC_TARGET_PE
10453 tcc_define_symbol(s
, "_WIN32", NULL
);
10455 tcc_define_symbol(s
, "__unix__", NULL
);
10456 tcc_define_symbol(s
, "__unix", NULL
);
10457 #if defined(__linux)
10458 tcc_define_symbol(s
, "__linux__", NULL
);
10459 tcc_define_symbol(s
, "__linux", NULL
);
10462 /* tiny C specific defines */
10463 tcc_define_symbol(s
, "__TINYC__", NULL
);
10465 /* tiny C & gcc defines */
10466 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
10467 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
10468 #ifdef TCC_TARGET_PE
10469 tcc_define_symbol(s
, "__WCHAR_TYPE__", "unsigned short");
10471 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
10474 #ifndef TCC_TARGET_PE
10475 /* default library paths */
10476 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/local/lib");
10477 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/lib");
10478 tcc_add_library_path(s
, CONFIG_SYSROOT
"/lib");
10481 /* no section zero */
10482 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
10484 /* create standard sections */
10485 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
10486 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
10487 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
10489 /* symbols are always generated for linking stage */
10490 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
10492 ".hashtab", SHF_PRIVATE
);
10493 strtab_section
= symtab_section
->link
;
10495 /* private symbol table for dynamic symbols */
10496 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
10498 ".dynhashtab", SHF_PRIVATE
);
10499 s
->alacarte_link
= 1;
10501 #ifdef CHAR_IS_UNSIGNED
10502 s
->char_is_unsigned
= 1;
10504 #if defined(TCC_TARGET_PE) && 0
10505 /* XXX: currently the PE linker is not ready to support that */
10506 s
->leading_underscore
= 1;
10509 #ifdef TCC_TARGET_X86_64
10510 s
->jmp_table
= NULL
;
10511 s
->got_table
= NULL
;
10516 void tcc_delete(TCCState
*s1
)
10522 /* free all sections */
10523 for(i
= 1; i
< s1
->nb_sections
; i
++)
10524 free_section(s1
->sections
[i
]);
10525 dynarray_reset(&s1
->sections
, &s1
->nb_sections
);
10527 for(i
= 0; i
< s1
->nb_priv_sections
; i
++)
10528 free_section(s1
->priv_sections
[i
]);
10529 dynarray_reset(&s1
->priv_sections
, &s1
->nb_priv_sections
);
10531 /* free any loaded DLLs */
10532 for ( i
= 0; i
< s1
->nb_loaded_dlls
; i
++) {
10533 DLLReference
*ref
= s1
->loaded_dlls
[i
];
10535 dlclose(ref
->handle
);
10538 /* free loaded dlls array */
10539 dynarray_reset(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
);
10541 /* free library paths */
10542 dynarray_reset(&s1
->library_paths
, &s1
->nb_library_paths
);
10544 /* free include paths */
10545 dynarray_reset(&s1
->cached_includes
, &s1
->nb_cached_includes
);
10546 dynarray_reset(&s1
->include_paths
, &s1
->nb_include_paths
);
10547 dynarray_reset(&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
);
10549 #ifdef TCC_TARGET_X86_64
10550 tcc_free(s1
->jmp_table
);
10551 tcc_free(s1
->got_table
);
10556 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
10560 pathname1
= tcc_strdup(pathname
);
10561 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
10565 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
10569 pathname1
= tcc_strdup(pathname
);
10570 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
10574 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
10579 BufferedFile
*saved_file
;
10581 /* find source file type with extension */
10582 ext
= tcc_fileextension(filename
);
10586 /* open the file */
10588 file
= tcc_open(s1
, filename
);
10590 if (flags
& AFF_PRINT_ERROR
) {
10591 error_noabort("file '%s' not found", filename
);
10597 if (flags
& AFF_PREPROCESS
) {
10598 ret
= tcc_preprocess(s1
);
10599 } else if (!ext
[0] || !strcmp(ext
, "c")) {
10600 /* C file assumed */
10601 ret
= tcc_compile(s1
);
10603 #ifdef CONFIG_TCC_ASM
10604 if (!strcmp(ext
, "S")) {
10605 /* preprocessed assembler */
10606 ret
= tcc_assemble(s1
, 1);
10607 } else if (!strcmp(ext
, "s")) {
10608 /* non preprocessed assembler */
10609 ret
= tcc_assemble(s1
, 0);
10612 #ifdef TCC_TARGET_PE
10613 if (!strcmp(ext
, "def")) {
10614 ret
= pe_load_def_file(s1
, file
->fd
);
10619 /* assume executable format: auto guess file type */
10620 ret
= read(fd
, &ehdr
, sizeof(ehdr
));
10621 lseek(fd
, 0, SEEK_SET
);
10623 error_noabort("could not read header");
10625 } else if (ret
!= sizeof(ehdr
)) {
10626 goto try_load_script
;
10629 if (ehdr
.e_ident
[0] == ELFMAG0
&&
10630 ehdr
.e_ident
[1] == ELFMAG1
&&
10631 ehdr
.e_ident
[2] == ELFMAG2
&&
10632 ehdr
.e_ident
[3] == ELFMAG3
) {
10633 file
->line_num
= 0; /* do not display line number if error */
10634 if (ehdr
.e_type
== ET_REL
) {
10635 ret
= tcc_load_object_file(s1
, fd
, 0);
10636 } else if (ehdr
.e_type
== ET_DYN
) {
10637 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
10638 #ifdef TCC_TARGET_PE
10642 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
10649 ret
= tcc_load_dll(s1
, fd
, filename
,
10650 (flags
& AFF_REFERENCED_DLL
) != 0);
10653 error_noabort("unrecognized ELF file");
10656 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
10657 file
->line_num
= 0; /* do not display line number if error */
10658 ret
= tcc_load_archive(s1
, fd
);
10660 #ifdef TCC_TARGET_COFF
10661 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
10662 ret
= tcc_load_coff(s1
, fd
);
10665 #ifdef TCC_TARGET_PE
10666 if (pe_test_res_file(&ehdr
, ret
)) {
10667 ret
= pe_load_res_file(s1
, fd
);
10671 /* as GNU ld, consider it is an ld script if not recognized */
10673 ret
= tcc_load_ldscript(s1
);
10675 error_noabort("unrecognized file type");
10690 int tcc_add_file(TCCState
*s
, const char *filename
)
10692 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
10695 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
10699 pathname1
= tcc_strdup(pathname
);
10700 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
10704 /* find and load a dll. Return non zero if not found */
10705 /* XXX: add '-rpath' option support ? */
10706 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
10711 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10712 snprintf(buf
, sizeof(buf
), "%s/%s",
10713 s
->library_paths
[i
], filename
);
10714 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
10720 /* the library name is the same as the argument of the '-l' option */
10721 int tcc_add_library(TCCState
*s
, const char *libraryname
)
10726 /* first we look for the dynamic library if not static linking */
10727 if (!s
->static_link
) {
10728 #ifdef TCC_TARGET_PE
10729 snprintf(buf
, sizeof(buf
), "%s.def", libraryname
);
10731 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
10733 if (tcc_add_dll(s
, buf
, 0) == 0)
10737 /* then we look for the static library */
10738 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10739 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
10740 s
->library_paths
[i
], libraryname
);
10741 if (tcc_add_file_internal(s
, buf
, 0) == 0)
10747 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
10749 add_elf_sym(symtab_section
, val
, 0,
10750 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
10755 int tcc_set_output_type(TCCState
*s
, int output_type
)
10759 s
->output_type
= output_type
;
10761 if (!s
->nostdinc
) {
10762 /* default include paths */
10763 /* XXX: reverse order needed if -isystem support */
10764 #ifndef TCC_TARGET_PE
10765 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/local/include");
10766 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/include");
10768 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
10769 tcc_add_sysinclude_path(s
, buf
);
10770 #ifdef TCC_TARGET_PE
10771 snprintf(buf
, sizeof(buf
), "%s/include/winapi", tcc_lib_path
);
10772 tcc_add_sysinclude_path(s
, buf
);
10776 /* if bound checking, then add corresponding sections */
10777 #ifdef CONFIG_TCC_BCHECK
10778 if (do_bounds_check
) {
10779 /* define symbol */
10780 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
10781 /* create bounds sections */
10782 bounds_section
= new_section(s
, ".bounds",
10783 SHT_PROGBITS
, SHF_ALLOC
);
10784 lbounds_section
= new_section(s
, ".lbounds",
10785 SHT_PROGBITS
, SHF_ALLOC
);
10789 if (s
->char_is_unsigned
) {
10790 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
10793 /* add debug sections */
10796 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
10797 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
10798 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
10799 put_elf_str(stabstr_section
, "");
10800 stab_section
->link
= stabstr_section
;
10801 /* put first entry */
10802 put_stabs("", 0, 0, 0, 0);
10805 /* add libc crt1/crti objects */
10806 #ifndef TCC_TARGET_PE
10807 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
10809 if (output_type
!= TCC_OUTPUT_DLL
)
10810 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
10811 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
10815 #ifdef TCC_TARGET_PE
10816 snprintf(buf
, sizeof(buf
), "%s/lib", tcc_lib_path
);
10817 tcc_add_library_path(s
, buf
);
10823 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
10824 #define FD_INVERT 0x0002 /* invert value before storing */
10826 typedef struct FlagDef
{
10832 static const FlagDef warning_defs
[] = {
10833 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
10834 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
10835 { offsetof(TCCState
, warn_error
), 0, "error" },
10836 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
10837 "implicit-function-declaration" },
10840 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
10841 const char *name
, int value
)
10848 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
10852 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
10853 if (!strcmp(r
, p
->name
))
10858 if (p
->flags
& FD_INVERT
)
10860 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
10865 /* set/reset a warning */
10866 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
10871 if (!strcmp(warning_name
, "all")) {
10872 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
10873 if (p
->flags
& WD_ALL
)
10874 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
10878 return set_flag(s
, warning_defs
, countof(warning_defs
),
10879 warning_name
, value
);
10883 static const FlagDef flag_defs
[] = {
10884 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
10885 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
10886 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
10887 { offsetof(TCCState
, leading_underscore
), 0, "leading-underscore" },
10890 /* set/reset a flag */
10891 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
10893 return set_flag(s
, flag_defs
, countof(flag_defs
),
10897 #if !defined(LIBTCC)
10899 static int64_t getclock_us(void)
10904 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
10907 gettimeofday(&tv
, NULL
);
10908 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
10914 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard\n"
10915 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
10916 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-soname name]\n"
10917 " [-static] [infile1 infile2...] [-run infile args...]\n"
10919 "General options:\n"
10920 " -v display current version, increase verbosity\n"
10921 " -c compile only - generate an object file\n"
10922 " -o outfile set output filename\n"
10923 " -Bdir set tcc internal library path\n"
10924 " -bench output compilation statistics\n"
10925 " -run run compiled source\n"
10926 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
10927 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
10928 " -w disable all warnings\n"
10929 "Preprocessor options:\n"
10930 " -E preprocess only\n"
10931 " -Idir add include path 'dir'\n"
10932 " -Dsym[=val] define 'sym' with value 'val'\n"
10933 " -Usym undefine 'sym'\n"
10934 "Linker options:\n"
10935 " -Ldir add library path 'dir'\n"
10936 " -llib link with dynamic or static library 'lib'\n"
10937 " -shared generate a shared library\n"
10938 " -soname set name for shared library to be used at runtime\n"
10939 " -static static linking\n"
10940 " -rdynamic export all global symbols to dynamic linker\n"
10941 " -r generate (relocatable) object file\n"
10942 "Debugger options:\n"
10943 " -g generate runtime debug info\n"
10944 #ifdef CONFIG_TCC_BCHECK
10945 " -b compile with built-in memory and bounds checker (implies -g)\n"
10947 " -bt N show N callers in stack traces\n"
10951 #define TCC_OPTION_HAS_ARG 0x0001
10952 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
10954 typedef struct TCCOption
{
10983 TCC_OPTION_nostdinc
,
10984 TCC_OPTION_nostdlib
,
10985 TCC_OPTION_print_search_dirs
,
10986 TCC_OPTION_rdynamic
,
10994 static const TCCOption tcc_options
[] = {
10995 { "h", TCC_OPTION_HELP
, 0 },
10996 { "?", TCC_OPTION_HELP
, 0 },
10997 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
10998 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
10999 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
11000 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
11001 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
11002 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11003 { "bench", TCC_OPTION_bench
, 0 },
11004 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
11005 #ifdef CONFIG_TCC_BCHECK
11006 { "b", TCC_OPTION_b
, 0 },
11008 { "g", TCC_OPTION_g
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11009 { "c", TCC_OPTION_c
, 0 },
11010 { "static", TCC_OPTION_static
, 0 },
11011 { "shared", TCC_OPTION_shared
, 0 },
11012 { "soname", TCC_OPTION_soname
, TCC_OPTION_HAS_ARG
},
11013 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
11014 { "run", TCC_OPTION_run
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11015 { "rdynamic", TCC_OPTION_rdynamic
, 0 },
11016 { "r", TCC_OPTION_r
, 0 },
11017 { "Wl,", TCC_OPTION_Wl
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11018 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11019 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11020 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
11021 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11022 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
11023 { "nostdlib", TCC_OPTION_nostdlib
, 0 },
11024 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
11025 { "v", TCC_OPTION_v
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11026 { "w", TCC_OPTION_w
, 0 },
11027 { "pipe", TCC_OPTION_pipe
, 0},
11028 { "E", TCC_OPTION_E
, 0},
11032 /* convert 'str' into an array of space separated strings */
11033 static int expand_args(char ***pargv
, const char *str
)
11042 while (is_space(*str
))
11047 while (*str
!= '\0' && !is_space(*str
))
11050 arg
= tcc_malloc(len
+ 1);
11051 memcpy(arg
, s1
, len
);
11053 dynarray_add((void ***)&argv
, &argc
, arg
);
11059 static char **files
;
11060 static int nb_files
, nb_libraries
;
11061 static int multiple_files
;
11062 static int print_search_dirs
;
11063 static int output_type
;
11064 static int reloc_output
;
11065 static const char *outfile
;
11067 int parse_args(TCCState
*s
, int argc
, char **argv
)
11070 const TCCOption
*popt
;
11071 const char *optarg
, *p1
, *r1
;
11075 while (optind
< argc
) {
11077 r
= argv
[optind
++];
11078 if (r
[0] != '-' || r
[1] == '\0') {
11079 /* add a new file */
11080 dynarray_add((void ***)&files
, &nb_files
, r
);
11081 if (!multiple_files
) {
11083 /* argv[0] will be this file */
11087 /* find option in table (match only the first chars */
11088 popt
= tcc_options
;
11092 error("invalid option -- '%s'", r
);
11105 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
11106 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
11109 if (optind
>= argc
)
11110 error("argument to '%s' is missing", r
);
11111 optarg
= argv
[optind
++];
11119 switch(popt
->index
) {
11120 case TCC_OPTION_HELP
:
11124 if (tcc_add_include_path(s
, optarg
) < 0)
11125 error("too many include paths");
11130 sym
= (char *)optarg
;
11131 value
= strchr(sym
, '=');
11136 tcc_define_symbol(s
, sym
, value
);
11140 tcc_undefine_symbol(s
, optarg
);
11143 tcc_add_library_path(s
, optarg
);
11146 /* set tcc utilities path (mainly for tcc development) */
11147 tcc_lib_path
= optarg
;
11150 dynarray_add((void ***)&files
, &nb_files
, r
);
11153 case TCC_OPTION_bench
:
11156 case TCC_OPTION_bt
:
11157 num_callers
= atoi(optarg
);
11159 #ifdef CONFIG_TCC_BCHECK
11161 do_bounds_check
= 1;
11169 multiple_files
= 1;
11170 output_type
= TCC_OUTPUT_OBJ
;
11172 case TCC_OPTION_static
:
11173 s
->static_link
= 1;
11175 case TCC_OPTION_shared
:
11176 output_type
= TCC_OUTPUT_DLL
;
11178 case TCC_OPTION_soname
:
11179 s
->soname
= optarg
;
11182 multiple_files
= 1;
11186 /* generate a .o merging several output files */
11188 output_type
= TCC_OUTPUT_OBJ
;
11190 case TCC_OPTION_nostdinc
:
11193 case TCC_OPTION_nostdlib
:
11196 case TCC_OPTION_print_search_dirs
:
11197 print_search_dirs
= 1;
11199 case TCC_OPTION_run
:
11203 argc1
= expand_args(&argv1
, optarg
);
11205 parse_args(s
, argc1
, argv1
);
11207 multiple_files
= 0;
11208 output_type
= TCC_OUTPUT_MEMORY
;
11213 if (0 == verbose
++)
11214 printf("tcc version %s\n", TCC_VERSION
);
11215 } while (*optarg
++ == 'v');
11218 if (tcc_set_flag(s
, optarg
, 1) < 0 && s
->warn_unsupported
)
11219 goto unsupported_option
;
11222 if (tcc_set_warning(s
, optarg
, 1) < 0 &&
11223 s
->warn_unsupported
)
11224 goto unsupported_option
;
11229 case TCC_OPTION_rdynamic
:
11232 case TCC_OPTION_Wl
:
11235 if (strstart(optarg
, "-Ttext,", &p
)) {
11236 s
->text_addr
= strtoul(p
, NULL
, 16);
11237 s
->has_text_addr
= 1;
11238 } else if (strstart(optarg
, "--oformat,", &p
)) {
11239 if (strstart(p
, "elf32-", NULL
)) {
11240 s
->output_format
= TCC_OUTPUT_FORMAT_ELF
;
11241 } else if (!strcmp(p
, "binary")) {
11242 s
->output_format
= TCC_OUTPUT_FORMAT_BINARY
;
11244 #ifdef TCC_TARGET_COFF
11245 if (!strcmp(p
, "coff")) {
11246 s
->output_format
= TCC_OUTPUT_FORMAT_COFF
;
11250 error("target %s not found", p
);
11253 error("unsupported linker option '%s'", optarg
);
11258 output_type
= TCC_OUTPUT_PREPROCESS
;
11261 if (s
->warn_unsupported
) {
11262 unsupported_option
:
11263 warning("unsupported option '%s'", r
);
11272 int main(int argc
, char **argv
)
11276 int nb_objfiles
, ret
, optind
;
11277 char objfilename
[1024];
11278 int64_t start_time
= 0;
11281 tcc_lib_path
= w32_tcc_lib_path();
11285 output_type
= TCC_OUTPUT_EXE
;
11287 multiple_files
= 1;
11292 print_search_dirs
= 0;
11295 optind
= parse_args(s
, argc
- 1, argv
+ 1);
11296 if (print_search_dirs
) {
11297 /* enough for Linux kernel */
11298 printf("install: %s/\n", tcc_lib_path
);
11301 if (optind
== 0 || nb_files
== 0) {
11302 if (optind
&& verbose
)
11308 nb_objfiles
= nb_files
- nb_libraries
;
11310 /* if outfile provided without other options, we output an
11312 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
11313 output_type
= TCC_OUTPUT_EXE
;
11315 /* check -c consistency : only single file handled. XXX: checks file type */
11316 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
11317 /* accepts only a single input file */
11318 if (nb_objfiles
!= 1)
11319 error("cannot specify multiple files with -c");
11320 if (nb_libraries
!= 0)
11321 error("cannot specify libraries with -c");
11325 if (output_type
== TCC_OUTPUT_PREPROCESS
) {
11327 s
->outfile
= stdout
;
11329 s
->outfile
= fopen(outfile
, "w");
11331 error("could not open '%s", outfile
);
11333 } else if (output_type
!= TCC_OUTPUT_MEMORY
) {
11335 /* compute default outfile name */
11338 strcmp(files
[0], "-") == 0 ? "a" : tcc_basename(files
[0]);
11339 pstrcpy(objfilename
, sizeof(objfilename
), name
);
11340 ext
= tcc_fileextension(objfilename
);
11341 #ifdef TCC_TARGET_PE
11342 if (output_type
== TCC_OUTPUT_DLL
)
11343 strcpy(ext
, ".dll");
11345 if (output_type
== TCC_OUTPUT_EXE
)
11346 strcpy(ext
, ".exe");
11349 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
&& *ext
)
11352 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
11353 outfile
= objfilename
;
11358 start_time
= getclock_us();
11361 tcc_set_output_type(s
, output_type
);
11363 /* compile or add each files or library */
11364 for(i
= 0; i
< nb_files
&& ret
== 0; i
++) {
11365 const char *filename
;
11367 filename
= files
[i
];
11368 if (output_type
== TCC_OUTPUT_PREPROCESS
) {
11369 if (tcc_add_file_internal(s
, filename
,
11370 AFF_PRINT_ERROR
| AFF_PREPROCESS
) < 0)
11372 } else if (filename
[0] == '-' && filename
[1]) {
11373 if (tcc_add_library(s
, filename
+ 2) < 0)
11374 error("cannot find %s", filename
);
11377 printf("-> %s\n", filename
);
11378 if (tcc_add_file(s
, filename
) < 0)
11383 /* free all files */
11391 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
11392 if (total_time
< 0.001)
11393 total_time
= 0.001;
11394 if (total_bytes
< 1)
11396 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
11397 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
11398 total_time
, (int)(total_lines
/ total_time
),
11399 total_bytes
/ total_time
/ 1000000.0);
11402 if (s
->output_type
== TCC_OUTPUT_PREPROCESS
) {
11404 fclose(s
->outfile
);
11405 } else if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
11406 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
11408 ret
= tcc_output_file(s
, outfile
) ? 1 : 0;
11410 /* XXX: cannot do it with bound checking because of the malloc hooks */
11411 if (!do_bounds_check
)
11416 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);