2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 #define CONFIG_TCC_STATIC
42 #include <sys/timeb.h>
43 // #include <windows.h>
47 #include <sys/ucontext.h>
51 #endif /* !CONFIG_TCCBOOT */
68 /* preprocessor debug */
70 /* include file debug */
78 /* target selection */
79 //#define TCC_TARGET_I386 /* i386 code generator */
80 //#define TCC_TARGET_ARM /* ARMv4 code generator */
81 //#define TCC_TARGET_C67 /* TMS320C67xx code generator */
83 /* default target is I386 */
84 #if !defined(TCC_TARGET_I386) && !defined(TCC_TARGET_ARM) && \
85 !defined(TCC_TARGET_C67)
86 #define TCC_TARGET_I386
89 #if !defined(WIN32) && !defined(TCC_UCLIBC) && !defined(TCC_TARGET_ARM) && \
90 !defined(TCC_TARGET_C67)
91 #define CONFIG_TCC_BCHECK /* enable bound checking code */
94 #if defined(WIN32) && !defined(TCC_TARGET_PE)
95 #define CONFIG_TCC_STATIC
98 /* define it to include assembler support */
99 #if !defined(TCC_TARGET_ARM) && !defined(TCC_TARGET_C67)
100 #define CONFIG_TCC_ASM
103 /* object format selection */
104 #if defined(TCC_TARGET_C67)
105 #define TCC_TARGET_COFF
114 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
115 executables or dlls */
116 #define CONFIG_TCC_CRT_PREFIX "/usr/lib"
118 #define INCLUDE_STACK_SIZE 32
119 #define IFDEF_STACK_SIZE 64
120 #define VSTACK_SIZE 256
121 #define STRING_MAX_SIZE 1024
122 #define PACK_STACK_SIZE 8
124 #define TOK_HASH_SIZE 8192 /* must be a power of two */
125 #define TOK_ALLOC_INCR 512 /* must be a power of two */
126 #define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
128 /* token symbol management */
129 typedef struct TokenSym
{
130 struct TokenSym
*hash_next
;
131 struct Sym
*sym_define
; /* direct pointer to define */
132 struct Sym
*sym_label
; /* direct pointer to label */
133 struct Sym
*sym_struct
; /* direct pointer to structure */
134 struct Sym
*sym_identifier
; /* direct pointer to identifier */
135 int tok
; /* token number */
141 typedef unsigned short nwchar_t
;
143 typedef int nwchar_t
;
146 typedef struct CString
{
147 int size
; /* size in bytes */
148 void *data
; /* either 'char *' or 'nwchar_t *' */
150 void *data_allocated
; /* if non NULL, data has been malloced */
153 /* type definition */
154 typedef struct CType
{
160 typedef union CValue
{
166 unsigned int ul
; /* address (should be unsigned long on 64 bit cpu) */
168 unsigned long long ull
;
169 struct CString
*cstr
;
175 typedef struct SValue
{
176 CType type
; /* type */
177 unsigned short r
; /* register + flags */
178 unsigned short r2
; /* second register, used for 'long long'
179 type. If not used, set to VT_CONST */
180 CValue c
; /* constant, if VT_CONST */
181 struct Sym
*sym
; /* symbol, if (VT_SYM | VT_CONST) */
184 /* symbol management */
186 int v
; /* symbol token */
187 int r
; /* associated register */
188 int c
; /* associated number */
189 CType type
; /* associated type */
190 struct Sym
*next
; /* next related symbol */
191 struct Sym
*prev
; /* prev symbol in stack */
192 struct Sym
*prev_tok
; /* previous symbol for this token */
195 /* section definition */
196 /* XXX: use directly ELF structure for parameters ? */
197 /* special flag to indicate that the section should not be linked to
199 #define SHF_PRIVATE 0x80000000
201 typedef struct Section
{
202 unsigned long data_offset
; /* current data offset */
203 unsigned char *data
; /* section data */
204 unsigned long data_allocated
; /* used for realloc() handling */
205 int sh_name
; /* elf section name (only used during output) */
206 int sh_num
; /* elf section number */
207 int sh_type
; /* elf section type */
208 int sh_flags
; /* elf section flags */
209 int sh_info
; /* elf section info */
210 int sh_addralign
; /* elf section alignment */
211 int sh_entsize
; /* elf entry size */
212 unsigned long sh_size
; /* section size (only used during output) */
213 unsigned long sh_addr
; /* address at which the section is relocated */
214 unsigned long sh_offset
; /* file offset */
215 int nb_hashed_syms
; /* used to resize the hash table */
216 struct Section
*link
; /* link to another section */
217 struct Section
*reloc
; /* corresponding section for relocation, if any */
218 struct Section
*hash
; /* hash table for symbols */
219 struct Section
*next
;
220 char name
[1]; /* section name */
223 typedef struct DLLReference
{
228 /* GNUC attribute definition */
229 typedef struct AttributeDef
{
233 unsigned char func_call
; /* FUNC_CDECL, FUNC_STDCALL, FUNC_FASTCALLx */
234 unsigned char dllexport
;
237 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
238 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
239 #define SYM_FIRST_ANOM 0x10000000 /* first anonymous sym */
241 /* stored in 'Sym.c' field */
242 #define FUNC_NEW 1 /* ansi function prototype */
243 #define FUNC_OLD 2 /* old function prototype */
244 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
246 /* stored in 'Sym.r' field */
247 #define FUNC_CDECL 0 /* standard c call */
248 #define FUNC_STDCALL 1 /* pascal c call */
249 #define FUNC_FASTCALL1 2 /* first param in %eax */
250 #define FUNC_FASTCALL2 3 /* first parameters in %eax, %edx */
251 #define FUNC_FASTCALL3 4 /* first parameter in %eax, %edx, %ecx */
252 #define FUNC_FASTCALLW 5 /* first parameter in %ecx, %edx */
254 /* field 'Sym.t' for macros */
255 #define MACRO_OBJ 0 /* object like macro */
256 #define MACRO_FUNC 1 /* function like macro */
258 /* field 'Sym.r' for C labels */
259 #define LABEL_DEFINED 0 /* label is defined */
260 #define LABEL_FORWARD 1 /* label is forward defined */
261 #define LABEL_DECLARED 2 /* label is declared but never used */
263 /* type_decl() types */
264 #define TYPE_ABSTRACT 1 /* type without variable */
265 #define TYPE_DIRECT 2 /* type with variable */
267 #define IO_BUF_SIZE 8192
269 typedef struct BufferedFile
{
273 int line_num
; /* current line number - here to simplify code */
274 int ifndef_macro
; /* #ifndef macro / #endif search */
275 int ifndef_macro_saved
; /* saved ifndef_macro */
276 int *ifdef_stack_ptr
; /* ifdef_stack value at the start of the file */
277 char inc_type
; /* type of include */
278 char inc_filename
[512]; /* filename specified by the user */
279 char filename
[1024]; /* current filename - here to simplify code */
280 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
283 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
284 #define CH_EOF (-1) /* end of file */
286 /* parsing state (used to save parser state to reparse part of the
287 source several times) */
288 typedef struct ParseState
{
295 /* used to record tokens */
296 typedef struct TokenString
{
303 /* include file cache, used to find files faster and also to eliminate
304 inclusion if the include file is protected by #ifndef ... #endif */
305 typedef struct CachedInclude
{
307 int hash_next
; /* -1 if none */
308 char type
; /* '"' or '>' to give include type */
309 char filename
[1]; /* path specified in #include */
312 #define CACHED_INCLUDES_HASH_SIZE 512
315 static struct BufferedFile
*file
;
318 static CString tokcstr
; /* current parsed string, if any */
319 /* additional informations about token */
320 static int tok_flags
;
321 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
322 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
323 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
325 static int *macro_ptr
, *macro_ptr_allocated
;
326 static int *unget_saved_macro_ptr
;
327 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
328 static int unget_buffer_enabled
;
329 static int parse_flags
;
330 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
331 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
332 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
333 token. line feed is also
335 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
337 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
338 static Section
*cur_text_section
; /* current section where function code is
340 #ifdef CONFIG_TCC_ASM
341 static Section
*last_text_section
; /* to handle .previous asm directive */
343 /* bound check related sections */
344 static Section
*bounds_section
; /* contains global data bound description */
345 static Section
*lbounds_section
; /* contains local data bound description */
346 /* symbol sections */
347 static Section
*symtab_section
, *strtab_section
;
350 static Section
*stab_section
, *stabstr_section
;
352 /* loc : local variable index
353 ind : output code index
355 anon_sym: anonymous symbol index
357 static int rsym
, anon_sym
, ind
, loc
;
358 /* expression generation modifiers */
359 static int const_wanted
; /* true if constant wanted */
360 static int nocode_wanted
; /* true if no code generation wanted for an expression */
361 static int global_expr
; /* true if compound literals must be allocated
362 globally (used during initializers parsing */
363 static CType func_vt
; /* current function return type (used by return
366 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
367 static int tok_ident
;
368 static TokenSym
**table_ident
;
369 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
370 static char token_buf
[STRING_MAX_SIZE
+ 1];
371 static char *funcname
;
372 static Sym
*global_stack
, *local_stack
;
373 static Sym
*define_stack
;
374 static Sym
*global_label_stack
, *local_label_stack
;
375 /* symbol allocator */
376 #define SYM_POOL_NB (8192 / sizeof(Sym))
377 static Sym
*sym_free_first
;
379 static SValue vstack
[VSTACK_SIZE
], *vtop
;
380 /* some predefined types */
381 static CType char_pointer_type
, func_old_type
, int_type
;
382 /* true if isid(c) || isnum(c) */
383 static unsigned char isidnum_table
[256];
385 /* compile with debug symbol (and use them if error during execution) */
386 static int do_debug
= 0;
388 /* compile with built-in memory and bounds checker */
389 static int do_bounds_check
= 0;
391 /* display benchmark infos */
393 static int do_bench
= 0;
395 static int total_lines
;
396 static int total_bytes
;
398 /* use GNU C extensions */
399 static int gnu_ext
= 1;
401 /* use Tiny C extensions */
402 static int tcc_ext
= 1;
404 /* max number of callers shown if error */
405 static int num_callers
= 6;
406 static const char **rt_bound_error_msg
;
408 /* XXX: get rid of this ASAP */
409 static struct TCCState
*tcc_state
;
411 /* give the path of the tcc libraries */
412 static const char *tcc_lib_path
= CONFIG_TCCDIR
;
417 BufferedFile
**include_stack_ptr
;
418 int *ifdef_stack_ptr
;
420 /* include file handling */
421 char **include_paths
;
422 int nb_include_paths
;
423 char **sysinclude_paths
;
424 int nb_sysinclude_paths
;
425 CachedInclude
**cached_includes
;
426 int nb_cached_includes
;
428 char **library_paths
;
429 int nb_library_paths
;
431 /* array of all loaded dlls (including those referenced by loaded
433 DLLReference
**loaded_dlls
;
438 int nb_sections
; /* number of sections, including first dummy section */
443 unsigned long *got_offsets
;
445 /* give the correspondance from symtab indexes to dynsym indexes */
446 int *symtab_to_dynsym
;
448 /* temporary dynamic symbol sections (for dll loading) */
449 Section
*dynsymtab_section
;
450 /* exported dynamic symbol section */
453 int nostdinc
; /* if true, no standard headers are added */
454 int nostdlib
; /* if true, no standard libraries are added */
456 int nocommon
; /* if true, do not use common symbols for .bss data */
458 /* if true, static linking is performed */
461 /* if true, all symbols are exported */
464 /* if true, only link in referenced objects from archive */
467 /* address of text section */
468 unsigned long text_addr
;
471 /* output format, see TCC_OUTPUT_FORMAT_xxx */
474 /* C language options */
475 int char_is_unsigned
;
476 int leading_underscore
;
478 /* warning switches */
479 int warn_write_strings
;
480 int warn_unsupported
;
483 int warn_implicit_function_declaration
;
487 void (*error_func
)(void *opaque
, const char *msg
);
488 int error_set_jmp_enabled
;
489 jmp_buf error_jmp_buf
;
492 /* tiny assembler state */
495 /* see include_stack_ptr */
496 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
498 /* see ifdef_stack_ptr */
499 int ifdef_stack
[IFDEF_STACK_SIZE
];
501 /* see cached_includes */
502 int cached_includes_hash
[CACHED_INCLUDES_HASH_SIZE
];
505 int pack_stack
[PACK_STACK_SIZE
];
508 /* output file for preprocessing */
512 /* The current value can be: */
513 #define VT_VALMASK 0x00ff
514 #define VT_CONST 0x00f0 /* constant in vc
515 (must be first non register value) */
516 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
517 #define VT_LOCAL 0x00f2 /* offset on stack */
518 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
519 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
520 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
521 #define VT_LVAL 0x0100 /* var is an lvalue */
522 #define VT_SYM 0x0200 /* a symbol value is added */
523 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
524 char/short stored in integer registers) */
525 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
526 dereferencing value */
527 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
528 bounding function call point is in vc */
529 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
530 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
531 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
532 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
535 #define VT_INT 0 /* integer type */
536 #define VT_BYTE 1 /* signed byte type */
537 #define VT_SHORT 2 /* short type */
538 #define VT_VOID 3 /* void type */
539 #define VT_PTR 4 /* pointer */
540 #define VT_ENUM 5 /* enum definition */
541 #define VT_FUNC 6 /* function type */
542 #define VT_STRUCT 7 /* struct/union definition */
543 #define VT_FLOAT 8 /* IEEE float */
544 #define VT_DOUBLE 9 /* IEEE double */
545 #define VT_LDOUBLE 10 /* IEEE long double */
546 #define VT_BOOL 11 /* ISOC99 boolean type */
547 #define VT_LLONG 12 /* 64 bit integer */
548 #define VT_LONG 13 /* long integer (NEVER USED as type, only
550 #define VT_BTYPE 0x000f /* mask for basic type */
551 #define VT_UNSIGNED 0x0010 /* unsigned type */
552 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
553 #define VT_BITFIELD 0x0040 /* bitfield modifier */
554 #define VT_CONSTANT 0x0800 /* const modifier */
555 #define VT_VOLATILE 0x1000 /* volatile modifier */
556 #define VT_SIGNED 0x2000 /* signed type */
559 #define VT_EXTERN 0x00000080 /* extern definition */
560 #define VT_STATIC 0x00000100 /* static variable */
561 #define VT_TYPEDEF 0x00000200 /* typedef definition */
562 #define VT_INLINE 0x00000400 /* inline definition */
564 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
566 /* type mask (except storage) */
567 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
568 #define VT_TYPE (~(VT_STORAGE))
572 /* warning: the following compare tokens depend on i386 asm code */
584 #define TOK_LAND 0xa0
588 #define TOK_MID 0xa3 /* inc/dec, to void constant */
590 #define TOK_UDIV 0xb0 /* unsigned division */
591 #define TOK_UMOD 0xb1 /* unsigned modulo */
592 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
593 #define TOK_CINT 0xb3 /* number in tokc */
594 #define TOK_CCHAR 0xb4 /* char constant in tokc */
595 #define TOK_STR 0xb5 /* pointer to string in tokc */
596 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
597 #define TOK_LCHAR 0xb7
598 #define TOK_LSTR 0xb8
599 #define TOK_CFLOAT 0xb9 /* float constant */
600 #define TOK_LINENUM 0xba /* line number info */
601 #define TOK_CDOUBLE 0xc0 /* double constant */
602 #define TOK_CLDOUBLE 0xc1 /* long double constant */
603 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
604 #define TOK_ADDC1 0xc3 /* add with carry generation */
605 #define TOK_ADDC2 0xc4 /* add with carry use */
606 #define TOK_SUBC1 0xc5 /* add with carry generation */
607 #define TOK_SUBC2 0xc6 /* add with carry use */
608 #define TOK_CUINT 0xc8 /* unsigned int constant */
609 #define TOK_CLLONG 0xc9 /* long long constant */
610 #define TOK_CULLONG 0xca /* unsigned long long constant */
611 #define TOK_ARROW 0xcb
612 #define TOK_DOTS 0xcc /* three dots */
613 #define TOK_SHR 0xcd /* unsigned shift right */
614 #define TOK_PPNUM 0xce /* preprocessor number */
616 #define TOK_SHL 0x01 /* shift left */
617 #define TOK_SAR 0x02 /* signed shift right */
619 /* assignement operators : normal operator or 0x80 */
620 #define TOK_A_MOD 0xa5
621 #define TOK_A_AND 0xa6
622 #define TOK_A_MUL 0xaa
623 #define TOK_A_ADD 0xab
624 #define TOK_A_SUB 0xad
625 #define TOK_A_DIV 0xaf
626 #define TOK_A_XOR 0xde
627 #define TOK_A_OR 0xfc
628 #define TOK_A_SHL 0x81
629 #define TOK_A_SAR 0x82
632 #define offsetof(type, field) ((size_t) &((type *)0)->field)
636 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
639 /* WARNING: the content of this string encodes token numbers */
640 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";
642 #define TOK_EOF (-1) /* end of file */
643 #define TOK_LINEFEED 10 /* line feed */
645 /* all identificators and strings have token above that */
646 #define TOK_IDENT 256
648 /* only used for i386 asm opcodes definitions */
649 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
652 DEF(TOK_ASM_ ## x ## b, #x "b") \
653 DEF(TOK_ASM_ ## x ## w, #x "w") \
654 DEF(TOK_ASM_ ## x ## l, #x "l") \
655 DEF(TOK_ASM_ ## x, #x)
658 DEF(TOK_ASM_ ## x ## w, #x "w") \
659 DEF(TOK_ASM_ ## x ## l, #x "l") \
660 DEF(TOK_ASM_ ## x, #x)
663 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
664 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
665 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
666 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
669 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
670 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
673 #define DEF_ASMTEST(x) \
705 #define TOK_ASM_int TOK_INT
708 TOK_LAST
= TOK_IDENT
- 1,
709 #define DEF(id, str) id,
714 static const char tcc_keywords
[] =
715 #define DEF(id, str) str "\0"
720 #define TOK_UIDENT TOK_DEFINE
723 int __stdcall
GetModuleFileNameA(void *, char *, int);
724 void *__stdcall
GetProcAddress(void *, const char *);
725 void *__stdcall
GetModuleHandleA(const char *);
726 void *__stdcall
LoadLibraryA(const char *);
727 int __stdcall
FreeConsole(void);
728 int __stdcall
VirtualProtect(void*,unsigned long,unsigned long,unsigned long*);
729 #define PAGE_EXECUTE_READWRITE 0x0040
731 #define snprintf _snprintf
732 #define vsnprintf _vsnprintf
734 #define strtold (long double)strtod
735 #define strtof (float)strtod
736 #define strtoll (long long)strtol
738 #elif defined(TCC_UCLIBC) || defined(__FreeBSD__)
739 /* currently incorrect */
740 long double strtold(const char *nptr
, char **endptr
)
742 return (long double)strtod(nptr
, endptr
);
744 float strtof(const char *nptr
, char **endptr
)
746 return (float)strtod(nptr
, endptr
);
749 /* XXX: need to define this to use them in non ISOC99 context */
750 extern float strtof (const char *__nptr
, char **__endptr
);
751 extern long double strtold (const char *__nptr
, char **__endptr
);
754 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
755 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
756 static char *tcc_basename(const char *name
);
758 static void next(void);
759 static void next_nomacro(void);
760 static void parse_expr_type(CType
*type
);
761 static void expr_type(CType
*type
);
762 static void unary_type(CType
*type
);
763 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
764 int case_reg
, int is_expr
);
765 static int expr_const(void);
766 static void expr_eq(void);
767 static void gexpr(void);
768 static void gen_inline_functions(void);
769 static void decl(int l
);
770 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
771 int first
, int size_only
);
772 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
773 int has_init
, int v
, int scope
);
775 void gv2(int rc1
, int rc2
);
776 void move_reg(int r
, int s
);
777 void save_regs(int n
);
778 void save_reg(int r
);
783 int get_reg_ex(int rc
,int rc2
);
786 struct macro_level
*prev
;
790 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
791 const int *macro_str
, struct macro_level
**can_read_stream
);
793 void force_charshort_cast(int t
);
794 static void gen_cast(CType
*type
);
796 static Sym
*sym_find(int v
);
797 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
800 static int type_size(CType
*type
, int *a
);
801 static inline CType
*pointed_type(CType
*type
);
802 static int pointed_size(CType
*type
);
803 static int lvalue_type(int t
);
804 static int parse_btype(CType
*type
, AttributeDef
*ad
);
805 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
806 static int compare_types(CType
*type1
, CType
*type2
, int unqualified
);
807 static int is_compatible_types(CType
*type1
, CType
*type2
);
808 static int is_compatible_parameter_types(CType
*type1
, CType
*type2
);
810 int ieee_finite(double d
);
811 void error(const char *fmt
, ...);
815 void lexpand_nr(void);
816 static void vpush_global_sym(CType
*type
, int v
);
817 void vset(CType
*type
, int r
, int v
);
818 void type_to_str(char *buf
, int buf_size
,
819 CType
*type
, const char *varstr
);
820 char *get_tok_str(int v
, CValue
*cv
);
821 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
822 unsigned long offset
, unsigned long size
);
823 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
825 /* section generation */
826 static void section_realloc(Section
*sec
, unsigned long new_size
);
827 static void *section_ptr_add(Section
*sec
, unsigned long size
);
828 static void put_extern_sym(Sym
*sym
, Section
*section
,
829 unsigned long value
, unsigned long size
);
830 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
831 static int put_elf_str(Section
*s
, const char *sym
);
832 static int put_elf_sym(Section
*s
,
833 unsigned long value
, unsigned long size
,
834 int info
, int other
, int shndx
, const char *name
);
835 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
836 int info
, int other
, int sh_num
, const char *name
);
837 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
838 int type
, int symbol
);
839 static void put_stabs(const char *str
, int type
, int other
, int desc
,
840 unsigned long value
);
841 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
842 unsigned long value
, Section
*sec
, int sym_index
);
843 static void put_stabn(int type
, int other
, int desc
, int value
);
844 static void put_stabd(int type
, int other
, int desc
);
845 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
847 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
848 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
849 #define AFF_PREPROCESS 0x0004 /* preprocess file */
850 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
853 int tcc_output_coff(TCCState
*s1
, FILE *f
);
856 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
);
857 int pe_load_def_file(struct TCCState
*s1
, FILE *fp
);
858 void pe_setup_paths(struct TCCState
*s1
, int *p_output_type
, const char **p_outfile
, char *first_file
);
859 unsigned long pe_add_runtime(struct TCCState
*s1
);
860 int tcc_output_pe(struct TCCState
*s1
, const char *filename
);
864 #ifdef CONFIG_TCC_ASM
866 typedef struct ExprValue
{
871 #define MAX_ASM_OPERANDS 30
873 typedef struct ASMOperand
{
874 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
876 char asm_str
[16]; /* computed asm string for operand */
877 SValue
*vt
; /* C value of the expression */
878 int ref_index
; /* if >= 0, gives reference to a output constraint */
879 int input_index
; /* if >= 0, gives reference to an input constraint */
880 int priority
; /* priority, used to assign registers */
881 int reg
; /* if >= 0, register number used for this operand */
882 int is_llong
; /* true if double register value */
883 int is_memory
; /* true if memory operand */
884 int is_rw
; /* for '+' modifier */
887 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
888 static int asm_int_expr(TCCState
*s1
);
889 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
890 const char *name
, const char **pp
);
892 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
896 static void asm_instr(void);
897 static void asm_global_instr(void);
899 /* true if float/double/long double type */
900 static inline int is_float(int t
)
904 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
907 #ifdef TCC_TARGET_I386
908 #include "i386-gen.c"
911 #ifdef TCC_TARGET_ARM
915 #ifdef TCC_TARGET_C67
919 #ifdef CONFIG_TCC_STATIC
921 #define RTLD_LAZY 0x001
922 #define RTLD_NOW 0x002
923 #define RTLD_GLOBAL 0x100
924 #define RTLD_DEFAULT NULL
926 /* dummy function for profiling */
927 void *dlopen(const char *filename
, int flag
)
932 const char *dlerror(void)
937 typedef struct TCCSyms
{
942 #define TCCSYM(a) { #a, &a, },
944 /* add the symbol you want here if no dynamic linking is done */
945 static TCCSyms tcc_syms
[] = {
946 #if !defined(CONFIG_TCCBOOT)
955 void *resolve_sym(TCCState
*s1
, const char *symbol
, int type
)
959 while (p
->str
!= NULL
) {
960 if (!strcmp(p
->str
, symbol
))
967 #elif !defined(WIN32)
971 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
)
973 return dlsym(RTLD_DEFAULT
, sym
);
978 /********************************************************/
980 /* we use our own 'finite' function to avoid potential problems with
981 non standard math libs */
982 /* XXX: endianness dependent */
983 int ieee_finite(double d
)
986 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
989 /* copy a string and truncate it. */
990 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
997 q_end
= buf
+ buf_size
- 1;
1009 /* strcat and truncate. */
1010 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
1015 pstrcpy(buf
+ len
, buf_size
- len
, s
);
1019 static int strstart(const char *str
, const char *val
, const char **ptr
)
1024 while (*q
!= '\0') {
1035 /* memory management */
1041 static inline void tcc_free(void *ptr
)
1044 mem_cur_size
-= malloc_usable_size(ptr
);
1049 static void *tcc_malloc(unsigned long size
)
1054 error("memory full");
1056 mem_cur_size
+= malloc_usable_size(ptr
);
1057 if (mem_cur_size
> mem_max_size
)
1058 mem_max_size
= mem_cur_size
;
1063 static void *tcc_mallocz(unsigned long size
)
1066 ptr
= tcc_malloc(size
);
1067 memset(ptr
, 0, size
);
1071 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
1075 mem_cur_size
-= malloc_usable_size(ptr
);
1077 ptr1
= realloc(ptr
, size
);
1079 /* NOTE: count not correct if alloc error, but not critical */
1080 mem_cur_size
+= malloc_usable_size(ptr1
);
1081 if (mem_cur_size
> mem_max_size
)
1082 mem_max_size
= mem_cur_size
;
1087 static char *tcc_strdup(const char *str
)
1090 ptr
= tcc_malloc(strlen(str
) + 1);
1095 #define free(p) use_tcc_free(p)
1096 #define malloc(s) use_tcc_malloc(s)
1097 #define realloc(p, s) use_tcc_realloc(p, s)
1099 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
1106 /* every power of two we double array size */
1107 if ((nb
& (nb
- 1)) == 0) {
1112 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
1114 error("memory full");
1121 /* symbol allocator */
1122 static Sym
*__sym_malloc(void)
1124 Sym
*sym_pool
, *sym
, *last_sym
;
1127 sym_pool
= tcc_malloc(SYM_POOL_NB
* sizeof(Sym
));
1129 last_sym
= sym_free_first
;
1131 for(i
= 0; i
< SYM_POOL_NB
; i
++) {
1132 sym
->next
= last_sym
;
1136 sym_free_first
= last_sym
;
1140 static inline Sym
*sym_malloc(void)
1143 sym
= sym_free_first
;
1145 sym
= __sym_malloc();
1146 sym_free_first
= sym
->next
;
1150 static inline void sym_free(Sym
*sym
)
1152 sym
->next
= sym_free_first
;
1153 sym_free_first
= sym
;
1156 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
1160 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
1161 strcpy(sec
->name
, name
);
1162 sec
->sh_type
= sh_type
;
1163 sec
->sh_flags
= sh_flags
;
1170 sec
->sh_addralign
= 4;
1173 sec
->sh_addralign
= 1;
1176 sec
->sh_addralign
= 32; /* default conservative alignment */
1180 /* only add section if not private */
1181 if (!(sh_flags
& SHF_PRIVATE
)) {
1182 sec
->sh_num
= s1
->nb_sections
;
1183 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
1188 static void free_section(Section
*s
)
1194 /* realloc section and set its content to zero */
1195 static void section_realloc(Section
*sec
, unsigned long new_size
)
1198 unsigned char *data
;
1200 size
= sec
->data_allocated
;
1203 while (size
< new_size
)
1205 data
= tcc_realloc(sec
->data
, size
);
1207 error("memory full");
1208 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1210 sec
->data_allocated
= size
;
1213 /* reserve at least 'size' bytes in section 'sec' from
1214 sec->data_offset. */
1215 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1217 unsigned long offset
, offset1
;
1219 offset
= sec
->data_offset
;
1220 offset1
= offset
+ size
;
1221 if (offset1
> sec
->data_allocated
)
1222 section_realloc(sec
, offset1
);
1223 sec
->data_offset
= offset1
;
1224 return sec
->data
+ offset
;
1227 /* return a reference to a section, and create it if it does not
1229 Section
*find_section(TCCState
*s1
, const char *name
)
1233 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1234 sec
= s1
->sections
[i
];
1235 if (!strcmp(name
, sec
->name
))
1238 /* sections are created as PROGBITS */
1239 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1242 #define SECTION_ABS ((void *)1)
1244 /* update sym->c so that it points to an external symbol in section
1245 'section' with value 'value' */
1246 static void put_extern_sym2(Sym
*sym
, Section
*section
,
1247 unsigned long value
, unsigned long size
,
1248 int can_add_underscore
)
1250 int sym_type
, sym_bind
, sh_num
, info
;
1255 if (section
== NULL
)
1257 else if (section
== SECTION_ABS
)
1260 sh_num
= section
->sh_num
;
1262 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
)
1263 sym_type
= STT_FUNC
;
1265 sym_type
= STT_OBJECT
;
1266 if (sym
->type
.t
& VT_STATIC
)
1267 sym_bind
= STB_LOCAL
;
1269 sym_bind
= STB_GLOBAL
;
1271 name
= get_tok_str(sym
->v
, NULL
);
1272 #ifdef CONFIG_TCC_BCHECK
1273 if (do_bounds_check
) {
1276 /* XXX: avoid doing that for statics ? */
1277 /* if bound checking is activated, we change some function
1278 names by adding the "__bound" prefix */
1281 /* XXX: we rely only on malloc hooks */
1293 strcpy(buf
, "__bound_");
1300 if (tcc_state
->leading_underscore
&& can_add_underscore
) {
1302 pstrcpy(buf1
+ 1, sizeof(buf1
) - 1, name
);
1305 info
= ELF32_ST_INFO(sym_bind
, sym_type
);
1306 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, 0, sh_num
, name
);
1308 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
1309 esym
->st_value
= value
;
1310 esym
->st_size
= size
;
1311 esym
->st_shndx
= sh_num
;
1315 static void put_extern_sym(Sym
*sym
, Section
*section
,
1316 unsigned long value
, unsigned long size
)
1318 put_extern_sym2(sym
, section
, value
, size
, 1);
1321 /* add a new relocation entry to symbol 'sym' in section 's' */
1322 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1325 put_extern_sym(sym
, NULL
, 0, 0);
1326 /* now we can add ELF relocation info */
1327 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1330 static inline int isid(int c
)
1332 return (c
>= 'a' && c
<= 'z') ||
1333 (c
>= 'A' && c
<= 'Z') ||
1337 static inline int isnum(int c
)
1339 return c
>= '0' && c
<= '9';
1342 static inline int isoct(int c
)
1344 return c
>= '0' && c
<= '7';
1347 static inline int toup(int c
)
1349 if (c
>= 'a' && c
<= 'z')
1350 return c
- 'a' + 'A';
1355 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1359 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1362 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1366 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1370 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1377 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1378 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1379 (*f
)->filename
, (*f
)->line_num
);
1380 if (file
->line_num
> 0) {
1381 strcat_printf(buf
, sizeof(buf
),
1382 "%s:%d: ", file
->filename
, file
->line_num
);
1384 strcat_printf(buf
, sizeof(buf
),
1385 "%s: ", file
->filename
);
1388 strcat_printf(buf
, sizeof(buf
),
1392 strcat_printf(buf
, sizeof(buf
), "warning: ");
1393 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1395 if (!s1
->error_func
) {
1396 /* default case: stderr */
1397 fprintf(stderr
, "%s\n", buf
);
1399 s1
->error_func(s1
->error_opaque
, buf
);
1401 if (!is_warning
|| s1
->warn_error
)
1406 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1407 void (*error_func
)(void *opaque
, const char *msg
))
1409 s
->error_opaque
= error_opaque
;
1410 s
->error_func
= error_func
;
1414 /* error without aborting current compilation */
1415 void error_noabort(const char *fmt
, ...)
1417 TCCState
*s1
= tcc_state
;
1421 error1(s1
, 0, fmt
, ap
);
1425 void error(const char *fmt
, ...)
1427 TCCState
*s1
= tcc_state
;
1431 error1(s1
, 0, fmt
, ap
);
1433 /* better than nothing: in some cases, we accept to handle errors */
1434 if (s1
->error_set_jmp_enabled
) {
1435 longjmp(s1
->error_jmp_buf
, 1);
1437 /* XXX: eliminate this someday */
1442 void expect(const char *msg
)
1444 error("%s expected", msg
);
1447 void warning(const char *fmt
, ...)
1449 TCCState
*s1
= tcc_state
;
1456 error1(s1
, 1, fmt
, ap
);
1463 error("'%c' expected", c
);
1467 static void test_lvalue(void)
1469 if (!(vtop
->r
& VT_LVAL
))
1473 /* allocate a new token */
1474 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1476 TokenSym
*ts
, **ptable
;
1479 if (tok_ident
>= SYM_FIRST_ANOM
)
1480 error("memory full");
1482 /* expand token table if needed */
1483 i
= tok_ident
- TOK_IDENT
;
1484 if ((i
% TOK_ALLOC_INCR
) == 0) {
1485 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1487 error("memory full");
1488 table_ident
= ptable
;
1491 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1492 table_ident
[i
] = ts
;
1493 ts
->tok
= tok_ident
++;
1494 ts
->sym_define
= NULL
;
1495 ts
->sym_label
= NULL
;
1496 ts
->sym_struct
= NULL
;
1497 ts
->sym_identifier
= NULL
;
1499 ts
->hash_next
= NULL
;
1500 memcpy(ts
->str
, str
, len
);
1501 ts
->str
[len
] = '\0';
1506 #define TOK_HASH_INIT 1
1507 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1509 /* find a token and add it if not found */
1510 static TokenSym
*tok_alloc(const char *str
, int len
)
1512 TokenSym
*ts
, **pts
;
1518 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1519 h
&= (TOK_HASH_SIZE
- 1);
1521 pts
= &hash_ident
[h
];
1526 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1528 pts
= &(ts
->hash_next
);
1530 return tok_alloc_new(pts
, str
, len
);
1533 /* CString handling */
1535 static void cstr_realloc(CString
*cstr
, int new_size
)
1540 size
= cstr
->size_allocated
;
1542 size
= 8; /* no need to allocate a too small first string */
1543 while (size
< new_size
)
1545 data
= tcc_realloc(cstr
->data_allocated
, size
);
1547 error("memory full");
1548 cstr
->data_allocated
= data
;
1549 cstr
->size_allocated
= size
;
1554 static inline void cstr_ccat(CString
*cstr
, int ch
)
1557 size
= cstr
->size
+ 1;
1558 if (size
> cstr
->size_allocated
)
1559 cstr_realloc(cstr
, size
);
1560 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1564 static void cstr_cat(CString
*cstr
, const char *str
)
1576 /* add a wide char */
1577 static void cstr_wccat(CString
*cstr
, int ch
)
1580 size
= cstr
->size
+ sizeof(nwchar_t
);
1581 if (size
> cstr
->size_allocated
)
1582 cstr_realloc(cstr
, size
);
1583 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
1587 static void cstr_new(CString
*cstr
)
1589 memset(cstr
, 0, sizeof(CString
));
1592 /* free string and reset it to NULL */
1593 static void cstr_free(CString
*cstr
)
1595 tcc_free(cstr
->data_allocated
);
1599 #define cstr_reset(cstr) cstr_free(cstr)
1601 /* XXX: unicode ? */
1602 static void add_char(CString
*cstr
, int c
)
1604 if (c
== '\'' || c
== '\"' || c
== '\\') {
1605 /* XXX: could be more precise if char or string */
1606 cstr_ccat(cstr
, '\\');
1608 if (c
>= 32 && c
<= 126) {
1611 cstr_ccat(cstr
, '\\');
1613 cstr_ccat(cstr
, 'n');
1615 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1616 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1617 cstr_ccat(cstr
, '0' + (c
& 7));
1622 /* XXX: buffer overflow */
1623 /* XXX: float tokens */
1624 char *get_tok_str(int v
, CValue
*cv
)
1626 static char buf
[STRING_MAX_SIZE
+ 1];
1627 static CString cstr_buf
;
1633 /* NOTE: to go faster, we give a fixed buffer for small strings */
1634 cstr_reset(&cstr_buf
);
1635 cstr_buf
.data
= buf
;
1636 cstr_buf
.size_allocated
= sizeof(buf
);
1642 /* XXX: not quite exact, but only useful for testing */
1643 sprintf(p
, "%u", cv
->ui
);
1647 /* XXX: not quite exact, but only useful for testing */
1648 sprintf(p
, "%Lu", cv
->ull
);
1652 cstr_ccat(&cstr_buf
, '\'');
1653 add_char(&cstr_buf
, cv
->i
);
1654 cstr_ccat(&cstr_buf
, '\'');
1655 cstr_ccat(&cstr_buf
, '\0');
1659 len
= cstr
->size
- 1;
1661 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1662 cstr_ccat(&cstr_buf
, '\0');
1667 cstr_ccat(&cstr_buf
, '\"');
1669 len
= cstr
->size
- 1;
1671 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1673 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
1675 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
1677 cstr_ccat(&cstr_buf
, '\"');
1678 cstr_ccat(&cstr_buf
, '\0');
1687 return strcpy(p
, "...");
1689 return strcpy(p
, "<<=");
1691 return strcpy(p
, ">>=");
1693 if (v
< TOK_IDENT
) {
1694 /* search in two bytes table */
1708 } else if (v
< tok_ident
) {
1709 return table_ident
[v
- TOK_IDENT
]->str
;
1710 } else if (v
>= SYM_FIRST_ANOM
) {
1711 /* special name for anonymous symbol */
1712 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1714 /* should never happen */
1719 return cstr_buf
.data
;
1722 /* push, without hashing */
1723 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, int c
)
1737 /* find a symbol and return its associated structure. 's' is the top
1738 of the symbol stack */
1739 static Sym
*sym_find2(Sym
*s
, int v
)
1749 /* structure lookup */
1750 static inline Sym
*struct_find(int v
)
1753 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1755 return table_ident
[v
]->sym_struct
;
1758 /* find an identifier */
1759 static inline Sym
*sym_find(int v
)
1762 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1764 return table_ident
[v
]->sym_identifier
;
1767 /* push a given symbol on the symbol stack */
1768 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1777 s
= sym_push2(ps
, v
, type
->t
, c
);
1778 s
->type
.ref
= type
->ref
;
1780 /* don't record fields or anonymous symbols */
1782 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1783 /* record symbol in token array */
1784 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1786 ps
= &ts
->sym_struct
;
1788 ps
= &ts
->sym_identifier
;
1795 /* push a global identifier */
1796 static Sym
*global_identifier_push(int v
, int t
, int c
)
1799 s
= sym_push2(&global_stack
, v
, t
, c
);
1800 /* don't record anonymous symbol */
1801 if (v
< SYM_FIRST_ANOM
) {
1802 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1803 /* modify the top most local identifier, so that
1804 sym_identifier will point to 's' when popped */
1806 ps
= &(*ps
)->prev_tok
;
1813 /* pop symbols until top reaches 'b' */
1814 static void sym_pop(Sym
**ptop
, Sym
*b
)
1824 /* remove symbol in token array */
1826 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1827 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1829 ps
= &ts
->sym_struct
;
1831 ps
= &ts
->sym_identifier
;
1842 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1848 fd
= open(filename
, O_RDONLY
| O_BINARY
);
1851 bf
= tcc_malloc(sizeof(BufferedFile
));
1857 bf
->buf_ptr
= bf
->buffer
;
1858 bf
->buf_end
= bf
->buffer
;
1859 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1860 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1861 len
= strlen(bf
->filename
);
1862 for (i
= 0; i
< len
; i
++)
1863 if (bf
->filename
[i
] == '\\')
1864 bf
->filename
[i
] = '/';
1866 bf
->ifndef_macro
= 0;
1867 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1868 // printf("opening '%s'\n", filename);
1872 void tcc_close(BufferedFile
*bf
)
1874 total_lines
+= bf
->line_num
;
1879 /* fill input buffer and peek next char */
1880 static int tcc_peekc_slow(BufferedFile
*bf
)
1883 /* only tries to read if really end of buffer */
1884 if (bf
->buf_ptr
>= bf
->buf_end
) {
1886 #if defined(PARSE_DEBUG)
1891 len
= read(bf
->fd
, bf
->buffer
, len
);
1898 bf
->buf_ptr
= bf
->buffer
;
1899 bf
->buf_end
= bf
->buffer
+ len
;
1900 *bf
->buf_end
= CH_EOB
;
1902 if (bf
->buf_ptr
< bf
->buf_end
) {
1903 return bf
->buf_ptr
[0];
1905 bf
->buf_ptr
= bf
->buf_end
;
1910 /* return the current character, handling end of block if necessary
1912 static int handle_eob(void)
1914 return tcc_peekc_slow(file
);
1917 /* read next char from current input file and handle end of input buffer */
1918 static inline void inp(void)
1920 ch
= *(++(file
->buf_ptr
));
1921 /* end of buffer/file handling */
1926 /* handle '\[\r]\n' */
1927 static void handle_stray(void)
1929 while (ch
== '\\') {
1934 } else if (ch
== '\r') {
1942 error("stray '\\' in program");
1947 /* skip the stray and handle the \\n case. Output an error if
1948 incorrect char after the stray */
1949 static int handle_stray1(uint8_t *p
)
1953 if (p
>= file
->buf_end
) {
1970 /* handle just the EOB case, but not stray */
1971 #define PEEKC_EOB(c, p)\
1982 /* handle the complicated stray case */
1983 #define PEEKC(c, p)\
1988 c = handle_stray1(p);\
1993 /* input with '\[\r]\n' handling. Note that this function cannot
1994 handle other characters after '\', so you cannot call it inside
1995 strings or comments */
1996 static void minp(void)
2004 /* single line C++ comments */
2005 static uint8_t *parse_line_comment(uint8_t *p
)
2013 if (c
== '\n' || c
== CH_EOF
) {
2015 } else if (c
== '\\') {
2024 } else if (c
== '\r') {
2042 static uint8_t *parse_comment(uint8_t *p
)
2048 /* fast skip loop */
2051 if (c
== '\n' || c
== '*' || c
== '\\')
2055 if (c
== '\n' || c
== '*' || c
== '\\')
2059 /* now we can handle all the cases */
2063 } else if (c
== '*') {
2069 } else if (c
== '/') {
2070 goto end_of_comment
;
2071 } else if (c
== '\\') {
2076 /* skip '\[\r]\n', otherwise just skip the stray */
2082 } else if (c
== '\r') {
2099 /* stray, eob or eof */
2104 error("unexpected end of file in comment");
2105 } else if (c
== '\\') {
2117 /* space exlcuding newline */
2118 static inline int is_space(int ch
)
2120 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
2123 static inline void skip_spaces(void)
2125 while (is_space(ch
))
2129 /* parse a string without interpreting escapes */
2130 static uint8_t *parse_pp_string(uint8_t *p
,
2131 int sep
, CString
*str
)
2139 } else if (c
== '\\') {
2144 unterminated_string
:
2145 /* XXX: indicate line number of start of string */
2146 error("missing terminating %c character", sep
);
2147 } else if (c
== '\\') {
2148 /* escape : just skip \[\r]\n */
2153 } else if (c
== '\r') {
2156 expect("'\n' after '\r'");
2159 } else if (c
== CH_EOF
) {
2160 goto unterminated_string
;
2163 cstr_ccat(str
, '\\');
2169 } else if (c
== '\n') {
2172 } else if (c
== '\r') {
2176 cstr_ccat(str
, '\r');
2192 /* skip block of text until #else, #elif or #endif. skip also pairs of
2194 void preprocess_skip(void)
2196 int a
, start_of_line
, c
;
2223 } else if (c
== '\\') {
2224 /* XXX: incorrect: should not give an error */
2225 ch
= file
->buf_ptr
[0];
2233 p
= parse_pp_string(p
, c
, NULL
);
2242 p
= parse_comment(p
);
2243 } else if (ch
== '/') {
2244 p
= parse_line_comment(p
);
2250 if (start_of_line
) {
2255 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2257 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2259 else if (tok
== TOK_ENDIF
)
2273 /* ParseState handling */
2275 /* XXX: currently, no include file info is stored. Thus, we cannot display
2276 accurate messages if the function or data definition spans multiple
2279 /* save current parse state in 's' */
2280 void save_parse_state(ParseState
*s
)
2282 s
->line_num
= file
->line_num
;
2283 s
->macro_ptr
= macro_ptr
;
2288 /* restore parse state from 's' */
2289 void restore_parse_state(ParseState
*s
)
2291 file
->line_num
= s
->line_num
;
2292 macro_ptr
= s
->macro_ptr
;
2297 /* return the number of additional 'ints' necessary to store the
2299 static inline int tok_ext_size(int t
)
2313 error("unsupported token");
2320 return LDOUBLE_SIZE
/ 4;
2326 /* token string handling */
2328 static inline void tok_str_new(TokenString
*s
)
2332 s
->allocated_len
= 0;
2333 s
->last_line_num
= -1;
2336 static void tok_str_free(int *str
)
2341 static int *tok_str_realloc(TokenString
*s
)
2345 if (s
->allocated_len
== 0) {
2348 len
= s
->allocated_len
* 2;
2350 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2352 error("memory full");
2353 s
->allocated_len
= len
;
2358 static void tok_str_add(TokenString
*s
, int t
)
2364 if (len
>= s
->allocated_len
)
2365 str
= tok_str_realloc(s
);
2370 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2377 /* allocate space for worst case */
2378 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2379 str
= tok_str_realloc(s
);
2388 str
[len
++] = cv
->tab
[0];
2397 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
2398 while ((len
+ nb_words
) > s
->allocated_len
)
2399 str
= tok_str_realloc(s
);
2400 cstr
= (CString
*)(str
+ len
);
2402 cstr
->size
= cv
->cstr
->size
;
2403 cstr
->data_allocated
= NULL
;
2404 cstr
->size_allocated
= cstr
->size
;
2405 memcpy((char *)cstr
+ sizeof(CString
),
2406 cv
->cstr
->data
, cstr
->size
);
2413 #if LDOUBLE_SIZE == 8
2416 str
[len
++] = cv
->tab
[0];
2417 str
[len
++] = cv
->tab
[1];
2419 #if LDOUBLE_SIZE == 12
2421 str
[len
++] = cv
->tab
[0];
2422 str
[len
++] = cv
->tab
[1];
2423 str
[len
++] = cv
->tab
[2];
2424 #elif LDOUBLE_SIZE != 8
2425 #error add long double size support
2434 /* add the current parse token in token string 's' */
2435 static void tok_str_add_tok(TokenString
*s
)
2439 /* save line number info */
2440 if (file
->line_num
!= s
->last_line_num
) {
2441 s
->last_line_num
= file
->line_num
;
2442 cval
.i
= s
->last_line_num
;
2443 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2445 tok_str_add2(s
, tok
, &tokc
);
2448 #if LDOUBLE_SIZE == 12
2449 #define LDOUBLE_GET(p, cv) \
2453 #elif LDOUBLE_SIZE == 8
2454 #define LDOUBLE_GET(p, cv) \
2458 #error add long double size support
2462 /* get a token from an integer array and increment pointer
2463 accordingly. we code it as a macro to avoid pointer aliasing. */
2464 #define TOK_GET(t, p, cv) \
2479 cv.cstr = (CString *)p; \
2480 cv.cstr->data = (char *)p + sizeof(CString);\
2481 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
2490 case TOK_CLDOUBLE: \
2491 LDOUBLE_GET(p, cv); \
2492 p += LDOUBLE_SIZE / 4; \
2499 /* defines handling */
2500 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2504 s
= sym_push2(&define_stack
, v
, macro_type
, (int)str
);
2505 s
->next
= first_arg
;
2506 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2509 /* undefined a define symbol. Its name is just set to zero */
2510 static void define_undef(Sym
*s
)
2514 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2515 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2519 static inline Sym
*define_find(int v
)
2522 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2524 return table_ident
[v
]->sym_define
;
2527 /* free define stack until top reaches 'b' */
2528 static void free_defines(Sym
*b
)
2536 /* do not free args or predefined defines */
2538 tok_str_free((int *)top
->c
);
2540 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2541 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2549 static Sym
*label_find(int v
)
2552 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2554 return table_ident
[v
]->sym_label
;
2557 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2560 s
= sym_push2(ptop
, v
, 0, 0);
2562 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2563 if (ptop
== &global_label_stack
) {
2564 /* modify the top most local identifier, so that
2565 sym_identifier will point to 's' when popped */
2567 ps
= &(*ps
)->prev_tok
;
2574 /* pop labels until element last is reached. Look if any labels are
2575 undefined. Define symbols if '&&label' was used. */
2576 static void label_pop(Sym
**ptop
, Sym
*slast
)
2579 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2581 if (s
->r
== LABEL_DECLARED
) {
2582 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2583 } else if (s
->r
== LABEL_FORWARD
) {
2584 error("label '%s' used but not defined",
2585 get_tok_str(s
->v
, NULL
));
2588 /* define corresponding symbol. A size of
2590 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2594 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2600 /* eval an expression for #if/#elif */
2601 static int expr_preprocess(void)
2607 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2608 next(); /* do macro subst */
2609 if (tok
== TOK_DEFINED
) {
2614 c
= define_find(tok
) != 0;
2619 } else if (tok
>= TOK_IDENT
) {
2620 /* if undefined macro */
2624 tok_str_add_tok(&str
);
2626 tok_str_add(&str
, -1); /* simulate end of file */
2627 tok_str_add(&str
, 0);
2628 /* now evaluate C constant expression */
2629 macro_ptr
= str
.str
;
2633 tok_str_free(str
.str
);
2637 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2638 static void tok_print(int *str
)
2644 TOK_GET(t
, str
, cval
);
2647 printf(" %s", get_tok_str(t
, &cval
));
2653 /* parse after #define */
2654 static void parse_define(void)
2656 Sym
*s
, *first
, **ps
;
2657 int v
, t
, varg
, is_vaargs
, c
;
2662 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2663 /* XXX: should check if same macro (ANSI) */
2666 /* '(' must be just after macro definition for MACRO_FUNC */
2667 c
= file
->buf_ptr
[0];
2669 c
= handle_stray1(file
->buf_ptr
);
2674 while (tok
!= ')') {
2678 if (varg
== TOK_DOTS
) {
2679 varg
= TOK___VA_ARGS__
;
2681 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2685 if (varg
< TOK_IDENT
)
2686 error("badly punctuated parameter list");
2687 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2698 /* EOF testing necessary for '-D' handling */
2699 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2700 tok_str_add2(&str
, tok
, &tokc
);
2703 tok_str_add(&str
, 0);
2705 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2708 define_push(v
, t
, str
.str
, first
);
2711 static inline int hash_cached_include(int type
, const char *filename
)
2713 const unsigned char *s
;
2717 h
= TOK_HASH_FUNC(h
, type
);
2720 h
= TOK_HASH_FUNC(h
, *s
);
2723 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
2727 /* XXX: use a token or a hash table to accelerate matching ? */
2728 static CachedInclude
*search_cached_include(TCCState
*s1
,
2729 int type
, const char *filename
)
2733 h
= hash_cached_include(type
, filename
);
2734 i
= s1
->cached_includes_hash
[h
];
2738 e
= s1
->cached_includes
[i
- 1];
2739 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2746 static inline void add_cached_include(TCCState
*s1
, int type
,
2747 const char *filename
, int ifndef_macro
)
2752 if (search_cached_include(s1
, type
, filename
))
2755 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2757 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2761 strcpy(e
->filename
, filename
);
2762 e
->ifndef_macro
= ifndef_macro
;
2763 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2764 /* add in hash table */
2765 h
= hash_cached_include(type
, filename
);
2766 e
->hash_next
= s1
->cached_includes_hash
[h
];
2767 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
2770 static void pragma_parse(TCCState
*s1
)
2775 if (tok
== TOK_pack
) {
2778 #pragma pack(1) // set
2779 #pragma pack() // reset to default
2780 #pragma pack(push,1) // push & set
2781 #pragma pack(pop) // restore previous
2785 if (tok
== TOK_ASM_pop
) {
2787 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
2789 error("out of pack stack");
2791 s1
->pack_stack_ptr
--;
2795 if (tok
== TOK_ASM_push
) {
2797 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
2799 s1
->pack_stack_ptr
++;
2802 if (tok
!= TOK_CINT
) {
2804 error("invalid pack pragma");
2807 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
2811 *s1
->pack_stack_ptr
= val
;
2817 /* is_bof is true if first non space token at beginning of file */
2818 static void preprocess(int is_bof
)
2820 TCCState
*s1
= tcc_state
;
2821 int size
, i
, c
, n
, saved_parse_flags
;
2822 char buf
[1024], *q
, *p
;
2828 saved_parse_flags
= parse_flags
;
2829 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
2830 PARSE_FLAG_LINEFEED
;
2840 s
= define_find(tok
);
2841 /* undefine symbol by putting an invalid name */
2846 case TOK_INCLUDE_NEXT
:
2847 ch
= file
->buf_ptr
[0];
2848 /* XXX: incorrect if comments : use next_nomacro with a special mode */
2853 } else if (ch
== '\"') {
2856 /* XXX: better stray handling */
2859 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
2860 if ((q
- buf
) < sizeof(buf
) - 1)
2867 /* eat all spaces and comments after include */
2868 /* XXX: slightly incorrect */
2869 while (ch1
!= '\n' && ch1
!= CH_EOF
)
2873 /* computed #include : either we have only strings or
2874 we have anything enclosed in '<>' */
2877 if (tok
== TOK_STR
) {
2878 while (tok
!= TOK_LINEFEED
) {
2879 if (tok
!= TOK_STR
) {
2881 error("'#include' expects \"FILENAME\" or <FILENAME>");
2883 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
2889 while (tok
!= TOK_LINEFEED
) {
2890 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
2894 /* check syntax and remove '<>' */
2895 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
2896 goto include_syntax
;
2897 memmove(buf
, buf
+ 1, len
- 2);
2898 buf
[len
- 2] = '\0';
2903 e
= search_cached_include(s1
, c
, buf
);
2904 if (e
&& define_find(e
->ifndef_macro
)) {
2905 /* no need to parse the include because the 'ifndef macro'
2908 printf("%s: skipping %s\n", file
->filename
, buf
);
2912 /* first search in current dir if "header.h" */
2914 p
= strrchr(file
->filename
, '/');
2916 size
= p
+ 1 - file
->filename
;
2917 if (size
> sizeof(buf1
) - 1)
2918 size
= sizeof(buf1
) - 1;
2919 memcpy(buf1
, file
->filename
, size
);
2921 pstrcat(buf1
, sizeof(buf1
), buf
);
2922 f
= tcc_open(s1
, buf1
);
2924 if (tok
== TOK_INCLUDE_NEXT
)
2930 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
2931 error("#include recursion too deep");
2932 /* now search in all the include paths */
2933 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
2934 for(i
= 0; i
< n
; i
++) {
2936 if (i
< s1
->nb_include_paths
)
2937 path
= s1
->include_paths
[i
];
2939 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
2940 pstrcpy(buf1
, sizeof(buf1
), path
);
2941 pstrcat(buf1
, sizeof(buf1
), "/");
2942 pstrcat(buf1
, sizeof(buf1
), buf
);
2943 f
= tcc_open(s1
, buf1
);
2945 if (tok
== TOK_INCLUDE_NEXT
)
2951 error("include file '%s' not found", buf
);
2955 printf("%s: including %s\n", file
->filename
, buf1
);
2958 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
2959 /* push current file in stack */
2960 /* XXX: fix current line init */
2961 *s1
->include_stack_ptr
++ = file
;
2963 /* add include file debug info */
2965 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
2967 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
2968 ch
= file
->buf_ptr
[0];
2976 c
= expr_preprocess();
2982 if (tok
< TOK_IDENT
)
2983 error("invalid argument for '#if%sdef'", c
? "n" : "");
2987 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
2989 file
->ifndef_macro
= tok
;
2992 c
= (define_find(tok
) != 0) ^ c
;
2994 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
2995 error("memory full");
2996 *s1
->ifdef_stack_ptr
++ = c
;
2999 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
3000 error("#else without matching #if");
3001 if (s1
->ifdef_stack_ptr
[-1] & 2)
3002 error("#else after #else");
3003 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
3006 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
3007 error("#elif without matching #if");
3008 c
= s1
->ifdef_stack_ptr
[-1];
3010 error("#elif after #else");
3011 /* last #if/#elif expression was true: we skip */
3014 c
= expr_preprocess();
3015 s1
->ifdef_stack_ptr
[-1] = c
;
3025 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
3026 error("#endif without matching #if");
3027 s1
->ifdef_stack_ptr
--;
3028 /* '#ifndef macro' was at the start of file. Now we check if
3029 an '#endif' is exactly at the end of file */
3030 if (file
->ifndef_macro
&&
3031 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
3032 file
->ifndef_macro_saved
= file
->ifndef_macro
;
3033 /* need to set to zero to avoid false matches if another
3034 #ifndef at middle of file */
3035 file
->ifndef_macro
= 0;
3036 while (tok
!= TOK_LINEFEED
)
3038 tok_flags
|= TOK_FLAG_ENDIF
;
3044 if (tok
!= TOK_CINT
)
3046 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
3048 if (tok
!= TOK_LINEFEED
) {
3051 pstrcpy(file
->filename
, sizeof(file
->filename
),
3052 (char *)tokc
.cstr
->data
);
3058 ch
= file
->buf_ptr
[0];
3061 while (ch
!= '\n' && ch
!= CH_EOF
) {
3062 if ((q
- buf
) < sizeof(buf
) - 1)
3068 error("#error %s", buf
);
3070 warning("#warning %s", buf
);
3076 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
3077 /* '!' is ignored to allow C scripts. numbers are ignored
3078 to emulate cpp behaviour */
3080 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
3081 error("invalid preprocessing directive #%s", get_tok_str(tok
, &tokc
));
3085 /* ignore other preprocess commands or #! for C scripts */
3086 while (tok
!= TOK_LINEFEED
)
3089 parse_flags
= saved_parse_flags
;
3092 /* evaluate escape codes in a string. */
3093 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
3108 case '0': case '1': case '2': case '3':
3109 case '4': case '5': case '6': case '7':
3110 /* at most three octal digits */
3115 n
= n
* 8 + c
- '0';
3119 n
= n
* 8 + c
- '0';
3124 goto add_char_nonext
;
3130 if (c
>= 'a' && c
<= 'f')
3132 else if (c
>= 'A' && c
<= 'F')
3142 goto add_char_nonext
;
3166 goto invalid_escape
;
3176 if (c
>= '!' && c
<= '~')
3177 warning("unknown escape sequence: \'\\%c\'", c
);
3179 warning("unknown escape sequence: \'\\x%x\'", c
);
3186 cstr_ccat(outstr
, c
);
3188 cstr_wccat(outstr
, c
);
3190 /* add a trailing '\0' */
3192 cstr_ccat(outstr
, '\0');
3194 cstr_wccat(outstr
, '\0');
3197 /* we use 64 bit numbers */
3200 /* bn = (bn << shift) | or_val */
3201 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
3205 for(i
=0;i
<BN_SIZE
;i
++) {
3207 bn
[i
] = (v
<< shift
) | or_val
;
3208 or_val
= v
>> (32 - shift
);
3212 void bn_zero(unsigned int *bn
)
3215 for(i
=0;i
<BN_SIZE
;i
++) {
3220 /* parse number in null terminated string 'p' and return it in the
3222 void parse_number(const char *p
)
3224 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
3226 unsigned int bn
[BN_SIZE
];
3237 goto float_frac_parse
;
3238 } else if (t
== '0') {
3239 if (ch
== 'x' || ch
== 'X') {
3243 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
3249 /* parse all digits. cannot check octal numbers at this stage
3250 because of floating point constants */
3252 if (ch
>= 'a' && ch
<= 'f')
3254 else if (ch
>= 'A' && ch
<= 'F')
3262 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
3264 error("number too long");
3270 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
3271 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
3273 /* NOTE: strtox should support that for hexa numbers, but
3274 non ISOC99 libcs do not support it, so we prefer to do
3276 /* hexadecimal or binary floats */
3277 /* XXX: handle overflows */
3289 } else if (t
>= 'a') {
3291 } else if (t
>= 'A') {
3296 bn_lshift(bn
, shift
, t
);
3303 if (t
>= 'a' && t
<= 'f') {
3305 } else if (t
>= 'A' && t
<= 'F') {
3307 } else if (t
>= '0' && t
<= '9') {
3313 error("invalid digit");
3314 bn_lshift(bn
, shift
, t
);
3319 if (ch
!= 'p' && ch
!= 'P')
3326 } else if (ch
== '-') {
3330 if (ch
< '0' || ch
> '9')
3331 expect("exponent digits");
3332 while (ch
>= '0' && ch
<= '9') {
3333 exp_val
= exp_val
* 10 + ch
- '0';
3336 exp_val
= exp_val
* s
;
3338 /* now we can generate the number */
3339 /* XXX: should patch directly float number */
3340 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3341 d
= ldexp(d
, exp_val
- frac_bits
);
3346 /* float : should handle overflow */
3348 } else if (t
== 'L') {
3351 /* XXX: not large enough */
3352 tokc
.ld
= (long double)d
;
3358 /* decimal floats */
3360 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3365 while (ch
>= '0' && ch
<= '9') {
3366 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3372 if (ch
== 'e' || ch
== 'E') {
3373 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3377 if (ch
== '-' || ch
== '+') {
3378 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3383 if (ch
< '0' || ch
> '9')
3384 expect("exponent digits");
3385 while (ch
>= '0' && ch
<= '9') {
3386 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3398 tokc
.f
= strtof(token_buf
, NULL
);
3399 } else if (t
== 'L') {
3402 tokc
.ld
= strtold(token_buf
, NULL
);
3405 tokc
.d
= strtod(token_buf
, NULL
);
3409 unsigned long long n
, n1
;
3412 /* integer number */
3415 if (b
== 10 && *q
== '0') {
3422 /* no need for checks except for base 10 / 8 errors */
3425 } else if (t
>= 'a') {
3427 } else if (t
>= 'A') {
3432 error("invalid digit");
3436 /* detect overflow */
3437 /* XXX: this test is not reliable */
3439 error("integer constant overflow");
3442 /* XXX: not exactly ANSI compliant */
3443 if ((n
& 0xffffffff00000000LL
) != 0) {
3448 } else if (n
> 0x7fffffff) {
3459 error("three 'l's in integer constant");
3462 if (tok
== TOK_CINT
)
3464 else if (tok
== TOK_CUINT
)
3468 } else if (t
== 'U') {
3470 error("two 'u's in integer constant");
3472 if (tok
== TOK_CINT
)
3474 else if (tok
== TOK_CLLONG
)
3481 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3489 #define PARSE2(c1, tok1, c2, tok2) \
3500 /* return next token without macro substitution */
3501 static inline void next_nomacro1(void)
3521 /* first look if it is in fact an end of buffer */
3522 if (p
>= file
->buf_end
) {
3526 if (p
>= file
->buf_end
)
3539 TCCState
*s1
= tcc_state
;
3540 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3542 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3543 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3544 /* no include left : end of file. */
3547 /* pop include file */
3549 /* test if previous '#endif' was after a #ifdef at
3551 if (tok_flags
& TOK_FLAG_ENDIF
) {
3553 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3555 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3556 file
->ifndef_macro_saved
);
3559 /* add end of include file debug info */
3561 put_stabd(N_EINCL
, 0, 0);
3563 /* pop include stack */
3565 s1
->include_stack_ptr
--;
3566 file
= *s1
->include_stack_ptr
;
3574 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3578 tok_flags
|= TOK_FLAG_BOL
;
3587 if ((tok_flags
& TOK_FLAG_BOL
) &&
3588 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3590 preprocess(tok_flags
& TOK_FLAG_BOF
);
3596 tok
= TOK_TWOSHARPS
;
3598 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
3599 p
= parse_line_comment(p
- 1);
3608 case 'a': case 'b': case 'c': case 'd':
3609 case 'e': case 'f': case 'g': case 'h':
3610 case 'i': case 'j': case 'k': case 'l':
3611 case 'm': case 'n': case 'o': case 'p':
3612 case 'q': case 'r': case 's': case 't':
3613 case 'u': case 'v': case 'w': case 'x':
3615 case 'A': case 'B': case 'C': case 'D':
3616 case 'E': case 'F': case 'G': case 'H':
3617 case 'I': case 'J': case 'K':
3618 case 'M': case 'N': case 'O': case 'P':
3619 case 'Q': case 'R': case 'S': case 'T':
3620 case 'U': case 'V': case 'W': case 'X':
3626 h
= TOK_HASH_FUNC(h
, c
);
3630 if (!isidnum_table
[c
])
3632 h
= TOK_HASH_FUNC(h
, c
);
3639 /* fast case : no stray found, so we have the full token
3640 and we have already hashed it */
3642 h
&= (TOK_HASH_SIZE
- 1);
3643 pts
= &hash_ident
[h
];
3648 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3650 pts
= &(ts
->hash_next
);
3652 ts
= tok_alloc_new(pts
, p1
, len
);
3656 cstr_reset(&tokcstr
);
3659 cstr_ccat(&tokcstr
, *p1
);
3665 while (isidnum_table
[c
]) {
3666 cstr_ccat(&tokcstr
, c
);
3669 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3675 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3677 goto parse_ident_fast
;
3680 if (c
== '\'' || c
== '\"') {
3684 cstr_reset(&tokcstr
);
3685 cstr_ccat(&tokcstr
, 'L');
3686 goto parse_ident_slow
;
3690 case '0': case '1': case '2': case '3':
3691 case '4': case '5': case '6': case '7':
3694 cstr_reset(&tokcstr
);
3695 /* after the first digit, accept digits, alpha, '.' or sign if
3696 prefixed by 'eEpP' */
3700 cstr_ccat(&tokcstr
, c
);
3702 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3703 ((c
== '+' || c
== '-') &&
3704 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3707 /* We add a trailing '\0' to ease parsing */
3708 cstr_ccat(&tokcstr
, '\0');
3709 tokc
.cstr
= &tokcstr
;
3713 /* special dot handling because it can also start a number */
3716 cstr_reset(&tokcstr
);
3717 cstr_ccat(&tokcstr
, '.');
3719 } else if (c
== '.') {
3739 /* parse the string */
3741 p
= parse_pp_string(p
, sep
, &str
);
3742 cstr_ccat(&str
, '\0');
3744 /* eval the escape (should be done as TOK_PPNUM) */
3745 cstr_reset(&tokcstr
);
3746 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3751 /* XXX: make it portable */
3755 char_size
= sizeof(nwchar_t
);
3756 if (tokcstr
.size
<= char_size
)
3757 error("empty character constant");
3758 if (tokcstr
.size
> 2 * char_size
)
3759 warning("multi-character character constant");
3761 tokc
.i
= *(int8_t *)tokcstr
.data
;
3764 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
3768 tokc
.cstr
= &tokcstr
;
3782 } else if (c
== '<') {
3800 } else if (c
== '>') {
3818 } else if (c
== '=') {
3831 } else if (c
== '=') {
3844 } else if (c
== '=') {
3857 } else if (c
== '=') {
3860 } else if (c
== '>') {
3868 PARSE2('!', '!', '=', TOK_NE
)
3869 PARSE2('=', '=', '=', TOK_EQ
)
3870 PARSE2('*', '*', '=', TOK_A_MUL
)
3871 PARSE2('%', '%', '=', TOK_A_MOD
)
3872 PARSE2('^', '^', '=', TOK_A_XOR
)
3874 /* comments or operator */
3878 p
= parse_comment(p
);
3880 } else if (c
== '/') {
3881 p
= parse_line_comment(p
);
3883 } else if (c
== '=') {
3903 case '$': /* only used in assembler */
3904 case '@': /* dito */
3909 error("unrecognized character \\x%02x", c
);
3914 #if defined(PARSE_DEBUG)
3915 printf("token = %s\n", get_tok_str(tok
, &tokc
));
3919 /* return next token without macro substitution. Can read input from
3921 static void next_nomacro(void)
3927 TOK_GET(tok
, macro_ptr
, tokc
);
3928 if (tok
== TOK_LINENUM
) {
3929 file
->line_num
= tokc
.i
;
3938 /* substitute args in macro_str and return allocated string */
3939 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
3941 int *st
, last_tok
, t
, notfirst
;
3950 TOK_GET(t
, macro_str
, cval
);
3955 TOK_GET(t
, macro_str
, cval
);
3958 s
= sym_find2(args
, t
);
3965 cstr_ccat(&cstr
, ' ');
3966 TOK_GET(t
, st
, cval
);
3967 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
3970 cstr_ccat(&cstr
, '\0');
3972 printf("stringize: %s\n", (char *)cstr
.data
);
3976 tok_str_add2(&str
, TOK_STR
, &cval
);
3979 tok_str_add2(&str
, t
, &cval
);
3981 } else if (t
>= TOK_IDENT
) {
3982 s
= sym_find2(args
, t
);
3985 /* if '##' is present before or after, no arg substitution */
3986 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
3987 /* special case for var arg macros : ## eats the
3988 ',' if empty VA_ARGS variable. */
3989 /* XXX: test of the ',' is not 100%
3990 reliable. should fix it to avoid security
3992 if (gnu_ext
&& s
->type
.t
&&
3993 last_tok
== TOK_TWOSHARPS
&&
3994 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
3996 /* suppress ',' '##' */
3999 /* suppress '##' and add variable */
4007 TOK_GET(t1
, st
, cval
);
4010 tok_str_add2(&str
, t1
, &cval
);
4014 /* NOTE: the stream cannot be read when macro
4015 substituing an argument */
4016 macro_subst(&str
, nested_list
, st
, NULL
);
4019 tok_str_add(&str
, t
);
4022 tok_str_add2(&str
, t
, &cval
);
4026 tok_str_add(&str
, 0);
4030 static char const ab_month_name
[12][4] =
4032 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
4033 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
4036 /* do macro substitution of current token with macro 's' and add
4037 result to (tok_str,tok_len). 'nested_list' is the list of all
4038 macros we got inside to avoid recursing. Return non zero if no
4039 substitution needs to be done */
4040 static int macro_subst_tok(TokenString
*tok_str
,
4041 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
4043 Sym
*args
, *sa
, *sa1
;
4044 int mstr_allocated
, parlevel
, *mstr
, t
, t1
;
4051 /* if symbol is a macro, prepare substitution */
4052 /* special macros */
4053 if (tok
== TOK___LINE__
) {
4054 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
4058 } else if (tok
== TOK___FILE__
) {
4059 cstrval
= file
->filename
;
4061 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
4066 tm
= localtime(&ti
);
4067 if (tok
== TOK___DATE__
) {
4068 snprintf(buf
, sizeof(buf
), "%s %2d %d",
4069 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
4071 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
4072 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
4079 cstr_cat(&cstr
, cstrval
);
4080 cstr_ccat(&cstr
, '\0');
4082 tok_str_add2(tok_str
, t1
, &cval
);
4087 if (s
->type
.t
== MACRO_FUNC
) {
4088 /* NOTE: we do not use next_nomacro to avoid eating the
4089 next token. XXX: find better solution */
4093 if (t
== 0 && can_read_stream
) {
4094 /* end of macro stream: we must look at the token
4095 after in the file */
4096 struct macro_level
*ml
= *can_read_stream
;
4102 *can_read_stream
= ml
-> prev
;
4107 /* XXX: incorrect with comments */
4108 ch
= file
->buf_ptr
[0];
4109 while (is_space(ch
) || ch
== '\n')
4113 if (t
!= '(') /* no macro subst */
4116 /* argument macro */
4121 /* NOTE: empty args are allowed, except if no args */
4123 /* handle '()' case */
4124 if (!args
&& !sa
&& tok
== ')')
4127 error("macro '%s' used with too many args",
4128 get_tok_str(s
->v
, 0));
4131 /* NOTE: non zero sa->t indicates VA_ARGS */
4132 while ((parlevel
> 0 ||
4134 (tok
!= ',' || sa
->type
.t
))) &&
4138 else if (tok
== ')')
4140 tok_str_add2(&str
, tok
, &tokc
);
4143 tok_str_add(&str
, 0);
4144 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (int)str
.str
);
4147 /* special case for gcc var args: add an empty
4148 var arg argument if it is omitted */
4149 if (sa
&& sa
->type
.t
&& gnu_ext
)
4159 error("macro '%s' used with too few args",
4160 get_tok_str(s
->v
, 0));
4163 /* now subst each arg */
4164 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
4169 tok_str_free((int *)sa
->c
);
4175 sym_push2(nested_list
, s
->v
, 0, 0);
4176 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
4177 /* pop nested defined symbol */
4179 *nested_list
= sa1
->prev
;
4187 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4188 return the resulting string (which must be freed). */
4189 static inline int *macro_twosharps(const int *macro_str
)
4192 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
4194 const char *p1
, *p2
;
4196 TokenString macro_str1
;
4199 start_macro_ptr
= macro_str
;
4200 /* we search the first '##' */
4202 macro_ptr1
= macro_str
;
4203 TOK_GET(t
, macro_str
, cval
);
4204 /* nothing more to do if end of string */
4207 if (*macro_str
== TOK_TWOSHARPS
)
4211 /* we saw '##', so we need more processing to handle it */
4213 tok_str_new(¯o_str1
);
4217 /* add all tokens seen so far */
4218 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
4219 TOK_GET(t
, ptr
, cval
);
4220 tok_str_add2(¯o_str1
, t
, &cval
);
4222 saved_macro_ptr
= macro_ptr
;
4223 /* XXX: get rid of the use of macro_ptr here */
4224 macro_ptr
= (int *)macro_str
;
4226 while (*macro_ptr
== TOK_TWOSHARPS
) {
4228 macro_ptr1
= macro_ptr
;
4231 TOK_GET(t
, macro_ptr
, cval
);
4232 /* We concatenate the two tokens if we have an
4233 identifier or a preprocessing number */
4235 p1
= get_tok_str(tok
, &tokc
);
4236 cstr_cat(&cstr
, p1
);
4237 p2
= get_tok_str(t
, &cval
);
4238 cstr_cat(&cstr
, p2
);
4239 cstr_ccat(&cstr
, '\0');
4241 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
4242 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
4243 if (tok
== TOK_PPNUM
) {
4244 /* if number, then create a number token */
4245 /* NOTE: no need to allocate because
4246 tok_str_add2() does it */
4247 cstr_reset(&tokcstr
);
4250 tokc
.cstr
= &tokcstr
;
4252 /* if identifier, we must do a test to
4253 validate we have a correct identifier */
4254 if (t
== TOK_PPNUM
) {
4264 if (!isnum(c
) && !isid(c
))
4268 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
4269 tok
= ts
->tok
; /* modify current token */
4272 const char *str
= cstr
.data
;
4273 const unsigned char *q
;
4275 /* we look for a valid token */
4276 /* XXX: do more extensive checks */
4277 if (!strcmp(str
, ">>=")) {
4279 } else if (!strcmp(str
, "<<=")) {
4281 } else if (strlen(str
) == 2) {
4282 /* search in two bytes table */
4287 if (q
[0] == str
[0] && q
[1] == str
[1])
4294 /* NOTE: because get_tok_str use a static buffer,
4297 p1
= get_tok_str(tok
, &tokc
);
4298 cstr_cat(&cstr
, p1
);
4299 cstr_ccat(&cstr
, '\0');
4300 p2
= get_tok_str(t
, &cval
);
4301 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
4302 /* cannot merge tokens: just add them separately */
4303 tok_str_add2(¯o_str1
, tok
, &tokc
);
4304 /* XXX: free associated memory ? */
4311 tok_str_add2(¯o_str1
, tok
, &tokc
);
4316 macro_ptr
= (int *)saved_macro_ptr
;
4318 tok_str_add(¯o_str1
, 0);
4319 return macro_str1
.str
;
4323 /* do macro substitution of macro_str and add result to
4324 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4325 inside to avoid recursing. */
4326 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
4327 const int *macro_str
, struct macro_level
** can_read_stream
)
4334 struct macro_level ml
;
4336 /* first scan for '##' operator handling */
4338 macro_str1
= macro_twosharps(ptr
);
4342 /* NOTE: ptr == NULL can only happen if tokens are read from
4343 file stream due to a macro function call */
4346 TOK_GET(t
, ptr
, cval
);
4351 /* if nested substitution, do nothing */
4352 if (sym_find2(*nested_list
, t
))
4355 if (can_read_stream
)
4356 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
4357 macro_ptr
= (int *)ptr
;
4359 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
4360 ptr
= (int *)macro_ptr
;
4362 if (can_read_stream
&& *can_read_stream
== &ml
)
4363 *can_read_stream
= ml
.prev
;
4368 tok_str_add2(tok_str
, t
, &cval
);
4372 tok_str_free(macro_str1
);
4375 /* return next token with macro substitution */
4376 static void next(void)
4378 Sym
*nested_list
, *s
;
4380 struct macro_level
*ml
;
4385 /* if not reading from macro substituted string, then try
4386 to substitute macros */
4387 if (tok
>= TOK_IDENT
&&
4388 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4389 s
= define_find(tok
);
4391 /* we have a macro: we try to substitute */
4395 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
4396 /* substitution done, NOTE: maybe empty */
4397 tok_str_add(&str
, 0);
4398 macro_ptr
= str
.str
;
4399 macro_ptr_allocated
= str
.str
;
4406 /* end of macro or end of unget buffer */
4407 if (unget_buffer_enabled
) {
4408 macro_ptr
= unget_saved_macro_ptr
;
4409 unget_buffer_enabled
= 0;
4411 /* end of macro string: free it */
4412 tok_str_free(macro_ptr_allocated
);
4419 /* convert preprocessor tokens into C tokens */
4420 if (tok
== TOK_PPNUM
&&
4421 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4422 parse_number((char *)tokc
.cstr
->data
);
4426 /* push back current token and set current token to 'last_tok'. Only
4427 identifier case handled for labels. */
4428 static inline void unget_tok(int last_tok
)
4432 unget_saved_macro_ptr
= macro_ptr
;
4433 unget_buffer_enabled
= 1;
4434 q
= unget_saved_buffer
;
4437 n
= tok_ext_size(tok
) - 1;
4440 *q
= 0; /* end of token string */
4445 void swap(int *p
, int *q
)
4453 void vsetc(CType
*type
, int r
, CValue
*vc
)
4457 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4458 error("memory full");
4459 /* cannot let cpu flags if other instruction are generated. Also
4460 avoid leaving VT_JMP anywhere except on the top of the stack
4461 because it would complicate the code generator. */
4462 if (vtop
>= vstack
) {
4463 v
= vtop
->r
& VT_VALMASK
;
4464 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4470 vtop
->r2
= VT_CONST
;
4474 /* push integer constant */
4479 vsetc(&int_type
, VT_CONST
, &cval
);
4482 /* Return a static symbol pointing to a section */
4483 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4484 unsigned long offset
, unsigned long size
)
4490 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4491 sym
->type
.ref
= type
->ref
;
4492 sym
->r
= VT_CONST
| VT_SYM
;
4493 put_extern_sym(sym
, sec
, offset
, size
);
4497 /* push a reference to a section offset by adding a dummy symbol */
4498 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4503 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4504 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4507 /* define a new external reference to a symbol 'v' of type 'u' */
4508 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4514 /* push forward reference */
4515 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4516 s
->type
.ref
= type
->ref
;
4517 s
->r
= r
| VT_CONST
| VT_SYM
;
4522 /* define a new external reference to a symbol 'v' of type 'u' */
4523 static Sym
*external_sym(int v
, CType
*type
, int r
)
4529 /* push forward reference */
4530 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4531 s
->type
.t
|= VT_EXTERN
;
4533 if (!is_compatible_types(&s
->type
, type
))
4534 error("incompatible types for redefinition of '%s'",
4535 get_tok_str(v
, NULL
));
4540 /* push a reference to global symbol v */
4541 static void vpush_global_sym(CType
*type
, int v
)
4546 sym
= external_global_sym(v
, type
, 0);
4548 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4552 void vset(CType
*type
, int r
, int v
)
4557 vsetc(type
, r
, &cval
);
4560 void vseti(int r
, int v
)
4576 void vpushv(SValue
*v
)
4578 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4579 error("memory full");
4589 /* save r to the memory stack, and mark it as being free */
4590 void save_reg(int r
)
4592 int l
, saved
, size
, align
;
4596 /* modify all stack values */
4599 for(p
=vstack
;p
<=vtop
;p
++) {
4600 if ((p
->r
& VT_VALMASK
) == r
||
4601 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& (p
->r2
& VT_VALMASK
) == r
)) {
4602 /* must save value on stack if not already done */
4604 /* NOTE: must reload 'r' because r might be equal to r2 */
4605 r
= p
->r
& VT_VALMASK
;
4606 /* store register in the stack */
4608 if ((p
->r
& VT_LVAL
) ||
4609 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4611 size
= type_size(type
, &align
);
4612 loc
= (loc
- size
) & -align
;
4613 sv
.type
.t
= type
->t
;
4614 sv
.r
= VT_LOCAL
| VT_LVAL
;
4617 #ifdef TCC_TARGET_I386
4618 /* x86 specific: need to pop fp register ST0 if saved */
4619 if (r
== TREG_ST0
) {
4620 o(0xd9dd); /* fstp %st(1) */
4623 /* special long long case */
4624 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4631 /* mark that stack entry as being saved on the stack */
4632 if (p
->r
& VT_LVAL
) {
4633 /* also clear the bounded flag because the
4634 relocation address of the function was stored in
4636 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4638 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4646 /* find a register of class 'rc2' with at most one reference on stack.
4647 * If none, call get_reg(rc) */
4648 int get_reg_ex(int rc
, int rc2
)
4653 for(r
=0;r
<NB_REGS
;r
++) {
4654 if (reg_classes
[r
] & rc2
) {
4657 for(p
= vstack
; p
<= vtop
; p
++) {
4658 if ((p
->r
& VT_VALMASK
) == r
||
4659 (p
->r2
& VT_VALMASK
) == r
)
4669 /* find a free register of class 'rc'. If none, save one register */
4675 /* find a free register */
4676 for(r
=0;r
<NB_REGS
;r
++) {
4677 if (reg_classes
[r
] & rc
) {
4678 for(p
=vstack
;p
<=vtop
;p
++) {
4679 if ((p
->r
& VT_VALMASK
) == r
||
4680 (p
->r2
& VT_VALMASK
) == r
)
4688 /* no register left : free the first one on the stack (VERY
4689 IMPORTANT to start from the bottom to ensure that we don't
4690 spill registers used in gen_opi()) */
4691 for(p
=vstack
;p
<=vtop
;p
++) {
4692 r
= p
->r
& VT_VALMASK
;
4693 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4695 /* also look at second register (if long long) */
4696 r
= p
->r2
& VT_VALMASK
;
4697 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4703 /* Should never comes here */
4707 /* save registers up to (vtop - n) stack entry */
4708 void save_regs(int n
)
4713 for(p
= vstack
;p
<= p1
; p
++) {
4714 r
= p
->r
& VT_VALMASK
;
4721 /* move register 's' to 'r', and flush previous value of r to memory
4723 void move_reg(int r
, int s
)
4736 /* get address of vtop (vtop MUST BE an lvalue) */
4739 vtop
->r
&= ~VT_LVAL
;
4740 /* tricky: if saved lvalue, then we can go back to lvalue */
4741 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4742 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4745 #ifdef CONFIG_TCC_BCHECK
4746 /* generate lvalue bound code */
4752 vtop
->r
&= ~VT_MUSTBOUND
;
4753 /* if lvalue, then use checking code before dereferencing */
4754 if (vtop
->r
& VT_LVAL
) {
4755 /* if not VT_BOUNDED value, then make one */
4756 if (!(vtop
->r
& VT_BOUNDED
)) {
4757 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4758 /* must save type because we must set it to int to get pointer */
4760 vtop
->type
.t
= VT_INT
;
4763 gen_bounded_ptr_add();
4764 vtop
->r
|= lval_type
;
4767 /* then check for dereferencing */
4768 gen_bounded_ptr_deref();
4773 /* store vtop a register belonging to class 'rc'. lvalues are
4774 converted to values. Cannot be used if cannot be converted to
4775 register value (such as structures). */
4778 int r
, r2
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4779 unsigned long long ll
;
4781 /* NOTE: get_reg can modify vstack[] */
4782 if (vtop
->type
.t
& VT_BITFIELD
) {
4783 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4784 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4785 /* remove bit field info to avoid loops */
4786 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4787 /* generate shifts */
4788 vpushi(32 - (bit_pos
+ bit_size
));
4790 vpushi(32 - bit_size
);
4791 /* NOTE: transformed to SHR if unsigned */
4795 if (is_float(vtop
->type
.t
) &&
4796 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4799 unsigned long offset
;
4801 /* XXX: unify with initializers handling ? */
4802 /* CPUs usually cannot use float constants, so we store them
4803 generically in data segment */
4804 size
= type_size(&vtop
->type
, &align
);
4805 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
4806 data_section
->data_offset
= offset
;
4807 /* XXX: not portable yet */
4809 /* Zero pad x87 tenbyte long doubles */
4811 vtop
->c
.tab
[2] &= 0xffff;
4813 ptr
= section_ptr_add(data_section
, size
);
4816 ptr
[i
] = vtop
->c
.tab
[i
];
4817 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
4818 vtop
->r
|= VT_LVAL
| VT_SYM
;
4822 #ifdef CONFIG_TCC_BCHECK
4823 if (vtop
->r
& VT_MUSTBOUND
)
4827 r
= vtop
->r
& VT_VALMASK
;
4828 /* need to reload if:
4830 - lvalue (need to dereference pointer)
4831 - already a register, but not in the right class */
4832 if (r
>= VT_CONST
||
4833 (vtop
->r
& VT_LVAL
) ||
4834 !(reg_classes
[r
] & rc
) ||
4835 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
4836 !(reg_classes
[vtop
->r2
] & rc
))) {
4838 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
4839 /* two register type load : expand to two words
4841 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4844 vtop
->c
.ui
= ll
; /* first word */
4846 vtop
->r
= r
; /* save register value */
4847 vpushi(ll
>> 32); /* second word */
4848 } else if (r
>= VT_CONST
|| /* XXX: test to VT_CONST incorrect ? */
4849 (vtop
->r
& VT_LVAL
)) {
4850 /* We do not want to modifier the long long
4851 pointer here, so the safest (and less
4852 efficient) is to save all the other registers
4853 in the stack. XXX: totally inefficient. */
4855 /* load from memory */
4858 vtop
[-1].r
= r
; /* save register value */
4859 /* increment pointer to get second word */
4860 vtop
->type
.t
= VT_INT
;
4866 /* move registers */
4869 vtop
[-1].r
= r
; /* save register value */
4870 vtop
->r
= vtop
[-1].r2
;
4872 /* allocate second register */
4879 /* write second register */
4881 } else if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
4883 /* lvalue of scalar type : need to use lvalue type
4884 because of possible cast */
4887 /* compute memory access type */
4888 if (vtop
->r
& VT_LVAL_BYTE
)
4890 else if (vtop
->r
& VT_LVAL_SHORT
)
4892 if (vtop
->r
& VT_LVAL_UNSIGNED
)
4896 /* restore wanted type */
4899 /* one register type load */
4904 #ifdef TCC_TARGET_C67
4905 /* uses register pairs for doubles */
4906 if ((vtop
->type
.t
& VT_BTYPE
) == VT_DOUBLE
)
4913 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
4914 void gv2(int rc1
, int rc2
)
4918 /* generate more generic register first. But VT_JMP or VT_CMP
4919 values must be generated first in all cases to avoid possible
4921 v
= vtop
[0].r
& VT_VALMASK
;
4922 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
4927 /* test if reload is needed for first register */
4928 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
4938 /* test if reload is needed for first register */
4939 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
4945 /* expand long long on stack in two int registers */
4950 u
= vtop
->type
.t
& VT_UNSIGNED
;
4953 vtop
[0].r
= vtop
[-1].r2
;
4954 vtop
[0].r2
= VT_CONST
;
4955 vtop
[-1].r2
= VT_CONST
;
4956 vtop
[0].type
.t
= VT_INT
| u
;
4957 vtop
[-1].type
.t
= VT_INT
| u
;
4960 #ifdef TCC_TARGET_ARM
4961 /* expand long long on stack */
4962 void lexpand_nr(void)
4966 u
= vtop
->type
.t
& VT_UNSIGNED
;
4968 vtop
->r2
= VT_CONST
;
4969 vtop
->type
.t
= VT_INT
| u
;
4970 v
=vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
);
4971 if (v
== VT_CONST
) {
4972 vtop
[-1].c
.ui
= vtop
->c
.ull
;
4973 vtop
->c
.ui
= vtop
->c
.ull
>> 32;
4975 } else if (v
== (VT_LVAL
|VT_CONST
) || v
== (VT_LVAL
|VT_LOCAL
)) {
4977 vtop
->r
= vtop
[-1].r
;
4978 } else if (v
> VT_CONST
) {
4982 vtop
->r
= vtop
[-1].r2
;
4983 vtop
[-1].r2
= VT_CONST
;
4984 vtop
[-1].type
.t
= VT_INT
| u
;
4988 /* build a long long from two ints */
4991 gv2(RC_INT
, RC_INT
);
4992 vtop
[-1].r2
= vtop
[0].r
;
4993 vtop
[-1].type
.t
= t
;
4997 /* rotate n first stack elements to the bottom
4998 I1 ... In -> I2 ... In I1 [top is right]
5006 for(i
=-n
+1;i
!=0;i
++)
5007 vtop
[i
] = vtop
[i
+1];
5011 /* rotate n first stack elements to the top
5012 I1 ... In -> In I1 ... I(n-1) [top is right]
5020 for(i
= 0;i
< n
- 1; i
++)
5021 vtop
[-i
] = vtop
[-i
- 1];
5025 #ifdef TCC_TARGET_ARM
5026 /* like vrott but in other direction
5027 In ... I1 -> I(n-1) ... I1 In [top is right]
5035 for(i
= n
- 1; i
> 0; i
--)
5036 vtop
[-i
] = vtop
[-i
+ 1];
5041 /* pop stack value */
5045 v
= vtop
->r
& VT_VALMASK
;
5046 #ifdef TCC_TARGET_I386
5047 /* for x86, we need to pop the FP stack */
5048 if (v
== TREG_ST0
&& !nocode_wanted
) {
5049 o(0xd9dd); /* fstp %st(1) */
5052 if (v
== VT_JMP
|| v
== VT_JMPI
) {
5053 /* need to put correct jump if && or || without test */
5059 /* convert stack entry to register and duplicate its value in another
5067 if ((t
& VT_BTYPE
) == VT_LLONG
) {
5074 /* stack: H L L1 H1 */
5082 /* duplicate value */
5093 load(r1
, &sv
); /* move r to r1 */
5095 /* duplicates value */
5100 /* generate CPU independent (unsigned) long long operations */
5101 void gen_opl(int op
)
5103 int t
, a
, b
, op1
, c
, i
;
5110 func
= TOK___divdi3
;
5113 func
= TOK___udivdi3
;
5116 func
= TOK___moddi3
;
5119 func
= TOK___umoddi3
;
5121 /* call generic long long function */
5122 vpush_global_sym(&func_old_type
, func
);
5127 vtop
->r2
= REG_LRET
;
5140 /* stack: L1 H1 L2 H2 */
5145 vtop
[-2] = vtop
[-3];
5148 /* stack: H1 H2 L1 L2 */
5154 /* stack: H1 H2 L1 L2 ML MH */
5157 /* stack: ML MH H1 H2 L1 L2 */
5161 /* stack: ML MH H1 L2 H2 L1 */
5166 /* stack: ML MH M1 M2 */
5169 } else if (op
== '+' || op
== '-') {
5170 /* XXX: add non carry method too (for MIPS or alpha) */
5176 /* stack: H1 H2 (L1 op L2) */
5179 gen_op(op1
+ 1); /* TOK_xxxC2 */
5182 /* stack: H1 H2 (L1 op L2) */
5185 /* stack: (L1 op L2) H1 H2 */
5187 /* stack: (L1 op L2) (H1 op H2) */
5195 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
5196 t
= vtop
[-1].type
.t
;
5200 /* stack: L H shift */
5202 /* constant: simpler */
5203 /* NOTE: all comments are for SHL. the other cases are
5204 done by swaping words */
5215 if (op
!= TOK_SAR
) {
5248 /* XXX: should provide a faster fallback on x86 ? */
5251 func
= TOK___sardi3
;
5254 func
= TOK___shrdi3
;
5257 func
= TOK___shldi3
;
5263 /* compare operations */
5269 /* stack: L1 H1 L2 H2 */
5271 vtop
[-1] = vtop
[-2];
5273 /* stack: L1 L2 H1 H2 */
5276 /* when values are equal, we need to compare low words. since
5277 the jump is inverted, we invert the test too. */
5280 else if (op1
== TOK_GT
)
5282 else if (op1
== TOK_ULT
)
5284 else if (op1
== TOK_UGT
)
5289 if (op1
!= TOK_NE
) {
5293 /* generate non equal test */
5294 /* XXX: NOT PORTABLE yet */
5298 #if defined(TCC_TARGET_I386)
5299 b
= psym(0x850f, 0);
5300 #elif defined(TCC_TARGET_ARM)
5302 o(0x1A000000 | encbranch(ind
, 0, 1));
5303 #elif defined(TCC_TARGET_C67)
5304 error("not implemented");
5306 #error not supported
5310 /* compare low. Always unsigned */
5314 else if (op1
== TOK_LE
)
5316 else if (op1
== TOK_GT
)
5318 else if (op1
== TOK_GE
)
5328 /* handle integer constant optimizations and various machine
5330 void gen_opic(int op
)
5337 /* currently, we cannot do computations with forward symbols */
5338 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5339 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5343 case '+': v1
->c
.i
+= fc
; break;
5344 case '-': v1
->c
.i
-= fc
; break;
5345 case '&': v1
->c
.i
&= fc
; break;
5346 case '^': v1
->c
.i
^= fc
; break;
5347 case '|': v1
->c
.i
|= fc
; break;
5348 case '*': v1
->c
.i
*= fc
; break;
5355 /* if division by zero, generate explicit division */
5358 error("division by zero in constant");
5362 default: v1
->c
.i
/= fc
; break;
5363 case '%': v1
->c
.i
%= fc
; break;
5364 case TOK_UDIV
: v1
->c
.i
= (unsigned)v1
->c
.i
/ fc
; break;
5365 case TOK_UMOD
: v1
->c
.i
= (unsigned)v1
->c
.i
% fc
; break;
5368 case TOK_SHL
: v1
->c
.i
<<= fc
; break;
5369 case TOK_SHR
: v1
->c
.i
= (unsigned)v1
->c
.i
>> fc
; break;
5370 case TOK_SAR
: v1
->c
.i
>>= fc
; break;
5372 case TOK_ULT
: v1
->c
.i
= (unsigned)v1
->c
.i
< (unsigned)fc
; break;
5373 case TOK_UGE
: v1
->c
.i
= (unsigned)v1
->c
.i
>= (unsigned)fc
; break;
5374 case TOK_EQ
: v1
->c
.i
= v1
->c
.i
== fc
; break;
5375 case TOK_NE
: v1
->c
.i
= v1
->c
.i
!= fc
; break;
5376 case TOK_ULE
: v1
->c
.i
= (unsigned)v1
->c
.i
<= (unsigned)fc
; break;
5377 case TOK_UGT
: v1
->c
.i
= (unsigned)v1
->c
.i
> (unsigned)fc
; break;
5378 case TOK_LT
: v1
->c
.i
= v1
->c
.i
< fc
; break;
5379 case TOK_GE
: v1
->c
.i
= v1
->c
.i
>= fc
; break;
5380 case TOK_LE
: v1
->c
.i
= v1
->c
.i
<= fc
; break;
5381 case TOK_GT
: v1
->c
.i
= v1
->c
.i
> fc
; break;
5383 case TOK_LAND
: v1
->c
.i
= v1
->c
.i
&& fc
; break;
5384 case TOK_LOR
: v1
->c
.i
= v1
->c
.i
|| fc
; break;
5390 /* if commutative ops, put c2 as constant */
5391 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
5392 op
== '|' || op
== '*')) {
5397 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
5400 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
5401 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
5407 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
5408 /* try to use shifts instead of muls or divs */
5409 if (fc
> 0 && (fc
& (fc
- 1)) == 0) {
5418 else if (op
== TOK_PDIV
)
5424 } else if (c2
&& (op
== '+' || op
== '-') &&
5425 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5426 (VT_CONST
| VT_SYM
)) {
5427 /* symbol + constant case */
5434 if (!nocode_wanted
) {
5435 /* call low level op generator */
5444 /* generate a floating point operation with constant propagation */
5445 void gen_opif(int op
)
5453 /* currently, we cannot do computations with forward symbols */
5454 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5455 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5457 if (v1
->type
.t
== VT_FLOAT
) {
5460 } else if (v1
->type
.t
== VT_DOUBLE
) {
5468 /* NOTE: we only do constant propagation if finite number (not
5469 NaN or infinity) (ANSI spec) */
5470 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5474 case '+': f1
+= f2
; break;
5475 case '-': f1
-= f2
; break;
5476 case '*': f1
*= f2
; break;
5480 error("division by zero in constant");
5485 /* XXX: also handles tests ? */
5489 /* XXX: overflow test ? */
5490 if (v1
->type
.t
== VT_FLOAT
) {
5492 } else if (v1
->type
.t
== VT_DOUBLE
) {
5500 if (!nocode_wanted
) {
5508 static int pointed_size(CType
*type
)
5511 return type_size(pointed_type(type
), &align
);
5514 static inline int is_null_pointer(SValue
*p
)
5516 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5518 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5519 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5522 static inline int is_integer_btype(int bt
)
5524 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5525 bt
== VT_INT
|| bt
== VT_LLONG
);
5528 /* check types for comparison or substraction of pointers */
5529 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5531 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5534 /* null pointers are accepted for all comparisons as gcc */
5535 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5539 bt1
= type1
->t
& VT_BTYPE
;
5540 bt2
= type2
->t
& VT_BTYPE
;
5541 /* accept comparison between pointer and integer with a warning */
5542 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5543 warning("comparison between pointer and integer");
5547 /* both must be pointers or implicit function pointers */
5548 if (bt1
== VT_PTR
) {
5549 type1
= pointed_type(type1
);
5550 } else if (bt1
!= VT_FUNC
)
5551 goto invalid_operands
;
5553 if (bt2
== VT_PTR
) {
5554 type2
= pointed_type(type2
);
5555 } else if (bt2
!= VT_FUNC
) {
5557 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5559 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5560 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5564 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5565 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5566 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5567 /* gcc-like error if '-' is used */
5569 goto invalid_operands
;
5571 warning("comparison of distinct pointer types lacks a cast");
5575 /* generic gen_op: handles types problems */
5578 int u
, t1
, t2
, bt1
, bt2
, t
;
5581 t1
= vtop
[-1].type
.t
;
5582 t2
= vtop
[0].type
.t
;
5583 bt1
= t1
& VT_BTYPE
;
5584 bt2
= t2
& VT_BTYPE
;
5586 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5587 /* at least one operand is a pointer */
5588 /* relationnal op: must be both pointers */
5589 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5590 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5591 /* pointers are handled are unsigned */
5592 t
= VT_INT
| VT_UNSIGNED
;
5595 /* if both pointers, then it must be the '-' op */
5596 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5598 error("cannot use pointers here");
5599 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5600 /* XXX: check that types are compatible */
5601 u
= pointed_size(&vtop
[-1].type
);
5603 /* set to integer type */
5604 vtop
->type
.t
= VT_INT
;
5608 /* exactly one pointer : must be '+' or '-'. */
5609 if (op
!= '-' && op
!= '+')
5610 error("cannot use pointers here");
5611 /* Put pointer as first operand */
5612 if (bt2
== VT_PTR
) {
5616 type1
= vtop
[-1].type
;
5617 /* XXX: cast to int ? (long long case) */
5618 vpushi(pointed_size(&vtop
[-1].type
));
5620 #ifdef CONFIG_TCC_BCHECK
5621 /* if evaluating constant expression, no code should be
5622 generated, so no bound check */
5623 if (do_bounds_check
&& !const_wanted
) {
5624 /* if bounded pointers, we generate a special code to
5631 gen_bounded_ptr_add();
5637 /* put again type if gen_opic() swaped operands */
5640 } else if (is_float(bt1
) || is_float(bt2
)) {
5641 /* compute bigger type and do implicit casts */
5642 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5644 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5649 /* floats can only be used for a few operations */
5650 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5651 (op
< TOK_ULT
|| op
> TOK_GT
))
5652 error("invalid operands for binary operation");
5654 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5655 /* cast to biggest op */
5657 /* convert to unsigned if it does not fit in a long long */
5658 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5659 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5663 /* integer operations */
5665 /* convert to unsigned if it does not fit in an integer */
5666 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5667 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5670 /* XXX: currently, some unsigned operations are explicit, so
5671 we modify them here */
5672 if (t
& VT_UNSIGNED
) {
5679 else if (op
== TOK_LT
)
5681 else if (op
== TOK_GT
)
5683 else if (op
== TOK_LE
)
5685 else if (op
== TOK_GE
)
5692 /* special case for shifts and long long: we keep the shift as
5694 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5699 else if ((t
& VT_BTYPE
) == VT_LLONG
)
5703 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5704 /* relationnal op: the result is an int */
5705 vtop
->type
.t
= VT_INT
;
5712 /* generic itof for unsigned long long case */
5713 void gen_cvt_itof1(int t
)
5715 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
5716 (VT_LLONG
| VT_UNSIGNED
)) {
5719 vpush_global_sym(&func_old_type
, TOK___ulltof
);
5720 else if (t
== VT_DOUBLE
)
5721 vpush_global_sym(&func_old_type
, TOK___ulltod
);
5723 vpush_global_sym(&func_old_type
, TOK___ulltold
);
5733 /* generic ftoi for unsigned long long case */
5734 void gen_cvt_ftoi1(int t
)
5738 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
5739 /* not handled natively */
5740 st
= vtop
->type
.t
& VT_BTYPE
;
5742 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
5743 else if (st
== VT_DOUBLE
)
5744 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
5746 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
5751 vtop
->r2
= REG_LRET
;
5757 /* force char or short cast */
5758 void force_charshort_cast(int t
)
5762 /* XXX: add optimization if lvalue : just change type and offset */
5767 if (t
& VT_UNSIGNED
) {
5768 vpushi((1 << bits
) - 1);
5774 /* result must be signed or the SAR is converted to an SHL
5775 This was not the case when "t" was a signed short
5776 and the last value on the stack was an unsigned int */
5777 vtop
->type
.t
&= ~VT_UNSIGNED
;
5783 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
5784 static void gen_cast(CType
*type
)
5786 int sbt
, dbt
, sf
, df
, c
;
5788 /* special delayed cast for char/short */
5789 /* XXX: in some cases (multiple cascaded casts), it may still
5791 if (vtop
->r
& VT_MUSTCAST
) {
5792 vtop
->r
&= ~VT_MUSTCAST
;
5793 force_charshort_cast(vtop
->type
.t
);
5796 /* bitfields first get cast to ints */
5797 if (vtop
->type
.t
& VT_BITFIELD
) {
5801 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
5802 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
5804 if (sbt
!= dbt
&& !nocode_wanted
) {
5807 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5809 /* convert from fp to fp */
5811 /* constant case: we can do it now */
5812 /* XXX: in ISOC, cannot do it if error in convert */
5813 if (dbt
== VT_FLOAT
&& sbt
== VT_DOUBLE
)
5814 vtop
->c
.f
= (float)vtop
->c
.d
;
5815 else if (dbt
== VT_FLOAT
&& sbt
== VT_LDOUBLE
)
5816 vtop
->c
.f
= (float)vtop
->c
.ld
;
5817 else if (dbt
== VT_DOUBLE
&& sbt
== VT_FLOAT
)
5818 vtop
->c
.d
= (double)vtop
->c
.f
;
5819 else if (dbt
== VT_DOUBLE
&& sbt
== VT_LDOUBLE
)
5820 vtop
->c
.d
= (double)vtop
->c
.ld
;
5821 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_FLOAT
)
5822 vtop
->c
.ld
= (long double)vtop
->c
.f
;
5823 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_DOUBLE
)
5824 vtop
->c
.ld
= (long double)vtop
->c
.d
;
5826 /* non constant case: generate code */
5830 /* convert int to fp */
5833 case VT_LLONG
| VT_UNSIGNED
:
5835 /* XXX: add const cases for long long */
5837 case VT_INT
| VT_UNSIGNED
:
5839 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.ui
; break;
5840 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.ui
; break;
5841 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.ui
; break;
5846 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.i
; break;
5847 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.i
; break;
5848 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.i
; break;
5854 #if !defined(TCC_TARGET_ARM)
5861 /* convert fp to int */
5862 if (dbt
== VT_BOOL
) {
5866 /* we handle char/short/etc... with generic code */
5867 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
5868 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
5873 case VT_LLONG
| VT_UNSIGNED
:
5875 /* XXX: add const cases for long long */
5877 case VT_INT
| VT_UNSIGNED
:
5879 case VT_FLOAT
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5880 case VT_DOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5881 case VT_LDOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5887 case VT_FLOAT
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5888 case VT_DOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5889 case VT_LDOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5897 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
5898 /* additional cast for char/short... */
5903 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
5904 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
5905 /* scalar to long long */
5907 if (sbt
== (VT_INT
| VT_UNSIGNED
))
5908 vtop
->c
.ll
= vtop
->c
.ui
;
5910 vtop
->c
.ll
= vtop
->c
.i
;
5912 /* machine independent conversion */
5914 /* generate high word */
5915 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
5923 /* patch second register */
5924 vtop
[-1].r2
= vtop
->r
;
5928 } else if (dbt
== VT_BOOL
) {
5929 /* scalar to bool */
5932 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
5933 (dbt
& VT_BTYPE
) == VT_SHORT
) {
5934 if (sbt
== VT_PTR
) {
5935 vtop
->type
.t
= VT_INT
;
5936 warning("nonportable conversion from pointer to char/short");
5938 force_charshort_cast(dbt
);
5939 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
5941 if (sbt
== VT_LLONG
) {
5942 /* from long long: just take low order word */
5946 /* if lvalue and single word type, nothing to do because
5947 the lvalue already contains the real type size (see
5948 VT_LVAL_xxx constants) */
5954 /* return type size. Put alignment at 'a' */
5955 static int type_size(CType
*type
, int *a
)
5960 bt
= type
->t
& VT_BTYPE
;
5961 if (bt
== VT_STRUCT
) {
5966 } else if (bt
== VT_PTR
) {
5967 if (type
->t
& VT_ARRAY
) {
5969 return type_size(&s
->type
, a
) * s
->c
;
5974 } else if (bt
== VT_LDOUBLE
) {
5976 return LDOUBLE_SIZE
;
5977 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
5978 #ifdef TCC_TARGET_I386
5984 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
5987 } else if (bt
== VT_SHORT
) {
5991 /* char, void, function, _Bool */
5997 /* return the pointed type of t */
5998 static inline CType
*pointed_type(CType
*type
)
6000 return &type
->ref
->type
;
6003 /* modify type so that its it is a pointer to type. */
6004 static void mk_pointer(CType
*type
)
6007 s
= sym_push(SYM_FIELD
, type
, 0, -1);
6008 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
6012 /* compare function types. OLD functions match any new functions */
6013 static int is_compatible_func(CType
*type1
, CType
*type2
)
6019 if (!is_compatible_types(&s1
->type
, &s2
->type
))
6021 /* check func_call */
6024 /* XXX: not complete */
6025 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
6029 while (s1
!= NULL
) {
6032 if (!is_compatible_parameter_types(&s1
->type
, &s2
->type
))
6042 /* return true if type1 and type2 are the same. If unqualified is
6043 true, qualifiers on the types are ignored.
6045 - enums are not checked as gcc __builtin_types_compatible_p ()
6047 static int compare_types(CType
*type1
, CType
*type2
, int unqualified
)
6051 t1
= type1
->t
& VT_TYPE
;
6052 t2
= type2
->t
& VT_TYPE
;
6054 /* strip qualifiers before comparing */
6055 t1
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6056 t2
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6058 /* XXX: bitfields ? */
6061 /* test more complicated cases */
6062 bt1
= t1
& VT_BTYPE
;
6063 if (bt1
== VT_PTR
) {
6064 type1
= pointed_type(type1
);
6065 type2
= pointed_type(type2
);
6066 return is_compatible_types(type1
, type2
);
6067 } else if (bt1
== VT_STRUCT
) {
6068 return (type1
->ref
== type2
->ref
);
6069 } else if (bt1
== VT_FUNC
) {
6070 return is_compatible_func(type1
, type2
);
6076 /* return true if type1 and type2 are exactly the same (including
6079 static int is_compatible_types(CType
*type1
, CType
*type2
)
6081 return compare_types(type1
,type2
,0);
6084 /* return true if type1 and type2 are the same (ignoring qualifiers).
6086 static int is_compatible_parameter_types(CType
*type1
, CType
*type2
)
6088 return compare_types(type1
,type2
,1);
6091 /* print a type. If 'varstr' is not NULL, then the variable is also
6092 printed in the type */
6094 /* XXX: add array and function pointers */
6095 void type_to_str(char *buf
, int buf_size
,
6096 CType
*type
, const char *varstr
)
6103 t
= type
->t
& VT_TYPE
;
6106 if (t
& VT_CONSTANT
)
6107 pstrcat(buf
, buf_size
, "const ");
6108 if (t
& VT_VOLATILE
)
6109 pstrcat(buf
, buf_size
, "volatile ");
6110 if (t
& VT_UNSIGNED
)
6111 pstrcat(buf
, buf_size
, "unsigned ");
6141 tstr
= "long double";
6143 pstrcat(buf
, buf_size
, tstr
);
6147 if (bt
== VT_STRUCT
)
6151 pstrcat(buf
, buf_size
, tstr
);
6152 v
= type
->ref
->v
& ~SYM_STRUCT
;
6153 if (v
>= SYM_FIRST_ANOM
)
6154 pstrcat(buf
, buf_size
, "<anonymous>");
6156 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
6160 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
6161 pstrcat(buf
, buf_size
, "(");
6163 while (sa
!= NULL
) {
6164 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
6165 pstrcat(buf
, buf_size
, buf1
);
6168 pstrcat(buf
, buf_size
, ", ");
6170 pstrcat(buf
, buf_size
, ")");
6174 pstrcpy(buf1
, sizeof(buf1
), "*");
6176 pstrcat(buf1
, sizeof(buf1
), varstr
);
6177 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
6181 pstrcat(buf
, buf_size
, " ");
6182 pstrcat(buf
, buf_size
, varstr
);
6187 /* verify type compatibility to store vtop in 'dt' type, and generate
6189 static void gen_assign_cast(CType
*dt
)
6191 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
6192 char buf1
[256], buf2
[256];
6195 st
= &vtop
->type
; /* source type */
6196 dbt
= dt
->t
& VT_BTYPE
;
6197 sbt
= st
->t
& VT_BTYPE
;
6198 if (dt
->t
& VT_CONSTANT
)
6199 warning("assignment of read-only location");
6202 /* special cases for pointers */
6203 /* '0' can also be a pointer */
6204 if (is_null_pointer(vtop
))
6206 /* accept implicit pointer to integer cast with warning */
6207 if (is_integer_btype(sbt
)) {
6208 warning("assignment makes pointer from integer without a cast");
6211 type1
= pointed_type(dt
);
6212 /* a function is implicitely a function pointer */
6213 if (sbt
== VT_FUNC
) {
6214 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
6215 !is_compatible_types(pointed_type(dt
), st
))
6222 type2
= pointed_type(st
);
6223 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
6224 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
6225 /* void * can match anything */
6227 /* exact type match, except for unsigned */
6230 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6231 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6232 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
6233 warning("assignment from incompatible pointer type");
6235 /* check const and volatile */
6236 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
6237 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
6238 warning("assignment discards qualifiers from pointer target type");
6244 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
6245 warning("assignment makes integer from pointer without a cast");
6247 /* XXX: more tests */
6252 tmp_type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6253 tmp_type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6254 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
6256 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
6257 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
6258 error("cannot cast '%s' to '%s'", buf1
, buf2
);
6266 /* store vtop in lvalue pushed on stack */
6269 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
6271 ft
= vtop
[-1].type
.t
;
6272 sbt
= vtop
->type
.t
& VT_BTYPE
;
6273 dbt
= ft
& VT_BTYPE
;
6274 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
6275 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
6276 /* optimize char/short casts */
6277 delayed_cast
= VT_MUSTCAST
;
6278 vtop
->type
.t
= ft
& VT_TYPE
;
6279 /* XXX: factorize */
6280 if (ft
& VT_CONSTANT
)
6281 warning("assignment of read-only location");
6284 if (!(ft
& VT_BITFIELD
))
6285 gen_assign_cast(&vtop
[-1].type
);
6288 if (sbt
== VT_STRUCT
) {
6289 /* if structure, only generate pointer */
6290 /* structure assignment : generate memcpy */
6291 /* XXX: optimize if small size */
6292 if (!nocode_wanted
) {
6293 size
= type_size(&vtop
->type
, &align
);
6295 vpush_global_sym(&func_old_type
, TOK_memcpy
);
6299 vtop
->type
.t
= VT_INT
;
6303 vtop
->type
.t
= VT_INT
;
6315 /* leave source on stack */
6316 } else if (ft
& VT_BITFIELD
) {
6317 /* bitfield store handling */
6318 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
6319 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
6320 /* remove bit field info to avoid loops */
6321 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
6323 /* duplicate source into other register */
6328 /* duplicate destination */
6330 vtop
[-1] = vtop
[-2];
6332 /* mask and shift source */
6333 vpushi((1 << bit_size
) - 1);
6337 /* load destination, mask and or with source */
6339 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
6345 /* pop off shifted source from "duplicate source..." above */
6349 #ifdef CONFIG_TCC_BCHECK
6350 /* bound check case */
6351 if (vtop
[-1].r
& VT_MUSTBOUND
) {
6357 if (!nocode_wanted
) {
6361 r
= gv(rc
); /* generate value */
6362 /* if lvalue was saved on stack, must read it */
6363 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
6365 t
= get_reg(RC_INT
);
6367 sv
.r
= VT_LOCAL
| VT_LVAL
;
6368 sv
.c
.ul
= vtop
[-1].c
.ul
;
6370 vtop
[-1].r
= t
| VT_LVAL
;
6373 /* two word case handling : store second register at word + 4 */
6374 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
6376 /* convert to int to increment easily */
6377 vtop
->type
.t
= VT_INT
;
6383 /* XXX: it works because r2 is spilled last ! */
6384 store(vtop
->r2
, vtop
- 1);
6388 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
6389 vtop
->r
|= delayed_cast
;
6393 /* post defines POST/PRE add. c is the token ++ or -- */
6394 void inc(int post
, int c
)
6397 vdup(); /* save lvalue */
6399 gv_dup(); /* duplicate value */
6404 vpushi(c
- TOK_MID
);
6406 vstore(); /* store value */
6408 vpop(); /* if post op, return saved value */
6411 /* Parse GNUC __attribute__ extension. Currently, the following
6412 extensions are recognized:
6413 - aligned(n) : set data/function alignment.
6414 - packed : force data alignment to 1
6415 - section(x) : generate data/code in this section.
6416 - unused : currently ignored, but may be used someday.
6417 - regparm(n) : pass function parameters in registers (i386 only)
6419 static void parse_attribute(AttributeDef
*ad
)
6423 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
6427 while (tok
!= ')') {
6428 if (tok
< TOK_IDENT
)
6429 expect("attribute name");
6437 expect("section name");
6438 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
6447 if (n
<= 0 || (n
& (n
- 1)) != 0)
6448 error("alignment must be a positive power of two");
6461 /* currently, no need to handle it because tcc does not
6462 track unused objects */
6466 /* currently, no need to handle it because tcc does not
6467 track unused objects */
6472 ad
->func_call
= FUNC_CDECL
;
6477 ad
->func_call
= FUNC_STDCALL
;
6479 #ifdef TCC_TARGET_I386
6489 ad
->func_call
= FUNC_FASTCALL1
+ n
- 1;
6495 ad
->func_call
= FUNC_FASTCALLW
;
6502 if (tcc_state
->warn_unsupported
)
6503 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6504 /* skip parameters */
6505 /* XXX: skip parenthesis too */
6508 while (tok
!= ')' && tok
!= -1)
6523 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6524 static void struct_decl(CType
*type
, int u
)
6526 int a
, v
, size
, align
, maxalign
, c
, offset
;
6527 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
;
6528 Sym
*s
, *ss
, *ass
, **ps
;
6532 a
= tok
; /* save decl type */
6537 /* struct already defined ? return it */
6539 expect("struct/union/enum name");
6543 error("invalid type");
6550 /* we put an undefined size for struct/union */
6551 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6552 s
->r
= 0; /* default alignment is zero as gcc */
6553 /* put struct/union/enum name in type */
6561 error("struct/union/enum already defined");
6562 /* cannot be empty */
6564 /* non empty enums are not allowed */
6565 if (a
== TOK_ENUM
) {
6569 expect("identifier");
6575 /* enum symbols have static storage */
6576 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6577 ss
->type
.t
|= VT_STATIC
;
6582 /* NOTE: we accept a trailing comma */
6592 while (tok
!= '}') {
6593 parse_btype(&btype
, &ad
);
6599 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6600 if (v
== 0 && (type1
.t
& VT_BTYPE
) != VT_STRUCT
)
6601 expect("identifier");
6602 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6603 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6604 error("invalid type for '%s'",
6605 get_tok_str(v
, NULL
));
6609 bit_size
= expr_const();
6610 /* XXX: handle v = 0 case for messages */
6612 error("negative width in bit-field '%s'",
6613 get_tok_str(v
, NULL
));
6614 if (v
&& bit_size
== 0)
6615 error("zero width for bit-field '%s'",
6616 get_tok_str(v
, NULL
));
6618 size
= type_size(&type1
, &align
);
6620 if (align
< ad
.aligned
)
6622 } else if (ad
.packed
) {
6624 } else if (*tcc_state
->pack_stack_ptr
) {
6625 if (align
> *tcc_state
->pack_stack_ptr
)
6626 align
= *tcc_state
->pack_stack_ptr
;
6629 if (bit_size
>= 0) {
6630 bt
= type1
.t
& VT_BTYPE
;
6636 error("bitfields must have scalar type");
6638 if (bit_size
> bsize
) {
6639 error("width of '%s' exceeds its type",
6640 get_tok_str(v
, NULL
));
6641 } else if (bit_size
== bsize
) {
6642 /* no need for bit fields */
6644 } else if (bit_size
== 0) {
6645 /* XXX: what to do if only padding in a
6647 /* zero size: means to pad */
6651 /* we do not have enough room ? */
6652 if ((bit_pos
+ bit_size
) > bsize
)
6655 /* XXX: handle LSB first */
6656 type1
.t
|= VT_BITFIELD
|
6657 (bit_pos
<< VT_STRUCT_SHIFT
) |
6658 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
6659 bit_pos
+= bit_size
;
6664 if (v
!= 0 || (type1
.t
& VT_BTYPE
) == VT_STRUCT
) {
6665 /* add new memory data only if starting
6667 if (lbit_pos
== 0) {
6668 if (a
== TOK_STRUCT
) {
6669 c
= (c
+ align
- 1) & -align
;
6677 if (align
> maxalign
)
6681 printf("add field %s offset=%d",
6682 get_tok_str(v
, NULL
), offset
);
6683 if (type1
.t
& VT_BITFIELD
) {
6684 printf(" pos=%d size=%d",
6685 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
6686 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
6691 if (v
== 0 && (type1
.t
& VT_BTYPE
) == VT_STRUCT
) {
6693 while ((ass
= ass
->next
) != NULL
) {
6694 ss
= sym_push(ass
->v
, &ass
->type
, 0, offset
+ ass
->c
);
6699 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
6703 if (tok
== ';' || tok
== TOK_EOF
)
6710 /* store size and alignment */
6711 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
6717 /* return 0 if no type declaration. otherwise, return the basic type
6720 static int parse_btype(CType
*type
, AttributeDef
*ad
)
6722 int t
, u
, type_found
, typespec_found
;
6726 memset(ad
, 0, sizeof(AttributeDef
));
6733 /* currently, we really ignore extension */
6743 if ((t
& VT_BTYPE
) != 0)
6744 error("too many basic types");
6760 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
6761 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6762 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
6763 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
6777 if ((t
& VT_BTYPE
) == VT_LONG
) {
6778 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6785 struct_decl(&type1
, VT_ENUM
);
6788 type
->ref
= type1
.ref
;
6792 struct_decl(&type1
, VT_STRUCT
);
6795 /* type modifiers */
6848 /* GNUC attribute */
6849 case TOK_ATTRIBUTE1
:
6850 case TOK_ATTRIBUTE2
:
6851 parse_attribute(ad
);
6858 parse_expr_type(&type1
);
6864 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
6866 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
6867 type
->ref
= s
->type
.ref
;
6875 if ((t
& (VT_SIGNED
|VT_UNSIGNED
)) == (VT_SIGNED
|VT_UNSIGNED
))
6876 error("signed and unsigned modifier");
6877 if (tcc_state
->char_is_unsigned
) {
6878 if ((t
& (VT_SIGNED
|VT_UNSIGNED
|VT_BTYPE
)) == VT_BYTE
)
6883 /* long is never used as type */
6884 if ((t
& VT_BTYPE
) == VT_LONG
)
6885 t
= (t
& ~VT_BTYPE
) | VT_INT
;
6890 /* convert a function parameter type (array to pointer and function to
6891 function pointer) */
6892 static inline void convert_parameter_type(CType
*pt
)
6894 /* remove const and volatile qualifiers (XXX: const could be used
6895 to indicate a const function parameter */
6896 pt
->t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6897 /* array must be transformed to pointer according to ANSI C */
6899 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
6904 static void post_type(CType
*type
, AttributeDef
*ad
)
6907 Sym
**plast
, *s
, *first
;
6912 /* function declaration */
6919 /* read param name and compute offset */
6920 if (l
!= FUNC_OLD
) {
6921 if (!parse_btype(&pt
, &ad1
)) {
6923 error("invalid type");
6930 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
6932 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6933 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
6934 error("parameter declared as void");
6939 expect("identifier");
6943 convert_parameter_type(&pt
);
6944 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
6950 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
6957 /* if no parameters, then old type prototype */
6961 t1
= type
->t
& VT_STORAGE
;
6962 /* NOTE: const is ignored in returned type as it has a special
6963 meaning in gcc / C++ */
6964 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
6965 post_type(type
, ad
);
6966 /* we push a anonymous symbol which will contain the function prototype */
6967 s
= sym_push(SYM_FIELD
, type
, ad
->func_call
, l
);
6969 type
->t
= t1
| VT_FUNC
;
6971 } else if (tok
== '[') {
6972 /* array definition */
6978 error("invalid array size");
6981 /* parse next post type */
6982 t1
= type
->t
& VT_STORAGE
;
6983 type
->t
&= ~VT_STORAGE
;
6984 post_type(type
, ad
);
6986 /* we push a anonymous symbol which will contain the array
6988 s
= sym_push(SYM_FIELD
, type
, 0, n
);
6989 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
6994 /* Parse a type declaration (except basic type), and return the type
6995 in 'type'. 'td' is a bitmask indicating which kind of type decl is
6996 expected. 'type' should contain the basic type. 'ad' is the
6997 attribute definition of the basic type. It can be modified by
7000 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
7003 CType type1
, *type2
;
7006 while (tok
== '*') {
7014 qualifiers
|= VT_CONSTANT
;
7019 qualifiers
|= VT_VOLATILE
;
7027 type
->t
|= qualifiers
;
7030 /* XXX: clarify attribute handling */
7031 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7032 parse_attribute(ad
);
7034 /* recursive type */
7035 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
7036 type1
.t
= 0; /* XXX: same as int */
7039 /* XXX: this is not correct to modify 'ad' at this point, but
7040 the syntax is not clear */
7041 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7042 parse_attribute(ad
);
7043 type_decl(&type1
, ad
, v
, td
);
7046 /* type identifier */
7047 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
7051 if (!(td
& TYPE_ABSTRACT
))
7052 expect("identifier");
7056 post_type(type
, ad
);
7057 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
7058 parse_attribute(ad
);
7061 /* append type at the end of type1 */
7074 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
7075 static int lvalue_type(int t
)
7080 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
7082 else if (bt
== VT_SHORT
)
7086 if (t
& VT_UNSIGNED
)
7087 r
|= VT_LVAL_UNSIGNED
;
7091 /* indirection with full error checking and bound check */
7092 static void indir(void)
7094 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
) {
7095 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FUNC
)
7099 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
7101 vtop
->type
= *pointed_type(&vtop
->type
);
7102 /* Arrays and functions are never lvalues */
7103 if (!(vtop
->type
.t
& VT_ARRAY
)
7104 && (vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7105 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7106 /* if bound checking, the referenced pointer must be checked */
7107 if (do_bounds_check
)
7108 vtop
->r
|= VT_MUSTBOUND
;
7112 /* pass a parameter to a function and do type checking and casting */
7113 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
7118 func_type
= func
->c
;
7119 if (func_type
== FUNC_OLD
||
7120 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
7121 /* default casting : only need to convert float to double */
7122 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
7126 } else if (arg
== NULL
) {
7127 error("too many arguments to function");
7130 type
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
7131 gen_assign_cast(&type
);
7135 /* parse an expression of the form '(type)' or '(expr)' and return its
7137 static void parse_expr_type(CType
*type
)
7143 if (parse_btype(type
, &ad
)) {
7144 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7151 static void parse_type(CType
*type
)
7156 if (!parse_btype(type
, &ad
)) {
7159 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7162 static void vpush_tokc(int t
)
7166 vsetc(&type
, VT_CONST
, &tokc
);
7169 static void unary(void)
7171 int n
, t
, align
, size
, r
;
7176 /* XXX: GCC 2.95.3 does not generate a table although it should be
7190 vpush_tokc(VT_INT
| VT_UNSIGNED
);
7194 vpush_tokc(VT_LLONG
);
7198 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
7202 vpush_tokc(VT_FLOAT
);
7206 vpush_tokc(VT_DOUBLE
);
7210 vpush_tokc(VT_LDOUBLE
);
7213 case TOK___FUNCTION__
:
7215 goto tok_identifier
;
7221 /* special function name identifier */
7222 len
= strlen(funcname
) + 1;
7223 /* generate char[len] type */
7228 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
7229 ptr
= section_ptr_add(data_section
, len
);
7230 memcpy(ptr
, funcname
, len
);
7235 #ifdef TCC_TARGET_PE
7236 t
= VT_SHORT
| VT_UNSIGNED
;
7242 /* string parsing */
7245 if (tcc_state
->warn_write_strings
)
7250 memset(&ad
, 0, sizeof(AttributeDef
));
7251 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
7256 if (parse_btype(&type
, &ad
)) {
7257 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
7259 /* check ISOC99 compound literal */
7261 /* data is allocated locally by default */
7266 /* all except arrays are lvalues */
7267 if (!(type
.t
& VT_ARRAY
))
7268 r
|= lvalue_type(type
.t
);
7269 memset(&ad
, 0, sizeof(AttributeDef
));
7270 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
7275 } else if (tok
== '{') {
7276 /* save all registers */
7278 /* statement expression : we do not accept break/continue
7279 inside as GCC does */
7280 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
7295 /* functions names must be treated as function pointers,
7296 except for unary '&' and sizeof. Since we consider that
7297 functions are not lvalues, we only have to handle it
7298 there and in function calls. */
7299 /* arrays can also be used although they are not lvalues */
7300 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
7301 !(vtop
->type
.t
& VT_ARRAY
) && !(vtop
->type
.t
& VT_LLOCAL
))
7303 mk_pointer(&vtop
->type
);
7309 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
)
7310 vtop
->c
.i
= !vtop
->c
.i
;
7311 else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
7312 vtop
->c
.i
= vtop
->c
.i
^ 1;
7315 vseti(VT_JMP
, gtst(1, 0));
7326 /* in order to force cast, we add zero */
7328 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
7329 error("pointer not accepted for unary plus");
7339 parse_expr_type(&type
);
7343 size
= type_size(&type
, &align
);
7344 if (t
== TOK_SIZEOF
) {
7346 error("sizeof applied to an incomplete type");
7351 vtop
->type
.t
|= VT_UNSIGNED
;
7354 case TOK_builtin_types_compatible_p
:
7363 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7364 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7365 vpushi(is_compatible_types(&type1
, &type2
));
7368 case TOK_builtin_constant_p
:
7370 int saved_nocode_wanted
, res
;
7373 saved_nocode_wanted
= nocode_wanted
;
7376 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
7378 nocode_wanted
= saved_nocode_wanted
;
7398 goto tok_identifier
;
7400 /* allow to take the address of a label */
7401 if (tok
< TOK_UIDENT
)
7402 expect("label identifier");
7403 s
= label_find(tok
);
7405 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7407 if (s
->r
== LABEL_DECLARED
)
7408 s
->r
= LABEL_FORWARD
;
7411 s
->type
.t
= VT_VOID
;
7412 mk_pointer(&s
->type
);
7413 s
->type
.t
|= VT_STATIC
;
7415 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
7424 expect("identifier");
7428 error("'%s' undeclared", get_tok_str(t
, NULL
));
7429 /* for simple function calls, we tolerate undeclared
7430 external reference to int() function */
7431 if (tcc_state
->warn_implicit_function_declaration
)
7432 warning("implicit declaration of function '%s'",
7433 get_tok_str(t
, NULL
));
7434 s
= external_global_sym(t
, &func_old_type
, 0);
7436 if ((s
->type
.t
& (VT_STATIC
| VT_INLINE
| VT_BTYPE
)) ==
7437 (VT_STATIC
| VT_INLINE
| VT_FUNC
)) {
7438 /* if referencing an inline function, then we generate a
7439 symbol to it if not already done. It will have the
7440 effect to generate code for it at the end of the
7441 compilation unit. Inline function as always
7442 generated in the text section. */
7444 put_extern_sym(s
, text_section
, 0, 0);
7445 r
= VT_SYM
| VT_CONST
;
7449 vset(&s
->type
, r
, s
->c
);
7450 /* if forward reference, we must point to s */
7451 if (vtop
->r
& VT_SYM
) {
7458 /* post operations */
7460 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
7463 } else if (tok
== '.' || tok
== TOK_ARROW
) {
7465 if (tok
== TOK_ARROW
)
7470 /* expect pointer on structure */
7471 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
7472 expect("struct or union");
7476 while ((s
= s
->next
) != NULL
) {
7481 error("field not found");
7482 /* add field offset to pointer */
7483 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
7486 /* change type to field type, and set to lvalue */
7487 vtop
->type
= s
->type
;
7488 /* an array is never an lvalue */
7489 if (!(vtop
->type
.t
& VT_ARRAY
)) {
7490 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7491 /* if bound checking, the referenced pointer must be checked */
7492 if (do_bounds_check
)
7493 vtop
->r
|= VT_MUSTBOUND
;
7496 } else if (tok
== '[') {
7502 } else if (tok
== '(') {
7508 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7509 /* pointer test (no array accepted) */
7510 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
7511 vtop
->type
= *pointed_type(&vtop
->type
);
7512 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
7516 expect("function pointer");
7519 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
7521 /* get return type */
7524 sa
= s
->next
; /* first parameter */
7526 /* compute first implicit argument if a structure is returned */
7527 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
7528 /* get some space for the returned structure */
7529 size
= type_size(&s
->type
, &align
);
7530 loc
= (loc
- size
) & -align
;
7532 ret
.r
= VT_LOCAL
| VT_LVAL
;
7533 /* pass it as 'int' to avoid structure arg passing
7535 vseti(VT_LOCAL
, loc
);
7541 /* return in register */
7542 if (is_float(ret
.type
.t
)) {
7545 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
7554 gfunc_param_typed(s
, sa
);
7564 error("too few arguments to function");
7566 if (!nocode_wanted
) {
7567 gfunc_call(nb_args
);
7569 vtop
-= (nb_args
+ 1);
7572 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
7580 static void uneq(void)
7586 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
7587 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
7588 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
7603 static void expr_prod(void)
7608 while (tok
== '*' || tok
== '/' || tok
== '%') {
7616 static void expr_sum(void)
7621 while (tok
== '+' || tok
== '-') {
7629 static void expr_shift(void)
7634 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
7642 static void expr_cmp(void)
7647 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
7648 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
7656 static void expr_cmpeq(void)
7661 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
7669 static void expr_and(void)
7672 while (tok
== '&') {
7679 static void expr_xor(void)
7682 while (tok
== '^') {
7689 static void expr_or(void)
7692 while (tok
== '|') {
7699 /* XXX: fix this mess */
7700 static void expr_land_const(void)
7703 while (tok
== TOK_LAND
) {
7710 /* XXX: fix this mess */
7711 static void expr_lor_const(void)
7714 while (tok
== TOK_LOR
) {
7721 /* only used if non constant */
7722 static void expr_land(void)
7727 if (tok
== TOK_LAND
) {
7732 if (tok
!= TOK_LAND
) {
7742 static void expr_lor(void)
7747 if (tok
== TOK_LOR
) {
7752 if (tok
!= TOK_LOR
) {
7762 /* XXX: better constant handling */
7763 static void expr_eq(void)
7765 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
7767 CType type
, type1
, type2
;
7776 if (tok
== ':' && gnu_ext
) {
7792 if (vtop
!= vstack
) {
7793 /* needed to avoid having different registers saved in
7795 if (is_float(vtop
->type
.t
))
7802 if (tok
== ':' && gnu_ext
) {
7810 sv
= *vtop
; /* save value to handle it later */
7811 vtop
--; /* no vpop so that FP stack is not flushed */
7819 bt1
= t1
& VT_BTYPE
;
7821 bt2
= t2
& VT_BTYPE
;
7822 /* cast operands to correct type according to ISOC rules */
7823 if (is_float(bt1
) || is_float(bt2
)) {
7824 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
7825 type
.t
= VT_LDOUBLE
;
7826 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
7831 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
7832 /* cast to biggest op */
7834 /* convert to unsigned if it does not fit in a long long */
7835 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
7836 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
7837 type
.t
|= VT_UNSIGNED
;
7838 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
7839 /* XXX: test pointer compatibility */
7841 } else if (bt1
== VT_FUNC
|| bt2
== VT_FUNC
) {
7842 /* XXX: test function pointer compatibility */
7844 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
7845 /* XXX: test structure compatibility */
7847 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
7848 /* NOTE: as an extension, we accept void on only one side */
7851 /* integer operations */
7853 /* convert to unsigned if it does not fit in an integer */
7854 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
7855 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
7856 type
.t
|= VT_UNSIGNED
;
7859 /* now we convert second operand */
7861 if (VT_STRUCT
== (vtop
->type
.t
& VT_BTYPE
))
7864 if (is_float(type
.t
)) {
7866 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
7867 /* for long longs, we use fixed registers to avoid having
7868 to handle a complicated move */
7873 /* this is horrible, but we must also convert first
7877 /* put again first value and cast it */
7880 if (VT_STRUCT
== (vtop
->type
.t
& VT_BTYPE
))
7890 static void gexpr(void)
7901 /* parse an expression and return its type without any side effect. */
7902 static void expr_type(CType
*type
)
7904 int saved_nocode_wanted
;
7906 saved_nocode_wanted
= nocode_wanted
;
7911 nocode_wanted
= saved_nocode_wanted
;
7914 /* parse a unary expression and return its type without any side
7916 static void unary_type(CType
*type
)
7928 /* parse a constant expression and return value in vtop. */
7929 static void expr_const1(void)
7938 /* parse an integer constant and return its value. */
7939 static int expr_const(void)
7943 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
7944 expect("constant expression");
7950 /* return the label token if current token is a label, otherwise
7952 static int is_label(void)
7956 /* fast test first */
7957 if (tok
< TOK_UIDENT
)
7959 /* no need to save tokc because tok is an identifier */
7966 unget_tok(last_tok
);
7971 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
7972 int case_reg
, int is_expr
)
7977 /* generate line number info */
7979 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
7980 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
7982 last_line_num
= file
->line_num
;
7986 /* default return value is (void) */
7988 vtop
->type
.t
= VT_VOID
;
7991 if (tok
== TOK_IF
) {
7998 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
8000 if (c
== TOK_ELSE
) {
8004 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
8005 gsym(d
); /* patch else jmp */
8008 } else if (tok
== TOK_WHILE
) {
8016 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8020 } else if (tok
== '{') {
8024 /* record local declaration stack position */
8026 llabel
= local_label_stack
;
8027 /* handle local labels declarations */
8028 if (tok
== TOK_LABEL
) {
8031 if (tok
< TOK_UIDENT
)
8032 expect("label identifier");
8033 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
8043 while (tok
!= '}') {
8048 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8051 /* pop locally defined labels */
8052 label_pop(&local_label_stack
, llabel
);
8053 /* pop locally defined symbols */
8054 sym_pop(&local_stack
, s
);
8056 } else if (tok
== TOK_RETURN
) {
8060 gen_assign_cast(&func_vt
);
8061 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
8063 /* if returning structure, must copy it to implicit
8064 first pointer arg location */
8067 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
8070 /* copy structure value to pointer */
8072 } else if (is_float(func_vt
.t
)) {
8077 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
8080 rsym
= gjmp(rsym
); /* jmp */
8081 } else if (tok
== TOK_BREAK
) {
8084 error("cannot break");
8085 *bsym
= gjmp(*bsym
);
8088 } else if (tok
== TOK_CONTINUE
) {
8091 error("cannot continue");
8092 *csym
= gjmp(*csym
);
8095 } else if (tok
== TOK_FOR
) {
8122 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8127 if (tok
== TOK_DO
) {
8132 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8143 if (tok
== TOK_SWITCH
) {
8147 /* XXX: other types than integer */
8148 case_reg
= gv(RC_INT
);
8152 b
= gjmp(0); /* jump to first case */
8154 block(&a
, csym
, &b
, &c
, case_reg
, 0);
8155 /* if no default, jmp after switch */
8163 if (tok
== TOK_CASE
) {
8170 if (gnu_ext
&& tok
== TOK_DOTS
) {
8174 warning("empty case range");
8176 /* since a case is like a label, we must skip it with a jmp */
8183 *case_sym
= gtst(1, 0);
8186 *case_sym
= gtst(1, 0);
8190 *case_sym
= gtst(1, *case_sym
);
8195 goto block_after_label
;
8197 if (tok
== TOK_DEFAULT
) {
8203 error("too many 'default'");
8206 goto block_after_label
;
8208 if (tok
== TOK_GOTO
) {
8210 if (tok
== '*' && gnu_ext
) {
8214 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
8217 } else if (tok
>= TOK_UIDENT
) {
8218 s
= label_find(tok
);
8219 /* put forward definition if needed */
8221 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
8223 if (s
->r
== LABEL_DECLARED
)
8224 s
->r
= LABEL_FORWARD
;
8226 /* label already defined */
8227 if (s
->r
& LABEL_FORWARD
)
8228 s
->next
= (void *)gjmp((long)s
->next
);
8230 gjmp_addr((long)s
->next
);
8233 expect("label identifier");
8236 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
8244 if (s
->r
== LABEL_DEFINED
)
8245 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
8246 gsym((long)s
->next
);
8247 s
->r
= LABEL_DEFINED
;
8249 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
8251 s
->next
= (void *)ind
;
8252 /* we accept this, but it is a mistake */
8255 warning("deprecated use of label at end of compound statement");
8259 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8262 /* expression case */
8277 /* t is the array or struct type. c is the array or struct
8278 address. cur_index/cur_field is the pointer to the current
8279 value. 'size_only' is true if only size info is needed (only used
8281 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
8282 int *cur_index
, Sym
**cur_field
,
8286 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
8292 if (gnu_ext
&& (l
= is_label()) != 0)
8294 while (tok
== '[' || tok
== '.') {
8296 if (!(type
->t
& VT_ARRAY
))
8297 expect("array type");
8300 index
= expr_const();
8301 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
8302 expect("invalid index");
8303 if (tok
== TOK_DOTS
&& gnu_ext
) {
8305 index_last
= expr_const();
8306 if (index_last
< 0 ||
8307 (s
->c
>= 0 && index_last
>= s
->c
) ||
8309 expect("invalid index");
8315 *cur_index
= index_last
;
8316 type
= pointed_type(type
);
8317 elem_size
= type_size(type
, &align
);
8318 c
+= index
* elem_size
;
8319 /* NOTE: we only support ranges for last designator */
8320 nb_elems
= index_last
- index
+ 1;
8321 if (nb_elems
!= 1) {
8330 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
8331 expect("struct/union type");
8344 /* XXX: fix this mess by using explicit storage field */
8346 type1
.t
|= (type
->t
& ~VT_TYPE
);
8360 if (type
->t
& VT_ARRAY
) {
8362 type
= pointed_type(type
);
8363 c
+= index
* type_size(type
, &align
);
8367 error("too many field init");
8368 /* XXX: fix this mess by using explicit storage field */
8370 type1
.t
|= (type
->t
& ~VT_TYPE
);
8375 decl_initializer(type
, sec
, c
, 0, size_only
);
8377 /* XXX: make it more general */
8378 if (!size_only
&& nb_elems
> 1) {
8379 unsigned long c_end
;
8384 error("range init not supported yet for dynamic storage");
8385 c_end
= c
+ nb_elems
* elem_size
;
8386 if (c_end
> sec
->data_allocated
)
8387 section_realloc(sec
, c_end
);
8388 src
= sec
->data
+ c
;
8390 for(i
= 1; i
< nb_elems
; i
++) {
8392 memcpy(dst
, src
, elem_size
);
8398 #define EXPR_CONST 1
8401 /* store a value or an expression directly in global data or in local array */
8402 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
8403 int v
, int expr_type
)
8405 int saved_global_expr
, bt
, bit_pos
, bit_size
;
8407 unsigned long long bit_mask
;
8415 /* compound literals must be allocated globally in this case */
8416 saved_global_expr
= global_expr
;
8419 global_expr
= saved_global_expr
;
8420 /* NOTE: symbols are accepted */
8421 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
8422 error("initializer element is not constant");
8430 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
8433 /* XXX: not portable */
8434 /* XXX: generate error if incorrect relocation */
8435 gen_assign_cast(&dtype
);
8436 bt
= type
->t
& VT_BTYPE
;
8437 ptr
= sec
->data
+ c
;
8438 /* XXX: make code faster ? */
8439 if (!(type
->t
& VT_BITFIELD
)) {
8444 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
8445 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
8446 bit_mask
= (1LL << bit_size
) - 1;
8448 if ((vtop
->r
& VT_SYM
) &&
8454 (bt
== VT_INT
&& bit_size
!= 32)))
8455 error("initializer element is not computable at load time");
8458 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8461 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8464 *(double *)ptr
= vtop
->c
.d
;
8467 *(long double *)ptr
= vtop
->c
.ld
;
8470 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
8473 if (vtop
->r
& VT_SYM
) {
8474 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
8476 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8481 vset(&dtype
, VT_LOCAL
|VT_LVAL
, c
);
8488 /* put zeros for variable based init */
8489 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
8492 /* nothing to do because globals are already set to zero */
8494 vpush_global_sym(&func_old_type
, TOK_memset
);
8502 /* 't' contains the type and storage info. 'c' is the offset of the
8503 object in section 'sec'. If 'sec' is NULL, it means stack based
8504 allocation. 'first' is true if array '{' must be read (multi
8505 dimension implicit array init handling). 'size_only' is true if
8506 size only evaluation is wanted (only for arrays). */
8507 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
8508 int first
, int size_only
)
8510 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
8511 int size1
, align1
, expr_type
;
8515 if (type
->t
& VT_ARRAY
) {
8519 t1
= pointed_type(type
);
8520 size1
= type_size(t1
, &align1
);
8523 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
8529 /* only parse strings here if correct type (otherwise: handle
8530 them as ((w)char *) expressions */
8531 if ((tok
== TOK_LSTR
&&
8532 #ifdef TCC_TARGET_PE
8533 (t1
->t
& VT_BTYPE
) == VT_SHORT
&& (t1
->t
& VT_UNSIGNED
)) ||
8535 (t1
->t
& VT_BTYPE
) == VT_INT
) ||
8538 (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
8539 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8544 /* compute maximum number of chars wanted */
8546 cstr_len
= cstr
->size
;
8548 cstr_len
= cstr
->size
/ sizeof(nwchar_t
);
8551 if (n
>= 0 && nb
> (n
- array_length
))
8552 nb
= n
- array_length
;
8555 warning("initializer-string for array is too long");
8556 /* in order to go faster for common case (char
8557 string in global variable, we handle it
8559 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
8560 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
8564 ch
= ((unsigned char *)cstr
->data
)[i
];
8566 ch
= ((nwchar_t
*)cstr
->data
)[i
];
8567 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
8575 /* only add trailing zero if enough storage (no
8576 warning in this case since it is standard) */
8577 if (n
< 0 || array_length
< n
) {
8579 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
8585 while (tok
!= '}') {
8586 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
8587 if (n
>= 0 && index
>= n
)
8588 error("index too large");
8589 /* must put zero in holes (note that doing it that way
8590 ensures that it even works with designators) */
8591 if (!size_only
&& array_length
< index
) {
8592 init_putz(t1
, sec
, c
+ array_length
* size1
,
8593 (index
- array_length
) * size1
);
8596 if (index
> array_length
)
8597 array_length
= index
;
8598 /* special test for multi dimensional arrays (may not
8599 be strictly correct if designators are used at the
8601 if (index
>= n
&& no_oblock
)
8610 /* put zeros at the end */
8611 if (!size_only
&& n
>= 0 && array_length
< n
) {
8612 init_putz(t1
, sec
, c
+ array_length
* size1
,
8613 (n
- array_length
) * size1
);
8615 /* patch type size if needed */
8617 s
->c
= array_length
;
8618 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
8619 (sec
|| !first
|| tok
== '{')) {
8622 /* NOTE: the previous test is a specific case for automatic
8623 struct/union init */
8624 /* XXX: union needs only one init */
8626 /* XXX: this test is incorrect for local initializers
8627 beginning with ( without {. It would be much more difficult
8628 to do it correctly (ideally, the expression parser should
8629 be used in all cases) */
8635 while (tok
== '(') {
8639 if (!parse_btype(&type1
, &ad1
))
8641 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
8643 if (!is_assignable_types(type
, &type1
))
8644 error("invalid type for cast");
8649 if (first
|| tok
== '{') {
8658 while (tok
!= '}') {
8659 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
8661 if (!size_only
&& array_length
< index
) {
8662 init_putz(type
, sec
, c
+ array_length
,
8663 index
- array_length
);
8665 index
= index
+ type_size(&f
->type
, &align1
);
8666 if (index
> array_length
)
8667 array_length
= index
;
8669 if (no_oblock
&& f
== NULL
)
8675 /* put zeros at the end */
8676 if (!size_only
&& array_length
< n
) {
8677 init_putz(type
, sec
, c
+ array_length
,
8686 } else if (tok
== '{') {
8688 decl_initializer(type
, sec
, c
, first
, size_only
);
8690 } else if (size_only
) {
8691 /* just skip expression */
8693 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
8697 else if (tok
== ')')
8702 /* currently, we always use constant expression for globals
8703 (may change for scripting case) */
8704 expr_type
= EXPR_CONST
;
8706 expr_type
= EXPR_ANY
;
8707 init_putv(type
, sec
, c
, 0, expr_type
);
8711 /* parse an initializer for type 't' if 'has_init' is non zero, and
8712 allocate space in local or global data space ('r' is either
8713 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
8714 variable 'v' of scope 'scope' is declared before initializers are
8715 parsed. If 'v' is zero, then a reference to the new object is put
8716 in the value stack. If 'has_init' is 2, a special parsing is done
8717 to handle string constants. */
8718 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
8719 int has_init
, int v
, int scope
)
8721 int size
, align
, addr
, data_offset
;
8723 ParseState saved_parse_state
;
8724 TokenString init_str
;
8727 size
= type_size(type
, &align
);
8728 /* If unknown size, we must evaluate it before
8729 evaluating initializers because
8730 initializers can generate global data too
8731 (e.g. string pointers or ISOC99 compound
8732 literals). It also simplifies local
8733 initializers handling */
8734 tok_str_new(&init_str
);
8737 error("unknown type size");
8738 /* get all init string */
8739 if (has_init
== 2) {
8740 /* only get strings */
8741 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8742 tok_str_add_tok(&init_str
);
8747 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
8749 error("unexpected end of file in initializer");
8750 tok_str_add_tok(&init_str
);
8753 else if (tok
== '}') {
8761 tok_str_add(&init_str
, -1);
8762 tok_str_add(&init_str
, 0);
8765 save_parse_state(&saved_parse_state
);
8767 macro_ptr
= init_str
.str
;
8769 decl_initializer(type
, NULL
, 0, 1, 1);
8770 /* prepare second initializer parsing */
8771 macro_ptr
= init_str
.str
;
8774 /* if still unknown size, error */
8775 size
= type_size(type
, &align
);
8777 error("unknown type size");
8779 /* take into account specified alignment if bigger */
8781 if (ad
->aligned
> align
)
8782 align
= ad
->aligned
;
8783 } else if (ad
->packed
) {
8786 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
8788 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
8790 loc
= (loc
- size
) & -align
;
8792 /* handles bounds */
8793 /* XXX: currently, since we do only one pass, we cannot track
8794 '&' operators, so we add only arrays */
8795 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
8796 unsigned long *bounds_ptr
;
8797 /* add padding between regions */
8799 /* then add local bound info */
8800 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
8801 bounds_ptr
[0] = addr
;
8802 bounds_ptr
[1] = size
;
8805 /* local variable */
8806 sym_push(v
, type
, r
, addr
);
8808 /* push local reference */
8809 vset(type
, r
, addr
);
8815 if (v
&& scope
== VT_CONST
) {
8816 /* see if the symbol was already defined */
8819 if (!is_compatible_types(&sym
->type
, type
))
8820 error("incompatible types for redefinition of '%s'",
8821 get_tok_str(v
, NULL
));
8822 if (sym
->type
.t
& VT_EXTERN
) {
8823 /* if the variable is extern, it was not allocated */
8824 sym
->type
.t
&= ~VT_EXTERN
;
8825 /* set array size if it was ommited in extern
8827 if ((sym
->type
.t
& VT_ARRAY
) &&
8828 sym
->type
.ref
->c
< 0 &&
8830 sym
->type
.ref
->c
= type
->ref
->c
;
8832 /* we accept several definitions of the same
8833 global variable. this is tricky, because we
8834 must play with the SHN_COMMON type of the symbol */
8835 /* XXX: should check if the variable was already
8836 initialized. It is incorrect to initialized it
8838 /* no init data, we won't add more to the symbol */
8845 /* allocate symbol in corresponding section */
8850 else if (tcc_state
->nocommon
)
8854 data_offset
= sec
->data_offset
;
8855 data_offset
= (data_offset
+ align
- 1) & -align
;
8857 /* very important to increment global pointer at this time
8858 because initializers themselves can create new initializers */
8859 data_offset
+= size
;
8860 /* add padding if bound check */
8861 if (do_bounds_check
)
8863 sec
->data_offset
= data_offset
;
8864 /* allocate section space to put the data */
8865 if (sec
->sh_type
!= SHT_NOBITS
&&
8866 data_offset
> sec
->data_allocated
)
8867 section_realloc(sec
, data_offset
);
8868 /* align section if needed */
8869 if (align
> sec
->sh_addralign
)
8870 sec
->sh_addralign
= align
;
8872 addr
= 0; /* avoid warning */
8876 if (scope
== VT_CONST
) {
8881 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
8883 /* update symbol definition */
8885 put_extern_sym(sym
, sec
, addr
, size
);
8888 /* put a common area */
8889 put_extern_sym(sym
, NULL
, align
, size
);
8890 /* XXX: find a nicer way */
8891 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
8892 esym
->st_shndx
= SHN_COMMON
;
8897 /* push global reference */
8898 sym
= get_sym_ref(type
, sec
, addr
, size
);
8900 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
8904 /* handles bounds now because the symbol must be defined
8905 before for the relocation */
8906 if (do_bounds_check
) {
8907 unsigned long *bounds_ptr
;
8909 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
8910 /* then add global bound info */
8911 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
8912 bounds_ptr
[0] = 0; /* relocated */
8913 bounds_ptr
[1] = size
;
8917 decl_initializer(type
, sec
, addr
, 1, 0);
8918 /* restore parse state if needed */
8920 tok_str_free(init_str
.str
);
8921 restore_parse_state(&saved_parse_state
);
8927 void put_func_debug(Sym
*sym
)
8932 /* XXX: we put here a dummy type */
8933 snprintf(buf
, sizeof(buf
), "%s:%c1",
8934 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
8935 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
8936 cur_text_section
, sym
->c
);
8941 /* parse an old style function declaration list */
8942 /* XXX: check multiple parameter */
8943 static void func_decl_list(Sym
*func_sym
)
8950 /* parse each declaration */
8951 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
8952 if (!parse_btype(&btype
, &ad
))
8953 expect("declaration list");
8954 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8955 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8957 /* we accept no variable after */
8961 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8962 /* find parameter in function parameter list */
8965 if ((s
->v
& ~SYM_FIELD
) == v
)
8969 error("declaration for parameter '%s' but no such parameter",
8970 get_tok_str(v
, NULL
));
8972 /* check that no storage specifier except 'register' was given */
8973 if (type
.t
& VT_STORAGE
)
8974 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
8975 convert_parameter_type(&type
);
8976 /* we can add the type (NOTE: it could be local to the function) */
8978 /* accept other parameters */
8989 /* parse a function defined by symbol 'sym' and generate its code in
8990 'cur_text_section' */
8991 static void gen_function(Sym
*sym
)
8993 ind
= cur_text_section
->data_offset
;
8994 /* NOTE: we patch the symbol size later */
8995 put_extern_sym(sym
, cur_text_section
, ind
, 0);
8996 funcname
= get_tok_str(sym
->v
, NULL
);
8998 /* put debug symbol */
9000 put_func_debug(sym
);
9001 /* push a dummy symbol to enable local sym storage */
9002 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
9003 gfunc_prolog(&sym
->type
);
9005 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
9008 cur_text_section
->data_offset
= ind
;
9009 label_pop(&global_label_stack
, NULL
);
9010 sym_pop(&local_stack
, NULL
); /* reset local stack */
9011 /* end of function */
9012 /* patch symbol size */
9013 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_size
=
9016 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
9018 funcname
= ""; /* for safety */
9019 func_vt
.t
= VT_VOID
; /* for safety */
9020 ind
= 0; /* for safety */
9023 static void gen_inline_functions(void)
9027 int *str
, inline_generated
;
9029 /* iterate while inline function are referenced */
9031 inline_generated
= 0;
9032 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
9034 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
9035 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
9036 (VT_STATIC
| VT_INLINE
) &&
9038 /* the function was used: generate its code and
9039 convert it to a normal function */
9040 str
= (int *)sym
->r
;
9041 sym
->r
= VT_SYM
| VT_CONST
;
9042 type
->t
&= ~VT_INLINE
;
9046 cur_text_section
= text_section
;
9048 macro_ptr
= NULL
; /* fail safe */
9051 inline_generated
= 1;
9054 if (!inline_generated
)
9058 /* free all remaining inline function tokens */
9059 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
9061 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
9062 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
9063 (VT_STATIC
| VT_INLINE
)) {
9064 str
= (int *)sym
->r
;
9066 sym
->r
= 0; /* fail safe */
9071 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
9072 static void decl(int l
)
9080 if (!parse_btype(&btype
, &ad
)) {
9081 /* skip redundant ';' */
9082 /* XXX: find more elegant solution */
9087 if (l
== VT_CONST
&&
9088 (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
)) {
9089 /* global asm block */
9093 /* special test for old K&R protos without explicit int
9094 type. Only accepted when defining global data */
9095 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
9099 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
9100 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
9102 /* we accept no variable after */
9106 while (1) { /* iterate thru each declaration */
9108 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
9112 type_to_str(buf
, sizeof(buf
), &type
, get_tok_str(v
, NULL
));
9113 printf("type = '%s'\n", buf
);
9116 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9117 /* if old style function prototype, we accept a
9120 if (sym
->c
== FUNC_OLD
)
9121 func_decl_list(sym
);
9126 error("cannot use local functions");
9127 if ((type
.t
& VT_BTYPE
) != VT_FUNC
)
9128 expect("function definition");
9130 /* reject abstract declarators in function definition */
9132 while ((sym
= sym
->next
) != NULL
)
9133 if (!(sym
->v
& ~SYM_FIELD
))
9134 expect("identifier");
9136 /* XXX: cannot do better now: convert extern line to static inline */
9137 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
9138 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
9142 if ((sym
->type
.t
& VT_BTYPE
) != VT_FUNC
)
9144 /* specific case: if not func_call defined, we put
9145 the one of the prototype */
9146 /* XXX: should have default value */
9147 if (sym
->type
.ref
->r
!= FUNC_CDECL
&&
9148 type
.ref
->r
== FUNC_CDECL
)
9149 type
.ref
->r
= sym
->type
.ref
->r
;
9150 if (!is_compatible_types(&sym
->type
, &type
)) {
9152 error("incompatible types for redefinition of '%s'",
9153 get_tok_str(v
, NULL
));
9155 /* if symbol is already defined, then put complete type */
9158 /* put function symbol */
9159 sym
= global_identifier_push(v
, type
.t
, 0);
9160 sym
->type
.ref
= type
.ref
;
9163 /* static inline functions are just recorded as a kind
9164 of macro. Their code will be emitted at the end of
9165 the compilation unit only if they are used */
9166 if ((type
.t
& (VT_INLINE
| VT_STATIC
)) ==
9167 (VT_INLINE
| VT_STATIC
)) {
9168 TokenString func_str
;
9171 tok_str_new(&func_str
);
9177 error("unexpected end of file");
9178 tok_str_add_tok(&func_str
);
9183 } else if (t
== '}') {
9185 if (block_level
== 0)
9189 tok_str_add(&func_str
, -1);
9190 tok_str_add(&func_str
, 0);
9191 sym
->r
= (int)func_str
.str
;
9193 /* compute text section */
9194 cur_text_section
= ad
.section
;
9195 if (!cur_text_section
)
9196 cur_text_section
= text_section
;
9197 sym
->r
= VT_SYM
| VT_CONST
;
9199 #ifdef TCC_TARGET_PE
9201 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_other
|= 1;
9207 if (btype
.t
& VT_TYPEDEF
) {
9208 /* save typedefed type */
9209 /* XXX: test storage specifiers ? */
9210 sym
= sym_push(v
, &type
, 0, 0);
9211 sym
->type
.t
|= VT_TYPEDEF
;
9212 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9213 /* external function definition */
9214 /* specific case for func_call attribute */
9216 type
.ref
->r
= ad
.func_call
;
9217 external_sym(v
, &type
, 0);
9219 /* not lvalue if array */
9221 if (!(type
.t
& VT_ARRAY
))
9222 r
|= lvalue_type(type
.t
);
9223 has_init
= (tok
== '=');
9224 if ((btype
.t
& VT_EXTERN
) ||
9225 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
9226 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
9227 /* external variable */
9228 /* NOTE: as GCC, uninitialized global static
9229 arrays of null size are considered as
9231 external_sym(v
, &type
, r
);
9233 type
.t
|= (btype
.t
& VT_STATIC
); /* Retain "static". */
9234 if (type
.t
& VT_STATIC
)
9240 decl_initializer_alloc(&type
, &ad
, r
,
9254 /* better than nothing, but needs extension to handle '-E' option
9256 static void preprocess_init(TCCState
*s1
)
9258 s1
->include_stack_ptr
= s1
->include_stack
;
9259 /* XXX: move that before to avoid having to initialize
9260 file->ifdef_stack_ptr ? */
9261 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
9262 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
9264 /* XXX: not ANSI compliant: bound checking says error */
9266 s1
->pack_stack
[0] = 0;
9267 s1
->pack_stack_ptr
= s1
->pack_stack
;
9270 /* compile the C file opened in 'file'. Return non zero if errors. */
9271 static int tcc_compile(TCCState
*s1
)
9275 volatile int section_sym
;
9278 printf("%s: **** new file\n", file
->filename
);
9280 preprocess_init(s1
);
9283 anon_sym
= SYM_FIRST_ANOM
;
9285 /* file info: full path + filename */
9286 section_sym
= 0; /* avoid warning */
9288 section_sym
= put_elf_sym(symtab_section
, 0, 0,
9289 ELF32_ST_INFO(STB_LOCAL
, STT_SECTION
), 0,
9290 text_section
->sh_num
, NULL
);
9291 getcwd(buf
, sizeof(buf
));
9292 pstrcat(buf
, sizeof(buf
), "/");
9293 put_stabs_r(buf
, N_SO
, 0, 0,
9294 text_section
->data_offset
, text_section
, section_sym
);
9295 put_stabs_r(file
->filename
, N_SO
, 0, 0,
9296 text_section
->data_offset
, text_section
, section_sym
);
9298 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
9299 symbols can be safely used */
9300 put_elf_sym(symtab_section
, 0, 0,
9301 ELF32_ST_INFO(STB_LOCAL
, STT_FILE
), 0,
9302 SHN_ABS
, file
->filename
);
9304 /* define some often used types */
9305 int_type
.t
= VT_INT
;
9307 char_pointer_type
.t
= VT_BYTE
;
9308 mk_pointer(&char_pointer_type
);
9310 func_old_type
.t
= VT_FUNC
;
9311 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
9314 /* define 'void *alloca(unsigned int)' builtin function */
9319 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
9320 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
9323 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
9327 define_start
= define_stack
;
9329 if (setjmp(s1
->error_jmp_buf
) == 0) {
9331 s1
->error_set_jmp_enabled
= 1;
9333 ch
= file
->buf_ptr
[0];
9334 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9335 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
9339 expect("declaration");
9341 /* end of translation unit info */
9343 put_stabs_r(NULL
, N_SO
, 0, 0,
9344 text_section
->data_offset
, text_section
, section_sym
);
9347 s1
->error_set_jmp_enabled
= 0;
9349 /* reset define stack, but leave -Dsymbols (may be incorrect if
9350 they are undefined) */
9351 free_defines(define_start
);
9353 gen_inline_functions();
9355 sym_pop(&global_stack
, NULL
);
9357 return s1
->nb_errors
!= 0 ? -1 : 0;
9360 /* Preprocess the current file */
9361 /* XXX: add line and file infos, add options to preserve spaces */
9362 static int tcc_preprocess(TCCState
*s1
)
9367 preprocess_init(s1
);
9369 define_start
= define_stack
;
9371 ch
= file
->buf_ptr
[0];
9372 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9373 parse_flags
= PARSE_FLAG_ASM_COMMENTS
| PARSE_FLAG_PREPROCESS
|
9374 PARSE_FLAG_LINEFEED
;
9380 if (!last_is_space
) {
9381 fputc(' ', s1
->outfile
);
9383 fputs(get_tok_str(tok
, &tokc
), s1
->outfile
);
9384 if (tok
== TOK_LINEFEED
) {
9386 /* XXX: suppress that hack */
9387 parse_flags
&= ~PARSE_FLAG_LINEFEED
;
9389 parse_flags
|= PARSE_FLAG_LINEFEED
;
9396 free_defines(define_start
);
9402 int tcc_compile_string(TCCState
*s
, const char *str
)
9404 BufferedFile bf1
, *bf
= &bf1
;
9408 /* init file structure */
9410 /* XXX: avoid copying */
9412 buf
= tcc_malloc(len
+ 1);
9415 memcpy(buf
, str
, len
);
9418 bf
->buf_end
= buf
+ len
;
9419 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
9423 ret
= tcc_compile(s
);
9427 /* currently, no need to close */
9432 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9433 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
9435 BufferedFile bf1
, *bf
= &bf1
;
9437 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
9438 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
9442 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
9444 /* init file structure */
9446 bf
->buf_ptr
= bf
->buffer
;
9447 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
9448 *bf
->buf_end
= CH_EOB
;
9449 bf
->filename
[0] = '\0';
9453 s1
->include_stack_ptr
= s1
->include_stack
;
9455 /* parse with define parser */
9456 ch
= file
->buf_ptr
[0];
9462 /* undefine a preprocessor symbol */
9463 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
9467 ts
= tok_alloc(sym
, strlen(sym
));
9468 s
= define_find(ts
->tok
);
9469 /* undefine symbol by putting an invalid name */
9474 #ifdef CONFIG_TCC_ASM
9476 #ifdef TCC_TARGET_I386
9477 #include "i386-asm.c"
9482 static void asm_instr(void)
9484 error("inline asm() not supported");
9486 static void asm_global_instr(void)
9488 error("inline asm() not supported");
9494 #ifdef TCC_TARGET_COFF
9495 #include "tcccoff.c"
9498 #ifdef TCC_TARGET_PE
9502 /* print the position in the source file of PC value 'pc' by reading
9503 the stabs debug information */
9504 static void rt_printline(unsigned long wanted_pc
)
9506 Stab_Sym
*sym
, *sym_end
;
9507 char func_name
[128], last_func_name
[128];
9508 unsigned long func_addr
, last_pc
, pc
;
9509 const char *incl_files
[INCLUDE_STACK_SIZE
];
9510 int incl_index
, len
, last_line_num
, i
;
9511 const char *str
, *p
;
9513 fprintf(stderr
, "0x%08lx:", wanted_pc
);
9515 func_name
[0] = '\0';
9518 last_func_name
[0] = '\0';
9519 last_pc
= 0xffffffff;
9521 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
9522 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
9523 while (sym
< sym_end
) {
9524 switch(sym
->n_type
) {
9525 /* function start or end */
9527 if (sym
->n_strx
== 0) {
9528 /* we test if between last line and end of function */
9529 pc
= sym
->n_value
+ func_addr
;
9530 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9532 func_name
[0] = '\0';
9535 str
= stabstr_section
->data
+ sym
->n_strx
;
9536 p
= strchr(str
, ':');
9538 pstrcpy(func_name
, sizeof(func_name
), str
);
9541 if (len
> sizeof(func_name
) - 1)
9542 len
= sizeof(func_name
) - 1;
9543 memcpy(func_name
, str
, len
);
9544 func_name
[len
] = '\0';
9546 func_addr
= sym
->n_value
;
9549 /* line number info */
9551 pc
= sym
->n_value
+ func_addr
;
9552 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9555 last_line_num
= sym
->n_desc
;
9557 strcpy(last_func_name
, func_name
);
9561 str
= stabstr_section
->data
+ sym
->n_strx
;
9563 if (incl_index
< INCLUDE_STACK_SIZE
) {
9564 incl_files
[incl_index
++] = str
;
9572 if (sym
->n_strx
== 0) {
9573 incl_index
= 0; /* end of translation unit */
9575 str
= stabstr_section
->data
+ sym
->n_strx
;
9576 /* do not add path */
9578 if (len
> 0 && str
[len
- 1] != '/')
9586 /* second pass: we try symtab symbols (no line number info) */
9589 Elf32_Sym
*sym
, *sym_end
;
9592 sym_end
= (Elf32_Sym
*)(symtab_section
->data
+ symtab_section
->data_offset
);
9593 for(sym
= (Elf32_Sym
*)symtab_section
->data
+ 1;
9596 type
= ELF32_ST_TYPE(sym
->st_info
);
9597 if (type
== STT_FUNC
) {
9598 if (wanted_pc
>= sym
->st_value
&&
9599 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
9600 pstrcpy(last_func_name
, sizeof(last_func_name
),
9601 strtab_section
->data
+ sym
->st_name
);
9607 /* did not find any info: */
9608 fprintf(stderr
, " ???\n");
9611 if (last_func_name
[0] != '\0') {
9612 fprintf(stderr
, " %s()", last_func_name
);
9614 if (incl_index
> 0) {
9615 fprintf(stderr
, " (%s:%d",
9616 incl_files
[incl_index
- 1], last_line_num
);
9617 for(i
= incl_index
- 2; i
>= 0; i
--)
9618 fprintf(stderr
, ", included from %s", incl_files
[i
]);
9619 fprintf(stderr
, ")");
9621 fprintf(stderr
, "\n");
9624 #if !defined(WIN32) && !defined(CONFIG_TCCBOOT)
9628 /* fix for glibc 2.1 */
9634 /* return the PC at frame level 'level'. Return non zero if not found */
9635 static int rt_get_caller_pc(unsigned long *paddr
,
9636 ucontext_t
*uc
, int level
)
9642 #if defined(__FreeBSD__)
9643 *paddr
= uc
->uc_mcontext
.mc_eip
;
9644 #elif defined(__dietlibc__)
9645 *paddr
= uc
->uc_mcontext
.eip
;
9647 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
9651 #if defined(__FreeBSD__)
9652 fp
= uc
->uc_mcontext
.mc_ebp
;
9653 #elif defined(__dietlibc__)
9654 fp
= uc
->uc_mcontext
.ebp
;
9656 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
9658 for(i
=1;i
<level
;i
++) {
9659 /* XXX: check address validity with program info */
9660 if (fp
<= 0x1000 || fp
>= 0xc0000000)
9662 fp
= ((unsigned long *)fp
)[0];
9664 *paddr
= ((unsigned long *)fp
)[1];
9670 #warning add arch specific rt_get_caller_pc()
9672 static int rt_get_caller_pc(unsigned long *paddr
,
9673 ucontext_t
*uc
, int level
)
9679 /* emit a run time error at position 'pc' */
9680 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
9687 fprintf(stderr
, "Runtime error: ");
9688 vfprintf(stderr
, fmt
, ap
);
9689 fprintf(stderr
, "\n");
9690 for(i
=0;i
<num_callers
;i
++) {
9691 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
9694 fprintf(stderr
, "at ");
9696 fprintf(stderr
, "by ");
9703 /* signal handler for fatal errors */
9704 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
9706 ucontext_t
*uc
= puc
;
9710 switch(siginf
->si_code
) {
9713 rt_error(uc
, "division by zero");
9716 rt_error(uc
, "floating point exception");
9722 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
9723 rt_error(uc
, *rt_bound_error_msg
);
9725 rt_error(uc
, "dereferencing invalid pointer");
9728 rt_error(uc
, "illegal instruction");
9731 rt_error(uc
, "abort() called");
9734 rt_error(uc
, "caught signal %d", signum
);
9741 /* do all relocations (needed before using tcc_get_symbol()) */
9742 int tcc_relocate(TCCState
*s1
)
9749 #ifdef TCC_TARGET_PE
9752 tcc_add_runtime(s1
);
9755 relocate_common_syms();
9757 tcc_add_linker_symbols(s1
);
9759 build_got_entries(s1
);
9761 /* compute relocation address : section are relocated in place. We
9762 also alloc the bss space */
9763 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9764 s
= s1
->sections
[i
];
9765 if (s
->sh_flags
& SHF_ALLOC
) {
9766 if (s
->sh_type
== SHT_NOBITS
)
9767 s
->data
= tcc_mallocz(s
->data_offset
);
9768 s
->sh_addr
= (unsigned long)s
->data
;
9772 relocate_syms(s1
, 1);
9774 if (s1
->nb_errors
!= 0)
9777 /* relocate each section */
9778 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9779 s
= s1
->sections
[i
];
9781 relocate_section(s1
, s
);
9784 /* mark executable sections as executable in memory */
9785 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9786 s
= s1
->sections
[i
];
9787 if ((s
->sh_flags
& (SHF_ALLOC
| SHF_EXECINSTR
)) ==
9788 (SHF_ALLOC
| SHF_EXECINSTR
)) {
9791 unsigned long old_protect
;
9792 VirtualProtect(s
->data
, s
->data_offset
,
9793 PAGE_EXECUTE_READWRITE
, &old_protect
);
9797 unsigned long start
, end
;
9798 start
= (unsigned long)(s
->data
) & ~(PAGESIZE
- 1);
9799 end
= (unsigned long)(s
->data
+ s
->data_offset
);
9800 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
9801 mprotect((void *)start
, end
- start
,
9802 PROT_READ
| PROT_WRITE
| PROT_EXEC
);
9810 /* launch the compiled program with the given arguments */
9811 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
9813 int (*prog_main
)(int, char **);
9815 if (tcc_relocate(s1
) < 0)
9818 prog_main
= tcc_get_symbol_err(s1
, "main");
9821 #if defined(WIN32) || defined(CONFIG_TCCBOOT)
9822 error("debug mode currently not available for Windows");
9824 struct sigaction sigact
;
9825 /* install TCC signal handlers to print debug info on fatal
9827 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
9828 sigact
.sa_sigaction
= sig_error
;
9829 sigemptyset(&sigact
.sa_mask
);
9830 sigaction(SIGFPE
, &sigact
, NULL
);
9831 sigaction(SIGILL
, &sigact
, NULL
);
9832 sigaction(SIGSEGV
, &sigact
, NULL
);
9833 sigaction(SIGBUS
, &sigact
, NULL
);
9834 sigaction(SIGABRT
, &sigact
, NULL
);
9838 #ifdef CONFIG_TCC_BCHECK
9839 if (do_bounds_check
) {
9840 void (*bound_init
)(void);
9842 /* set error function */
9843 rt_bound_error_msg
= (void *)tcc_get_symbol_err(s1
,
9844 "__bound_error_msg");
9846 /* XXX: use .init section so that it also work in binary ? */
9847 bound_init
= (void *)tcc_get_symbol_err(s1
, "__bound_init");
9851 return (*prog_main
)(argc
, argv
);
9854 TCCState
*tcc_new(void)
9861 s
= tcc_mallocz(sizeof(TCCState
));
9865 s
->output_type
= TCC_OUTPUT_MEMORY
;
9867 /* init isid table */
9869 isidnum_table
[i
] = isid(i
) || isnum(i
);
9871 /* add all tokens */
9873 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
9875 tok_ident
= TOK_IDENT
;
9884 ts
= tok_alloc(p
, r
- p
- 1);
9888 /* we add dummy defines for some special macros to speed up tests
9889 and to have working defined() */
9890 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
9891 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
9892 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
9893 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
9895 /* standard defines */
9896 tcc_define_symbol(s
, "__STDC__", NULL
);
9897 #if defined(TCC_TARGET_I386)
9898 tcc_define_symbol(s
, "__i386__", NULL
);
9900 #if defined(TCC_TARGET_ARM)
9901 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
9902 tcc_define_symbol(s
, "__arm_elf__", NULL
);
9903 tcc_define_symbol(s
, "__arm_elf", NULL
);
9904 tcc_define_symbol(s
, "arm_elf", NULL
);
9905 tcc_define_symbol(s
, "__arm__", NULL
);
9906 tcc_define_symbol(s
, "__arm", NULL
);
9907 tcc_define_symbol(s
, "arm", NULL
);
9908 tcc_define_symbol(s
, "__APCS_32__", NULL
);
9911 tcc_define_symbol(s
, "__linux__", NULL
);
9912 tcc_define_symbol(s
, "linux", NULL
);
9914 /* tiny C specific defines */
9915 tcc_define_symbol(s
, "__TINYC__", NULL
);
9917 /* tiny C & gcc defines */
9918 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
9919 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
9920 #ifdef TCC_TARGET_PE
9921 tcc_define_symbol(s
, "__WCHAR_TYPE__", "unsigned short");
9923 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
9926 /* default library paths */
9927 #ifdef TCC_TARGET_PE
9930 snprintf(buf
, sizeof(buf
), "%s/lib", tcc_lib_path
);
9931 tcc_add_library_path(s
, buf
);
9934 tcc_add_library_path(s
, "/usr/local/lib");
9935 tcc_add_library_path(s
, "/usr/lib");
9936 tcc_add_library_path(s
, "/lib");
9939 /* no section zero */
9940 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
9942 /* create standard sections */
9943 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
9944 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
9945 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
9947 /* symbols are always generated for linking stage */
9948 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
9950 ".hashtab", SHF_PRIVATE
);
9951 strtab_section
= symtab_section
->link
;
9953 /* private symbol table for dynamic symbols */
9954 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
9956 ".dynhashtab", SHF_PRIVATE
);
9957 s
->alacarte_link
= 1;
9959 #ifdef CHAR_IS_UNSIGNED
9960 s
->char_is_unsigned
= 1;
9962 #if defined(TCC_TARGET_PE) && 0
9963 /* XXX: currently the PE linker is not ready to support that */
9964 s
->leading_underscore
= 1;
9969 void tcc_delete(TCCState
*s1
)
9973 /* free -D defines */
9977 n
= tok_ident
- TOK_IDENT
;
9978 for(i
= 0; i
< n
; i
++)
9979 tcc_free(table_ident
[i
]);
9980 tcc_free(table_ident
);
9982 /* free all sections */
9984 free_section(symtab_section
->hash
);
9986 free_section(s1
->dynsymtab_section
->hash
);
9987 free_section(s1
->dynsymtab_section
->link
);
9988 free_section(s1
->dynsymtab_section
);
9990 for(i
= 1; i
< s1
->nb_sections
; i
++)
9991 free_section(s1
->sections
[i
]);
9992 tcc_free(s1
->sections
);
9994 /* free loaded dlls array */
9995 for(i
= 0; i
< s1
->nb_loaded_dlls
; i
++)
9996 tcc_free(s1
->loaded_dlls
[i
]);
9997 tcc_free(s1
->loaded_dlls
);
10000 for(i
= 0; i
< s1
->nb_library_paths
; i
++)
10001 tcc_free(s1
->library_paths
[i
]);
10002 tcc_free(s1
->library_paths
);
10004 /* cached includes */
10005 for(i
= 0; i
< s1
->nb_cached_includes
; i
++)
10006 tcc_free(s1
->cached_includes
[i
]);
10007 tcc_free(s1
->cached_includes
);
10009 for(i
= 0; i
< s1
->nb_include_paths
; i
++)
10010 tcc_free(s1
->include_paths
[i
]);
10011 tcc_free(s1
->include_paths
);
10013 for(i
= 0; i
< s1
->nb_sysinclude_paths
; i
++)
10014 tcc_free(s1
->sysinclude_paths
[i
]);
10015 tcc_free(s1
->sysinclude_paths
);
10020 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
10024 pathname1
= tcc_strdup(pathname
);
10025 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
10029 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
10033 pathname1
= tcc_strdup(pathname
);
10034 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
10038 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
10040 const char *ext
, *filename1
;
10043 BufferedFile
*saved_file
;
10045 /* find source file type with extension */
10046 filename1
= strrchr(filename
, '/');
10050 filename1
= filename
;
10051 ext
= strrchr(filename1
, '.');
10055 /* open the file */
10057 file
= tcc_open(s1
, filename
);
10059 if (flags
& AFF_PRINT_ERROR
) {
10060 error_noabort("file '%s' not found", filename
);
10066 if (flags
& AFF_PREPROCESS
) {
10067 ret
= tcc_preprocess(s1
);
10068 } else if (!ext
|| !strcmp(ext
, "c")) {
10069 /* C file assumed */
10070 ret
= tcc_compile(s1
);
10072 #ifdef CONFIG_TCC_ASM
10073 if (!strcmp(ext
, "S")) {
10074 /* preprocessed assembler */
10075 ret
= tcc_assemble(s1
, 1);
10076 } else if (!strcmp(ext
, "s")) {
10077 /* non preprocessed assembler */
10078 ret
= tcc_assemble(s1
, 0);
10081 #ifdef TCC_TARGET_PE
10082 if (!strcmp(ext
, "def")) {
10083 ret
= pe_load_def_file(s1
, fdopen(file
->fd
, "rb"));
10088 /* assume executable format: auto guess file type */
10089 ret
= read(fd
, &ehdr
, sizeof(ehdr
));
10090 lseek(fd
, 0, SEEK_SET
);
10092 error_noabort("could not read header");
10094 } else if (ret
!= sizeof(ehdr
)) {
10095 goto try_load_script
;
10098 if (ehdr
.e_ident
[0] == ELFMAG0
&&
10099 ehdr
.e_ident
[1] == ELFMAG1
&&
10100 ehdr
.e_ident
[2] == ELFMAG2
&&
10101 ehdr
.e_ident
[3] == ELFMAG3
) {
10102 file
->line_num
= 0; /* do not display line number if error */
10103 if (ehdr
.e_type
== ET_REL
) {
10104 ret
= tcc_load_object_file(s1
, fd
, 0);
10105 } else if (ehdr
.e_type
== ET_DYN
) {
10106 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
10107 #ifdef TCC_TARGET_PE
10111 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
10118 ret
= tcc_load_dll(s1
, fd
, filename
,
10119 (flags
& AFF_REFERENCED_DLL
) != 0);
10122 error_noabort("unrecognized ELF file");
10125 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
10126 file
->line_num
= 0; /* do not display line number if error */
10127 ret
= tcc_load_archive(s1
, fd
);
10129 #ifdef TCC_TARGET_COFF
10130 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
10131 ret
= tcc_load_coff(s1
, fd
);
10135 /* as GNU ld, consider it is an ld script if not recognized */
10137 ret
= tcc_load_ldscript(s1
);
10139 error_noabort("unrecognized file type");
10154 int tcc_add_file(TCCState
*s
, const char *filename
)
10156 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
10159 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
10163 pathname1
= tcc_strdup(pathname
);
10164 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
10168 /* find and load a dll. Return non zero if not found */
10169 /* XXX: add '-rpath' option support ? */
10170 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
10175 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10176 snprintf(buf
, sizeof(buf
), "%s/%s",
10177 s
->library_paths
[i
], filename
);
10178 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
10184 /* the library name is the same as the argument of the '-l' option */
10185 int tcc_add_library(TCCState
*s
, const char *libraryname
)
10190 /* first we look for the dynamic library if not static linking */
10191 if (!s
->static_link
) {
10192 #ifdef TCC_TARGET_PE
10193 snprintf(buf
, sizeof(buf
), "%s.def", libraryname
);
10195 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
10197 if (tcc_add_dll(s
, buf
, 0) == 0)
10201 /* then we look for the static library */
10202 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10203 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
10204 s
->library_paths
[i
], libraryname
);
10205 if (tcc_add_file_internal(s
, buf
, 0) == 0)
10211 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
10213 add_elf_sym(symtab_section
, val
, 0,
10214 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
), 0,
10219 int tcc_set_output_type(TCCState
*s
, int output_type
)
10221 s
->output_type
= output_type
;
10223 if (!s
->nostdinc
) {
10226 /* default include paths */
10227 /* XXX: reverse order needed if -isystem support */
10228 #ifndef TCC_TARGET_PE
10229 tcc_add_sysinclude_path(s
, "/usr/local/include");
10230 tcc_add_sysinclude_path(s
, "/usr/include");
10232 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
10233 tcc_add_sysinclude_path(s
, buf
);
10234 #ifdef TCC_TARGET_PE
10235 snprintf(buf
, sizeof(buf
), "%s/include/winapi", tcc_lib_path
);
10236 tcc_add_sysinclude_path(s
, buf
);
10240 /* if bound checking, then add corresponding sections */
10241 #ifdef CONFIG_TCC_BCHECK
10242 if (do_bounds_check
) {
10243 /* define symbol */
10244 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
10245 /* create bounds sections */
10246 bounds_section
= new_section(s
, ".bounds",
10247 SHT_PROGBITS
, SHF_ALLOC
);
10248 lbounds_section
= new_section(s
, ".lbounds",
10249 SHT_PROGBITS
, SHF_ALLOC
);
10253 if (s
->char_is_unsigned
) {
10254 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
10257 /* add debug sections */
10260 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
10261 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
10262 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
10263 put_elf_str(stabstr_section
, "");
10264 stab_section
->link
= stabstr_section
;
10265 /* put first entry */
10266 put_stabs("", 0, 0, 0, 0);
10269 /* add libc crt1/crti objects */
10270 #ifndef TCC_TARGET_PE
10271 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
10273 if (output_type
!= TCC_OUTPUT_DLL
)
10274 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
10275 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
10281 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
10282 #define FD_INVERT 0x0002 /* invert value before storing */
10284 typedef struct FlagDef
{
10290 static const FlagDef warning_defs
[] = {
10291 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
10292 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
10293 { offsetof(TCCState
, warn_error
), 0, "error" },
10294 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
10295 "implicit-function-declaration" },
10298 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
10299 const char *name
, int value
)
10306 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
10310 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
10311 if (!strcmp(r
, p
->name
))
10316 if (p
->flags
& FD_INVERT
)
10318 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
10323 /* set/reset a warning */
10324 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
10329 if (!strcmp(warning_name
, "all")) {
10330 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
10331 if (p
->flags
& WD_ALL
)
10332 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
10336 return set_flag(s
, warning_defs
, countof(warning_defs
),
10337 warning_name
, value
);
10341 static const FlagDef flag_defs
[] = {
10342 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
10343 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
10344 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
10345 { offsetof(TCCState
, leading_underscore
), 0, "leading-underscore" },
10348 /* set/reset a flag */
10349 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
10351 return set_flag(s
, flag_defs
, countof(flag_defs
),
10355 /* extract the basename of a file */
10356 static char *tcc_basename(const char *name
)
10359 p
= strrchr(name
, '/');
10362 p
= strrchr(name
, '\\');
10371 #if !defined(LIBTCC)
10373 static int64_t getclock_us(void)
10378 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
10381 gettimeofday(&tv
, NULL
);
10382 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
10388 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2006 Fabrice Bellard\n"
10389 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
10390 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]\n"
10391 " [infile1 infile2...] [-run infile args...]\n"
10393 "General options:\n"
10394 " -v display current version\n"
10395 " -c compile only - generate an object file\n"
10396 " -o outfile set output filename\n"
10397 " -Bdir set tcc internal library path\n"
10398 " -bench output compilation statistics\n"
10399 " -run run compiled source\n"
10400 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
10401 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
10402 " -w disable all warnings\n"
10403 "Preprocessor options:\n"
10404 " -E preprocess only\n"
10405 " -Idir add include path 'dir'\n"
10406 " -Dsym[=val] define 'sym' with value 'val'\n"
10407 " -Usym undefine 'sym'\n"
10408 "Linker options:\n"
10409 " -Ldir add library path 'dir'\n"
10410 " -llib link with dynamic or static library 'lib'\n"
10411 " -shared generate a shared library\n"
10412 " -static static linking\n"
10413 " -rdynamic export all global symbols to dynamic linker\n"
10414 " -r relocatable output\n"
10415 "Debugger options:\n"
10416 " -g generate runtime debug info\n"
10417 #ifdef CONFIG_TCC_BCHECK
10418 " -b compile with built-in memory and bounds checker (implies -g)\n"
10420 " -bt N show N callers in stack traces\n"
10424 #define TCC_OPTION_HAS_ARG 0x0001
10425 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
10427 typedef struct TCCOption
{
10455 TCC_OPTION_nostdinc
,
10456 TCC_OPTION_nostdlib
,
10457 TCC_OPTION_print_search_dirs
,
10458 TCC_OPTION_rdynamic
,
10466 static const TCCOption tcc_options
[] = {
10467 { "h", TCC_OPTION_HELP
, 0 },
10468 { "?", TCC_OPTION_HELP
, 0 },
10469 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
10470 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
10471 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
10472 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
10473 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
10474 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10475 { "bench", TCC_OPTION_bench
, 0 },
10476 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
10477 #ifdef CONFIG_TCC_BCHECK
10478 { "b", TCC_OPTION_b
, 0 },
10480 { "g", TCC_OPTION_g
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10481 { "c", TCC_OPTION_c
, 0 },
10482 { "static", TCC_OPTION_static
, 0 },
10483 { "shared", TCC_OPTION_shared
, 0 },
10484 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
10485 { "run", TCC_OPTION_run
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10486 { "rdynamic", TCC_OPTION_rdynamic
, 0 },
10487 { "r", TCC_OPTION_r
, 0 },
10488 { "Wl,", TCC_OPTION_Wl
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10489 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10490 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10491 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
10492 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10493 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
10494 { "nostdlib", TCC_OPTION_nostdlib
, 0 },
10495 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
10496 { "v", TCC_OPTION_v
, 0 },
10497 { "w", TCC_OPTION_w
, 0 },
10498 { "pipe", TCC_OPTION_pipe
, 0},
10499 { "E", TCC_OPTION_E
, 0},
10503 /* convert 'str' into an array of space separated strings */
10504 static int expand_args(char ***pargv
, const char *str
)
10513 while (is_space(*str
))
10518 while (*str
!= '\0' && !is_space(*str
))
10521 arg
= tcc_malloc(len
+ 1);
10522 memcpy(arg
, s1
, len
);
10524 dynarray_add((void ***)&argv
, &argc
, arg
);
10530 static char **files
;
10531 static int nb_files
, nb_libraries
;
10532 static int multiple_files
;
10533 static int print_search_dirs
;
10534 static int output_type
;
10535 static int reloc_output
;
10536 static const char *outfile
;
10538 int parse_args(TCCState
*s
, int argc
, char **argv
)
10541 const TCCOption
*popt
;
10542 const char *optarg
, *p1
, *r1
;
10547 if (optind
>= argc
) {
10548 if (nb_files
== 0 && !print_search_dirs
)
10553 r
= argv
[optind
++];
10555 /* add a new file */
10556 dynarray_add((void ***)&files
, &nb_files
, r
);
10557 if (!multiple_files
) {
10559 /* argv[0] will be this file */
10563 /* find option in table (match only the first chars */
10564 popt
= tcc_options
;
10568 error("invalid option -- '%s'", r
);
10581 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
10582 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
10585 if (optind
>= argc
)
10586 error("argument to '%s' is missing", r
);
10587 optarg
= argv
[optind
++];
10595 switch(popt
->index
) {
10596 case TCC_OPTION_HELP
:
10601 if (tcc_add_include_path(s
, optarg
) < 0)
10602 error("too many include paths");
10607 sym
= (char *)optarg
;
10608 value
= strchr(sym
, '=');
10613 tcc_define_symbol(s
, sym
, value
);
10617 tcc_undefine_symbol(s
, optarg
);
10620 tcc_add_library_path(s
, optarg
);
10623 /* set tcc utilities path (mainly for tcc development) */
10624 tcc_lib_path
= optarg
;
10627 dynarray_add((void ***)&files
, &nb_files
, r
);
10630 case TCC_OPTION_bench
:
10633 case TCC_OPTION_bt
:
10634 num_callers
= atoi(optarg
);
10636 #ifdef CONFIG_TCC_BCHECK
10638 do_bounds_check
= 1;
10646 multiple_files
= 1;
10647 output_type
= TCC_OUTPUT_OBJ
;
10649 case TCC_OPTION_static
:
10650 s
->static_link
= 1;
10652 case TCC_OPTION_shared
:
10653 output_type
= TCC_OUTPUT_DLL
;
10656 multiple_files
= 1;
10660 /* generate a .o merging several output files */
10662 output_type
= TCC_OUTPUT_OBJ
;
10664 case TCC_OPTION_nostdinc
:
10667 case TCC_OPTION_nostdlib
:
10670 case TCC_OPTION_print_search_dirs
:
10671 print_search_dirs
= 1;
10673 case TCC_OPTION_run
:
10677 argc1
= expand_args(&argv1
, optarg
);
10679 parse_args(s
, argc1
, argv1
);
10681 multiple_files
= 0;
10682 output_type
= TCC_OUTPUT_MEMORY
;
10686 printf("tcc version %s\n", TCC_VERSION
);
10689 if (tcc_set_flag(s
, optarg
, 1) < 0 && s
->warn_unsupported
)
10690 goto unsupported_option
;
10693 if (tcc_set_warning(s
, optarg
, 1) < 0 &&
10694 s
->warn_unsupported
)
10695 goto unsupported_option
;
10700 case TCC_OPTION_rdynamic
:
10703 case TCC_OPTION_Wl
:
10706 if (strstart(optarg
, "-Ttext,", &p
)) {
10707 s
->text_addr
= strtoul(p
, NULL
, 16);
10708 s
->has_text_addr
= 1;
10709 } else if (strstart(optarg
, "--oformat,", &p
)) {
10710 if (strstart(p
, "elf32-", NULL
)) {
10711 s
->output_format
= TCC_OUTPUT_FORMAT_ELF
;
10712 } else if (!strcmp(p
, "binary")) {
10713 s
->output_format
= TCC_OUTPUT_FORMAT_BINARY
;
10715 #ifdef TCC_TARGET_COFF
10716 if (!strcmp(p
, "coff")) {
10717 s
->output_format
= TCC_OUTPUT_FORMAT_COFF
;
10721 error("target %s not found", p
);
10724 error("unsupported linker option '%s'", optarg
);
10729 output_type
= TCC_OUTPUT_PREPROCESS
;
10732 if (s
->warn_unsupported
) {
10733 unsupported_option
:
10734 warning("unsupported option '%s'", r
);
10743 int main(int argc
, char **argv
)
10747 int nb_objfiles
, ret
, optind
;
10748 char objfilename
[1024];
10749 int64_t start_time
= 0;
10752 /* on win32, we suppose the lib and includes are at the location
10755 static char path
[1024];
10758 GetModuleFileNameA(NULL
, path
, sizeof path
);
10759 p
= d
= strlwr(path
);
10762 if (*d
== '\\') *d
= '/', p
= d
;
10766 tcc_lib_path
= path
;
10771 output_type
= TCC_OUTPUT_EXE
;
10773 multiple_files
= 1;
10778 print_search_dirs
= 0;
10780 optind
= parse_args(s
, argc
- 1, argv
+ 1) + 1;
10782 if (print_search_dirs
) {
10783 /* enough for Linux kernel */
10784 printf("install: %s/\n", tcc_lib_path
);
10788 nb_objfiles
= nb_files
- nb_libraries
;
10790 /* if outfile provided without other options, we output an
10792 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
10793 output_type
= TCC_OUTPUT_EXE
;
10795 /* check -c consistency : only single file handled. XXX: checks file type */
10796 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
10797 /* accepts only a single input file */
10798 if (nb_objfiles
!= 1)
10799 error("cannot specify multiple files with -c");
10800 if (nb_libraries
!= 0)
10801 error("cannot specify libraries with -c");
10805 if (output_type
== TCC_OUTPUT_PREPROCESS
) {
10807 s
->outfile
= stdout
;
10809 s
->outfile
= fopen(outfile
, "wb");
10811 error("could not open '%s", outfile
);
10813 } else if (output_type
!= TCC_OUTPUT_MEMORY
) {
10815 /* compute default outfile name */
10816 pstrcpy(objfilename
, sizeof(objfilename
) - 1,
10818 tcc_basename(files
[0]));
10819 #ifdef TCC_TARGET_PE
10820 pe_guess_outfile(objfilename
, output_type
);
10822 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
10823 char *ext
= strrchr(objfilename
, '.');
10825 goto default_outfile
;
10826 /* add .o extension */
10827 strcpy(ext
+ 1, "o");
10830 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
10833 outfile
= objfilename
;
10838 start_time
= getclock_us();
10841 tcc_set_output_type(s
, output_type
);
10843 /* compile or add each files or library */
10844 for(i
= 0;i
< nb_files
; i
++) {
10845 const char *filename
;
10847 filename
= files
[i
];
10848 if (output_type
== TCC_OUTPUT_PREPROCESS
) {
10849 tcc_add_file_internal(s
, filename
,
10850 AFF_PRINT_ERROR
| AFF_PREPROCESS
);
10852 if (filename
[0] == '-') {
10853 if (tcc_add_library(s
, filename
+ 2) < 0)
10854 error("cannot find %s", filename
);
10856 if (tcc_add_file(s
, filename
) < 0) {
10864 /* free all files */
10869 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
10870 if (total_time
< 0.001)
10871 total_time
= 0.001;
10872 if (total_bytes
< 1)
10874 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
10875 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
10876 total_time
, (int)(total_lines
/ total_time
),
10877 total_bytes
/ total_time
/ 1000000.0);
10880 if (s
->output_type
== TCC_OUTPUT_PREPROCESS
) {
10882 fclose(s
->outfile
);
10884 } else if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
10885 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
10887 #ifdef TCC_TARGET_PE
10888 if (s
->output_type
!= TCC_OUTPUT_OBJ
) {
10889 ret
= tcc_output_pe(s
, outfile
);
10893 ret
= tcc_output_file(s
, outfile
) ? 1 : 0;
10896 /* XXX: cannot do it with bound checking because of the malloc hooks */
10897 if (!do_bounds_check
)
10902 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);