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])))
1079 #define IS_PATHSEP(c) (c == '/')
1080 #define IS_ABSPATH(p) IS_PATHSEP(p[0])
1083 /* extract the basename of a file */
1084 static char *tcc_basename(const char *name
)
1086 char *p
= strchr(name
, 0);
1087 while (p
> name
&& !IS_PATHSEP(p
[-1]))
1092 static char *tcc_fileextension (const char *name
)
1094 char *b
= tcc_basename(name
);
1095 char *e
= strrchr(b
, '.');
1096 return e
? e
: strchr(b
, 0);
1100 char *normalize_slashes(char *path
)
1103 for (p
= path
; *p
; ++p
)
1109 char *w32_tcc_lib_path(void)
1111 /* on win32, we suppose the lib and includes are at the location
1113 char path
[1024], *p
;
1114 GetModuleFileNameA(NULL
, path
, sizeof path
);
1115 p
= tcc_basename(normalize_slashes(strlwr(path
)));
1116 if (p
- 5 > path
&& 0 == strncmp(p
- 5, "/bin/", 5))
1121 return strdup(path
);
1125 void set_pages_executable(void *ptr
, unsigned long length
)
1128 unsigned long old_protect
;
1129 VirtualProtect(ptr
, length
, PAGE_EXECUTE_READWRITE
, &old_protect
);
1131 unsigned long start
, end
;
1132 start
= (unsigned long)ptr
& ~(PAGESIZE
- 1);
1133 end
= (unsigned long)ptr
+ length
;
1134 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
1135 mprotect((void *)start
, end
- start
, PROT_READ
| PROT_WRITE
| PROT_EXEC
);
1139 /* memory management */
1143 unsigned malloc_usable_size(void*);
1146 static inline void tcc_free(void *ptr
)
1149 mem_cur_size
-= malloc_usable_size(ptr
);
1154 static void *tcc_malloc(unsigned long size
)
1159 error("memory full");
1161 mem_cur_size
+= malloc_usable_size(ptr
);
1162 if (mem_cur_size
> mem_max_size
)
1163 mem_max_size
= mem_cur_size
;
1168 static void *tcc_mallocz(unsigned long size
)
1171 ptr
= tcc_malloc(size
);
1172 memset(ptr
, 0, size
);
1176 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
1180 mem_cur_size
-= malloc_usable_size(ptr
);
1182 ptr1
= realloc(ptr
, size
);
1184 /* NOTE: count not correct if alloc error, but not critical */
1185 mem_cur_size
+= malloc_usable_size(ptr1
);
1186 if (mem_cur_size
> mem_max_size
)
1187 mem_max_size
= mem_cur_size
;
1192 static char *tcc_strdup(const char *str
)
1195 ptr
= tcc_malloc(strlen(str
) + 1);
1200 #define free(p) use_tcc_free(p)
1201 #define malloc(s) use_tcc_malloc(s)
1202 #define realloc(p, s) use_tcc_realloc(p, s)
1204 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
1211 /* every power of two we double array size */
1212 if ((nb
& (nb
- 1)) == 0) {
1217 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
1219 error("memory full");
1226 static void dynarray_reset(void *pp
, int *n
)
1229 for (p
= *(void***)pp
; *n
; ++p
, --*n
)
1232 tcc_free(*(void**)pp
);
1236 /* symbol allocator */
1237 static Sym
*__sym_malloc(void)
1239 Sym
*sym_pool
, *sym
, *last_sym
;
1242 sym_pool
= tcc_malloc(SYM_POOL_NB
* sizeof(Sym
));
1243 dynarray_add(&sym_pools
, &nb_sym_pools
, sym_pool
);
1245 last_sym
= sym_free_first
;
1247 for(i
= 0; i
< SYM_POOL_NB
; i
++) {
1248 sym
->next
= last_sym
;
1252 sym_free_first
= last_sym
;
1256 static inline Sym
*sym_malloc(void)
1259 sym
= sym_free_first
;
1261 sym
= __sym_malloc();
1262 sym_free_first
= sym
->next
;
1266 static inline void sym_free(Sym
*sym
)
1268 sym
->next
= sym_free_first
;
1269 sym_free_first
= sym
;
1272 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
1276 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
1277 strcpy(sec
->name
, name
);
1278 sec
->sh_type
= sh_type
;
1279 sec
->sh_flags
= sh_flags
;
1287 sec
->sh_addralign
= 4;
1290 sec
->sh_addralign
= 1;
1293 sec
->sh_addralign
= 32; /* default conservative alignment */
1297 if (sh_flags
& SHF_PRIVATE
) {
1298 dynarray_add((void ***)&s1
->priv_sections
, &s1
->nb_priv_sections
, sec
);
1300 sec
->sh_num
= s1
->nb_sections
;
1301 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
1307 static void free_section(Section
*s
)
1309 #ifdef TCC_TARGET_X86_64
1310 /* after tcc_relocate(), some sections share the data buffer.
1311 let's check if the data is allocated not to free the shared buffers */
1312 if (s
->data_allocated
)
1317 /* realloc section and set its content to zero */
1318 static void section_realloc(Section
*sec
, unsigned long new_size
)
1321 unsigned char *data
;
1323 size
= sec
->data_allocated
;
1326 while (size
< new_size
)
1328 data
= tcc_realloc(sec
->data
, size
);
1330 error("memory full");
1331 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1333 sec
->data_allocated
= size
;
1336 /* reserve at least 'size' bytes in section 'sec' from
1337 sec->data_offset. */
1338 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1340 unsigned long offset
, offset1
;
1342 offset
= sec
->data_offset
;
1343 offset1
= offset
+ size
;
1344 if (offset1
> sec
->data_allocated
)
1345 section_realloc(sec
, offset1
);
1346 sec
->data_offset
= offset1
;
1347 return sec
->data
+ offset
;
1350 /* return a reference to a section, and create it if it does not
1352 Section
*find_section(TCCState
*s1
, const char *name
)
1356 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1357 sec
= s1
->sections
[i
];
1358 if (!strcmp(name
, sec
->name
))
1361 /* sections are created as PROGBITS */
1362 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1365 #define SECTION_ABS ((void *)1)
1367 /* update sym->c so that it points to an external symbol in section
1368 'section' with value 'value' */
1369 static void put_extern_sym2(Sym
*sym
, Section
*section
,
1370 unsigned long value
, unsigned long size
,
1371 int can_add_underscore
)
1373 int sym_type
, sym_bind
, sh_num
, info
, other
, attr
;
1378 if (section
== NULL
)
1380 else if (section
== SECTION_ABS
)
1383 sh_num
= section
->sh_num
;
1387 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
) {
1388 sym_type
= STT_FUNC
;
1389 #ifdef TCC_TARGET_PE
1391 attr
= sym
->type
.ref
->r
;
1392 if (FUNC_EXPORT(attr
))
1394 if (FUNC_CALL(attr
) == FUNC_STDCALL
)
1398 sym_type
= STT_OBJECT
;
1401 if (sym
->type
.t
& VT_STATIC
)
1402 sym_bind
= STB_LOCAL
;
1404 sym_bind
= STB_GLOBAL
;
1407 name
= get_tok_str(sym
->v
, NULL
);
1408 #ifdef CONFIG_TCC_BCHECK
1409 if (do_bounds_check
) {
1412 /* XXX: avoid doing that for statics ? */
1413 /* if bound checking is activated, we change some function
1414 names by adding the "__bound" prefix */
1417 /* XXX: we rely only on malloc hooks */
1430 strcpy(buf
, "__bound_");
1438 #ifdef TCC_TARGET_PE
1439 if ((other
& 2) && can_add_underscore
) {
1440 sprintf(buf1
, "_%s@%d", name
, FUNC_ARGS(attr
));
1444 if (tcc_state
->leading_underscore
&& can_add_underscore
) {
1446 pstrcpy(buf1
+ 1, sizeof(buf1
) - 1, name
);
1449 info
= ELFW(ST_INFO
)(sym_bind
, sym_type
);
1450 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, other
, sh_num
, name
);
1452 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
1453 esym
->st_value
= value
;
1454 esym
->st_size
= size
;
1455 esym
->st_shndx
= sh_num
;
1456 esym
->st_other
|= other
;
1460 static void put_extern_sym(Sym
*sym
, Section
*section
,
1461 unsigned long value
, unsigned long size
)
1463 put_extern_sym2(sym
, section
, value
, size
, 1);
1466 /* add a new relocation entry to symbol 'sym' in section 's' */
1467 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1470 put_extern_sym(sym
, NULL
, 0, 0);
1471 /* now we can add ELF relocation info */
1472 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1475 static inline int isid(int c
)
1477 return (c
>= 'a' && c
<= 'z') ||
1478 (c
>= 'A' && c
<= 'Z') ||
1482 static inline int isnum(int c
)
1484 return c
>= '0' && c
<= '9';
1487 static inline int isoct(int c
)
1489 return c
>= '0' && c
<= '7';
1492 static inline int toup(int c
)
1494 if (c
>= 'a' && c
<= 'z')
1495 return c
- 'a' + 'A';
1500 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1504 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1507 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1511 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1515 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1522 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1523 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1524 (*f
)->filename
, (*f
)->line_num
);
1525 if (file
->line_num
> 0) {
1526 strcat_printf(buf
, sizeof(buf
),
1527 "%s:%d: ", file
->filename
, file
->line_num
);
1529 strcat_printf(buf
, sizeof(buf
),
1530 "%s: ", file
->filename
);
1533 strcat_printf(buf
, sizeof(buf
),
1537 strcat_printf(buf
, sizeof(buf
), "warning: ");
1538 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1540 if (!s1
->error_func
) {
1541 /* default case: stderr */
1542 fprintf(stderr
, "%s\n", buf
);
1544 s1
->error_func(s1
->error_opaque
, buf
);
1546 if (!is_warning
|| s1
->warn_error
)
1551 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1552 void (*error_func
)(void *opaque
, const char *msg
))
1554 s
->error_opaque
= error_opaque
;
1555 s
->error_func
= error_func
;
1559 /* error without aborting current compilation */
1560 void error_noabort(const char *fmt
, ...)
1562 TCCState
*s1
= tcc_state
;
1566 error1(s1
, 0, fmt
, ap
);
1570 void error(const char *fmt
, ...)
1572 TCCState
*s1
= tcc_state
;
1576 error1(s1
, 0, fmt
, ap
);
1578 /* better than nothing: in some cases, we accept to handle errors */
1579 if (s1
->error_set_jmp_enabled
) {
1580 longjmp(s1
->error_jmp_buf
, 1);
1582 /* XXX: eliminate this someday */
1587 void expect(const char *msg
)
1589 error("%s expected", msg
);
1592 void warning(const char *fmt
, ...)
1594 TCCState
*s1
= tcc_state
;
1601 error1(s1
, 1, fmt
, ap
);
1608 error("'%c' expected", c
);
1612 static void test_lvalue(void)
1614 if (!(vtop
->r
& VT_LVAL
))
1618 /* allocate a new token */
1619 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1621 TokenSym
*ts
, **ptable
;
1624 if (tok_ident
>= SYM_FIRST_ANOM
)
1625 error("memory full");
1627 /* expand token table if needed */
1628 i
= tok_ident
- TOK_IDENT
;
1629 if ((i
% TOK_ALLOC_INCR
) == 0) {
1630 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1632 error("memory full");
1633 table_ident
= ptable
;
1636 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1637 table_ident
[i
] = ts
;
1638 ts
->tok
= tok_ident
++;
1639 ts
->sym_define
= NULL
;
1640 ts
->sym_label
= NULL
;
1641 ts
->sym_struct
= NULL
;
1642 ts
->sym_identifier
= NULL
;
1644 ts
->hash_next
= NULL
;
1645 memcpy(ts
->str
, str
, len
);
1646 ts
->str
[len
] = '\0';
1651 #define TOK_HASH_INIT 1
1652 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1654 /* find a token and add it if not found */
1655 static TokenSym
*tok_alloc(const char *str
, int len
)
1657 TokenSym
*ts
, **pts
;
1663 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1664 h
&= (TOK_HASH_SIZE
- 1);
1666 pts
= &hash_ident
[h
];
1671 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1673 pts
= &(ts
->hash_next
);
1675 return tok_alloc_new(pts
, str
, len
);
1678 /* CString handling */
1680 static void cstr_realloc(CString
*cstr
, int new_size
)
1685 size
= cstr
->size_allocated
;
1687 size
= 8; /* no need to allocate a too small first string */
1688 while (size
< new_size
)
1690 data
= tcc_realloc(cstr
->data_allocated
, size
);
1692 error("memory full");
1693 cstr
->data_allocated
= data
;
1694 cstr
->size_allocated
= size
;
1699 static inline void cstr_ccat(CString
*cstr
, int ch
)
1702 size
= cstr
->size
+ 1;
1703 if (size
> cstr
->size_allocated
)
1704 cstr_realloc(cstr
, size
);
1705 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1709 static void cstr_cat(CString
*cstr
, const char *str
)
1721 /* add a wide char */
1722 static void cstr_wccat(CString
*cstr
, int ch
)
1725 size
= cstr
->size
+ sizeof(nwchar_t
);
1726 if (size
> cstr
->size_allocated
)
1727 cstr_realloc(cstr
, size
);
1728 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
1732 static void cstr_new(CString
*cstr
)
1734 memset(cstr
, 0, sizeof(CString
));
1737 /* free string and reset it to NULL */
1738 static void cstr_free(CString
*cstr
)
1740 tcc_free(cstr
->data_allocated
);
1744 #define cstr_reset(cstr) cstr_free(cstr)
1746 /* XXX: unicode ? */
1747 static void add_char(CString
*cstr
, int c
)
1749 if (c
== '\'' || c
== '\"' || c
== '\\') {
1750 /* XXX: could be more precise if char or string */
1751 cstr_ccat(cstr
, '\\');
1753 if (c
>= 32 && c
<= 126) {
1756 cstr_ccat(cstr
, '\\');
1758 cstr_ccat(cstr
, 'n');
1760 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1761 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1762 cstr_ccat(cstr
, '0' + (c
& 7));
1767 /* XXX: buffer overflow */
1768 /* XXX: float tokens */
1769 char *get_tok_str(int v
, CValue
*cv
)
1771 static char buf
[STRING_MAX_SIZE
+ 1];
1772 static CString cstr_buf
;
1778 /* NOTE: to go faster, we give a fixed buffer for small strings */
1779 cstr_reset(&cstr_buf
);
1780 cstr_buf
.data
= buf
;
1781 cstr_buf
.size_allocated
= sizeof(buf
);
1787 /* XXX: not quite exact, but only useful for testing */
1788 sprintf(p
, "%u", cv
->ui
);
1792 /* XXX: not quite exact, but only useful for testing */
1793 sprintf(p
, "%Lu", cv
->ull
);
1796 cstr_ccat(&cstr_buf
, 'L');
1798 cstr_ccat(&cstr_buf
, '\'');
1799 add_char(&cstr_buf
, cv
->i
);
1800 cstr_ccat(&cstr_buf
, '\'');
1801 cstr_ccat(&cstr_buf
, '\0');
1805 len
= cstr
->size
- 1;
1807 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1808 cstr_ccat(&cstr_buf
, '\0');
1811 cstr_ccat(&cstr_buf
, 'L');
1814 cstr_ccat(&cstr_buf
, '\"');
1816 len
= cstr
->size
- 1;
1818 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1820 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
1822 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
1824 cstr_ccat(&cstr_buf
, '\"');
1825 cstr_ccat(&cstr_buf
, '\0');
1834 return strcpy(p
, "...");
1836 return strcpy(p
, "<<=");
1838 return strcpy(p
, ">>=");
1840 if (v
< TOK_IDENT
) {
1841 /* search in two bytes table */
1855 } else if (v
< tok_ident
) {
1856 return table_ident
[v
- TOK_IDENT
]->str
;
1857 } else if (v
>= SYM_FIRST_ANOM
) {
1858 /* special name for anonymous symbol */
1859 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1861 /* should never happen */
1866 return cstr_buf
.data
;
1869 /* push, without hashing */
1870 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, long c
)
1884 /* find a symbol and return its associated structure. 's' is the top
1885 of the symbol stack */
1886 static Sym
*sym_find2(Sym
*s
, int v
)
1896 /* structure lookup */
1897 static inline Sym
*struct_find(int v
)
1900 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1902 return table_ident
[v
]->sym_struct
;
1905 /* find an identifier */
1906 static inline Sym
*sym_find(int v
)
1909 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1911 return table_ident
[v
]->sym_identifier
;
1914 /* push a given symbol on the symbol stack */
1915 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1924 s
= sym_push2(ps
, v
, type
->t
, c
);
1925 s
->type
.ref
= type
->ref
;
1927 /* don't record fields or anonymous symbols */
1929 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1930 /* record symbol in token array */
1931 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1933 ps
= &ts
->sym_struct
;
1935 ps
= &ts
->sym_identifier
;
1942 /* push a global identifier */
1943 static Sym
*global_identifier_push(int v
, int t
, int c
)
1946 s
= sym_push2(&global_stack
, v
, t
, c
);
1947 /* don't record anonymous symbol */
1948 if (v
< SYM_FIRST_ANOM
) {
1949 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1950 /* modify the top most local identifier, so that
1951 sym_identifier will point to 's' when popped */
1953 ps
= &(*ps
)->prev_tok
;
1960 /* pop symbols until top reaches 'b' */
1961 static void sym_pop(Sym
**ptop
, Sym
*b
)
1971 /* remove symbol in token array */
1973 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1974 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1976 ps
= &ts
->sym_struct
;
1978 ps
= &ts
->sym_identifier
;
1989 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1994 if (strcmp(filename
, "-") == 0)
1995 fd
= 0, filename
= "stdin";
1997 fd
= open(filename
, O_RDONLY
| O_BINARY
);
1998 if ((verbose
== 2 && fd
>= 0) || verbose
== 3)
1999 printf("%s %*s%s\n", fd
< 0 ? "nf":"->",
2000 (s1
->include_stack_ptr
- s1
->include_stack
), "", filename
);
2003 bf
= tcc_malloc(sizeof(BufferedFile
));
2005 bf
->buf_ptr
= bf
->buffer
;
2006 bf
->buf_end
= bf
->buffer
;
2007 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
2008 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
2010 normalize_slashes(bf
->filename
);
2013 bf
->ifndef_macro
= 0;
2014 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
2015 // printf("opening '%s'\n", filename);
2019 void tcc_close(BufferedFile
*bf
)
2021 total_lines
+= bf
->line_num
;
2026 /* fill input buffer and peek next char */
2027 static int tcc_peekc_slow(BufferedFile
*bf
)
2030 /* only tries to read if really end of buffer */
2031 if (bf
->buf_ptr
>= bf
->buf_end
) {
2033 #if defined(PARSE_DEBUG)
2038 len
= read(bf
->fd
, bf
->buffer
, len
);
2045 bf
->buf_ptr
= bf
->buffer
;
2046 bf
->buf_end
= bf
->buffer
+ len
;
2047 *bf
->buf_end
= CH_EOB
;
2049 if (bf
->buf_ptr
< bf
->buf_end
) {
2050 return bf
->buf_ptr
[0];
2052 bf
->buf_ptr
= bf
->buf_end
;
2057 /* return the current character, handling end of block if necessary
2059 static int handle_eob(void)
2061 return tcc_peekc_slow(file
);
2064 /* read next char from current input file and handle end of input buffer */
2065 static inline void inp(void)
2067 ch
= *(++(file
->buf_ptr
));
2068 /* end of buffer/file handling */
2073 /* handle '\[\r]\n' */
2074 static int handle_stray_noerror(void)
2076 while (ch
== '\\') {
2081 } else if (ch
== '\r') {
2095 static void handle_stray(void)
2097 if (handle_stray_noerror())
2098 error("stray '\\' in program");
2101 /* skip the stray and handle the \\n case. Output an error if
2102 incorrect char after the stray */
2103 static int handle_stray1(uint8_t *p
)
2107 if (p
>= file
->buf_end
) {
2124 /* handle just the EOB case, but not stray */
2125 #define PEEKC_EOB(c, p)\
2136 /* handle the complicated stray case */
2137 #define PEEKC(c, p)\
2142 c = handle_stray1(p);\
2147 /* input with '\[\r]\n' handling. Note that this function cannot
2148 handle other characters after '\', so you cannot call it inside
2149 strings or comments */
2150 static void minp(void)
2158 /* single line C++ comments */
2159 static uint8_t *parse_line_comment(uint8_t *p
)
2167 if (c
== '\n' || c
== CH_EOF
) {
2169 } else if (c
== '\\') {
2178 } else if (c
== '\r') {
2196 static uint8_t *parse_comment(uint8_t *p
)
2202 /* fast skip loop */
2205 if (c
== '\n' || c
== '*' || c
== '\\')
2209 if (c
== '\n' || c
== '*' || c
== '\\')
2213 /* now we can handle all the cases */
2217 } else if (c
== '*') {
2223 } else if (c
== '/') {
2224 goto end_of_comment
;
2225 } else if (c
== '\\') {
2230 /* skip '\[\r]\n', otherwise just skip the stray */
2236 } else if (c
== '\r') {
2253 /* stray, eob or eof */
2258 error("unexpected end of file in comment");
2259 } else if (c
== '\\') {
2271 /* space exlcuding newline */
2272 static inline int is_space(int ch
)
2274 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
2277 static inline void skip_spaces(void)
2279 while (is_space(ch
))
2283 /* parse a string without interpreting escapes */
2284 static uint8_t *parse_pp_string(uint8_t *p
,
2285 int sep
, CString
*str
)
2293 } else if (c
== '\\') {
2298 unterminated_string
:
2299 /* XXX: indicate line number of start of string */
2300 error("missing terminating %c character", sep
);
2301 } else if (c
== '\\') {
2302 /* escape : just skip \[\r]\n */
2307 } else if (c
== '\r') {
2310 expect("'\n' after '\r'");
2313 } else if (c
== CH_EOF
) {
2314 goto unterminated_string
;
2317 cstr_ccat(str
, '\\');
2323 } else if (c
== '\n') {
2326 } else if (c
== '\r') {
2330 cstr_ccat(str
, '\r');
2346 /* skip block of text until #else, #elif or #endif. skip also pairs of
2348 void preprocess_skip(void)
2350 int a
, start_of_line
, c
, in_warn_or_error
;
2357 in_warn_or_error
= 0;
2378 } else if (c
== '\\') {
2379 ch
= file
->buf_ptr
[0];
2380 handle_stray_noerror();
2387 if (in_warn_or_error
)
2389 p
= parse_pp_string(p
, c
, NULL
);
2393 if (in_warn_or_error
)
2400 p
= parse_comment(p
);
2401 } else if (ch
== '/') {
2402 p
= parse_line_comment(p
);
2407 if (start_of_line
) {
2412 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2414 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2416 else if (tok
== TOK_ENDIF
)
2418 else if( tok
== TOK_ERROR
|| tok
== TOK_WARNING
)
2419 in_warn_or_error
= 1;
2433 /* ParseState handling */
2435 /* XXX: currently, no include file info is stored. Thus, we cannot display
2436 accurate messages if the function or data definition spans multiple
2439 /* save current parse state in 's' */
2440 void save_parse_state(ParseState
*s
)
2442 s
->line_num
= file
->line_num
;
2443 s
->macro_ptr
= macro_ptr
;
2448 /* restore parse state from 's' */
2449 void restore_parse_state(ParseState
*s
)
2451 file
->line_num
= s
->line_num
;
2452 macro_ptr
= s
->macro_ptr
;
2457 /* return the number of additional 'ints' necessary to store the
2459 static inline int tok_ext_size(int t
)
2473 error("unsupported token");
2480 return LDOUBLE_SIZE
/ 4;
2486 /* token string handling */
2488 static inline void tok_str_new(TokenString
*s
)
2492 s
->allocated_len
= 0;
2493 s
->last_line_num
= -1;
2496 static void tok_str_free(int *str
)
2501 static int *tok_str_realloc(TokenString
*s
)
2505 if (s
->allocated_len
== 0) {
2508 len
= s
->allocated_len
* 2;
2510 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2512 error("memory full");
2513 s
->allocated_len
= len
;
2518 static void tok_str_add(TokenString
*s
, int t
)
2524 if (len
>= s
->allocated_len
)
2525 str
= tok_str_realloc(s
);
2530 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2537 /* allocate space for worst case */
2538 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2539 str
= tok_str_realloc(s
);
2548 str
[len
++] = cv
->tab
[0];
2557 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
2558 while ((len
+ nb_words
) > s
->allocated_len
)
2559 str
= tok_str_realloc(s
);
2560 cstr
= (CString
*)(str
+ len
);
2562 cstr
->size
= cv
->cstr
->size
;
2563 cstr
->data_allocated
= NULL
;
2564 cstr
->size_allocated
= cstr
->size
;
2565 memcpy((char *)cstr
+ sizeof(CString
),
2566 cv
->cstr
->data
, cstr
->size
);
2573 #if LDOUBLE_SIZE == 8
2576 str
[len
++] = cv
->tab
[0];
2577 str
[len
++] = cv
->tab
[1];
2579 #if LDOUBLE_SIZE == 12
2581 str
[len
++] = cv
->tab
[0];
2582 str
[len
++] = cv
->tab
[1];
2583 str
[len
++] = cv
->tab
[2];
2584 #elif LDOUBLE_SIZE == 16
2586 str
[len
++] = cv
->tab
[0];
2587 str
[len
++] = cv
->tab
[1];
2588 str
[len
++] = cv
->tab
[2];
2589 str
[len
++] = cv
->tab
[3];
2590 #elif LDOUBLE_SIZE != 8
2591 #error add long double size support
2600 /* add the current parse token in token string 's' */
2601 static void tok_str_add_tok(TokenString
*s
)
2605 /* save line number info */
2606 if (file
->line_num
!= s
->last_line_num
) {
2607 s
->last_line_num
= file
->line_num
;
2608 cval
.i
= s
->last_line_num
;
2609 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2611 tok_str_add2(s
, tok
, &tokc
);
2614 #if LDOUBLE_SIZE == 16
2615 #define LDOUBLE_GET(p, cv) \
2620 #elif LDOUBLE_SIZE == 12
2621 #define LDOUBLE_GET(p, cv) \
2625 #elif LDOUBLE_SIZE == 8
2626 #define LDOUBLE_GET(p, cv) \
2630 #error add long double size support
2634 /* get a token from an integer array and increment pointer
2635 accordingly. we code it as a macro to avoid pointer aliasing. */
2636 #define TOK_GET(t, p, cv) \
2651 cv.cstr = (CString *)p; \
2652 cv.cstr->data = (char *)p + sizeof(CString);\
2653 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
2662 case TOK_CLDOUBLE: \
2663 LDOUBLE_GET(p, cv); \
2664 p += LDOUBLE_SIZE / 4; \
2671 /* defines handling */
2672 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2676 s
= sym_push2(&define_stack
, v
, macro_type
, (long)str
);
2677 s
->next
= first_arg
;
2678 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2681 /* undefined a define symbol. Its name is just set to zero */
2682 static void define_undef(Sym
*s
)
2686 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2687 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2691 static inline Sym
*define_find(int v
)
2694 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2696 return table_ident
[v
]->sym_define
;
2699 /* free define stack until top reaches 'b' */
2700 static void free_defines(Sym
*b
)
2708 /* do not free args or predefined defines */
2710 tok_str_free((int *)top
->c
);
2712 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2713 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2721 static Sym
*label_find(int v
)
2724 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2726 return table_ident
[v
]->sym_label
;
2729 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2732 s
= sym_push2(ptop
, v
, 0, 0);
2734 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2735 if (ptop
== &global_label_stack
) {
2736 /* modify the top most local identifier, so that
2737 sym_identifier will point to 's' when popped */
2739 ps
= &(*ps
)->prev_tok
;
2746 /* pop labels until element last is reached. Look if any labels are
2747 undefined. Define symbols if '&&label' was used. */
2748 static void label_pop(Sym
**ptop
, Sym
*slast
)
2751 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2753 if (s
->r
== LABEL_DECLARED
) {
2754 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2755 } else if (s
->r
== LABEL_FORWARD
) {
2756 error("label '%s' used but not defined",
2757 get_tok_str(s
->v
, NULL
));
2760 /* define corresponding symbol. A size of
2762 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2766 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2772 /* eval an expression for #if/#elif */
2773 static int expr_preprocess(void)
2779 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2780 next(); /* do macro subst */
2781 if (tok
== TOK_DEFINED
) {
2786 c
= define_find(tok
) != 0;
2791 } else if (tok
>= TOK_IDENT
) {
2792 /* if undefined macro */
2796 tok_str_add_tok(&str
);
2798 tok_str_add(&str
, -1); /* simulate end of file */
2799 tok_str_add(&str
, 0);
2800 /* now evaluate C constant expression */
2801 macro_ptr
= str
.str
;
2805 tok_str_free(str
.str
);
2809 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2810 static void tok_print(int *str
)
2816 TOK_GET(t
, str
, cval
);
2819 printf(" %s", get_tok_str(t
, &cval
));
2825 /* parse after #define */
2826 static void parse_define(void)
2828 Sym
*s
, *first
, **ps
;
2829 int v
, t
, varg
, is_vaargs
, c
;
2834 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2835 /* XXX: should check if same macro (ANSI) */
2838 /* '(' must be just after macro definition for MACRO_FUNC */
2839 c
= file
->buf_ptr
[0];
2841 c
= handle_stray1(file
->buf_ptr
);
2846 while (tok
!= ')') {
2850 if (varg
== TOK_DOTS
) {
2851 varg
= TOK___VA_ARGS__
;
2853 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2857 if (varg
< TOK_IDENT
)
2858 error("badly punctuated parameter list");
2859 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2870 /* EOF testing necessary for '-D' handling */
2871 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2872 tok_str_add2(&str
, tok
, &tokc
);
2875 tok_str_add(&str
, 0);
2877 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2880 define_push(v
, t
, str
.str
, first
);
2883 static inline int hash_cached_include(int type
, const char *filename
)
2885 const unsigned char *s
;
2889 h
= TOK_HASH_FUNC(h
, type
);
2892 h
= TOK_HASH_FUNC(h
, *s
);
2895 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
2899 /* XXX: use a token or a hash table to accelerate matching ? */
2900 static CachedInclude
*search_cached_include(TCCState
*s1
,
2901 int type
, const char *filename
)
2905 h
= hash_cached_include(type
, filename
);
2906 i
= s1
->cached_includes_hash
[h
];
2910 e
= s1
->cached_includes
[i
- 1];
2911 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2918 static inline void add_cached_include(TCCState
*s1
, int type
,
2919 const char *filename
, int ifndef_macro
)
2924 if (search_cached_include(s1
, type
, filename
))
2927 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2929 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2933 strcpy(e
->filename
, filename
);
2934 e
->ifndef_macro
= ifndef_macro
;
2935 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2936 /* add in hash table */
2937 h
= hash_cached_include(type
, filename
);
2938 e
->hash_next
= s1
->cached_includes_hash
[h
];
2939 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
2942 static void pragma_parse(TCCState
*s1
)
2947 if (tok
== TOK_pack
) {
2950 #pragma pack(1) // set
2951 #pragma pack() // reset to default
2952 #pragma pack(push,1) // push & set
2953 #pragma pack(pop) // restore previous
2957 if (tok
== TOK_ASM_pop
) {
2959 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
2961 error("out of pack stack");
2963 s1
->pack_stack_ptr
--;
2967 if (tok
== TOK_ASM_push
) {
2969 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
2971 s1
->pack_stack_ptr
++;
2974 if (tok
!= TOK_CINT
) {
2976 error("invalid pack pragma");
2979 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
2983 *s1
->pack_stack_ptr
= val
;
2989 /* is_bof is true if first non space token at beginning of file */
2990 static void preprocess(int is_bof
)
2992 TCCState
*s1
= tcc_state
;
2993 int size
, i
, c
, n
, saved_parse_flags
;
3000 saved_parse_flags
= parse_flags
;
3001 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
3002 PARSE_FLAG_LINEFEED
;
3012 s
= define_find(tok
);
3013 /* undefine symbol by putting an invalid name */
3018 case TOK_INCLUDE_NEXT
:
3019 ch
= file
->buf_ptr
[0];
3020 /* XXX: incorrect if comments : use next_nomacro with a special mode */
3025 } else if (ch
== '\"') {
3030 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
3031 if ((q
- buf
) < sizeof(buf
) - 1)
3034 if (handle_stray_noerror() == 0)
3042 /* eat all spaces and comments after include */
3043 /* XXX: slightly incorrect */
3044 while (ch1
!= '\n' && ch1
!= CH_EOF
)
3048 /* computed #include : either we have only strings or
3049 we have anything enclosed in '<>' */
3052 if (tok
== TOK_STR
) {
3053 while (tok
!= TOK_LINEFEED
) {
3054 if (tok
!= TOK_STR
) {
3056 error("'#include' expects \"FILENAME\" or <FILENAME>");
3058 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
3064 while (tok
!= TOK_LINEFEED
) {
3065 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
3069 /* check syntax and remove '<>' */
3070 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
3071 goto include_syntax
;
3072 memmove(buf
, buf
+ 1, len
- 2);
3073 buf
[len
- 2] = '\0';
3078 e
= search_cached_include(s1
, c
, buf
);
3079 if (e
&& define_find(e
->ifndef_macro
)) {
3080 /* no need to parse the include because the 'ifndef macro'
3083 printf("%s: skipping %s\n", file
->filename
, buf
);
3086 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
3087 error("#include recursion too deep");
3088 /* push current file in stack */
3089 /* XXX: fix current line init */
3090 *s1
->include_stack_ptr
++ = file
;
3092 /* check absolute include path */
3093 if (IS_ABSPATH(buf
)) {
3094 f
= tcc_open(s1
, buf
);
3099 /* first search in current dir if "header.h" */
3100 size
= tcc_basename(file
->filename
) - file
->filename
;
3101 if (size
> sizeof(buf1
) - 1)
3102 size
= sizeof(buf1
) - 1;
3103 memcpy(buf1
, file
->filename
, size
);
3105 pstrcat(buf1
, sizeof(buf1
), buf
);
3106 f
= tcc_open(s1
, buf1
);
3108 if (tok
== TOK_INCLUDE_NEXT
)
3114 /* now search in all the include paths */
3115 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
3116 for(i
= 0; i
< n
; i
++) {
3118 if (i
< s1
->nb_include_paths
)
3119 path
= s1
->include_paths
[i
];
3121 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
3122 pstrcpy(buf1
, sizeof(buf1
), path
);
3123 pstrcat(buf1
, sizeof(buf1
), "/");
3124 pstrcat(buf1
, sizeof(buf1
), buf
);
3125 f
= tcc_open(s1
, buf1
);
3127 if (tok
== TOK_INCLUDE_NEXT
)
3133 --s1
->include_stack_ptr
;
3134 error("include file '%s' not found", buf
);
3138 printf("%s: including %s\n", file
->filename
, buf1
);
3141 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
3143 /* add include file debug info */
3145 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
3147 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
3148 ch
= file
->buf_ptr
[0];
3156 c
= expr_preprocess();
3162 if (tok
< TOK_IDENT
)
3163 error("invalid argument for '#if%sdef'", c
? "n" : "");
3167 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
3169 file
->ifndef_macro
= tok
;
3172 c
= (define_find(tok
) != 0) ^ c
;
3174 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
3175 error("memory full");
3176 *s1
->ifdef_stack_ptr
++ = c
;
3179 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
3180 error("#else without matching #if");
3181 if (s1
->ifdef_stack_ptr
[-1] & 2)
3182 error("#else after #else");
3183 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
3186 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
3187 error("#elif without matching #if");
3188 c
= s1
->ifdef_stack_ptr
[-1];
3190 error("#elif after #else");
3191 /* last #if/#elif expression was true: we skip */
3194 c
= expr_preprocess();
3195 s1
->ifdef_stack_ptr
[-1] = c
;
3205 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
3206 error("#endif without matching #if");
3207 s1
->ifdef_stack_ptr
--;
3208 /* '#ifndef macro' was at the start of file. Now we check if
3209 an '#endif' is exactly at the end of file */
3210 if (file
->ifndef_macro
&&
3211 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
3212 file
->ifndef_macro_saved
= file
->ifndef_macro
;
3213 /* need to set to zero to avoid false matches if another
3214 #ifndef at middle of file */
3215 file
->ifndef_macro
= 0;
3216 while (tok
!= TOK_LINEFEED
)
3218 tok_flags
|= TOK_FLAG_ENDIF
;
3224 if (tok
!= TOK_CINT
)
3226 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
3228 if (tok
!= TOK_LINEFEED
) {
3231 pstrcpy(file
->filename
, sizeof(file
->filename
),
3232 (char *)tokc
.cstr
->data
);
3238 ch
= file
->buf_ptr
[0];
3241 while (ch
!= '\n' && ch
!= CH_EOF
) {
3242 if ((q
- buf
) < sizeof(buf
) - 1)
3245 if (handle_stray_noerror() == 0)
3252 error("#error %s", buf
);
3254 warning("#warning %s", buf
);
3260 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
3261 /* '!' is ignored to allow C scripts. numbers are ignored
3262 to emulate cpp behaviour */
3264 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
3265 warning("Ignoring unknown preprocessing directive #%s", get_tok_str(tok
, &tokc
));
3269 /* ignore other preprocess commands or #! for C scripts */
3270 while (tok
!= TOK_LINEFEED
)
3273 parse_flags
= saved_parse_flags
;
3276 /* evaluate escape codes in a string. */
3277 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
3292 case '0': case '1': case '2': case '3':
3293 case '4': case '5': case '6': case '7':
3294 /* at most three octal digits */
3299 n
= n
* 8 + c
- '0';
3303 n
= n
* 8 + c
- '0';
3308 goto add_char_nonext
;
3316 if (c
>= 'a' && c
<= 'f')
3318 else if (c
>= 'A' && c
<= 'F')
3328 goto add_char_nonext
;
3352 goto invalid_escape
;
3362 if (c
>= '!' && c
<= '~')
3363 warning("unknown escape sequence: \'\\%c\'", c
);
3365 warning("unknown escape sequence: \'\\x%x\'", c
);
3372 cstr_ccat(outstr
, c
);
3374 cstr_wccat(outstr
, c
);
3376 /* add a trailing '\0' */
3378 cstr_ccat(outstr
, '\0');
3380 cstr_wccat(outstr
, '\0');
3383 /* we use 64 bit numbers */
3386 /* bn = (bn << shift) | or_val */
3387 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
3391 for(i
=0;i
<BN_SIZE
;i
++) {
3393 bn
[i
] = (v
<< shift
) | or_val
;
3394 or_val
= v
>> (32 - shift
);
3398 void bn_zero(unsigned int *bn
)
3401 for(i
=0;i
<BN_SIZE
;i
++) {
3406 /* parse number in null terminated string 'p' and return it in the
3408 void parse_number(const char *p
)
3410 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
3412 unsigned int bn
[BN_SIZE
];
3423 goto float_frac_parse
;
3424 } else if (t
== '0') {
3425 if (ch
== 'x' || ch
== 'X') {
3429 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
3435 /* parse all digits. cannot check octal numbers at this stage
3436 because of floating point constants */
3438 if (ch
>= 'a' && ch
<= 'f')
3440 else if (ch
>= 'A' && ch
<= 'F')
3448 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
3450 error("number too long");
3456 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
3457 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
3459 /* NOTE: strtox should support that for hexa numbers, but
3460 non ISOC99 libcs do not support it, so we prefer to do
3462 /* hexadecimal or binary floats */
3463 /* XXX: handle overflows */
3475 } else if (t
>= 'a') {
3477 } else if (t
>= 'A') {
3482 bn_lshift(bn
, shift
, t
);
3489 if (t
>= 'a' && t
<= 'f') {
3491 } else if (t
>= 'A' && t
<= 'F') {
3493 } else if (t
>= '0' && t
<= '9') {
3499 error("invalid digit");
3500 bn_lshift(bn
, shift
, t
);
3505 if (ch
!= 'p' && ch
!= 'P')
3512 } else if (ch
== '-') {
3516 if (ch
< '0' || ch
> '9')
3517 expect("exponent digits");
3518 while (ch
>= '0' && ch
<= '9') {
3519 exp_val
= exp_val
* 10 + ch
- '0';
3522 exp_val
= exp_val
* s
;
3524 /* now we can generate the number */
3525 /* XXX: should patch directly float number */
3526 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3527 d
= ldexp(d
, exp_val
- frac_bits
);
3532 /* float : should handle overflow */
3534 } else if (t
== 'L') {
3537 /* XXX: not large enough */
3538 tokc
.ld
= (long double)d
;
3544 /* decimal floats */
3546 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3551 while (ch
>= '0' && ch
<= '9') {
3552 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3558 if (ch
== 'e' || ch
== 'E') {
3559 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3563 if (ch
== '-' || ch
== '+') {
3564 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3569 if (ch
< '0' || ch
> '9')
3570 expect("exponent digits");
3571 while (ch
>= '0' && ch
<= '9') {
3572 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3584 tokc
.f
= strtof(token_buf
, NULL
);
3585 } else if (t
== 'L') {
3588 tokc
.ld
= strtold(token_buf
, NULL
);
3591 tokc
.d
= strtod(token_buf
, NULL
);
3595 unsigned long long n
, n1
;
3598 /* integer number */
3601 if (b
== 10 && *q
== '0') {
3608 /* no need for checks except for base 10 / 8 errors */
3611 } else if (t
>= 'a') {
3613 } else if (t
>= 'A') {
3618 error("invalid digit");
3622 /* detect overflow */
3623 /* XXX: this test is not reliable */
3625 error("integer constant overflow");
3628 /* XXX: not exactly ANSI compliant */
3629 if ((n
& 0xffffffff00000000LL
) != 0) {
3634 } else if (n
> 0x7fffffff) {
3645 error("three 'l's in integer constant");
3648 if (tok
== TOK_CINT
)
3650 else if (tok
== TOK_CUINT
)
3654 } else if (t
== 'U') {
3656 error("two 'u's in integer constant");
3658 if (tok
== TOK_CINT
)
3660 else if (tok
== TOK_CLLONG
)
3667 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3673 error("invalid number\n");
3677 #define PARSE2(c1, tok1, c2, tok2) \
3688 /* return next token without macro substitution */
3689 static inline void next_nomacro1(void)
3696 cstr_reset(&tok_spaces
);
3706 cstr_ccat(&tok_spaces
, c
);
3711 /* first look if it is in fact an end of buffer */
3712 if (p
>= file
->buf_end
) {
3716 if (p
>= file
->buf_end
)
3729 TCCState
*s1
= tcc_state
;
3730 if ((parse_flags
& PARSE_FLAG_LINEFEED
)
3731 && !(tok_flags
& TOK_FLAG_EOF
)) {
3732 tok_flags
|= TOK_FLAG_EOF
;
3734 goto keep_tok_flags
;
3735 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3736 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3737 /* no include left : end of file. */
3740 tok_flags
&= ~TOK_FLAG_EOF
;
3741 /* pop include file */
3743 /* test if previous '#endif' was after a #ifdef at
3745 if (tok_flags
& TOK_FLAG_ENDIF
) {
3747 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3749 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3750 file
->ifndef_macro_saved
);
3753 /* add end of include file debug info */
3755 put_stabd(N_EINCL
, 0, 0);
3757 /* pop include stack */
3759 s1
->include_stack_ptr
--;
3760 file
= *s1
->include_stack_ptr
;
3769 tok_flags
|= TOK_FLAG_BOL
;
3771 if (0 == (parse_flags
& PARSE_FLAG_LINEFEED
))
3774 goto keep_tok_flags
;
3779 if ((tok_flags
& TOK_FLAG_BOL
) &&
3780 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3782 preprocess(tok_flags
& TOK_FLAG_BOF
);
3788 tok
= TOK_TWOSHARPS
;
3790 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
3791 p
= parse_line_comment(p
- 1);
3800 case 'a': case 'b': case 'c': case 'd':
3801 case 'e': case 'f': case 'g': case 'h':
3802 case 'i': case 'j': case 'k': case 'l':
3803 case 'm': case 'n': case 'o': case 'p':
3804 case 'q': case 'r': case 's': case 't':
3805 case 'u': case 'v': case 'w': case 'x':
3807 case 'A': case 'B': case 'C': case 'D':
3808 case 'E': case 'F': case 'G': case 'H':
3809 case 'I': case 'J': case 'K':
3810 case 'M': case 'N': case 'O': case 'P':
3811 case 'Q': case 'R': case 'S': case 'T':
3812 case 'U': case 'V': case 'W': case 'X':
3818 h
= TOK_HASH_FUNC(h
, c
);
3822 if (!isidnum_table
[c
-CH_EOF
])
3824 h
= TOK_HASH_FUNC(h
, c
);
3831 /* fast case : no stray found, so we have the full token
3832 and we have already hashed it */
3834 h
&= (TOK_HASH_SIZE
- 1);
3835 pts
= &hash_ident
[h
];
3840 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3842 pts
= &(ts
->hash_next
);
3844 ts
= tok_alloc_new(pts
, p1
, len
);
3848 cstr_reset(&tokcstr
);
3851 cstr_ccat(&tokcstr
, *p1
);
3857 while (isidnum_table
[c
-CH_EOF
]) {
3858 cstr_ccat(&tokcstr
, c
);
3861 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3867 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3869 goto parse_ident_fast
;
3872 if (c
== '\'' || c
== '\"') {
3876 cstr_reset(&tokcstr
);
3877 cstr_ccat(&tokcstr
, 'L');
3878 goto parse_ident_slow
;
3882 case '0': case '1': case '2': case '3':
3883 case '4': case '5': case '6': case '7':
3886 cstr_reset(&tokcstr
);
3887 /* after the first digit, accept digits, alpha, '.' or sign if
3888 prefixed by 'eEpP' */
3892 cstr_ccat(&tokcstr
, c
);
3894 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3895 ((c
== '+' || c
== '-') &&
3896 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3899 /* We add a trailing '\0' to ease parsing */
3900 cstr_ccat(&tokcstr
, '\0');
3901 tokc
.cstr
= &tokcstr
;
3905 /* special dot handling because it can also start a number */
3908 cstr_reset(&tokcstr
);
3909 cstr_ccat(&tokcstr
, '.');
3911 } else if (c
== '.') {
3931 /* parse the string */
3933 p
= parse_pp_string(p
, sep
, &str
);
3934 cstr_ccat(&str
, '\0');
3936 /* eval the escape (should be done as TOK_PPNUM) */
3937 cstr_reset(&tokcstr
);
3938 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3943 /* XXX: make it portable */
3947 char_size
= sizeof(nwchar_t
);
3948 if (tokcstr
.size
<= char_size
)
3949 error("empty character constant");
3950 if (tokcstr
.size
> 2 * char_size
)
3951 warning("multi-character character constant");
3953 tokc
.i
= *(int8_t *)tokcstr
.data
;
3956 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
3960 tokc
.cstr
= &tokcstr
;
3974 } else if (c
== '<') {
3992 } else if (c
== '>') {
4010 } else if (c
== '=') {
4023 } else if (c
== '=') {
4036 } else if (c
== '=') {
4049 } else if (c
== '=') {
4052 } else if (c
== '>') {
4060 PARSE2('!', '!', '=', TOK_NE
)
4061 PARSE2('=', '=', '=', TOK_EQ
)
4062 PARSE2('*', '*', '=', TOK_A_MUL
)
4063 PARSE2('%', '%', '=', TOK_A_MOD
)
4064 PARSE2('^', '^', '=', TOK_A_XOR
)
4066 /* comments or operator */
4070 p
= parse_comment(p
);
4072 } else if (c
== '/') {
4073 p
= parse_line_comment(p
);
4075 } else if (c
== '=') {
4095 case '$': /* only used in assembler */
4096 case '@': /* dito */
4101 error("unrecognized character \\x%02x", c
);
4107 #if defined(PARSE_DEBUG)
4108 printf("token = %s\n", get_tok_str(tok
, &tokc
));
4112 /* return next token without macro substitution. Can read input from
4114 static void next_nomacro(void)
4120 TOK_GET(tok
, macro_ptr
, tokc
);
4121 if (tok
== TOK_LINENUM
) {
4122 file
->line_num
= tokc
.i
;
4131 /* substitute args in macro_str and return allocated string */
4132 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
4134 int *st
, last_tok
, t
, notfirst
;
4143 TOK_GET(t
, macro_str
, cval
);
4148 TOK_GET(t
, macro_str
, cval
);
4151 s
= sym_find2(args
, t
);
4158 cstr_ccat(&cstr
, ' ');
4159 TOK_GET(t
, st
, cval
);
4160 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
4165 cstr_ccat(&cstr
, '\0');
4167 printf("stringize: %s\n", (char *)cstr
.data
);
4171 tok_str_add2(&str
, TOK_STR
, &cval
);
4174 tok_str_add2(&str
, t
, &cval
);
4176 } else if (t
>= TOK_IDENT
) {
4177 s
= sym_find2(args
, t
);
4180 /* if '##' is present before or after, no arg substitution */
4181 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
4182 /* special case for var arg macros : ## eats the
4183 ',' if empty VA_ARGS variable. */
4184 /* XXX: test of the ',' is not 100%
4185 reliable. should fix it to avoid security
4187 if (gnu_ext
&& s
->type
.t
&&
4188 last_tok
== TOK_TWOSHARPS
&&
4189 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
4191 /* suppress ',' '##' */
4194 /* suppress '##' and add variable */
4202 TOK_GET(t1
, st
, cval
);
4205 tok_str_add2(&str
, t1
, &cval
);
4209 /* NOTE: the stream cannot be read when macro
4210 substituing an argument */
4211 macro_subst(&str
, nested_list
, st
, NULL
);
4214 tok_str_add(&str
, t
);
4217 tok_str_add2(&str
, t
, &cval
);
4221 tok_str_add(&str
, 0);
4225 static char const ab_month_name
[12][4] =
4227 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
4228 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
4231 /* do macro substitution of current token with macro 's' and add
4232 result to (tok_str,tok_len). 'nested_list' is the list of all
4233 macros we got inside to avoid recursing. Return non zero if no
4234 substitution needs to be done */
4235 static int macro_subst_tok(TokenString
*tok_str
,
4236 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
4238 Sym
*args
, *sa
, *sa1
;
4239 int mstr_allocated
, parlevel
, *mstr
, t
, t1
;
4246 /* if symbol is a macro, prepare substitution */
4247 /* special macros */
4248 if (tok
== TOK___LINE__
) {
4249 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
4253 } else if (tok
== TOK___FILE__
) {
4254 cstrval
= file
->filename
;
4256 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
4261 tm
= localtime(&ti
);
4262 if (tok
== TOK___DATE__
) {
4263 snprintf(buf
, sizeof(buf
), "%s %2d %d",
4264 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
4266 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
4267 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
4274 cstr_cat(&cstr
, cstrval
);
4275 cstr_ccat(&cstr
, '\0');
4277 tok_str_add2(tok_str
, t1
, &cval
);
4282 if (s
->type
.t
== MACRO_FUNC
) {
4283 /* NOTE: we do not use next_nomacro to avoid eating the
4284 next token. XXX: find better solution */
4288 if (t
== 0 && can_read_stream
) {
4289 /* end of macro stream: we must look at the token
4290 after in the file */
4291 struct macro_level
*ml
= *can_read_stream
;
4297 *can_read_stream
= ml
-> prev
;
4302 /* XXX: incorrect with comments */
4303 ch
= file
->buf_ptr
[0];
4304 while (is_space(ch
) || ch
== '\n')
4308 if (t
!= '(') /* no macro subst */
4311 /* argument macro */
4316 /* NOTE: empty args are allowed, except if no args */
4318 /* handle '()' case */
4319 if (!args
&& !sa
&& tok
== ')')
4322 error("macro '%s' used with too many args",
4323 get_tok_str(s
->v
, 0));
4326 /* NOTE: non zero sa->t indicates VA_ARGS */
4327 while ((parlevel
> 0 ||
4329 (tok
!= ',' || sa
->type
.t
))) &&
4333 else if (tok
== ')')
4335 if (tok
!= TOK_LINEFEED
)
4336 tok_str_add2(&str
, tok
, &tokc
);
4339 tok_str_add(&str
, 0);
4340 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (long)str
.str
);
4343 /* special case for gcc var args: add an empty
4344 var arg argument if it is omitted */
4345 if (sa
&& sa
->type
.t
&& gnu_ext
)
4355 error("macro '%s' used with too few args",
4356 get_tok_str(s
->v
, 0));
4359 /* now subst each arg */
4360 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
4365 tok_str_free((int *)sa
->c
);
4371 sym_push2(nested_list
, s
->v
, 0, 0);
4372 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
4373 /* pop nested defined symbol */
4375 *nested_list
= sa1
->prev
;
4383 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4384 return the resulting string (which must be freed). */
4385 static inline int *macro_twosharps(const int *macro_str
)
4388 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
4390 const char *p1
, *p2
;
4392 TokenString macro_str1
;
4395 start_macro_ptr
= macro_str
;
4396 /* we search the first '##' */
4398 macro_ptr1
= macro_str
;
4399 TOK_GET(t
, macro_str
, cval
);
4400 /* nothing more to do if end of string */
4403 if (*macro_str
== TOK_TWOSHARPS
)
4407 /* we saw '##', so we need more processing to handle it */
4409 tok_str_new(¯o_str1
);
4413 /* add all tokens seen so far */
4414 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
4415 TOK_GET(t
, ptr
, cval
);
4416 tok_str_add2(¯o_str1
, t
, &cval
);
4418 saved_macro_ptr
= macro_ptr
;
4419 /* XXX: get rid of the use of macro_ptr here */
4420 macro_ptr
= (int *)macro_str
;
4422 while (*macro_ptr
== TOK_TWOSHARPS
) {
4424 macro_ptr1
= macro_ptr
;
4427 TOK_GET(t
, macro_ptr
, cval
);
4428 /* We concatenate the two tokens if we have an
4429 identifier or a preprocessing number */
4431 p1
= get_tok_str(tok
, &tokc
);
4432 cstr_cat(&cstr
, p1
);
4433 p2
= get_tok_str(t
, &cval
);
4434 cstr_cat(&cstr
, p2
);
4435 cstr_ccat(&cstr
, '\0');
4437 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
4438 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
4439 if (tok
== TOK_PPNUM
) {
4440 /* if number, then create a number token */
4441 /* NOTE: no need to allocate because
4442 tok_str_add2() does it */
4443 cstr_reset(&tokcstr
);
4446 tokc
.cstr
= &tokcstr
;
4448 /* if identifier, we must do a test to
4449 validate we have a correct identifier */
4450 if (t
== TOK_PPNUM
) {
4460 if (!isnum(c
) && !isid(c
))
4464 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
4465 tok
= ts
->tok
; /* modify current token */
4468 const char *str
= cstr
.data
;
4469 const unsigned char *q
;
4471 /* we look for a valid token */
4472 /* XXX: do more extensive checks */
4473 if (!strcmp(str
, ">>=")) {
4475 } else if (!strcmp(str
, "<<=")) {
4477 } else if (strlen(str
) == 2) {
4478 /* search in two bytes table */
4483 if (q
[0] == str
[0] && q
[1] == str
[1])
4490 /* NOTE: because get_tok_str use a static buffer,
4493 p1
= get_tok_str(tok
, &tokc
);
4494 cstr_cat(&cstr
, p1
);
4495 cstr_ccat(&cstr
, '\0');
4496 p2
= get_tok_str(t
, &cval
);
4497 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
4498 /* cannot merge tokens: just add them separately */
4499 tok_str_add2(¯o_str1
, tok
, &tokc
);
4500 /* XXX: free associated memory ? */
4507 tok_str_add2(¯o_str1
, tok
, &tokc
);
4512 macro_ptr
= (int *)saved_macro_ptr
;
4514 tok_str_add(¯o_str1
, 0);
4515 return macro_str1
.str
;
4519 /* do macro substitution of macro_str and add result to
4520 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4521 inside to avoid recursing. */
4522 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
4523 const int *macro_str
, struct macro_level
** can_read_stream
)
4530 struct macro_level ml
;
4532 /* first scan for '##' operator handling */
4534 macro_str1
= macro_twosharps(ptr
);
4538 /* NOTE: ptr == NULL can only happen if tokens are read from
4539 file stream due to a macro function call */
4542 TOK_GET(t
, ptr
, cval
);
4547 /* if nested substitution, do nothing */
4548 if (sym_find2(*nested_list
, t
))
4551 if (can_read_stream
)
4552 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
4553 macro_ptr
= (int *)ptr
;
4555 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
4556 ptr
= (int *)macro_ptr
;
4558 if (can_read_stream
&& *can_read_stream
== &ml
)
4559 *can_read_stream
= ml
.prev
;
4564 tok_str_add2(tok_str
, t
, &cval
);
4568 tok_str_free(macro_str1
);
4571 /* return next token with macro substitution */
4572 static void next(void)
4574 Sym
*nested_list
, *s
;
4576 struct macro_level
*ml
;
4581 /* if not reading from macro substituted string, then try
4582 to substitute macros */
4583 if (tok
>= TOK_IDENT
&&
4584 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4585 s
= define_find(tok
);
4587 /* we have a macro: we try to substitute */
4591 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
4592 /* substitution done, NOTE: maybe empty */
4593 tok_str_add(&str
, 0);
4594 macro_ptr
= str
.str
;
4595 macro_ptr_allocated
= str
.str
;
4602 /* end of macro or end of unget buffer */
4603 if (unget_buffer_enabled
) {
4604 macro_ptr
= unget_saved_macro_ptr
;
4605 unget_buffer_enabled
= 0;
4607 /* end of macro string: free it */
4608 tok_str_free(macro_ptr_allocated
);
4615 /* convert preprocessor tokens into C tokens */
4616 if (tok
== TOK_PPNUM
&&
4617 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4618 parse_number((char *)tokc
.cstr
->data
);
4622 /* push back current token and set current token to 'last_tok'. Only
4623 identifier case handled for labels. */
4624 static inline void unget_tok(int last_tok
)
4628 unget_saved_macro_ptr
= macro_ptr
;
4629 unget_buffer_enabled
= 1;
4630 q
= unget_saved_buffer
;
4633 n
= tok_ext_size(tok
) - 1;
4636 *q
= 0; /* end of token string */
4641 void swap(int *p
, int *q
)
4649 void vsetc(CType
*type
, int r
, CValue
*vc
)
4653 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4654 error("memory full");
4655 /* cannot let cpu flags if other instruction are generated. Also
4656 avoid leaving VT_JMP anywhere except on the top of the stack
4657 because it would complicate the code generator. */
4658 if (vtop
>= vstack
) {
4659 v
= vtop
->r
& VT_VALMASK
;
4660 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4666 vtop
->r2
= VT_CONST
;
4670 /* push integer constant */
4675 vsetc(&int_type
, VT_CONST
, &cval
);
4678 /* push long long constant */
4679 void vpushll(long long v
)
4685 vsetc(&ctype
, VT_CONST
, &cval
);
4688 /* Return a static symbol pointing to a section */
4689 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4690 unsigned long offset
, unsigned long size
)
4696 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4697 sym
->type
.ref
= type
->ref
;
4698 sym
->r
= VT_CONST
| VT_SYM
;
4699 put_extern_sym(sym
, sec
, offset
, size
);
4703 /* push a reference to a section offset by adding a dummy symbol */
4704 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4709 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4710 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4713 /* define a new external reference to a symbol 'v' of type 'u' */
4714 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4720 /* push forward reference */
4721 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4722 s
->type
.ref
= type
->ref
;
4723 s
->r
= r
| VT_CONST
| VT_SYM
;
4728 /* define a new external reference to a symbol 'v' of type 'u' */
4729 static Sym
*external_sym(int v
, CType
*type
, int r
)
4735 /* push forward reference */
4736 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4737 s
->type
.t
|= VT_EXTERN
;
4739 if (!is_compatible_types(&s
->type
, type
))
4740 error("incompatible types for redefinition of '%s'",
4741 get_tok_str(v
, NULL
));
4746 /* push a reference to global symbol v */
4747 static void vpush_global_sym(CType
*type
, int v
)
4752 sym
= external_global_sym(v
, type
, 0);
4754 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4758 void vset(CType
*type
, int r
, int v
)
4763 vsetc(type
, r
, &cval
);
4766 void vseti(int r
, int v
)
4782 void vpushv(SValue
*v
)
4784 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4785 error("memory full");
4795 /* save r to the memory stack, and mark it as being free */
4796 void save_reg(int r
)
4798 int l
, saved
, size
, align
;
4802 /* modify all stack values */
4805 for(p
=vstack
;p
<=vtop
;p
++) {
4806 if ((p
->r
& VT_VALMASK
) == r
||
4807 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& (p
->r2
& VT_VALMASK
) == r
)) {
4808 /* must save value on stack if not already done */
4810 /* NOTE: must reload 'r' because r might be equal to r2 */
4811 r
= p
->r
& VT_VALMASK
;
4812 /* store register in the stack */
4814 if ((p
->r
& VT_LVAL
) ||
4815 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4816 #ifdef TCC_TARGET_X86_64
4817 type
= &char_pointer_type
;
4821 size
= type_size(type
, &align
);
4822 loc
= (loc
- size
) & -align
;
4823 sv
.type
.t
= type
->t
;
4824 sv
.r
= VT_LOCAL
| VT_LVAL
;
4827 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
4828 /* x86 specific: need to pop fp register ST0 if saved */
4829 if (r
== TREG_ST0
) {
4830 o(0xd9dd); /* fstp %st(1) */
4833 #ifndef TCC_TARGET_X86_64
4834 /* special long long case */
4835 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4843 /* mark that stack entry as being saved on the stack */
4844 if (p
->r
& VT_LVAL
) {
4845 /* also clear the bounded flag because the
4846 relocation address of the function was stored in
4848 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4850 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4858 /* find a register of class 'rc2' with at most one reference on stack.
4859 * If none, call get_reg(rc) */
4860 int get_reg_ex(int rc
, int rc2
)
4865 for(r
=0;r
<NB_REGS
;r
++) {
4866 if (reg_classes
[r
] & rc2
) {
4869 for(p
= vstack
; p
<= vtop
; p
++) {
4870 if ((p
->r
& VT_VALMASK
) == r
||
4871 (p
->r2
& VT_VALMASK
) == r
)
4881 /* find a free register of class 'rc'. If none, save one register */
4887 /* find a free register */
4888 for(r
=0;r
<NB_REGS
;r
++) {
4889 if (reg_classes
[r
] & rc
) {
4890 for(p
=vstack
;p
<=vtop
;p
++) {
4891 if ((p
->r
& VT_VALMASK
) == r
||
4892 (p
->r2
& VT_VALMASK
) == r
)
4900 /* no register left : free the first one on the stack (VERY
4901 IMPORTANT to start from the bottom to ensure that we don't
4902 spill registers used in gen_opi()) */
4903 for(p
=vstack
;p
<=vtop
;p
++) {
4904 r
= p
->r
& VT_VALMASK
;
4905 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4907 /* also look at second register (if long long) */
4908 r
= p
->r2
& VT_VALMASK
;
4909 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4915 /* Should never comes here */
4919 /* save registers up to (vtop - n) stack entry */
4920 void save_regs(int n
)
4925 for(p
= vstack
;p
<= p1
; p
++) {
4926 r
= p
->r
& VT_VALMASK
;
4933 /* move register 's' to 'r', and flush previous value of r to memory
4935 void move_reg(int r
, int s
)
4948 /* get address of vtop (vtop MUST BE an lvalue) */
4951 vtop
->r
&= ~VT_LVAL
;
4952 /* tricky: if saved lvalue, then we can go back to lvalue */
4953 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4954 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4957 #ifdef CONFIG_TCC_BCHECK
4958 /* generate lvalue bound code */
4964 vtop
->r
&= ~VT_MUSTBOUND
;
4965 /* if lvalue, then use checking code before dereferencing */
4966 if (vtop
->r
& VT_LVAL
) {
4967 /* if not VT_BOUNDED value, then make one */
4968 if (!(vtop
->r
& VT_BOUNDED
)) {
4969 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4970 /* must save type because we must set it to int to get pointer */
4972 vtop
->type
.t
= VT_INT
;
4975 gen_bounded_ptr_add();
4976 vtop
->r
|= lval_type
;
4979 /* then check for dereferencing */
4980 gen_bounded_ptr_deref();
4985 /* store vtop a register belonging to class 'rc'. lvalues are
4986 converted to values. Cannot be used if cannot be converted to
4987 register value (such as structures). */
4990 int r
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4992 /* NOTE: get_reg can modify vstack[] */
4993 if (vtop
->type
.t
& VT_BITFIELD
) {
4996 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4997 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4998 /* remove bit field info to avoid loops */
4999 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
5000 /* cast to int to propagate signedness in following ops */
5001 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
5006 if((vtop
->type
.t
& VT_UNSIGNED
) ||
5007 (vtop
->type
.t
& VT_BTYPE
) == VT_BOOL
)
5008 type
.t
|= VT_UNSIGNED
;
5010 /* generate shifts */
5011 vpushi(bits
- (bit_pos
+ bit_size
));
5013 vpushi(bits
- bit_size
);
5014 /* NOTE: transformed to SHR if unsigned */
5018 if (is_float(vtop
->type
.t
) &&
5019 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
5022 unsigned long offset
;
5023 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5027 /* XXX: unify with initializers handling ? */
5028 /* CPUs usually cannot use float constants, so we store them
5029 generically in data segment */
5030 size
= type_size(&vtop
->type
, &align
);
5031 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
5032 data_section
->data_offset
= offset
;
5033 /* XXX: not portable yet */
5034 #if defined(__i386__) || defined(__x86_64__)
5035 /* Zero pad x87 tenbyte long doubles */
5036 if (size
== LDOUBLE_SIZE
)
5037 vtop
->c
.tab
[2] &= 0xffff;
5039 ptr
= section_ptr_add(data_section
, size
);
5041 #if defined(TCC_TARGET_ARM) && !defined(TCC_ARM_VFP)
5045 ptr
[i
] = vtop
->c
.tab
[size
-1-i
];
5049 ptr
[i
] = vtop
->c
.tab
[i
];
5050 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
5051 vtop
->r
|= VT_LVAL
| VT_SYM
;
5055 #ifdef CONFIG_TCC_BCHECK
5056 if (vtop
->r
& VT_MUSTBOUND
)
5060 r
= vtop
->r
& VT_VALMASK
;
5064 /* need to reload if:
5066 - lvalue (need to dereference pointer)
5067 - already a register, but not in the right class */
5068 if (r
>= VT_CONST
||
5069 (vtop
->r
& VT_LVAL
) ||
5070 !(reg_classes
[r
] & rc
) ||
5071 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
5072 !(reg_classes
[vtop
->r2
] & rc2
))) {
5074 #ifndef TCC_TARGET_X86_64
5075 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
5077 unsigned long long ll
;
5078 /* two register type load : expand to two words
5080 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
5083 vtop
->c
.ui
= ll
; /* first word */
5085 vtop
->r
= r
; /* save register value */
5086 vpushi(ll
>> 32); /* second word */
5087 } else if (r
>= VT_CONST
|| /* XXX: test to VT_CONST incorrect ? */
5088 (vtop
->r
& VT_LVAL
)) {
5089 /* We do not want to modifier the long long
5090 pointer here, so the safest (and less
5091 efficient) is to save all the other registers
5092 in the stack. XXX: totally inefficient. */
5094 /* load from memory */
5097 vtop
[-1].r
= r
; /* save register value */
5098 /* increment pointer to get second word */
5099 vtop
->type
.t
= VT_INT
;
5105 /* move registers */
5108 vtop
[-1].r
= r
; /* save register value */
5109 vtop
->r
= vtop
[-1].r2
;
5111 /* allocate second register */
5115 /* write second register */
5119 if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
5121 /* lvalue of scalar type : need to use lvalue type
5122 because of possible cast */
5125 /* compute memory access type */
5126 if (vtop
->r
& VT_LVAL_BYTE
)
5128 else if (vtop
->r
& VT_LVAL_SHORT
)
5130 if (vtop
->r
& VT_LVAL_UNSIGNED
)
5134 /* restore wanted type */
5137 /* one register type load */
5142 #ifdef TCC_TARGET_C67
5143 /* uses register pairs for doubles */
5144 if ((vtop
->type
.t
& VT_BTYPE
) == VT_DOUBLE
)
5151 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
5152 void gv2(int rc1
, int rc2
)
5156 /* generate more generic register first. But VT_JMP or VT_CMP
5157 values must be generated first in all cases to avoid possible
5159 v
= vtop
[0].r
& VT_VALMASK
;
5160 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
5165 /* test if reload is needed for first register */
5166 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
5176 /* test if reload is needed for first register */
5177 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
5183 /* expand long long on stack in two int registers */
5188 u
= vtop
->type
.t
& VT_UNSIGNED
;
5191 vtop
[0].r
= vtop
[-1].r2
;
5192 vtop
[0].r2
= VT_CONST
;
5193 vtop
[-1].r2
= VT_CONST
;
5194 vtop
[0].type
.t
= VT_INT
| u
;
5195 vtop
[-1].type
.t
= VT_INT
| u
;
5198 #ifdef TCC_TARGET_ARM
5199 /* expand long long on stack */
5200 void lexpand_nr(void)
5204 u
= vtop
->type
.t
& VT_UNSIGNED
;
5206 vtop
->r2
= VT_CONST
;
5207 vtop
->type
.t
= VT_INT
| u
;
5208 v
=vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
);
5209 if (v
== VT_CONST
) {
5210 vtop
[-1].c
.ui
= vtop
->c
.ull
;
5211 vtop
->c
.ui
= vtop
->c
.ull
>> 32;
5213 } else if (v
== (VT_LVAL
|VT_CONST
) || v
== (VT_LVAL
|VT_LOCAL
)) {
5215 vtop
->r
= vtop
[-1].r
;
5216 } else if (v
> VT_CONST
) {
5220 vtop
->r
= vtop
[-1].r2
;
5221 vtop
[-1].r2
= VT_CONST
;
5222 vtop
[-1].type
.t
= VT_INT
| u
;
5226 /* build a long long from two ints */
5229 gv2(RC_INT
, RC_INT
);
5230 vtop
[-1].r2
= vtop
[0].r
;
5231 vtop
[-1].type
.t
= t
;
5235 /* rotate n first stack elements to the bottom
5236 I1 ... In -> I2 ... In I1 [top is right]
5244 for(i
=-n
+1;i
!=0;i
++)
5245 vtop
[i
] = vtop
[i
+1];
5249 /* rotate n first stack elements to the top
5250 I1 ... In -> In I1 ... I(n-1) [top is right]
5258 for(i
= 0;i
< n
- 1; i
++)
5259 vtop
[-i
] = vtop
[-i
- 1];
5263 #ifdef TCC_TARGET_ARM
5264 /* like vrott but in other direction
5265 In ... I1 -> I(n-1) ... I1 In [top is right]
5273 for(i
= n
- 1; i
> 0; i
--)
5274 vtop
[-i
] = vtop
[-i
+ 1];
5279 /* pop stack value */
5283 v
= vtop
->r
& VT_VALMASK
;
5284 #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
5285 /* for x86, we need to pop the FP stack */
5286 if (v
== TREG_ST0
&& !nocode_wanted
) {
5287 o(0xd9dd); /* fstp %st(1) */
5290 if (v
== VT_JMP
|| v
== VT_JMPI
) {
5291 /* need to put correct jump if && or || without test */
5297 /* convert stack entry to register and duplicate its value in another
5305 if ((t
& VT_BTYPE
) == VT_LLONG
) {
5312 /* stack: H L L1 H1 */
5320 /* duplicate value */
5325 #ifdef TCC_TARGET_X86_64
5326 if ((t
& VT_BTYPE
) == VT_LDOUBLE
) {
5336 load(r1
, &sv
); /* move r to r1 */
5338 /* duplicates value */
5343 #ifndef TCC_TARGET_X86_64
5344 /* generate CPU independent (unsigned) long long operations */
5345 void gen_opl(int op
)
5347 int t
, a
, b
, op1
, c
, i
;
5349 unsigned short reg_iret
= REG_IRET
;
5350 unsigned short reg_lret
= REG_LRET
;
5356 func
= TOK___divdi3
;
5359 func
= TOK___udivdi3
;
5362 func
= TOK___moddi3
;
5365 func
= TOK___umoddi3
;
5372 /* call generic long long function */
5373 vpush_global_sym(&func_old_type
, func
);
5378 vtop
->r2
= reg_lret
;
5391 /* stack: L1 H1 L2 H2 */
5396 vtop
[-2] = vtop
[-3];
5399 /* stack: H1 H2 L1 L2 */
5405 /* stack: H1 H2 L1 L2 ML MH */
5408 /* stack: ML MH H1 H2 L1 L2 */
5412 /* stack: ML MH H1 L2 H2 L1 */
5417 /* stack: ML MH M1 M2 */
5420 } else if (op
== '+' || op
== '-') {
5421 /* XXX: add non carry method too (for MIPS or alpha) */
5427 /* stack: H1 H2 (L1 op L2) */
5430 gen_op(op1
+ 1); /* TOK_xxxC2 */
5433 /* stack: H1 H2 (L1 op L2) */
5436 /* stack: (L1 op L2) H1 H2 */
5438 /* stack: (L1 op L2) (H1 op H2) */
5446 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
5447 t
= vtop
[-1].type
.t
;
5451 /* stack: L H shift */
5453 /* constant: simpler */
5454 /* NOTE: all comments are for SHL. the other cases are
5455 done by swaping words */
5466 if (op
!= TOK_SAR
) {
5499 /* XXX: should provide a faster fallback on x86 ? */
5502 func
= TOK___ashrdi3
;
5505 func
= TOK___lshrdi3
;
5508 func
= TOK___ashldi3
;
5514 /* compare operations */
5520 /* stack: L1 H1 L2 H2 */
5522 vtop
[-1] = vtop
[-2];
5524 /* stack: L1 L2 H1 H2 */
5527 /* when values are equal, we need to compare low words. since
5528 the jump is inverted, we invert the test too. */
5531 else if (op1
== TOK_GT
)
5533 else if (op1
== TOK_ULT
)
5535 else if (op1
== TOK_UGT
)
5540 if (op1
!= TOK_NE
) {
5544 /* generate non equal test */
5545 /* XXX: NOT PORTABLE yet */
5549 #if defined(TCC_TARGET_I386)
5550 b
= psym(0x850f, 0);
5551 #elif defined(TCC_TARGET_ARM)
5553 o(0x1A000000 | encbranch(ind
, 0, 1));
5554 #elif defined(TCC_TARGET_C67)
5555 error("not implemented");
5557 #error not supported
5561 /* compare low. Always unsigned */
5565 else if (op1
== TOK_LE
)
5567 else if (op1
== TOK_GT
)
5569 else if (op1
== TOK_GE
)
5580 /* handle integer constant optimizations and various machine
5582 void gen_opic(int op
)
5584 int c1
, c2
, t1
, t2
, n
;
5587 typedef unsigned long long U
;
5591 t1
= v1
->type
.t
& VT_BTYPE
;
5592 t2
= v2
->type
.t
& VT_BTYPE
;
5596 else if (v1
->type
.t
& VT_UNSIGNED
)
5603 else if (v2
->type
.t
& VT_UNSIGNED
)
5608 /* currently, we cannot do computations with forward symbols */
5609 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5610 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5613 case '+': l1
+= l2
; break;
5614 case '-': l1
-= l2
; break;
5615 case '&': l1
&= l2
; break;
5616 case '^': l1
^= l2
; break;
5617 case '|': l1
|= l2
; break;
5618 case '*': l1
*= l2
; break;
5625 /* if division by zero, generate explicit division */
5628 error("division by zero in constant");
5632 default: l1
/= l2
; break;
5633 case '%': l1
%= l2
; break;
5634 case TOK_UDIV
: l1
= (U
)l1
/ l2
; break;
5635 case TOK_UMOD
: l1
= (U
)l1
% l2
; break;
5638 case TOK_SHL
: l1
<<= l2
; break;
5639 case TOK_SHR
: l1
= (U
)l1
>> l2
; break;
5640 case TOK_SAR
: l1
>>= l2
; break;
5642 case TOK_ULT
: l1
= (U
)l1
< (U
)l2
; break;
5643 case TOK_UGE
: l1
= (U
)l1
>= (U
)l2
; break;
5644 case TOK_EQ
: l1
= l1
== l2
; break;
5645 case TOK_NE
: l1
= l1
!= l2
; break;
5646 case TOK_ULE
: l1
= (U
)l1
<= (U
)l2
; break;
5647 case TOK_UGT
: l1
= (U
)l1
> (U
)l2
; break;
5648 case TOK_LT
: l1
= l1
< l2
; break;
5649 case TOK_GE
: l1
= l1
>= l2
; break;
5650 case TOK_LE
: l1
= l1
<= l2
; break;
5651 case TOK_GT
: l1
= l1
> l2
; break;
5653 case TOK_LAND
: l1
= l1
&& l2
; break;
5654 case TOK_LOR
: l1
= l1
|| l2
; break;
5661 /* if commutative ops, put c2 as constant */
5662 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
5663 op
== '|' || op
== '*')) {
5665 c2
= c1
; //c = c1, c1 = c2, c2 = c;
5666 l2
= l1
; //l = l1, l1 = l2, l2 = l;
5668 /* Filter out NOP operations like x*1, x-0, x&-1... */
5669 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
5672 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
5673 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
5679 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
5680 /* try to use shifts instead of muls or divs */
5681 if (l2
> 0 && (l2
& (l2
- 1)) == 0) {
5690 else if (op
== TOK_PDIV
)
5696 } else if (c2
&& (op
== '+' || op
== '-') &&
5697 ((vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5698 (VT_CONST
| VT_SYM
) ||
5699 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
)) == VT_LOCAL
)) {
5700 /* symbol + constant case */
5707 if (!nocode_wanted
) {
5708 /* call low level op generator */
5709 if (t1
== VT_LLONG
|| t2
== VT_LLONG
)
5720 /* generate a floating point operation with constant propagation */
5721 void gen_opif(int op
)
5729 /* currently, we cannot do computations with forward symbols */
5730 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5731 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5733 if (v1
->type
.t
== VT_FLOAT
) {
5736 } else if (v1
->type
.t
== VT_DOUBLE
) {
5744 /* NOTE: we only do constant propagation if finite number (not
5745 NaN or infinity) (ANSI spec) */
5746 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5750 case '+': f1
+= f2
; break;
5751 case '-': f1
-= f2
; break;
5752 case '*': f1
*= f2
; break;
5756 error("division by zero in constant");
5761 /* XXX: also handles tests ? */
5765 /* XXX: overflow test ? */
5766 if (v1
->type
.t
== VT_FLOAT
) {
5768 } else if (v1
->type
.t
== VT_DOUBLE
) {
5776 if (!nocode_wanted
) {
5784 static int pointed_size(CType
*type
)
5787 return type_size(pointed_type(type
), &align
);
5790 static inline int is_null_pointer(SValue
*p
)
5792 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5794 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5795 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5798 static inline int is_integer_btype(int bt
)
5800 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5801 bt
== VT_INT
|| bt
== VT_LLONG
);
5804 /* check types for comparison or substraction of pointers */
5805 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5807 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5810 /* null pointers are accepted for all comparisons as gcc */
5811 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5815 bt1
= type1
->t
& VT_BTYPE
;
5816 bt2
= type2
->t
& VT_BTYPE
;
5817 /* accept comparison between pointer and integer with a warning */
5818 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5819 if (op
!= TOK_LOR
&& op
!= TOK_LAND
)
5820 warning("comparison between pointer and integer");
5824 /* both must be pointers or implicit function pointers */
5825 if (bt1
== VT_PTR
) {
5826 type1
= pointed_type(type1
);
5827 } else if (bt1
!= VT_FUNC
)
5828 goto invalid_operands
;
5830 if (bt2
== VT_PTR
) {
5831 type2
= pointed_type(type2
);
5832 } else if (bt2
!= VT_FUNC
) {
5834 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5836 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5837 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5841 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5842 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5843 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5844 /* gcc-like error if '-' is used */
5846 goto invalid_operands
;
5848 warning("comparison of distinct pointer types lacks a cast");
5852 /* generic gen_op: handles types problems */
5855 int u
, t1
, t2
, bt1
, bt2
, t
;
5858 t1
= vtop
[-1].type
.t
;
5859 t2
= vtop
[0].type
.t
;
5860 bt1
= t1
& VT_BTYPE
;
5861 bt2
= t2
& VT_BTYPE
;
5863 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5864 /* at least one operand is a pointer */
5865 /* relationnal op: must be both pointers */
5866 if (op
>= TOK_ULT
&& op
<= TOK_LOR
) {
5867 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5868 /* pointers are handled are unsigned */
5869 #ifdef TCC_TARGET_X86_64
5870 t
= VT_LLONG
| VT_UNSIGNED
;
5872 t
= VT_INT
| VT_UNSIGNED
;
5876 /* if both pointers, then it must be the '-' op */
5877 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5879 error("cannot use pointers here");
5880 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5881 /* XXX: check that types are compatible */
5882 u
= pointed_size(&vtop
[-1].type
);
5884 /* set to integer type */
5885 #ifdef TCC_TARGET_X86_64
5886 vtop
->type
.t
= VT_LLONG
;
5888 vtop
->type
.t
= VT_INT
;
5893 /* exactly one pointer : must be '+' or '-'. */
5894 if (op
!= '-' && op
!= '+')
5895 error("cannot use pointers here");
5896 /* Put pointer as first operand */
5897 if (bt2
== VT_PTR
) {
5901 type1
= vtop
[-1].type
;
5902 #ifdef TCC_TARGET_X86_64
5903 vpushll(pointed_size(&vtop
[-1].type
));
5905 /* XXX: cast to int ? (long long case) */
5906 vpushi(pointed_size(&vtop
[-1].type
));
5909 #ifdef CONFIG_TCC_BCHECK
5910 /* if evaluating constant expression, no code should be
5911 generated, so no bound check */
5912 if (do_bounds_check
&& !const_wanted
) {
5913 /* if bounded pointers, we generate a special code to
5920 gen_bounded_ptr_add();
5926 /* put again type if gen_opic() swaped operands */
5929 } else if (is_float(bt1
) || is_float(bt2
)) {
5930 /* compute bigger type and do implicit casts */
5931 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5933 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5938 /* floats can only be used for a few operations */
5939 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5940 (op
< TOK_ULT
|| op
> TOK_GT
))
5941 error("invalid operands for binary operation");
5943 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5944 /* cast to biggest op */
5946 /* convert to unsigned if it does not fit in a long long */
5947 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5948 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5952 /* integer operations */
5954 /* convert to unsigned if it does not fit in an integer */
5955 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5956 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5959 /* XXX: currently, some unsigned operations are explicit, so
5960 we modify them here */
5961 if (t
& VT_UNSIGNED
) {
5968 else if (op
== TOK_LT
)
5970 else if (op
== TOK_GT
)
5972 else if (op
== TOK_LE
)
5974 else if (op
== TOK_GE
)
5981 /* special case for shifts and long long: we keep the shift as
5983 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5990 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5991 /* relationnal op: the result is an int */
5992 vtop
->type
.t
= VT_INT
;
5999 #ifndef TCC_TARGET_ARM
6000 /* generic itof for unsigned long long case */
6001 void gen_cvt_itof1(int t
)
6003 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
6004 (VT_LLONG
| VT_UNSIGNED
)) {
6007 vpush_global_sym(&func_old_type
, TOK___floatundisf
);
6008 #if LDOUBLE_SIZE != 8
6009 else if (t
== VT_LDOUBLE
)
6010 vpush_global_sym(&func_old_type
, TOK___floatundixf
);
6013 vpush_global_sym(&func_old_type
, TOK___floatundidf
);
6024 /* generic ftoi for unsigned long long case */
6025 void gen_cvt_ftoi1(int t
)
6029 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
6030 /* not handled natively */
6031 st
= vtop
->type
.t
& VT_BTYPE
;
6033 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
6034 #if LDOUBLE_SIZE != 8
6035 else if (st
== VT_LDOUBLE
)
6036 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
6039 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
6044 vtop
->r2
= REG_LRET
;
6050 /* force char or short cast */
6051 void force_charshort_cast(int t
)
6055 /* XXX: add optimization if lvalue : just change type and offset */
6060 if (t
& VT_UNSIGNED
) {
6061 vpushi((1 << bits
) - 1);
6067 /* result must be signed or the SAR is converted to an SHL
6068 This was not the case when "t" was a signed short
6069 and the last value on the stack was an unsigned int */
6070 vtop
->type
.t
&= ~VT_UNSIGNED
;
6076 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
6077 static void gen_cast(CType
*type
)
6079 int sbt
, dbt
, sf
, df
, c
, p
;
6081 /* special delayed cast for char/short */
6082 /* XXX: in some cases (multiple cascaded casts), it may still
6084 if (vtop
->r
& VT_MUSTCAST
) {
6085 vtop
->r
&= ~VT_MUSTCAST
;
6086 force_charshort_cast(vtop
->type
.t
);
6089 /* bitfields first get cast to ints */
6090 if (vtop
->type
.t
& VT_BITFIELD
) {
6094 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
6095 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
6100 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
6101 p
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == (VT_CONST
| VT_SYM
);
6103 /* constant case: we can do it now */
6104 /* XXX: in ISOC, cannot do it if error in convert */
6105 if (sbt
== VT_FLOAT
)
6106 vtop
->c
.ld
= vtop
->c
.f
;
6107 else if (sbt
== VT_DOUBLE
)
6108 vtop
->c
.ld
= vtop
->c
.d
;
6111 if ((sbt
& VT_BTYPE
) == VT_LLONG
) {
6112 if (sbt
& VT_UNSIGNED
)
6113 vtop
->c
.ld
= vtop
->c
.ull
;
6115 vtop
->c
.ld
= vtop
->c
.ll
;
6117 if (sbt
& VT_UNSIGNED
)
6118 vtop
->c
.ld
= vtop
->c
.ui
;
6120 vtop
->c
.ld
= vtop
->c
.i
;
6123 if (dbt
== VT_FLOAT
)
6124 vtop
->c
.f
= (float)vtop
->c
.ld
;
6125 else if (dbt
== VT_DOUBLE
)
6126 vtop
->c
.d
= (double)vtop
->c
.ld
;
6127 } else if (sf
&& dbt
== (VT_LLONG
|VT_UNSIGNED
)) {
6128 vtop
->c
.ull
= (unsigned long long)vtop
->c
.ld
;
6129 } else if (sf
&& dbt
== VT_BOOL
) {
6130 vtop
->c
.i
= (vtop
->c
.ld
!= 0);
6133 vtop
->c
.ll
= (long long)vtop
->c
.ld
;
6134 else if (sbt
== (VT_LLONG
|VT_UNSIGNED
))
6135 vtop
->c
.ll
= vtop
->c
.ull
;
6136 else if (sbt
& VT_UNSIGNED
)
6137 vtop
->c
.ll
= vtop
->c
.ui
;
6138 else if (sbt
!= VT_LLONG
)
6139 vtop
->c
.ll
= vtop
->c
.i
;
6141 if (dbt
== (VT_LLONG
|VT_UNSIGNED
))
6142 vtop
->c
.ull
= vtop
->c
.ll
;
6143 else if (dbt
== VT_BOOL
)
6144 vtop
->c
.i
= (vtop
->c
.ll
!= 0);
6145 else if (dbt
!= VT_LLONG
) {
6147 if ((dbt
& VT_BTYPE
) == VT_BYTE
)
6149 else if ((dbt
& VT_BTYPE
) == VT_SHORT
)
6152 if(dbt
& VT_UNSIGNED
)
6153 vtop
->c
.ui
= ((unsigned int)vtop
->c
.ll
<< s
) >> s
;
6155 vtop
->c
.i
= ((int)vtop
->c
.ll
<< s
) >> s
;
6158 } else if (p
&& dbt
== VT_BOOL
) {
6161 } else if (!nocode_wanted
) {
6162 /* non constant case: generate code */
6164 /* convert from fp to fp */
6167 /* convert int to fp */
6170 /* convert fp to int */
6171 if (dbt
== VT_BOOL
) {
6175 /* we handle char/short/etc... with generic code */
6176 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
6177 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
6181 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
6182 /* additional cast for char/short... */
6187 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
6188 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
6189 /* scalar to long long */
6190 #ifndef TCC_TARGET_X86_64
6191 /* machine independent conversion */
6193 /* generate high word */
6194 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
6202 /* patch second register */
6203 vtop
[-1].r2
= vtop
->r
;
6207 if (sbt
!= (VT_INT
| VT_UNSIGNED
)) {
6208 /* x86_64 specific: movslq */
6210 o(0xc0 + (REG_VALUE(r
) << 3) + REG_VALUE(r
));
6214 } else if (dbt
== VT_BOOL
) {
6215 /* scalar to bool */
6218 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
6219 (dbt
& VT_BTYPE
) == VT_SHORT
) {
6220 if (sbt
== VT_PTR
) {
6221 vtop
->type
.t
= VT_INT
;
6222 warning("nonportable conversion from pointer to char/short");
6224 force_charshort_cast(dbt
);
6225 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
6227 if (sbt
== VT_LLONG
) {
6228 /* from long long: just take low order word */
6232 /* if lvalue and single word type, nothing to do because
6233 the lvalue already contains the real type size (see
6234 VT_LVAL_xxx constants) */
6237 } else if ((dbt
& VT_BTYPE
) == VT_PTR
&& !(vtop
->r
& VT_LVAL
)) {
6238 /* if we are casting between pointer types,
6239 we must update the VT_LVAL_xxx size */
6240 vtop
->r
= (vtop
->r
& ~VT_LVAL_TYPE
)
6241 | (lvalue_type(type
->ref
->type
.t
) & VT_LVAL_TYPE
);
6246 /* return type size. Put alignment at 'a' */
6247 static int type_size(CType
*type
, int *a
)
6252 bt
= type
->t
& VT_BTYPE
;
6253 if (bt
== VT_STRUCT
) {
6258 } else if (bt
== VT_PTR
) {
6259 if (type
->t
& VT_ARRAY
) {
6263 ts
= type_size(&s
->type
, a
);
6265 if (ts
< 0 && s
->c
< 0)
6273 } else if (bt
== VT_LDOUBLE
) {
6275 return LDOUBLE_SIZE
;
6276 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
6277 #ifdef TCC_TARGET_I386
6278 #ifdef TCC_TARGET_PE
6283 #elif defined(TCC_TARGET_ARM)
6293 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
6296 } else if (bt
== VT_SHORT
) {
6300 /* char, void, function, _Bool */
6306 /* return the pointed type of t */
6307 static inline CType
*pointed_type(CType
*type
)
6309 return &type
->ref
->type
;
6312 /* modify type so that its it is a pointer to type. */
6313 static void mk_pointer(CType
*type
)
6316 s
= sym_push(SYM_FIELD
, type
, 0, -1);
6317 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
6321 /* compare function types. OLD functions match any new functions */
6322 static int is_compatible_func(CType
*type1
, CType
*type2
)
6328 if (!is_compatible_types(&s1
->type
, &s2
->type
))
6330 /* check func_call */
6331 if (FUNC_CALL(s1
->r
) != FUNC_CALL(s2
->r
))
6333 /* XXX: not complete */
6334 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
6338 while (s1
!= NULL
) {
6341 if (!is_compatible_parameter_types(&s1
->type
, &s2
->type
))
6351 /* return true if type1 and type2 are the same. If unqualified is
6352 true, qualifiers on the types are ignored.
6354 - enums are not checked as gcc __builtin_types_compatible_p ()
6356 static int compare_types(CType
*type1
, CType
*type2
, int unqualified
)
6360 t1
= type1
->t
& VT_TYPE
;
6361 t2
= type2
->t
& VT_TYPE
;
6363 /* strip qualifiers before comparing */
6364 t1
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6365 t2
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6367 /* XXX: bitfields ? */
6370 /* test more complicated cases */
6371 bt1
= t1
& VT_BTYPE
;
6372 if (bt1
== VT_PTR
) {
6373 type1
= pointed_type(type1
);
6374 type2
= pointed_type(type2
);
6375 return is_compatible_types(type1
, type2
);
6376 } else if (bt1
== VT_STRUCT
) {
6377 return (type1
->ref
== type2
->ref
);
6378 } else if (bt1
== VT_FUNC
) {
6379 return is_compatible_func(type1
, type2
);
6385 /* return true if type1 and type2 are exactly the same (including
6388 static int is_compatible_types(CType
*type1
, CType
*type2
)
6390 return compare_types(type1
,type2
,0);
6393 /* return true if type1 and type2 are the same (ignoring qualifiers).
6395 static int is_compatible_parameter_types(CType
*type1
, CType
*type2
)
6397 return compare_types(type1
,type2
,1);
6400 /* print a type. If 'varstr' is not NULL, then the variable is also
6401 printed in the type */
6403 /* XXX: add array and function pointers */
6404 void type_to_str(char *buf
, int buf_size
,
6405 CType
*type
, const char *varstr
)
6412 t
= type
->t
& VT_TYPE
;
6415 if (t
& VT_CONSTANT
)
6416 pstrcat(buf
, buf_size
, "const ");
6417 if (t
& VT_VOLATILE
)
6418 pstrcat(buf
, buf_size
, "volatile ");
6419 if (t
& VT_UNSIGNED
)
6420 pstrcat(buf
, buf_size
, "unsigned ");
6450 tstr
= "long double";
6452 pstrcat(buf
, buf_size
, tstr
);
6456 if (bt
== VT_STRUCT
)
6460 pstrcat(buf
, buf_size
, tstr
);
6461 v
= type
->ref
->v
& ~SYM_STRUCT
;
6462 if (v
>= SYM_FIRST_ANOM
)
6463 pstrcat(buf
, buf_size
, "<anonymous>");
6465 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
6469 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
6470 pstrcat(buf
, buf_size
, "(");
6472 while (sa
!= NULL
) {
6473 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
6474 pstrcat(buf
, buf_size
, buf1
);
6477 pstrcat(buf
, buf_size
, ", ");
6479 pstrcat(buf
, buf_size
, ")");
6483 pstrcpy(buf1
, sizeof(buf1
), "*");
6485 pstrcat(buf1
, sizeof(buf1
), varstr
);
6486 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
6490 pstrcat(buf
, buf_size
, " ");
6491 pstrcat(buf
, buf_size
, varstr
);
6496 /* verify type compatibility to store vtop in 'dt' type, and generate
6498 static void gen_assign_cast(CType
*dt
)
6500 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
6501 char buf1
[256], buf2
[256];
6504 st
= &vtop
->type
; /* source type */
6505 dbt
= dt
->t
& VT_BTYPE
;
6506 sbt
= st
->t
& VT_BTYPE
;
6507 if (dt
->t
& VT_CONSTANT
)
6508 warning("assignment of read-only location");
6511 /* special cases for pointers */
6512 /* '0' can also be a pointer */
6513 if (is_null_pointer(vtop
))
6515 /* accept implicit pointer to integer cast with warning */
6516 if (is_integer_btype(sbt
)) {
6517 warning("assignment makes pointer from integer without a cast");
6520 type1
= pointed_type(dt
);
6521 /* a function is implicitely a function pointer */
6522 if (sbt
== VT_FUNC
) {
6523 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
6524 !is_compatible_types(pointed_type(dt
), st
))
6531 type2
= pointed_type(st
);
6532 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
6533 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
6534 /* void * can match anything */
6536 /* exact type match, except for unsigned */
6539 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6540 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6541 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
6542 warning("assignment from incompatible pointer type");
6544 /* check const and volatile */
6545 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
6546 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
6547 warning("assignment discards qualifiers from pointer target type");
6553 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
6554 warning("assignment makes integer from pointer without a cast");
6556 /* XXX: more tests */
6561 tmp_type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6562 tmp_type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6563 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
6565 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
6566 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
6567 error("cannot cast '%s' to '%s'", buf1
, buf2
);
6575 /* store vtop in lvalue pushed on stack */
6578 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
6580 ft
= vtop
[-1].type
.t
;
6581 sbt
= vtop
->type
.t
& VT_BTYPE
;
6582 dbt
= ft
& VT_BTYPE
;
6583 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
6584 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
6585 /* optimize char/short casts */
6586 delayed_cast
= VT_MUSTCAST
;
6587 vtop
->type
.t
= ft
& (VT_TYPE
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
)));
6588 /* XXX: factorize */
6589 if (ft
& VT_CONSTANT
)
6590 warning("assignment of read-only location");
6593 if (!(ft
& VT_BITFIELD
))
6594 gen_assign_cast(&vtop
[-1].type
);
6597 if (sbt
== VT_STRUCT
) {
6598 /* if structure, only generate pointer */
6599 /* structure assignment : generate memcpy */
6600 /* XXX: optimize if small size */
6601 if (!nocode_wanted
) {
6602 size
= type_size(&vtop
->type
, &align
);
6606 vpush_global_sym(&func_old_type
, TOK_memcpy8
);
6607 else if(!(align
& 3))
6608 vpush_global_sym(&func_old_type
, TOK_memcpy4
);
6611 vpush_global_sym(&func_old_type
, TOK_memcpy
);
6615 vtop
->type
.t
= VT_INT
;
6619 vtop
->type
.t
= VT_INT
;
6631 /* leave source on stack */
6632 } else if (ft
& VT_BITFIELD
) {
6633 /* bitfield store handling */
6634 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
6635 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
6636 /* remove bit field info to avoid loops */
6637 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
6639 /* duplicate source into other register */
6644 if((ft
& VT_BTYPE
) == VT_BOOL
) {
6645 gen_cast(&vtop
[-1].type
);
6646 vtop
[-1].type
.t
= (vtop
[-1].type
.t
& ~VT_BTYPE
) | (VT_BYTE
| VT_UNSIGNED
);
6649 /* duplicate destination */
6651 vtop
[-1] = vtop
[-2];
6653 /* mask and shift source */
6654 if((ft
& VT_BTYPE
) != VT_BOOL
) {
6655 if((ft
& VT_BTYPE
) == VT_LLONG
) {
6656 vpushll((1ULL << bit_size
) - 1ULL);
6658 vpushi((1 << bit_size
) - 1);
6664 /* load destination, mask and or with source */
6666 if((ft
& VT_BTYPE
) == VT_LLONG
) {
6667 vpushll(~(((1ULL << bit_size
) - 1ULL) << bit_pos
));
6669 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
6676 /* pop off shifted source from "duplicate source..." above */
6680 #ifdef CONFIG_TCC_BCHECK
6681 /* bound check case */
6682 if (vtop
[-1].r
& VT_MUSTBOUND
) {
6688 if (!nocode_wanted
) {
6692 #ifdef TCC_TARGET_X86_64
6693 if ((ft
& VT_BTYPE
) == VT_LDOUBLE
) {
6698 r
= gv(rc
); /* generate value */
6699 /* if lvalue was saved on stack, must read it */
6700 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
6702 t
= get_reg(RC_INT
);
6703 #ifdef TCC_TARGET_X86_64
6708 sv
.r
= VT_LOCAL
| VT_LVAL
;
6709 sv
.c
.ul
= vtop
[-1].c
.ul
;
6711 vtop
[-1].r
= t
| VT_LVAL
;
6714 #ifndef TCC_TARGET_X86_64
6715 /* two word case handling : store second register at word + 4 */
6716 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
6718 /* convert to int to increment easily */
6719 vtop
->type
.t
= VT_INT
;
6725 /* XXX: it works because r2 is spilled last ! */
6726 store(vtop
->r2
, vtop
- 1);
6731 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
6732 vtop
->r
|= delayed_cast
;
6736 /* post defines POST/PRE add. c is the token ++ or -- */
6737 void inc(int post
, int c
)
6740 vdup(); /* save lvalue */
6742 gv_dup(); /* duplicate value */
6747 vpushi(c
- TOK_MID
);
6749 vstore(); /* store value */
6751 vpop(); /* if post op, return saved value */
6754 /* Parse GNUC __attribute__ extension. Currently, the following
6755 extensions are recognized:
6756 - aligned(n) : set data/function alignment.
6757 - packed : force data alignment to 1
6758 - section(x) : generate data/code in this section.
6759 - unused : currently ignored, but may be used someday.
6760 - regparm(n) : pass function parameters in registers (i386 only)
6762 static void parse_attribute(AttributeDef
*ad
)
6766 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
6770 while (tok
!= ')') {
6771 if (tok
< TOK_IDENT
)
6772 expect("attribute name");
6780 expect("section name");
6781 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
6790 if (n
<= 0 || (n
& (n
- 1)) != 0)
6791 error("alignment must be a positive power of two");
6804 /* currently, no need to handle it because tcc does not
6805 track unused objects */
6809 /* currently, no need to handle it because tcc does not
6810 track unused objects */
6815 FUNC_CALL(ad
->func_attr
) = FUNC_CDECL
;
6820 FUNC_CALL(ad
->func_attr
) = FUNC_STDCALL
;
6822 #ifdef TCC_TARGET_I386
6832 FUNC_CALL(ad
->func_attr
) = FUNC_FASTCALL1
+ n
- 1;
6838 FUNC_CALL(ad
->func_attr
) = FUNC_FASTCALLW
;
6842 FUNC_EXPORT(ad
->func_attr
) = 1;
6845 if (tcc_state
->warn_unsupported
)
6846 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6847 /* skip parameters */
6849 int parenthesis
= 0;
6853 else if (tok
== ')')
6856 } while (parenthesis
&& tok
!= -1);
6869 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6870 static void struct_decl(CType
*type
, int u
)
6872 int a
, v
, size
, align
, maxalign
, c
, offset
;
6873 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
, prevbt
;
6874 Sym
*s
, *ss
, *ass
, **ps
;
6878 a
= tok
; /* save decl type */
6883 /* struct already defined ? return it */
6885 expect("struct/union/enum name");
6889 error("invalid type");
6896 /* we put an undefined size for struct/union */
6897 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6898 s
->r
= 0; /* default alignment is zero as gcc */
6899 /* put struct/union/enum name in type */
6907 error("struct/union/enum already defined");
6908 /* cannot be empty */
6910 /* non empty enums are not allowed */
6911 if (a
== TOK_ENUM
) {
6915 expect("identifier");
6921 /* enum symbols have static storage */
6922 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6923 ss
->type
.t
|= VT_STATIC
;
6928 /* NOTE: we accept a trailing comma */
6939 while (tok
!= '}') {
6940 parse_btype(&btype
, &ad
);
6946 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6947 if (v
== 0 && (type1
.t
& VT_BTYPE
) != VT_STRUCT
)
6948 expect("identifier");
6949 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6950 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6951 error("invalid type for '%s'",
6952 get_tok_str(v
, NULL
));
6956 bit_size
= expr_const();
6957 /* XXX: handle v = 0 case for messages */
6959 error("negative width in bit-field '%s'",
6960 get_tok_str(v
, NULL
));
6961 if (v
&& bit_size
== 0)
6962 error("zero width for bit-field '%s'",
6963 get_tok_str(v
, NULL
));
6965 size
= type_size(&type1
, &align
);
6967 if (align
< ad
.aligned
)
6969 } else if (ad
.packed
) {
6971 } else if (*tcc_state
->pack_stack_ptr
) {
6972 if (align
> *tcc_state
->pack_stack_ptr
)
6973 align
= *tcc_state
->pack_stack_ptr
;
6976 if (bit_size
>= 0) {
6977 bt
= type1
.t
& VT_BTYPE
;
6984 error("bitfields must have scalar type");
6986 if (bit_size
> bsize
) {
6987 error("width of '%s' exceeds its type",
6988 get_tok_str(v
, NULL
));
6989 } else if (bit_size
== bsize
) {
6990 /* no need for bit fields */
6992 } else if (bit_size
== 0) {
6993 /* XXX: what to do if only padding in a
6995 /* zero size: means to pad */
6998 /* we do not have enough room ?
6999 did the type change?
7001 if ((bit_pos
+ bit_size
) > bsize
||
7002 bt
!= prevbt
|| a
== TOK_UNION
)
7005 /* XXX: handle LSB first */
7006 type1
.t
|= VT_BITFIELD
|
7007 (bit_pos
<< VT_STRUCT_SHIFT
) |
7008 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
7009 bit_pos
+= bit_size
;
7015 if (v
!= 0 || (type1
.t
& VT_BTYPE
) == VT_STRUCT
) {
7016 /* add new memory data only if starting
7018 if (lbit_pos
== 0) {
7019 if (a
== TOK_STRUCT
) {
7020 c
= (c
+ align
- 1) & -align
;
7029 if (align
> maxalign
)
7033 printf("add field %s offset=%d",
7034 get_tok_str(v
, NULL
), offset
);
7035 if (type1
.t
& VT_BITFIELD
) {
7036 printf(" pos=%d size=%d",
7037 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
7038 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
7043 if (v
== 0 && (type1
.t
& VT_BTYPE
) == VT_STRUCT
) {
7045 while ((ass
= ass
->next
) != NULL
) {
7046 ss
= sym_push(ass
->v
, &ass
->type
, 0, offset
+ ass
->c
);
7051 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
7055 if (tok
== ';' || tok
== TOK_EOF
)
7062 /* store size and alignment */
7063 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
7069 /* return 0 if no type declaration. otherwise, return the basic type
7072 static int parse_btype(CType
*type
, AttributeDef
*ad
)
7074 int t
, u
, type_found
, typespec_found
, typedef_found
;
7078 memset(ad
, 0, sizeof(AttributeDef
));
7086 /* currently, we really ignore extension */
7096 if ((t
& VT_BTYPE
) != 0)
7097 error("too many basic types");
7113 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
7114 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
7115 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
7116 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
7130 if ((t
& VT_BTYPE
) == VT_LONG
) {
7131 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
7138 struct_decl(&type1
, VT_ENUM
);
7141 type
->ref
= type1
.ref
;
7145 struct_decl(&type1
, VT_STRUCT
);
7148 /* type modifiers */
7201 /* GNUC attribute */
7202 case TOK_ATTRIBUTE1
:
7203 case TOK_ATTRIBUTE2
:
7204 parse_attribute(ad
);
7211 parse_expr_type(&type1
);
7214 if (typespec_found
|| typedef_found
)
7217 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
7220 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
7221 type
->ref
= s
->type
.ref
;
7229 if ((t
& (VT_SIGNED
|VT_UNSIGNED
)) == (VT_SIGNED
|VT_UNSIGNED
))
7230 error("signed and unsigned modifier");
7231 if (tcc_state
->char_is_unsigned
) {
7232 if ((t
& (VT_SIGNED
|VT_UNSIGNED
|VT_BTYPE
)) == VT_BYTE
)
7237 /* long is never used as type */
7238 if ((t
& VT_BTYPE
) == VT_LONG
)
7239 #ifndef TCC_TARGET_X86_64
7240 t
= (t
& ~VT_BTYPE
) | VT_INT
;
7242 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
7248 /* convert a function parameter type (array to pointer and function to
7249 function pointer) */
7250 static inline void convert_parameter_type(CType
*pt
)
7252 /* remove const and volatile qualifiers (XXX: const could be used
7253 to indicate a const function parameter */
7254 pt
->t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7255 /* array must be transformed to pointer according to ANSI C */
7257 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
7262 static void post_type(CType
*type
, AttributeDef
*ad
)
7264 int n
, l
, t1
, arg_size
, align
;
7265 Sym
**plast
, *s
, *first
;
7270 /* function declaration */
7278 /* read param name and compute offset */
7279 if (l
!= FUNC_OLD
) {
7280 if (!parse_btype(&pt
, &ad1
)) {
7282 error("invalid type");
7289 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
7291 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
7292 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
7293 error("parameter declared as void");
7294 arg_size
+= (type_size(&pt
, &align
) + 3) & ~3;
7299 expect("identifier");
7303 convert_parameter_type(&pt
);
7304 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
7310 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
7317 /* if no parameters, then old type prototype */
7321 t1
= type
->t
& VT_STORAGE
;
7322 /* NOTE: const is ignored in returned type as it has a special
7323 meaning in gcc / C++ */
7324 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
7325 post_type(type
, ad
);
7326 /* we push a anonymous symbol which will contain the function prototype */
7327 FUNC_ARGS(ad
->func_attr
) = arg_size
;
7328 s
= sym_push(SYM_FIELD
, type
, ad
->func_attr
, l
);
7330 type
->t
= t1
| VT_FUNC
;
7332 } else if (tok
== '[') {
7333 /* array definition */
7335 if (tok
== TOK_RESTRICT1
)
7341 error("invalid array size");
7344 /* parse next post type */
7345 t1
= type
->t
& VT_STORAGE
;
7346 type
->t
&= ~VT_STORAGE
;
7347 post_type(type
, ad
);
7349 /* we push a anonymous symbol which will contain the array
7351 s
= sym_push(SYM_FIELD
, type
, 0, n
);
7352 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
7357 /* Parse a type declaration (except basic type), and return the type
7358 in 'type'. 'td' is a bitmask indicating which kind of type decl is
7359 expected. 'type' should contain the basic type. 'ad' is the
7360 attribute definition of the basic type. It can be modified by
7363 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
7366 CType type1
, *type2
;
7369 while (tok
== '*') {
7377 qualifiers
|= VT_CONSTANT
;
7382 qualifiers
|= VT_VOLATILE
;
7390 type
->t
|= qualifiers
;
7393 /* XXX: clarify attribute handling */
7394 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7395 parse_attribute(ad
);
7397 /* recursive type */
7398 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
7399 type1
.t
= 0; /* XXX: same as int */
7402 /* XXX: this is not correct to modify 'ad' at this point, but
7403 the syntax is not clear */
7404 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7405 parse_attribute(ad
);
7406 type_decl(&type1
, ad
, v
, td
);
7409 /* type identifier */
7410 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
7414 if (!(td
& TYPE_ABSTRACT
))
7415 expect("identifier");
7419 post_type(type
, ad
);
7420 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7421 parse_attribute(ad
);
7424 /* append type at the end of type1 */
7437 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
7438 static int lvalue_type(int t
)
7443 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
7445 else if (bt
== VT_SHORT
)
7449 if (t
& VT_UNSIGNED
)
7450 r
|= VT_LVAL_UNSIGNED
;
7454 /* indirection with full error checking and bound check */
7455 static void indir(void)
7457 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
) {
7458 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FUNC
)
7462 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
7464 vtop
->type
= *pointed_type(&vtop
->type
);
7465 /* Arrays and functions are never lvalues */
7466 if (!(vtop
->type
.t
& VT_ARRAY
)
7467 && (vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7468 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7469 /* if bound checking, the referenced pointer must be checked */
7470 if (do_bounds_check
)
7471 vtop
->r
|= VT_MUSTBOUND
;
7475 /* pass a parameter to a function and do type checking and casting */
7476 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
7481 func_type
= func
->c
;
7482 if (func_type
== FUNC_OLD
||
7483 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
7484 /* default casting : only need to convert float to double */
7485 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
7489 } else if (arg
== NULL
) {
7490 error("too many arguments to function");
7493 type
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
7494 gen_assign_cast(&type
);
7498 /* parse an expression of the form '(type)' or '(expr)' and return its
7500 static void parse_expr_type(CType
*type
)
7506 if (parse_btype(type
, &ad
)) {
7507 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7514 static void parse_type(CType
*type
)
7519 if (!parse_btype(type
, &ad
)) {
7522 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7525 static void vpush_tokc(int t
)
7529 vsetc(&type
, VT_CONST
, &tokc
);
7532 static void unary(void)
7534 int n
, t
, align
, size
, r
;
7539 /* XXX: GCC 2.95.3 does not generate a table although it should be
7553 vpush_tokc(VT_INT
| VT_UNSIGNED
);
7557 vpush_tokc(VT_LLONG
);
7561 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
7565 vpush_tokc(VT_FLOAT
);
7569 vpush_tokc(VT_DOUBLE
);
7573 vpush_tokc(VT_LDOUBLE
);
7576 case TOK___FUNCTION__
:
7578 goto tok_identifier
;
7584 /* special function name identifier */
7585 len
= strlen(funcname
) + 1;
7586 /* generate char[len] type */
7591 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
7592 ptr
= section_ptr_add(data_section
, len
);
7593 memcpy(ptr
, funcname
, len
);
7598 #ifdef TCC_TARGET_PE
7599 t
= VT_SHORT
| VT_UNSIGNED
;
7605 /* string parsing */
7608 if (tcc_state
->warn_write_strings
)
7613 memset(&ad
, 0, sizeof(AttributeDef
));
7614 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
7619 if (parse_btype(&type
, &ad
)) {
7620 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
7622 /* check ISOC99 compound literal */
7624 /* data is allocated locally by default */
7629 /* all except arrays are lvalues */
7630 if (!(type
.t
& VT_ARRAY
))
7631 r
|= lvalue_type(type
.t
);
7632 memset(&ad
, 0, sizeof(AttributeDef
));
7633 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
7638 } else if (tok
== '{') {
7639 /* save all registers */
7641 /* statement expression : we do not accept break/continue
7642 inside as GCC does */
7643 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
7658 /* functions names must be treated as function pointers,
7659 except for unary '&' and sizeof. Since we consider that
7660 functions are not lvalues, we only have to handle it
7661 there and in function calls. */
7662 /* arrays can also be used although they are not lvalues */
7663 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
7664 !(vtop
->type
.t
& VT_ARRAY
) && !(vtop
->type
.t
& VT_LLOCAL
))
7666 mk_pointer(&vtop
->type
);
7672 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
7674 boolean
.t
= VT_BOOL
;
7676 vtop
->c
.i
= !vtop
->c
.i
;
7677 } else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
7678 vtop
->c
.i
= vtop
->c
.i
^ 1;
7681 vseti(VT_JMP
, gtst(1, 0));
7692 /* in order to force cast, we add zero */
7694 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
7695 error("pointer not accepted for unary plus");
7705 parse_expr_type(&type
);
7709 size
= type_size(&type
, &align
);
7710 if (t
== TOK_SIZEOF
) {
7712 error("sizeof applied to an incomplete type");
7717 vtop
->type
.t
|= VT_UNSIGNED
;
7720 case TOK_builtin_types_compatible_p
:
7729 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7730 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7731 vpushi(is_compatible_types(&type1
, &type2
));
7734 case TOK_builtin_constant_p
:
7736 int saved_nocode_wanted
, res
;
7739 saved_nocode_wanted
= nocode_wanted
;
7742 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
7744 nocode_wanted
= saved_nocode_wanted
;
7749 case TOK_builtin_frame_address
:
7754 if (tok
!= TOK_CINT
) {
7755 error("__builtin_frame_address only takes integers");
7758 error("TCC only supports __builtin_frame_address(0)");
7764 vset(&type
, VT_LOCAL
, 0);
7767 #ifdef TCC_TARGET_X86_64
7768 case TOK_builtin_malloc
:
7770 char *p
= file
->buf_ptr
;
7771 file
->buf_ptr
= "malloc";
7774 goto tok_identifier
;
7776 case TOK_builtin_free
:
7778 char *p
= file
->buf_ptr
;
7779 file
->buf_ptr
= "free";
7782 goto tok_identifier
;
7800 goto tok_identifier
;
7802 /* allow to take the address of a label */
7803 if (tok
< TOK_UIDENT
)
7804 expect("label identifier");
7805 s
= label_find(tok
);
7807 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7809 if (s
->r
== LABEL_DECLARED
)
7810 s
->r
= LABEL_FORWARD
;
7813 s
->type
.t
= VT_VOID
;
7814 mk_pointer(&s
->type
);
7815 s
->type
.t
|= VT_STATIC
;
7817 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
7826 expect("identifier");
7830 error("'%s' undeclared", get_tok_str(t
, NULL
));
7831 /* for simple function calls, we tolerate undeclared
7832 external reference to int() function */
7833 if (tcc_state
->warn_implicit_function_declaration
)
7834 warning("implicit declaration of function '%s'",
7835 get_tok_str(t
, NULL
));
7836 s
= external_global_sym(t
, &func_old_type
, 0);
7838 if ((s
->type
.t
& (VT_STATIC
| VT_INLINE
| VT_BTYPE
)) ==
7839 (VT_STATIC
| VT_INLINE
| VT_FUNC
)) {
7840 /* if referencing an inline function, then we generate a
7841 symbol to it if not already done. It will have the
7842 effect to generate code for it at the end of the
7843 compilation unit. Inline function as always
7844 generated in the text section. */
7846 put_extern_sym(s
, text_section
, 0, 0);
7847 r
= VT_SYM
| VT_CONST
;
7851 vset(&s
->type
, r
, s
->c
);
7852 /* if forward reference, we must point to s */
7853 if (vtop
->r
& VT_SYM
) {
7860 /* post operations */
7862 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
7865 } else if (tok
== '.' || tok
== TOK_ARROW
) {
7867 if (tok
== TOK_ARROW
)
7872 /* expect pointer on structure */
7873 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
7874 expect("struct or union");
7878 while ((s
= s
->next
) != NULL
) {
7883 error("field not found: %s", get_tok_str(tok
& ~SYM_FIELD
, NULL
));
7884 /* add field offset to pointer */
7885 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
7888 /* change type to field type, and set to lvalue */
7889 vtop
->type
= s
->type
;
7890 /* an array is never an lvalue */
7891 if (!(vtop
->type
.t
& VT_ARRAY
)) {
7892 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7893 /* if bound checking, the referenced pointer must be checked */
7894 if (do_bounds_check
)
7895 vtop
->r
|= VT_MUSTBOUND
;
7898 } else if (tok
== '[') {
7904 } else if (tok
== '(') {
7910 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7911 /* pointer test (no array accepted) */
7912 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
7913 vtop
->type
= *pointed_type(&vtop
->type
);
7914 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
7918 expect("function pointer");
7921 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
7923 /* get return type */
7926 sa
= s
->next
; /* first parameter */
7929 /* compute first implicit argument if a structure is returned */
7930 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
7931 /* get some space for the returned structure */
7932 size
= type_size(&s
->type
, &align
);
7933 loc
= (loc
- size
) & -align
;
7935 ret
.r
= VT_LOCAL
| VT_LVAL
;
7936 /* pass it as 'int' to avoid structure arg passing
7938 vseti(VT_LOCAL
, loc
);
7943 /* return in register */
7944 if (is_float(ret
.type
.t
)) {
7947 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
7956 gfunc_param_typed(s
, sa
);
7966 error("too few arguments to function");
7968 if (!nocode_wanted
) {
7969 gfunc_call(nb_args
);
7971 vtop
-= (nb_args
+ 1);
7974 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
7982 static void uneq(void)
7988 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
7989 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
7990 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
8005 static void expr_prod(void)
8010 while (tok
== '*' || tok
== '/' || tok
== '%') {
8018 static void expr_sum(void)
8023 while (tok
== '+' || tok
== '-') {
8031 static void expr_shift(void)
8036 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
8044 static void expr_cmp(void)
8049 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
8050 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
8058 static void expr_cmpeq(void)
8063 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
8071 static void expr_and(void)
8074 while (tok
== '&') {
8081 static void expr_xor(void)
8084 while (tok
== '^') {
8091 static void expr_or(void)
8094 while (tok
== '|') {
8101 /* XXX: fix this mess */
8102 static void expr_land_const(void)
8105 while (tok
== TOK_LAND
) {
8112 /* XXX: fix this mess */
8113 static void expr_lor_const(void)
8116 while (tok
== TOK_LOR
) {
8123 /* only used if non constant */
8124 static void expr_land(void)
8129 if (tok
== TOK_LAND
) {
8134 if (tok
!= TOK_LAND
) {
8144 static void expr_lor(void)
8149 if (tok
== TOK_LOR
) {
8154 if (tok
!= TOK_LOR
) {
8164 /* XXX: better constant handling */
8165 static void expr_eq(void)
8167 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
8169 CType type
, type1
, type2
;
8176 boolean
.t
= VT_BOOL
;
8182 if (tok
!= ':' || !gnu_ext
) {
8197 if (vtop
!= vstack
) {
8198 /* needed to avoid having different registers saved in
8200 if (is_float(vtop
->type
.t
)) {
8202 #ifdef TCC_TARGET_X86_64
8203 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LDOUBLE
) {
8213 if (tok
== ':' && gnu_ext
) {
8221 sv
= *vtop
; /* save value to handle it later */
8222 vtop
--; /* no vpop so that FP stack is not flushed */
8230 bt1
= t1
& VT_BTYPE
;
8232 bt2
= t2
& VT_BTYPE
;
8233 /* cast operands to correct type according to ISOC rules */
8234 if (is_float(bt1
) || is_float(bt2
)) {
8235 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
8236 type
.t
= VT_LDOUBLE
;
8237 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
8242 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
8243 /* cast to biggest op */
8245 /* convert to unsigned if it does not fit in a long long */
8246 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
8247 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
8248 type
.t
|= VT_UNSIGNED
;
8249 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
8250 /* XXX: test pointer compatibility */
8252 } else if (bt1
== VT_FUNC
|| bt2
== VT_FUNC
) {
8253 /* XXX: test function pointer compatibility */
8255 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
8256 /* XXX: test structure compatibility */
8258 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
8259 /* NOTE: as an extension, we accept void on only one side */
8262 /* integer operations */
8264 /* convert to unsigned if it does not fit in an integer */
8265 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
8266 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
8267 type
.t
|= VT_UNSIGNED
;
8270 /* now we convert second operand */
8272 if (VT_STRUCT
== (vtop
->type
.t
& VT_BTYPE
))
8275 if (is_float(type
.t
)) {
8277 #ifdef TCC_TARGET_X86_64
8278 if ((type
.t
& VT_BTYPE
) == VT_LDOUBLE
) {
8282 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
8283 /* for long longs, we use fixed registers to avoid having
8284 to handle a complicated move */
8289 /* this is horrible, but we must also convert first
8293 /* put again first value and cast it */
8296 if (VT_STRUCT
== (vtop
->type
.t
& VT_BTYPE
))
8306 static void gexpr(void)
8317 /* parse an expression and return its type without any side effect. */
8318 static void expr_type(CType
*type
)
8320 int saved_nocode_wanted
;
8322 saved_nocode_wanted
= nocode_wanted
;
8327 nocode_wanted
= saved_nocode_wanted
;
8330 /* parse a unary expression and return its type without any side
8332 static void unary_type(CType
*type
)
8344 /* parse a constant expression and return value in vtop. */
8345 static void expr_const1(void)
8354 /* parse an integer constant and return its value. */
8355 static int expr_const(void)
8359 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
8360 expect("constant expression");
8366 /* return the label token if current token is a label, otherwise
8368 static int is_label(void)
8372 /* fast test first */
8373 if (tok
< TOK_UIDENT
)
8375 /* no need to save tokc because tok is an identifier */
8382 unget_tok(last_tok
);
8387 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
8388 int case_reg
, int is_expr
)
8393 /* generate line number info */
8395 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
8396 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
8398 last_line_num
= file
->line_num
;
8402 /* default return value is (void) */
8404 vtop
->type
.t
= VT_VOID
;
8407 if (tok
== TOK_IF
) {
8414 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
8416 if (c
== TOK_ELSE
) {
8420 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
8421 gsym(d
); /* patch else jmp */
8424 } else if (tok
== TOK_WHILE
) {
8432 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8436 } else if (tok
== '{') {
8440 /* record local declaration stack position */
8442 llabel
= local_label_stack
;
8443 /* handle local labels declarations */
8444 if (tok
== TOK_LABEL
) {
8447 if (tok
< TOK_UIDENT
)
8448 expect("label identifier");
8449 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
8459 while (tok
!= '}') {
8464 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8467 /* pop locally defined labels */
8468 label_pop(&local_label_stack
, llabel
);
8469 /* pop locally defined symbols */
8471 /* XXX: this solution makes only valgrind happy...
8472 triggered by gcc.c-torture/execute/20000917-1.c */
8474 switch(vtop
->type
.t
& VT_BTYPE
) {
8479 for(p
=vtop
->type
.ref
;p
;p
=p
->prev
)
8481 error("unsupported expression type");
8484 sym_pop(&local_stack
, s
);
8486 } else if (tok
== TOK_RETURN
) {
8490 gen_assign_cast(&func_vt
);
8491 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
8493 /* if returning structure, must copy it to implicit
8494 first pointer arg location */
8497 size
= type_size(&func_vt
,&align
);
8500 if((vtop
->r
!= (VT_LOCAL
| VT_LVAL
) || (vtop
->c
.i
& 3))
8504 loc
= (loc
- size
) & -4;
8507 vset(&type
, VT_LOCAL
| VT_LVAL
, addr
);
8510 vset(&int_type
, VT_LOCAL
| VT_LVAL
, addr
);
8512 vtop
->type
= int_type
;
8518 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
8521 /* copy structure value to pointer */
8526 } else if (is_float(func_vt
.t
)) {
8531 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
8534 rsym
= gjmp(rsym
); /* jmp */
8535 } else if (tok
== TOK_BREAK
) {
8538 error("cannot break");
8539 *bsym
= gjmp(*bsym
);
8542 } else if (tok
== TOK_CONTINUE
) {
8545 error("cannot continue");
8546 *csym
= gjmp(*csym
);
8549 } else if (tok
== TOK_FOR
) {
8576 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8581 if (tok
== TOK_DO
) {
8586 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8597 if (tok
== TOK_SWITCH
) {
8601 /* XXX: other types than integer */
8602 case_reg
= gv(RC_INT
);
8606 b
= gjmp(0); /* jump to first case */
8608 block(&a
, csym
, &b
, &c
, case_reg
, 0);
8609 /* if no default, jmp after switch */
8617 if (tok
== TOK_CASE
) {
8624 if (gnu_ext
&& tok
== TOK_DOTS
) {
8628 warning("empty case range");
8630 /* since a case is like a label, we must skip it with a jmp */
8637 *case_sym
= gtst(1, 0);
8640 *case_sym
= gtst(1, 0);
8644 *case_sym
= gtst(1, *case_sym
);
8649 goto block_after_label
;
8651 if (tok
== TOK_DEFAULT
) {
8657 error("too many 'default'");
8660 goto block_after_label
;
8662 if (tok
== TOK_GOTO
) {
8664 if (tok
== '*' && gnu_ext
) {
8668 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
8671 } else if (tok
>= TOK_UIDENT
) {
8672 s
= label_find(tok
);
8673 /* put forward definition if needed */
8675 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
8677 if (s
->r
== LABEL_DECLARED
)
8678 s
->r
= LABEL_FORWARD
;
8680 /* label already defined */
8681 if (s
->r
& LABEL_FORWARD
)
8682 s
->next
= (void *)gjmp((long)s
->next
);
8684 gjmp_addr((long)s
->next
);
8687 expect("label identifier");
8690 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
8698 if (s
->r
== LABEL_DEFINED
)
8699 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
8700 gsym((long)s
->next
);
8701 s
->r
= LABEL_DEFINED
;
8703 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
8705 s
->next
= (void *)ind
;
8706 /* we accept this, but it is a mistake */
8709 warning("deprecated use of label at end of compound statement");
8713 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8716 /* expression case */
8731 /* t is the array or struct type. c is the array or struct
8732 address. cur_index/cur_field is the pointer to the current
8733 value. 'size_only' is true if only size info is needed (only used
8735 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
8736 int *cur_index
, Sym
**cur_field
,
8740 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
8746 if (gnu_ext
&& (l
= is_label()) != 0)
8748 while (tok
== '[' || tok
== '.') {
8750 if (!(type
->t
& VT_ARRAY
))
8751 expect("array type");
8754 index
= expr_const();
8755 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
8756 expect("invalid index");
8757 if (tok
== TOK_DOTS
&& gnu_ext
) {
8759 index_last
= expr_const();
8760 if (index_last
< 0 ||
8761 (s
->c
>= 0 && index_last
>= s
->c
) ||
8763 expect("invalid index");
8769 *cur_index
= index_last
;
8770 type
= pointed_type(type
);
8771 elem_size
= type_size(type
, &align
);
8772 c
+= index
* elem_size
;
8773 /* NOTE: we only support ranges for last designator */
8774 nb_elems
= index_last
- index
+ 1;
8775 if (nb_elems
!= 1) {
8784 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
8785 expect("struct/union type");
8798 /* XXX: fix this mess by using explicit storage field */
8800 type1
.t
|= (type
->t
& ~VT_TYPE
);
8814 if (type
->t
& VT_ARRAY
) {
8816 type
= pointed_type(type
);
8817 c
+= index
* type_size(type
, &align
);
8821 error("too many field init");
8822 /* XXX: fix this mess by using explicit storage field */
8824 type1
.t
|= (type
->t
& ~VT_TYPE
);
8829 decl_initializer(type
, sec
, c
, 0, size_only
);
8831 /* XXX: make it more general */
8832 if (!size_only
&& nb_elems
> 1) {
8833 unsigned long c_end
;
8838 error("range init not supported yet for dynamic storage");
8839 c_end
= c
+ nb_elems
* elem_size
;
8840 if (c_end
> sec
->data_allocated
)
8841 section_realloc(sec
, c_end
);
8842 src
= sec
->data
+ c
;
8844 for(i
= 1; i
< nb_elems
; i
++) {
8846 memcpy(dst
, src
, elem_size
);
8852 #define EXPR_CONST 1
8855 /* store a value or an expression directly in global data or in local array */
8856 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
8857 int v
, int expr_type
)
8859 int saved_global_expr
, bt
, bit_pos
, bit_size
;
8861 unsigned long long bit_mask
;
8869 /* compound literals must be allocated globally in this case */
8870 saved_global_expr
= global_expr
;
8873 global_expr
= saved_global_expr
;
8874 /* NOTE: symbols are accepted */
8875 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
8876 error("initializer element is not constant");
8884 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
8887 /* XXX: not portable */
8888 /* XXX: generate error if incorrect relocation */
8889 gen_assign_cast(&dtype
);
8890 bt
= type
->t
& VT_BTYPE
;
8891 /* we'll write at most 12 bytes */
8892 if (c
+ 12 > sec
->data_allocated
) {
8893 section_realloc(sec
, c
+ 12);
8895 ptr
= sec
->data
+ c
;
8896 /* XXX: make code faster ? */
8897 if (!(type
->t
& VT_BITFIELD
)) {
8902 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
8903 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
8904 bit_mask
= (1LL << bit_size
) - 1;
8906 if ((vtop
->r
& VT_SYM
) &&
8912 (bt
== VT_INT
&& bit_size
!= 32)))
8913 error("initializer element is not computable at load time");
8916 vtop
->c
.i
= (vtop
->c
.i
!= 0);
8918 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8921 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8924 *(double *)ptr
= vtop
->c
.d
;
8927 *(long double *)ptr
= vtop
->c
.ld
;
8930 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
8933 if (vtop
->r
& VT_SYM
) {
8934 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
8936 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8941 vset(&dtype
, VT_LOCAL
|VT_LVAL
, c
);
8948 /* put zeros for variable based init */
8949 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
8952 /* nothing to do because globals are already set to zero */
8954 vpush_global_sym(&func_old_type
, TOK_memset
);
8962 /* 't' contains the type and storage info. 'c' is the offset of the
8963 object in section 'sec'. If 'sec' is NULL, it means stack based
8964 allocation. 'first' is true if array '{' must be read (multi
8965 dimension implicit array init handling). 'size_only' is true if
8966 size only evaluation is wanted (only for arrays). */
8967 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
8968 int first
, int size_only
)
8970 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
8971 int size1
, align1
, expr_type
;
8975 if (type
->t
& VT_ARRAY
) {
8979 t1
= pointed_type(type
);
8980 size1
= type_size(t1
, &align1
);
8983 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
8989 /* only parse strings here if correct type (otherwise: handle
8990 them as ((w)char *) expressions */
8991 if ((tok
== TOK_LSTR
&&
8992 #ifdef TCC_TARGET_PE
8993 (t1
->t
& VT_BTYPE
) == VT_SHORT
&& (t1
->t
& VT_UNSIGNED
)
8995 (t1
->t
& VT_BTYPE
) == VT_INT
8997 ) || (tok
== TOK_STR
&& (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
8998 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
9003 /* compute maximum number of chars wanted */
9005 cstr_len
= cstr
->size
;
9007 cstr_len
= cstr
->size
/ sizeof(nwchar_t
);
9010 if (n
>= 0 && nb
> (n
- array_length
))
9011 nb
= n
- array_length
;
9014 warning("initializer-string for array is too long");
9015 /* in order to go faster for common case (char
9016 string in global variable, we handle it
9018 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
9019 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
9023 ch
= ((unsigned char *)cstr
->data
)[i
];
9025 ch
= ((nwchar_t
*)cstr
->data
)[i
];
9026 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
9034 /* only add trailing zero if enough storage (no
9035 warning in this case since it is standard) */
9036 if (n
< 0 || array_length
< n
) {
9038 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
9044 while (tok
!= '}') {
9045 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
9046 if (n
>= 0 && index
>= n
)
9047 error("index too large");
9048 /* must put zero in holes (note that doing it that way
9049 ensures that it even works with designators) */
9050 if (!size_only
&& array_length
< index
) {
9051 init_putz(t1
, sec
, c
+ array_length
* size1
,
9052 (index
- array_length
) * size1
);
9055 if (index
> array_length
)
9056 array_length
= index
;
9057 /* special test for multi dimensional arrays (may not
9058 be strictly correct if designators are used at the
9060 if (index
>= n
&& no_oblock
)
9069 /* put zeros at the end */
9070 if (!size_only
&& n
>= 0 && array_length
< n
) {
9071 init_putz(t1
, sec
, c
+ array_length
* size1
,
9072 (n
- array_length
) * size1
);
9074 /* patch type size if needed */
9076 s
->c
= array_length
;
9077 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
9078 (sec
|| !first
|| tok
== '{')) {
9081 /* NOTE: the previous test is a specific case for automatic
9082 struct/union init */
9083 /* XXX: union needs only one init */
9085 /* XXX: this test is incorrect for local initializers
9086 beginning with ( without {. It would be much more difficult
9087 to do it correctly (ideally, the expression parser should
9088 be used in all cases) */
9094 while (tok
== '(') {
9098 if (!parse_btype(&type1
, &ad1
))
9100 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
9102 if (!is_assignable_types(type
, &type1
))
9103 error("invalid type for cast");
9108 if (first
|| tok
== '{') {
9117 while (tok
!= '}') {
9118 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
9120 if (!size_only
&& array_length
< index
) {
9121 init_putz(type
, sec
, c
+ array_length
,
9122 index
- array_length
);
9124 index
= index
+ type_size(&f
->type
, &align1
);
9125 if (index
> array_length
)
9126 array_length
= index
;
9128 if (no_oblock
&& f
== NULL
)
9134 /* put zeros at the end */
9135 if (!size_only
&& array_length
< n
) {
9136 init_putz(type
, sec
, c
+ array_length
,
9145 } else if (tok
== '{') {
9147 decl_initializer(type
, sec
, c
, first
, size_only
);
9149 } else if (size_only
) {
9150 /* just skip expression */
9152 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
9156 else if (tok
== ')')
9161 /* currently, we always use constant expression for globals
9162 (may change for scripting case) */
9163 expr_type
= EXPR_CONST
;
9165 expr_type
= EXPR_ANY
;
9166 init_putv(type
, sec
, c
, 0, expr_type
);
9170 /* parse an initializer for type 't' if 'has_init' is non zero, and
9171 allocate space in local or global data space ('r' is either
9172 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
9173 variable 'v' of scope 'scope' is declared before initializers are
9174 parsed. If 'v' is zero, then a reference to the new object is put
9175 in the value stack. If 'has_init' is 2, a special parsing is done
9176 to handle string constants. */
9177 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
9178 int has_init
, int v
, int scope
)
9180 int size
, align
, addr
, data_offset
;
9182 ParseState saved_parse_state
;
9183 TokenString init_str
;
9186 size
= type_size(type
, &align
);
9187 /* If unknown size, we must evaluate it before
9188 evaluating initializers because
9189 initializers can generate global data too
9190 (e.g. string pointers or ISOC99 compound
9191 literals). It also simplifies local
9192 initializers handling */
9193 tok_str_new(&init_str
);
9196 error("unknown type size");
9197 /* get all init string */
9198 if (has_init
== 2) {
9199 /* only get strings */
9200 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
9201 tok_str_add_tok(&init_str
);
9206 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
9208 error("unexpected end of file in initializer");
9209 tok_str_add_tok(&init_str
);
9212 else if (tok
== '}') {
9222 tok_str_add(&init_str
, -1);
9223 tok_str_add(&init_str
, 0);
9226 save_parse_state(&saved_parse_state
);
9228 macro_ptr
= init_str
.str
;
9230 decl_initializer(type
, NULL
, 0, 1, 1);
9231 /* prepare second initializer parsing */
9232 macro_ptr
= init_str
.str
;
9235 /* if still unknown size, error */
9236 size
= type_size(type
, &align
);
9238 error("unknown type size");
9240 /* take into account specified alignment if bigger */
9242 if (ad
->aligned
> align
)
9243 align
= ad
->aligned
;
9244 } else if (ad
->packed
) {
9247 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
9249 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
9251 loc
= (loc
- size
) & -align
;
9253 /* handles bounds */
9254 /* XXX: currently, since we do only one pass, we cannot track
9255 '&' operators, so we add only arrays */
9256 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
9257 unsigned long *bounds_ptr
;
9258 /* add padding between regions */
9260 /* then add local bound info */
9261 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
9262 bounds_ptr
[0] = addr
;
9263 bounds_ptr
[1] = size
;
9266 /* local variable */
9267 sym_push(v
, type
, r
, addr
);
9269 /* push local reference */
9270 vset(type
, r
, addr
);
9276 if (v
&& scope
== VT_CONST
) {
9277 /* see if the symbol was already defined */
9280 if (!is_compatible_types(&sym
->type
, type
))
9281 error("incompatible types for redefinition of '%s'",
9282 get_tok_str(v
, NULL
));
9283 if (sym
->type
.t
& VT_EXTERN
) {
9284 /* if the variable is extern, it was not allocated */
9285 sym
->type
.t
&= ~VT_EXTERN
;
9286 /* set array size if it was ommited in extern
9288 if ((sym
->type
.t
& VT_ARRAY
) &&
9289 sym
->type
.ref
->c
< 0 &&
9291 sym
->type
.ref
->c
= type
->ref
->c
;
9293 /* we accept several definitions of the same
9294 global variable. this is tricky, because we
9295 must play with the SHN_COMMON type of the symbol */
9296 /* XXX: should check if the variable was already
9297 initialized. It is incorrect to initialized it
9299 /* no init data, we won't add more to the symbol */
9306 /* allocate symbol in corresponding section */
9311 else if (tcc_state
->nocommon
)
9315 data_offset
= sec
->data_offset
;
9316 data_offset
= (data_offset
+ align
- 1) & -align
;
9318 /* very important to increment global pointer at this time
9319 because initializers themselves can create new initializers */
9320 data_offset
+= size
;
9321 /* add padding if bound check */
9322 if (do_bounds_check
)
9324 sec
->data_offset
= data_offset
;
9325 /* allocate section space to put the data */
9326 if (sec
->sh_type
!= SHT_NOBITS
&&
9327 data_offset
> sec
->data_allocated
)
9328 section_realloc(sec
, data_offset
);
9329 /* align section if needed */
9330 if (align
> sec
->sh_addralign
)
9331 sec
->sh_addralign
= align
;
9333 addr
= 0; /* avoid warning */
9337 if (scope
!= VT_CONST
|| !sym
) {
9338 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
9340 /* update symbol definition */
9342 put_extern_sym(sym
, sec
, addr
, size
);
9345 /* put a common area */
9346 put_extern_sym(sym
, NULL
, align
, size
);
9347 /* XXX: find a nicer way */
9348 esym
= &((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
];
9349 esym
->st_shndx
= SHN_COMMON
;
9354 /* push global reference */
9355 sym
= get_sym_ref(type
, sec
, addr
, size
);
9357 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
9361 /* handles bounds now because the symbol must be defined
9362 before for the relocation */
9363 if (do_bounds_check
) {
9364 unsigned long *bounds_ptr
;
9366 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
9367 /* then add global bound info */
9368 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
9369 bounds_ptr
[0] = 0; /* relocated */
9370 bounds_ptr
[1] = size
;
9374 decl_initializer(type
, sec
, addr
, 1, 0);
9375 /* restore parse state if needed */
9377 tok_str_free(init_str
.str
);
9378 restore_parse_state(&saved_parse_state
);
9384 void put_func_debug(Sym
*sym
)
9389 /* XXX: we put here a dummy type */
9390 snprintf(buf
, sizeof(buf
), "%s:%c1",
9391 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
9392 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
9393 cur_text_section
, sym
->c
);
9394 /* //gr gdb wants a line at the function */
9395 put_stabn(N_SLINE
, 0, file
->line_num
, 0);
9400 /* parse an old style function declaration list */
9401 /* XXX: check multiple parameter */
9402 static void func_decl_list(Sym
*func_sym
)
9409 /* parse each declaration */
9410 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
9411 if (!parse_btype(&btype
, &ad
))
9412 expect("declaration list");
9413 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
9414 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
9416 /* we accept no variable after */
9420 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
9421 /* find parameter in function parameter list */
9424 if ((s
->v
& ~SYM_FIELD
) == v
)
9428 error("declaration for parameter '%s' but no such parameter",
9429 get_tok_str(v
, NULL
));
9431 /* check that no storage specifier except 'register' was given */
9432 if (type
.t
& VT_STORAGE
)
9433 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
9434 convert_parameter_type(&type
);
9435 /* we can add the type (NOTE: it could be local to the function) */
9437 /* accept other parameters */
9448 /* parse a function defined by symbol 'sym' and generate its code in
9449 'cur_text_section' */
9450 static void gen_function(Sym
*sym
)
9452 int saved_nocode_wanted
= nocode_wanted
;
9454 ind
= cur_text_section
->data_offset
;
9455 /* NOTE: we patch the symbol size later */
9456 put_extern_sym(sym
, cur_text_section
, ind
, 0);
9457 funcname
= get_tok_str(sym
->v
, NULL
);
9459 /* put debug symbol */
9461 put_func_debug(sym
);
9462 /* push a dummy symbol to enable local sym storage */
9463 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
9464 gfunc_prolog(&sym
->type
);
9466 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
9469 cur_text_section
->data_offset
= ind
;
9470 label_pop(&global_label_stack
, NULL
);
9471 sym_pop(&local_stack
, NULL
); /* reset local stack */
9472 /* end of function */
9473 /* patch symbol size */
9474 ((ElfW(Sym
) *)symtab_section
->data
)[sym
->c
].st_size
=
9477 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
9479 /* It's better to crash than to generate wrong code */
9480 cur_text_section
= NULL
;
9481 funcname
= ""; /* for safety */
9482 func_vt
.t
= VT_VOID
; /* for safety */
9483 ind
= 0; /* for safety */
9484 nocode_wanted
= saved_nocode_wanted
;
9487 static void gen_inline_functions(void)
9491 int *str
, inline_generated
;
9493 /* iterate while inline function are referenced */
9495 inline_generated
= 0;
9496 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
9498 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
9499 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
9500 (VT_STATIC
| VT_INLINE
) &&
9502 /* the function was used: generate its code and
9503 convert it to a normal function */
9504 str
= INLINE_DEF(sym
->r
);
9505 sym
->r
= VT_SYM
| VT_CONST
;
9506 sym
->type
.t
&= ~VT_INLINE
;
9510 cur_text_section
= text_section
;
9512 macro_ptr
= NULL
; /* fail safe */
9515 inline_generated
= 1;
9518 if (!inline_generated
)
9522 /* free all remaining inline function tokens */
9523 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
9525 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
9526 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
9527 (VT_STATIC
| VT_INLINE
)) {
9528 //gr printf("sym %d %s\n", sym->r, get_tok_str(sym->v, NULL));
9529 if (sym
->r
== (VT_SYM
| VT_CONST
)) //gr beware!
9531 str
= INLINE_DEF(sym
->r
);
9533 sym
->r
= 0; /* fail safe */
9538 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
9539 static void decl(int l
)
9547 if (!parse_btype(&btype
, &ad
)) {
9548 /* skip redundant ';' */
9549 /* XXX: find more elegant solution */
9554 if (l
== VT_CONST
&&
9555 (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
)) {
9556 /* global asm block */
9560 /* special test for old K&R protos without explicit int
9561 type. Only accepted when defining global data */
9562 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
9566 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
9567 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
9569 /* we accept no variable after */
9573 while (1) { /* iterate thru each declaration */
9575 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
9579 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
9580 printf("type = '%s'\n", buf
);
9583 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9584 /* if old style function prototype, we accept a
9587 if (sym
->c
== FUNC_OLD
)
9588 func_decl_list(sym
);
9593 error("cannot use local functions");
9594 if ((type
.t
& VT_BTYPE
) != VT_FUNC
)
9595 expect("function definition");
9597 /* reject abstract declarators in function definition */
9599 while ((sym
= sym
->next
) != NULL
)
9600 if (!(sym
->v
& ~SYM_FIELD
))
9601 expect("identifier");
9603 /* XXX: cannot do better now: convert extern line to static inline */
9604 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
9605 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
9609 if ((sym
->type
.t
& VT_BTYPE
) != VT_FUNC
)
9611 /* specific case: if not func_call defined, we put
9612 the one of the prototype */
9613 /* XXX: should have default value */
9614 r
= sym
->type
.ref
->r
;
9615 if (FUNC_CALL(r
) != FUNC_CDECL
9616 && FUNC_CALL(type
.ref
->r
) == FUNC_CDECL
)
9617 FUNC_CALL(type
.ref
->r
) = FUNC_CALL(r
);
9619 FUNC_EXPORT(type
.ref
->r
) = 1;
9621 if (!is_compatible_types(&sym
->type
, &type
)) {
9623 error("incompatible types for redefinition of '%s'",
9624 get_tok_str(v
, NULL
));
9626 /* if symbol is already defined, then put complete type */
9629 /* put function symbol */
9630 sym
= global_identifier_push(v
, type
.t
, 0);
9631 sym
->type
.ref
= type
.ref
;
9634 /* static inline functions are just recorded as a kind
9635 of macro. Their code will be emitted at the end of
9636 the compilation unit only if they are used */
9637 if ((type
.t
& (VT_INLINE
| VT_STATIC
)) ==
9638 (VT_INLINE
| VT_STATIC
)) {
9639 TokenString func_str
;
9642 tok_str_new(&func_str
);
9648 error("unexpected end of file");
9649 tok_str_add_tok(&func_str
);
9654 } else if (t
== '}') {
9656 if (block_level
== 0)
9660 tok_str_add(&func_str
, -1);
9661 tok_str_add(&func_str
, 0);
9662 INLINE_DEF(sym
->r
) = func_str
.str
;
9664 /* compute text section */
9665 cur_text_section
= ad
.section
;
9666 if (!cur_text_section
)
9667 cur_text_section
= text_section
;
9668 sym
->r
= VT_SYM
| VT_CONST
;
9673 if (btype
.t
& VT_TYPEDEF
) {
9674 /* save typedefed type */
9675 /* XXX: test storage specifiers ? */
9676 sym
= sym_push(v
, &type
, 0, 0);
9677 sym
->type
.t
|= VT_TYPEDEF
;
9678 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9679 /* external function definition */
9680 /* specific case for func_call attribute */
9682 type
.ref
->r
= ad
.func_attr
;
9683 external_sym(v
, &type
, 0);
9685 /* not lvalue if array */
9687 if (!(type
.t
& VT_ARRAY
))
9688 r
|= lvalue_type(type
.t
);
9689 has_init
= (tok
== '=');
9690 if ((btype
.t
& VT_EXTERN
) ||
9691 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
9692 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
9693 /* external variable */
9694 /* NOTE: as GCC, uninitialized global static
9695 arrays of null size are considered as
9697 external_sym(v
, &type
, r
);
9699 type
.t
|= (btype
.t
& VT_STATIC
); /* Retain "static". */
9700 if (type
.t
& VT_STATIC
)
9706 decl_initializer_alloc(&type
, &ad
, r
,
9720 /* better than nothing, but needs extension to handle '-E' option
9722 static void preprocess_init(TCCState
*s1
)
9724 s1
->include_stack_ptr
= s1
->include_stack
;
9725 /* XXX: move that before to avoid having to initialize
9726 file->ifdef_stack_ptr ? */
9727 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
9728 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
9730 /* XXX: not ANSI compliant: bound checking says error */
9732 s1
->pack_stack
[0] = 0;
9733 s1
->pack_stack_ptr
= s1
->pack_stack
;
9736 /* compile the C file opened in 'file'. Return non zero if errors. */
9737 static int tcc_compile(TCCState
*s1
)
9741 volatile int section_sym
;
9744 printf("%s: **** new file\n", file
->filename
);
9746 preprocess_init(s1
);
9748 cur_text_section
= NULL
;
9750 anon_sym
= SYM_FIRST_ANOM
;
9752 /* file info: full path + filename */
9753 section_sym
= 0; /* avoid warning */
9755 section_sym
= put_elf_sym(symtab_section
, 0, 0,
9756 ELFW(ST_INFO
)(STB_LOCAL
, STT_SECTION
), 0,
9757 text_section
->sh_num
, NULL
);
9758 getcwd(buf
, sizeof(buf
));
9760 normalize_slashes(buf
);
9762 pstrcat(buf
, sizeof(buf
), "/");
9763 put_stabs_r(buf
, N_SO
, 0, 0,
9764 text_section
->data_offset
, text_section
, section_sym
);
9765 put_stabs_r(file
->filename
, N_SO
, 0, 0,
9766 text_section
->data_offset
, text_section
, section_sym
);
9768 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
9769 symbols can be safely used */
9770 put_elf_sym(symtab_section
, 0, 0,
9771 ELFW(ST_INFO
)(STB_LOCAL
, STT_FILE
), 0,
9772 SHN_ABS
, file
->filename
);
9774 /* define some often used types */
9775 int_type
.t
= VT_INT
;
9777 char_pointer_type
.t
= VT_BYTE
;
9778 mk_pointer(&char_pointer_type
);
9780 func_old_type
.t
= VT_FUNC
;
9781 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
9783 #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
9784 float_type
.t
= VT_FLOAT
;
9785 double_type
.t
= VT_DOUBLE
;
9787 func_float_type
.t
= VT_FUNC
;
9788 func_float_type
.ref
= sym_push(SYM_FIELD
, &float_type
, FUNC_CDECL
, FUNC_OLD
);
9789 func_double_type
.t
= VT_FUNC
;
9790 func_double_type
.ref
= sym_push(SYM_FIELD
, &double_type
, FUNC_CDECL
, FUNC_OLD
);
9794 /* define 'void *alloca(unsigned int)' builtin function */
9799 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
9800 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
9803 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
9807 define_start
= define_stack
;
9810 if (setjmp(s1
->error_jmp_buf
) == 0) {
9812 s1
->error_set_jmp_enabled
= 1;
9814 ch
= file
->buf_ptr
[0];
9815 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9816 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
9820 expect("declaration");
9822 /* end of translation unit info */
9824 put_stabs_r(NULL
, N_SO
, 0, 0,
9825 text_section
->data_offset
, text_section
, section_sym
);
9828 s1
->error_set_jmp_enabled
= 0;
9830 /* reset define stack, but leave -Dsymbols (may be incorrect if
9831 they are undefined) */
9832 free_defines(define_start
);
9834 gen_inline_functions();
9836 sym_pop(&global_stack
, NULL
);
9837 sym_pop(&local_stack
, NULL
);
9839 return s1
->nb_errors
!= 0 ? -1 : 0;
9842 /* Preprocess the current file */
9843 /* XXX: add line and file infos,
9844 * XXX: add options to preserve spaces (partly done, only spaces in macro are
9847 static int tcc_preprocess(TCCState
*s1
)
9850 BufferedFile
*file_ref
;
9851 int token_seen
, line_ref
;
9853 preprocess_init(s1
);
9854 define_start
= define_stack
;
9855 ch
= file
->buf_ptr
[0];
9857 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9858 parse_flags
= PARSE_FLAG_ASM_COMMENTS
| PARSE_FLAG_PREPROCESS
|
9859 PARSE_FLAG_LINEFEED
;
9867 if (tok
== TOK_EOF
) {
9869 } else if (tok
== TOK_LINEFEED
) {
9874 } else if (token_seen
) {
9875 fwrite(tok_spaces
.data
, tok_spaces
.size
, 1, s1
->outfile
);
9877 int d
= file
->line_num
- line_ref
;
9878 if (file
!= file_ref
|| d
< 0 || d
>= 8)
9879 fprintf(s1
->outfile
, "# %d \"%s\"\n", file
->line_num
, file
->filename
);
9882 fputs("\n", s1
->outfile
), --d
;
9883 line_ref
= (file_ref
= file
)->line_num
;
9886 fputs(get_tok_str(tok
, &tokc
), s1
->outfile
);
9888 free_defines(define_start
);
9893 int tcc_compile_string(TCCState
*s
, const char *str
)
9895 BufferedFile bf1
, *bf
= &bf1
;
9899 /* init file structure */
9901 /* XXX: avoid copying */
9903 buf
= tcc_malloc(len
+ 1);
9906 memcpy(buf
, str
, len
);
9909 bf
->buf_end
= buf
+ len
;
9910 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
9913 ret
= tcc_compile(s
);
9917 /* currently, no need to close */
9922 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9923 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
9925 BufferedFile bf1
, *bf
= &bf1
;
9927 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
9928 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
9932 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
9934 /* init file structure */
9936 bf
->buf_ptr
= bf
->buffer
;
9937 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
9938 *bf
->buf_end
= CH_EOB
;
9939 bf
->filename
[0] = '\0';
9943 s1
->include_stack_ptr
= s1
->include_stack
;
9945 /* parse with define parser */
9946 ch
= file
->buf_ptr
[0];
9952 /* undefine a preprocessor symbol */
9953 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
9957 ts
= tok_alloc(sym
, strlen(sym
));
9958 s
= define_find(ts
->tok
);
9959 /* undefine symbol by putting an invalid name */
9964 #ifdef CONFIG_TCC_ASM
9966 #ifdef TCC_TARGET_I386
9967 #include "i386-asm.c"
9972 static void asm_instr(void)
9974 error("inline asm() not supported");
9976 static void asm_global_instr(void)
9978 error("inline asm() not supported");
9984 #ifdef TCC_TARGET_COFF
9985 #include "tcccoff.c"
9988 #ifdef TCC_TARGET_PE
9992 /* print the position in the source file of PC value 'pc' by reading
9993 the stabs debug information */
9994 static void rt_printline(unsigned long wanted_pc
)
9996 Stab_Sym
*sym
, *sym_end
;
9997 char func_name
[128], last_func_name
[128];
9998 unsigned long func_addr
, last_pc
, pc
;
9999 const char *incl_files
[INCLUDE_STACK_SIZE
];
10000 int incl_index
, len
, last_line_num
, i
;
10001 const char *str
, *p
;
10003 fprintf(stderr
, "0x%08lx:", wanted_pc
);
10005 func_name
[0] = '\0';
10008 last_func_name
[0] = '\0';
10009 last_pc
= 0xffffffff;
10011 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
10012 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
10013 while (sym
< sym_end
) {
10014 switch(sym
->n_type
) {
10015 /* function start or end */
10017 if (sym
->n_strx
== 0) {
10018 /* we test if between last line and end of function */
10019 pc
= sym
->n_value
+ func_addr
;
10020 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
10022 func_name
[0] = '\0';
10025 str
= stabstr_section
->data
+ sym
->n_strx
;
10026 p
= strchr(str
, ':');
10028 pstrcpy(func_name
, sizeof(func_name
), str
);
10031 if (len
> sizeof(func_name
) - 1)
10032 len
= sizeof(func_name
) - 1;
10033 memcpy(func_name
, str
, len
);
10034 func_name
[len
] = '\0';
10036 func_addr
= sym
->n_value
;
10039 /* line number info */
10041 pc
= sym
->n_value
+ func_addr
;
10042 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
10045 last_line_num
= sym
->n_desc
;
10047 strcpy(last_func_name
, func_name
);
10049 /* include files */
10051 str
= stabstr_section
->data
+ sym
->n_strx
;
10053 if (incl_index
< INCLUDE_STACK_SIZE
) {
10054 incl_files
[incl_index
++] = str
;
10058 if (incl_index
> 1)
10062 if (sym
->n_strx
== 0) {
10063 incl_index
= 0; /* end of translation unit */
10065 str
= stabstr_section
->data
+ sym
->n_strx
;
10066 /* do not add path */
10068 if (len
> 0 && str
[len
- 1] != '/')
10076 /* second pass: we try symtab symbols (no line number info) */
10079 ElfW(Sym
) *sym
, *sym_end
;
10082 sym_end
= (ElfW(Sym
) *)(symtab_section
->data
+ symtab_section
->data_offset
);
10083 for(sym
= (ElfW(Sym
) *)symtab_section
->data
+ 1;
10086 type
= ELFW(ST_TYPE
)(sym
->st_info
);
10087 if (type
== STT_FUNC
) {
10088 if (wanted_pc
>= sym
->st_value
&&
10089 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
10090 pstrcpy(last_func_name
, sizeof(last_func_name
),
10091 strtab_section
->data
+ sym
->st_name
);
10097 /* did not find any info: */
10098 fprintf(stderr
, " ???\n");
10101 if (last_func_name
[0] != '\0') {
10102 fprintf(stderr
, " %s()", last_func_name
);
10104 if (incl_index
> 0) {
10105 fprintf(stderr
, " (%s:%d",
10106 incl_files
[incl_index
- 1], last_line_num
);
10107 for(i
= incl_index
- 2; i
>= 0; i
--)
10108 fprintf(stderr
, ", included from %s", incl_files
[i
]);
10109 fprintf(stderr
, ")");
10111 fprintf(stderr
, "\n");
10114 #if !defined(_WIN32) && !defined(CONFIG_TCCBOOT)
10118 /* fix for glibc 2.1 */
10120 #define REG_EIP EIP
10121 #define REG_EBP EBP
10124 /* return the PC at frame level 'level'. Return non zero if not found */
10125 static int rt_get_caller_pc(unsigned long *paddr
,
10126 ucontext_t
*uc
, int level
)
10132 #if defined(__FreeBSD__)
10133 *paddr
= uc
->uc_mcontext
.mc_eip
;
10134 #elif defined(__dietlibc__)
10135 *paddr
= uc
->uc_mcontext
.eip
;
10137 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
10141 #if defined(__FreeBSD__)
10142 fp
= uc
->uc_mcontext
.mc_ebp
;
10143 #elif defined(__dietlibc__)
10144 fp
= uc
->uc_mcontext
.ebp
;
10146 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
10148 for(i
=1;i
<level
;i
++) {
10149 /* XXX: check address validity with program info */
10150 if (fp
<= 0x1000 || fp
>= 0xc0000000)
10152 fp
= ((unsigned long *)fp
)[0];
10154 *paddr
= ((unsigned long *)fp
)[1];
10158 #elif defined(__x86_64__)
10159 /* return the PC at frame level 'level'. Return non zero if not found */
10160 static int rt_get_caller_pc(unsigned long *paddr
,
10161 ucontext_t
*uc
, int level
)
10167 /* XXX: only support linux */
10168 *paddr
= uc
->uc_mcontext
.gregs
[REG_RIP
];
10171 fp
= uc
->uc_mcontext
.gregs
[REG_RBP
];
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];
10184 #warning add arch specific rt_get_caller_pc()
10186 static int rt_get_caller_pc(unsigned long *paddr
,
10187 ucontext_t
*uc
, int level
)
10193 /* emit a run time error at position 'pc' */
10194 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
10201 fprintf(stderr
, "Runtime error: ");
10202 vfprintf(stderr
, fmt
, ap
);
10203 fprintf(stderr
, "\n");
10204 for(i
=0;i
<num_callers
;i
++) {
10205 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
10208 fprintf(stderr
, "at ");
10210 fprintf(stderr
, "by ");
10217 /* signal handler for fatal errors */
10218 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
10220 ucontext_t
*uc
= puc
;
10224 switch(siginf
->si_code
) {
10227 rt_error(uc
, "division by zero");
10230 rt_error(uc
, "floating point exception");
10236 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
10237 rt_error(uc
, *rt_bound_error_msg
);
10239 rt_error(uc
, "dereferencing invalid pointer");
10242 rt_error(uc
, "illegal instruction");
10245 rt_error(uc
, "abort() called");
10248 rt_error(uc
, "caught signal %d", signum
);
10255 /* do all relocations (needed before using tcc_get_symbol()) */
10256 int tcc_relocate(TCCState
*s1
)
10263 #ifdef TCC_TARGET_PE
10264 pe_add_runtime(s1
);
10266 tcc_add_runtime(s1
);
10269 relocate_common_syms();
10271 tcc_add_linker_symbols(s1
);
10272 #ifndef TCC_TARGET_PE
10273 build_got_entries(s1
);
10276 #ifdef TCC_TARGET_X86_64
10278 /* If the distance of two sections are longer than 32bit, our
10279 program will crash. Let's combine all sections which are
10280 necessary to run the program into a single buffer in the
10284 /* calculate the size of buffers we need */
10286 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10287 s
= s1
->sections
[i
];
10288 if (s
->sh_flags
& SHF_ALLOC
) {
10289 size
+= s
->data_offset
;
10292 /* double the size of the buffer for got and plt entries
10293 XXX: calculate exact size for them? */
10294 section_realloc(text_section
, size
* 2);
10295 p
= text_section
->data
+ text_section
->data_offset
;
10296 /* we will put got and plt after this offset */
10297 text_section
->data_offset
= size
;
10299 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10300 s
= s1
->sections
[i
];
10301 if (s
->sh_flags
& SHF_ALLOC
) {
10302 if (s
!= text_section
&& s
->data_offset
) {
10303 if (s
->sh_type
== SHT_NOBITS
) {
10304 /* for bss section */
10305 memset(p
, 0, s
->data_offset
);
10307 memcpy(p
, s
->data
, s
->data_offset
);
10311 /* we won't free s->data for this section */
10312 s
->data_allocated
= 0;
10313 p
+= s
->data_offset
;
10315 s
->sh_addr
= (unsigned long)s
->data
;
10320 /* compute relocation address : section are relocated in place. We
10321 also alloc the bss space */
10322 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10323 s
= s1
->sections
[i
];
10324 if (s
->sh_flags
& SHF_ALLOC
) {
10325 if (s
->sh_type
== SHT_NOBITS
)
10326 s
->data
= tcc_mallocz(s
->data_offset
);
10327 s
->sh_addr
= (unsigned long)s
->data
;
10332 relocate_syms(s1
, 1);
10334 if (s1
->nb_errors
!= 0)
10337 /* relocate each section */
10338 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10339 s
= s1
->sections
[i
];
10341 relocate_section(s1
, s
);
10344 /* mark executable sections as executable in memory */
10345 for(i
= 1; i
< s1
->nb_sections
; i
++) {
10346 s
= s1
->sections
[i
];
10347 if ((s
->sh_flags
& (SHF_ALLOC
| SHF_EXECINSTR
)) ==
10348 (SHF_ALLOC
| SHF_EXECINSTR
))
10349 set_pages_executable(s
->data
, s
->data_offset
);
10354 /* launch the compiled program with the given arguments */
10355 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
10357 int (*prog_main
)(int, char **);
10359 if (tcc_relocate(s1
) < 0)
10362 prog_main
= tcc_get_symbol_err(s1
, "main");
10365 #if defined(_WIN32) || defined(CONFIG_TCCBOOT)
10366 error("debug mode currently not available for Windows");
10368 struct sigaction sigact
;
10369 /* install TCC signal handlers to print debug info on fatal
10371 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
10372 sigact
.sa_sigaction
= sig_error
;
10373 sigemptyset(&sigact
.sa_mask
);
10374 sigaction(SIGFPE
, &sigact
, NULL
);
10375 sigaction(SIGILL
, &sigact
, NULL
);
10376 sigaction(SIGSEGV
, &sigact
, NULL
);
10377 sigaction(SIGBUS
, &sigact
, NULL
);
10378 sigaction(SIGABRT
, &sigact
, NULL
);
10382 #ifdef CONFIG_TCC_BCHECK
10383 if (do_bounds_check
) {
10384 void (*bound_init
)(void);
10386 /* set error function */
10387 rt_bound_error_msg
= (void *)tcc_get_symbol_err(s1
,
10388 "__bound_error_msg");
10390 /* XXX: use .init section so that it also work in binary ? */
10391 bound_init
= (void *)tcc_get_symbol_err(s1
, "__bound_init");
10395 return (*prog_main
)(argc
, argv
);
10398 void tcc_memstats(void)
10401 printf("memory in use: %d\n", mem_cur_size
);
10405 static void tcc_cleanup(void)
10409 if (NULL
== tcc_state
)
10413 /* free -D defines */
10414 free_defines(NULL
);
10417 n
= tok_ident
- TOK_IDENT
;
10418 for(i
= 0; i
< n
; i
++)
10419 tcc_free(table_ident
[i
]);
10420 tcc_free(table_ident
);
10422 /* free sym_pools */
10423 dynarray_reset(&sym_pools
, &nb_sym_pools
);
10424 /* string buffer */
10425 cstr_free(&tokcstr
);
10426 /* reset symbol stack */
10427 sym_free_first
= NULL
;
10428 /* cleanup from error/setjmp */
10432 TCCState
*tcc_new(void)
10441 s
= tcc_mallocz(sizeof(TCCState
));
10445 s
->output_type
= TCC_OUTPUT_MEMORY
;
10447 /* init isid table */
10448 for(i
=CH_EOF
;i
<256;i
++)
10449 isidnum_table
[i
-CH_EOF
] = isid(i
) || isnum(i
);
10451 /* add all tokens */
10452 table_ident
= NULL
;
10453 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
10455 tok_ident
= TOK_IDENT
;
10464 ts
= tok_alloc(p
, r
- p
- 1);
10468 /* we add dummy defines for some special macros to speed up tests
10469 and to have working defined() */
10470 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
10471 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
10472 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
10473 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
10475 /* standard defines */
10476 tcc_define_symbol(s
, "__STDC__", NULL
);
10477 tcc_define_symbol(s
, "__STDC_VERSION__", "199901L");
10478 #if defined(TCC_TARGET_I386)
10479 tcc_define_symbol(s
, "__i386__", NULL
);
10481 #if defined(TCC_TARGET_X86_64)
10482 tcc_define_symbol(s
, "__x86_64__", NULL
);
10484 #if defined(TCC_TARGET_ARM)
10485 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
10486 tcc_define_symbol(s
, "__arm_elf__", NULL
);
10487 tcc_define_symbol(s
, "__arm_elf", NULL
);
10488 tcc_define_symbol(s
, "arm_elf", NULL
);
10489 tcc_define_symbol(s
, "__arm__", NULL
);
10490 tcc_define_symbol(s
, "__arm", NULL
);
10491 tcc_define_symbol(s
, "arm", NULL
);
10492 tcc_define_symbol(s
, "__APCS_32__", NULL
);
10494 #ifdef TCC_TARGET_PE
10495 tcc_define_symbol(s
, "_WIN32", NULL
);
10497 tcc_define_symbol(s
, "__unix__", NULL
);
10498 tcc_define_symbol(s
, "__unix", NULL
);
10499 #if defined(__linux)
10500 tcc_define_symbol(s
, "__linux__", NULL
);
10501 tcc_define_symbol(s
, "__linux", NULL
);
10504 /* tiny C specific defines */
10505 tcc_define_symbol(s
, "__TINYC__", NULL
);
10507 /* tiny C & gcc defines */
10508 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
10509 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
10510 #ifdef TCC_TARGET_PE
10511 tcc_define_symbol(s
, "__WCHAR_TYPE__", "unsigned short");
10513 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
10516 #ifndef TCC_TARGET_PE
10517 /* default library paths */
10518 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/local/lib");
10519 tcc_add_library_path(s
, CONFIG_SYSROOT
"/usr/lib");
10520 tcc_add_library_path(s
, CONFIG_SYSROOT
"/lib");
10523 /* no section zero */
10524 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
10526 /* create standard sections */
10527 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
10528 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
10529 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
10531 /* symbols are always generated for linking stage */
10532 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
10534 ".hashtab", SHF_PRIVATE
);
10535 strtab_section
= symtab_section
->link
;
10537 /* private symbol table for dynamic symbols */
10538 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
10540 ".dynhashtab", SHF_PRIVATE
);
10541 s
->alacarte_link
= 1;
10543 #ifdef CHAR_IS_UNSIGNED
10544 s
->char_is_unsigned
= 1;
10546 #if defined(TCC_TARGET_PE) && 0
10547 /* XXX: currently the PE linker is not ready to support that */
10548 s
->leading_underscore
= 1;
10553 void tcc_delete(TCCState
*s1
)
10559 /* free all sections */
10560 for(i
= 1; i
< s1
->nb_sections
; i
++)
10561 free_section(s1
->sections
[i
]);
10562 dynarray_reset(&s1
->sections
, &s1
->nb_sections
);
10564 for(i
= 0; i
< s1
->nb_priv_sections
; i
++)
10565 free_section(s1
->priv_sections
[i
]);
10566 dynarray_reset(&s1
->priv_sections
, &s1
->nb_priv_sections
);
10568 /* free any loaded DLLs */
10569 for ( i
= 0; i
< s1
->nb_loaded_dlls
; i
++) {
10570 DLLReference
*ref
= s1
->loaded_dlls
[i
];
10572 dlclose(ref
->handle
);
10575 /* free loaded dlls array */
10576 dynarray_reset(&s1
->loaded_dlls
, &s1
->nb_loaded_dlls
);
10578 /* free library paths */
10579 dynarray_reset(&s1
->library_paths
, &s1
->nb_library_paths
);
10581 /* free include paths */
10582 dynarray_reset(&s1
->cached_includes
, &s1
->nb_cached_includes
);
10583 dynarray_reset(&s1
->include_paths
, &s1
->nb_include_paths
);
10584 dynarray_reset(&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
);
10589 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
10593 pathname1
= tcc_strdup(pathname
);
10594 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
10598 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
10602 pathname1
= tcc_strdup(pathname
);
10603 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
10607 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
10612 BufferedFile
*saved_file
;
10614 /* find source file type with extension */
10615 ext
= tcc_fileextension(filename
);
10619 /* open the file */
10621 file
= tcc_open(s1
, filename
);
10623 if (flags
& AFF_PRINT_ERROR
) {
10624 error_noabort("file '%s' not found", filename
);
10630 if (flags
& AFF_PREPROCESS
) {
10631 ret
= tcc_preprocess(s1
);
10632 } else if (!ext
[0] || !strcmp(ext
, "c")) {
10633 /* C file assumed */
10634 ret
= tcc_compile(s1
);
10636 #ifdef CONFIG_TCC_ASM
10637 if (!strcmp(ext
, "S")) {
10638 /* preprocessed assembler */
10639 ret
= tcc_assemble(s1
, 1);
10640 } else if (!strcmp(ext
, "s")) {
10641 /* non preprocessed assembler */
10642 ret
= tcc_assemble(s1
, 0);
10645 #ifdef TCC_TARGET_PE
10646 if (!strcmp(ext
, "def")) {
10647 ret
= pe_load_def_file(s1
, file
->fd
);
10652 /* assume executable format: auto guess file type */
10653 ret
= read(fd
, &ehdr
, sizeof(ehdr
));
10654 lseek(fd
, 0, SEEK_SET
);
10656 error_noabort("could not read header");
10658 } else if (ret
!= sizeof(ehdr
)) {
10659 goto try_load_script
;
10662 if (ehdr
.e_ident
[0] == ELFMAG0
&&
10663 ehdr
.e_ident
[1] == ELFMAG1
&&
10664 ehdr
.e_ident
[2] == ELFMAG2
&&
10665 ehdr
.e_ident
[3] == ELFMAG3
) {
10666 file
->line_num
= 0; /* do not display line number if error */
10667 if (ehdr
.e_type
== ET_REL
) {
10668 ret
= tcc_load_object_file(s1
, fd
, 0);
10669 } else if (ehdr
.e_type
== ET_DYN
) {
10670 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
10671 #ifdef TCC_TARGET_PE
10675 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
10682 ret
= tcc_load_dll(s1
, fd
, filename
,
10683 (flags
& AFF_REFERENCED_DLL
) != 0);
10686 error_noabort("unrecognized ELF file");
10689 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
10690 file
->line_num
= 0; /* do not display line number if error */
10691 ret
= tcc_load_archive(s1
, fd
);
10693 #ifdef TCC_TARGET_COFF
10694 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
10695 ret
= tcc_load_coff(s1
, fd
);
10698 #ifdef TCC_TARGET_PE
10699 if (pe_test_res_file(&ehdr
, ret
)) {
10700 ret
= pe_load_res_file(s1
, fd
);
10704 /* as GNU ld, consider it is an ld script if not recognized */
10706 ret
= tcc_load_ldscript(s1
);
10708 error_noabort("unrecognized file type");
10723 int tcc_add_file(TCCState
*s
, const char *filename
)
10725 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
10728 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
10732 pathname1
= tcc_strdup(pathname
);
10733 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
10737 /* find and load a dll. Return non zero if not found */
10738 /* XXX: add '-rpath' option support ? */
10739 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
10744 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10745 snprintf(buf
, sizeof(buf
), "%s/%s",
10746 s
->library_paths
[i
], filename
);
10747 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
10753 /* the library name is the same as the argument of the '-l' option */
10754 int tcc_add_library(TCCState
*s
, const char *libraryname
)
10759 /* first we look for the dynamic library if not static linking */
10760 if (!s
->static_link
) {
10761 #ifdef TCC_TARGET_PE
10762 snprintf(buf
, sizeof(buf
), "%s.def", libraryname
);
10764 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
10766 if (tcc_add_dll(s
, buf
, 0) == 0)
10770 /* then we look for the static library */
10771 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10772 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
10773 s
->library_paths
[i
], libraryname
);
10774 if (tcc_add_file_internal(s
, buf
, 0) == 0)
10780 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
10782 add_elf_sym(symtab_section
, val
, 0,
10783 ELFW(ST_INFO
)(STB_GLOBAL
, STT_NOTYPE
), 0,
10788 int tcc_set_output_type(TCCState
*s
, int output_type
)
10792 s
->output_type
= output_type
;
10794 if (!s
->nostdinc
) {
10795 /* default include paths */
10796 /* XXX: reverse order needed if -isystem support */
10797 #ifndef TCC_TARGET_PE
10798 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/local/include");
10799 tcc_add_sysinclude_path(s
, CONFIG_SYSROOT
"/usr/include");
10801 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
10802 tcc_add_sysinclude_path(s
, buf
);
10803 #ifdef TCC_TARGET_PE
10804 snprintf(buf
, sizeof(buf
), "%s/include/winapi", tcc_lib_path
);
10805 tcc_add_sysinclude_path(s
, buf
);
10809 /* if bound checking, then add corresponding sections */
10810 #ifdef CONFIG_TCC_BCHECK
10811 if (do_bounds_check
) {
10812 /* define symbol */
10813 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
10814 /* create bounds sections */
10815 bounds_section
= new_section(s
, ".bounds",
10816 SHT_PROGBITS
, SHF_ALLOC
);
10817 lbounds_section
= new_section(s
, ".lbounds",
10818 SHT_PROGBITS
, SHF_ALLOC
);
10822 if (s
->char_is_unsigned
) {
10823 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
10826 /* add debug sections */
10829 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
10830 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
10831 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
10832 put_elf_str(stabstr_section
, "");
10833 stab_section
->link
= stabstr_section
;
10834 /* put first entry */
10835 put_stabs("", 0, 0, 0, 0);
10838 /* add libc crt1/crti objects */
10839 #ifndef TCC_TARGET_PE
10840 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
10842 if (output_type
!= TCC_OUTPUT_DLL
)
10843 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
10844 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
10848 #ifdef TCC_TARGET_PE
10849 snprintf(buf
, sizeof(buf
), "%s/lib", tcc_lib_path
);
10850 tcc_add_library_path(s
, buf
);
10856 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
10857 #define FD_INVERT 0x0002 /* invert value before storing */
10859 typedef struct FlagDef
{
10865 static const FlagDef warning_defs
[] = {
10866 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
10867 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
10868 { offsetof(TCCState
, warn_error
), 0, "error" },
10869 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
10870 "implicit-function-declaration" },
10873 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
10874 const char *name
, int value
)
10881 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
10885 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
10886 if (!strcmp(r
, p
->name
))
10891 if (p
->flags
& FD_INVERT
)
10893 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
10898 /* set/reset a warning */
10899 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
10904 if (!strcmp(warning_name
, "all")) {
10905 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
10906 if (p
->flags
& WD_ALL
)
10907 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
10911 return set_flag(s
, warning_defs
, countof(warning_defs
),
10912 warning_name
, value
);
10916 static const FlagDef flag_defs
[] = {
10917 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
10918 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
10919 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
10920 { offsetof(TCCState
, leading_underscore
), 0, "leading-underscore" },
10923 /* set/reset a flag */
10924 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
10926 return set_flag(s
, flag_defs
, countof(flag_defs
),
10930 #if !defined(LIBTCC)
10932 static int64_t getclock_us(void)
10937 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
10940 gettimeofday(&tv
, NULL
);
10941 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
10947 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard\n"
10948 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
10949 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-soname name]\n"
10950 " [-static] [infile1 infile2...] [-run infile args...]\n"
10952 "General options:\n"
10953 " -v display current version, increase verbosity\n"
10954 " -c compile only - generate an object file\n"
10955 " -o outfile set output filename\n"
10956 " -Bdir set tcc internal library path\n"
10957 " -bench output compilation statistics\n"
10958 " -run run compiled source\n"
10959 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
10960 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
10961 " -w disable all warnings\n"
10962 "Preprocessor options:\n"
10963 " -E preprocess only\n"
10964 " -Idir add include path 'dir'\n"
10965 " -Dsym[=val] define 'sym' with value 'val'\n"
10966 " -Usym undefine 'sym'\n"
10967 "Linker options:\n"
10968 " -Ldir add library path 'dir'\n"
10969 " -llib link with dynamic or static library 'lib'\n"
10970 " -shared generate a shared library\n"
10971 " -soname set name for shared library to be used at runtime\n"
10972 " -static static linking\n"
10973 " -rdynamic export all global symbols to dynamic linker\n"
10974 " -r generate (relocatable) object file\n"
10975 "Debugger options:\n"
10976 " -g generate runtime debug info\n"
10977 #ifdef CONFIG_TCC_BCHECK
10978 " -b compile with built-in memory and bounds checker (implies -g)\n"
10980 " -bt N show N callers in stack traces\n"
10984 #define TCC_OPTION_HAS_ARG 0x0001
10985 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
10987 typedef struct TCCOption
{
11016 TCC_OPTION_nostdinc
,
11017 TCC_OPTION_nostdlib
,
11018 TCC_OPTION_print_search_dirs
,
11019 TCC_OPTION_rdynamic
,
11027 static const TCCOption tcc_options
[] = {
11028 { "h", TCC_OPTION_HELP
, 0 },
11029 { "?", TCC_OPTION_HELP
, 0 },
11030 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
11031 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
11032 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
11033 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
11034 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
11035 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11036 { "bench", TCC_OPTION_bench
, 0 },
11037 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
11038 #ifdef CONFIG_TCC_BCHECK
11039 { "b", TCC_OPTION_b
, 0 },
11041 { "g", TCC_OPTION_g
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11042 { "c", TCC_OPTION_c
, 0 },
11043 { "static", TCC_OPTION_static
, 0 },
11044 { "shared", TCC_OPTION_shared
, 0 },
11045 { "soname", TCC_OPTION_soname
, TCC_OPTION_HAS_ARG
},
11046 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
11047 { "run", TCC_OPTION_run
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11048 { "rdynamic", TCC_OPTION_rdynamic
, 0 },
11049 { "r", TCC_OPTION_r
, 0 },
11050 { "Wl,", TCC_OPTION_Wl
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11051 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11052 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11053 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
11054 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11055 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
11056 { "nostdlib", TCC_OPTION_nostdlib
, 0 },
11057 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
11058 { "v", TCC_OPTION_v
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
11059 { "w", TCC_OPTION_w
, 0 },
11060 { "pipe", TCC_OPTION_pipe
, 0},
11061 { "E", TCC_OPTION_E
, 0},
11065 /* convert 'str' into an array of space separated strings */
11066 static int expand_args(char ***pargv
, const char *str
)
11075 while (is_space(*str
))
11080 while (*str
!= '\0' && !is_space(*str
))
11083 arg
= tcc_malloc(len
+ 1);
11084 memcpy(arg
, s1
, len
);
11086 dynarray_add((void ***)&argv
, &argc
, arg
);
11092 static char **files
;
11093 static int nb_files
, nb_libraries
;
11094 static int multiple_files
;
11095 static int print_search_dirs
;
11096 static int output_type
;
11097 static int reloc_output
;
11098 static const char *outfile
;
11100 int parse_args(TCCState
*s
, int argc
, char **argv
)
11103 const TCCOption
*popt
;
11104 const char *optarg
, *p1
, *r1
;
11108 while (optind
< argc
) {
11110 r
= argv
[optind
++];
11111 if (r
[0] != '-' || r
[1] == '\0') {
11112 /* add a new file */
11113 dynarray_add((void ***)&files
, &nb_files
, r
);
11114 if (!multiple_files
) {
11116 /* argv[0] will be this file */
11120 /* find option in table (match only the first chars */
11121 popt
= tcc_options
;
11125 error("invalid option -- '%s'", r
);
11138 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
11139 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
11142 if (optind
>= argc
)
11143 error("argument to '%s' is missing", r
);
11144 optarg
= argv
[optind
++];
11152 switch(popt
->index
) {
11153 case TCC_OPTION_HELP
:
11157 if (tcc_add_include_path(s
, optarg
) < 0)
11158 error("too many include paths");
11163 sym
= (char *)optarg
;
11164 value
= strchr(sym
, '=');
11169 tcc_define_symbol(s
, sym
, value
);
11173 tcc_undefine_symbol(s
, optarg
);
11176 tcc_add_library_path(s
, optarg
);
11179 /* set tcc utilities path (mainly for tcc development) */
11180 tcc_lib_path
= optarg
;
11183 dynarray_add((void ***)&files
, &nb_files
, r
);
11186 case TCC_OPTION_bench
:
11189 case TCC_OPTION_bt
:
11190 num_callers
= atoi(optarg
);
11192 #ifdef CONFIG_TCC_BCHECK
11194 do_bounds_check
= 1;
11202 multiple_files
= 1;
11203 output_type
= TCC_OUTPUT_OBJ
;
11205 case TCC_OPTION_static
:
11206 s
->static_link
= 1;
11208 case TCC_OPTION_shared
:
11209 output_type
= TCC_OUTPUT_DLL
;
11211 case TCC_OPTION_soname
:
11212 s
->soname
= optarg
;
11215 multiple_files
= 1;
11219 /* generate a .o merging several output files */
11221 output_type
= TCC_OUTPUT_OBJ
;
11223 case TCC_OPTION_nostdinc
:
11226 case TCC_OPTION_nostdlib
:
11229 case TCC_OPTION_print_search_dirs
:
11230 print_search_dirs
= 1;
11232 case TCC_OPTION_run
:
11236 argc1
= expand_args(&argv1
, optarg
);
11238 parse_args(s
, argc1
, argv1
);
11240 multiple_files
= 0;
11241 output_type
= TCC_OUTPUT_MEMORY
;
11246 if (0 == verbose
++)
11247 printf("tcc version %s\n", TCC_VERSION
);
11248 } while (*optarg
++ == 'v');
11251 if (tcc_set_flag(s
, optarg
, 1) < 0 && s
->warn_unsupported
)
11252 goto unsupported_option
;
11255 if (tcc_set_warning(s
, optarg
, 1) < 0 &&
11256 s
->warn_unsupported
)
11257 goto unsupported_option
;
11262 case TCC_OPTION_rdynamic
:
11265 case TCC_OPTION_Wl
:
11268 if (strstart(optarg
, "-Ttext,", &p
)) {
11269 s
->text_addr
= strtoul(p
, NULL
, 16);
11270 s
->has_text_addr
= 1;
11271 } else if (strstart(optarg
, "--oformat,", &p
)) {
11272 if (strstart(p
, "elf32-", NULL
)) {
11273 s
->output_format
= TCC_OUTPUT_FORMAT_ELF
;
11274 } else if (!strcmp(p
, "binary")) {
11275 s
->output_format
= TCC_OUTPUT_FORMAT_BINARY
;
11277 #ifdef TCC_TARGET_COFF
11278 if (!strcmp(p
, "coff")) {
11279 s
->output_format
= TCC_OUTPUT_FORMAT_COFF
;
11283 error("target %s not found", p
);
11286 error("unsupported linker option '%s'", optarg
);
11291 output_type
= TCC_OUTPUT_PREPROCESS
;
11294 if (s
->warn_unsupported
) {
11295 unsupported_option
:
11296 warning("unsupported option '%s'", r
);
11305 int main(int argc
, char **argv
)
11309 int nb_objfiles
, ret
, optind
;
11310 char objfilename
[1024];
11311 int64_t start_time
= 0;
11314 tcc_lib_path
= w32_tcc_lib_path();
11318 output_type
= TCC_OUTPUT_EXE
;
11320 multiple_files
= 1;
11325 print_search_dirs
= 0;
11328 optind
= parse_args(s
, argc
- 1, argv
+ 1);
11329 if (print_search_dirs
) {
11330 /* enough for Linux kernel */
11331 printf("install: %s/\n", tcc_lib_path
);
11334 if (optind
== 0 || nb_files
== 0) {
11335 if (optind
&& verbose
)
11341 nb_objfiles
= nb_files
- nb_libraries
;
11343 /* if outfile provided without other options, we output an
11345 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
11346 output_type
= TCC_OUTPUT_EXE
;
11348 /* check -c consistency : only single file handled. XXX: checks file type */
11349 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
11350 /* accepts only a single input file */
11351 if (nb_objfiles
!= 1)
11352 error("cannot specify multiple files with -c");
11353 if (nb_libraries
!= 0)
11354 error("cannot specify libraries with -c");
11358 if (output_type
== TCC_OUTPUT_PREPROCESS
) {
11360 s
->outfile
= stdout
;
11362 s
->outfile
= fopen(outfile
, "w");
11364 error("could not open '%s", outfile
);
11366 } else if (output_type
!= TCC_OUTPUT_MEMORY
) {
11368 /* compute default outfile name */
11371 strcmp(files
[0], "-") == 0 ? "a" : tcc_basename(files
[0]);
11372 pstrcpy(objfilename
, sizeof(objfilename
), name
);
11373 ext
= tcc_fileextension(objfilename
);
11374 #ifdef TCC_TARGET_PE
11375 if (output_type
== TCC_OUTPUT_DLL
)
11376 strcpy(ext
, ".dll");
11378 if (output_type
== TCC_OUTPUT_EXE
)
11379 strcpy(ext
, ".exe");
11382 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
&& *ext
)
11385 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
11386 outfile
= objfilename
;
11391 start_time
= getclock_us();
11394 tcc_set_output_type(s
, output_type
);
11396 /* compile or add each files or library */
11397 for(i
= 0; i
< nb_files
&& ret
== 0; i
++) {
11398 const char *filename
;
11400 filename
= files
[i
];
11401 if (output_type
== TCC_OUTPUT_PREPROCESS
) {
11402 if (tcc_add_file_internal(s
, filename
,
11403 AFF_PRINT_ERROR
| AFF_PREPROCESS
) < 0)
11405 } else if (filename
[0] == '-' && filename
[1]) {
11406 if (tcc_add_library(s
, filename
+ 2) < 0)
11407 error("cannot find %s", filename
);
11410 printf("-> %s\n", filename
);
11411 if (tcc_add_file(s
, filename
) < 0)
11416 /* free all files */
11424 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
11425 if (total_time
< 0.001)
11426 total_time
= 0.001;
11427 if (total_bytes
< 1)
11429 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
11430 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
11431 total_time
, (int)(total_lines
/ total_time
),
11432 total_bytes
/ total_time
/ 1000000.0);
11435 if (s
->output_type
== TCC_OUTPUT_PREPROCESS
) {
11437 fclose(s
->outfile
);
11438 } else if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
11439 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
11441 ret
= tcc_output_file(s
, outfile
) ? 1 : 0;
11443 /* XXX: cannot do it with bound checking because of the malloc hooks */
11444 if (!do_bounds_check
)
11449 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);