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 */
547 /* The current value can be: */
548 #define VT_VALMASK 0x00ff
549 #define VT_CONST 0x00f0 /* constant in vc
550 (must be first non register value) */
551 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
552 #define VT_LOCAL 0x00f2 /* offset on stack */
553 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
554 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
555 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
556 #define VT_LVAL 0x0100 /* var is an lvalue */
557 #define VT_SYM 0x0200 /* a symbol value is added */
558 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
559 char/short stored in integer registers) */
560 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
561 dereferencing value */
562 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
563 bounding function call point is in vc */
564 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
565 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
566 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
567 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
570 #define VT_INT 0 /* integer type */
571 #define VT_BYTE 1 /* signed byte type */
572 #define VT_SHORT 2 /* short type */
573 #define VT_VOID 3 /* void type */
574 #define VT_PTR 4 /* pointer */
575 #define VT_ENUM 5 /* enum definition */
576 #define VT_FUNC 6 /* function type */
577 #define VT_STRUCT 7 /* struct/union definition */
578 #define VT_FLOAT 8 /* IEEE float */
579 #define VT_DOUBLE 9 /* IEEE double */
580 #define VT_LDOUBLE 10 /* IEEE long double */
581 #define VT_BOOL 11 /* ISOC99 boolean type */
582 #define VT_LLONG 12 /* 64 bit integer */
583 #define VT_LONG 13 /* long integer (NEVER USED as type, only
585 #define VT_BTYPE 0x000f /* mask for basic type */
586 #define VT_UNSIGNED 0x0010 /* unsigned type */
587 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
588 #define VT_BITFIELD 0x0040 /* bitfield modifier */
589 #define VT_CONSTANT 0x0800 /* const modifier */
590 #define VT_VOLATILE 0x1000 /* volatile modifier */
591 #define VT_SIGNED 0x2000 /* signed type */
594 #define VT_EXTERN 0x00000080 /* extern definition */
595 #define VT_STATIC 0x00000100 /* static variable */
596 #define VT_TYPEDEF 0x00000200 /* typedef definition */
597 #define VT_INLINE 0x00000400 /* inline definition */
599 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
601 /* type mask (except storage) */
602 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
603 #define VT_TYPE (~(VT_STORAGE))
607 /* warning: the following compare tokens depend on i386 asm code */
614 #define TOK_Nset 0x98
615 #define TOK_Nclear 0x99
621 #define TOK_LAND 0xa0
625 #define TOK_MID 0xa3 /* inc/dec, to void constant */
627 #define TOK_UDIV 0xb0 /* unsigned division */
628 #define TOK_UMOD 0xb1 /* unsigned modulo */
629 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
630 #define TOK_CINT 0xb3 /* number in tokc */
631 #define TOK_CCHAR 0xb4 /* char constant in tokc */
632 #define TOK_STR 0xb5 /* pointer to string in tokc */
633 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
634 #define TOK_LCHAR 0xb7
635 #define TOK_LSTR 0xb8
636 #define TOK_CFLOAT 0xb9 /* float constant */
637 #define TOK_LINENUM 0xba /* line number info */
638 #define TOK_CDOUBLE 0xc0 /* double constant */
639 #define TOK_CLDOUBLE 0xc1 /* long double constant */
640 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
641 #define TOK_ADDC1 0xc3 /* add with carry generation */
642 #define TOK_ADDC2 0xc4 /* add with carry use */
643 #define TOK_SUBC1 0xc5 /* add with carry generation */
644 #define TOK_SUBC2 0xc6 /* add with carry use */
645 #define TOK_CUINT 0xc8 /* unsigned int constant */
646 #define TOK_CLLONG 0xc9 /* long long constant */
647 #define TOK_CULLONG 0xca /* unsigned long long constant */
648 #define TOK_ARROW 0xcb
649 #define TOK_DOTS 0xcc /* three dots */
650 #define TOK_SHR 0xcd /* unsigned shift right */
651 #define TOK_PPNUM 0xce /* preprocessor number */
653 #define TOK_SHL 0x01 /* shift left */
654 #define TOK_SAR 0x02 /* signed shift right */
656 /* assignement operators : normal operator or 0x80 */
657 #define TOK_A_MOD 0xa5
658 #define TOK_A_AND 0xa6
659 #define TOK_A_MUL 0xaa
660 #define TOK_A_ADD 0xab
661 #define TOK_A_SUB 0xad
662 #define TOK_A_DIV 0xaf
663 #define TOK_A_XOR 0xde
664 #define TOK_A_OR 0xfc
665 #define TOK_A_SHL 0x81
666 #define TOK_A_SAR 0x82
669 #define offsetof(type, field) ((size_t) &((type *)0)->field)
673 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
676 /* WARNING: the content of this string encodes token numbers */
677 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";
679 #define TOK_EOF (-1) /* end of file */
680 #define TOK_LINEFEED 10 /* line feed */
682 /* all identificators and strings have token above that */
683 #define TOK_IDENT 256
685 /* only used for i386 asm opcodes definitions */
686 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
689 DEF(TOK_ASM_ ## x ## b, #x "b") \
690 DEF(TOK_ASM_ ## x ## w, #x "w") \
691 DEF(TOK_ASM_ ## x ## l, #x "l") \
692 DEF(TOK_ASM_ ## x, #x)
695 DEF(TOK_ASM_ ## x ## w, #x "w") \
696 DEF(TOK_ASM_ ## x ## l, #x "l") \
697 DEF(TOK_ASM_ ## x, #x)
700 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
701 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
702 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
703 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
706 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
707 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
710 #define DEF_ASMTEST(x) \
742 #define TOK_ASM_int TOK_INT
745 TOK_LAST
= TOK_IDENT
- 1,
746 #define DEF(id, str) id,
751 static const char tcc_keywords
[] =
752 #define DEF(id, str) str "\0"
757 #define TOK_UIDENT TOK_DEFINE
760 #define snprintf _snprintf
761 #define vsnprintf _vsnprintf
763 #define strtold (long double)strtod
764 #define strtof (float)strtod
765 #define strtoll (long long)strtol
767 #elif defined(TCC_UCLIBC) || defined(__FreeBSD__) || defined(__DragonFly__) \
768 || defined(__OpenBSD__)
769 /* currently incorrect */
770 long double strtold(const char *nptr
, char **endptr
)
772 return (long double)strtod(nptr
, endptr
);
774 float strtof(const char *nptr
, char **endptr
)
776 return (float)strtod(nptr
, endptr
);
779 /* XXX: need to define this to use them in non ISOC99 context */
780 extern float strtof (const char *__nptr
, char **__endptr
);
781 extern long double strtold (const char *__nptr
, char **__endptr
);
784 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
785 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
786 static char *tcc_basename(const char *name
);
787 static char *tcc_fileextension (const char *p
);
789 static void next(void);
790 static void next_nomacro(void);
791 static void parse_expr_type(CType
*type
);
792 static void expr_type(CType
*type
);
793 static void unary_type(CType
*type
);
794 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
795 int case_reg
, int is_expr
);
796 static int expr_const(void);
797 static void expr_eq(void);
798 static void gexpr(void);
799 static void gen_inline_functions(void);
800 static void decl(int l
);
801 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
802 int first
, int size_only
);
803 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
804 int has_init
, int v
, int scope
);
806 void gv2(int rc1
, int rc2
);
807 void move_reg(int r
, int s
);
808 void save_regs(int n
);
809 void save_reg(int r
);
814 int get_reg_ex(int rc
,int rc2
);
817 struct macro_level
*prev
;
821 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
822 const int *macro_str
, struct macro_level
**can_read_stream
);
824 void force_charshort_cast(int t
);
825 static void gen_cast(CType
*type
);
827 static Sym
*sym_find(int v
);
828 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
831 static int type_size(CType
*type
, int *a
);
832 static inline CType
*pointed_type(CType
*type
);
833 static int pointed_size(CType
*type
);
834 static int lvalue_type(int t
);
835 static int parse_btype(CType
*type
, AttributeDef
*ad
);
836 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
837 static int compare_types(CType
*type1
, CType
*type2
, int unqualified
);
838 static int is_compatible_types(CType
*type1
, CType
*type2
);
839 static int is_compatible_parameter_types(CType
*type1
, CType
*type2
);
841 int ieee_finite(double d
);
842 void error(const char *fmt
, ...);
844 void vpushll(long long v
);
847 void lexpand_nr(void);
848 static void vpush_global_sym(CType
*type
, int v
);
849 void vset(CType
*type
, int r
, int v
);
850 void type_to_str(char *buf
, int buf_size
,
851 CType
*type
, const char *varstr
);
852 char *get_tok_str(int v
, CValue
*cv
);
853 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
854 unsigned long offset
, unsigned long size
);
855 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
857 /* section generation */
858 static void section_realloc(Section
*sec
, unsigned long new_size
);
859 static void *section_ptr_add(Section
*sec
, unsigned long size
);
860 static void put_extern_sym(Sym
*sym
, Section
*section
,
861 unsigned long value
, unsigned long size
);
862 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
863 static int put_elf_str(Section
*s
, const char *sym
);
864 static int put_elf_sym(Section
*s
,
865 unsigned long value
, unsigned long size
,
866 int info
, int other
, int shndx
, const char *name
);
867 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
868 int info
, int other
, int sh_num
, const char *name
);
869 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
870 int type
, int symbol
);
871 static void put_stabs(const char *str
, int type
, int other
, int desc
,
872 unsigned long value
);
873 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
874 unsigned long value
, Section
*sec
, int sym_index
);
875 static void put_stabn(int type
, int other
, int desc
, int value
);
876 static void put_stabd(int type
, int other
, int desc
);
877 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
879 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
880 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
881 #define AFF_PREPROCESS 0x0004 /* preprocess file */
882 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
885 int tcc_output_coff(TCCState
*s1
, FILE *f
);
888 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
);
889 int pe_load_def_file(struct TCCState
*s1
, int fd
);
890 int pe_test_res_file(void *v
, int size
);
891 int pe_load_res_file(struct TCCState
*s1
, int fd
);
892 void pe_add_runtime(struct TCCState
*s1
);
893 void pe_guess_outfile(char *objfilename
, int output_type
);
894 int pe_output_file(struct TCCState
*s1
, const char *filename
);
898 #ifdef CONFIG_TCC_ASM
900 typedef struct ExprValue
{
905 #define MAX_ASM_OPERANDS 30
907 typedef struct ASMOperand
{
908 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
910 char asm_str
[16]; /* computed asm string for operand */
911 SValue
*vt
; /* C value of the expression */
912 int ref_index
; /* if >= 0, gives reference to a output constraint */
913 int input_index
; /* if >= 0, gives reference to an input constraint */
914 int priority
; /* priority, used to assign registers */
915 int reg
; /* if >= 0, register number used for this operand */
916 int is_llong
; /* true if double register value */
917 int is_memory
; /* true if memory operand */
918 int is_rw
; /* for '+' modifier */
921 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
922 static int asm_int_expr(TCCState
*s1
);
923 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
924 const char *name
, const char **pp
);
926 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
930 static void asm_instr(void);
931 static void asm_global_instr(void);
933 /* true if float/double/long double type */
934 static inline int is_float(int t
)
938 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
941 #ifdef TCC_TARGET_I386
942 #include "i386-gen.c"
945 #ifdef TCC_TARGET_ARM
949 #ifdef TCC_TARGET_C67
953 #ifdef TCC_TARGET_X86_64
954 #include "x86_64-gen.c"
957 #ifdef CONFIG_TCC_STATIC
959 #define RTLD_LAZY 0x001
960 #define RTLD_NOW 0x002
961 #define RTLD_GLOBAL 0x100
962 #define RTLD_DEFAULT NULL
964 /* dummy function for profiling */
965 void *dlopen(const char *filename
, int flag
)
970 const char *dlerror(void)
975 typedef struct TCCSyms
{
980 #define TCCSYM(a) { #a, &a, },
982 /* add the symbol you want here if no dynamic linking is done */
983 static TCCSyms tcc_syms
[] = {
984 #if !defined(CONFIG_TCCBOOT)
993 void *resolve_sym(TCCState
*s1
, const char *symbol
, int type
)
997 while (p
->str
!= NULL
) {
998 if (!strcmp(p
->str
, symbol
))
1005 #elif !defined(_WIN32)
1009 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
)
1011 return dlsym(RTLD_DEFAULT
, sym
);
1016 /********************************************************/
1018 /* we use our own 'finite' function to avoid potential problems with
1019 non standard math libs */
1020 /* XXX: endianness dependent */
1021 int ieee_finite(double d
)
1024 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
1027 /* copy a string and truncate it. */
1028 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
1035 q_end
= buf
+ buf_size
- 1;
1047 /* strcat and truncate. */
1048 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
1053 pstrcpy(buf
+ len
, buf_size
- len
, s
);
1058 static int strstart(const char *str
, const char *val
, const char **ptr
)
1063 while (*q
!= '\0') {
1076 #define IS_PATHSEP(c) (c == '/' || c == '\\')
1077 #define IS_ABSPATH(p) (IS_PATHSEP(p[0]) || (p[0] && p[1] == ':' && IS_PATHSEP(p[2])))
1078 #define PATHCMP stricmp
1080 #define IS_PATHSEP(c) (c == '/')
1081 #define IS_ABSPATH(p) IS_PATHSEP(p[0])
1082 #define PATHCMP strcmp
1085 /* extract the basename of a file */
1086 static char *tcc_basename(const char *name
)
1088 char *p
= strchr(name
, 0);
1089 while (p
> name
&& !IS_PATHSEP(p
[-1]))
1094 static char *tcc_fileextension (const char *name
)
1096 char *b
= tcc_basename(name
);
1097 char *e
= strrchr(b
, '.');
1098 return e
? e
: strchr(b
, 0);
1102 char *normalize_slashes(char *path
)
1105 for (p
= path
; *p
; ++p
)
1111 char *w32_tcc_lib_path(void)
1113 /* on win32, we suppose the lib and includes are at the location
1115 char path
[1024], *p
;
1116 GetModuleFileNameA(NULL
, path
, sizeof path
);
1117 p
= tcc_basename(normalize_slashes(strlwr(path
)));
1118 if (p
- 5 > path
&& 0 == strncmp(p
- 5, "/bin/", 5))
1123 return strdup(path
);
1127 void set_pages_executable(void *ptr
, unsigned long length
)
1130 unsigned long old_protect
;
1131 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
1133 unsigned long start
, end
;
1134 start
= (unsigned long)ptr
& ~(PAGESIZE
- 1);
1135 end
= (unsigned long)ptr
+ length
;
1136 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
1137 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
1141 /* memory management */
1145 unsigned malloc_usable_size(void*);
1148 static inline void tcc_free(void *ptr
)
1151 mem_cur_size
-= malloc_usable_size(ptr
);
1156 static void *tcc_malloc(unsigned long size
)
1161 error("memory full");
1163 mem_cur_size
+= malloc_usable_size(ptr
);
1164 if (mem_cur_size
> mem_max_size
)
1165 mem_max_size
= mem_cur_size
;
1170 static void *tcc_mallocz(unsigned long size
)
1173 ptr
= tcc_malloc(size
);
1174 memset(ptr
, 0, size
);
1178 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
1182 mem_cur_size
-= malloc_usable_size(ptr
);
1184 ptr1
= realloc(ptr
, size
);
1186 /* NOTE: count not correct if alloc error, but not critical */
1187 mem_cur_size
+= malloc_usable_size(ptr1
);
1188 if (mem_cur_size
> mem_max_size
)
1189 mem_max_size
= mem_cur_size
;
1194 static char *tcc_strdup(const char *str
)
1197 ptr
= tcc_malloc(strlen(str
) + 1);
1202 #define free(p) use_tcc_free(p)
1203 #define malloc(s) use_tcc_malloc(s)
1204 #define realloc(p, s) use_tcc_realloc(p, s)
1206 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
1213 /* every power of two we double array size */
1214 if ((nb
& (nb
- 1)) == 0) {
1219 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
1221 error("memory full");
1228 static void dynarray_reset(void *pp
, int *n
)
1231 for (p
= *(void***)pp
; *n
; ++p
, --*n
)
1234 tcc_free(*(void**)pp
);
1238 /* symbol allocator */
1239 static Sym
*__sym_malloc(void)
1241 Sym
*sym_pool
, *sym
, *last_sym
;
1244 sym_pool
= tcc_malloc(SYM_POOL_NB
* sizeof(Sym
));
1245 dynarray_add(&sym_pools
, &nb_sym_pools
, sym_pool
);
1247 last_sym
= sym_free_first
;
1249 for(i
= 0; i
< SYM_POOL_NB
; i
++) {
1250 sym
->next
= last_sym
;
1254 sym_free_first
= last_sym
;
1258 static inline Sym
*sym_malloc(void)
1261 sym
= sym_free_first
;
1263 sym
= __sym_malloc();
1264 sym_free_first
= sym
->next
;
1268 static inline void sym_free(Sym
*sym
)
1270 sym
->next
= sym_free_first
;
1271 sym_free_first
= sym
;
1274 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
1278 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
1279 strcpy(sec
->name
, name
);
1280 sec
->sh_type
= sh_type
;
1281 sec
->sh_flags
= sh_flags
;
1289 sec
->sh_addralign
= 4;
1292 sec
->sh_addralign
= 1;
1295 sec
->sh_addralign
= 32; /* default conservative alignment */
1299 if (sh_flags
& SHF_PRIVATE
) {
1300 dynarray_add((void ***)&s1
->priv_sections
, &s1
->nb_priv_sections
, sec
);
1302 sec
->sh_num
= s1
->nb_sections
;
1303 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
1309 static void free_section(Section
*s
)
1311 #ifdef TCC_TARGET_X86_64
1312 /* after tcc_relocate(), some sections share the data buffer.
1313 let's check if the data is allocated not to free the shared buffers */
1314 if (s
->data_allocated
)
1319 /* realloc section and set its content to zero */
1320 static void section_realloc(Section
*sec
, unsigned long new_size
)
1323 unsigned char *data
;
1325 size
= sec
->data_allocated
;
1328 while (size
< new_size
)
1330 data
= tcc_realloc(sec
->data
, size
);
1332 error("memory full");
1333 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1335 sec
->data_allocated
= size
;
1338 /* reserve at least 'size' bytes in section 'sec' from
1339 sec->data_offset. */
1340 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1342 unsigned long offset
, offset1
;
1344 offset
= sec
->data_offset
;
1345 offset1
= offset
+ size
;
1346 if (offset1
> sec
->data_allocated
)
1347 section_realloc(sec
, offset1
);
1348 sec
->data_offset
= offset1
;
1349 return sec
->data
+ offset
;
1352 /* return a reference to a section, and create it if it does not
1354 Section
*find_section(TCCState
*s1
, const char *name
)
1358 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1359 sec
= s1
->sections
[i
];
1360 if (!strcmp(name
, sec
->name
))
1363 /* sections are created as PROGBITS */
1364 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1367 #define SECTION_ABS ((void *)1)
1369 /* update sym->c so that it points to an external symbol in section
1370 'section' with value 'value' */
1371 static void put_extern_sym2(Sym
*sym
, Section
*section
,
1372 unsigned long value
, unsigned long size
,
1373 int can_add_underscore
)
1375 int sym_type
, sym_bind
, sh_num
, info
, other
, attr
;
1380 if (section
== NULL
)
1382 else if (section
== SECTION_ABS
)
1385 sh_num
= section
->sh_num
;
1389 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
) {
1390 sym_type
= STT_FUNC
;
1391 #ifdef TCC_TARGET_PE
1393 attr
= sym
->type
.ref
->r
;
1394 if (FUNC_EXPORT(attr
))
1396 if (FUNC_CALL(attr
) == FUNC_STDCALL
)
1400 sym_type
= STT_OBJECT
;
1403 if (sym
->type
.t
& VT_STATIC
)
1404 sym_bind
= STB_LOCAL
;
1406 sym_bind
= STB_GLOBAL
;
1409 name
= get_tok_str(sym
->v
, NULL
);
1410 #ifdef CONFIG_TCC_BCHECK
1411 if (do_bounds_check
) {
1414 /* XXX: avoid doing that for statics ? */
1415 /* if bound checking is activated, we change some function
1416 names by adding the "__bound" prefix */
1419 /* XXX: we rely only on malloc hooks */
1432 strcpy(buf
, "__bound_");
1440 #ifdef TCC_TARGET_PE
1441 if ((other
& 2) && can_add_underscore
) {
1442 sprintf(buf1
, "_%s@%d", name
, FUNC_ARGS(attr
));
1446 if (tcc_state
->leading_underscore
&& can_add_underscore
) {
1448 pstrcpy(buf1
+ 1, sizeof(buf1
) - 1, name
);
1451 info
= ELFW(ST_INFO
)(sym_bind
, sym_type
);
1452 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, other
, sh_num
, name
);
1454 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
1455 esym
->st_value
= value
;
1456 esym
->st_size
= size
;
1457 esym
->st_shndx
= sh_num
;
1458 esym
->st_other
|= other
;
1462 static void put_extern_sym(Sym
*sym
, Section
*section
,
1463 unsigned long value
, unsigned long size
)
1465 put_extern_sym2(sym
, section
, value
, size
, 1);
1468 /* add a new relocation entry to symbol 'sym' in section 's' */
1469 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1472 put_extern_sym(sym
, NULL
, 0, 0);
1473 /* now we can add ELF relocation info */
1474 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1477 static inline int isid(int c
)
1479 return (c
>= 'a' && c
<= 'z') ||
1480 (c
>= 'A' && c
<= 'Z') ||
1484 static inline int isnum(int c
)
1486 return c
>= '0' && c
<= '9';
1489 static inline int isoct(int c
)
1491 return c
>= '0' && c
<= '7';
1494 static inline int toup(int c
)
1496 if (c
>= 'a' && c
<= 'z')
1497 return c
- 'a' + 'A';
1502 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1506 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1509 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1513 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1517 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1524 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1525 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1526 (*f
)->filename
, (*f
)->line_num
);
1527 if (file
->line_num
> 0) {
1528 strcat_printf(buf
, sizeof(buf
),
1529 "%s:%d: ", file
->filename
, file
->line_num
);
1531 strcat_printf(buf
, sizeof(buf
),
1532 "%s: ", file
->filename
);
1535 strcat_printf(buf
, sizeof(buf
),
1539 strcat_printf(buf
, sizeof(buf
), "warning: ");
1540 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1542 if (!s1
->error_func
) {
1543 /* default case: stderr */
1544 fprintf(stderr
, "%s\n", buf
);
1546 s1
->error_func(s1
->error_opaque
, buf
);
1548 if (!is_warning
|| s1
->warn_error
)
1553 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1554 void (*error_func
)(void *opaque
, const char *msg
))
1556 s
->error_opaque
= error_opaque
;
1557 s
->error_func
= error_func
;
1561 /* error without aborting current compilation */
1562 void error_noabort(const char *fmt
, ...)
1564 TCCState
*s1
= tcc_state
;
1568 error1(s1
, 0, fmt
, ap
);
1572 void error(const char *fmt
, ...)
1574 TCCState
*s1
= tcc_state
;
1578 error1(s1
, 0, fmt
, ap
);
1580 /* better than nothing: in some cases, we accept to handle errors */
1581 if (s1
->error_set_jmp_enabled
) {
1582 longjmp(s1
->error_jmp_buf
, 1);
1584 /* XXX: eliminate this someday */
1589 void expect(const char *msg
)
1591 error("%s expected", msg
);
1594 void warning(const char *fmt
, ...)
1596 TCCState
*s1
= tcc_state
;
1603 error1(s1
, 1, fmt
, ap
);
1610 error("'%c' expected", c
);
1614 static void test_lvalue(void)
1616 if (!(vtop
->r
& VT_LVAL
))
1620 /* allocate a new token */
1621 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1623 TokenSym
*ts
, **ptable
;
1626 if (tok_ident
>= SYM_FIRST_ANOM
)
1627 error("memory full");
1629 /* expand token table if needed */
1630 i
= tok_ident
- TOK_IDENT
;
1631 if ((i
% TOK_ALLOC_INCR
) == 0) {
1632 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1634 error("memory full");
1635 table_ident
= ptable
;
1638 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1639 table_ident
[i
] = ts
;
1640 ts
->tok
= tok_ident
++;
1641 ts
->sym_define
= NULL
;
1642 ts
->sym_label
= NULL
;
1643 ts
->sym_struct
= NULL
;
1644 ts
->sym_identifier
= NULL
;
1646 ts
->hash_next
= NULL
;
1647 memcpy(ts
->str
, str
, len
);
1648 ts
->str
[len
] = '\0';
1653 #define TOK_HASH_INIT 1
1654 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1656 /* find a token and add it if not found */
1657 static TokenSym
*tok_alloc(const char *str
, int len
)
1659 TokenSym
*ts
, **pts
;
1665 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1666 h
&= (TOK_HASH_SIZE
- 1);
1668 pts
= &hash_ident
[h
];
1673 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1675 pts
= &(ts
->hash_next
);
1677 return tok_alloc_new(pts
, str
, len
);
1680 /* CString handling */
1682 static void cstr_realloc(CString
*cstr
, int new_size
)
1687 size
= cstr
->size_allocated
;
1689 size
= 8; /* no need to allocate a too small first string */
1690 while (size
< new_size
)
1692 data
= tcc_realloc(cstr
->data_allocated
, size
);
1694 error("memory full");
1695 cstr
->data_allocated
= data
;
1696 cstr
->size_allocated
= size
;
1701 static inline void cstr_ccat(CString
*cstr
, int ch
)
1704 size
= cstr
->size
+ 1;
1705 if (size
> cstr
->size_allocated
)
1706 cstr_realloc(cstr
, size
);
1707 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1711 static void cstr_cat(CString
*cstr
, const char *str
)
1723 /* add a wide char */
1724 static void cstr_wccat(CString
*cstr
, int ch
)
1727 size
= cstr
->size
+ sizeof(nwchar_t
);
1728 if (size
> cstr
->size_allocated
)
1729 cstr_realloc(cstr
, size
);
1730 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
1734 static void cstr_new(CString
*cstr
)
1736 memset(cstr
, 0, sizeof(CString
));
1739 /* free string and reset it to NULL */
1740 static void cstr_free(CString
*cstr
)
1742 tcc_free(cstr
->data_allocated
);
1746 #define cstr_reset(cstr) cstr_free(cstr)
1748 /* XXX: unicode ? */
1749 static void add_char(CString
*cstr
, int c
)
1751 if (c
== '\'' || c
== '\"' || c
== '\\') {
1752 /* XXX: could be more precise if char or string */
1753 cstr_ccat(cstr
, '\\');
1755 if (c
>= 32 && c
<= 126) {
1758 cstr_ccat(cstr
, '\\');
1760 cstr_ccat(cstr
, 'n');
1762 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1763 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1764 cstr_ccat(cstr
, '0' + (c
& 7));
1769 /* XXX: buffer overflow */
1770 /* XXX: float tokens */
1771 char *get_tok_str(int v
, CValue
*cv
)
1773 static char buf
[STRING_MAX_SIZE
+ 1];
1774 static CString cstr_buf
;
1780 /* NOTE: to go faster, we give a fixed buffer for small strings */
1781 cstr_reset(&cstr_buf
);
1782 cstr_buf
.data
= buf
;
1783 cstr_buf
.size_allocated
= sizeof(buf
);
1789 /* XXX: not quite exact, but only useful for testing */
1790 sprintf(p
, "%u", cv
->ui
);
1794 /* XXX: not quite exact, but only useful for testing */
1795 sprintf(p
, "%Lu", cv
->ull
);
1798 cstr_ccat(&cstr_buf
, 'L');
1800 cstr_ccat(&cstr_buf
, '\'');
1801 add_char(&cstr_buf
, cv
->i
);
1802 cstr_ccat(&cstr_buf
, '\'');
1803 cstr_ccat(&cstr_buf
, '\0');
1807 len
= cstr
->size
- 1;
1809 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1810 cstr_ccat(&cstr_buf
, '\0');
1813 cstr_ccat(&cstr_buf
, 'L');
1816 cstr_ccat(&cstr_buf
, '\"');
1818 len
= cstr
->size
- 1;
1820 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1822 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
1824 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
1826 cstr_ccat(&cstr_buf
, '\"');
1827 cstr_ccat(&cstr_buf
, '\0');
1836 return strcpy(p
, "...");
1838 return strcpy(p
, "<<=");
1840 return strcpy(p
, ">>=");
1842 if (v
< TOK_IDENT
) {
1843 /* search in two bytes table */
1857 } else if (v
< tok_ident
) {
1858 return table_ident
[v
- TOK_IDENT
]->str
;
1859 } else if (v
>= SYM_FIRST_ANOM
) {
1860 /* special name for anonymous symbol */
1861 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1863 /* should never happen */
1868 return cstr_buf
.data
;
1871 /* push, without hashing */
1872 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, long c
)
1886 /* find a symbol and return its associated structure. 's' is the top
1887 of the symbol stack */
1888 static Sym
*sym_find2(Sym
*s
, int v
)
1898 /* structure lookup */
1899 static inline Sym
*struct_find(int v
)
1902 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1904 return table_ident
[v
]->sym_struct
;
1907 /* find an identifier */
1908 static inline Sym
*sym_find(int v
)
1911 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1913 return table_ident
[v
]->sym_identifier
;
1916 /* push a given symbol on the symbol stack */
1917 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1926 s
= sym_push2(ps
, v
, type
->t
, c
);
1927 s
->type
.ref
= type
->ref
;
1929 /* don't record fields or anonymous symbols */
1931 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1932 /* record symbol in token array */
1933 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1935 ps
= &ts
->sym_struct
;
1937 ps
= &ts
->sym_identifier
;
1944 /* push a global identifier */
1945 static Sym
*global_identifier_push(int v
, int t
, int c
)
1948 s
= sym_push2(&global_stack
, v
, t
, c
);
1949 /* don't record anonymous symbol */
1950 if (v
< SYM_FIRST_ANOM
) {
1951 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1952 /* modify the top most local identifier, so that
1953 sym_identifier will point to 's' when popped */
1955 ps
= &(*ps
)->prev_tok
;
1962 /* pop symbols until top reaches 'b' */
1963 static void sym_pop(Sym
**ptop
, Sym
*b
)
1973 /* remove symbol in token array */
1975 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1976 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1978 ps
= &ts
->sym_struct
;
1980 ps
= &ts
->sym_identifier
;
1991 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1996 if (strcmp(filename
, "-") == 0)
1997 fd
= 0, filename
= "stdin";
1999 fd
= open(filename
, O_RDONLY
| O_BINARY
);
2000 if ((verbose
== 2 && fd
>= 0) || verbose
== 3)
2001 printf("%s %*s%s\n", fd
< 0 ? "nf":"->",
2002 (s1
->include_stack_ptr
- s1
->include_stack
), "", filename
);
2005 bf
= tcc_malloc(sizeof(BufferedFile
));
2007 bf
->buf_ptr
= bf
->buffer
;
2008 bf
->buf_end
= bf
->buffer
;
2009 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
2010 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
2012 normalize_slashes(bf
->filename
);
2015 bf
->ifndef_macro
= 0;
2016 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
2017 // printf("opening '%s'\n", filename);
2021 void tcc_close(BufferedFile
*bf
)
2023 total_lines
+= bf
->line_num
;
2028 /* fill input buffer and peek next char */
2029 static int tcc_peekc_slow(BufferedFile
*bf
)
2032 /* only tries to read if really end of buffer */
2033 if (bf
->buf_ptr
>= bf
->buf_end
) {
2035 #if defined(PARSE_DEBUG)
2040 len
= read(bf
->fd
, bf
->buffer
, len
);
2047 bf
->buf_ptr
= bf
->buffer
;
2048 bf
->buf_end
= bf
->buffer
+ len
;
2049 *bf
->buf_end
= CH_EOB
;
2051 if (bf
->buf_ptr
< bf
->buf_end
) {
2052 return bf
->buf_ptr
[0];
2054 bf
->buf_ptr
= bf
->buf_end
;
2059 /* return the current character, handling end of block if necessary
2061 static int handle_eob(void)
2063 return tcc_peekc_slow(file
);
2066 /* read next char from current input file and handle end of input buffer */
2067 static inline void inp(void)
2069 ch
= *(++(file
->buf_ptr
));
2070 /* end of buffer/file handling */
2075 /* handle '\[\r]\n' */
2076 static int handle_stray_noerror(void)
2078 while (ch
== '\\') {
2083 } else if (ch
== '\r') {
2097 static void handle_stray(void)
2099 if (handle_stray_noerror())
2100 error("stray '\\' in program");
2103 /* skip the stray and handle the \\n case. Output an error if
2104 incorrect char after the stray */
2105 static int handle_stray1(uint8_t *p
)
2109 if (p
>= file
->buf_end
) {
2126 /* handle just the EOB case, but not stray */
2127 #define PEEKC_EOB(c, p)\
2138 /* handle the complicated stray case */
2139 #define PEEKC(c, p)\
2144 c = handle_stray1(p);\
2149 /* input with '\[\r]\n' handling. Note that this function cannot
2150 handle other characters after '\', so you cannot call it inside
2151 strings or comments */
2152 static void minp(void)
2160 /* single line C++ comments */
2161 static uint8_t *parse_line_comment(uint8_t *p
)
2169 if (c
== '\n' || c
== CH_EOF
) {
2171 } else if (c
== '\\') {
2180 } else if (c
== '\r') {
2198 static uint8_t *parse_comment(uint8_t *p
)
2204 /* fast skip loop */
2207 if (c
== '\n' || c
== '*' || c
== '\\')
2211 if (c
== '\n' || c
== '*' || c
== '\\')
2215 /* now we can handle all the cases */
2219 } else if (c
== '*') {
2225 } else if (c
== '/') {
2226 goto end_of_comment
;
2227 } else if (c
== '\\') {
2232 /* skip '\[\r]\n', otherwise just skip the stray */
2238 } else if (c
== '\r') {
2255 /* stray, eob or eof */
2260 error("unexpected end of file in comment");
2261 } else if (c
== '\\') {
2273 /* space exlcuding newline */
2274 static inline int is_space(int ch
)
2276 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
2279 static inline void skip_spaces(void)
2281 while (is_space(ch
))
2285 /* parse a string without interpreting escapes */
2286 static uint8_t *parse_pp_string(uint8_t *p
,
2287 int sep
, CString
*str
)
2295 } else if (c
== '\\') {
2300 unterminated_string
:
2301 /* XXX: indicate line number of start of string */
2302 error("missing terminating %c character", sep
);
2303 } else if (c
== '\\') {
2304 /* escape : just skip \[\r]\n */
2309 } else if (c
== '\r') {
2312 expect("'\n' after '\r'");
2315 } else if (c
== CH_EOF
) {
2316 goto unterminated_string
;
2319 cstr_ccat(str
, '\\');
2325 } else if (c
== '\n') {
2328 } else if (c
== '\r') {
2332 cstr_ccat(str
, '\r');
2348 /* skip block of text until #else, #elif or #endif. skip also pairs of
2350 void preprocess_skip(void)
2352 int a
, start_of_line
, c
, in_warn_or_error
;
2359 in_warn_or_error
= 0;
2380 } else if (c
== '\\') {
2381 ch
= file
->buf_ptr
[0];
2382 handle_stray_noerror();
2389 if (in_warn_or_error
)
2391 p
= parse_pp_string(p
, c
, NULL
);
2395 if (in_warn_or_error
)
2402 p
= parse_comment(p
);
2403 } else if (ch
== '/') {
2404 p
= parse_line_comment(p
);
2409 if (start_of_line
) {
2414 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2416 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2418 else if (tok
== TOK_ENDIF
)
2420 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
2421 in_warn_or_error
= 1;
2435 /* ParseState handling */
2437 /* XXX: currently, no include file info is stored. Thus, we cannot display
2438 accurate messages if the function or data definition spans multiple
2441 /* save current parse state in 's' */
2442 void save_parse_state(ParseState
*s
)
2444 s
->line_num
= file
->line_num
;
2445 s
->macro_ptr
= macro_ptr
;
2450 /* restore parse state from 's' */
2451 void restore_parse_state(ParseState
*s
)
2453 file
->line_num
= s
->line_num
;
2454 macro_ptr
= s
->macro_ptr
;
2459 /* return the number of additional 'ints' necessary to store the
2461 static inline int tok_ext_size(int t
)
2475 error("unsupported token");
2482 return LDOUBLE_SIZE
/ 4;
2488 /* token string handling */
2490 static inline void tok_str_new(TokenString
*s
)
2494 s
->allocated_len
= 0;
2495 s
->last_line_num
= -1;
2498 static void tok_str_free(int *str
)
2503 static int *tok_str_realloc(TokenString
*s
)
2507 if (s
->allocated_len
== 0) {
2510 len
= s
->allocated_len
* 2;
2512 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2514 error("memory full");
2515 s
->allocated_len
= len
;
2520 static void tok_str_add(TokenString
*s
, int t
)
2526 if (len
>= s
->allocated_len
)
2527 str
= tok_str_realloc(s
);
2532 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2539 /* allocate space for worst case */
2540 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2541 str
= tok_str_realloc(s
);
2550 str
[len
++] = cv
->tab
[0];
2559 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
2560 while ((len
+ nb_words
) > s
->allocated_len
)
2561 str
= tok_str_realloc(s
);
2562 cstr
= (CString
*)(str
+ len
);
2564 cstr
->size
= cv
->cstr
->size
;
2565 cstr
->data_allocated
= NULL
;
2566 cstr
->size_allocated
= cstr
->size
;
2567 memcpy((char *)cstr
+ sizeof(CString
),
2568 cv
->cstr
->data
, cstr
->size
);
2575 #if LDOUBLE_SIZE == 8
2578 str
[len
++] = cv
->tab
[0];
2579 str
[len
++] = cv
->tab
[1];
2581 #if LDOUBLE_SIZE == 12
2583 str
[len
++] = cv
->tab
[0];
2584 str
[len
++] = cv
->tab
[1];
2585 str
[len
++] = cv
->tab
[2];
2586 #elif LDOUBLE_SIZE == 16
2588 str
[len
++] = cv
->tab
[0];
2589 str
[len
++] = cv
->tab
[1];
2590 str
[len
++] = cv
->tab
[2];
2591 str
[len
++] = cv
->tab
[3];
2592 #elif LDOUBLE_SIZE != 8
2593 #error add long double size support
2602 /* add the current parse token in token string 's' */
2603 static void tok_str_add_tok(TokenString
*s
)
2607 /* save line number info */
2608 if (file
->line_num
!= s
->last_line_num
) {
2609 s
->last_line_num
= file
->line_num
;
2610 cval
.i
= s
->last_line_num
;
2611 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2613 tok_str_add2(s
, tok
, &tokc
);
2616 #if LDOUBLE_SIZE == 16
2617 #define LDOUBLE_GET(p, cv) \
2622 #elif LDOUBLE_SIZE == 12
2623 #define LDOUBLE_GET(p, cv) \
2627 #elif LDOUBLE_SIZE == 8
2628 #define LDOUBLE_GET(p, cv) \
2632 #error add long double size support
2636 /* get a token from an integer array and increment pointer
2637 accordingly. we code it as a macro to avoid pointer aliasing. */
2638 #define TOK_GET(t, p, cv) \
2653 cv.cstr = (CString *)p; \
2654 cv.cstr->data = (char *)p + sizeof(CString);\
2655 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
2664 case TOK_CLDOUBLE: \
2665 LDOUBLE_GET(p, cv); \
2666 p += LDOUBLE_SIZE / 4; \
2673 /* defines handling */
2674 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2678 s
= sym_push2(&define_stack
, v
, macro_type
, (long)str
);
2679 s
->next
= first_arg
;
2680 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2683 /* undefined a define symbol. Its name is just set to zero */
2684 static void define_undef(Sym
*s
)
2688 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2689 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2693 static inline Sym
*define_find(int v
)
2696 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2698 return table_ident
[v
]->sym_define
;
2701 /* free define stack until top reaches 'b' */
2702 static void free_defines(Sym
*b
)
2710 /* do not free args or predefined defines */
2712 tok_str_free((int *)top
->c
);
2714 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2715 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2723 static Sym
*label_find(int v
)
2726 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2728 return table_ident
[v
]->sym_label
;
2731 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2734 s
= sym_push2(ptop
, v
, 0, 0);
2736 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2737 if (ptop
== &global_label_stack
) {
2738 /* modify the top most local identifier, so that
2739 sym_identifier will point to 's' when popped */
2741 ps
= &(*ps
)->prev_tok
;
2748 /* pop labels until element last is reached. Look if any labels are
2749 undefined. Define symbols if '&&label' was used. */
2750 static void label_pop(Sym
**ptop
, Sym
*slast
)
2753 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2755 if (s
->r
== LABEL_DECLARED
) {
2756 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2757 } else if (s
->r
== LABEL_FORWARD
) {
2758 error("label '%s' used but not defined",
2759 get_tok_str(s
->v
, NULL
));
2762 /* define corresponding symbol. A size of
2764 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2768 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2774 /* eval an expression for #if/#elif */
2775 static int expr_preprocess(void)
2781 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2782 next(); /* do macro subst */
2783 if (tok
== TOK_DEFINED
) {
2788 c
= define_find(tok
) != 0;
2793 } else if (tok
>= TOK_IDENT
) {
2794 /* if undefined macro */
2798 tok_str_add_tok(&str
);
2800 tok_str_add(&str
, -1); /* simulate end of file */
2801 tok_str_add(&str
, 0);
2802 /* now evaluate C constant expression */
2803 macro_ptr
= str
.str
;
2807 tok_str_free(str
.str
);
2811 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2812 static void tok_print(int *str
)
2818 TOK_GET(t
, str
, cval
);
2821 printf(" %s", get_tok_str(t
, &cval
));
2827 /* parse after #define */
2828 static void parse_define(void)
2830 Sym
*s
, *first
, **ps
;
2831 int v
, t
, varg
, is_vaargs
, c
;
2836 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2837 /* XXX: should check if same macro (ANSI) */
2840 /* '(' must be just after macro definition for MACRO_FUNC */
2841 c
= file
->buf_ptr
[0];
2843 c
= handle_stray1(file
->buf_ptr
);
2848 while (tok
!= ')') {
2852 if (varg
== TOK_DOTS
) {
2853 varg
= TOK___VA_ARGS__
;
2855 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2859 if (varg
< TOK_IDENT
)
2860 error("badly punctuated parameter list");
2861 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2872 /* EOF testing necessary for '-D' handling */
2873 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2874 tok_str_add2(&str
, tok
, &tokc
);
2877 tok_str_add(&str
, 0);
2879 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2882 define_push(v
, t
, str
.str
, first
);
2885 static inline int hash_cached_include(int type
, const char *filename
)
2887 const unsigned char *s
;
2891 h
= TOK_HASH_FUNC(h
, type
);
2894 h
= TOK_HASH_FUNC(h
, *s
);
2897 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
2901 /* XXX: use a token or a hash table to accelerate matching ? */
2902 static CachedInclude
*search_cached_include(TCCState
*s1
,
2903 int type
, const char *filename
)
2907 h
= hash_cached_include(type
, filename
);
2908 i
= s1
->cached_includes_hash
[h
];
2912 e
= s1
->cached_includes
[i
- 1];
2913 if (e
->type
== type
&& !PATHCMP(e
->filename
, filename
))
2920 static inline void add_cached_include(TCCState
*s1
, int type
,
2921 const char *filename
, int ifndef_macro
)
2926 if (search_cached_include(s1
, type
, filename
))
2929 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2931 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2935 strcpy(e
->filename
, filename
);
2936 e
->ifndef_macro
= ifndef_macro
;
2937 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2938 /* add in hash table */
2939 h
= hash_cached_include(type
, filename
);
2940 e
->hash_next
= s1
->cached_includes_hash
[h
];
2941 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
2944 static void pragma_parse(TCCState
*s1
)
2949 if (tok
== TOK_pack
) {
2952 #pragma pack(1) // set
2953 #pragma pack() // reset to default
2954 #pragma pack(push,1) // push & set
2955 #pragma pack(pop) // restore previous
2959 if (tok
== TOK_ASM_pop
) {
2961 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
2963 error("out of pack stack");
2965 s1
->pack_stack_ptr
--;
2969 if (tok
== TOK_ASM_push
) {
2971 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
2973 s1
->pack_stack_ptr
++;
2976 if (tok
!= TOK_CINT
) {
2978 error("invalid pack pragma");
2981 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
2985 *s1
->pack_stack_ptr
= val
;
2991 /* is_bof is true if first non space token at beginning of file */
2992 static void preprocess(int is_bof
)
2994 TCCState
*s1
= tcc_state
;
2995 int size
, i
, c
, n
, saved_parse_flags
;
3002 saved_parse_flags
= parse_flags
;
3003 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
3004 PARSE_FLAG_LINEFEED
;
3014 s
= define_find(tok
);
3015 /* undefine symbol by putting an invalid name */
3020 case TOK_INCLUDE_NEXT
:
3021 ch
= file
->buf_ptr
[0];
3022 /* XXX: incorrect if comments : use next_nomacro with a special mode */
3027 } else if (ch
== '\"') {
3032 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
3033 if ((q
- buf
) < sizeof(buf
) - 1)
3036 if (handle_stray_noerror() == 0)
3044 /* eat all spaces and comments after include */
3045 /* XXX: slightly incorrect */
3046 while (ch1
!= '\n' && ch1
!= CH_EOF
)
3050 /* computed #include : either we have only strings or
3051 we have anything enclosed in '<>' */
3054 if (tok
== TOK_STR
) {
3055 while (tok
!= TOK_LINEFEED
) {
3056 if (tok
!= TOK_STR
) {
3058 error("'#include' expects \"FILENAME\" or <FILENAME>");
3060 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
3066 while (tok
!= TOK_LINEFEED
) {
3067 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
3071 /* check syntax and remove '<>' */
3072 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
3073 goto include_syntax
;
3074 memmove(buf
, buf
+ 1, len
- 2);
3075 buf
[len
- 2] = '\0';
3080 e
= search_cached_include(s1
, c
, buf
);
3081 if (e
&& define_find(e
->ifndef_macro
)) {
3082 /* no need to parse the include because the 'ifndef macro'
3085 printf("%s: skipping %s\n", file
->filename
, buf
);
3088 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
3089 error("#include recursion too deep");
3090 /* push current file in stack */
3091 /* XXX: fix current line init */
3092 *s1
->include_stack_ptr
++ = file
;
3094 /* check absolute include path */
3095 if (IS_ABSPATH(buf
)) {
3096 f
= tcc_open(s1
, buf
);
3101 /* first search in current dir if "header.h" */
3102 size
= tcc_basename(file
->filename
) - file
->filename
;
3103 if (size
> sizeof(buf1
) - 1)
3104 size
= sizeof(buf1
) - 1;
3105 memcpy(buf1
, file
->filename
, size
);
3107 pstrcat(buf1
, sizeof(buf1
), buf
);
3108 f
= tcc_open(s1
, buf1
);
3110 if (tok
== TOK_INCLUDE_NEXT
)
3116 /* now search in all the include paths */
3117 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
3118 for(i
= 0; i
< n
; i
++) {
3120 if (i
< s1
->nb_include_paths
)
3121 path
= s1
->include_paths
[i
];
3123 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
3124 pstrcpy(buf1
, sizeof(buf1
), path
);
3125 pstrcat(buf1
, sizeof(buf1
), "/");
3126 pstrcat(buf1
, sizeof(buf1
), buf
);
3127 f
= tcc_open(s1
, buf1
);
3129 if (tok
== TOK_INCLUDE_NEXT
)
3135 --s1
->include_stack_ptr
;
3136 error("include file '%s' not found", buf
);
3140 printf("%s: including %s\n", file
->filename
, buf1
);
3143 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
3145 /* add include file debug info */
3147 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
3149 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
3150 ch
= file
->buf_ptr
[0];
3158 c
= expr_preprocess();
3164 if (tok
< TOK_IDENT
)
3165 error("invalid argument for '#if%sdef'", c
? "n" : "");
3169 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
3171 file
->ifndef_macro
= tok
;
3174 c
= (define_find(tok
) != 0) ^ c
;
3176 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
3177 error("memory full");
3178 *s1
->ifdef_stack_ptr
++ = c
;
3181 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
3182 error("#else without matching #if");
3183 if (s1
->ifdef_stack_ptr
[-1] & 2)
3184 error("#else after #else");
3185 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
3188 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
3189 error("#elif without matching #if");
3190 c
= s1
->ifdef_stack_ptr
[-1];
3192 error("#elif after #else");
3193 /* last #if/#elif expression was true: we skip */
3196 c
= expr_preprocess();
3197 s1
->ifdef_stack_ptr
[-1] = c
;
3207 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
3208 error("#endif without matching #if");
3209 s1
->ifdef_stack_ptr
--;
3210 /* '#ifndef macro' was at the start of file. Now we check if
3211 an '#endif' is exactly at the end of file */
3212 if (file
->ifndef_macro
&&
3213 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
3214 file
->ifndef_macro_saved
= file
->ifndef_macro
;
3215 /* need to set to zero to avoid false matches if another
3216 #ifndef at middle of file */
3217 file
->ifndef_macro
= 0;
3218 while (tok
!= TOK_LINEFEED
)
3220 tok_flags
|= TOK_FLAG_ENDIF
;
3226 if (tok
!= TOK_CINT
)
3228 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
3230 if (tok
!= TOK_LINEFEED
) {
3233 pstrcpy(file
->filename
, sizeof(file
->filename
),
3234 (char *)tokc
.cstr
->data
);
3240 ch
= file
->buf_ptr
[0];
3243 while (ch
!= '\n' && ch
!= CH_EOF
) {
3244 if ((q
- buf
) < sizeof(buf
) - 1)
3247 if (handle_stray_noerror() == 0)
3254 error("#error %s", buf
);
3256 warning("#warning %s", buf
);
3262 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
3263 /* '!' is ignored to allow C scripts. numbers are ignored
3264 to emulate cpp behaviour */
3266 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
3267 warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
3271 /* ignore other preprocess commands or #! for C scripts */
3272 while (tok
!= TOK_LINEFEED
)
3275 parse_flags
= saved_parse_flags
;
3278 /* evaluate escape codes in a string. */
3279 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
3294 case '0': case '1': case '2': case '3':
3295 case '4': case '5': case '6': case '7':
3296 /* at most three octal digits */
3301 n
= n
* 8 + c
- '0';
3305 n
= n
* 8 + c
- '0';
3310 goto add_char_nonext
;
3318 if (c
>= 'a' && c
<= 'f')
3320 else if (c
>= 'A' && c
<= 'F')
3330 goto add_char_nonext
;
3354 goto invalid_escape
;
3364 if (c
>= '!' && c
<= '~')
3365 warning("unknown escape sequence: \'\\%c\'", c
);
3367 warning("unknown escape sequence: \'\\x%x\'", c
);
3374 cstr_ccat(outstr
, c
);
3376 cstr_wccat(outstr
, c
);
3378 /* add a trailing '\0' */
3380 cstr_ccat(outstr
, '\0');
3382 cstr_wccat(outstr
, '\0');
3385 /* we use 64 bit numbers */
3388 /* bn = (bn << shift) | or_val */
3389 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
3393 for(i
=0;i
<BN_SIZE
;i
++) {
3395 bn
[i
] = (v
<< shift
) | or_val
;
3396 or_val
= v
>> (32 - shift
);
3400 void bn_zero(unsigned int *bn
)
3403 for(i
=0;i
<BN_SIZE
;i
++) {
3408 /* parse number in null terminated string 'p' and return it in the
3410 void parse_number(const char *p
)
3412 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
3414 unsigned int bn
[BN_SIZE
];
3425 goto float_frac_parse
;
3426 } else if (t
== '0') {
3427 if (ch
== 'x' || ch
== 'X') {
3431 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
3437 /* parse all digits. cannot check octal numbers at this stage
3438 because of floating point constants */
3440 if (ch
>= 'a' && ch
<= 'f')
3442 else if (ch
>= 'A' && ch
<= 'F')
3450 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
3452 error("number too long");
3458 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
3459 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
3461 /* NOTE: strtox should support that for hexa numbers, but
3462 non ISOC99 libcs do not support it, so we prefer to do
3464 /* hexadecimal or binary floats */
3465 /* XXX: handle overflows */
3477 } else if (t
>= 'a') {
3479 } else if (t
>= 'A') {
3484 bn_lshift(bn
, shift
, t
);
3491 if (t
>= 'a' && t
<= 'f') {
3493 } else if (t
>= 'A' && t
<= 'F') {
3495 } else if (t
>= '0' && t
<= '9') {
3501 error("invalid digit");
3502 bn_lshift(bn
, shift
, t
);
3507 if (ch
!= 'p' && ch
!= 'P')
3514 } else if (ch
== '-') {
3518 if (ch
< '0' || ch
> '9')
3519 expect("exponent digits");
3520 while (ch
>= '0' && ch
<= '9') {
3521 exp_val
= exp_val
* 10 + ch
- '0';
3524 exp_val
= exp_val
* s
;
3526 /* now we can generate the number */
3527 /* XXX: should patch directly float number */
3528 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3529 d
= ldexp(d
, exp_val
- frac_bits
);
3534 /* float : should handle overflow */
3536 } else if (t
== 'L') {
3539 /* XXX: not large enough */
3540 tokc
.ld
= (long double)d
;
3546 /* decimal floats */
3548 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3553 while (ch
>= '0' && ch
<= '9') {
3554 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3560 if (ch
== 'e' || ch
== 'E') {
3561 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3565 if (ch
== '-' || ch
== '+') {
3566 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3571 if (ch
< '0' || ch
> '9')
3572 expect("exponent digits");
3573 while (ch
>= '0' && ch
<= '9') {
3574 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3586 tokc
.f
= strtof(token_buf
, NULL
);
3587 } else if (t
== 'L') {
3590 tokc
.ld
= strtold(token_buf
, NULL
);
3593 tokc
.d
= strtod(token_buf
, NULL
);
3597 unsigned long long n
, n1
;
3600 /* integer number */
3603 if (b
== 10 && *q
== '0') {
3610 /* no need for checks except for base 10 / 8 errors */
3613 } else if (t
>= 'a') {
3615 } else if (t
>= 'A') {
3620 error("invalid digit");
3624 /* detect overflow */
3625 /* XXX: this test is not reliable */
3627 error("integer constant overflow");
3630 /* XXX: not exactly ANSI compliant */
3631 if ((n
& 0xffffffff00000000LL
) != 0) {
3636 } else if (n
> 0x7fffffff) {
3647 error("three 'l's in integer constant");
3650 if (tok
== TOK_CINT
)
3652 else if (tok
== TOK_CUINT
)
3656 } else if (t
== 'U') {
3658 error("two 'u's in integer constant");
3660 if (tok
== TOK_CINT
)
3662 else if (tok
== TOK_CLLONG
)
3669 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3675 error("invalid number\n");
3679 #define PARSE2(c1, tok1, c2, tok2) \
3690 /* return next token without macro substitution */
3691 static inline void next_nomacro1(void)
3698 cstr_reset(&tok_spaces
);
3708 cstr_ccat(&tok_spaces
, c
);
3713 /* first look if it is in fact an end of buffer */
3714 if (p
>= file
->buf_end
) {
3718 if (p
>= file
->buf_end
)
3731 TCCState
*s1
= tcc_state
;
3732 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
3733 && !(tok_flags
& TOK_FLAG_EOF
)) {
3734 tok_flags
|= TOK_FLAG_EOF
;
3736 goto keep_tok_flags
;
3737 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3738 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3739 /* no include left : end of file. */
3742 tok_flags
&= ~TOK_FLAG_EOF
;
3743 /* pop include file */
3745 /* test if previous '#endif' was after a #ifdef at
3747 if (tok_flags
& TOK_FLAG_ENDIF
) {
3749 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3751 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3752 file
->ifndef_macro_saved
);
3755 /* add end of include file debug info */
3757 put_stabd(N_EINCL
, 0, 0);
3759 /* pop include stack */
3761 s1
->include_stack_ptr
--;
3762 file
= *s1
->include_stack_ptr
;
3771 tok_flags
|= TOK_FLAG_BOL
;
3773 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
3776 goto keep_tok_flags
;
3781 if ((tok_flags
& TOK_FLAG_BOL
) &&
3782 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3784 preprocess(tok_flags
& TOK_FLAG_BOF
);
3790 tok
= TOK_TWOSHARPS
;
3792 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
3793 p
= parse_line_comment(p
- 1);
3802 case 'a': case 'b': case 'c': case 'd':
3803 case 'e': case 'f': case 'g': case 'h':
3804 case 'i': case 'j': case 'k': case 'l':
3805 case 'm': case 'n': case 'o': case 'p':
3806 case 'q': case 'r': case 's': case 't':
3807 case 'u': case 'v': case 'w': case 'x':
3809 case 'A': case 'B': case 'C': case 'D':
3810 case 'E': case 'F': case 'G': case 'H':
3811 case 'I': case 'J': case 'K':
3812 case 'M': case 'N': case 'O': case 'P':
3813 case 'Q': case 'R': case 'S': case 'T':
3814 case 'U': case 'V': case 'W': case 'X':
3820 h
= TOK_HASH_FUNC(h
, c
);
3824 if (!isidnum_table
[c
-CH_EOF
])
3826 h
= TOK_HASH_FUNC(h
, c
);
3833 /* fast case : no stray found, so we have the full token
3834 and we have already hashed it */
3836 h
&= (TOK_HASH_SIZE
- 1);
3837 pts
= &hash_ident
[h
];
3842 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3844 pts
= &(ts
->hash_next
);
3846 ts
= tok_alloc_new(pts
, p1
, len
);
3850 cstr_reset(&tokcstr
);
3853 cstr_ccat(&tokcstr
, *p1
);
3859 while (isidnum_table
[c
-CH_EOF
]) {
3860 cstr_ccat(&tokcstr
, c
);
3863 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3869 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3871 goto parse_ident_fast
;
3874 if (c
== '\'' || c
== '\"') {
3878 cstr_reset(&tokcstr
);
3879 cstr_ccat(&tokcstr
, 'L');
3880 goto parse_ident_slow
;
3884 case '0': case '1': case '2': case '3':
3885 case '4': case '5': case '6': case '7':
3888 cstr_reset(&tokcstr
);
3889 /* after the first digit, accept digits, alpha, '.' or sign if
3890 prefixed by 'eEpP' */
3894 cstr_ccat(&tokcstr
, c
);
3896 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3897 ((c
== '+' || c
== '-') &&
3898 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3901 /* We add a trailing '\0' to ease parsing */
3902 cstr_ccat(&tokcstr
, '\0');
3903 tokc
.cstr
= &tokcstr
;
3907 /* special dot handling because it can also start a number */
3910 cstr_reset(&tokcstr
);
3911 cstr_ccat(&tokcstr
, '.');
3913 } else if (c
== '.') {
3933 /* parse the string */
3935 p
= parse_pp_string(p
, sep
, &str
);
3936 cstr_ccat(&str
, '\0');
3938 /* eval the escape (should be done as TOK_PPNUM) */
3939 cstr_reset(&tokcstr
);
3940 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3945 /* XXX: make it portable */
3949 char_size
= sizeof(nwchar_t
);
3950 if (tokcstr
.size
<= char_size
)
3951 error("empty character constant");
3952 if (tokcstr
.size
> 2 * char_size
)
3953 warning("multi-character character constant");
3955 tokc
.i
= *(int8_t *)tokcstr
.data
;
3958 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
3962 tokc
.cstr
= &tokcstr
;
3976 } else if (c
== '<') {
3994 } else if (c
== '>') {
4012 } else if (c
== '=') {
4025 } else if (c
== '=') {
4038 } else if (c
== '=') {
4051 } else if (c
== '=') {
4054 } else if (c
== '>') {
4062 PARSE2('!', '!', '=', TOK_NE
)
4063 PARSE2('=', '=', '=', TOK_EQ
)
4064 PARSE2('*', '*', '=', TOK_A_MUL
)
4065 PARSE2('%', '%', '=', TOK_A_MOD
)
4066 PARSE2('^', '^', '=', TOK_A_XOR
)
4068 /* comments or operator */
4072 p
= parse_comment(p
);
4074 } else if (c
== '/') {
4075 p
= parse_line_comment(p
);
4077 } else if (c
== '=') {
4097 case '$': /* only used in assembler */
4098 case '@': /* dito */
4103 error("unrecognized character \\x%02x", c
);
4109 #if defined(PARSE_DEBUG)
4110 printf("token = %s\n", get_tok_str(tok
, &tokc
));
4114 /* return next token without macro substitution. Can read input from
4116 static void next_nomacro(void)
4122 TOK_GET(tok
, macro_ptr
, tokc
);
4123 if (tok
== TOK_LINENUM
) {
4124 file
->line_num
= tokc
.i
;
4133 /* substitute args in macro_str and return allocated string */
4134 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
4136 int *st
, last_tok
, t
, notfirst
;
4145 TOK_GET(t
, macro_str
, cval
);
4150 TOK_GET(t
, macro_str
, cval
);
4153 s
= sym_find2(args
, t
);
4160 cstr_ccat(&cstr
, ' ');
4161 TOK_GET(t
, st
, cval
);
4162 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
4167 cstr_ccat(&cstr
, '\0');
4169 printf("stringize: %s\n", (char *)cstr
.data
);
4173 tok_str_add2(&str
, TOK_STR
, &cval
);
4176 tok_str_add2(&str
, t
, &cval
);
4178 } else if (t
>= TOK_IDENT
) {
4179 s
= sym_find2(args
, t
);
4182 /* if '##' is present before or after, no arg substitution */
4183 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
4184 /* special case for var arg macros : ## eats the
4185 ',' if empty VA_ARGS variable. */
4186 /* XXX: test of the ',' is not 100%
4187 reliable. should fix it to avoid security
4189 if (gnu_ext
&& s
->type
.t
&&
4190 last_tok
== TOK_TWOSHARPS
&&
4191 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
4193 /* suppress ',' '##' */
4196 /* suppress '##' and add variable */
4204 TOK_GET(t1
, st
, cval
);
4207 tok_str_add2(&str
, t1
, &cval
);
4211 /* NOTE: the stream cannot be read when macro
4212 substituing an argument */
4213 macro_subst(&str
, nested_list
, st
, NULL
);
4216 tok_str_add(&str
, t
);
4219 tok_str_add2(&str
, t
, &cval
);
4223 tok_str_add(&str
, 0);
4227 static char const ab_month_name
[12][4] =
4229 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
4230 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
4233 /* do macro substitution of current token with macro 's' and add
4234 result to (tok_str,tok_len). 'nested_list' is the list of all
4235 macros we got inside to avoid recursing. Return non zero if no
4236 substitution needs to be done */
4237 static int macro_subst_tok(TokenString
*tok_str
,
4238 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
4240 Sym
*args
, *sa
, *sa1
;
4241 int mstr_allocated
, parlevel
, *mstr
, t
, t1
;
4248 /* if symbol is a macro, prepare substitution */
4249 /* special macros */
4250 if (tok
== TOK___LINE__
) {
4251 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
4255 } else if (tok
== TOK___FILE__
) {
4256 cstrval
= file
->filename
;
4258 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
4263 tm
= localtime(&ti
);
4264 if (tok
== TOK___DATE__
) {
4265 snprintf(buf
, sizeof(buf
), "%s %2d %d",
4266 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
4268 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
4269 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
4276 cstr_cat(&cstr
, cstrval
);
4277 cstr_ccat(&cstr
, '\0');
4279 tok_str_add2(tok_str
, t1
, &cval
);
4284 if (s
->type
.t
== MACRO_FUNC
) {
4285 /* NOTE: we do not use next_nomacro to avoid eating the
4286 next token. XXX: find better solution */
4290 if (t
== 0 && can_read_stream
) {
4291 /* end of macro stream: we must look at the token
4292 after in the file */
4293 struct macro_level
*ml
= *can_read_stream
;
4299 *can_read_stream
= ml
-> prev
;
4304 /* XXX: incorrect with comments */
4305 ch
= file
->buf_ptr
[0];
4306 while (is_space(ch
) || ch
== '\n')
4310 if (t
!= '(') /* no macro subst */
4313 /* argument macro */
4318 /* NOTE: empty args are allowed, except if no args */
4320 /* handle '()' case */
4321 if (!args
&& !sa
&& tok
== ')')
4324 error("macro '%s' used with too many args",
4325 get_tok_str(s
->v
, 0));
4328 /* NOTE: non zero sa->t indicates VA_ARGS */
4329 while ((parlevel
> 0 ||
4331 (tok
!= ',' || sa
->type
.t
))) &&
4335 else if (tok
== ')')
4337 if (tok
!= TOK_LINEFEED
)
4338 tok_str_add2(&str
, tok
, &tokc
);
4341 tok_str_add(&str
, 0);
4342 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (long)str
.str
);
4345 /* special case for gcc var args: add an empty
4346 var arg argument if it is omitted */
4347 if (sa
&& sa
->type
.t
&& gnu_ext
)
4357 error("macro '%s' used with too few args",
4358 get_tok_str(s
->v
, 0));
4361 /* now subst each arg */
4362 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
4367 tok_str_free((int *)sa
->c
);
4373 sym_push2(nested_list
, s
->v
, 0, 0);
4374 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
4375 /* pop nested defined symbol */
4377 *nested_list
= sa1
->prev
;
4385 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4386 return the resulting string (which must be freed). */
4387 static inline int *macro_twosharps(const int *macro_str
)
4390 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
4392 const char *p1
, *p2
;
4394 TokenString macro_str1
;
4397 start_macro_ptr
= macro_str
;
4398 /* we search the first '##' */
4400 macro_ptr1
= macro_str
;
4401 TOK_GET(t
, macro_str
, cval
);
4402 /* nothing more to do if end of string */
4405 if (*macro_str
== TOK_TWOSHARPS
)
4409 /* we saw '##', so we need more processing to handle it */
4411 tok_str_new(¯o_str1
);
4415 /* add all tokens seen so far */
4416 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
4417 TOK_GET(t
, ptr
, cval
);
4418 tok_str_add2(¯o_str1
, t
, &cval
);
4420 saved_macro_ptr
= macro_ptr
;
4421 /* XXX: get rid of the use of macro_ptr here */
4422 macro_ptr
= (int *)macro_str
;
4424 while (*macro_ptr
== TOK_TWOSHARPS
) {
4426 macro_ptr1
= macro_ptr
;
4429 TOK_GET(t
, macro_ptr
, cval
);
4430 /* We concatenate the two tokens if we have an
4431 identifier or a preprocessing number */
4433 p1
= get_tok_str(tok
, &tokc
);
4434 cstr_cat(&cstr
, p1
);
4435 p2
= get_tok_str(t
, &cval
);
4436 cstr_cat(&cstr
, p2
);
4437 cstr_ccat(&cstr
, '\0');
4439 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
4440 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
4441 if (tok
== TOK_PPNUM
) {
4442 /* if number, then create a number token */
4443 /* NOTE: no need to allocate because
4444 tok_str_add2() does it */
4445 cstr_reset(&tokcstr
);
4448 tokc
.cstr
= &tokcstr
;
4450 /* if identifier, we must do a test to
4451 validate we have a correct identifier */
4452 if (t
== TOK_PPNUM
) {
4462 if (!isnum(c
) && !isid(c
))
4466 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
4467 tok
= ts
->tok
; /* modify current token */
4470 const char *str
= cstr
.data
;
4471 const unsigned char *q
;
4473 /* we look for a valid token */
4474 /* XXX: do more extensive checks */
4475 if (!strcmp(str
, ">>=")) {
4477 } else if (!strcmp(str
, "<<=")) {
4479 } else if (strlen(str
) == 2) {
4480 /* search in two bytes table */
4485 if (q
[0] == str
[0] && q
[1] == str
[1])
4492 /* NOTE: because get_tok_str use a static buffer,
4495 p1
= get_tok_str(tok
, &tokc
);
4496 cstr_cat(&cstr
, p1
);
4497 cstr_ccat(&cstr
, '\0');
4498 p2
= get_tok_str(t
, &cval
);
4499 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
4500 /* cannot merge tokens: just add them separately */
4501 tok_str_add2(¯o_str1
, tok
, &tokc
);
4502 /* XXX: free associated memory ? */
4509 tok_str_add2(¯o_str1
, tok
, &tokc
);
4514 macro_ptr
= (int *)saved_macro_ptr
;
4516 tok_str_add(¯o_str1
, 0);
4517 return macro_str1
.str
;
4521 /* do macro substitution of macro_str and add result to
4522 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4523 inside to avoid recursing. */
4524 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
4525 const int *macro_str
, struct macro_level
** can_read_stream
)
4532 struct macro_level ml
;
4534 /* first scan for '##' operator handling */
4536 macro_str1
= macro_twosharps(ptr
);
4540 /* NOTE: ptr == NULL can only happen if tokens are read from
4541 file stream due to a macro function call */
4544 TOK_GET(t
, ptr
, cval
);
4549 /* if nested substitution, do nothing */
4550 if (sym_find2(*nested_list
, t
))
4553 if (can_read_stream
)
4554 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
4555 macro_ptr
= (int *)ptr
;
4557 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
4558 ptr
= (int *)macro_ptr
;
4560 if (can_read_stream
&& *can_read_stream
== &ml
)
4561 *can_read_stream
= ml
.prev
;
4566 tok_str_add2(tok_str
, t
, &cval
);
4570 tok_str_free(macro_str1
);
4573 /* return next token with macro substitution */
4574 static void next(void)
4576 Sym
*nested_list
, *s
;
4578 struct macro_level
*ml
;
4583 /* if not reading from macro substituted string, then try
4584 to substitute macros */
4585 if (tok
>= TOK_IDENT
&&
4586 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4587 s
= define_find(tok
);
4589 /* we have a macro: we try to substitute */
4593 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
4594 /* substitution done, NOTE: maybe empty */
4595 tok_str_add(&str
, 0);
4596 macro_ptr
= str
.str
;
4597 macro_ptr_allocated
= str
.str
;
4604 /* end of macro or end of unget buffer */
4605 if (unget_buffer_enabled
) {
4606 macro_ptr
= unget_saved_macro_ptr
;
4607 unget_buffer_enabled
= 0;
4609 /* end of macro string: free it */
4610 tok_str_free(macro_ptr_allocated
);
4617 /* convert preprocessor tokens into C tokens */
4618 if (tok
== TOK_PPNUM
&&
4619 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4620 parse_number((char *)tokc
.cstr
->data
);
4624 /* push back current token and set current token to 'last_tok'. Only
4625 identifier case handled for labels. */
4626 static inline void unget_tok(int last_tok
)
4630 unget_saved_macro_ptr
= macro_ptr
;
4631 unget_buffer_enabled
= 1;
4632 q
= unget_saved_buffer
;
4635 n
= tok_ext_size(tok
) - 1;
4638 *q
= 0; /* end of token string */
4643 void swap(int *p
, int *q
)
4651 void vsetc(CType
*type
, int r
, CValue
*vc
)
4655 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4656 error("memory full");
4657 /* cannot let cpu flags if other instruction are generated. Also
4658 avoid leaving VT_JMP anywhere except on the top of the stack
4659 because it would complicate the code generator. */
4660 if (vtop
>= vstack
) {
4661 v
= vtop
->r
& VT_VALMASK
;
4662 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4668 vtop
->r2
= VT_CONST
;
4672 /* push integer constant */
4677 vsetc(&int_type
, VT_CONST
, &cval
);
4680 /* push long long constant */
4681 void vpushll(long long v
)
4687 vsetc(&ctype
, VT_CONST
, &cval
);
4690 /* Return a static symbol pointing to a section */
4691 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4692 unsigned long offset
, unsigned long size
)
4698 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4699 sym
->type
.ref
= type
->ref
;
4700 sym
->r
= VT_CONST
| VT_SYM
;
4701 put_extern_sym(sym
, sec
, offset
, size
);
4705 /* push a reference to a section offset by adding a dummy symbol */
4706 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4711 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4712 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4715 /* define a new external reference to a symbol 'v' of type 'u' */
4716 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4722 /* push forward reference */
4723 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4724 s
->type
.ref
= type
->ref
;
4725 s
->r
= r
| VT_CONST
| VT_SYM
;
4730 /* define a new external reference to a symbol 'v' of type 'u' */
4731 static Sym
*external_sym(int v
, CType
*type
, int r
)
4737 /* push forward reference */
4738 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4739 s
->type
.t
|= VT_EXTERN
;
4741 if (!is_compatible_types(&s
->type
, type
))
4742 error("incompatible types for redefinition of '%s'",
4743 get_tok_str(v
, NULL
));
4748 /* push a reference to global symbol v */
4749 static void vpush_global_sym(CType
*type
, int v
)
4754 sym
= external_global_sym(v
, type
, 0);
4756 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4760 void vset(CType
*type
, int r
, int v
)
4765 vsetc(type
, r
, &cval
);
4768 void vseti(int r
, int v
)
4784 void vpushv(SValue
*v
)
4786 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4787 error("memory full");
4797 /* save r to the memory stack, and mark it as being free */
4798 void save_reg(int r
)
4800 int l
, saved
, size
, align
;
4804 /* modify all stack values */
4807 for(p
=vstack
;p
<=vtop
;p
++) {
4808 if ((p
->r
& VT_VALMASK
) == r
||
4809 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& (p
->r2
& VT_VALMASK
) == r
)) {
4810 /* must save value on stack if not already done */
4812 /* NOTE: must reload 'r' because r might be equal to r2 */
4813 r
= p
->r
& VT_VALMASK
;
4814 /* store register in the stack */
4816 if ((p
->r
& VT_LVAL
) ||
4817 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4818 #ifdef TCC_TARGET_X86_64
4819 type
= &char_pointer_type
;
4823 size
= type_size(type
, &align
);
4824 loc
= (loc
- size
) & -align
;
4825 sv
.type
.t
= type
->t
;
4826 sv
.r
= VT_LOCAL
| VT_LVAL
;
4829 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
4830 /* x86 specific: need to pop fp register ST0 if saved */
4831 if (r
== TREG_ST0
) {
4832 o(0xd9dd); /* fstp %st(1) */
4835 #ifndef TCC_TARGET_X86_64
4836 /* special long long case */
4837 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4845 /* mark that stack entry as being saved on the stack */
4846 if (p
->r
& VT_LVAL
) {
4847 /* also clear the bounded flag because the
4848 relocation address of the function was stored in
4850 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4852 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4860 /* find a register of class 'rc2' with at most one reference on stack.
4861 * If none, call get_reg(rc) */
4862 int get_reg_ex(int rc
, int rc2
)
4867 for(r
=0;r
<NB_REGS
;r
++) {
4868 if (reg_classes
[r
] & rc2
) {
4871 for(p
= vstack
; p
<= vtop
; p
++) {
4872 if ((p
->r
& VT_VALMASK
) == r
||
4873 (p
->r2
& VT_VALMASK
) == r
)
4883 /* find a free register of class 'rc'. If none, save one register */
4889 /* find a free register */
4890 for(r
=0;r
<NB_REGS
;r
++) {
4891 if (reg_classes
[r
] & rc
) {
4892 for(p
=vstack
;p
<=vtop
;p
++) {
4893 if ((p
->r
& VT_VALMASK
) == r
||
4894 (p
->r2
& VT_VALMASK
) == r
)
4902 /* no register left : free the first one on the stack (VERY
4903 IMPORTANT to start from the bottom to ensure that we don't
4904 spill registers used in gen_opi()) */
4905 for(p
=vstack
;p
<=vtop
;p
++) {
4906 r
= p
->r
& VT_VALMASK
;
4907 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4909 /* also look at second register (if long long) */
4910 r
= p
->r2
& VT_VALMASK
;
4911 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4917 /* Should never comes here */
4921 /* save registers up to (vtop - n) stack entry */
4922 void save_regs(int n
)
4927 for(p
= vstack
;p
<= p1
; p
++) {
4928 r
= p
->r
& VT_VALMASK
;
4935 /* move register 's' to 'r', and flush previous value of r to memory
4937 void move_reg(int r
, int s
)
4950 /* get address of vtop (vtop MUST BE an lvalue) */
4953 vtop
->r
&= ~VT_LVAL
;
4954 /* tricky: if saved lvalue, then we can go back to lvalue */
4955 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4956 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4959 #ifdef CONFIG_TCC_BCHECK
4960 /* generate lvalue bound code */
4966 vtop
->r
&= ~VT_MUSTBOUND
;
4967 /* if lvalue, then use checking code before dereferencing */
4968 if (vtop
->r
& VT_LVAL
) {
4969 /* if not VT_BOUNDED value, then make one */
4970 if (!(vtop
->r
& VT_BOUNDED
)) {
4971 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4972 /* must save type because we must set it to int to get pointer */
4974 vtop
->type
.t
= VT_INT
;
4977 gen_bounded_ptr_add();
4978 vtop
->r
|= lval_type
;
4981 /* then check for dereferencing */
4982 gen_bounded_ptr_deref();
4987 /* store vtop a register belonging to class 'rc'. lvalues are
4988 converted to values. Cannot be used if cannot be converted to
4989 register value (such as structures). */
4992 int r
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4994 /* NOTE: get_reg can modify vstack[] */
4995 if (vtop
->type
.t
& VT_BITFIELD
) {
4998 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4999 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
5000 /* remove bit field info to avoid loops */
5001 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
5002 /* cast to int to propagate signedness in following ops */
5003 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
5008 if((vtop
->type
.t
& VT_UNSIGNED
) ||
5009 (vtop
->type
.t
& VT_BTYPE
) == VT_BOOL
)
5010 type
.t
|= VT_UNSIGNED
;
5012 /* generate shifts */
5013 vpushi(bits
- (bit_pos
+ bit_size
));
5015 vpushi(bits
- bit_size
);
5016 /* NOTE: transformed to SHR if unsigned */
5020 if (is_float(vtop
->type
.t
) &&
5021 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
5024 unsigned long offset
;
5025 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5029 /* XXX: unify with initializers handling ? */
5030 /* CPUs usually cannot use float constants, so we store them
5031 generically in data segment */
5032 size
= type_size(&vtop
->type
, &align
);
5033 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
5034 data_section
->data_offset
= offset
;
5035 /* XXX: not portable yet */
5036 #if defined(__i386__) || defined(__x86_64__)
5037 /* Zero pad x87 tenbyte long doubles */
5038 if (size
== LDOUBLE_SIZE
)
5039 vtop
->c
.tab
[2] &= 0xffff;
5041 ptr
= section_ptr_add(data_section
, size
);
5043 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5047 ptr
[i
] = vtop
->c
.tab
[size
-1-i
];
5051 ptr
[i
] = vtop
->c
.tab
[i
];
5052 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
5053 vtop
->r
|= VT_LVAL
| VT_SYM
;
5057 #ifdef CONFIG_TCC_BCHECK
5058 if (vtop
->r
& VT_MUSTBOUND
)
5062 r
= vtop
->r
& VT_VALMASK
;
5066 /* need to reload if:
5068 - lvalue (need to dereference pointer)
5069 - already a register, but not in the right class */
5070 if (r
>= VT_CONST
||
5071 (vtop
->r
& VT_LVAL
) ||
5072 !(reg_classes
[r
] & rc
) ||
5073 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
5074 !(reg_classes
[vtop
->r2
] & rc2
))) {
5076 #ifndef TCC_TARGET_X86_64
5077 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
5079 unsigned long long ll
;
5080 /* two register type load : expand to two words
5082 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
5085 vtop
->c
.ui
= ll
; /* first word */
5087 vtop
->r
= r
; /* save register value */
5088 vpushi(ll
>> 32); /* second word */
5089 } else if (r
>= VT_CONST
|| /* XXX: test to VT_CONST incorrect ? */
5090 (vtop
->r
& VT_LVAL
)) {
5091 /* We do not want to modifier the long long
5092 pointer here, so the safest (and less
5093 efficient) is to save all the other registers
5094 in the stack. XXX: totally inefficient. */
5096 /* load from memory */
5099 vtop
[-1].r
= r
; /* save register value */
5100 /* increment pointer to get second word */
5101 vtop
->type
.t
= VT_INT
;
5107 /* move registers */
5110 vtop
[-1].r
= r
; /* save register value */
5111 vtop
->r
= vtop
[-1].r2
;
5113 /* allocate second register */
5117 /* write second register */
5121 if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
5123 /* lvalue of scalar type : need to use lvalue type
5124 because of possible cast */
5127 /* compute memory access type */
5128 if (vtop
->r
& VT_LVAL_BYTE
)
5130 else if (vtop
->r
& VT_LVAL_SHORT
)
5132 if (vtop
->r
& VT_LVAL_UNSIGNED
)
5136 /* restore wanted type */
5139 /* one register type load */
5144 #ifdef TCC_TARGET_C67
5145 /* uses register pairs for doubles */
5146 if ((vtop
->type
.t
& VT_BTYPE
) == VT_DOUBLE
)
5153 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
5154 void gv2(int rc1
, int rc2
)
5158 /* generate more generic register first. But VT_JMP or VT_CMP
5159 values must be generated first in all cases to avoid possible
5161 v
= vtop
[0].r
& VT_VALMASK
;
5162 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
5167 /* test if reload is needed for first register */
5168 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
5178 /* test if reload is needed for first register */
5179 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
5185 /* wrapper around RC_FRET to return a register by type */
5188 #ifdef TCC_TARGET_X86_64
5189 if (t
== VT_LDOUBLE
) {
5196 /* wrapper around REG_FRET to return a register by type */
5199 #ifdef TCC_TARGET_X86_64
5200 if (t
== VT_LDOUBLE
) {
5207 /* expand long long on stack in two int registers */
5212 u
= vtop
->type
.t
& VT_UNSIGNED
;
5215 vtop
[0].r
= vtop
[-1].r2
;
5216 vtop
[0].r2
= VT_CONST
;
5217 vtop
[-1].r2
= VT_CONST
;
5218 vtop
[0].type
.t
= VT_INT
| u
;
5219 vtop
[-1].type
.t
= VT_INT
| u
;
5222 #ifdef TCC_TARGET_ARM
5223 /* expand long long on stack */
5224 void lexpand_nr(void)
5228 u
= vtop
->type
.t
& VT_UNSIGNED
;
5230 vtop
->r2
= VT_CONST
;
5231 vtop
->type
.t
= VT_INT
| u
;
5232 v
=vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
);
5233 if (v
== VT_CONST
) {
5234 vtop
[-1].c
.ui
= vtop
->c
.ull
;
5235 vtop
->c
.ui
= vtop
->c
.ull
>> 32;
5237 } else if (v
== (VT_LVAL
|VT_CONST
) || v
== (VT_LVAL
|VT_LOCAL
)) {
5239 vtop
->r
= vtop
[-1].r
;
5240 } else if (v
> VT_CONST
) {
5244 vtop
->r
= vtop
[-1].r2
;
5245 vtop
[-1].r2
= VT_CONST
;
5246 vtop
[-1].type
.t
= VT_INT
| u
;
5250 /* build a long long from two ints */
5253 gv2(RC_INT
, RC_INT
);
5254 vtop
[-1].r2
= vtop
[0].r
;
5255 vtop
[-1].type
.t
= t
;
5259 /* rotate n first stack elements to the bottom
5260 I1 ... In -> I2 ... In I1 [top is right]
5268 for(i
=-n
+1;i
!=0;i
++)
5269 vtop
[i
] = vtop
[i
+1];
5273 /* rotate n first stack elements to the top
5274 I1 ... In -> In I1 ... I(n-1) [top is right]
5282 for(i
= 0;i
< n
- 1; i
++)
5283 vtop
[-i
] = vtop
[-i
- 1];
5287 #ifdef TCC_TARGET_ARM
5288 /* like vrott but in other direction
5289 In ... I1 -> I(n-1) ... I1 In [top is right]
5297 for(i
= n
- 1; i
> 0; i
--)
5298 vtop
[-i
] = vtop
[-i
+ 1];
5303 /* pop stack value */
5307 v
= vtop
->r
& VT_VALMASK
;
5308 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
5309 /* for x86, we need to pop the FP stack */
5310 if (v
== TREG_ST0
&& !nocode_wanted
) {
5311 o(0xd9dd); /* fstp %st(1) */
5314 if (v
== VT_JMP
|| v
== VT_JMPI
) {
5315 /* need to put correct jump if && or || without test */
5321 /* convert stack entry to register and duplicate its value in another
5329 if ((t
& VT_BTYPE
) == VT_LLONG
) {
5336 /* stack: H L L1 H1 */
5344 /* duplicate value */
5349 #ifdef TCC_TARGET_X86_64
5350 if ((t
& VT_BTYPE
) == VT_LDOUBLE
) {
5360 load(r1
, &sv
); /* move r to r1 */
5362 /* duplicates value */
5367 #ifndef TCC_TARGET_X86_64
5368 /* generate CPU independent (unsigned) long long operations */
5369 void gen_opl(int op
)
5371 int t
, a
, b
, op1
, c
, i
;
5373 unsigned short reg_iret
= REG_IRET
;
5374 unsigned short reg_lret
= REG_LRET
;
5380 func
= TOK___divdi3
;
5383 func
= TOK___udivdi3
;
5386 func
= TOK___moddi3
;
5389 func
= TOK___umoddi3
;
5396 /* call generic long long function */
5397 vpush_global_sym(&func_old_type
, func
);
5402 vtop
->r2
= reg_lret
;
5415 /* stack: L1 H1 L2 H2 */
5420 vtop
[-2] = vtop
[-3];
5423 /* stack: H1 H2 L1 L2 */
5429 /* stack: H1 H2 L1 L2 ML MH */
5432 /* stack: ML MH H1 H2 L1 L2 */
5436 /* stack: ML MH H1 L2 H2 L1 */
5441 /* stack: ML MH M1 M2 */
5444 } else if (op
== '+' || op
== '-') {
5445 /* XXX: add non carry method too (for MIPS or alpha) */
5451 /* stack: H1 H2 (L1 op L2) */
5454 gen_op(op1
+ 1); /* TOK_xxxC2 */
5457 /* stack: H1 H2 (L1 op L2) */
5460 /* stack: (L1 op L2) H1 H2 */
5462 /* stack: (L1 op L2) (H1 op H2) */
5470 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
5471 t
= vtop
[-1].type
.t
;
5475 /* stack: L H shift */
5477 /* constant: simpler */
5478 /* NOTE: all comments are for SHL. the other cases are
5479 done by swaping words */
5490 if (op
!= TOK_SAR
) {
5523 /* XXX: should provide a faster fallback on x86 ? */
5526 func
= TOK___ashrdi3
;
5529 func
= TOK___lshrdi3
;
5532 func
= TOK___ashldi3
;
5538 /* compare operations */
5544 /* stack: L1 H1 L2 H2 */
5546 vtop
[-1] = vtop
[-2];
5548 /* stack: L1 L2 H1 H2 */
5551 /* when values are equal, we need to compare low words. since
5552 the jump is inverted, we invert the test too. */
5555 else if (op1
== TOK_GT
)
5557 else if (op1
== TOK_ULT
)
5559 else if (op1
== TOK_UGT
)
5564 if (op1
!= TOK_NE
) {
5568 /* generate non equal test */
5569 /* XXX: NOT PORTABLE yet */
5573 #if defined(TCC_TARGET_I386)
5574 b
= psym(0x850f, 0);
5575 #elif defined(TCC_TARGET_ARM)
5577 o(0x1A000000 | encbranch(ind
, 0, 1));
5578 #elif defined(TCC_TARGET_C67)
5579 error("not implemented");
5581 #error not supported
5585 /* compare low. Always unsigned */
5589 else if (op1
== TOK_LE
)
5591 else if (op1
== TOK_GT
)
5593 else if (op1
== TOK_GE
)
5604 /* handle integer constant optimizations and various machine
5606 void gen_opic(int op
)
5608 int c1
, c2
, t1
, t2
, n
;
5611 typedef unsigned long long U
;
5615 t1
= v1
->type
.t
& VT_BTYPE
;
5616 t2
= v2
->type
.t
& VT_BTYPE
;
5620 else if (v1
->type
.t
& VT_UNSIGNED
)
5627 else if (v2
->type
.t
& VT_UNSIGNED
)
5632 /* currently, we cannot do computations with forward symbols */
5633 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5634 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5637 case '+': l1
+= l2
; break;
5638 case '-': l1
-= l2
; break;
5639 case '&': l1
&= l2
; break;
5640 case '^': l1
^= l2
; break;
5641 case '|': l1
|= l2
; break;
5642 case '*': l1
*= l2
; break;
5649 /* if division by zero, generate explicit division */
5652 error("division by zero in constant");
5656 default: l1
/= l2
; break;
5657 case '%': l1
%= l2
; break;
5658 case TOK_UDIV
: l1
= (U
)l1
/ l2
; break;
5659 case TOK_UMOD
: l1
= (U
)l1
% l2
; break;
5662 case TOK_SHL
: l1
<<= l2
; break;
5663 case TOK_SHR
: l1
= (U
)l1
>> l2
; break;
5664 case TOK_SAR
: l1
>>= l2
; break;
5666 case TOK_ULT
: l1
= (U
)l1
< (U
)l2
; break;
5667 case TOK_UGE
: l1
= (U
)l1
>= (U
)l2
; break;
5668 case TOK_EQ
: l1
= l1
== l2
; break;
5669 case TOK_NE
: l1
= l1
!= l2
; break;
5670 case TOK_ULE
: l1
= (U
)l1
<= (U
)l2
; break;
5671 case TOK_UGT
: l1
= (U
)l1
> (U
)l2
; break;
5672 case TOK_LT
: l1
= l1
< l2
; break;
5673 case TOK_GE
: l1
= l1
>= l2
; break;
5674 case TOK_LE
: l1
= l1
<= l2
; break;
5675 case TOK_GT
: l1
= l1
> l2
; break;
5677 case TOK_LAND
: l1
= l1
&& l2
; break;
5678 case TOK_LOR
: l1
= l1
|| l2
; break;
5685 /* if commutative ops, put c2 as constant */
5686 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
5687 op
== '|' || op
== '*')) {
5689 c2
= c1
; //c = c1, c1 = c2, c2 = c;
5690 l2
= l1
; //l = l1, l1 = l2, l2 = l;
5692 /* Filter out NOP operations like x*1, x-0, x&-1... */
5693 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
5696 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
5697 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
5703 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
5704 /* try to use shifts instead of muls or divs */
5705 if (l2
> 0 && (l2
& (l2
- 1)) == 0) {
5714 else if (op
== TOK_PDIV
)
5720 } else if (c2
&& (op
== '+' || op
== '-') &&
5721 ((vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5722 (VT_CONST
| VT_SYM
) ||
5723 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
)) == VT_LOCAL
)) {
5724 /* symbol + constant case */
5731 if (!nocode_wanted
) {
5732 /* call low level op generator */
5733 if (t1
== VT_LLONG
|| t2
== VT_LLONG
)
5744 /* generate a floating point operation with constant propagation */
5745 void gen_opif(int op
)
5753 /* currently, we cannot do computations with forward symbols */
5754 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5755 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5757 if (v1
->type
.t
== VT_FLOAT
) {
5760 } else if (v1
->type
.t
== VT_DOUBLE
) {
5768 /* NOTE: we only do constant propagation if finite number (not
5769 NaN or infinity) (ANSI spec) */
5770 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5774 case '+': f1
+= f2
; break;
5775 case '-': f1
-= f2
; break;
5776 case '*': f1
*= f2
; break;
5780 error("division by zero in constant");
5785 /* XXX: also handles tests ? */
5789 /* XXX: overflow test ? */
5790 if (v1
->type
.t
== VT_FLOAT
) {
5792 } else if (v1
->type
.t
== VT_DOUBLE
) {
5800 if (!nocode_wanted
) {
5808 static int pointed_size(CType
*type
)
5811 return type_size(pointed_type(type
), &align
);
5814 static inline int is_null_pointer(SValue
*p
)
5816 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5818 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5819 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5822 static inline int is_integer_btype(int bt
)
5824 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5825 bt
== VT_INT
|| bt
== VT_LLONG
);
5828 /* check types for comparison or substraction of pointers */
5829 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5831 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5834 /* null pointers are accepted for all comparisons as gcc */
5835 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5839 bt1
= type1
->t
& VT_BTYPE
;
5840 bt2
= type2
->t
& VT_BTYPE
;
5841 /* accept comparison between pointer and integer with a warning */
5842 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5843 if (op
!= TOK_LOR
&& op
!= TOK_LAND
)
5844 warning("comparison between pointer and integer");
5848 /* both must be pointers or implicit function pointers */
5849 if (bt1
== VT_PTR
) {
5850 type1
= pointed_type(type1
);
5851 } else if (bt1
!= VT_FUNC
)
5852 goto invalid_operands
;
5854 if (bt2
== VT_PTR
) {
5855 type2
= pointed_type(type2
);
5856 } else if (bt2
!= VT_FUNC
) {
5858 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5860 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5861 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5865 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5866 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5867 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5868 /* gcc-like error if '-' is used */
5870 goto invalid_operands
;
5872 warning("comparison of distinct pointer types lacks a cast");
5876 /* generic gen_op: handles types problems */
5879 int u
, t1
, t2
, bt1
, bt2
, t
;
5882 t1
= vtop
[-1].type
.t
;
5883 t2
= vtop
[0].type
.t
;
5884 bt1
= t1
& VT_BTYPE
;
5885 bt2
= t2
& VT_BTYPE
;
5887 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5888 /* at least one operand is a pointer */
5889 /* relationnal op: must be both pointers */
5890 if (op
>= TOK_ULT
&& op
<= TOK_LOR
) {
5891 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5892 /* pointers are handled are unsigned */
5893 #ifdef TCC_TARGET_X86_64
5894 t
= VT_LLONG
| VT_UNSIGNED
;
5896 t
= VT_INT
| VT_UNSIGNED
;
5900 /* if both pointers, then it must be the '-' op */
5901 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5903 error("cannot use pointers here");
5904 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5905 /* XXX: check that types are compatible */
5906 u
= pointed_size(&vtop
[-1].type
);
5908 /* set to integer type */
5909 #ifdef TCC_TARGET_X86_64
5910 vtop
->type
.t
= VT_LLONG
;
5912 vtop
->type
.t
= VT_INT
;
5917 /* exactly one pointer : must be '+' or '-'. */
5918 if (op
!= '-' && op
!= '+')
5919 error("cannot use pointers here");
5920 /* Put pointer as first operand */
5921 if (bt2
== VT_PTR
) {
5925 type1
= vtop
[-1].type
;
5926 #ifdef TCC_TARGET_X86_64
5927 vpushll(pointed_size(&vtop
[-1].type
));
5929 /* XXX: cast to int ? (long long case) */
5930 vpushi(pointed_size(&vtop
[-1].type
));
5933 #ifdef CONFIG_TCC_BCHECK
5934 /* if evaluating constant expression, no code should be
5935 generated, so no bound check */
5936 if (do_bounds_check
&& !const_wanted
) {
5937 /* if bounded pointers, we generate a special code to
5944 gen_bounded_ptr_add();
5950 /* put again type if gen_opic() swaped operands */
5953 } else if (is_float(bt1
) || is_float(bt2
)) {
5954 /* compute bigger type and do implicit casts */
5955 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5957 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5962 /* floats can only be used for a few operations */
5963 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5964 (op
< TOK_ULT
|| op
> TOK_GT
))
5965 error("invalid operands for binary operation");
5967 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5968 /* cast to biggest op */
5970 /* convert to unsigned if it does not fit in a long long */
5971 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5972 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5976 /* integer operations */
5978 /* convert to unsigned if it does not fit in an integer */
5979 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5980 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5983 /* XXX: currently, some unsigned operations are explicit, so
5984 we modify them here */
5985 if (t
& VT_UNSIGNED
) {
5992 else if (op
== TOK_LT
)
5994 else if (op
== TOK_GT
)
5996 else if (op
== TOK_LE
)
5998 else if (op
== TOK_GE
)
6005 /* special case for shifts and long long: we keep the shift as
6007 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
6014 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
6015 /* relationnal op: the result is an int */
6016 vtop
->type
.t
= VT_INT
;
6023 #ifndef TCC_TARGET_ARM
6024 /* generic itof for unsigned long long case */
6025 void gen_cvt_itof1(int t
)
6027 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
6028 (VT_LLONG
| VT_UNSIGNED
)) {
6031 vpush_global_sym(&func_old_type
, TOK___floatundisf
);
6032 #if LDOUBLE_SIZE != 8
6033 else if (t
== VT_LDOUBLE
)
6034 vpush_global_sym(&func_old_type
, TOK___floatundixf
);
6037 vpush_global_sym(&func_old_type
, TOK___floatundidf
);
6041 vtop
->r
= reg_fret(t
);
6048 /* generic ftoi for unsigned long long case */
6049 void gen_cvt_ftoi1(int t
)
6053 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
6054 /* not handled natively */
6055 st
= vtop
->type
.t
& VT_BTYPE
;
6057 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
6058 #if LDOUBLE_SIZE != 8
6059 else if (st
== VT_LDOUBLE
)
6060 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
6063 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
6068 vtop
->r2
= REG_LRET
;
6074 /* force char or short cast */
6075 void force_charshort_cast(int t
)
6079 /* XXX: add optimization if lvalue : just change type and offset */
6084 if (t
& VT_UNSIGNED
) {
6085 vpushi((1 << bits
) - 1);
6091 /* result must be signed or the SAR is converted to an SHL
6092 This was not the case when "t" was a signed short
6093 and the last value on the stack was an unsigned int */
6094 vtop
->type
.t
&= ~VT_UNSIGNED
;
6100 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
6101 static void gen_cast(CType
*type
)
6103 int sbt
, dbt
, sf
, df
, c
, p
;
6105 /* special delayed cast for char/short */
6106 /* XXX: in some cases (multiple cascaded casts), it may still
6108 if (vtop
->r
& VT_MUSTCAST
) {
6109 vtop
->r
&= ~VT_MUSTCAST
;
6110 force_charshort_cast(vtop
->type
.t
);
6113 /* bitfields first get cast to ints */
6114 if (vtop
->type
.t
& VT_BITFIELD
) {
6118 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
6119 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
6124 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
6125 p
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == (VT_CONST
| VT_SYM
);
6127 /* constant case: we can do it now */
6128 /* XXX: in ISOC, cannot do it if error in convert */
6129 if (sbt
== VT_FLOAT
)
6130 vtop
->c
.ld
= vtop
->c
.f
;
6131 else if (sbt
== VT_DOUBLE
)
6132 vtop
->c
.ld
= vtop
->c
.d
;
6135 if ((sbt
& VT_BTYPE
) == VT_LLONG
) {
6136 if (sbt
& VT_UNSIGNED
)
6137 vtop
->c
.ld
= vtop
->c
.ull
;
6139 vtop
->c
.ld
= vtop
->c
.ll
;
6141 if (sbt
& VT_UNSIGNED
)
6142 vtop
->c
.ld
= vtop
->c
.ui
;
6144 vtop
->c
.ld
= vtop
->c
.i
;
6147 if (dbt
== VT_FLOAT
)
6148 vtop
->c
.f
= (float)vtop
->c
.ld
;
6149 else if (dbt
== VT_DOUBLE
)
6150 vtop
->c
.d
= (double)vtop
->c
.ld
;
6151 } else if (sf
&& dbt
== (VT_LLONG
|VT_UNSIGNED
)) {
6152 vtop
->c
.ull
= (unsigned long long)vtop
->c
.ld
;
6153 } else if (sf
&& dbt
== VT_BOOL
) {
6154 vtop
->c
.i
= (vtop
->c
.ld
!= 0);
6157 vtop
->c
.ll
= (long long)vtop
->c
.ld
;
6158 else if (sbt
== (VT_LLONG
|VT_UNSIGNED
))
6159 vtop
->c
.ll
= vtop
->c
.ull
;
6160 else if (sbt
& VT_UNSIGNED
)
6161 vtop
->c
.ll
= vtop
->c
.ui
;
6162 else if (sbt
!= VT_LLONG
)
6163 vtop
->c
.ll
= vtop
->c
.i
;
6165 if (dbt
== (VT_LLONG
|VT_UNSIGNED
))
6166 vtop
->c
.ull
= vtop
->c
.ll
;
6167 else if (dbt
== VT_BOOL
)
6168 vtop
->c
.i
= (vtop
->c
.ll
!= 0);
6169 else if (dbt
!= VT_LLONG
) {
6171 if ((dbt
& VT_BTYPE
) == VT_BYTE
)
6173 else if ((dbt
& VT_BTYPE
) == VT_SHORT
)
6176 if(dbt
& VT_UNSIGNED
)
6177 vtop
->c
.ui
= ((unsigned int)vtop
->c
.ll
<< s
) >> s
;
6179 vtop
->c
.i
= ((int)vtop
->c
.ll
<< s
) >> s
;
6182 } else if (p
&& dbt
== VT_BOOL
) {
6185 } else if (!nocode_wanted
) {
6186 /* non constant case: generate code */
6188 /* convert from fp to fp */
6191 /* convert int to fp */
6194 /* convert fp to int */
6195 if (dbt
== VT_BOOL
) {
6199 /* we handle char/short/etc... with generic code */
6200 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
6201 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
6205 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
6206 /* additional cast for char/short... */
6211 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
6212 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
6213 /* scalar to long long */
6214 #ifndef TCC_TARGET_X86_64
6215 /* machine independent conversion */
6217 /* generate high word */
6218 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
6226 /* patch second register */
6227 vtop
[-1].r2
= vtop
->r
;
6231 if (sbt
!= (VT_INT
| VT_UNSIGNED
)) {
6232 /* x86_64 specific: movslq */
6234 o(0xc0 + (REG_VALUE(r
) << 3) + REG_VALUE(r
));
6238 } else if (dbt
== VT_BOOL
) {
6239 /* scalar to bool */
6242 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
6243 (dbt
& VT_BTYPE
) == VT_SHORT
) {
6244 if (sbt
== VT_PTR
) {
6245 vtop
->type
.t
= VT_INT
;
6246 warning("nonportable conversion from pointer to char/short");
6248 force_charshort_cast(dbt
);
6249 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
6251 if (sbt
== VT_LLONG
) {
6252 /* from long long: just take low order word */
6256 /* if lvalue and single word type, nothing to do because
6257 the lvalue already contains the real type size (see
6258 VT_LVAL_xxx constants) */
6261 } else if ((dbt
& VT_BTYPE
) == VT_PTR
&& !(vtop
->r
& VT_LVAL
)) {
6262 /* if we are casting between pointer types,
6263 we must update the VT_LVAL_xxx size */
6264 vtop
->r
= (vtop
->r
& ~VT_LVAL_TYPE
)
6265 | (lvalue_type(type
->ref
->type
.t
) & VT_LVAL_TYPE
);
6270 /* return type size. Put alignment at 'a' */
6271 static int type_size(CType
*type
, int *a
)
6276 bt
= type
->t
& VT_BTYPE
;
6277 if (bt
== VT_STRUCT
) {
6282 } else if (bt
== VT_PTR
) {
6283 if (type
->t
& VT_ARRAY
) {
6287 ts
= type_size(&s
->type
, a
);
6289 if (ts
< 0 && s
->c
< 0)
6297 } else if (bt
== VT_LDOUBLE
) {
6299 return LDOUBLE_SIZE
;
6300 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
6301 #ifdef TCC_TARGET_I386
6302 #ifdef TCC_TARGET_PE
6307 #elif defined(TCC_TARGET_ARM)
6317 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
6320 } else if (bt
== VT_SHORT
) {
6324 /* char, void, function, _Bool */
6330 /* return the pointed type of t */
6331 static inline CType
*pointed_type(CType
*type
)
6333 return &type
->ref
->type
;
6336 /* modify type so that its it is a pointer to type. */
6337 static void mk_pointer(CType
*type
)
6340 s
= sym_push(SYM_FIELD
, type
, 0, -1);
6341 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
6345 /* compare function types. OLD functions match any new functions */
6346 static int is_compatible_func(CType
*type1
, CType
*type2
)
6352 if (!is_compatible_types(&s1
->type
, &s2
->type
))
6354 /* check func_call */
6355 if (FUNC_CALL(s1
->r
) != FUNC_CALL(s2
->r
))
6357 /* XXX: not complete */
6358 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
6362 while (s1
!= NULL
) {
6365 if (!is_compatible_parameter_types(&s1
->type
, &s2
->type
))
6375 /* return true if type1 and type2 are the same. If unqualified is
6376 true, qualifiers on the types are ignored.
6378 - enums are not checked as gcc __builtin_types_compatible_p ()
6380 static int compare_types(CType
*type1
, CType
*type2
, int unqualified
)
6384 t1
= type1
->t
& VT_TYPE
;
6385 t2
= type2
->t
& VT_TYPE
;
6387 /* strip qualifiers before comparing */
6388 t1
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6389 t2
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6391 /* XXX: bitfields ? */
6394 /* test more complicated cases */
6395 bt1
= t1
& VT_BTYPE
;
6396 if (bt1
== VT_PTR
) {
6397 type1
= pointed_type(type1
);
6398 type2
= pointed_type(type2
);
6399 return is_compatible_types(type1
, type2
);
6400 } else if (bt1
== VT_STRUCT
) {
6401 return (type1
->ref
== type2
->ref
);
6402 } else if (bt1
== VT_FUNC
) {
6403 return is_compatible_func(type1
, type2
);
6409 /* return true if type1 and type2 are exactly the same (including
6412 static int is_compatible_types(CType
*type1
, CType
*type2
)
6414 return compare_types(type1
,type2
,0);
6417 /* return true if type1 and type2 are the same (ignoring qualifiers).
6419 static int is_compatible_parameter_types(CType
*type1
, CType
*type2
)
6421 return compare_types(type1
,type2
,1);
6424 /* print a type. If 'varstr' is not NULL, then the variable is also
6425 printed in the type */
6427 /* XXX: add array and function pointers */
6428 void type_to_str(char *buf
, int buf_size
,
6429 CType
*type
, const char *varstr
)
6436 t
= type
->t
& VT_TYPE
;
6439 if (t
& VT_CONSTANT
)
6440 pstrcat(buf
, buf_size
, "const ");
6441 if (t
& VT_VOLATILE
)
6442 pstrcat(buf
, buf_size
, "volatile ");
6443 if (t
& VT_UNSIGNED
)
6444 pstrcat(buf
, buf_size
, "unsigned ");
6474 tstr
= "long double";
6476 pstrcat(buf
, buf_size
, tstr
);
6480 if (bt
== VT_STRUCT
)
6484 pstrcat(buf
, buf_size
, tstr
);
6485 v
= type
->ref
->v
& ~SYM_STRUCT
;
6486 if (v
>= SYM_FIRST_ANOM
)
6487 pstrcat(buf
, buf_size
, "<anonymous>");
6489 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
6493 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
6494 pstrcat(buf
, buf_size
, "(");
6496 while (sa
!= NULL
) {
6497 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
6498 pstrcat(buf
, buf_size
, buf1
);
6501 pstrcat(buf
, buf_size
, ", ");
6503 pstrcat(buf
, buf_size
, ")");
6507 pstrcpy(buf1
, sizeof(buf1
), "*");
6509 pstrcat(buf1
, sizeof(buf1
), varstr
);
6510 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
6514 pstrcat(buf
, buf_size
, " ");
6515 pstrcat(buf
, buf_size
, varstr
);
6520 /* verify type compatibility to store vtop in 'dt' type, and generate
6522 static void gen_assign_cast(CType
*dt
)
6524 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
6525 char buf1
[256], buf2
[256];
6528 st
= &vtop
->type
; /* source type */
6529 dbt
= dt
->t
& VT_BTYPE
;
6530 sbt
= st
->t
& VT_BTYPE
;
6531 if (dt
->t
& VT_CONSTANT
)
6532 warning("assignment of read-only location");
6535 /* special cases for pointers */
6536 /* '0' can also be a pointer */
6537 if (is_null_pointer(vtop
))
6539 /* accept implicit pointer to integer cast with warning */
6540 if (is_integer_btype(sbt
)) {
6541 warning("assignment makes pointer from integer without a cast");
6544 type1
= pointed_type(dt
);
6545 /* a function is implicitely a function pointer */
6546 if (sbt
== VT_FUNC
) {
6547 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
6548 !is_compatible_types(pointed_type(dt
), st
))
6555 type2
= pointed_type(st
);
6556 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
6557 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
6558 /* void * can match anything */
6560 /* exact type match, except for unsigned */
6563 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6564 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6565 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
6566 warning("assignment from incompatible pointer type");
6568 /* check const and volatile */
6569 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
6570 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
6571 warning("assignment discards qualifiers from pointer target type");
6577 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
6578 warning("assignment makes integer from pointer without a cast");
6580 /* XXX: more tests */
6585 tmp_type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6586 tmp_type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6587 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
6589 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
6590 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
6591 error("cannot cast '%s' to '%s'", buf1
, buf2
);
6599 /* store vtop in lvalue pushed on stack */
6602 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
6604 ft
= vtop
[-1].type
.t
;
6605 sbt
= vtop
->type
.t
& VT_BTYPE
;
6606 dbt
= ft
& VT_BTYPE
;
6607 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
6608 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
6609 /* optimize char/short casts */
6610 delayed_cast
= VT_MUSTCAST
;
6611 vtop
->type
.t
= ft
& (VT_TYPE
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
)));
6612 /* XXX: factorize */
6613 if (ft
& VT_CONSTANT
)
6614 warning("assignment of read-only location");
6617 if (!(ft
& VT_BITFIELD
))
6618 gen_assign_cast(&vtop
[-1].type
);
6621 if (sbt
== VT_STRUCT
) {
6622 /* if structure, only generate pointer */
6623 /* structure assignment : generate memcpy */
6624 /* XXX: optimize if small size */
6625 if (!nocode_wanted
) {
6626 size
= type_size(&vtop
->type
, &align
);
6630 vpush_global_sym(&func_old_type
, TOK_memcpy8
);
6631 else if(!(align
& 3))
6632 vpush_global_sym(&func_old_type
, TOK_memcpy4
);
6635 vpush_global_sym(&func_old_type
, TOK_memcpy
);
6639 vtop
->type
.t
= VT_PTR
;
6643 vtop
->type
.t
= VT_PTR
;
6655 /* leave source on stack */
6656 } else if (ft
& VT_BITFIELD
) {
6657 /* bitfield store handling */
6658 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
6659 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
6660 /* remove bit field info to avoid loops */
6661 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
6663 /* duplicate source into other register */
6668 if((ft
& VT_BTYPE
) == VT_BOOL
) {
6669 gen_cast(&vtop
[-1].type
);
6670 vtop
[-1].type
.t
= (vtop
[-1].type
.t
& ~VT_BTYPE
) | (VT_BYTE
| VT_UNSIGNED
);
6673 /* duplicate destination */
6675 vtop
[-1] = vtop
[-2];
6677 /* mask and shift source */
6678 if((ft
& VT_BTYPE
) != VT_BOOL
) {
6679 if((ft
& VT_BTYPE
) == VT_LLONG
) {
6680 vpushll((1ULL << bit_size
) - 1ULL);
6682 vpushi((1 << bit_size
) - 1);
6688 /* load destination, mask and or with source */
6690 if((ft
& VT_BTYPE
) == VT_LLONG
) {
6691 vpushll(~(((1ULL << bit_size
) - 1ULL) << bit_pos
));
6693 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
6700 /* pop off shifted source from "duplicate source..." above */
6704 #ifdef CONFIG_TCC_BCHECK
6705 /* bound check case */
6706 if (vtop
[-1].r
& VT_MUSTBOUND
) {
6712 if (!nocode_wanted
) {
6716 #ifdef TCC_TARGET_X86_64
6717 if ((ft
& VT_BTYPE
) == VT_LDOUBLE
) {
6722 r
= gv(rc
); /* generate value */
6723 /* if lvalue was saved on stack, must read it */
6724 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
6726 t
= get_reg(RC_INT
);
6727 #ifdef TCC_TARGET_X86_64
6732 sv
.r
= VT_LOCAL
| VT_LVAL
;
6733 sv
.c
.ul
= vtop
[-1].c
.ul
;
6735 vtop
[-1].r
= t
| VT_LVAL
;
6738 #ifndef TCC_TARGET_X86_64
6739 /* two word case handling : store second register at word + 4 */
6740 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
6742 /* convert to int to increment easily */
6743 vtop
->type
.t
= VT_INT
;
6749 /* XXX: it works because r2 is spilled last ! */
6750 store(vtop
->r2
, vtop
- 1);
6755 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
6756 vtop
->r
|= delayed_cast
;
6760 /* post defines POST/PRE add. c is the token ++ or -- */
6761 void inc(int post
, int c
)
6764 vdup(); /* save lvalue */
6766 gv_dup(); /* duplicate value */
6771 vpushi(c
- TOK_MID
);
6773 vstore(); /* store value */
6775 vpop(); /* if post op, return saved value */
6778 /* Parse GNUC __attribute__ extension. Currently, the following
6779 extensions are recognized:
6780 - aligned(n) : set data/function alignment.
6781 - packed : force data alignment to 1
6782 - section(x) : generate data/code in this section.
6783 - unused : currently ignored, but may be used someday.
6784 - regparm(n) : pass function parameters in registers (i386 only)
6786 static void parse_attribute(AttributeDef
*ad
)
6790 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
6794 while (tok
!= ')') {
6795 if (tok
< TOK_IDENT
)
6796 expect("attribute name");
6804 expect("section name");
6805 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
6814 if (n
<= 0 || (n
& (n
- 1)) != 0)
6815 error("alignment must be a positive power of two");
6828 /* currently, no need to handle it because tcc does not
6829 track unused objects */
6833 /* currently, no need to handle it because tcc does not
6834 track unused objects */
6839 FUNC_CALL(ad
->func_attr
) = FUNC_CDECL
;
6844 FUNC_CALL(ad
->func_attr
) = FUNC_STDCALL
;
6846 #ifdef TCC_TARGET_I386
6856 FUNC_CALL(ad
->func_attr
) = FUNC_FASTCALL1
+ n
- 1;
6862 FUNC_CALL(ad
->func_attr
) = FUNC_FASTCALLW
;
6866 FUNC_EXPORT(ad
->func_attr
) = 1;
6869 if (tcc_state
->warn_unsupported
)
6870 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6871 /* skip parameters */
6873 int parenthesis
= 0;
6877 else if (tok
== ')')
6880 } while (parenthesis
&& tok
!= -1);
6893 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6894 static void struct_decl(CType
*type
, int u
)
6896 int a
, v
, size
, align
, maxalign
, c
, offset
;
6897 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
, prevbt
;
6898 Sym
*s
, *ss
, *ass
, **ps
;
6902 a
= tok
; /* save decl type */
6907 /* struct already defined ? return it */
6909 expect("struct/union/enum name");
6913 error("invalid type");
6920 /* we put an undefined size for struct/union */
6921 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6922 s
->r
= 0; /* default alignment is zero as gcc */
6923 /* put struct/union/enum name in type */
6931 error("struct/union/enum already defined");
6932 /* cannot be empty */
6934 /* non empty enums are not allowed */
6935 if (a
== TOK_ENUM
) {
6939 expect("identifier");
6945 /* enum symbols have static storage */
6946 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6947 ss
->type
.t
|= VT_STATIC
;
6952 /* NOTE: we accept a trailing comma */
6963 while (tok
!= '}') {
6964 parse_btype(&btype
, &ad
);
6970 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6971 if (v
== 0 && (type1
.t
& VT_BTYPE
) != VT_STRUCT
)
6972 expect("identifier");
6973 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6974 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6975 error("invalid type for '%s'",
6976 get_tok_str(v
, NULL
));
6980 bit_size
= expr_const();
6981 /* XXX: handle v = 0 case for messages */
6983 error("negative width in bit-field '%s'",
6984 get_tok_str(v
, NULL
));
6985 if (v
&& bit_size
== 0)
6986 error("zero width for bit-field '%s'",
6987 get_tok_str(v
, NULL
));
6989 size
= type_size(&type1
, &align
);
6991 if (align
< ad
.aligned
)
6993 } else if (ad
.packed
) {
6995 } else if (*tcc_state
->pack_stack_ptr
) {
6996 if (align
> *tcc_state
->pack_stack_ptr
)
6997 align
= *tcc_state
->pack_stack_ptr
;
7000 if (bit_size
>= 0) {
7001 bt
= type1
.t
& VT_BTYPE
;
7008 error("bitfields must have scalar type");
7010 if (bit_size
> bsize
) {
7011 error("width of '%s' exceeds its type",
7012 get_tok_str(v
, NULL
));
7013 } else if (bit_size
== bsize
) {
7014 /* no need for bit fields */
7016 } else if (bit_size
== 0) {
7017 /* XXX: what to do if only padding in a
7019 /* zero size: means to pad */
7022 /* we do not have enough room ?
7023 did the type change?
7025 if ((bit_pos
+ bit_size
) > bsize
||
7026 bt
!= prevbt
|| a
== TOK_UNION
)
7029 /* XXX: handle LSB first */
7030 type1
.t
|= VT_BITFIELD
|
7031 (bit_pos
<< VT_STRUCT_SHIFT
) |
7032 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
7033 bit_pos
+= bit_size
;
7039 if (v
!= 0 || (type1
.t
& VT_BTYPE
) == VT_STRUCT
) {
7040 /* add new memory data only if starting
7042 if (lbit_pos
== 0) {
7043 if (a
== TOK_STRUCT
) {
7044 c
= (c
+ align
- 1) & -align
;
7053 if (align
> maxalign
)
7057 printf("add field %s offset=%d",
7058 get_tok_str(v
, NULL
), offset
);
7059 if (type1
.t
& VT_BITFIELD
) {
7060 printf(" pos=%d size=%d",
7061 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
7062 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
7067 if (v
== 0 && (type1
.t
& VT_BTYPE
) == VT_STRUCT
) {
7069 while ((ass
= ass
->next
) != NULL
) {
7070 ss
= sym_push(ass
->v
, &ass
->type
, 0, offset
+ ass
->c
);
7075 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
7079 if (tok
== ';' || tok
== TOK_EOF
)
7086 /* store size and alignment */
7087 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
7093 /* return 0 if no type declaration. otherwise, return the basic type
7096 static int parse_btype(CType
*type
, AttributeDef
*ad
)
7098 int t
, u
, type_found
, typespec_found
, typedef_found
;
7102 memset(ad
, 0, sizeof(AttributeDef
));
7110 /* currently, we really ignore extension */
7120 if ((t
& VT_BTYPE
) != 0)
7121 error("too many basic types");
7137 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
7138 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
7139 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
7140 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
7154 if ((t
& VT_BTYPE
) == VT_LONG
) {
7155 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
7162 struct_decl(&type1
, VT_ENUM
);
7165 type
->ref
= type1
.ref
;
7169 struct_decl(&type1
, VT_STRUCT
);
7172 /* type modifiers */
7225 /* GNUC attribute */
7226 case TOK_ATTRIBUTE1
:
7227 case TOK_ATTRIBUTE2
:
7228 parse_attribute(ad
);
7235 parse_expr_type(&type1
);
7238 if (typespec_found
|| typedef_found
)
7241 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
7244 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
7245 type
->ref
= s
->type
.ref
;
7253 if ((t
& (VT_SIGNED
|VT_UNSIGNED
)) == (VT_SIGNED
|VT_UNSIGNED
))
7254 error("signed and unsigned modifier");
7255 if (tcc_state
->char_is_unsigned
) {
7256 if ((t
& (VT_SIGNED
|VT_UNSIGNED
|VT_BTYPE
)) == VT_BYTE
)
7261 /* long is never used as type */
7262 if ((t
& VT_BTYPE
) == VT_LONG
)
7263 #ifndef TCC_TARGET_X86_64
7264 t
= (t
& ~VT_BTYPE
) | VT_INT
;
7266 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
7272 /* convert a function parameter type (array to pointer and function to
7273 function pointer) */
7274 static inline void convert_parameter_type(CType
*pt
)
7276 /* remove const and volatile qualifiers (XXX: const could be used
7277 to indicate a const function parameter */
7278 pt
->t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7279 /* array must be transformed to pointer according to ANSI C */
7281 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
7286 static void post_type(CType
*type
, AttributeDef
*ad
)
7288 int n
, l
, t1
, arg_size
, align
;
7289 Sym
**plast
, *s
, *first
;
7294 /* function declaration */
7302 /* read param name and compute offset */
7303 if (l
!= FUNC_OLD
) {
7304 if (!parse_btype(&pt
, &ad1
)) {
7306 error("invalid type");
7313 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
7315 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
7316 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
7317 error("parameter declared as void");
7318 arg_size
+= (type_size(&pt
, &align
) + 3) & ~3;
7323 expect("identifier");
7327 convert_parameter_type(&pt
);
7328 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
7334 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
7341 /* if no parameters, then old type prototype */
7345 t1
= type
->t
& VT_STORAGE
;
7346 /* NOTE: const is ignored in returned type as it has a special
7347 meaning in gcc / C++ */
7348 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
7349 post_type(type
, ad
);
7350 /* we push a anonymous symbol which will contain the function prototype */
7351 FUNC_ARGS(ad
->func_attr
) = arg_size
;
7352 s
= sym_push(SYM_FIELD
, type
, ad
->func_attr
, l
);
7354 type
->t
= t1
| VT_FUNC
;
7356 } else if (tok
== '[') {
7357 /* array definition */
7359 if (tok
== TOK_RESTRICT1
)
7365 error("invalid array size");
7368 /* parse next post type */
7369 t1
= type
->t
& VT_STORAGE
;
7370 type
->t
&= ~VT_STORAGE
;
7371 post_type(type
, ad
);
7373 /* we push a anonymous symbol which will contain the array
7375 s
= sym_push(SYM_FIELD
, type
, 0, n
);
7376 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
7381 /* Parse a type declaration (except basic type), and return the type
7382 in 'type'. 'td' is a bitmask indicating which kind of type decl is
7383 expected. 'type' should contain the basic type. 'ad' is the
7384 attribute definition of the basic type. It can be modified by
7387 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
7390 CType type1
, *type2
;
7393 while (tok
== '*') {
7401 qualifiers
|= VT_CONSTANT
;
7406 qualifiers
|= VT_VOLATILE
;
7414 type
->t
|= qualifiers
;
7417 /* XXX: clarify attribute handling */
7418 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7419 parse_attribute(ad
);
7421 /* recursive type */
7422 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
7423 type1
.t
= 0; /* XXX: same as int */
7426 /* XXX: this is not correct to modify 'ad' at this point, but
7427 the syntax is not clear */
7428 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7429 parse_attribute(ad
);
7430 type_decl(&type1
, ad
, v
, td
);
7433 /* type identifier */
7434 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
7438 if (!(td
& TYPE_ABSTRACT
))
7439 expect("identifier");
7443 post_type(type
, ad
);
7444 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7445 parse_attribute(ad
);
7448 /* append type at the end of type1 */
7461 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
7462 static int lvalue_type(int t
)
7467 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
7469 else if (bt
== VT_SHORT
)
7473 if (t
& VT_UNSIGNED
)
7474 r
|= VT_LVAL_UNSIGNED
;
7478 /* indirection with full error checking and bound check */
7479 static void indir(void)
7481 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
) {
7482 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FUNC
)
7486 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
7488 vtop
->type
= *pointed_type(&vtop
->type
);
7489 /* Arrays and functions are never lvalues */
7490 if (!(vtop
->type
.t
& VT_ARRAY
)
7491 && (vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7492 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7493 /* if bound checking, the referenced pointer must be checked */
7494 if (do_bounds_check
)
7495 vtop
->r
|= VT_MUSTBOUND
;
7499 /* pass a parameter to a function and do type checking and casting */
7500 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
7505 func_type
= func
->c
;
7506 if (func_type
== FUNC_OLD
||
7507 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
7508 /* default casting : only need to convert float to double */
7509 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
7513 } else if (arg
== NULL
) {
7514 error("too many arguments to function");
7517 type
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
7518 gen_assign_cast(&type
);
7522 /* parse an expression of the form '(type)' or '(expr)' and return its
7524 static void parse_expr_type(CType
*type
)
7530 if (parse_btype(type
, &ad
)) {
7531 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7538 static void parse_type(CType
*type
)
7543 if (!parse_btype(type
, &ad
)) {
7546 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7549 static void vpush_tokc(int t
)
7553 vsetc(&type
, VT_CONST
, &tokc
);
7556 static void unary(void)
7558 int n
, t
, align
, size
, r
;
7563 /* XXX: GCC 2.95.3 does not generate a table although it should be
7577 vpush_tokc(VT_INT
| VT_UNSIGNED
);
7581 vpush_tokc(VT_LLONG
);
7585 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
7589 vpush_tokc(VT_FLOAT
);
7593 vpush_tokc(VT_DOUBLE
);
7597 vpush_tokc(VT_LDOUBLE
);
7600 case TOK___FUNCTION__
:
7602 goto tok_identifier
;
7608 /* special function name identifier */
7609 len
= strlen(funcname
) + 1;
7610 /* generate char[len] type */
7615 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
7616 ptr
= section_ptr_add(data_section
, len
);
7617 memcpy(ptr
, funcname
, len
);
7622 #ifdef TCC_TARGET_PE
7623 t
= VT_SHORT
| VT_UNSIGNED
;
7629 /* string parsing */
7632 if (tcc_state
->warn_write_strings
)
7637 memset(&ad
, 0, sizeof(AttributeDef
));
7638 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
7643 if (parse_btype(&type
, &ad
)) {
7644 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
7646 /* check ISOC99 compound literal */
7648 /* data is allocated locally by default */
7653 /* all except arrays are lvalues */
7654 if (!(type
.t
& VT_ARRAY
))
7655 r
|= lvalue_type(type
.t
);
7656 memset(&ad
, 0, sizeof(AttributeDef
));
7657 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
7662 } else if (tok
== '{') {
7663 /* save all registers */
7665 /* statement expression : we do not accept break/continue
7666 inside as GCC does */
7667 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
7682 /* functions names must be treated as function pointers,
7683 except for unary '&' and sizeof. Since we consider that
7684 functions are not lvalues, we only have to handle it
7685 there and in function calls. */
7686 /* arrays can also be used although they are not lvalues */
7687 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
7688 !(vtop
->type
.t
& VT_ARRAY
) && !(vtop
->type
.t
& VT_LLOCAL
))
7690 mk_pointer(&vtop
->type
);
7696 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
7698 boolean
.t
= VT_BOOL
;
7700 vtop
->c
.i
= !vtop
->c
.i
;
7701 } else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
7702 vtop
->c
.i
= vtop
->c
.i
^ 1;
7705 vseti(VT_JMP
, gtst(1, 0));
7716 /* in order to force cast, we add zero */
7718 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
7719 error("pointer not accepted for unary plus");
7729 parse_expr_type(&type
);
7733 size
= type_size(&type
, &align
);
7734 if (t
== TOK_SIZEOF
) {
7736 error("sizeof applied to an incomplete type");
7741 vtop
->type
.t
|= VT_UNSIGNED
;
7744 case TOK_builtin_types_compatible_p
:
7753 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7754 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7755 vpushi(is_compatible_types(&type1
, &type2
));
7758 case TOK_builtin_constant_p
:
7760 int saved_nocode_wanted
, res
;
7763 saved_nocode_wanted
= nocode_wanted
;
7766 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
7768 nocode_wanted
= saved_nocode_wanted
;
7773 case TOK_builtin_frame_address
:
7778 if (tok
!= TOK_CINT
) {
7779 error("__builtin_frame_address only takes integers");
7782 error("TCC only supports __builtin_frame_address(0)");
7788 vset(&type
, VT_LOCAL
, 0);
7791 #ifdef TCC_TARGET_X86_64
7792 case TOK_builtin_malloc
:
7794 char *p
= file
->buf_ptr
;
7795 file
->buf_ptr
= "malloc";
7798 goto tok_identifier
;
7800 case TOK_builtin_free
:
7802 char *p
= file
->buf_ptr
;
7803 file
->buf_ptr
= "free";
7806 goto tok_identifier
;
7824 goto tok_identifier
;
7826 /* allow to take the address of a label */
7827 if (tok
< TOK_UIDENT
)
7828 expect("label identifier");
7829 s
= label_find(tok
);
7831 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7833 if (s
->r
== LABEL_DECLARED
)
7834 s
->r
= LABEL_FORWARD
;
7837 s
->type
.t
= VT_VOID
;
7838 mk_pointer(&s
->type
);
7839 s
->type
.t
|= VT_STATIC
;
7841 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
7850 expect("identifier");
7854 error("'%s' undeclared", get_tok_str(t
, NULL
));
7855 /* for simple function calls, we tolerate undeclared
7856 external reference to int() function */
7857 if (tcc_state
->warn_implicit_function_declaration
)
7858 warning("implicit declaration of function '%s'",
7859 get_tok_str(t
, NULL
));
7860 s
= external_global_sym(t
, &func_old_type
, 0);
7862 if ((s
->type
.t
& (VT_STATIC
| VT_INLINE
| VT_BTYPE
)) ==
7863 (VT_STATIC
| VT_INLINE
| VT_FUNC
)) {
7864 /* if referencing an inline function, then we generate a
7865 symbol to it if not already done. It will have the
7866 effect to generate code for it at the end of the
7867 compilation unit. Inline function as always
7868 generated in the text section. */
7870 put_extern_sym(s
, text_section
, 0, 0);
7871 r
= VT_SYM
| VT_CONST
;
7875 vset(&s
->type
, r
, s
->c
);
7876 /* if forward reference, we must point to s */
7877 if (vtop
->r
& VT_SYM
) {
7884 /* post operations */
7886 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
7889 } else if (tok
== '.' || tok
== TOK_ARROW
) {
7891 if (tok
== TOK_ARROW
)
7896 /* expect pointer on structure */
7897 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
7898 expect("struct or union");
7902 while ((s
= s
->next
) != NULL
) {
7907 error("field not found: %s", get_tok_str(tok
& ~SYM_FIELD
, NULL
));
7908 /* add field offset to pointer */
7909 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
7912 /* change type to field type, and set to lvalue */
7913 vtop
->type
= s
->type
;
7914 /* an array is never an lvalue */
7915 if (!(vtop
->type
.t
& VT_ARRAY
)) {
7916 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7917 /* if bound checking, the referenced pointer must be checked */
7918 if (do_bounds_check
)
7919 vtop
->r
|= VT_MUSTBOUND
;
7922 } else if (tok
== '[') {
7928 } else if (tok
== '(') {
7934 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7935 /* pointer test (no array accepted) */
7936 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
7937 vtop
->type
= *pointed_type(&vtop
->type
);
7938 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
7942 expect("function pointer");
7945 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
7947 /* get return type */
7950 sa
= s
->next
; /* first parameter */
7953 /* compute first implicit argument if a structure is returned */
7954 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
7955 /* get some space for the returned structure */
7956 size
= type_size(&s
->type
, &align
);
7957 loc
= (loc
- size
) & -align
;
7959 ret
.r
= VT_LOCAL
| VT_LVAL
;
7960 /* pass it as 'int' to avoid structure arg passing
7962 vseti(VT_LOCAL
, loc
);
7967 /* return in register */
7968 if (is_float(ret
.type
.t
)) {
7969 ret
.r
= reg_fret(ret
.type
.t
);
7971 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
7980 gfunc_param_typed(s
, sa
);
7990 error("too few arguments to function");
7992 if (!nocode_wanted
) {
7993 gfunc_call(nb_args
);
7995 vtop
-= (nb_args
+ 1);
7998 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
8006 static void uneq(void)
8012 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
8013 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
8014 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
8029 static void expr_prod(void)
8034 while (tok
== '*' || tok
== '/' || tok
== '%') {
8042 static void expr_sum(void)
8047 while (tok
== '+' || tok
== '-') {
8055 static void expr_shift(void)
8060 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
8068 static void expr_cmp(void)
8073 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
8074 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
8082 static void expr_cmpeq(void)
8087 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
8095 static void expr_and(void)
8098 while (tok
== '&') {
8105 static void expr_xor(void)
8108 while (tok
== '^') {
8115 static void expr_or(void)
8118 while (tok
== '|') {
8125 /* XXX: fix this mess */
8126 static void expr_land_const(void)
8129 while (tok
== TOK_LAND
) {
8136 /* XXX: fix this mess */
8137 static void expr_lor_const(void)
8140 while (tok
== TOK_LOR
) {
8147 /* only used if non constant */
8148 static void expr_land(void)
8153 if (tok
== TOK_LAND
) {
8158 if (tok
!= TOK_LAND
) {
8168 static void expr_lor(void)
8173 if (tok
== TOK_LOR
) {
8178 if (tok
!= TOK_LOR
) {
8188 /* XXX: better constant handling */
8189 static void expr_eq(void)
8191 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
8193 CType type
, type1
, type2
;
8200 boolean
.t
= VT_BOOL
;
8206 if (tok
!= ':' || !gnu_ext
) {
8221 if (vtop
!= vstack
) {
8222 /* needed to avoid having different registers saved in
8224 if (is_float(vtop
->type
.t
)) {
8226 #ifdef TCC_TARGET_X86_64
8227 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LDOUBLE
) {
8237 if (tok
== ':' && gnu_ext
) {
8245 sv
= *vtop
; /* save value to handle it later */
8246 vtop
--; /* no vpop so that FP stack is not flushed */
8254 bt1
= t1
& VT_BTYPE
;
8256 bt2
= t2
& VT_BTYPE
;
8257 /* cast operands to correct type according to ISOC rules */
8258 if (is_float(bt1
) || is_float(bt2
)) {
8259 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
8260 type
.t
= VT_LDOUBLE
;
8261 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
8266 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
8267 /* cast to biggest op */
8269 /* convert to unsigned if it does not fit in a long long */
8270 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
8271 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
8272 type
.t
|= VT_UNSIGNED
;
8273 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
8274 /* XXX: test pointer compatibility */
8276 } else if (bt1
== VT_FUNC
|| bt2
== VT_FUNC
) {
8277 /* XXX: test function pointer compatibility */
8279 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
8280 /* XXX: test structure compatibility */
8282 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
8283 /* NOTE: as an extension, we accept void on only one side */
8286 /* integer operations */
8288 /* convert to unsigned if it does not fit in an integer */
8289 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
8290 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
8291 type
.t
|= VT_UNSIGNED
;
8294 /* now we convert second operand */
8296 if (VT_STRUCT
== (vtop
->type
.t
& VT_BTYPE
))
8299 if (is_float(type
.t
)) {
8301 #ifdef TCC_TARGET_X86_64
8302 if ((type
.t
& VT_BTYPE
) == VT_LDOUBLE
) {
8306 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
8307 /* for long longs, we use fixed registers to avoid having
8308 to handle a complicated move */
8313 /* this is horrible, but we must also convert first
8317 /* put again first value and cast it */
8320 if (VT_STRUCT
== (vtop
->type
.t
& VT_BTYPE
))
8330 static void gexpr(void)
8341 /* parse an expression and return its type without any side effect. */
8342 static void expr_type(CType
*type
)
8344 int saved_nocode_wanted
;
8346 saved_nocode_wanted
= nocode_wanted
;
8351 nocode_wanted
= saved_nocode_wanted
;
8354 /* parse a unary expression and return its type without any side
8356 static void unary_type(CType
*type
)
8368 /* parse a constant expression and return value in vtop. */
8369 static void expr_const1(void)
8378 /* parse an integer constant and return its value. */
8379 static int expr_const(void)
8383 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
8384 expect("constant expression");
8390 /* return the label token if current token is a label, otherwise
8392 static int is_label(void)
8396 /* fast test first */
8397 if (tok
< TOK_UIDENT
)
8399 /* no need to save tokc because tok is an identifier */
8406 unget_tok(last_tok
);
8411 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
8412 int case_reg
, int is_expr
)
8417 /* generate line number info */
8419 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
8420 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
8422 last_line_num
= file
->line_num
;
8426 /* default return value is (void) */
8428 vtop
->type
.t
= VT_VOID
;
8431 if (tok
== TOK_IF
) {
8438 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
8440 if (c
== TOK_ELSE
) {
8444 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
8445 gsym(d
); /* patch else jmp */
8448 } else if (tok
== TOK_WHILE
) {
8456 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8460 } else if (tok
== '{') {
8464 /* record local declaration stack position */
8466 llabel
= local_label_stack
;
8467 /* handle local labels declarations */
8468 if (tok
== TOK_LABEL
) {
8471 if (tok
< TOK_UIDENT
)
8472 expect("label identifier");
8473 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
8483 while (tok
!= '}') {
8488 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8491 /* pop locally defined labels */
8492 label_pop(&local_label_stack
, llabel
);
8493 /* pop locally defined symbols */
8495 /* XXX: this solution makes only valgrind happy...
8496 triggered by gcc.c-torture/execute/20000917-1.c */
8498 switch(vtop
->type
.t
& VT_BTYPE
) {
8503 for(p
=vtop
->type
.ref
;p
;p
=p
->prev
)
8505 error("unsupported expression type");
8508 sym_pop(&local_stack
, s
);
8510 } else if (tok
== TOK_RETURN
) {
8514 gen_assign_cast(&func_vt
);
8515 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
8517 /* if returning structure, must copy it to implicit
8518 first pointer arg location */
8521 size
= type_size(&func_vt
,&align
);
8524 if((vtop
->r
!= (VT_LOCAL
| VT_LVAL
) || (vtop
->c
.i
& 3))
8528 loc
= (loc
- size
) & -4;
8531 vset(&type
, VT_LOCAL
| VT_LVAL
, addr
);
8534 vset(&int_type
, VT_LOCAL
| VT_LVAL
, addr
);
8536 vtop
->type
= int_type
;
8542 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
8545 /* copy structure value to pointer */
8550 } else if (is_float(func_vt
.t
)) {
8551 gv(rc_fret(func_vt
.t
));
8555 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
8558 rsym
= gjmp(rsym
); /* jmp */
8559 } else if (tok
== TOK_BREAK
) {
8562 error("cannot break");
8563 *bsym
= gjmp(*bsym
);
8566 } else if (tok
== TOK_CONTINUE
) {
8569 error("cannot continue");
8570 *csym
= gjmp(*csym
);
8573 } else if (tok
== TOK_FOR
) {
8600 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8605 if (tok
== TOK_DO
) {
8610 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8621 if (tok
== TOK_SWITCH
) {
8625 /* XXX: other types than integer */
8626 case_reg
= gv(RC_INT
);
8630 b
= gjmp(0); /* jump to first case */
8632 block(&a
, csym
, &b
, &c
, case_reg
, 0);
8633 /* if no default, jmp after switch */
8641 if (tok
== TOK_CASE
) {
8648 if (gnu_ext
&& tok
== TOK_DOTS
) {
8652 warning("empty case range");
8654 /* since a case is like a label, we must skip it with a jmp */
8661 *case_sym
= gtst(1, 0);
8664 *case_sym
= gtst(1, 0);
8668 *case_sym
= gtst(1, *case_sym
);
8673 goto block_after_label
;
8675 if (tok
== TOK_DEFAULT
) {
8681 error("too many 'default'");
8684 goto block_after_label
;
8686 if (tok
== TOK_GOTO
) {
8688 if (tok
== '*' && gnu_ext
) {
8692 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
8695 } else if (tok
>= TOK_UIDENT
) {
8696 s
= label_find(tok
);
8697 /* put forward definition if needed */
8699 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
8701 if (s
->r
== LABEL_DECLARED
)
8702 s
->r
= LABEL_FORWARD
;
8704 /* label already defined */
8705 if (s
->r
& LABEL_FORWARD
)
8706 s
->next
= (void *)gjmp((long)s
->next
);
8708 gjmp_addr((long)s
->next
);
8711 expect("label identifier");
8714 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
8722 if (s
->r
== LABEL_DEFINED
)
8723 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
8724 gsym((long)s
->next
);
8725 s
->r
= LABEL_DEFINED
;
8727 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
8729 s
->next
= (void *)ind
;
8730 /* we accept this, but it is a mistake */
8733 warning("deprecated use of label at end of compound statement");
8737 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8740 /* expression case */
8755 /* t is the array or struct type. c is the array or struct
8756 address. cur_index/cur_field is the pointer to the current
8757 value. 'size_only' is true if only size info is needed (only used
8759 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
8760 int *cur_index
, Sym
**cur_field
,
8764 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
8770 if (gnu_ext
&& (l
= is_label()) != 0)
8772 while (tok
== '[' || tok
== '.') {
8774 if (!(type
->t
& VT_ARRAY
))
8775 expect("array type");
8778 index
= expr_const();
8779 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
8780 expect("invalid index");
8781 if (tok
== TOK_DOTS
&& gnu_ext
) {
8783 index_last
= expr_const();
8784 if (index_last
< 0 ||
8785 (s
->c
>= 0 && index_last
>= s
->c
) ||
8787 expect("invalid index");
8793 *cur_index
= index_last
;
8794 type
= pointed_type(type
);
8795 elem_size
= type_size(type
, &align
);
8796 c
+= index
* elem_size
;
8797 /* NOTE: we only support ranges for last designator */
8798 nb_elems
= index_last
- index
+ 1;
8799 if (nb_elems
!= 1) {
8808 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
8809 expect("struct/union type");
8822 /* XXX: fix this mess by using explicit storage field */
8824 type1
.t
|= (type
->t
& ~VT_TYPE
);
8838 if (type
->t
& VT_ARRAY
) {
8840 type
= pointed_type(type
);
8841 c
+= index
* type_size(type
, &align
);
8845 error("too many field init");
8846 /* XXX: fix this mess by using explicit storage field */
8848 type1
.t
|= (type
->t
& ~VT_TYPE
);
8853 decl_initializer(type
, sec
, c
, 0, size_only
);
8855 /* XXX: make it more general */
8856 if (!size_only
&& nb_elems
> 1) {
8857 unsigned long c_end
;
8862 error("range init not supported yet for dynamic storage");
8863 c_end
= c
+ nb_elems
* elem_size
;
8864 if (c_end
> sec
->data_allocated
)
8865 section_realloc(sec
, c_end
);
8866 src
= sec
->data
+ c
;
8868 for(i
= 1; i
< nb_elems
; i
++) {
8870 memcpy(dst
, src
, elem_size
);
8876 #define EXPR_CONST 1
8879 /* store a value or an expression directly in global data or in local array */
8880 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
8881 int v
, int expr_type
)
8883 int saved_global_expr
, bt
, bit_pos
, bit_size
;
8885 unsigned long long bit_mask
;
8893 /* compound literals must be allocated globally in this case */
8894 saved_global_expr
= global_expr
;
8897 global_expr
= saved_global_expr
;
8898 /* NOTE: symbols are accepted */
8899 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
8900 error("initializer element is not constant");
8908 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
8911 /* XXX: not portable */
8912 /* XXX: generate error if incorrect relocation */
8913 gen_assign_cast(&dtype
);
8914 bt
= type
->t
& VT_BTYPE
;
8915 /* we'll write at most 12 bytes */
8916 if (c
+ 12 > sec
->data_allocated
) {
8917 section_realloc(sec
, c
+ 12);
8919 ptr
= sec
->data
+ c
;
8920 /* XXX: make code faster ? */
8921 if (!(type
->t
& VT_BITFIELD
)) {
8926 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
8927 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
8928 bit_mask
= (1LL << bit_size
) - 1;
8930 if ((vtop
->r
& VT_SYM
) &&
8936 (bt
== VT_INT
&& bit_size
!= 32)))
8937 error("initializer element is not computable at load time");
8940 vtop
->c
.i
= (vtop
->c
.i
!= 0);
8942 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8945 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8948 *(double *)ptr
= vtop
->c
.d
;
8951 *(long double *)ptr
= vtop
->c
.ld
;
8954 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
8957 if (vtop
->r
& VT_SYM
) {
8958 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
8960 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8965 vset(&dtype
, VT_LOCAL
|VT_LVAL
, c
);
8972 /* put zeros for variable based init */
8973 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
8976 /* nothing to do because globals are already set to zero */
8978 vpush_global_sym(&func_old_type
, TOK_memset
);
8986 /* 't' contains the type and storage info. 'c' is the offset of the
8987 object in section 'sec'. If 'sec' is NULL, it means stack based
8988 allocation. 'first' is true if array '{' must be read (multi
8989 dimension implicit array init handling). 'size_only' is true if
8990 size only evaluation is wanted (only for arrays). */
8991 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
8992 int first
, int size_only
)
8994 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
8995 int size1
, align1
, expr_type
;
8999 if (type
->t
& VT_ARRAY
) {
9003 t1
= pointed_type(type
);
9004 size1
= type_size(t1
, &align1
);
9007 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
9013 /* only parse strings here if correct type (otherwise: handle
9014 them as ((w)char *) expressions */
9015 if ((tok
== TOK_LSTR
&&
9016 #ifdef TCC_TARGET_PE
9017 (t1
->t
& VT_BTYPE
) == VT_SHORT
&& (t1
->t
& VT_UNSIGNED
)
9019 (t1
->t
& VT_BTYPE
) == VT_INT
9021 ) || (tok
== TOK_STR
&& (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
9022 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
9027 /* compute maximum number of chars wanted */
9029 cstr_len
= cstr
->size
;
9031 cstr_len
= cstr
->size
/ sizeof(nwchar_t
);
9034 if (n
>= 0 && nb
> (n
- array_length
))
9035 nb
= n
- array_length
;
9038 warning("initializer-string for array is too long");
9039 /* in order to go faster for common case (char
9040 string in global variable, we handle it
9042 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
9043 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
9047 ch
= ((unsigned char *)cstr
->data
)[i
];
9049 ch
= ((nwchar_t
*)cstr
->data
)[i
];
9050 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
9058 /* only add trailing zero if enough storage (no
9059 warning in this case since it is standard) */
9060 if (n
< 0 || array_length
< n
) {
9062 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
9068 while (tok
!= '}') {
9069 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
9070 if (n
>= 0 && index
>= n
)
9071 error("index too large");
9072 /* must put zero in holes (note that doing it that way
9073 ensures that it even works with designators) */
9074 if (!size_only
&& array_length
< index
) {
9075 init_putz(t1
, sec
, c
+ array_length
* size1
,
9076 (index
- array_length
) * size1
);
9079 if (index
> array_length
)
9080 array_length
= index
;
9081 /* special test for multi dimensional arrays (may not
9082 be strictly correct if designators are used at the
9084 if (index
>= n
&& no_oblock
)
9093 /* put zeros at the end */
9094 if (!size_only
&& n
>= 0 && array_length
< n
) {
9095 init_putz(t1
, sec
, c
+ array_length
* size1
,
9096 (n
- array_length
) * size1
);
9098 /* patch type size if needed */
9100 s
->c
= array_length
;
9101 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
9102 (sec
|| !first
|| tok
== '{')) {
9105 /* NOTE: the previous test is a specific case for automatic
9106 struct/union init */
9107 /* XXX: union needs only one init */
9109 /* XXX: this test is incorrect for local initializers
9110 beginning with ( without {. It would be much more difficult
9111 to do it correctly (ideally, the expression parser should
9112 be used in all cases) */
9118 while (tok
== '(') {
9122 if (!parse_btype(&type1
, &ad1
))
9124 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
9126 if (!is_assignable_types(type
, &type1
))
9127 error("invalid type for cast");
9132 if (first
|| tok
== '{') {
9141 while (tok
!= '}') {
9142 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
9144 if (!size_only
&& array_length
< index
) {
9145 init_putz(type
, sec
, c
+ array_length
,
9146 index
- array_length
);
9148 index
= index
+ type_size(&f
->type
, &align1
);
9149 if (index
> array_length
)
9150 array_length
= index
;
9152 if (no_oblock
&& f
== NULL
)
9158 /* put zeros at the end */
9159 if (!size_only
&& array_length
< n
) {
9160 init_putz(type
, sec
, c
+ array_length
,
9169 } else if (tok
== '{') {
9171 decl_initializer(type
, sec
, c
, first
, size_only
);
9173 } else if (size_only
) {
9174 /* just skip expression */
9176 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
9180 else if (tok
== ')')
9185 /* currently, we always use constant expression for globals
9186 (may change for scripting case) */
9187 expr_type
= EXPR_CONST
;
9189 expr_type
= EXPR_ANY
;
9190 init_putv(type
, sec
, c
, 0, expr_type
);
9194 /* parse an initializer for type 't' if 'has_init' is non zero, and
9195 allocate space in local or global data space ('r' is either
9196 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
9197 variable 'v' of scope 'scope' is declared before initializers are
9198 parsed. If 'v' is zero, then a reference to the new object is put
9199 in the value stack. If 'has_init' is 2, a special parsing is done
9200 to handle string constants. */
9201 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
9202 int has_init
, int v
, int scope
)
9204 int size
, align
, addr
, data_offset
;
9206 ParseState saved_parse_state
;
9207 TokenString init_str
;
9210 size
= type_size(type
, &align
);
9211 /* If unknown size, we must evaluate it before
9212 evaluating initializers because
9213 initializers can generate global data too
9214 (e.g. string pointers or ISOC99 compound
9215 literals). It also simplifies local
9216 initializers handling */
9217 tok_str_new(&init_str
);
9220 error("unknown type size");
9221 /* get all init string */
9222 if (has_init
== 2) {
9223 /* only get strings */
9224 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
9225 tok_str_add_tok(&init_str
);
9230 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
9232 error("unexpected end of file in initializer");
9233 tok_str_add_tok(&init_str
);
9236 else if (tok
== '}') {
9246 tok_str_add(&init_str
, -1);
9247 tok_str_add(&init_str
, 0);
9250 save_parse_state(&saved_parse_state
);
9252 macro_ptr
= init_str
.str
;
9254 decl_initializer(type
, NULL
, 0, 1, 1);
9255 /* prepare second initializer parsing */
9256 macro_ptr
= init_str
.str
;
9259 /* if still unknown size, error */
9260 size
= type_size(type
, &align
);
9262 error("unknown type size");
9264 /* take into account specified alignment if bigger */
9266 if (ad
->aligned
> align
)
9267 align
= ad
->aligned
;
9268 } else if (ad
->packed
) {
9271 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
9273 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
9275 loc
= (loc
- size
) & -align
;
9277 /* handles bounds */
9278 /* XXX: currently, since we do only one pass, we cannot track
9279 '&' operators, so we add only arrays */
9280 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
9281 unsigned long *bounds_ptr
;
9282 /* add padding between regions */
9284 /* then add local bound info */
9285 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
9286 bounds_ptr
[0] = addr
;
9287 bounds_ptr
[1] = size
;
9290 /* local variable */
9291 sym_push(v
, type
, r
, addr
);
9293 /* push local reference */
9294 vset(type
, r
, addr
);
9300 if (v
&& scope
== VT_CONST
) {
9301 /* see if the symbol was already defined */
9304 if (!is_compatible_types(&sym
->type
, type
))
9305 error("incompatible types for redefinition of '%s'",
9306 get_tok_str(v
, NULL
));
9307 if (sym
->type
.t
& VT_EXTERN
) {
9308 /* if the variable is extern, it was not allocated */
9309 sym
->type
.t
&= ~VT_EXTERN
;
9310 /* set array size if it was ommited in extern
9312 if ((sym
->type
.t
& VT_ARRAY
) &&
9313 sym
->type
.ref
->c
< 0 &&
9315 sym
->type
.ref
->c
= type
->ref
->c
;
9317 /* we accept several definitions of the same
9318 global variable. this is tricky, because we
9319 must play with the SHN_COMMON type of the symbol */
9320 /* XXX: should check if the variable was already
9321 initialized. It is incorrect to initialized it
9323 /* no init data, we won't add more to the symbol */
9330 /* allocate symbol in corresponding section */
9335 else if (tcc_state
->nocommon
)
9339 data_offset
= sec
->data_offset
;
9340 data_offset
= (data_offset
+ align
- 1) & -align
;
9342 /* very important to increment global pointer at this time
9343 because initializers themselves can create new initializers */
9344 data_offset
+= size
;
9345 /* add padding if bound check */
9346 if (do_bounds_check
)
9348 sec
->data_offset
= data_offset
;
9349 /* allocate section space to put the data */
9350 if (sec
->sh_type
!= SHT_NOBITS
&&
9351 data_offset
> sec
->data_allocated
)
9352 section_realloc(sec
, data_offset
);
9353 /* align section if needed */
9354 if (align
> sec
->sh_addralign
)
9355 sec
->sh_addralign
= align
;
9357 addr
= 0; /* avoid warning */
9361 if (scope
!= VT_CONST
|| !sym
) {
9362 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
9364 /* update symbol definition */
9366 put_extern_sym(sym
, sec
, addr
, size
);
9369 /* put a common area */
9370 put_extern_sym(sym
, NULL
, align
, size
);
9371 /* XXX: find a nicer way */
9372 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
9373 esym
->st_shndx
= SHN_COMMON
;
9378 /* push global reference */
9379 sym
= get_sym_ref(type
, sec
, addr
, size
);
9381 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
9385 /* handles bounds now because the symbol must be defined
9386 before for the relocation */
9387 if (do_bounds_check
) {
9388 unsigned long *bounds_ptr
;
9390 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
9391 /* then add global bound info */
9392 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
9393 bounds_ptr
[0] = 0; /* relocated */
9394 bounds_ptr
[1] = size
;
9398 decl_initializer(type
, sec
, addr
, 1, 0);
9399 /* restore parse state if needed */
9401 tok_str_free(init_str
.str
);
9402 restore_parse_state(&saved_parse_state
);
9408 void put_func_debug(Sym
*sym
)
9413 /* XXX: we put here a dummy type */
9414 snprintf(buf
, sizeof(buf
), "%s:%c1",
9415 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
9416 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
9417 cur_text_section
, sym
->c
);
9418 /* //gr gdb wants a line at the function */
9419 put_stabn(N_SLINE
, 0, file
->line_num
, 0);
9424 /* parse an old style function declaration list */
9425 /* XXX: check multiple parameter */
9426 static void func_decl_list(Sym
*func_sym
)
9433 /* parse each declaration */
9434 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
9435 if (!parse_btype(&btype
, &ad
))
9436 expect("declaration list");
9437 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
9438 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
9440 /* we accept no variable after */
9444 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
9445 /* find parameter in function parameter list */
9448 if ((s
->v
& ~SYM_FIELD
) == v
)
9452 error("declaration for parameter '%s' but no such parameter",
9453 get_tok_str(v
, NULL
));
9455 /* check that no storage specifier except 'register' was given */
9456 if (type
.t
& VT_STORAGE
)
9457 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
9458 convert_parameter_type(&type
);
9459 /* we can add the type (NOTE: it could be local to the function) */
9461 /* accept other parameters */
9472 /* parse a function defined by symbol 'sym' and generate its code in
9473 'cur_text_section' */
9474 static void gen_function(Sym
*sym
)
9476 int saved_nocode_wanted
= nocode_wanted
;
9478 ind
= cur_text_section
->data_offset
;
9479 /* NOTE: we patch the symbol size later */
9480 put_extern_sym(sym
, cur_text_section
, ind
, 0);
9481 funcname
= get_tok_str(sym
->v
, NULL
);
9483 /* put debug symbol */
9485 put_func_debug(sym
);
9486 /* push a dummy symbol to enable local sym storage */
9487 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
9488 gfunc_prolog(&sym
->type
);
9490 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
9493 cur_text_section
->data_offset
= ind
;
9494 label_pop(&global_label_stack
, NULL
);
9495 sym_pop(&local_stack
, NULL
); /* reset local stack */
9496 /* end of function */
9497 /* patch symbol size */
9498 ((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
].st_size
=
9501 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
9503 /* It's better to crash than to generate wrong code */
9504 cur_text_section
= NULL
;
9505 funcname
= ""; /* for safety */
9506 func_vt
.t
= VT_VOID
; /* for safety */
9507 ind
= 0; /* for safety */
9508 nocode_wanted
= saved_nocode_wanted
;
9511 static void gen_inline_functions(void)
9515 int *str
, inline_generated
;
9517 /* iterate while inline function are referenced */
9519 inline_generated
= 0;
9520 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
9522 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
9523 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
9524 (VT_STATIC
| VT_INLINE
) &&
9526 /* the function was used: generate its code and
9527 convert it to a normal function */
9528 str
= INLINE_DEF(sym
->r
);
9529 sym
->r
= VT_SYM
| VT_CONST
;
9530 sym
->type
.t
&= ~VT_INLINE
;
9534 cur_text_section
= text_section
;
9536 macro_ptr
= NULL
; /* fail safe */
9539 inline_generated
= 1;
9542 if (!inline_generated
)
9546 /* free all remaining inline function tokens */
9547 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
9549 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
9550 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
9551 (VT_STATIC
| VT_INLINE
)) {
9552 //gr printf("sym %d %s\n", sym->r, get_tok_str(sym->v, NULL));
9553 if (sym
->r
== (VT_SYM
| VT_CONST
)) //gr beware!
9555 str
= INLINE_DEF(sym
->r
);
9557 sym
->r
= 0; /* fail safe */
9562 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
9563 static void decl(int l
)
9571 if (!parse_btype(&btype
, &ad
)) {
9572 /* skip redundant ';' */
9573 /* XXX: find more elegant solution */
9578 if (l
== VT_CONST
&&
9579 (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
)) {
9580 /* global asm block */
9584 /* special test for old K&R protos without explicit int
9585 type. Only accepted when defining global data */
9586 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
9590 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
9591 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
9593 /* we accept no variable after */
9597 while (1) { /* iterate thru each declaration */
9599 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
9603 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
9604 printf("type = '%s'\n", buf
);
9607 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9608 /* if old style function prototype, we accept a
9611 if (sym
->c
== FUNC_OLD
)
9612 func_decl_list(sym
);
9617 error("cannot use local functions");
9618 if ((type
.t
& VT_BTYPE
) != VT_FUNC
)
9619 expect("function definition");
9621 /* reject abstract declarators in function definition */
9623 while ((sym
= sym
->next
) != NULL
)
9624 if (!(sym
->v
& ~SYM_FIELD
))
9625 expect("identifier");
9627 /* XXX: cannot do better now: convert extern line to static inline */
9628 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
9629 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
9633 if ((sym
->type
.t
& VT_BTYPE
) != VT_FUNC
)
9635 /* specific case: if not func_call defined, we put
9636 the one of the prototype */
9637 /* XXX: should have default value */
9638 r
= sym
->type
.ref
->r
;
9639 if (FUNC_CALL(r
) != FUNC_CDECL
9640 && FUNC_CALL(type
.ref
->r
) == FUNC_CDECL
)
9641 FUNC_CALL(type
.ref
->r
) = FUNC_CALL(r
);
9643 FUNC_EXPORT(type
.ref
->r
) = 1;
9645 if (!is_compatible_types(&sym
->type
, &type
)) {
9647 error("incompatible types for redefinition of '%s'",
9648 get_tok_str(v
, NULL
));
9650 /* if symbol is already defined, then put complete type */
9653 /* put function symbol */
9654 sym
= global_identifier_push(v
, type
.t
, 0);
9655 sym
->type
.ref
= type
.ref
;
9658 /* static inline functions are just recorded as a kind
9659 of macro. Their code will be emitted at the end of
9660 the compilation unit only if they are used */
9661 if ((type
.t
& (VT_INLINE
| VT_STATIC
)) ==
9662 (VT_INLINE
| VT_STATIC
)) {
9663 TokenString func_str
;
9666 tok_str_new(&func_str
);
9672 error("unexpected end of file");
9673 tok_str_add_tok(&func_str
);
9678 } else if (t
== '}') {
9680 if (block_level
== 0)
9684 tok_str_add(&func_str
, -1);
9685 tok_str_add(&func_str
, 0);
9686 INLINE_DEF(sym
->r
) = func_str
.str
;
9688 /* compute text section */
9689 cur_text_section
= ad
.section
;
9690 if (!cur_text_section
)
9691 cur_text_section
= text_section
;
9692 sym
->r
= VT_SYM
| VT_CONST
;
9697 if (btype
.t
& VT_TYPEDEF
) {
9698 /* save typedefed type */
9699 /* XXX: test storage specifiers ? */
9700 sym
= sym_push(v
, &type
, 0, 0);
9701 sym
->type
.t
|= VT_TYPEDEF
;
9702 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9703 /* external function definition */
9704 /* specific case for func_call attribute */
9706 type
.ref
->r
= ad
.func_attr
;
9707 external_sym(v
, &type
, 0);
9709 /* not lvalue if array */
9711 if (!(type
.t
& VT_ARRAY
))
9712 r
|= lvalue_type(type
.t
);
9713 has_init
= (tok
== '=');
9714 if ((btype
.t
& VT_EXTERN
) ||
9715 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
9716 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
9717 /* external variable */
9718 /* NOTE: as GCC, uninitialized global static
9719 arrays of null size are considered as
9721 external_sym(v
, &type
, r
);
9723 type
.t
|= (btype
.t
& VT_STATIC
); /* Retain "static". */
9724 if (type
.t
& VT_STATIC
)
9730 decl_initializer_alloc(&type
, &ad
, r
,
9744 /* better than nothing, but needs extension to handle '-E' option
9746 static void preprocess_init(TCCState
*s1
)
9748 s1
->include_stack_ptr
= s1
->include_stack
;
9749 /* XXX: move that before to avoid having to initialize
9750 file->ifdef_stack_ptr ? */
9751 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
9752 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
9754 /* XXX: not ANSI compliant: bound checking says error */
9756 s1
->pack_stack
[0] = 0;
9757 s1
->pack_stack_ptr
= s1
->pack_stack
;
9760 /* compile the C file opened in 'file'. Return non zero if errors. */
9761 static int tcc_compile(TCCState
*s1
)
9765 volatile int section_sym
;
9768 printf("%s: **** new file\n", file
->filename
);
9770 preprocess_init(s1
);
9772 cur_text_section
= NULL
;
9774 anon_sym
= SYM_FIRST_ANOM
;
9776 /* file info: full path + filename */
9777 section_sym
= 0; /* avoid warning */
9779 section_sym
= put_elf_sym(symtab_section
, 0, 0,
9780 ELFW(ST_INFO
)(STB_LOCAL
, STT_SECTION
), 0,
9781 text_section
->sh_num
, NULL
);
9782 getcwd(buf
, sizeof(buf
));
9784 normalize_slashes(buf
);
9786 pstrcat(buf
, sizeof(buf
), "/");
9787 put_stabs_r(buf
, N_SO
, 0, 0,
9788 text_section
->data_offset
, text_section
, section_sym
);
9789 put_stabs_r(file
->filename
, N_SO
, 0, 0,
9790 text_section
->data_offset
, text_section
, section_sym
);
9792 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
9793 symbols can be safely used */
9794 put_elf_sym(symtab_section
, 0, 0,
9795 ELFW(ST_INFO
)(STB_LOCAL
, STT_FILE
), 0,
9796 SHN_ABS
, file
->filename
);
9798 /* define some often used types */
9799 int_type
.t
= VT_INT
;
9801 char_pointer_type
.t
= VT_BYTE
;
9802 mk_pointer(&char_pointer_type
);
9804 func_old_type
.t
= VT_FUNC
;
9805 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
9807 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
9808 float_type
.t
= VT_FLOAT
;
9809 double_type
.t
= VT_DOUBLE
;
9811 func_float_type
.t
= VT_FUNC
;
9812 func_float_type
.ref
= sym_push(SYM_FIELD
, &float_type
, FUNC_CDECL
, FUNC_OLD
);
9813 func_double_type
.t
= VT_FUNC
;
9814 func_double_type
.ref
= sym_push(SYM_FIELD
, &double_type
, FUNC_CDECL
, FUNC_OLD
);
9818 /* define 'void *alloca(unsigned int)' builtin function */
9823 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
9824 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
9827 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
9831 define_start
= define_stack
;
9834 if (setjmp(s1
->error_jmp_buf
) == 0) {
9836 s1
->error_set_jmp_enabled
= 1;
9838 ch
= file
->buf_ptr
[0];
9839 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9840 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
9844 expect("declaration");
9846 /* end of translation unit info */
9848 put_stabs_r(NULL
, N_SO
, 0, 0,
9849 text_section
->data_offset
, text_section
, section_sym
);
9852 s1
->error_set_jmp_enabled
= 0;
9854 /* reset define stack, but leave -Dsymbols (may be incorrect if
9855 they are undefined) */
9856 free_defines(define_start
);
9858 gen_inline_functions();
9860 sym_pop(&global_stack
, NULL
);
9861 sym_pop(&local_stack
, NULL
);
9863 return s1
->nb_errors
!= 0 ? -1 : 0;
9866 /* Preprocess the current file */
9867 /* XXX: add line and file infos,
9868 * XXX: add options to preserve spaces (partly done, only spaces in macro are
9871 static int tcc_preprocess(TCCState
*s1
)
9874 BufferedFile
*file_ref
;
9875 int token_seen
, line_ref
;
9877 preprocess_init(s1
);
9878 define_start
= define_stack
;
9879 ch
= file
->buf_ptr
[0];
9881 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9882 parse_flags
= PARSE_FLAG_ASM_COMMENTS
| PARSE_FLAG_PREPROCESS
|
9883 PARSE_FLAG_LINEFEED
;
9891 if (tok
== TOK_EOF
) {
9893 } else if (tok
== TOK_LINEFEED
) {
9898 } else if (token_seen
) {
9899 fwrite(tok_spaces
.data
, tok_spaces
.size
, 1, s1
->outfile
);
9901 int d
= file
->line_num
- line_ref
;
9902 if (file
!= file_ref
|| d
< 0 || d
>= 8)
9903 fprintf(s1
->outfile
, "# %d \"%s\"\n", file
->line_num
, file
->filename
);
9906 fputs("\n", s1
->outfile
), --d
;
9907 line_ref
= (file_ref
= file
)->line_num
;
9910 fputs(get_tok_str(tok
, &tokc
), s1
->outfile
);
9912 free_defines(define_start
);
9917 int tcc_compile_string(TCCState
*s
, const char *str
)
9919 BufferedFile bf1
, *bf
= &bf1
;
9923 /* init file structure */
9925 /* XXX: avoid copying */
9927 buf
= tcc_malloc(len
+ 1);
9930 memcpy(buf
, str
, len
);
9933 bf
->buf_end
= buf
+ len
;
9934 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
9937 ret
= tcc_compile(s
);
9941 /* currently, no need to close */
9946 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9947 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
9949 BufferedFile bf1
, *bf
= &bf1
;
9951 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
9952 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
9956 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
9958 /* init file structure */
9960 bf
->buf_ptr
= bf
->buffer
;
9961 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
9962 *bf
->buf_end
= CH_EOB
;
9963 bf
->filename
[0] = '\0';
9967 s1
->include_stack_ptr
= s1
->include_stack
;
9969 /* parse with define parser */
9970 ch
= file
->buf_ptr
[0];
9976 /* undefine a preprocessor symbol */
9977 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
9981 ts
= tok_alloc(sym
, strlen(sym
));
9982 s
= define_find(ts
->tok
);
9983 /* undefine symbol by putting an invalid name */
9988 #ifdef CONFIG_TCC_ASM
9990 #ifdef TCC_TARGET_I386
9991 #include "i386-asm.c"
9996 static void asm_instr(void)
9998 error("inline asm() not supported");
10000 static void asm_global_instr(void)
10002 error("inline asm() not supported");
10006 #include "tccelf.c"
10008 #ifdef TCC_TARGET_COFF
10009 #include "tcccoff.c"
10012 #ifdef TCC_TARGET_PE
10016 /* print the position in the source file of PC value 'pc' by reading
10017 the stabs debug information */
10018 static void rt_printline(unsigned long wanted_pc
)
10020 Stab_Sym
*sym
, *sym_end
;
10021 char func_name
[128], last_func_name
[128];
10022 unsigned long func_addr
, last_pc
, pc
;
10023 const char *incl_files
[INCLUDE_STACK_SIZE
];
10024 int incl_index
, len
, last_line_num
, i
;
10025 const char *str
, *p
;
10027 fprintf(stderr
, "0x%08lx:", wanted_pc
);
10029 func_name
[0] = '\0';
10032 last_func_name
[0] = '\0';
10033 last_pc
= 0xffffffff;
10035 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
10036 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
10037 while (sym
< sym_end
) {
10038 switch(sym
->n_type
) {
10039 /* function start or end */
10041 if (sym
->n_strx
== 0) {
10042 /* we test if between last line and end of function */
10043 pc
= sym
->n_value
+ func_addr
;
10044 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
10046 func_name
[0] = '\0';
10049 str
= stabstr_section
->data
+ sym
->n_strx
;
10050 p
= strchr(str
, ':');
10052 pstrcpy(func_name
, sizeof(func_name
), str
);
10055 if (len
> sizeof(func_name
) - 1)
10056 len
= sizeof(func_name
) - 1;
10057 memcpy(func_name
, str
, len
);
10058 func_name
[len
] = '\0';
10060 func_addr
= sym
->n_value
;
10063 /* line number info */
10065 pc
= sym
->n_value
+ func_addr
;
10066 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
10069 last_line_num
= sym
->n_desc
;
10071 strcpy(last_func_name
, func_name
);
10073 /* include files */
10075 str
= stabstr_section
->data
+ sym
->n_strx
;
10077 if (incl_index
< INCLUDE_STACK_SIZE
) {
10078 incl_files
[incl_index
++] = str
;
10082 if (incl_index
> 1)
10086 if (sym
->n_strx
== 0) {
10087 incl_index
= 0; /* end of translation unit */
10089 str
= stabstr_section
->data
+ sym
->n_strx
;
10090 /* do not add path */
10092 if (len
> 0 && str
[len
- 1] != '/')
10100 /* second pass: we try symtab symbols (no line number info) */
10103 ElfW(Sym
) *sym
, *sym_end
;
10106 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
10107 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
10110 type
= ELFW(ST_TYPE
)(sym
->st_info
);
10111 if (type
== STT_FUNC
) {
10112 if (wanted_pc
>= sym
->st_value
&&
10113 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
10114 pstrcpy(last_func_name
, sizeof(last_func_name
),
10115 strtab_section
->data
+ sym
->st_name
);
10121 /* did not find any info: */
10122 fprintf(stderr
, " ???\n");
10125 if (last_func_name
[0] != '\0') {
10126 fprintf(stderr
, " %s()", last_func_name
);
10128 if (incl_index
> 0) {
10129 fprintf(stderr
, " (%s:%d",
10130 incl_files
[incl_index
- 1], last_line_num
);
10131 for(i
= incl_index
- 2; i
>= 0; i
--)
10132 fprintf(stderr
, ", included from %s", incl_files
[i
]);
10133 fprintf(stderr
, ")");
10135 fprintf(stderr
, "\n");
10138 #if !defined(_WIN32) && !defined(CONFIG_TCCBOOT)
10142 /* fix for glibc 2.1 */
10144 #define REG_EIP EIP
10145 #define REG_EBP EBP
10148 /* return the PC at frame level 'level'. Return non zero if not found */
10149 static int rt_get_caller_pc(unsigned long *paddr
,
10150 ucontext_t
*uc
, int level
)
10156 #if defined(__FreeBSD__)
10157 *paddr
= uc
->uc_mcontext
.mc_eip
;
10158 #elif defined(__dietlibc__)
10159 *paddr
= uc
->uc_mcontext
.eip
;
10161 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
10165 #if defined(__FreeBSD__)
10166 fp
= uc
->uc_mcontext
.mc_ebp
;
10167 #elif defined(__dietlibc__)
10168 fp
= uc
->uc_mcontext
.ebp
;
10170 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
10172 for(i
=1;i
<level
;i
++) {
10173 /* XXX: check address validity with program info */
10174 if (fp
<= 0x1000 || fp
>= 0xc0000000)
10176 fp
= ((unsigned long *)fp
)[0];
10178 *paddr
= ((unsigned long *)fp
)[1];
10182 #elif defined(__x86_64__)
10183 /* return the PC at frame level 'level'. Return non zero if not found */
10184 static int rt_get_caller_pc(unsigned long *paddr
,
10185 ucontext_t
*uc
, int level
)
10191 /* XXX: only support linux */
10192 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
10195 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
10196 for(i
=1;i
<level
;i
++) {
10197 /* XXX: check address validity with program info */
10200 fp
= ((unsigned long *)fp
)[0];
10202 *paddr
= ((unsigned long *)fp
)[1];
10208 #warning add arch specific rt_get_caller_pc()
10210 static int rt_get_caller_pc(unsigned long *paddr
,
10211 ucontext_t
*uc
, int level
)
10217 /* emit a run time error at position 'pc' */
10218 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
10225 fprintf(stderr
, "Runtime error: ");
10226 vfprintf(stderr
, fmt
, ap
);
10227 fprintf(stderr
, "\n");
10228 for(i
=0;i
<num_callers
;i
++) {
10229 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
10232 fprintf(stderr
, "at ");
10234 fprintf(stderr
, "by ");
10241 /* signal handler for fatal errors */
10242 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
10244 ucontext_t
*uc
= puc
;
10248 switch(siginf
->si_code
) {
10251 rt_error(uc
, "division by zero");
10254 rt_error(uc
, "floating point exception");
10260 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
10261 rt_error(uc
, *rt_bound_error_msg
);
10263 rt_error(uc
, "dereferencing invalid pointer");
10266 rt_error(uc
, "illegal instruction");
10269 rt_error(uc
, "abort() called");
10272 rt_error(uc
, "caught signal %d", signum
);
10279 /* do all relocations (needed before using tcc_get_symbol()) */
10280 int tcc_relocate(TCCState
*s1
)
10287 #ifdef TCC_TARGET_PE
10288 pe_add_runtime(s1
);
10290 tcc_add_runtime(s1
);
10293 relocate_common_syms();
10295 tcc_add_linker_symbols(s1
);
10296 #ifndef TCC_TARGET_PE
10297 build_got_entries(s1
);
10300 #ifdef TCC_TARGET_X86_64
10302 /* If the distance of two sections are longer than 32bit, our
10303 program will crash. Let's combine all sections which are
10304 necessary to run the program into a single buffer in the
10308 /* calculate the size of buffers we need */
10310 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10311 s
= s1
->sections
[i
];
10312 if (s
->sh_flags
& SHF_ALLOC
) {
10313 size
+= s
->data_offset
;
10316 /* double the size of the buffer for got and plt entries
10317 XXX: calculate exact size for them? */
10318 section_realloc(text_section
, size
* 2);
10319 p
= text_section
->data
+ text_section
->data_offset
;
10320 /* we will put got and plt after this offset */
10321 text_section
->data_offset
= size
;
10323 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10324 s
= s1
->sections
[i
];
10325 if (s
->sh_flags
& SHF_ALLOC
) {
10326 if (s
!= text_section
&& s
->data_offset
) {
10327 if (s
->sh_type
== SHT_NOBITS
) {
10328 /* for bss section */
10329 memset(p
, 0, s
->data_offset
);
10331 memcpy(p
, s
->data
, s
->data_offset
);
10335 /* we won't free s->data for this section */
10336 s
->data_allocated
= 0;
10337 p
+= s
->data_offset
;
10339 s
->sh_addr
= (unsigned long)s
->data
;
10344 /* compute relocation address : section are relocated in place. We
10345 also alloc the bss space */
10346 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10347 s
= s1
->sections
[i
];
10348 if (s
->sh_flags
& SHF_ALLOC
) {
10349 if (s
->sh_type
== SHT_NOBITS
)
10350 s
->data
= tcc_mallocz(s
->data_offset
);
10351 s
->sh_addr
= (unsigned long)s
->data
;
10356 relocate_syms(s1
, 1);
10358 if (s1
->nb_errors
!= 0)
10361 /* relocate each section */
10362 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10363 s
= s1
->sections
[i
];
10365 relocate_section(s1
, s
);
10368 /* mark executable sections as executable in memory */
10369 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10370 s
= s1
->sections
[i
];
10371 if ((s
->sh_flags
& (SHF_ALLOC
| SHF_EXECINSTR
)) ==
10372 (SHF_ALLOC
| SHF_EXECINSTR
))
10373 set_pages_executable(s
->data
, s
->data_offset
);
10378 /* launch the compiled program with the given arguments */
10379 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
10381 int (*prog_main
)(int, char **);
10383 if (tcc_relocate(s1
) < 0)
10386 prog_main
= tcc_get_symbol_err(s1
, "main");
10389 #if defined(_WIN32) || defined(CONFIG_TCCBOOT)
10390 error("debug mode currently not available for Windows");
10392 struct sigaction sigact
;
10393 /* install TCC signal handlers to print debug info on fatal
10395 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
10396 sigact
.sa_sigaction
= sig_error
;
10397 sigemptyset(&sigact
.sa_mask
);
10398 sigaction(SIGFPE
, &sigact
, NULL
);
10399 sigaction(SIGILL
, &sigact
, NULL
);
10400 sigaction(SIGSEGV
, &sigact
, NULL
);
10401 sigaction(SIGBUS
, &sigact
, NULL
);
10402 sigaction(SIGABRT
, &sigact
, NULL
);
10406 #ifdef CONFIG_TCC_BCHECK
10407 if (do_bounds_check
) {
10408 void (*bound_init
)(void);
10410 /* set error function */
10411 rt_bound_error_msg
= (void *)tcc_get_symbol_err(s1
,
10412 "__bound_error_msg");
10414 /* XXX: use .init section so that it also work in binary ? */
10415 bound_init
= (void *)tcc_get_symbol_err(s1
, "__bound_init");
10419 return (*prog_main
)(argc
, argv
);
10422 void tcc_memstats(void)
10425 printf("memory in use: %d\n", mem_cur_size
);
10429 static void tcc_cleanup(void)
10433 if (NULL
== tcc_state
)
10437 /* free -D defines */
10438 free_defines(NULL
);
10441 n
= tok_ident
- TOK_IDENT
;
10442 for(i
= 0; i
< n
; i
++)
10443 tcc_free(table_ident
[i
]);
10444 tcc_free(table_ident
);
10446 /* free sym_pools */
10447 dynarray_reset(&sym_pools
, &nb_sym_pools
);
10448 /* string buffer */
10449 cstr_free(&tokcstr
);
10450 /* reset symbol stack */
10451 sym_free_first
= NULL
;
10452 /* cleanup from error/setjmp */
10456 TCCState
*tcc_new(void)
10465 s
= tcc_mallocz(sizeof(TCCState
));
10469 s
->output_type
= TCC_OUTPUT_MEMORY
;
10471 /* init isid table */
10472 for(i
=CH_EOF
;i
<256;i
++)
10473 isidnum_table
[i
-CH_EOF
] = isid(i
) || isnum(i
);
10475 /* add all tokens */
10476 table_ident
= NULL
;
10477 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
10479 tok_ident
= TOK_IDENT
;
10488 ts
= tok_alloc(p
, r
- p
- 1);
10492 /* we add dummy defines for some special macros to speed up tests
10493 and to have working defined() */
10494 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
10495 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
10496 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
10497 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
10499 /* standard defines */
10500 tcc_define_symbol(s
, "__STDC__", NULL
);
10501 tcc_define_symbol(s
, "__STDC_VERSION__", "199901L");
10502 #if defined(TCC_TARGET_I386)
10503 tcc_define_symbol(s
, "__i386__", NULL
);
10505 #if defined(TCC_TARGET_X86_64)
10506 tcc_define_symbol(s
, "__x86_64__", NULL
);
10508 #if defined(TCC_TARGET_ARM)
10509 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
10510 tcc_define_symbol(s
, "__arm_elf__", NULL
);
10511 tcc_define_symbol(s
, "__arm_elf", NULL
);
10512 tcc_define_symbol(s
, "arm_elf", NULL
);
10513 tcc_define_symbol(s
, "__arm__", NULL
);
10514 tcc_define_symbol(s
, "__arm", NULL
);
10515 tcc_define_symbol(s
, "arm", NULL
);
10516 tcc_define_symbol(s
, "__APCS_32__", NULL
);
10518 #ifdef TCC_TARGET_PE
10519 tcc_define_symbol(s
, "_WIN32", NULL
);
10521 tcc_define_symbol(s
, "__unix__", NULL
);
10522 tcc_define_symbol(s
, "__unix", NULL
);
10523 #if defined(__linux)
10524 tcc_define_symbol(s
, "__linux__", NULL
);
10525 tcc_define_symbol(s
, "__linux", NULL
);
10528 /* tiny C specific defines */
10529 tcc_define_symbol(s
, "__TINYC__", NULL
);
10531 /* tiny C & gcc defines */
10532 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
10533 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
10534 #ifdef TCC_TARGET_PE
10535 tcc_define_symbol(s
, "__WCHAR_TYPE__", "unsigned short");
10537 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
10540 #ifndef TCC_TARGET_PE
10541 /* default library paths */
10542 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/local/lib");
10543 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/lib");
10544 tcc_add_library_path(s
, CONFIG_SYSROOT
"/lib");
10547 /* no section zero */
10548 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
10550 /* create standard sections */
10551 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
10552 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
10553 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
10555 /* symbols are always generated for linking stage */
10556 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
10558 ".hashtab", SHF_PRIVATE
);
10559 strtab_section
= symtab_section
->link
;
10561 /* private symbol table for dynamic symbols */
10562 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
10564 ".dynhashtab", SHF_PRIVATE
);
10565 s
->alacarte_link
= 1;
10567 #ifdef CHAR_IS_UNSIGNED
10568 s
->char_is_unsigned
= 1;
10570 #if defined(TCC_TARGET_PE) && 0
10571 /* XXX: currently the PE linker is not ready to support that */
10572 s
->leading_underscore
= 1;
10577 void tcc_delete(TCCState
*s1
)
10583 /* free all sections */
10584 for(i
= 1; i
< s1
->nb_sections
; i
++)
10585 free_section(s1
->sections
[i
]);
10586 dynarray_reset(&s1
->sections
, &s1
->nb_sections
);
10588 for(i
= 0; i
< s1
->nb_priv_sections
; i
++)
10589 free_section(s1
->priv_sections
[i
]);
10590 dynarray_reset(&s1
->priv_sections
, &s1
->nb_priv_sections
);
10592 /* free any loaded DLLs */
10593 for ( i
= 0; i
< s1
->nb_loaded_dlls
; i
++) {
10594 DLLReference
*ref
= s1
->loaded_dlls
[i
];
10596 dlclose(ref
->handle
);
10599 /* free loaded dlls array */
10600 dynarray_reset(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
);
10602 /* free library paths */
10603 dynarray_reset(&s1
->library_paths
, &s1
->nb_library_paths
);
10605 /* free include paths */
10606 dynarray_reset(&s1
->cached_includes
, &s1
->nb_cached_includes
);
10607 dynarray_reset(&s1
->include_paths
, &s1
->nb_include_paths
);
10608 dynarray_reset(&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
);
10613 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
10617 pathname1
= tcc_strdup(pathname
);
10618 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
10622 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
10626 pathname1
= tcc_strdup(pathname
);
10627 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
10631 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
10636 BufferedFile
*saved_file
;
10638 /* find source file type with extension */
10639 ext
= tcc_fileextension(filename
);
10643 /* open the file */
10645 file
= tcc_open(s1
, filename
);
10647 if (flags
& AFF_PRINT_ERROR
) {
10648 error_noabort("file '%s' not found", filename
);
10654 if (flags
& AFF_PREPROCESS
) {
10655 ret
= tcc_preprocess(s1
);
10656 } else if (!ext
[0] || !PATHCMP(ext
, "c")) {
10657 /* C file assumed */
10658 ret
= tcc_compile(s1
);
10660 #ifdef CONFIG_TCC_ASM
10661 if (!strcmp(ext
, "S")) {
10662 /* preprocessed assembler */
10663 ret
= tcc_assemble(s1
, 1);
10664 } else if (!strcmp(ext
, "s")) {
10665 /* non preprocessed assembler */
10666 ret
= tcc_assemble(s1
, 0);
10669 #ifdef TCC_TARGET_PE
10670 if (!PATHCMP(ext
, "def")) {
10671 ret
= pe_load_def_file(s1
, file
->fd
);
10676 /* assume executable format: auto guess file type */
10677 ret
= read(fd
, &ehdr
, sizeof(ehdr
));
10678 lseek(fd
, 0, SEEK_SET
);
10680 error_noabort("could not read header");
10682 } else if (ret
!= sizeof(ehdr
)) {
10683 goto try_load_script
;
10686 if (ehdr
.e_ident
[0] == ELFMAG0
&&
10687 ehdr
.e_ident
[1] == ELFMAG1
&&
10688 ehdr
.e_ident
[2] == ELFMAG2
&&
10689 ehdr
.e_ident
[3] == ELFMAG3
) {
10690 file
->line_num
= 0; /* do not display line number if error */
10691 if (ehdr
.e_type
== ET_REL
) {
10692 ret
= tcc_load_object_file(s1
, fd
, 0);
10693 } else if (ehdr
.e_type
== ET_DYN
) {
10694 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
10695 #ifdef TCC_TARGET_PE
10699 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
10706 ret
= tcc_load_dll(s1
, fd
, filename
,
10707 (flags
& AFF_REFERENCED_DLL
) != 0);
10710 error_noabort("unrecognized ELF file");
10713 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
10714 file
->line_num
= 0; /* do not display line number if error */
10715 ret
= tcc_load_archive(s1
, fd
);
10717 #ifdef TCC_TARGET_COFF
10718 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
10719 ret
= tcc_load_coff(s1
, fd
);
10722 #ifdef TCC_TARGET_PE
10723 if (pe_test_res_file(&ehdr
, ret
)) {
10724 ret
= pe_load_res_file(s1
, fd
);
10728 /* as GNU ld, consider it is an ld script if not recognized */
10730 ret
= tcc_load_ldscript(s1
);
10732 error_noabort("unrecognized file type");
10747 int tcc_add_file(TCCState
*s
, const char *filename
)
10749 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
10752 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
10756 pathname1
= tcc_strdup(pathname
);
10757 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
10761 /* find and load a dll. Return non zero if not found */
10762 /* XXX: add '-rpath' option support ? */
10763 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
10768 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10769 snprintf(buf
, sizeof(buf
), "%s/%s",
10770 s
->library_paths
[i
], filename
);
10771 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
10777 /* the library name is the same as the argument of the '-l' option */
10778 int tcc_add_library(TCCState
*s
, const char *libraryname
)
10783 /* first we look for the dynamic library if not static linking */
10784 if (!s
->static_link
) {
10785 #ifdef TCC_TARGET_PE
10786 snprintf(buf
, sizeof(buf
), "%s.def", libraryname
);
10788 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
10790 if (tcc_add_dll(s
, buf
, 0) == 0)
10794 /* then we look for the static library */
10795 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10796 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
10797 s
->library_paths
[i
], libraryname
);
10798 if (tcc_add_file_internal(s
, buf
, 0) == 0)
10804 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
10806 add_elf_sym(symtab_section
, val
, 0,
10807 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
10812 int tcc_set_output_type(TCCState
*s
, int output_type
)
10816 s
->output_type
= output_type
;
10818 if (!s
->nostdinc
) {
10819 /* default include paths */
10820 /* XXX: reverse order needed if -isystem support */
10821 #ifndef TCC_TARGET_PE
10822 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/local/include");
10823 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/include");
10825 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
10826 tcc_add_sysinclude_path(s
, buf
);
10827 #ifdef TCC_TARGET_PE
10828 snprintf(buf
, sizeof(buf
), "%s/include/winapi", tcc_lib_path
);
10829 tcc_add_sysinclude_path(s
, buf
);
10833 /* if bound checking, then add corresponding sections */
10834 #ifdef CONFIG_TCC_BCHECK
10835 if (do_bounds_check
) {
10836 /* define symbol */
10837 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
10838 /* create bounds sections */
10839 bounds_section
= new_section(s
, ".bounds",
10840 SHT_PROGBITS
, SHF_ALLOC
);
10841 lbounds_section
= new_section(s
, ".lbounds",
10842 SHT_PROGBITS
, SHF_ALLOC
);
10846 if (s
->char_is_unsigned
) {
10847 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
10850 /* add debug sections */
10853 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
10854 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
10855 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
10856 put_elf_str(stabstr_section
, "");
10857 stab_section
->link
= stabstr_section
;
10858 /* put first entry */
10859 put_stabs("", 0, 0, 0, 0);
10862 /* add libc crt1/crti objects */
10863 #ifndef TCC_TARGET_PE
10864 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
10866 if (output_type
!= TCC_OUTPUT_DLL
)
10867 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
10868 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
10872 #ifdef TCC_TARGET_PE
10873 snprintf(buf
, sizeof(buf
), "%s/lib", tcc_lib_path
);
10874 tcc_add_library_path(s
, buf
);
10880 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
10881 #define FD_INVERT 0x0002 /* invert value before storing */
10883 typedef struct FlagDef
{
10889 static const FlagDef warning_defs
[] = {
10890 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
10891 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
10892 { offsetof(TCCState
, warn_error
), 0, "error" },
10893 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
10894 "implicit-function-declaration" },
10897 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
10898 const char *name
, int value
)
10905 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
10909 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
10910 if (!strcmp(r
, p
->name
))
10915 if (p
->flags
& FD_INVERT
)
10917 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
10922 /* set/reset a warning */
10923 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
10928 if (!strcmp(warning_name
, "all")) {
10929 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
10930 if (p
->flags
& WD_ALL
)
10931 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
10935 return set_flag(s
, warning_defs
, countof(warning_defs
),
10936 warning_name
, value
);
10940 static const FlagDef flag_defs
[] = {
10941 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
10942 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
10943 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
10944 { offsetof(TCCState
, leading_underscore
), 0, "leading-underscore" },
10947 /* set/reset a flag */
10948 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
10950 return set_flag(s
, flag_defs
, countof(flag_defs
),
10954 #if !defined(LIBTCC)
10956 static int64_t getclock_us(void)
10961 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
10964 gettimeofday(&tv
, NULL
);
10965 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
10971 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard\n"
10972 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
10973 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-soname name]\n"
10974 " [-static] [infile1 infile2...] [-run infile args...]\n"
10976 "General options:\n"
10977 " -v display current version, increase verbosity\n"
10978 " -c compile only - generate an object file\n"
10979 " -o outfile set output filename\n"
10980 " -Bdir set tcc internal library path\n"
10981 " -bench output compilation statistics\n"
10982 " -run run compiled source\n"
10983 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
10984 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
10985 " -w disable all warnings\n"
10986 "Preprocessor options:\n"
10987 " -E preprocess only\n"
10988 " -Idir add include path 'dir'\n"
10989 " -Dsym[=val] define 'sym' with value 'val'\n"
10990 " -Usym undefine 'sym'\n"
10991 "Linker options:\n"
10992 " -Ldir add library path 'dir'\n"
10993 " -llib link with dynamic or static library 'lib'\n"
10994 " -shared generate a shared library\n"
10995 " -soname set name for shared library to be used at runtime\n"
10996 " -static static linking\n"
10997 " -rdynamic export all global symbols to dynamic linker\n"
10998 " -r generate (relocatable) object file\n"
10999 "Debugger options:\n"
11000 " -g generate runtime debug info\n"
11001 #ifdef CONFIG_TCC_BCHECK
11002 " -b compile with built-in memory and bounds checker (implies -g)\n"
11004 " -bt N show N callers in stack traces\n"
11008 #define TCC_OPTION_HAS_ARG 0x0001
11009 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
11011 typedef struct TCCOption
{
11040 TCC_OPTION_nostdinc
,
11041 TCC_OPTION_nostdlib
,
11042 TCC_OPTION_print_search_dirs
,
11043 TCC_OPTION_rdynamic
,
11051 static const TCCOption tcc_options
[] = {
11052 { "h", TCC_OPTION_HELP
, 0 },
11053 { "?", TCC_OPTION_HELP
, 0 },
11054 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
11055 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
11056 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
11057 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
11058 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
11059 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11060 { "bench", TCC_OPTION_bench
, 0 },
11061 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
11062 #ifdef CONFIG_TCC_BCHECK
11063 { "b", TCC_OPTION_b
, 0 },
11065 { "g", TCC_OPTION_g
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11066 { "c", TCC_OPTION_c
, 0 },
11067 { "static", TCC_OPTION_static
, 0 },
11068 { "shared", TCC_OPTION_shared
, 0 },
11069 { "soname", TCC_OPTION_soname
, TCC_OPTION_HAS_ARG
},
11070 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
11071 { "run", TCC_OPTION_run
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11072 { "rdynamic", TCC_OPTION_rdynamic
, 0 },
11073 { "r", TCC_OPTION_r
, 0 },
11074 { "Wl,", TCC_OPTION_Wl
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11075 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11076 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11077 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
11078 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11079 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
11080 { "nostdlib", TCC_OPTION_nostdlib
, 0 },
11081 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
11082 { "v", TCC_OPTION_v
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11083 { "w", TCC_OPTION_w
, 0 },
11084 { "pipe", TCC_OPTION_pipe
, 0},
11085 { "E", TCC_OPTION_E
, 0},
11089 /* convert 'str' into an array of space separated strings */
11090 static int expand_args(char ***pargv
, const char *str
)
11099 while (is_space(*str
))
11104 while (*str
!= '\0' && !is_space(*str
))
11107 arg
= tcc_malloc(len
+ 1);
11108 memcpy(arg
, s1
, len
);
11110 dynarray_add((void ***)&argv
, &argc
, arg
);
11116 static char **files
;
11117 static int nb_files
, nb_libraries
;
11118 static int multiple_files
;
11119 static int print_search_dirs
;
11120 static int output_type
;
11121 static int reloc_output
;
11122 static const char *outfile
;
11124 int parse_args(TCCState
*s
, int argc
, char **argv
)
11127 const TCCOption
*popt
;
11128 const char *optarg
, *p1
, *r1
;
11132 while (optind
< argc
) {
11134 r
= argv
[optind
++];
11135 if (r
[0] != '-' || r
[1] == '\0') {
11136 /* add a new file */
11137 dynarray_add((void ***)&files
, &nb_files
, r
);
11138 if (!multiple_files
) {
11140 /* argv[0] will be this file */
11144 /* find option in table (match only the first chars */
11145 popt
= tcc_options
;
11149 error("invalid option -- '%s'", r
);
11162 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
11163 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
11166 if (optind
>= argc
)
11167 error("argument to '%s' is missing", r
);
11168 optarg
= argv
[optind
++];
11176 switch(popt
->index
) {
11177 case TCC_OPTION_HELP
:
11181 if (tcc_add_include_path(s
, optarg
) < 0)
11182 error("too many include paths");
11187 sym
= (char *)optarg
;
11188 value
= strchr(sym
, '=');
11193 tcc_define_symbol(s
, sym
, value
);
11197 tcc_undefine_symbol(s
, optarg
);
11200 tcc_add_library_path(s
, optarg
);
11203 /* set tcc utilities path (mainly for tcc development) */
11204 tcc_lib_path
= optarg
;
11207 dynarray_add((void ***)&files
, &nb_files
, r
);
11210 case TCC_OPTION_bench
:
11213 case TCC_OPTION_bt
:
11214 num_callers
= atoi(optarg
);
11216 #ifdef CONFIG_TCC_BCHECK
11218 do_bounds_check
= 1;
11226 multiple_files
= 1;
11227 output_type
= TCC_OUTPUT_OBJ
;
11229 case TCC_OPTION_static
:
11230 s
->static_link
= 1;
11232 case TCC_OPTION_shared
:
11233 output_type
= TCC_OUTPUT_DLL
;
11235 case TCC_OPTION_soname
:
11236 s
->soname
= optarg
;
11239 multiple_files
= 1;
11243 /* generate a .o merging several output files */
11245 output_type
= TCC_OUTPUT_OBJ
;
11247 case TCC_OPTION_nostdinc
:
11250 case TCC_OPTION_nostdlib
:
11253 case TCC_OPTION_print_search_dirs
:
11254 print_search_dirs
= 1;
11256 case TCC_OPTION_run
:
11260 argc1
= expand_args(&argv1
, optarg
);
11262 parse_args(s
, argc1
, argv1
);
11264 multiple_files
= 0;
11265 output_type
= TCC_OUTPUT_MEMORY
;
11270 if (0 == verbose
++)
11271 printf("tcc version %s\n", TCC_VERSION
);
11272 } while (*optarg
++ == 'v');
11275 if (tcc_set_flag(s
, optarg
, 1) < 0 && s
->warn_unsupported
)
11276 goto unsupported_option
;
11279 if (tcc_set_warning(s
, optarg
, 1) < 0 &&
11280 s
->warn_unsupported
)
11281 goto unsupported_option
;
11286 case TCC_OPTION_rdynamic
:
11289 case TCC_OPTION_Wl
:
11292 if (strstart(optarg
, "-Ttext,", &p
)) {
11293 s
->text_addr
= strtoul(p
, NULL
, 16);
11294 s
->has_text_addr
= 1;
11295 } else if (strstart(optarg
, "--oformat,", &p
)) {
11296 if (strstart(p
, "elf32-", NULL
)) {
11297 s
->output_format
= TCC_OUTPUT_FORMAT_ELF
;
11298 } else if (!strcmp(p
, "binary")) {
11299 s
->output_format
= TCC_OUTPUT_FORMAT_BINARY
;
11301 #ifdef TCC_TARGET_COFF
11302 if (!strcmp(p
, "coff")) {
11303 s
->output_format
= TCC_OUTPUT_FORMAT_COFF
;
11307 error("target %s not found", p
);
11310 error("unsupported linker option '%s'", optarg
);
11315 output_type
= TCC_OUTPUT_PREPROCESS
;
11318 if (s
->warn_unsupported
) {
11319 unsupported_option
:
11320 warning("unsupported option '%s'", r
);
11329 int main(int argc
, char **argv
)
11333 int nb_objfiles
, ret
, optind
;
11334 char objfilename
[1024];
11335 int64_t start_time
= 0;
11338 tcc_lib_path
= w32_tcc_lib_path();
11342 output_type
= TCC_OUTPUT_EXE
;
11344 multiple_files
= 1;
11349 print_search_dirs
= 0;
11352 optind
= parse_args(s
, argc
- 1, argv
+ 1);
11353 if (print_search_dirs
) {
11354 /* enough for Linux kernel */
11355 printf("install: %s/\n", tcc_lib_path
);
11358 if (optind
== 0 || nb_files
== 0) {
11359 if (optind
&& verbose
)
11365 nb_objfiles
= nb_files
- nb_libraries
;
11367 /* if outfile provided without other options, we output an
11369 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
11370 output_type
= TCC_OUTPUT_EXE
;
11372 /* check -c consistency : only single file handled. XXX: checks file type */
11373 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
11374 /* accepts only a single input file */
11375 if (nb_objfiles
!= 1)
11376 error("cannot specify multiple files with -c");
11377 if (nb_libraries
!= 0)
11378 error("cannot specify libraries with -c");
11382 if (output_type
== TCC_OUTPUT_PREPROCESS
) {
11384 s
->outfile
= stdout
;
11386 s
->outfile
= fopen(outfile
, "w");
11388 error("could not open '%s", outfile
);
11390 } else if (output_type
!= TCC_OUTPUT_MEMORY
) {
11392 /* compute default outfile name */
11395 strcmp(files
[0], "-") == 0 ? "a" : tcc_basename(files
[0]);
11396 pstrcpy(objfilename
, sizeof(objfilename
), name
);
11397 ext
= tcc_fileextension(objfilename
);
11398 #ifdef TCC_TARGET_PE
11399 if (output_type
== TCC_OUTPUT_DLL
)
11400 strcpy(ext
, ".dll");
11402 if (output_type
== TCC_OUTPUT_EXE
)
11403 strcpy(ext
, ".exe");
11406 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
&& *ext
)
11409 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
11410 outfile
= objfilename
;
11415 start_time
= getclock_us();
11418 tcc_set_output_type(s
, output_type
);
11420 /* compile or add each files or library */
11421 for(i
= 0; i
< nb_files
&& ret
== 0; i
++) {
11422 const char *filename
;
11424 filename
= files
[i
];
11425 if (output_type
== TCC_OUTPUT_PREPROCESS
) {
11426 if (tcc_add_file_internal(s
, filename
,
11427 AFF_PRINT_ERROR
| AFF_PREPROCESS
) < 0)
11429 } else if (filename
[0] == '-' && filename
[1]) {
11430 if (tcc_add_library(s
, filename
+ 2) < 0)
11431 error("cannot find %s", filename
);
11434 printf("-> %s\n", filename
);
11435 if (tcc_add_file(s
, filename
) < 0)
11440 /* free all files */
11448 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
11449 if (total_time
< 0.001)
11450 total_time
= 0.001;
11451 if (total_bytes
< 1)
11453 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
11454 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
11455 total_time
, (int)(total_lines
/ total_time
),
11456 total_bytes
/ total_time
/ 1000000.0);
11459 if (s
->output_type
== TCC_OUTPUT_PREPROCESS
) {
11461 fclose(s
->outfile
);
11462 } else if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
11463 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
11465 ret
= tcc_output_file(s
, outfile
) ? 1 : 0;
11467 /* XXX: cannot do it with bound checking because of the malloc hooks */
11468 if (!do_bounds_check
)
11473 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);