2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 #define CONFIG_TCC_STATIC
42 #include <sys/timeb.h>
47 #include <sys/ucontext.h>
51 #endif /* !CONFIG_TCCBOOT */
68 /* preprocessor debug */
70 /* include file debug */
78 /* target selection */
79 //#define TCC_TARGET_I386 /* i386 code generator */
80 //#define TCC_TARGET_ARM /* ARMv4 code generator */
81 //#define TCC_TARGET_C67 /* TMS320C67xx code generator */
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 */
253 /* field 'Sym.t' for macros */
254 #define MACRO_OBJ 0 /* object like macro */
255 #define MACRO_FUNC 1 /* function like macro */
257 /* field 'Sym.r' for C labels */
258 #define LABEL_DEFINED 0 /* label is defined */
259 #define LABEL_FORWARD 1 /* label is forward defined */
260 #define LABEL_DECLARED 2 /* label is declared but never used */
262 /* type_decl() types */
263 #define TYPE_ABSTRACT 1 /* type without variable */
264 #define TYPE_DIRECT 2 /* type with variable */
266 #define IO_BUF_SIZE 8192
268 typedef struct BufferedFile
{
272 int line_num
; /* current line number - here to simplify code */
273 int ifndef_macro
; /* #ifndef macro / #endif search */
274 int ifndef_macro_saved
; /* saved ifndef_macro */
275 int *ifdef_stack_ptr
; /* ifdef_stack value at the start of the file */
276 char inc_type
; /* type of include */
277 char inc_filename
[512]; /* filename specified by the user */
278 char filename
[1024]; /* current filename - here to simplify code */
279 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
282 #define CH_EOB '\\' /* end of buffer or '\0' char in file */
283 #define CH_EOF (-1) /* end of file */
285 /* parsing state (used to save parser state to reparse part of the
286 source several times) */
287 typedef struct ParseState
{
294 /* used to record tokens */
295 typedef struct TokenString
{
302 /* include file cache, used to find files faster and also to eliminate
303 inclusion if the include file is protected by #ifndef ... #endif */
304 typedef struct CachedInclude
{
306 int hash_next
; /* -1 if none */
307 char type
; /* '"' or '>' to give include type */
308 char filename
[1]; /* path specified in #include */
311 #define CACHED_INCLUDES_HASH_SIZE 512
314 static struct BufferedFile
*file
;
317 static CString tokcstr
; /* current parsed string, if any */
318 /* additional informations about token */
319 static int tok_flags
;
320 #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
321 #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
322 #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
324 static int *macro_ptr
, *macro_ptr_allocated
;
325 static int *unget_saved_macro_ptr
;
326 static int unget_saved_buffer
[TOK_MAX_SIZE
+ 1];
327 static int unget_buffer_enabled
;
328 static int parse_flags
;
329 #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
330 #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
331 #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
332 token. line feed is also
334 #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
336 static Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
337 static Section
*cur_text_section
; /* current section where function code is
339 #ifdef CONFIG_TCC_ASM
340 static Section
*last_text_section
; /* to handle .previous asm directive */
342 /* bound check related sections */
343 static Section
*bounds_section
; /* contains global data bound description */
344 static Section
*lbounds_section
; /* contains local data bound description */
345 /* symbol sections */
346 static Section
*symtab_section
, *strtab_section
;
349 static Section
*stab_section
, *stabstr_section
;
351 /* loc : local variable index
352 ind : output code index
354 anon_sym: anonymous symbol index
356 static int rsym
, anon_sym
, ind
, loc
;
357 /* expression generation modifiers */
358 static int const_wanted
; /* true if constant wanted */
359 static int nocode_wanted
; /* true if no code generation wanted for an expression */
360 static int global_expr
; /* true if compound literals must be allocated
361 globally (used during initializers parsing */
362 static CType func_vt
; /* current function return type (used by return
365 static int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
366 static int tok_ident
;
367 static TokenSym
**table_ident
;
368 static TokenSym
*hash_ident
[TOK_HASH_SIZE
];
369 static char token_buf
[STRING_MAX_SIZE
+ 1];
370 static char *funcname
;
371 static Sym
*global_stack
, *local_stack
;
372 static Sym
*define_stack
;
373 static Sym
*global_label_stack
, *local_label_stack
;
374 /* symbol allocator */
375 #define SYM_POOL_NB (8192 / sizeof(Sym))
376 static Sym
*sym_free_first
;
378 static SValue vstack
[VSTACK_SIZE
], *vtop
;
379 /* some predefined types */
380 static CType char_pointer_type
, func_old_type
, int_type
;
381 /* true if isid(c) || isnum(c) */
382 static unsigned char isidnum_table
[256];
384 /* compile with debug symbol (and use them if error during execution) */
385 static int do_debug
= 0;
387 /* compile with built-in memory and bounds checker */
388 static int do_bounds_check
= 0;
390 /* display benchmark infos */
392 static int do_bench
= 0;
394 static int total_lines
;
395 static int total_bytes
;
397 /* use GNU C extensions */
398 static int gnu_ext
= 1;
400 /* use Tiny C extensions */
401 static int tcc_ext
= 1;
403 /* max number of callers shown if error */
404 static int num_callers
= 6;
405 static const char **rt_bound_error_msg
;
407 /* XXX: get rid of this ASAP */
408 static struct TCCState
*tcc_state
;
410 /* give the path of the tcc libraries */
411 static const char *tcc_lib_path
= CONFIG_TCCDIR
;
416 BufferedFile
**include_stack_ptr
;
417 int *ifdef_stack_ptr
;
419 /* include file handling */
420 char **include_paths
;
421 int nb_include_paths
;
422 char **sysinclude_paths
;
423 int nb_sysinclude_paths
;
424 CachedInclude
**cached_includes
;
425 int nb_cached_includes
;
427 char **library_paths
;
428 int nb_library_paths
;
430 /* array of all loaded dlls (including those referenced by loaded
432 DLLReference
**loaded_dlls
;
437 int nb_sections
; /* number of sections, including first dummy section */
442 unsigned long *got_offsets
;
444 /* give the correspondance from symtab indexes to dynsym indexes */
445 int *symtab_to_dynsym
;
447 /* temporary dynamic symbol sections (for dll loading) */
448 Section
*dynsymtab_section
;
449 /* exported dynamic symbol section */
452 int nostdinc
; /* if true, no standard headers are added */
453 int nostdlib
; /* if true, no standard libraries are added */
455 int nocommon
; /* if true, do not use common symbols for .bss data */
457 /* if true, static linking is performed */
460 /* if true, all symbols are exported */
463 /* if true, only link in referenced objects from archive */
466 /* address of text section */
467 unsigned long text_addr
;
470 /* output format, see TCC_OUTPUT_FORMAT_xxx */
473 /* C language options */
474 int char_is_unsigned
;
475 int leading_underscore
;
477 /* warning switches */
478 int warn_write_strings
;
479 int warn_unsupported
;
482 int warn_implicit_function_declaration
;
486 void (*error_func
)(void *opaque
, const char *msg
);
487 int error_set_jmp_enabled
;
488 jmp_buf error_jmp_buf
;
491 /* tiny assembler state */
494 /* see include_stack_ptr */
495 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
];
497 /* see ifdef_stack_ptr */
498 int ifdef_stack
[IFDEF_STACK_SIZE
];
500 /* see cached_includes */
501 int cached_includes_hash
[CACHED_INCLUDES_HASH_SIZE
];
504 int pack_stack
[PACK_STACK_SIZE
];
508 /* The current value can be: */
509 #define VT_VALMASK 0x00ff
510 #define VT_CONST 0x00f0 /* constant in vc
511 (must be first non register value) */
512 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
513 #define VT_LOCAL 0x00f2 /* offset on stack */
514 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
515 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
516 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
517 #define VT_LVAL 0x0100 /* var is an lvalue */
518 #define VT_SYM 0x0200 /* a symbol value is added */
519 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
520 char/short stored in integer registers) */
521 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
522 dereferencing value */
523 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
524 bounding function call point is in vc */
525 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
526 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
527 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
528 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
531 #define VT_INT 0 /* integer type */
532 #define VT_BYTE 1 /* signed byte type */
533 #define VT_SHORT 2 /* short type */
534 #define VT_VOID 3 /* void type */
535 #define VT_PTR 4 /* pointer */
536 #define VT_ENUM 5 /* enum definition */
537 #define VT_FUNC 6 /* function type */
538 #define VT_STRUCT 7 /* struct/union definition */
539 #define VT_FLOAT 8 /* IEEE float */
540 #define VT_DOUBLE 9 /* IEEE double */
541 #define VT_LDOUBLE 10 /* IEEE long double */
542 #define VT_BOOL 11 /* ISOC99 boolean type */
543 #define VT_LLONG 12 /* 64 bit integer */
544 #define VT_LONG 13 /* long integer (NEVER USED as type, only
546 #define VT_BTYPE 0x000f /* mask for basic type */
547 #define VT_UNSIGNED 0x0010 /* unsigned type */
548 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
549 #define VT_BITFIELD 0x0040 /* bitfield modifier */
550 #define VT_CONSTANT 0x0800 /* const modifier */
551 #define VT_VOLATILE 0x1000 /* volatile modifier */
552 #define VT_SIGNED 0x2000 /* signed type */
555 #define VT_EXTERN 0x00000080 /* extern definition */
556 #define VT_STATIC 0x00000100 /* static variable */
557 #define VT_TYPEDEF 0x00000200 /* typedef definition */
558 #define VT_INLINE 0x00000400 /* inline definition */
560 #define VT_STRUCT_SHIFT 16 /* shift for bitfield shift values */
562 /* type mask (except storage) */
563 #define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE)
564 #define VT_TYPE (~(VT_STORAGE))
568 /* warning: the following compare tokens depend on i386 asm code */
580 #define TOK_LAND 0xa0
584 #define TOK_MID 0xa3 /* inc/dec, to void constant */
586 #define TOK_UDIV 0xb0 /* unsigned division */
587 #define TOK_UMOD 0xb1 /* unsigned modulo */
588 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
589 #define TOK_CINT 0xb3 /* number in tokc */
590 #define TOK_CCHAR 0xb4 /* char constant in tokc */
591 #define TOK_STR 0xb5 /* pointer to string in tokc */
592 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
593 #define TOK_LCHAR 0xb7
594 #define TOK_LSTR 0xb8
595 #define TOK_CFLOAT 0xb9 /* float constant */
596 #define TOK_LINENUM 0xba /* line number info */
597 #define TOK_CDOUBLE 0xc0 /* double constant */
598 #define TOK_CLDOUBLE 0xc1 /* long double constant */
599 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
600 #define TOK_ADDC1 0xc3 /* add with carry generation */
601 #define TOK_ADDC2 0xc4 /* add with carry use */
602 #define TOK_SUBC1 0xc5 /* add with carry generation */
603 #define TOK_SUBC2 0xc6 /* add with carry use */
604 #define TOK_CUINT 0xc8 /* unsigned int constant */
605 #define TOK_CLLONG 0xc9 /* long long constant */
606 #define TOK_CULLONG 0xca /* unsigned long long constant */
607 #define TOK_ARROW 0xcb
608 #define TOK_DOTS 0xcc /* three dots */
609 #define TOK_SHR 0xcd /* unsigned shift right */
610 #define TOK_PPNUM 0xce /* preprocessor number */
612 #define TOK_SHL 0x01 /* shift left */
613 #define TOK_SAR 0x02 /* signed shift right */
615 /* assignement operators : normal operator or 0x80 */
616 #define TOK_A_MOD 0xa5
617 #define TOK_A_AND 0xa6
618 #define TOK_A_MUL 0xaa
619 #define TOK_A_ADD 0xab
620 #define TOK_A_SUB 0xad
621 #define TOK_A_DIV 0xaf
622 #define TOK_A_XOR 0xde
623 #define TOK_A_OR 0xfc
624 #define TOK_A_SHL 0x81
625 #define TOK_A_SAR 0x82
628 #define offsetof(type, field) ((size_t) &((type *)0)->field)
632 #define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
635 /* WARNING: the content of this string encodes token numbers */
636 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";
638 #define TOK_EOF (-1) /* end of file */
639 #define TOK_LINEFEED 10 /* line feed */
641 /* all identificators and strings have token above that */
642 #define TOK_IDENT 256
644 /* only used for i386 asm opcodes definitions */
645 #define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
648 DEF(TOK_ASM_ ## x ## b, #x "b") \
649 DEF(TOK_ASM_ ## x ## w, #x "w") \
650 DEF(TOK_ASM_ ## x ## l, #x "l") \
651 DEF(TOK_ASM_ ## x, #x)
654 DEF(TOK_ASM_ ## x ## w, #x "w") \
655 DEF(TOK_ASM_ ## x ## l, #x "l") \
656 DEF(TOK_ASM_ ## x, #x)
659 DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
660 DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
661 DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
662 DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
665 DEF(TOK_ASM_ ## f ## x, "f" #x ) \
666 DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
669 #define DEF_ASMTEST(x) \
701 #define TOK_ASM_int TOK_INT
704 TOK_LAST
= TOK_IDENT
- 1,
705 #define DEF(id, str) id,
710 static const char tcc_keywords
[] =
711 #define DEF(id, str) str "\0"
716 #define TOK_UIDENT TOK_DEFINE
719 int __stdcall
GetModuleFileNameA(void *, char *, int);
720 void *__stdcall
GetProcAddress(void *, const char *);
721 void *__stdcall
GetModuleHandleA(const char *);
722 void *__stdcall
LoadLibraryA(const char *);
723 int __stdcall
FreeConsole(void);
725 #define snprintf _snprintf
726 #define vsnprintf _vsnprintf
728 #define strtold (long double)strtod
729 #define strtof (float)strtod
730 #define strtoll (long long)strtol
732 #elif defined(TCC_UCLIBC) || defined(__FreeBSD__)
733 /* currently incorrect */
734 long double strtold(const char *nptr
, char **endptr
)
736 return (long double)strtod(nptr
, endptr
);
738 float strtof(const char *nptr
, char **endptr
)
740 return (float)strtod(nptr
, endptr
);
743 /* XXX: need to define this to use them in non ISOC99 context */
744 extern float strtof (const char *__nptr
, char **__endptr
);
745 extern long double strtold (const char *__nptr
, char **__endptr
);
748 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
749 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
750 static const char *tcc_basename(const char *name
);
752 static void next(void);
753 static void next_nomacro(void);
754 static void parse_expr_type(CType
*type
);
755 static void expr_type(CType
*type
);
756 static void unary_type(CType
*type
);
757 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
758 int case_reg
, int is_expr
);
759 static int expr_const(void);
760 static void expr_eq(void);
761 static void gexpr(void);
762 static void gen_inline_functions(void);
763 static void decl(int l
);
764 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
765 int first
, int size_only
);
766 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
767 int has_init
, int v
, int scope
);
769 void gv2(int rc1
, int rc2
);
770 void move_reg(int r
, int s
);
771 void save_regs(int n
);
772 void save_reg(int r
);
777 int get_reg_ex(int rc
,int rc2
);
780 struct macro_level
*prev
;
784 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
785 const int *macro_str
, struct macro_level
**can_read_stream
);
787 void force_charshort_cast(int t
);
788 static void gen_cast(CType
*type
);
790 static Sym
*sym_find(int v
);
791 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
);
794 static int type_size(CType
*type
, int *a
);
795 static inline CType
*pointed_type(CType
*type
);
796 static int pointed_size(CType
*type
);
797 static int lvalue_type(int t
);
798 static int parse_btype(CType
*type
, AttributeDef
*ad
);
799 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
);
800 static int is_compatible_types(CType
*type1
, CType
*type2
);
802 int ieee_finite(double d
);
803 void error(const char *fmt
, ...);
807 void lexpand_nr(void);
808 static void vpush_global_sym(CType
*type
, int v
);
809 void vset(CType
*type
, int r
, int v
);
810 void type_to_str(char *buf
, int buf_size
,
811 CType
*type
, const char *varstr
);
812 char *get_tok_str(int v
, CValue
*cv
);
813 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
814 unsigned long offset
, unsigned long size
);
815 static Sym
*external_global_sym(int v
, CType
*type
, int r
);
817 /* section generation */
818 static void section_realloc(Section
*sec
, unsigned long new_size
);
819 static void *section_ptr_add(Section
*sec
, unsigned long size
);
820 static void put_extern_sym(Sym
*sym
, Section
*section
,
821 unsigned long value
, unsigned long size
);
822 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
823 static int put_elf_str(Section
*s
, const char *sym
);
824 static int put_elf_sym(Section
*s
,
825 unsigned long value
, unsigned long size
,
826 int info
, int other
, int shndx
, const char *name
);
827 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
828 int info
, int other
, int sh_num
, const char *name
);
829 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
830 int type
, int symbol
);
831 static void put_stabs(const char *str
, int type
, int other
, int desc
,
832 unsigned long value
);
833 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
834 unsigned long value
, Section
*sec
, int sym_index
);
835 static void put_stabn(int type
, int other
, int desc
, int value
);
836 static void put_stabd(int type
, int other
, int desc
);
837 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
839 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
840 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
841 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
844 int tcc_output_coff(TCCState
*s1
, FILE *f
);
847 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
);
848 int pe_load_def_file(struct TCCState
*s1
, FILE *fp
);
849 void pe_setup_paths(struct TCCState
*s1
, int *p_output_type
, const char **p_outfile
, char *first_file
);
850 unsigned long pe_add_runtime(struct TCCState
*s1
);
851 int tcc_output_pe(struct TCCState
*s1
, const char *filename
);
855 #ifdef CONFIG_TCC_ASM
857 typedef struct ExprValue
{
862 #define MAX_ASM_OPERANDS 30
864 typedef struct ASMOperand
{
865 int id
; /* GCC 3 optionnal identifier (0 if number only supported */
867 char asm_str
[16]; /* computed asm string for operand */
868 SValue
*vt
; /* C value of the expression */
869 int ref_index
; /* if >= 0, gives reference to a output constraint */
870 int input_index
; /* if >= 0, gives reference to an input constraint */
871 int priority
; /* priority, used to assign registers */
872 int reg
; /* if >= 0, register number used for this operand */
873 int is_llong
; /* true if double register value */
874 int is_memory
; /* true if memory operand */
875 int is_rw
; /* for '+' modifier */
878 static void asm_expr(TCCState
*s1
, ExprValue
*pe
);
879 static int asm_int_expr(TCCState
*s1
);
880 static int find_constraint(ASMOperand
*operands
, int nb_operands
,
881 const char *name
, const char **pp
);
883 static int tcc_assemble(TCCState
*s1
, int do_preprocess
);
887 static void asm_instr(void);
888 static void asm_global_instr(void);
890 /* true if float/double/long double type */
891 static inline int is_float(int t
)
895 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
898 #ifdef TCC_TARGET_I386
899 #include "i386-gen.c"
902 #ifdef TCC_TARGET_ARM
906 #ifdef TCC_TARGET_C67
910 #ifdef CONFIG_TCC_STATIC
912 #define RTLD_LAZY 0x001
913 #define RTLD_NOW 0x002
914 #define RTLD_GLOBAL 0x100
915 #define RTLD_DEFAULT NULL
917 /* dummy function for profiling */
918 void *dlopen(const char *filename
, int flag
)
923 const char *dlerror(void)
928 typedef struct TCCSyms
{
933 #define TCCSYM(a) { #a, &a, },
935 /* add the symbol you want here if no dynamic linking is done */
936 static TCCSyms tcc_syms
[] = {
937 #if !defined(CONFIG_TCCBOOT)
946 void *resolve_sym(TCCState
*s1
, const char *symbol
, int type
)
950 while (p
->str
!= NULL
) {
951 if (!strcmp(p
->str
, symbol
))
958 #elif !defined(WIN32)
962 void *resolve_sym(TCCState
*s1
, const char *sym
, int type
)
964 return dlsym(RTLD_DEFAULT
, sym
);
969 /********************************************************/
971 /* we use our own 'finite' function to avoid potential problems with
972 non standard math libs */
973 /* XXX: endianness dependent */
974 int ieee_finite(double d
)
977 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
980 /* copy a string and truncate it. */
981 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
988 q_end
= buf
+ buf_size
- 1;
1000 /* strcat and truncate. */
1001 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
1006 pstrcpy(buf
+ len
, buf_size
- len
, s
);
1010 static int strstart(const char *str
, const char *val
, const char **ptr
)
1015 while (*q
!= '\0') {
1026 /* memory management */
1032 static inline void tcc_free(void *ptr
)
1035 mem_cur_size
-= malloc_usable_size(ptr
);
1040 static void *tcc_malloc(unsigned long size
)
1045 error("memory full");
1047 mem_cur_size
+= malloc_usable_size(ptr
);
1048 if (mem_cur_size
> mem_max_size
)
1049 mem_max_size
= mem_cur_size
;
1054 static void *tcc_mallocz(unsigned long size
)
1057 ptr
= tcc_malloc(size
);
1058 memset(ptr
, 0, size
);
1062 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
1066 mem_cur_size
-= malloc_usable_size(ptr
);
1068 ptr1
= realloc(ptr
, size
);
1070 /* NOTE: count not correct if alloc error, but not critical */
1071 mem_cur_size
+= malloc_usable_size(ptr1
);
1072 if (mem_cur_size
> mem_max_size
)
1073 mem_max_size
= mem_cur_size
;
1078 static char *tcc_strdup(const char *str
)
1081 ptr
= tcc_malloc(strlen(str
) + 1);
1086 #define free(p) use_tcc_free(p)
1087 #define malloc(s) use_tcc_malloc(s)
1088 #define realloc(p, s) use_tcc_realloc(p, s)
1090 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
1097 /* every power of two we double array size */
1098 if ((nb
& (nb
- 1)) == 0) {
1103 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
1105 error("memory full");
1112 /* symbol allocator */
1113 static Sym
*__sym_malloc(void)
1115 Sym
*sym_pool
, *sym
, *last_sym
;
1118 sym_pool
= tcc_malloc(SYM_POOL_NB
* sizeof(Sym
));
1120 last_sym
= sym_free_first
;
1122 for(i
= 0; i
< SYM_POOL_NB
; i
++) {
1123 sym
->next
= last_sym
;
1127 sym_free_first
= last_sym
;
1131 static inline Sym
*sym_malloc(void)
1134 sym
= sym_free_first
;
1136 sym
= __sym_malloc();
1137 sym_free_first
= sym
->next
;
1141 static inline void sym_free(Sym
*sym
)
1143 sym
->next
= sym_free_first
;
1144 sym_free_first
= sym
;
1147 Section
*new_section(TCCState
*s1
, const char *name
, int sh_type
, int sh_flags
)
1151 sec
= tcc_mallocz(sizeof(Section
) + strlen(name
));
1152 strcpy(sec
->name
, name
);
1153 sec
->sh_type
= sh_type
;
1154 sec
->sh_flags
= sh_flags
;
1161 sec
->sh_addralign
= 4;
1164 sec
->sh_addralign
= 1;
1167 sec
->sh_addralign
= 32; /* default conservative alignment */
1171 /* only add section if not private */
1172 if (!(sh_flags
& SHF_PRIVATE
)) {
1173 sec
->sh_num
= s1
->nb_sections
;
1174 dynarray_add((void ***)&s1
->sections
, &s1
->nb_sections
, sec
);
1179 static void free_section(Section
*s
)
1185 /* realloc section and set its content to zero */
1186 static void section_realloc(Section
*sec
, unsigned long new_size
)
1189 unsigned char *data
;
1191 size
= sec
->data_allocated
;
1194 while (size
< new_size
)
1196 data
= tcc_realloc(sec
->data
, size
);
1198 error("memory full");
1199 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
1201 sec
->data_allocated
= size
;
1204 /* reserve at least 'size' bytes in section 'sec' from
1205 sec->data_offset. */
1206 static void *section_ptr_add(Section
*sec
, unsigned long size
)
1208 unsigned long offset
, offset1
;
1210 offset
= sec
->data_offset
;
1211 offset1
= offset
+ size
;
1212 if (offset1
> sec
->data_allocated
)
1213 section_realloc(sec
, offset1
);
1214 sec
->data_offset
= offset1
;
1215 return sec
->data
+ offset
;
1218 /* return a reference to a section, and create it if it does not
1220 Section
*find_section(TCCState
*s1
, const char *name
)
1224 for(i
= 1; i
< s1
->nb_sections
; i
++) {
1225 sec
= s1
->sections
[i
];
1226 if (!strcmp(name
, sec
->name
))
1229 /* sections are created as PROGBITS */
1230 return new_section(s1
, name
, SHT_PROGBITS
, SHF_ALLOC
);
1233 #define SECTION_ABS ((void *)1)
1235 /* update sym->c so that it points to an external symbol in section
1236 'section' with value 'value' */
1237 static void put_extern_sym2(Sym
*sym
, Section
*section
,
1238 unsigned long value
, unsigned long size
,
1239 int can_add_underscore
)
1241 int sym_type
, sym_bind
, sh_num
, info
;
1246 if (section
== NULL
)
1248 else if (section
== SECTION_ABS
)
1251 sh_num
= section
->sh_num
;
1253 if ((sym
->type
.t
& VT_BTYPE
) == VT_FUNC
)
1254 sym_type
= STT_FUNC
;
1256 sym_type
= STT_OBJECT
;
1257 if (sym
->type
.t
& VT_STATIC
)
1258 sym_bind
= STB_LOCAL
;
1260 sym_bind
= STB_GLOBAL
;
1262 name
= get_tok_str(sym
->v
, NULL
);
1263 #ifdef CONFIG_TCC_BCHECK
1264 if (do_bounds_check
) {
1267 /* XXX: avoid doing that for statics ? */
1268 /* if bound checking is activated, we change some function
1269 names by adding the "__bound" prefix */
1272 /* XXX: we rely only on malloc hooks */
1284 strcpy(buf
, "__bound_");
1291 if (tcc_state
->leading_underscore
&& can_add_underscore
) {
1293 pstrcpy(buf1
+ 1, sizeof(buf1
) - 1, name
);
1296 info
= ELF32_ST_INFO(sym_bind
, sym_type
);
1297 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, 0, sh_num
, name
);
1299 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
1300 esym
->st_value
= value
;
1301 esym
->st_size
= size
;
1302 esym
->st_shndx
= sh_num
;
1306 static void put_extern_sym(Sym
*sym
, Section
*section
,
1307 unsigned long value
, unsigned long size
)
1309 put_extern_sym2(sym
, section
, value
, size
, 1);
1312 /* add a new relocation entry to symbol 'sym' in section 's' */
1313 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
1316 put_extern_sym(sym
, NULL
, 0, 0);
1317 /* now we can add ELF relocation info */
1318 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
1321 static inline int isid(int c
)
1323 return (c
>= 'a' && c
<= 'z') ||
1324 (c
>= 'A' && c
<= 'Z') ||
1328 static inline int isnum(int c
)
1330 return c
>= '0' && c
<= '9';
1333 static inline int isoct(int c
)
1335 return c
>= '0' && c
<= '7';
1338 static inline int toup(int c
)
1340 if (c
>= 'a' && c
<= 'z')
1341 return c
- 'a' + 'A';
1346 static void strcat_vprintf(char *buf
, int buf_size
, const char *fmt
, va_list ap
)
1350 vsnprintf(buf
+ len
, buf_size
- len
, fmt
, ap
);
1353 static void strcat_printf(char *buf
, int buf_size
, const char *fmt
, ...)
1357 strcat_vprintf(buf
, buf_size
, fmt
, ap
);
1361 void error1(TCCState
*s1
, int is_warning
, const char *fmt
, va_list ap
)
1368 for(f
= s1
->include_stack
; f
< s1
->include_stack_ptr
; f
++)
1369 strcat_printf(buf
, sizeof(buf
), "In file included from %s:%d:\n",
1370 (*f
)->filename
, (*f
)->line_num
);
1371 if (file
->line_num
> 0) {
1372 strcat_printf(buf
, sizeof(buf
),
1373 "%s:%d: ", file
->filename
, file
->line_num
);
1375 strcat_printf(buf
, sizeof(buf
),
1376 "%s: ", file
->filename
);
1379 strcat_printf(buf
, sizeof(buf
),
1383 strcat_printf(buf
, sizeof(buf
), "warning: ");
1384 strcat_vprintf(buf
, sizeof(buf
), fmt
, ap
);
1386 if (!s1
->error_func
) {
1387 /* default case: stderr */
1388 fprintf(stderr
, "%s\n", buf
);
1390 s1
->error_func(s1
->error_opaque
, buf
);
1392 if (!is_warning
|| s1
->warn_error
)
1397 void tcc_set_error_func(TCCState
*s
, void *error_opaque
,
1398 void (*error_func
)(void *opaque
, const char *msg
))
1400 s
->error_opaque
= error_opaque
;
1401 s
->error_func
= error_func
;
1405 /* error without aborting current compilation */
1406 void error_noabort(const char *fmt
, ...)
1408 TCCState
*s1
= tcc_state
;
1412 error1(s1
, 0, fmt
, ap
);
1416 void error(const char *fmt
, ...)
1418 TCCState
*s1
= tcc_state
;
1422 error1(s1
, 0, fmt
, ap
);
1424 /* better than nothing: in some cases, we accept to handle errors */
1425 if (s1
->error_set_jmp_enabled
) {
1426 longjmp(s1
->error_jmp_buf
, 1);
1428 /* XXX: eliminate this someday */
1433 void expect(const char *msg
)
1435 error("%s expected", msg
);
1438 void warning(const char *fmt
, ...)
1440 TCCState
*s1
= tcc_state
;
1447 error1(s1
, 1, fmt
, ap
);
1454 error("'%c' expected", c
);
1458 static void test_lvalue(void)
1460 if (!(vtop
->r
& VT_LVAL
))
1464 /* allocate a new token */
1465 static TokenSym
*tok_alloc_new(TokenSym
**pts
, const char *str
, int len
)
1467 TokenSym
*ts
, **ptable
;
1470 if (tok_ident
>= SYM_FIRST_ANOM
)
1471 error("memory full");
1473 /* expand token table if needed */
1474 i
= tok_ident
- TOK_IDENT
;
1475 if ((i
% TOK_ALLOC_INCR
) == 0) {
1476 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1478 error("memory full");
1479 table_ident
= ptable
;
1482 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1483 table_ident
[i
] = ts
;
1484 ts
->tok
= tok_ident
++;
1485 ts
->sym_define
= NULL
;
1486 ts
->sym_label
= NULL
;
1487 ts
->sym_struct
= NULL
;
1488 ts
->sym_identifier
= NULL
;
1490 ts
->hash_next
= NULL
;
1491 memcpy(ts
->str
, str
, len
);
1492 ts
->str
[len
] = '\0';
1497 #define TOK_HASH_INIT 1
1498 #define TOK_HASH_FUNC(h, c) ((h) * 263 + (c))
1500 /* find a token and add it if not found */
1501 static TokenSym
*tok_alloc(const char *str
, int len
)
1503 TokenSym
*ts
, **pts
;
1509 h
= TOK_HASH_FUNC(h
, ((unsigned char *)str
)[i
]);
1510 h
&= (TOK_HASH_SIZE
- 1);
1512 pts
= &hash_ident
[h
];
1517 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1519 pts
= &(ts
->hash_next
);
1521 return tok_alloc_new(pts
, str
, len
);
1524 /* CString handling */
1526 static void cstr_realloc(CString
*cstr
, int new_size
)
1531 size
= cstr
->size_allocated
;
1533 size
= 8; /* no need to allocate a too small first string */
1534 while (size
< new_size
)
1536 data
= tcc_realloc(cstr
->data_allocated
, size
);
1538 error("memory full");
1539 cstr
->data_allocated
= data
;
1540 cstr
->size_allocated
= size
;
1545 static inline void cstr_ccat(CString
*cstr
, int ch
)
1548 size
= cstr
->size
+ 1;
1549 if (size
> cstr
->size_allocated
)
1550 cstr_realloc(cstr
, size
);
1551 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1555 static void cstr_cat(CString
*cstr
, const char *str
)
1567 /* add a wide char */
1568 static void cstr_wccat(CString
*cstr
, int ch
)
1571 size
= cstr
->size
+ sizeof(nwchar_t
);
1572 if (size
> cstr
->size_allocated
)
1573 cstr_realloc(cstr
, size
);
1574 *(nwchar_t
*)(((unsigned char *)cstr
->data
) + size
- sizeof(nwchar_t
)) = ch
;
1578 static void cstr_new(CString
*cstr
)
1580 memset(cstr
, 0, sizeof(CString
));
1583 /* free string and reset it to NULL */
1584 static void cstr_free(CString
*cstr
)
1586 tcc_free(cstr
->data_allocated
);
1590 #define cstr_reset(cstr) cstr_free(cstr)
1592 /* XXX: unicode ? */
1593 static void add_char(CString
*cstr
, int c
)
1595 if (c
== '\'' || c
== '\"' || c
== '\\') {
1596 /* XXX: could be more precise if char or string */
1597 cstr_ccat(cstr
, '\\');
1599 if (c
>= 32 && c
<= 126) {
1602 cstr_ccat(cstr
, '\\');
1604 cstr_ccat(cstr
, 'n');
1606 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1607 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1608 cstr_ccat(cstr
, '0' + (c
& 7));
1613 /* XXX: buffer overflow */
1614 /* XXX: float tokens */
1615 char *get_tok_str(int v
, CValue
*cv
)
1617 static char buf
[STRING_MAX_SIZE
+ 1];
1618 static CString cstr_buf
;
1624 /* NOTE: to go faster, we give a fixed buffer for small strings */
1625 cstr_reset(&cstr_buf
);
1626 cstr_buf
.data
= buf
;
1627 cstr_buf
.size_allocated
= sizeof(buf
);
1633 /* XXX: not quite exact, but only useful for testing */
1634 sprintf(p
, "%u", cv
->ui
);
1638 /* XXX: not quite exact, but only useful for testing */
1639 sprintf(p
, "%Lu", cv
->ull
);
1643 cstr_ccat(&cstr_buf
, '\'');
1644 add_char(&cstr_buf
, cv
->i
);
1645 cstr_ccat(&cstr_buf
, '\'');
1646 cstr_ccat(&cstr_buf
, '\0');
1650 len
= cstr
->size
- 1;
1652 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1653 cstr_ccat(&cstr_buf
, '\0');
1658 cstr_ccat(&cstr_buf
, '\"');
1660 len
= cstr
->size
- 1;
1662 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1664 len
= (cstr
->size
/ sizeof(nwchar_t
)) - 1;
1666 add_char(&cstr_buf
, ((nwchar_t
*)cstr
->data
)[i
]);
1668 cstr_ccat(&cstr_buf
, '\"');
1669 cstr_ccat(&cstr_buf
, '\0');
1678 return strcpy(p
, "<<=");
1680 return strcpy(p
, ">>=");
1682 if (v
< TOK_IDENT
) {
1683 /* search in two bytes table */
1697 } else if (v
< tok_ident
) {
1698 return table_ident
[v
- TOK_IDENT
]->str
;
1699 } else if (v
>= SYM_FIRST_ANOM
) {
1700 /* special name for anonymous symbol */
1701 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1703 /* should never happen */
1708 return cstr_buf
.data
;
1711 /* push, without hashing */
1712 static Sym
*sym_push2(Sym
**ps
, int v
, int t
, int c
)
1726 /* find a symbol and return its associated structure. 's' is the top
1727 of the symbol stack */
1728 static Sym
*sym_find2(Sym
*s
, int v
)
1738 /* structure lookup */
1739 static inline Sym
*struct_find(int v
)
1742 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1744 return table_ident
[v
]->sym_struct
;
1747 /* find an identifier */
1748 static inline Sym
*sym_find(int v
)
1751 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
1753 return table_ident
[v
]->sym_identifier
;
1756 /* push a given symbol on the symbol stack */
1757 static Sym
*sym_push(int v
, CType
*type
, int r
, int c
)
1766 s
= sym_push2(ps
, v
, type
->t
, c
);
1767 s
->type
.ref
= type
->ref
;
1769 /* don't record fields or anonymous symbols */
1771 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1772 /* record symbol in token array */
1773 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1775 ps
= &ts
->sym_struct
;
1777 ps
= &ts
->sym_identifier
;
1784 /* push a global identifier */
1785 static Sym
*global_identifier_push(int v
, int t
, int c
)
1788 s
= sym_push2(&global_stack
, v
, t
, c
);
1789 /* don't record anonymous symbol */
1790 if (v
< SYM_FIRST_ANOM
) {
1791 ps
= &table_ident
[v
- TOK_IDENT
]->sym_identifier
;
1792 /* modify the top most local identifier, so that
1793 sym_identifier will point to 's' when popped */
1795 ps
= &(*ps
)->prev_tok
;
1802 /* pop symbols until top reaches 'b' */
1803 static void sym_pop(Sym
**ptop
, Sym
*b
)
1813 /* remove symbol in token array */
1815 if (!(v
& SYM_FIELD
) && (v
& ~SYM_STRUCT
) < SYM_FIRST_ANOM
) {
1816 ts
= table_ident
[(v
& ~SYM_STRUCT
) - TOK_IDENT
];
1818 ps
= &ts
->sym_struct
;
1820 ps
= &ts
->sym_identifier
;
1831 BufferedFile
*tcc_open(TCCState
*s1
, const char *filename
)
1836 fd
= open(filename
, O_RDONLY
| O_BINARY
);
1839 bf
= tcc_malloc(sizeof(BufferedFile
));
1845 bf
->buf_ptr
= bf
->buffer
;
1846 bf
->buf_end
= bf
->buffer
;
1847 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1848 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1850 bf
->ifndef_macro
= 0;
1851 bf
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
1852 // printf("opening '%s'\n", filename);
1856 void tcc_close(BufferedFile
*bf
)
1858 total_lines
+= bf
->line_num
;
1863 /* fill input buffer and peek next char */
1864 static int tcc_peekc_slow(BufferedFile
*bf
)
1867 /* only tries to read if really end of buffer */
1868 if (bf
->buf_ptr
>= bf
->buf_end
) {
1870 #if defined(PARSE_DEBUG)
1875 len
= read(bf
->fd
, bf
->buffer
, len
);
1882 bf
->buf_ptr
= bf
->buffer
;
1883 bf
->buf_end
= bf
->buffer
+ len
;
1884 *bf
->buf_end
= CH_EOB
;
1886 if (bf
->buf_ptr
< bf
->buf_end
) {
1887 return bf
->buf_ptr
[0];
1889 bf
->buf_ptr
= bf
->buf_end
;
1894 /* return the current character, handling end of block if necessary
1896 static int handle_eob(void)
1898 return tcc_peekc_slow(file
);
1901 /* read next char from current input file and handle end of input buffer */
1902 static inline void inp(void)
1904 ch
= *(++(file
->buf_ptr
));
1905 /* end of buffer/file handling */
1910 /* handle '\[\r]\n' */
1911 static void handle_stray(void)
1913 while (ch
== '\\') {
1918 } else if (ch
== '\r') {
1926 error("stray '\\' in program");
1931 /* skip the stray and handle the \\n case. Output an error if
1932 incorrect char after the stray */
1933 static int handle_stray1(uint8_t *p
)
1937 if (p
>= file
->buf_end
) {
1954 /* handle just the EOB case, but not stray */
1955 #define PEEKC_EOB(c, p)\
1966 /* handle the complicated stray case */
1967 #define PEEKC(c, p)\
1972 c = handle_stray1(p);\
1977 /* input with '\[\r]\n' handling. Note that this function cannot
1978 handle other characters after '\', so you cannot call it inside
1979 strings or comments */
1980 static void minp(void)
1988 /* single line C++ comments */
1989 static uint8_t *parse_line_comment(uint8_t *p
)
1997 if (c
== '\n' || c
== CH_EOF
) {
1999 } else if (c
== '\\') {
2008 } else if (c
== '\r') {
2026 static uint8_t *parse_comment(uint8_t *p
)
2032 /* fast skip loop */
2035 if (c
== '\n' || c
== '*' || c
== '\\')
2039 if (c
== '\n' || c
== '*' || c
== '\\')
2043 /* now we can handle all the cases */
2047 } else if (c
== '*') {
2053 } else if (c
== '/') {
2054 goto end_of_comment
;
2055 } else if (c
== '\\') {
2060 /* skip '\[\r]\n', otherwise just skip the stray */
2066 } else if (c
== '\r') {
2083 /* stray, eob or eof */
2088 error("unexpected end of file in comment");
2089 } else if (c
== '\\') {
2101 /* space exlcuding newline */
2102 static inline int is_space(int ch
)
2104 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
2107 static inline void skip_spaces(void)
2109 while (is_space(ch
))
2113 /* parse a string without interpreting escapes */
2114 static uint8_t *parse_pp_string(uint8_t *p
,
2115 int sep
, CString
*str
)
2123 } else if (c
== '\\') {
2128 unterminated_string
:
2129 /* XXX: indicate line number of start of string */
2130 error("missing terminating %c character", sep
);
2131 } else if (c
== '\\') {
2132 /* escape : just skip \[\r]\n */
2137 } else if (c
== '\r') {
2140 expect("'\n' after '\r'");
2143 } else if (c
== CH_EOF
) {
2144 goto unterminated_string
;
2147 cstr_ccat(str
, '\\');
2153 } else if (c
== '\n') {
2156 } else if (c
== '\r') {
2160 cstr_ccat(str
, '\r');
2176 /* skip block of text until #else, #elif or #endif. skip also pairs of
2178 void preprocess_skip(void)
2180 int a
, start_of_line
, c
;
2207 } else if (c
== '\\') {
2208 /* XXX: incorrect: should not give an error */
2209 ch
= file
->buf_ptr
[0];
2217 p
= parse_pp_string(p
, c
, NULL
);
2226 p
= parse_comment(p
);
2227 } else if (ch
== '/') {
2228 p
= parse_line_comment(p
);
2234 if (start_of_line
) {
2239 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
2241 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
2243 else if (tok
== TOK_ENDIF
)
2257 /* ParseState handling */
2259 /* XXX: currently, no include file info is stored. Thus, we cannot display
2260 accurate messages if the function or data definition spans multiple
2263 /* save current parse state in 's' */
2264 void save_parse_state(ParseState
*s
)
2266 s
->line_num
= file
->line_num
;
2267 s
->macro_ptr
= macro_ptr
;
2272 /* restore parse state from 's' */
2273 void restore_parse_state(ParseState
*s
)
2275 file
->line_num
= s
->line_num
;
2276 macro_ptr
= s
->macro_ptr
;
2281 /* return the number of additional 'ints' necessary to store the
2283 static inline int tok_ext_size(int t
)
2297 error("unsupported token");
2304 return LDOUBLE_SIZE
/ 4;
2310 /* token string handling */
2312 static inline void tok_str_new(TokenString
*s
)
2316 s
->allocated_len
= 0;
2317 s
->last_line_num
= -1;
2320 static void tok_str_free(int *str
)
2325 static int *tok_str_realloc(TokenString
*s
)
2329 if (s
->allocated_len
== 0) {
2332 len
= s
->allocated_len
* 2;
2334 str
= tcc_realloc(s
->str
, len
* sizeof(int));
2336 error("memory full");
2337 s
->allocated_len
= len
;
2342 static void tok_str_add(TokenString
*s
, int t
)
2348 if (len
>= s
->allocated_len
)
2349 str
= tok_str_realloc(s
);
2354 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
2361 /* allocate space for worst case */
2362 if (len
+ TOK_MAX_SIZE
> s
->allocated_len
)
2363 str
= tok_str_realloc(s
);
2372 str
[len
++] = cv
->tab
[0];
2381 nb_words
= (sizeof(CString
) + cv
->cstr
->size
+ 3) >> 2;
2382 while ((len
+ nb_words
) > s
->allocated_len
)
2383 str
= tok_str_realloc(s
);
2384 cstr
= (CString
*)(str
+ len
);
2386 cstr
->size
= cv
->cstr
->size
;
2387 cstr
->data_allocated
= NULL
;
2388 cstr
->size_allocated
= cstr
->size
;
2389 memcpy((char *)cstr
+ sizeof(CString
),
2390 cv
->cstr
->data
, cstr
->size
);
2397 #if LDOUBLE_SIZE == 8
2400 str
[len
++] = cv
->tab
[0];
2401 str
[len
++] = cv
->tab
[1];
2403 #if LDOUBLE_SIZE == 12
2405 str
[len
++] = cv
->tab
[0];
2406 str
[len
++] = cv
->tab
[1];
2407 str
[len
++] = cv
->tab
[2];
2408 #elif LDOUBLE_SIZE != 8
2409 #error add long double size support
2418 /* add the current parse token in token string 's' */
2419 static void tok_str_add_tok(TokenString
*s
)
2423 /* save line number info */
2424 if (file
->line_num
!= s
->last_line_num
) {
2425 s
->last_line_num
= file
->line_num
;
2426 cval
.i
= s
->last_line_num
;
2427 tok_str_add2(s
, TOK_LINENUM
, &cval
);
2429 tok_str_add2(s
, tok
, &tokc
);
2432 #if LDOUBLE_SIZE == 12
2433 #define LDOUBLE_GET(p, cv) \
2437 #elif LDOUBLE_SIZE == 8
2438 #define LDOUBLE_GET(p, cv) \
2442 #error add long double size support
2446 /* get a token from an integer array and increment pointer
2447 accordingly. we code it as a macro to avoid pointer aliasing. */
2448 #define TOK_GET(t, p, cv) \
2463 cv.cstr = (CString *)p; \
2464 cv.cstr->data = (char *)p + sizeof(CString);\
2465 p += (sizeof(CString) + cv.cstr->size + 3) >> 2;\
2474 case TOK_CLDOUBLE: \
2475 LDOUBLE_GET(p, cv); \
2476 p += LDOUBLE_SIZE / 4; \
2483 /* defines handling */
2484 static inline void define_push(int v
, int macro_type
, int *str
, Sym
*first_arg
)
2488 s
= sym_push2(&define_stack
, v
, macro_type
, (int)str
);
2489 s
->next
= first_arg
;
2490 table_ident
[v
- TOK_IDENT
]->sym_define
= s
;
2493 /* undefined a define symbol. Its name is just set to zero */
2494 static void define_undef(Sym
*s
)
2498 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2499 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2503 static inline Sym
*define_find(int v
)
2506 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2508 return table_ident
[v
]->sym_define
;
2511 /* free define stack until top reaches 'b' */
2512 static void free_defines(Sym
*b
)
2520 /* do not free args or predefined defines */
2522 tok_str_free((int *)top
->c
);
2524 if (v
>= TOK_IDENT
&& v
< tok_ident
)
2525 table_ident
[v
- TOK_IDENT
]->sym_define
= NULL
;
2533 static Sym
*label_find(int v
)
2536 if ((unsigned)v
>= (unsigned)(tok_ident
- TOK_IDENT
))
2538 return table_ident
[v
]->sym_label
;
2541 static Sym
*label_push(Sym
**ptop
, int v
, int flags
)
2544 s
= sym_push2(ptop
, v
, 0, 0);
2546 ps
= &table_ident
[v
- TOK_IDENT
]->sym_label
;
2547 if (ptop
== &global_label_stack
) {
2548 /* modify the top most local identifier, so that
2549 sym_identifier will point to 's' when popped */
2551 ps
= &(*ps
)->prev_tok
;
2558 /* pop labels until element last is reached. Look if any labels are
2559 undefined. Define symbols if '&&label' was used. */
2560 static void label_pop(Sym
**ptop
, Sym
*slast
)
2563 for(s
= *ptop
; s
!= slast
; s
= s1
) {
2565 if (s
->r
== LABEL_DECLARED
) {
2566 warning("label '%s' declared but not used", get_tok_str(s
->v
, NULL
));
2567 } else if (s
->r
== LABEL_FORWARD
) {
2568 error("label '%s' used but not defined",
2569 get_tok_str(s
->v
, NULL
));
2572 /* define corresponding symbol. A size of
2574 put_extern_sym(s
, cur_text_section
, (long)s
->next
, 1);
2578 table_ident
[s
->v
- TOK_IDENT
]->sym_label
= s
->prev_tok
;
2584 /* eval an expression for #if/#elif */
2585 static int expr_preprocess(void)
2591 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2592 next(); /* do macro subst */
2593 if (tok
== TOK_DEFINED
) {
2598 c
= define_find(tok
) != 0;
2603 } else if (tok
>= TOK_IDENT
) {
2604 /* if undefined macro */
2608 tok_str_add_tok(&str
);
2610 tok_str_add(&str
, -1); /* simulate end of file */
2611 tok_str_add(&str
, 0);
2612 /* now evaluate C constant expression */
2613 macro_ptr
= str
.str
;
2617 tok_str_free(str
.str
);
2621 #if defined(PARSE_DEBUG) || defined(PP_DEBUG)
2622 static void tok_print(int *str
)
2628 TOK_GET(t
, str
, cval
);
2631 printf(" %s", get_tok_str(t
, &cval
));
2637 /* parse after #define */
2638 static void parse_define(void)
2640 Sym
*s
, *first
, **ps
;
2641 int v
, t
, varg
, is_vaargs
, c
;
2646 error("invalid macro name '%s'", get_tok_str(tok
, &tokc
));
2647 /* XXX: should check if same macro (ANSI) */
2650 /* '(' must be just after macro definition for MACRO_FUNC */
2651 c
= file
->buf_ptr
[0];
2653 c
= handle_stray1(file
->buf_ptr
);
2658 while (tok
!= ')') {
2662 if (varg
== TOK_DOTS
) {
2663 varg
= TOK___VA_ARGS__
;
2665 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
2669 if (varg
< TOK_IDENT
)
2670 error("badly punctuated parameter list");
2671 s
= sym_push2(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
2682 /* EOF testing necessary for '-D' handling */
2683 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
2684 tok_str_add2(&str
, tok
, &tokc
);
2687 tok_str_add(&str
, 0);
2689 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
2692 define_push(v
, t
, str
.str
, first
);
2695 static inline int hash_cached_include(int type
, const char *filename
)
2697 const unsigned char *s
;
2701 h
= TOK_HASH_FUNC(h
, type
);
2704 h
= TOK_HASH_FUNC(h
, *s
);
2707 h
&= (CACHED_INCLUDES_HASH_SIZE
- 1);
2711 /* XXX: use a token or a hash table to accelerate matching ? */
2712 static CachedInclude
*search_cached_include(TCCState
*s1
,
2713 int type
, const char *filename
)
2717 h
= hash_cached_include(type
, filename
);
2718 i
= s1
->cached_includes_hash
[h
];
2722 e
= s1
->cached_includes
[i
- 1];
2723 if (e
->type
== type
&& !strcmp(e
->filename
, filename
))
2730 static inline void add_cached_include(TCCState
*s1
, int type
,
2731 const char *filename
, int ifndef_macro
)
2736 if (search_cached_include(s1
, type
, filename
))
2739 printf("adding cached '%s' %s\n", filename
, get_tok_str(ifndef_macro
, NULL
));
2741 e
= tcc_malloc(sizeof(CachedInclude
) + strlen(filename
));
2745 strcpy(e
->filename
, filename
);
2746 e
->ifndef_macro
= ifndef_macro
;
2747 dynarray_add((void ***)&s1
->cached_includes
, &s1
->nb_cached_includes
, e
);
2748 /* add in hash table */
2749 h
= hash_cached_include(type
, filename
);
2750 e
->hash_next
= s1
->cached_includes_hash
[h
];
2751 s1
->cached_includes_hash
[h
] = s1
->nb_cached_includes
;
2754 static void pragma_parse(TCCState
*s1
)
2759 if (tok
== TOK_pack
) {
2762 #pragma pack(1) // set
2763 #pragma pack() // reset to default
2764 #pragma pack(push,1) // push & set
2765 #pragma pack(pop) // restore previous
2769 if (tok
== TOK_ASM_pop
) {
2771 if (s1
->pack_stack_ptr
<= s1
->pack_stack
) {
2773 error("out of pack stack");
2775 s1
->pack_stack_ptr
--;
2779 if (tok
== TOK_ASM_push
) {
2781 if (s1
->pack_stack_ptr
>= s1
->pack_stack
+ PACK_STACK_SIZE
- 1)
2783 s1
->pack_stack_ptr
++;
2786 if (tok
!= TOK_CINT
) {
2788 error("invalid pack pragma");
2791 if (val
< 1 || val
> 16 || (val
& (val
- 1)) != 0)
2795 *s1
->pack_stack_ptr
= val
;
2801 /* is_bof is true if first non space token at beginning of file */
2802 static void preprocess(int is_bof
)
2804 TCCState
*s1
= tcc_state
;
2805 int size
, i
, c
, n
, saved_parse_flags
;
2806 char buf
[1024], *q
, *p
;
2812 saved_parse_flags
= parse_flags
;
2813 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
|
2814 PARSE_FLAG_LINEFEED
;
2824 s
= define_find(tok
);
2825 /* undefine symbol by putting an invalid name */
2830 case TOK_INCLUDE_NEXT
:
2831 ch
= file
->buf_ptr
[0];
2832 /* XXX: incorrect if comments : use next_nomacro with a special mode */
2837 } else if (ch
== '\"') {
2840 /* XXX: better stray handling */
2843 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
2844 if ((q
- buf
) < sizeof(buf
) - 1)
2851 /* eat all spaces and comments after include */
2852 /* XXX: slightly incorrect */
2853 while (ch1
!= '\n' && ch1
!= CH_EOF
)
2857 /* computed #include : either we have only strings or
2858 we have anything enclosed in '<>' */
2861 if (tok
== TOK_STR
) {
2862 while (tok
!= TOK_LINEFEED
) {
2863 if (tok
!= TOK_STR
) {
2865 error("'#include' expects \"FILENAME\" or <FILENAME>");
2867 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
2873 while (tok
!= TOK_LINEFEED
) {
2874 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
2878 /* check syntax and remove '<>' */
2879 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
2880 goto include_syntax
;
2881 memmove(buf
, buf
+ 1, len
- 2);
2882 buf
[len
- 2] = '\0';
2887 e
= search_cached_include(s1
, c
, buf
);
2888 if (e
&& define_find(e
->ifndef_macro
)) {
2889 /* no need to parse the include because the 'ifndef macro'
2892 printf("%s: skipping %s\n", file
->filename
, buf
);
2896 /* first search in current dir if "header.h" */
2898 p
= strrchr(file
->filename
, '/');
2900 size
= p
+ 1 - file
->filename
;
2901 if (size
> sizeof(buf1
) - 1)
2902 size
= sizeof(buf1
) - 1;
2903 memcpy(buf1
, file
->filename
, size
);
2905 pstrcat(buf1
, sizeof(buf1
), buf
);
2906 f
= tcc_open(s1
, buf1
);
2908 if (tok
== TOK_INCLUDE_NEXT
)
2914 if (s1
->include_stack_ptr
>= s1
->include_stack
+ INCLUDE_STACK_SIZE
)
2915 error("#include recursion too deep");
2916 /* now search in all the include paths */
2917 n
= s1
->nb_include_paths
+ s1
->nb_sysinclude_paths
;
2918 for(i
= 0; i
< n
; i
++) {
2920 if (i
< s1
->nb_include_paths
)
2921 path
= s1
->include_paths
[i
];
2923 path
= s1
->sysinclude_paths
[i
- s1
->nb_include_paths
];
2924 pstrcpy(buf1
, sizeof(buf1
), path
);
2925 pstrcat(buf1
, sizeof(buf1
), "/");
2926 pstrcat(buf1
, sizeof(buf1
), buf
);
2927 f
= tcc_open(s1
, buf1
);
2929 if (tok
== TOK_INCLUDE_NEXT
)
2935 error("include file '%s' not found", buf
);
2939 printf("%s: including %s\n", file
->filename
, buf1
);
2942 pstrcpy(f
->inc_filename
, sizeof(f
->inc_filename
), buf
);
2943 /* push current file in stack */
2944 /* XXX: fix current line init */
2945 *s1
->include_stack_ptr
++ = file
;
2947 /* add include file debug info */
2949 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
2951 tok_flags
|= TOK_FLAG_BOF
| TOK_FLAG_BOL
;
2952 ch
= file
->buf_ptr
[0];
2960 c
= expr_preprocess();
2966 if (tok
< TOK_IDENT
)
2967 error("invalid argument for '#if%sdef'", c
? "n" : "");
2971 printf("#ifndef %s\n", get_tok_str(tok
, NULL
));
2973 file
->ifndef_macro
= tok
;
2976 c
= (define_find(tok
) != 0) ^ c
;
2978 if (s1
->ifdef_stack_ptr
>= s1
->ifdef_stack
+ IFDEF_STACK_SIZE
)
2979 error("memory full");
2980 *s1
->ifdef_stack_ptr
++ = c
;
2983 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2984 error("#else without matching #if");
2985 if (s1
->ifdef_stack_ptr
[-1] & 2)
2986 error("#else after #else");
2987 c
= (s1
->ifdef_stack_ptr
[-1] ^= 3);
2990 if (s1
->ifdef_stack_ptr
== s1
->ifdef_stack
)
2991 error("#elif without matching #if");
2992 c
= s1
->ifdef_stack_ptr
[-1];
2994 error("#elif after #else");
2995 /* last #if/#elif expression was true: we skip */
2998 c
= expr_preprocess();
2999 s1
->ifdef_stack_ptr
[-1] = c
;
3009 if (s1
->ifdef_stack_ptr
<= file
->ifdef_stack_ptr
)
3010 error("#endif without matching #if");
3011 s1
->ifdef_stack_ptr
--;
3012 /* '#ifndef macro' was at the start of file. Now we check if
3013 an '#endif' is exactly at the end of file */
3014 if (file
->ifndef_macro
&&
3015 s1
->ifdef_stack_ptr
== file
->ifdef_stack_ptr
) {
3016 file
->ifndef_macro_saved
= file
->ifndef_macro
;
3017 /* need to set to zero to avoid false matches if another
3018 #ifndef at middle of file */
3019 file
->ifndef_macro
= 0;
3020 while (tok
!= TOK_LINEFEED
)
3022 tok_flags
|= TOK_FLAG_ENDIF
;
3028 if (tok
!= TOK_CINT
)
3030 file
->line_num
= tokc
.i
- 1; /* the line number will be incremented after */
3032 if (tok
!= TOK_LINEFEED
) {
3035 pstrcpy(file
->filename
, sizeof(file
->filename
),
3036 (char *)tokc
.cstr
->data
);
3042 ch
= file
->buf_ptr
[0];
3045 while (ch
!= '\n' && ch
!= CH_EOF
) {
3046 if ((q
- buf
) < sizeof(buf
) - 1)
3052 error("#error %s", buf
);
3054 warning("#warning %s", buf
);
3060 if (tok
== TOK_LINEFEED
|| tok
== '!' || tok
== TOK_CINT
) {
3061 /* '!' is ignored to allow C scripts. numbers are ignored
3062 to emulate cpp behaviour */
3064 if (!(saved_parse_flags
& PARSE_FLAG_ASM_COMMENTS
))
3065 error("invalid preprocessing directive #%s", get_tok_str(tok
, &tokc
));
3069 /* ignore other preprocess commands or #! for C scripts */
3070 while (tok
!= TOK_LINEFEED
)
3073 parse_flags
= saved_parse_flags
;
3076 /* evaluate escape codes in a string. */
3077 static void parse_escape_string(CString
*outstr
, const uint8_t *buf
, int is_long
)
3092 case '0': case '1': case '2': case '3':
3093 case '4': case '5': case '6': case '7':
3094 /* at most three octal digits */
3099 n
= n
* 8 + c
- '0';
3103 n
= n
* 8 + c
- '0';
3108 goto add_char_nonext
;
3114 if (c
>= 'a' && c
<= 'f')
3116 else if (c
>= 'A' && c
<= 'F')
3126 goto add_char_nonext
;
3150 goto invalid_escape
;
3160 if (c
>= '!' && c
<= '~')
3161 warning("unknown escape sequence: \'\\%c\'", c
);
3163 warning("unknown escape sequence: \'\\x%x\'", c
);
3170 cstr_ccat(outstr
, c
);
3172 cstr_wccat(outstr
, c
);
3174 /* add a trailing '\0' */
3176 cstr_ccat(outstr
, '\0');
3178 cstr_wccat(outstr
, '\0');
3181 /* we use 64 bit numbers */
3184 /* bn = (bn << shift) | or_val */
3185 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
3189 for(i
=0;i
<BN_SIZE
;i
++) {
3191 bn
[i
] = (v
<< shift
) | or_val
;
3192 or_val
= v
>> (32 - shift
);
3196 void bn_zero(unsigned int *bn
)
3199 for(i
=0;i
<BN_SIZE
;i
++) {
3204 /* parse number in null terminated string 'p' and return it in the
3206 void parse_number(const char *p
)
3208 int b
, t
, shift
, frac_bits
, s
, exp_val
, ch
;
3210 unsigned int bn
[BN_SIZE
];
3221 goto float_frac_parse
;
3222 } else if (t
== '0') {
3223 if (ch
== 'x' || ch
== 'X') {
3227 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
3233 /* parse all digits. cannot check octal numbers at this stage
3234 because of floating point constants */
3236 if (ch
>= 'a' && ch
<= 'f')
3238 else if (ch
>= 'A' && ch
<= 'F')
3246 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
3248 error("number too long");
3254 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
3255 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
3257 /* NOTE: strtox should support that for hexa numbers, but
3258 non ISOC99 libcs do not support it, so we prefer to do
3260 /* hexadecimal or binary floats */
3261 /* XXX: handle overflows */
3273 } else if (t
>= 'a') {
3275 } else if (t
>= 'A') {
3280 bn_lshift(bn
, shift
, t
);
3287 if (t
>= 'a' && t
<= 'f') {
3289 } else if (t
>= 'A' && t
<= 'F') {
3291 } else if (t
>= '0' && t
<= '9') {
3297 error("invalid digit");
3298 bn_lshift(bn
, shift
, t
);
3303 if (ch
!= 'p' && ch
!= 'P')
3310 } else if (ch
== '-') {
3314 if (ch
< '0' || ch
> '9')
3315 expect("exponent digits");
3316 while (ch
>= '0' && ch
<= '9') {
3317 exp_val
= exp_val
* 10 + ch
- '0';
3320 exp_val
= exp_val
* s
;
3322 /* now we can generate the number */
3323 /* XXX: should patch directly float number */
3324 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
3325 d
= ldexp(d
, exp_val
- frac_bits
);
3330 /* float : should handle overflow */
3332 } else if (t
== 'L') {
3335 /* XXX: not large enough */
3336 tokc
.ld
= (long double)d
;
3342 /* decimal floats */
3344 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3349 while (ch
>= '0' && ch
<= '9') {
3350 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3356 if (ch
== 'e' || ch
== 'E') {
3357 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3361 if (ch
== '-' || ch
== '+') {
3362 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3367 if (ch
< '0' || ch
> '9')
3368 expect("exponent digits");
3369 while (ch
>= '0' && ch
<= '9') {
3370 if (q
>= token_buf
+ STRING_MAX_SIZE
)
3382 tokc
.f
= strtof(token_buf
, NULL
);
3383 } else if (t
== 'L') {
3386 tokc
.ld
= strtold(token_buf
, NULL
);
3389 tokc
.d
= strtod(token_buf
, NULL
);
3393 unsigned long long n
, n1
;
3396 /* integer number */
3399 if (b
== 10 && *q
== '0') {
3406 /* no need for checks except for base 10 / 8 errors */
3409 } else if (t
>= 'a') {
3411 } else if (t
>= 'A') {
3416 error("invalid digit");
3420 /* detect overflow */
3421 /* XXX: this test is not reliable */
3423 error("integer constant overflow");
3426 /* XXX: not exactly ANSI compliant */
3427 if ((n
& 0xffffffff00000000LL
) != 0) {
3432 } else if (n
> 0x7fffffff) {
3443 error("three 'l's in integer constant");
3446 if (tok
== TOK_CINT
)
3448 else if (tok
== TOK_CUINT
)
3452 } else if (t
== 'U') {
3454 error("two 'u's in integer constant");
3456 if (tok
== TOK_CINT
)
3458 else if (tok
== TOK_CLLONG
)
3465 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
3473 #define PARSE2(c1, tok1, c2, tok2) \
3484 /* return next token without macro substitution */
3485 static inline void next_nomacro1(void)
3505 /* first look if it is in fact an end of buffer */
3506 if (p
>= file
->buf_end
) {
3510 if (p
>= file
->buf_end
)
3523 TCCState
*s1
= tcc_state
;
3524 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3526 } else if (s1
->include_stack_ptr
== s1
->include_stack
||
3527 !(parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3528 /* no include left : end of file. */
3531 /* pop include file */
3533 /* test if previous '#endif' was after a #ifdef at
3535 if (tok_flags
& TOK_FLAG_ENDIF
) {
3537 printf("#endif %s\n", get_tok_str(file
->ifndef_macro_saved
, NULL
));
3539 add_cached_include(s1
, file
->inc_type
, file
->inc_filename
,
3540 file
->ifndef_macro_saved
);
3543 /* add end of include file debug info */
3545 put_stabd(N_EINCL
, 0, 0);
3547 /* pop include stack */
3549 s1
->include_stack_ptr
--;
3550 file
= *s1
->include_stack_ptr
;
3558 if (parse_flags
& PARSE_FLAG_LINEFEED
) {
3562 tok_flags
|= TOK_FLAG_BOL
;
3571 if ((tok_flags
& TOK_FLAG_BOL
) &&
3572 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
3574 preprocess(tok_flags
& TOK_FLAG_BOF
);
3580 tok
= TOK_TWOSHARPS
;
3582 if (parse_flags
& PARSE_FLAG_ASM_COMMENTS
) {
3583 p
= parse_line_comment(p
- 1);
3592 case 'a': case 'b': case 'c': case 'd':
3593 case 'e': case 'f': case 'g': case 'h':
3594 case 'i': case 'j': case 'k': case 'l':
3595 case 'm': case 'n': case 'o': case 'p':
3596 case 'q': case 'r': case 's': case 't':
3597 case 'u': case 'v': case 'w': case 'x':
3599 case 'A': case 'B': case 'C': case 'D':
3600 case 'E': case 'F': case 'G': case 'H':
3601 case 'I': case 'J': case 'K':
3602 case 'M': case 'N': case 'O': case 'P':
3603 case 'Q': case 'R': case 'S': case 'T':
3604 case 'U': case 'V': case 'W': case 'X':
3610 h
= TOK_HASH_FUNC(h
, c
);
3614 if (!isidnum_table
[c
])
3616 h
= TOK_HASH_FUNC(h
, c
);
3623 /* fast case : no stray found, so we have the full token
3624 and we have already hashed it */
3626 h
&= (TOK_HASH_SIZE
- 1);
3627 pts
= &hash_ident
[h
];
3632 if (ts
->len
== len
&& !memcmp(ts
->str
, p1
, len
))
3634 pts
= &(ts
->hash_next
);
3636 ts
= tok_alloc_new(pts
, p1
, len
);
3640 cstr_reset(&tokcstr
);
3643 cstr_ccat(&tokcstr
, *p1
);
3649 while (isidnum_table
[c
]) {
3650 cstr_ccat(&tokcstr
, c
);
3653 ts
= tok_alloc(tokcstr
.data
, tokcstr
.size
);
3659 if (t
!= '\\' && t
!= '\'' && t
!= '\"') {
3661 goto parse_ident_fast
;
3664 if (c
== '\'' || c
== '\"') {
3668 cstr_reset(&tokcstr
);
3669 cstr_ccat(&tokcstr
, 'L');
3670 goto parse_ident_slow
;
3674 case '0': case '1': case '2': case '3':
3675 case '4': case '5': case '6': case '7':
3678 cstr_reset(&tokcstr
);
3679 /* after the first digit, accept digits, alpha, '.' or sign if
3680 prefixed by 'eEpP' */
3684 cstr_ccat(&tokcstr
, c
);
3686 if (!(isnum(c
) || isid(c
) || c
== '.' ||
3687 ((c
== '+' || c
== '-') &&
3688 (t
== 'e' || t
== 'E' || t
== 'p' || t
== 'P'))))
3691 /* We add a trailing '\0' to ease parsing */
3692 cstr_ccat(&tokcstr
, '\0');
3693 tokc
.cstr
= &tokcstr
;
3697 /* special dot handling because it can also start a number */
3700 cstr_reset(&tokcstr
);
3701 cstr_ccat(&tokcstr
, '.');
3703 } else if (c
== '.') {
3723 /* parse the string */
3725 p
= parse_pp_string(p
, sep
, &str
);
3726 cstr_ccat(&str
, '\0');
3728 /* eval the escape (should be done as TOK_PPNUM) */
3729 cstr_reset(&tokcstr
);
3730 parse_escape_string(&tokcstr
, str
.data
, is_long
);
3735 /* XXX: make it portable */
3739 char_size
= sizeof(nwchar_t
);
3740 if (tokcstr
.size
<= char_size
)
3741 error("empty character constant");
3742 if (tokcstr
.size
> 2 * char_size
)
3743 warning("multi-character character constant");
3745 tokc
.i
= *(int8_t *)tokcstr
.data
;
3748 tokc
.i
= *(nwchar_t
*)tokcstr
.data
;
3752 tokc
.cstr
= &tokcstr
;
3766 } else if (c
== '<') {
3784 } else if (c
== '>') {
3802 } else if (c
== '=') {
3815 } else if (c
== '=') {
3828 } else if (c
== '=') {
3841 } else if (c
== '=') {
3844 } else if (c
== '>') {
3852 PARSE2('!', '!', '=', TOK_NE
)
3853 PARSE2('=', '=', '=', TOK_EQ
)
3854 PARSE2('*', '*', '=', TOK_A_MUL
)
3855 PARSE2('%', '%', '=', TOK_A_MOD
)
3856 PARSE2('^', '^', '=', TOK_A_XOR
)
3858 /* comments or operator */
3862 p
= parse_comment(p
);
3864 } else if (c
== '/') {
3865 p
= parse_line_comment(p
);
3867 } else if (c
== '=') {
3887 case '$': /* only used in assembler */
3888 case '@': /* dito */
3893 error("unrecognized character \\x%02x", c
);
3898 #if defined(PARSE_DEBUG)
3899 printf("token = %s\n", get_tok_str(tok
, &tokc
));
3903 /* return next token without macro substitution. Can read input from
3905 static void next_nomacro(void)
3911 TOK_GET(tok
, macro_ptr
, tokc
);
3912 if (tok
== TOK_LINENUM
) {
3913 file
->line_num
= tokc
.i
;
3922 /* substitute args in macro_str and return allocated string */
3923 static int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
3925 int *st
, last_tok
, t
, notfirst
;
3934 TOK_GET(t
, macro_str
, cval
);
3939 TOK_GET(t
, macro_str
, cval
);
3942 s
= sym_find2(args
, t
);
3949 cstr_ccat(&cstr
, ' ');
3950 TOK_GET(t
, st
, cval
);
3951 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
3954 cstr_ccat(&cstr
, '\0');
3956 printf("stringize: %s\n", (char *)cstr
.data
);
3960 tok_str_add2(&str
, TOK_STR
, &cval
);
3963 tok_str_add2(&str
, t
, &cval
);
3965 } else if (t
>= TOK_IDENT
) {
3966 s
= sym_find2(args
, t
);
3969 /* if '##' is present before or after, no arg substitution */
3970 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
3971 /* special case for var arg macros : ## eats the
3972 ',' if empty VA_ARGS variable. */
3973 /* XXX: test of the ',' is not 100%
3974 reliable. should fix it to avoid security
3976 if (gnu_ext
&& s
->type
.t
&&
3977 last_tok
== TOK_TWOSHARPS
&&
3978 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
3980 /* suppress ',' '##' */
3983 /* suppress '##' and add variable */
3991 TOK_GET(t1
, st
, cval
);
3994 tok_str_add2(&str
, t1
, &cval
);
3998 /* NOTE: the stream cannot be read when macro
3999 substituing an argument */
4000 macro_subst(&str
, nested_list
, st
, NULL
);
4003 tok_str_add(&str
, t
);
4006 tok_str_add2(&str
, t
, &cval
);
4010 tok_str_add(&str
, 0);
4014 static char const ab_month_name
[12][4] =
4016 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
4017 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
4020 /* do macro substitution of current token with macro 's' and add
4021 result to (tok_str,tok_len). 'nested_list' is the list of all
4022 macros we got inside to avoid recursing. Return non zero if no
4023 substitution needs to be done */
4024 static int macro_subst_tok(TokenString
*tok_str
,
4025 Sym
**nested_list
, Sym
*s
, struct macro_level
**can_read_stream
)
4027 Sym
*args
, *sa
, *sa1
;
4028 int mstr_allocated
, parlevel
, *mstr
, t
, t1
;
4035 /* if symbol is a macro, prepare substitution */
4036 /* special macros */
4037 if (tok
== TOK___LINE__
) {
4038 snprintf(buf
, sizeof(buf
), "%d", file
->line_num
);
4042 } else if (tok
== TOK___FILE__
) {
4043 cstrval
= file
->filename
;
4045 } else if (tok
== TOK___DATE__
|| tok
== TOK___TIME__
) {
4050 tm
= localtime(&ti
);
4051 if (tok
== TOK___DATE__
) {
4052 snprintf(buf
, sizeof(buf
), "%s %2d %d",
4053 ab_month_name
[tm
->tm_mon
], tm
->tm_mday
, tm
->tm_year
+ 1900);
4055 snprintf(buf
, sizeof(buf
), "%02d:%02d:%02d",
4056 tm
->tm_hour
, tm
->tm_min
, tm
->tm_sec
);
4063 cstr_cat(&cstr
, cstrval
);
4064 cstr_ccat(&cstr
, '\0');
4066 tok_str_add2(tok_str
, t1
, &cval
);
4071 if (s
->type
.t
== MACRO_FUNC
) {
4072 /* NOTE: we do not use next_nomacro to avoid eating the
4073 next token. XXX: find better solution */
4077 if (t
== 0 && can_read_stream
) {
4078 /* end of macro stream: we must look at the token
4079 after in the file */
4080 struct macro_level
*ml
= *can_read_stream
;
4086 *can_read_stream
= ml
-> prev
;
4091 /* XXX: incorrect with comments */
4092 ch
= file
->buf_ptr
[0];
4093 while (is_space(ch
) || ch
== '\n')
4097 if (t
!= '(') /* no macro subst */
4100 /* argument macro */
4105 /* NOTE: empty args are allowed, except if no args */
4107 /* handle '()' case */
4108 if (!args
&& !sa
&& tok
== ')')
4111 error("macro '%s' used with too many args",
4112 get_tok_str(s
->v
, 0));
4115 /* NOTE: non zero sa->t indicates VA_ARGS */
4116 while ((parlevel
> 0 ||
4118 (tok
!= ',' || sa
->type
.t
))) &&
4122 else if (tok
== ')')
4124 tok_str_add2(&str
, tok
, &tokc
);
4127 tok_str_add(&str
, 0);
4128 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->type
.t
, (int)str
.str
);
4131 /* special case for gcc var args: add an empty
4132 var arg argument if it is omitted */
4133 if (sa
&& sa
->type
.t
&& gnu_ext
)
4143 error("macro '%s' used with too few args",
4144 get_tok_str(s
->v
, 0));
4147 /* now subst each arg */
4148 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
4153 tok_str_free((int *)sa
->c
);
4159 sym_push2(nested_list
, s
->v
, 0, 0);
4160 macro_subst(tok_str
, nested_list
, mstr
, can_read_stream
);
4161 /* pop nested defined symbol */
4163 *nested_list
= sa1
->prev
;
4171 /* handle the '##' operator. Return NULL if no '##' seen. Otherwise
4172 return the resulting string (which must be freed). */
4173 static inline int *macro_twosharps(const int *macro_str
)
4176 const int *macro_ptr1
, *start_macro_ptr
, *ptr
, *saved_macro_ptr
;
4178 const char *p1
, *p2
;
4180 TokenString macro_str1
;
4183 start_macro_ptr
= macro_str
;
4184 /* we search the first '##' */
4186 macro_ptr1
= macro_str
;
4187 TOK_GET(t
, macro_str
, cval
);
4188 /* nothing more to do if end of string */
4191 if (*macro_str
== TOK_TWOSHARPS
)
4195 /* we saw '##', so we need more processing to handle it */
4197 tok_str_new(¯o_str1
);
4201 /* add all tokens seen so far */
4202 for(ptr
= start_macro_ptr
; ptr
< macro_ptr1
;) {
4203 TOK_GET(t
, ptr
, cval
);
4204 tok_str_add2(¯o_str1
, t
, &cval
);
4206 saved_macro_ptr
= macro_ptr
;
4207 /* XXX: get rid of the use of macro_ptr here */
4208 macro_ptr
= (int *)macro_str
;
4210 while (*macro_ptr
== TOK_TWOSHARPS
) {
4212 macro_ptr1
= macro_ptr
;
4215 TOK_GET(t
, macro_ptr
, cval
);
4216 /* We concatenate the two tokens if we have an
4217 identifier or a preprocessing number */
4219 p1
= get_tok_str(tok
, &tokc
);
4220 cstr_cat(&cstr
, p1
);
4221 p2
= get_tok_str(t
, &cval
);
4222 cstr_cat(&cstr
, p2
);
4223 cstr_ccat(&cstr
, '\0');
4225 if ((tok
>= TOK_IDENT
|| tok
== TOK_PPNUM
) &&
4226 (t
>= TOK_IDENT
|| t
== TOK_PPNUM
)) {
4227 if (tok
== TOK_PPNUM
) {
4228 /* if number, then create a number token */
4229 /* NOTE: no need to allocate because
4230 tok_str_add2() does it */
4233 /* if identifier, we must do a test to
4234 validate we have a correct identifier */
4235 if (t
== TOK_PPNUM
) {
4245 if (!isnum(c
) && !isid(c
))
4249 ts
= tok_alloc(cstr
.data
, strlen(cstr
.data
));
4250 tok
= ts
->tok
; /* modify current token */
4253 const char *str
= cstr
.data
;
4254 const unsigned char *q
;
4256 /* we look for a valid token */
4257 /* XXX: do more extensive checks */
4258 if (!strcmp(str
, ">>=")) {
4260 } else if (!strcmp(str
, "<<=")) {
4262 } else if (strlen(str
) == 2) {
4263 /* search in two bytes table */
4268 if (q
[0] == str
[0] && q
[1] == str
[1])
4275 /* NOTE: because get_tok_str use a static buffer,
4278 p1
= get_tok_str(tok
, &tokc
);
4279 cstr_cat(&cstr
, p1
);
4280 cstr_ccat(&cstr
, '\0');
4281 p2
= get_tok_str(t
, &cval
);
4282 warning("pasting \"%s\" and \"%s\" does not give a valid preprocessing token", cstr
.data
, p2
);
4283 /* cannot merge tokens: just add them separately */
4284 tok_str_add2(¯o_str1
, tok
, &tokc
);
4285 /* XXX: free associated memory ? */
4292 tok_str_add2(¯o_str1
, tok
, &tokc
);
4297 macro_ptr
= (int *)saved_macro_ptr
;
4299 tok_str_add(¯o_str1
, 0);
4300 return macro_str1
.str
;
4304 /* do macro substitution of macro_str and add result to
4305 (tok_str,tok_len). 'nested_list' is the list of all macros we got
4306 inside to avoid recursing. */
4307 static void macro_subst(TokenString
*tok_str
, Sym
**nested_list
,
4308 const int *macro_str
, struct macro_level
** can_read_stream
)
4315 struct macro_level ml
;
4317 /* first scan for '##' operator handling */
4319 macro_str1
= macro_twosharps(ptr
);
4323 /* NOTE: ptr == NULL can only happen if tokens are read from
4324 file stream due to a macro function call */
4327 TOK_GET(t
, ptr
, cval
);
4332 /* if nested substitution, do nothing */
4333 if (sym_find2(*nested_list
, t
))
4336 if (can_read_stream
)
4337 ml
.prev
= *can_read_stream
, *can_read_stream
= &ml
;
4338 macro_ptr
= (int *)ptr
;
4340 ret
= macro_subst_tok(tok_str
, nested_list
, s
, can_read_stream
);
4341 ptr
= (int *)macro_ptr
;
4343 if (can_read_stream
&& *can_read_stream
== &ml
)
4344 *can_read_stream
= ml
.prev
;
4349 tok_str_add2(tok_str
, t
, &cval
);
4353 tok_str_free(macro_str1
);
4356 /* return next token with macro substitution */
4357 static void next(void)
4359 Sym
*nested_list
, *s
;
4361 struct macro_level
*ml
;
4366 /* if not reading from macro substituted string, then try
4367 to substitute macros */
4368 if (tok
>= TOK_IDENT
&&
4369 (parse_flags
& PARSE_FLAG_PREPROCESS
)) {
4370 s
= define_find(tok
);
4372 /* we have a macro: we try to substitute */
4376 if (macro_subst_tok(&str
, &nested_list
, s
, &ml
) == 0) {
4377 /* substitution done, NOTE: maybe empty */
4378 tok_str_add(&str
, 0);
4379 macro_ptr
= str
.str
;
4380 macro_ptr_allocated
= str
.str
;
4387 /* end of macro or end of unget buffer */
4388 if (unget_buffer_enabled
) {
4389 macro_ptr
= unget_saved_macro_ptr
;
4390 unget_buffer_enabled
= 0;
4392 /* end of macro string: free it */
4393 tok_str_free(macro_ptr_allocated
);
4400 /* convert preprocessor tokens into C tokens */
4401 if (tok
== TOK_PPNUM
&&
4402 (parse_flags
& PARSE_FLAG_TOK_NUM
)) {
4403 parse_number((char *)tokc
.cstr
->data
);
4407 /* push back current token and set current token to 'last_tok'. Only
4408 identifier case handled for labels. */
4409 static inline void unget_tok(int last_tok
)
4413 unget_saved_macro_ptr
= macro_ptr
;
4414 unget_buffer_enabled
= 1;
4415 q
= unget_saved_buffer
;
4418 n
= tok_ext_size(tok
) - 1;
4421 *q
= 0; /* end of token string */
4426 void swap(int *p
, int *q
)
4434 void vsetc(CType
*type
, int r
, CValue
*vc
)
4438 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4439 error("memory full");
4440 /* cannot let cpu flags if other instruction are generated. Also
4441 avoid leaving VT_JMP anywhere except on the top of the stack
4442 because it would complicate the code generator. */
4443 if (vtop
>= vstack
) {
4444 v
= vtop
->r
& VT_VALMASK
;
4445 if (v
== VT_CMP
|| (v
& ~1) == VT_JMP
)
4451 vtop
->r2
= VT_CONST
;
4455 /* push integer constant */
4460 vsetc(&int_type
, VT_CONST
, &cval
);
4463 /* Return a static symbol pointing to a section */
4464 static Sym
*get_sym_ref(CType
*type
, Section
*sec
,
4465 unsigned long offset
, unsigned long size
)
4471 sym
= global_identifier_push(v
, type
->t
| VT_STATIC
, 0);
4472 sym
->type
.ref
= type
->ref
;
4473 sym
->r
= VT_CONST
| VT_SYM
;
4474 put_extern_sym(sym
, sec
, offset
, size
);
4478 /* push a reference to a section offset by adding a dummy symbol */
4479 static void vpush_ref(CType
*type
, Section
*sec
, unsigned long offset
, unsigned long size
)
4484 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4485 vtop
->sym
= get_sym_ref(type
, sec
, offset
, size
);
4488 /* define a new external reference to a symbol 'v' of type 'u' */
4489 static Sym
*external_global_sym(int v
, CType
*type
, int r
)
4495 /* push forward reference */
4496 s
= global_identifier_push(v
, type
->t
| VT_EXTERN
, 0);
4497 s
->type
.ref
= type
->ref
;
4498 s
->r
= r
| VT_CONST
| VT_SYM
;
4503 /* define a new external reference to a symbol 'v' of type 'u' */
4504 static Sym
*external_sym(int v
, CType
*type
, int r
)
4510 /* push forward reference */
4511 s
= sym_push(v
, type
, r
| VT_CONST
| VT_SYM
, 0);
4512 s
->type
.t
|= VT_EXTERN
;
4514 if (!is_compatible_types(&s
->type
, type
))
4515 error("incompatible types for redefinition of '%s'",
4516 get_tok_str(v
, NULL
));
4521 /* push a reference to global symbol v */
4522 static void vpush_global_sym(CType
*type
, int v
)
4527 sym
= external_global_sym(v
, type
, 0);
4529 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
4533 void vset(CType
*type
, int r
, int v
)
4538 vsetc(type
, r
, &cval
);
4541 void vseti(int r
, int v
)
4557 void vpushv(SValue
*v
)
4559 if (vtop
>= vstack
+ (VSTACK_SIZE
- 1))
4560 error("memory full");
4570 /* save r to the memory stack, and mark it as being free */
4571 void save_reg(int r
)
4573 int l
, saved
, size
, align
;
4577 /* modify all stack values */
4580 for(p
=vstack
;p
<=vtop
;p
++) {
4581 if ((p
->r
& VT_VALMASK
) == r
||
4582 (p
->r2
& VT_VALMASK
) == r
) {
4583 /* must save value on stack if not already done */
4585 /* NOTE: must reload 'r' because r might be equal to r2 */
4586 r
= p
->r
& VT_VALMASK
;
4587 /* store register in the stack */
4589 if ((p
->r
& VT_LVAL
) ||
4590 (!is_float(type
->t
) && (type
->t
& VT_BTYPE
) != VT_LLONG
))
4592 size
= type_size(type
, &align
);
4593 loc
= (loc
- size
) & -align
;
4594 sv
.type
.t
= type
->t
;
4595 sv
.r
= VT_LOCAL
| VT_LVAL
;
4598 #ifdef TCC_TARGET_I386
4599 /* x86 specific: need to pop fp register ST0 if saved */
4600 if (r
== TREG_ST0
) {
4601 o(0xd9dd); /* fstp %st(1) */
4604 /* special long long case */
4605 if ((type
->t
& VT_BTYPE
) == VT_LLONG
) {
4612 /* mark that stack entry as being saved on the stack */
4613 if (p
->r
& VT_LVAL
) {
4614 /* also clear the bounded flag because the
4615 relocation address of the function was stored in
4617 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
4619 p
->r
= lvalue_type(p
->type
.t
) | VT_LOCAL
;
4627 /* find a register of class 'rc2' with at most one reference on stack.
4628 * If none, call get_reg(rc) */
4629 int get_reg_ex(int rc
, int rc2
)
4634 for(r
=0;r
<NB_REGS
;r
++) {
4635 if (reg_classes
[r
] & rc2
) {
4638 for(p
= vstack
; p
<= vtop
; p
++) {
4639 if ((p
->r
& VT_VALMASK
) == r
||
4640 (p
->r2
& VT_VALMASK
) == r
)
4650 /* find a free register of class 'rc'. If none, save one register */
4656 /* find a free register */
4657 for(r
=0;r
<NB_REGS
;r
++) {
4658 if (reg_classes
[r
] & rc
) {
4659 for(p
=vstack
;p
<=vtop
;p
++) {
4660 if ((p
->r
& VT_VALMASK
) == r
||
4661 (p
->r2
& VT_VALMASK
) == r
)
4669 /* no register left : free the first one on the stack (VERY
4670 IMPORTANT to start from the bottom to ensure that we don't
4671 spill registers used in gen_opi()) */
4672 for(p
=vstack
;p
<=vtop
;p
++) {
4673 r
= p
->r
& VT_VALMASK
;
4674 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
))
4676 /* also look at second register (if long long) */
4677 r
= p
->r2
& VT_VALMASK
;
4678 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
4684 /* Should never comes here */
4688 /* save registers up to (vtop - n) stack entry */
4689 void save_regs(int n
)
4694 for(p
= vstack
;p
<= p1
; p
++) {
4695 r
= p
->r
& VT_VALMASK
;
4702 /* move register 's' to 'r', and flush previous value of r to memory
4704 void move_reg(int r
, int s
)
4717 /* get address of vtop (vtop MUST BE an lvalue) */
4720 vtop
->r
&= ~VT_LVAL
;
4721 /* tricky: if saved lvalue, then we can go back to lvalue */
4722 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
4723 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
4726 #ifdef CONFIG_TCC_BCHECK
4727 /* generate lvalue bound code */
4733 vtop
->r
&= ~VT_MUSTBOUND
;
4734 /* if lvalue, then use checking code before dereferencing */
4735 if (vtop
->r
& VT_LVAL
) {
4736 /* if not VT_BOUNDED value, then make one */
4737 if (!(vtop
->r
& VT_BOUNDED
)) {
4738 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
4739 /* must save type because we must set it to int to get pointer */
4741 vtop
->type
.t
= VT_INT
;
4744 gen_bounded_ptr_add();
4745 vtop
->r
|= lval_type
;
4748 /* then check for dereferencing */
4749 gen_bounded_ptr_deref();
4754 /* store vtop a register belonging to class 'rc'. lvalues are
4755 converted to values. Cannot be used if cannot be converted to
4756 register value (such as structures). */
4759 int r
, r2
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
4760 unsigned long long ll
;
4762 /* NOTE: get_reg can modify vstack[] */
4763 if (vtop
->type
.t
& VT_BITFIELD
) {
4764 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
4765 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4766 /* remove bit field info to avoid loops */
4767 vtop
->type
.t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4768 /* generate shifts */
4769 vpushi(32 - (bit_pos
+ bit_size
));
4771 vpushi(32 - bit_size
);
4772 /* NOTE: transformed to SHR if unsigned */
4776 if (is_float(vtop
->type
.t
) &&
4777 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4780 unsigned long offset
;
4782 /* XXX: unify with initializers handling ? */
4783 /* CPUs usually cannot use float constants, so we store them
4784 generically in data segment */
4785 size
= type_size(&vtop
->type
, &align
);
4786 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
4787 data_section
->data_offset
= offset
;
4788 /* XXX: not portable yet */
4789 ptr
= section_ptr_add(data_section
, size
);
4792 ptr
[i
] = vtop
->c
.tab
[i
];
4793 sym
= get_sym_ref(&vtop
->type
, data_section
, offset
, size
<< 2);
4794 vtop
->r
|= VT_LVAL
| VT_SYM
;
4798 #ifdef CONFIG_TCC_BCHECK
4799 if (vtop
->r
& VT_MUSTBOUND
)
4803 r
= vtop
->r
& VT_VALMASK
;
4804 /* need to reload if:
4806 - lvalue (need to dereference pointer)
4807 - already a register, but not in the right class */
4808 if (r
>= VT_CONST
||
4809 (vtop
->r
& VT_LVAL
) ||
4810 !(reg_classes
[r
] & rc
) ||
4811 ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
&&
4812 !(reg_classes
[vtop
->r2
] & rc
))) {
4814 if ((vtop
->type
.t
& VT_BTYPE
) == VT_LLONG
) {
4815 /* two register type load : expand to two words
4817 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
4820 vtop
->c
.ui
= ll
; /* first word */
4822 vtop
->r
= r
; /* save register value */
4823 vpushi(ll
>> 32); /* second word */
4824 } else if (r
>= VT_CONST
|| /* XXX: test to VT_CONST incorrect ? */
4825 (vtop
->r
& VT_LVAL
)) {
4826 /* We do not want to modifier the long long
4827 pointer here, so the safest (and less
4828 efficient) is to save all the other registers
4829 in the stack. XXX: totally inefficient. */
4831 /* load from memory */
4834 vtop
[-1].r
= r
; /* save register value */
4835 /* increment pointer to get second word */
4836 vtop
->type
.t
= VT_INT
;
4842 /* move registers */
4845 vtop
[-1].r
= r
; /* save register value */
4846 vtop
->r
= vtop
[-1].r2
;
4848 /* allocate second register */
4855 /* write second register */
4857 } else if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->type
.t
)) {
4859 /* lvalue of scalar type : need to use lvalue type
4860 because of possible cast */
4863 /* compute memory access type */
4864 if (vtop
->r
& VT_LVAL_BYTE
)
4866 else if (vtop
->r
& VT_LVAL_SHORT
)
4868 if (vtop
->r
& VT_LVAL_UNSIGNED
)
4872 /* restore wanted type */
4875 /* one register type load */
4880 #ifdef TCC_TARGET_C67
4881 /* uses register pairs for doubles */
4882 if ((vtop
->type
.t
& VT_BTYPE
) == VT_DOUBLE
)
4889 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
4890 void gv2(int rc1
, int rc2
)
4894 /* generate more generic register first. But VT_JMP or VT_CMP
4895 values must be generated first in all cases to avoid possible
4897 v
= vtop
[0].r
& VT_VALMASK
;
4898 if (v
!= VT_CMP
&& (v
& ~1) != VT_JMP
&& rc1
<= rc2
) {
4903 /* test if reload is needed for first register */
4904 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
4914 /* test if reload is needed for first register */
4915 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
4921 /* expand long long on stack in two int registers */
4926 u
= vtop
->type
.t
& VT_UNSIGNED
;
4929 vtop
[0].r
= vtop
[-1].r2
;
4930 vtop
[0].r2
= VT_CONST
;
4931 vtop
[-1].r2
= VT_CONST
;
4932 vtop
[0].type
.t
= VT_INT
| u
;
4933 vtop
[-1].type
.t
= VT_INT
| u
;
4936 #ifdef TCC_TARGET_ARM
4937 /* expand long long on stack */
4938 void lexpand_nr(void)
4942 u
= vtop
->type
.t
& VT_UNSIGNED
;
4944 vtop
->r2
= VT_CONST
;
4945 vtop
->type
.t
= VT_INT
| u
;
4946 v
=vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
);
4947 if (v
== VT_CONST
) {
4948 vtop
[-1].c
.ui
= vtop
->c
.ull
;
4949 vtop
->c
.ui
= vtop
->c
.ull
>> 32;
4951 } else if (v
== (VT_LVAL
|VT_CONST
) || v
== (VT_LVAL
|VT_LOCAL
)) {
4953 vtop
->r
= vtop
[-1].r
;
4954 } else if (v
> VT_CONST
) {
4958 vtop
->r
= vtop
[-1].r2
;
4959 vtop
[-1].r2
= VT_CONST
;
4960 vtop
[-1].type
.t
= VT_INT
| u
;
4964 /* build a long long from two ints */
4967 gv2(RC_INT
, RC_INT
);
4968 vtop
[-1].r2
= vtop
[0].r
;
4969 vtop
[-1].type
.t
= t
;
4973 /* rotate n first stack elements to the bottom
4974 I1 ... In -> I2 ... In I1 [top is right]
4982 for(i
=-n
+1;i
!=0;i
++)
4983 vtop
[i
] = vtop
[i
+1];
4987 /* rotate n first stack elements to the top
4988 I1 ... In -> In I1 ... I(n-1) [top is right]
4996 for(i
= 0;i
< n
- 1; i
++)
4997 vtop
[-i
] = vtop
[-i
- 1];
5001 #ifdef TCC_TARGET_ARM
5002 /* like vrott but in other direction
5003 In ... I1 -> I(n-1) ... I1 In [top is right]
5011 for(i
= n
- 1; i
> 0; i
--)
5012 vtop
[-i
] = vtop
[-i
+ 1];
5017 /* pop stack value */
5021 v
= vtop
->r
& VT_VALMASK
;
5022 #ifdef TCC_TARGET_I386
5023 /* for x86, we need to pop the FP stack */
5024 if (v
== TREG_ST0
&& !nocode_wanted
) {
5025 o(0xd9dd); /* fstp %st(1) */
5028 if (v
== VT_JMP
|| v
== VT_JMPI
) {
5029 /* need to put correct jump if && or || without test */
5035 /* convert stack entry to register and duplicate its value in another
5043 if ((t
& VT_BTYPE
) == VT_LLONG
) {
5050 /* stack: H L L1 H1 */
5058 /* duplicate value */
5069 load(r1
, &sv
); /* move r to r1 */
5071 /* duplicates value */
5076 /* generate CPU independent (unsigned) long long operations */
5077 void gen_opl(int op
)
5079 int t
, a
, b
, op1
, c
, i
;
5086 func
= TOK___divdi3
;
5089 func
= TOK___udivdi3
;
5092 func
= TOK___moddi3
;
5095 func
= TOK___umoddi3
;
5097 /* call generic long long function */
5098 vpush_global_sym(&func_old_type
, func
);
5103 vtop
->r2
= REG_LRET
;
5116 /* stack: L1 H1 L2 H2 */
5121 vtop
[-2] = vtop
[-3];
5124 /* stack: H1 H2 L1 L2 */
5130 /* stack: H1 H2 L1 L2 ML MH */
5133 /* stack: ML MH H1 H2 L1 L2 */
5137 /* stack: ML MH H1 L2 H2 L1 */
5142 /* stack: ML MH M1 M2 */
5145 } else if (op
== '+' || op
== '-') {
5146 /* XXX: add non carry method too (for MIPS or alpha) */
5152 /* stack: H1 H2 (L1 op L2) */
5155 gen_op(op1
+ 1); /* TOK_xxxC2 */
5158 /* stack: H1 H2 (L1 op L2) */
5161 /* stack: (L1 op L2) H1 H2 */
5163 /* stack: (L1 op L2) (H1 op H2) */
5171 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
5172 t
= vtop
[-1].type
.t
;
5176 /* stack: L H shift */
5178 /* constant: simpler */
5179 /* NOTE: all comments are for SHL. the other cases are
5180 done by swaping words */
5191 if (op
!= TOK_SAR
) {
5224 /* XXX: should provide a faster fallback on x86 ? */
5227 func
= TOK___sardi3
;
5230 func
= TOK___shrdi3
;
5233 func
= TOK___shldi3
;
5239 /* compare operations */
5245 /* stack: L1 H1 L2 H2 */
5247 vtop
[-1] = vtop
[-2];
5249 /* stack: L1 L2 H1 H2 */
5252 /* when values are equal, we need to compare low words. since
5253 the jump is inverted, we invert the test too. */
5256 else if (op1
== TOK_GT
)
5258 else if (op1
== TOK_ULT
)
5260 else if (op1
== TOK_UGT
)
5265 if (op1
!= TOK_NE
) {
5269 /* generate non equal test */
5270 /* XXX: NOT PORTABLE yet */
5274 #if defined(TCC_TARGET_I386)
5275 b
= psym(0x850f, 0);
5276 #elif defined(TCC_TARGET_ARM)
5278 o(0x1A000000 | encbranch(ind
, 0, 1));
5279 #elif defined(TCC_TARGET_C67)
5280 error("not implemented");
5282 #error not supported
5286 /* compare low. Always unsigned */
5290 else if (op1
== TOK_LE
)
5292 else if (op1
== TOK_GT
)
5294 else if (op1
== TOK_GE
)
5304 /* handle integer constant optimizations and various machine
5306 void gen_opic(int op
)
5313 /* currently, we cannot do computations with forward symbols */
5314 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5315 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5319 case '+': v1
->c
.i
+= fc
; break;
5320 case '-': v1
->c
.i
-= fc
; break;
5321 case '&': v1
->c
.i
&= fc
; break;
5322 case '^': v1
->c
.i
^= fc
; break;
5323 case '|': v1
->c
.i
|= fc
; break;
5324 case '*': v1
->c
.i
*= fc
; break;
5331 /* if division by zero, generate explicit division */
5334 error("division by zero in constant");
5338 default: v1
->c
.i
/= fc
; break;
5339 case '%': v1
->c
.i
%= fc
; break;
5340 case TOK_UDIV
: v1
->c
.i
= (unsigned)v1
->c
.i
/ fc
; break;
5341 case TOK_UMOD
: v1
->c
.i
= (unsigned)v1
->c
.i
% fc
; break;
5344 case TOK_SHL
: v1
->c
.i
<<= fc
; break;
5345 case TOK_SHR
: v1
->c
.i
= (unsigned)v1
->c
.i
>> fc
; break;
5346 case TOK_SAR
: v1
->c
.i
>>= fc
; break;
5348 case TOK_ULT
: v1
->c
.i
= (unsigned)v1
->c
.i
< (unsigned)fc
; break;
5349 case TOK_UGE
: v1
->c
.i
= (unsigned)v1
->c
.i
>= (unsigned)fc
; break;
5350 case TOK_EQ
: v1
->c
.i
= v1
->c
.i
== fc
; break;
5351 case TOK_NE
: v1
->c
.i
= v1
->c
.i
!= fc
; break;
5352 case TOK_ULE
: v1
->c
.i
= (unsigned)v1
->c
.i
<= (unsigned)fc
; break;
5353 case TOK_UGT
: v1
->c
.i
= (unsigned)v1
->c
.i
> (unsigned)fc
; break;
5354 case TOK_LT
: v1
->c
.i
= v1
->c
.i
< fc
; break;
5355 case TOK_GE
: v1
->c
.i
= v1
->c
.i
>= fc
; break;
5356 case TOK_LE
: v1
->c
.i
= v1
->c
.i
<= fc
; break;
5357 case TOK_GT
: v1
->c
.i
= v1
->c
.i
> fc
; break;
5359 case TOK_LAND
: v1
->c
.i
= v1
->c
.i
&& fc
; break;
5360 case TOK_LOR
: v1
->c
.i
= v1
->c
.i
|| fc
; break;
5366 /* if commutative ops, put c2 as constant */
5367 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
5368 op
== '|' || op
== '*')) {
5373 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
5376 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
5377 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
5383 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
5384 /* try to use shifts instead of muls or divs */
5385 if (fc
> 0 && (fc
& (fc
- 1)) == 0) {
5394 else if (op
== TOK_PDIV
)
5400 } else if (c2
&& (op
== '+' || op
== '-') &&
5401 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
5402 (VT_CONST
| VT_SYM
)) {
5403 /* symbol + constant case */
5410 if (!nocode_wanted
) {
5411 /* call low level op generator */
5420 /* generate a floating point operation with constant propagation */
5421 void gen_opif(int op
)
5429 /* currently, we cannot do computations with forward symbols */
5430 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5431 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5433 if (v1
->type
.t
== VT_FLOAT
) {
5436 } else if (v1
->type
.t
== VT_DOUBLE
) {
5444 /* NOTE: we only do constant propagation if finite number (not
5445 NaN or infinity) (ANSI spec) */
5446 if (!ieee_finite(f1
) || !ieee_finite(f2
))
5450 case '+': f1
+= f2
; break;
5451 case '-': f1
-= f2
; break;
5452 case '*': f1
*= f2
; break;
5456 error("division by zero in constant");
5461 /* XXX: also handles tests ? */
5465 /* XXX: overflow test ? */
5466 if (v1
->type
.t
== VT_FLOAT
) {
5468 } else if (v1
->type
.t
== VT_DOUBLE
) {
5476 if (!nocode_wanted
) {
5484 static int pointed_size(CType
*type
)
5487 return type_size(pointed_type(type
), &align
);
5490 static inline int is_null_pointer(SValue
*p
)
5492 if ((p
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5494 return ((p
->type
.t
& VT_BTYPE
) == VT_INT
&& p
->c
.i
== 0) ||
5495 ((p
->type
.t
& VT_BTYPE
) == VT_LLONG
&& p
->c
.ll
== 0);
5498 static inline int is_integer_btype(int bt
)
5500 return (bt
== VT_BYTE
|| bt
== VT_SHORT
||
5501 bt
== VT_INT
|| bt
== VT_LLONG
);
5504 /* check types for comparison or substraction of pointers */
5505 static void check_comparison_pointer_types(SValue
*p1
, SValue
*p2
, int op
)
5507 CType
*type1
, *type2
, tmp_type1
, tmp_type2
;
5510 /* null pointers are accepted for all comparisons as gcc */
5511 if (is_null_pointer(p1
) || is_null_pointer(p2
))
5515 bt1
= type1
->t
& VT_BTYPE
;
5516 bt2
= type2
->t
& VT_BTYPE
;
5517 /* accept comparison between pointer and integer with a warning */
5518 if ((is_integer_btype(bt1
) || is_integer_btype(bt2
)) && op
!= '-') {
5519 warning("comparison between pointer and integer");
5523 /* both must be pointers or implicit function pointers */
5524 if (bt1
== VT_PTR
) {
5525 type1
= pointed_type(type1
);
5526 } else if (bt1
!= VT_FUNC
)
5527 goto invalid_operands
;
5529 if (bt2
== VT_PTR
) {
5530 type2
= pointed_type(type2
);
5531 } else if (bt2
!= VT_FUNC
) {
5533 error("invalid operands to binary %s", get_tok_str(op
, NULL
));
5535 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
5536 (type2
->t
& VT_BTYPE
) == VT_VOID
)
5540 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5541 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
5542 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
5543 /* gcc-like error if '-' is used */
5545 goto invalid_operands
;
5547 warning("comparison of distinct pointer types lacks a cast");
5551 /* generic gen_op: handles types problems */
5554 int u
, t1
, t2
, bt1
, bt2
, t
;
5557 t1
= vtop
[-1].type
.t
;
5558 t2
= vtop
[0].type
.t
;
5559 bt1
= t1
& VT_BTYPE
;
5560 bt2
= t2
& VT_BTYPE
;
5562 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
5563 /* at least one operand is a pointer */
5564 /* relationnal op: must be both pointers */
5565 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5566 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5567 /* pointers are handled are unsigned */
5568 t
= VT_INT
| VT_UNSIGNED
;
5571 /* if both pointers, then it must be the '-' op */
5572 if (bt1
== VT_PTR
&& bt2
== VT_PTR
) {
5574 error("cannot use pointers here");
5575 check_comparison_pointer_types(vtop
- 1, vtop
, op
);
5576 /* XXX: check that types are compatible */
5577 u
= pointed_size(&vtop
[-1].type
);
5579 /* set to integer type */
5580 vtop
->type
.t
= VT_INT
;
5584 /* exactly one pointer : must be '+' or '-'. */
5585 if (op
!= '-' && op
!= '+')
5586 error("cannot use pointers here");
5587 /* Put pointer as first operand */
5588 if (bt2
== VT_PTR
) {
5592 type1
= vtop
[-1].type
;
5593 /* XXX: cast to int ? (long long case) */
5594 vpushi(pointed_size(&vtop
[-1].type
));
5596 #ifdef CONFIG_TCC_BCHECK
5597 /* if evaluating constant expression, no code should be
5598 generated, so no bound check */
5599 if (do_bounds_check
&& !const_wanted
) {
5600 /* if bounded pointers, we generate a special code to
5607 gen_bounded_ptr_add();
5613 /* put again type if gen_opic() swaped operands */
5616 } else if (is_float(bt1
) || is_float(bt2
)) {
5617 /* compute bigger type and do implicit casts */
5618 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
5620 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
5625 /* floats can only be used for a few operations */
5626 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
5627 (op
< TOK_ULT
|| op
> TOK_GT
))
5628 error("invalid operands for binary operation");
5630 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
5631 /* cast to biggest op */
5633 /* convert to unsigned if it does not fit in a long long */
5634 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
5635 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
5639 /* integer operations */
5641 /* convert to unsigned if it does not fit in an integer */
5642 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
5643 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
5646 /* XXX: currently, some unsigned operations are explicit, so
5647 we modify them here */
5648 if (t
& VT_UNSIGNED
) {
5655 else if (op
== TOK_LT
)
5657 else if (op
== TOK_GT
)
5659 else if (op
== TOK_LE
)
5661 else if (op
== TOK_GE
)
5668 /* special case for shifts and long long: we keep the shift as
5670 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
5675 else if ((t
& VT_BTYPE
) == VT_LLONG
)
5679 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
5680 /* relationnal op: the result is an int */
5681 vtop
->type
.t
= VT_INT
;
5688 /* generic itof for unsigned long long case */
5689 void gen_cvt_itof1(int t
)
5691 if ((vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
5692 (VT_LLONG
| VT_UNSIGNED
)) {
5695 vpush_global_sym(&func_old_type
, TOK___ulltof
);
5696 else if (t
== VT_DOUBLE
)
5697 vpush_global_sym(&func_old_type
, TOK___ulltod
);
5699 vpush_global_sym(&func_old_type
, TOK___ulltold
);
5709 /* generic ftoi for unsigned long long case */
5710 void gen_cvt_ftoi1(int t
)
5714 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
5715 /* not handled natively */
5716 st
= vtop
->type
.t
& VT_BTYPE
;
5718 vpush_global_sym(&func_old_type
, TOK___fixunssfdi
);
5719 else if (st
== VT_DOUBLE
)
5720 vpush_global_sym(&func_old_type
, TOK___fixunsdfdi
);
5722 vpush_global_sym(&func_old_type
, TOK___fixunsxfdi
);
5727 vtop
->r2
= REG_LRET
;
5733 /* force char or short cast */
5734 void force_charshort_cast(int t
)
5738 /* XXX: add optimization if lvalue : just change type and offset */
5743 if (t
& VT_UNSIGNED
) {
5744 vpushi((1 << bits
) - 1);
5755 /* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
5756 static void gen_cast(CType
*type
)
5758 int sbt
, dbt
, sf
, df
, c
;
5760 /* special delayed cast for char/short */
5761 /* XXX: in some cases (multiple cascaded casts), it may still
5763 if (vtop
->r
& VT_MUSTCAST
) {
5764 vtop
->r
&= ~VT_MUSTCAST
;
5765 force_charshort_cast(vtop
->type
.t
);
5768 /* bitfields first get cast to ints */
5769 if (vtop
->type
.t
& VT_BITFIELD
) {
5773 dbt
= type
->t
& (VT_BTYPE
| VT_UNSIGNED
);
5774 sbt
= vtop
->type
.t
& (VT_BTYPE
| VT_UNSIGNED
);
5776 if (sbt
!= dbt
&& !nocode_wanted
) {
5779 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
5781 /* convert from fp to fp */
5783 /* constant case: we can do it now */
5784 /* XXX: in ISOC, cannot do it if error in convert */
5785 if (dbt
== VT_FLOAT
&& sbt
== VT_DOUBLE
)
5786 vtop
->c
.f
= (float)vtop
->c
.d
;
5787 else if (dbt
== VT_FLOAT
&& sbt
== VT_LDOUBLE
)
5788 vtop
->c
.f
= (float)vtop
->c
.ld
;
5789 else if (dbt
== VT_DOUBLE
&& sbt
== VT_FLOAT
)
5790 vtop
->c
.d
= (double)vtop
->c
.f
;
5791 else if (dbt
== VT_DOUBLE
&& sbt
== VT_LDOUBLE
)
5792 vtop
->c
.d
= (double)vtop
->c
.ld
;
5793 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_FLOAT
)
5794 vtop
->c
.ld
= (long double)vtop
->c
.f
;
5795 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_DOUBLE
)
5796 vtop
->c
.ld
= (long double)vtop
->c
.d
;
5798 /* non constant case: generate code */
5802 /* convert int to fp */
5805 case VT_LLONG
| VT_UNSIGNED
:
5807 /* XXX: add const cases for long long */
5809 case VT_INT
| VT_UNSIGNED
:
5811 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.ui
; break;
5812 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.ui
; break;
5813 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.ui
; break;
5818 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.i
; break;
5819 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.i
; break;
5820 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.i
; break;
5826 #if !defined(TCC_TARGET_ARM)
5833 /* convert fp to int */
5834 /* we handle char/short/etc... with generic code */
5835 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
5836 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
5841 case VT_LLONG
| VT_UNSIGNED
:
5843 /* XXX: add const cases for long long */
5845 case VT_INT
| VT_UNSIGNED
:
5847 case VT_FLOAT
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5848 case VT_DOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5849 case VT_LDOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
5855 case VT_FLOAT
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5856 case VT_DOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5857 case VT_LDOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
5865 if (dbt
== VT_INT
&& (type
->t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
5866 /* additional cast for char/short/bool... */
5870 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
5871 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
5872 /* scalar to long long */
5874 if (sbt
== (VT_INT
| VT_UNSIGNED
))
5875 vtop
->c
.ll
= vtop
->c
.ui
;
5877 vtop
->c
.ll
= vtop
->c
.i
;
5879 /* machine independent conversion */
5881 /* generate high word */
5882 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
5890 /* patch second register */
5891 vtop
[-1].r2
= vtop
->r
;
5895 } else if (dbt
== VT_BOOL
) {
5896 /* scalar to bool */
5899 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
5900 (dbt
& VT_BTYPE
) == VT_SHORT
) {
5901 force_charshort_cast(dbt
);
5902 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
5904 if (sbt
== VT_LLONG
) {
5905 /* from long long: just take low order word */
5909 /* if lvalue and single word type, nothing to do because
5910 the lvalue already contains the real type size (see
5911 VT_LVAL_xxx constants) */
5917 /* return type size. Put alignment at 'a' */
5918 static int type_size(CType
*type
, int *a
)
5923 bt
= type
->t
& VT_BTYPE
;
5924 if (bt
== VT_STRUCT
) {
5929 } else if (bt
== VT_PTR
) {
5930 if (type
->t
& VT_ARRAY
) {
5932 return type_size(&s
->type
, a
) * s
->c
;
5937 } else if (bt
== VT_LDOUBLE
) {
5939 return LDOUBLE_SIZE
;
5940 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
5941 #ifdef TCC_TARGET_I386
5947 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
5950 } else if (bt
== VT_SHORT
) {
5954 /* char, void, function, _Bool */
5960 /* return the pointed type of t */
5961 static inline CType
*pointed_type(CType
*type
)
5963 return &type
->ref
->type
;
5966 /* modify type so that its it is a pointer to type. */
5967 static void mk_pointer(CType
*type
)
5970 s
= sym_push(SYM_FIELD
, type
, 0, -1);
5971 type
->t
= VT_PTR
| (type
->t
& ~VT_TYPE
);
5975 /* compare function types. OLD functions match any new functions */
5976 static int is_compatible_func(CType
*type1
, CType
*type2
)
5982 if (!is_compatible_types(&s1
->type
, &s2
->type
))
5984 /* check func_call */
5987 /* XXX: not complete */
5988 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
5992 while (s1
!= NULL
) {
5995 if (!is_compatible_types(&s1
->type
, &s2
->type
))
6005 /* return true if type1 and type2 are exactly the same (including
6008 - enums are not checked as gcc __builtin_types_compatible_p ()
6010 static int is_compatible_types(CType
*type1
, CType
*type2
)
6014 t1
= type1
->t
& VT_TYPE
;
6015 t2
= type2
->t
& VT_TYPE
;
6016 /* XXX: bitfields ? */
6019 /* test more complicated cases */
6020 bt1
= t1
& VT_BTYPE
;
6021 if (bt1
== VT_PTR
) {
6022 type1
= pointed_type(type1
);
6023 type2
= pointed_type(type2
);
6024 return is_compatible_types(type1
, type2
);
6025 } else if (bt1
== VT_STRUCT
) {
6026 return (type1
->ref
== type2
->ref
);
6027 } else if (bt1
== VT_FUNC
) {
6028 return is_compatible_func(type1
, type2
);
6034 /* print a type. If 'varstr' is not NULL, then the variable is also
6035 printed in the type */
6037 /* XXX: add array and function pointers */
6038 void type_to_str(char *buf
, int buf_size
,
6039 CType
*type
, const char *varstr
)
6046 t
= type
->t
& VT_TYPE
;
6049 if (t
& VT_CONSTANT
)
6050 pstrcat(buf
, buf_size
, "const ");
6051 if (t
& VT_VOLATILE
)
6052 pstrcat(buf
, buf_size
, "volatile ");
6053 if (t
& VT_UNSIGNED
)
6054 pstrcat(buf
, buf_size
, "unsigned ");
6084 tstr
= "long double";
6086 pstrcat(buf
, buf_size
, tstr
);
6090 if (bt
== VT_STRUCT
)
6094 pstrcat(buf
, buf_size
, tstr
);
6095 v
= type
->ref
->v
& ~SYM_STRUCT
;
6096 if (v
>= SYM_FIRST_ANOM
)
6097 pstrcat(buf
, buf_size
, "<anonymous>");
6099 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
6103 type_to_str(buf
, buf_size
, &s
->type
, varstr
);
6104 pstrcat(buf
, buf_size
, "(");
6106 while (sa
!= NULL
) {
6107 type_to_str(buf1
, sizeof(buf1
), &sa
->type
, NULL
);
6108 pstrcat(buf
, buf_size
, buf1
);
6111 pstrcat(buf
, buf_size
, ", ");
6113 pstrcat(buf
, buf_size
, ")");
6117 pstrcpy(buf1
, sizeof(buf1
), "*");
6119 pstrcat(buf1
, sizeof(buf1
), varstr
);
6120 type_to_str(buf
, buf_size
, &s
->type
, buf1
);
6124 pstrcat(buf
, buf_size
, " ");
6125 pstrcat(buf
, buf_size
, varstr
);
6130 /* verify type compatibility to store vtop in 'dt' type, and generate
6132 static void gen_assign_cast(CType
*dt
)
6134 CType
*st
, *type1
, *type2
, tmp_type1
, tmp_type2
;
6135 char buf1
[256], buf2
[256];
6138 st
= &vtop
->type
; /* source type */
6139 dbt
= dt
->t
& VT_BTYPE
;
6140 sbt
= st
->t
& VT_BTYPE
;
6141 if (dt
->t
& VT_CONSTANT
)
6142 warning("assignment of read-only location");
6145 /* special cases for pointers */
6146 /* '0' can also be a pointer */
6147 if (is_null_pointer(vtop
))
6149 /* accept implicit pointer to integer cast with warning */
6150 if (is_integer_btype(sbt
)) {
6151 warning("assignment makes pointer from integer without a cast");
6154 type1
= pointed_type(dt
);
6155 /* a function is implicitely a function pointer */
6156 if (sbt
== VT_FUNC
) {
6157 if ((type1
->t
& VT_BTYPE
) != VT_VOID
&&
6158 !is_compatible_types(pointed_type(dt
), st
))
6165 type2
= pointed_type(st
);
6166 if ((type1
->t
& VT_BTYPE
) == VT_VOID
||
6167 (type2
->t
& VT_BTYPE
) == VT_VOID
) {
6168 /* void * can match anything */
6170 /* exact type match, except for unsigned */
6173 tmp_type1
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6174 tmp_type2
.t
&= ~(VT_UNSIGNED
| VT_CONSTANT
| VT_VOLATILE
);
6175 if (!is_compatible_types(&tmp_type1
, &tmp_type2
))
6178 /* check const and volatile */
6179 if ((!(type1
->t
& VT_CONSTANT
) && (type2
->t
& VT_CONSTANT
)) ||
6180 (!(type1
->t
& VT_VOLATILE
) && (type2
->t
& VT_VOLATILE
)))
6181 warning("assignment discards qualifiers from pointer target type");
6187 if (sbt
== VT_PTR
|| sbt
== VT_FUNC
) {
6188 warning("assignment makes integer from pointer without a cast");
6190 /* XXX: more tests */
6195 tmp_type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6196 tmp_type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6197 if (!is_compatible_types(&tmp_type1
, &tmp_type2
)) {
6199 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
6200 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
6201 error("cannot cast '%s' to '%s'", buf1
, buf2
);
6209 /* store vtop in lvalue pushed on stack */
6212 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
6214 ft
= vtop
[-1].type
.t
;
6215 sbt
= vtop
->type
.t
& VT_BTYPE
;
6216 dbt
= ft
& VT_BTYPE
;
6217 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
6218 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
6219 /* optimize char/short casts */
6220 delayed_cast
= VT_MUSTCAST
;
6221 vtop
->type
.t
= ft
& VT_TYPE
;
6222 /* XXX: factorize */
6223 if (ft
& VT_CONSTANT
)
6224 warning("assignment of read-only location");
6227 if (!(ft
& VT_BITFIELD
))
6228 gen_assign_cast(&vtop
[-1].type
);
6231 if (sbt
== VT_STRUCT
) {
6232 /* if structure, only generate pointer */
6233 /* structure assignment : generate memcpy */
6234 /* XXX: optimize if small size */
6235 if (!nocode_wanted
) {
6236 size
= type_size(&vtop
->type
, &align
);
6238 vpush_global_sym(&func_old_type
, TOK_memcpy
);
6242 vtop
->type
.t
= VT_INT
;
6246 vtop
->type
.t
= VT_INT
;
6258 /* leave source on stack */
6259 } else if (ft
& VT_BITFIELD
) {
6260 /* bitfield store handling */
6261 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
6262 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
6263 /* remove bit field info to avoid loops */
6264 vtop
[-1].type
.t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
6266 /* duplicate destination */
6268 vtop
[-1] = vtop
[-2];
6270 /* mask and shift source */
6271 vpushi((1 << bit_size
) - 1);
6275 /* load destination, mask and or with source */
6277 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
6283 #ifdef CONFIG_TCC_BCHECK
6284 /* bound check case */
6285 if (vtop
[-1].r
& VT_MUSTBOUND
) {
6291 if (!nocode_wanted
) {
6295 r
= gv(rc
); /* generate value */
6296 /* if lvalue was saved on stack, must read it */
6297 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
6299 t
= get_reg(RC_INT
);
6301 sv
.r
= VT_LOCAL
| VT_LVAL
;
6302 sv
.c
.ul
= vtop
[-1].c
.ul
;
6304 vtop
[-1].r
= t
| VT_LVAL
;
6307 /* two word case handling : store second register at word + 4 */
6308 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
6310 /* convert to int to increment easily */
6311 vtop
->type
.t
= VT_INT
;
6317 /* XXX: it works because r2 is spilled last ! */
6318 store(vtop
->r2
, vtop
- 1);
6322 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
6323 vtop
->r
|= delayed_cast
;
6327 /* post defines POST/PRE add. c is the token ++ or -- */
6328 void inc(int post
, int c
)
6331 vdup(); /* save lvalue */
6333 gv_dup(); /* duplicate value */
6338 vpushi(c
- TOK_MID
);
6340 vstore(); /* store value */
6342 vpop(); /* if post op, return saved value */
6345 /* Parse GNUC __attribute__ extension. Currently, the following
6346 extensions are recognized:
6347 - aligned(n) : set data/function alignment.
6348 - packed : force data alignment to 1
6349 - section(x) : generate data/code in this section.
6350 - unused : currently ignored, but may be used someday.
6351 - regparm(n) : pass function parameters in registers (i386 only)
6353 static void parse_attribute(AttributeDef
*ad
)
6357 while (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
) {
6361 while (tok
!= ')') {
6362 if (tok
< TOK_IDENT
)
6363 expect("attribute name");
6371 expect("section name");
6372 ad
->section
= find_section(tcc_state
, (char *)tokc
.cstr
->data
);
6381 if (n
<= 0 || (n
& (n
- 1)) != 0)
6382 error("alignment must be a positive power of two");
6395 /* currently, no need to handle it because tcc does not
6396 track unused objects */
6400 /* currently, no need to handle it because tcc does not
6401 track unused objects */
6406 ad
->func_call
= FUNC_CDECL
;
6411 ad
->func_call
= FUNC_STDCALL
;
6413 #ifdef TCC_TARGET_I386
6423 ad
->func_call
= FUNC_FASTCALL1
+ n
- 1;
6431 if (tcc_state
->warn_unsupported
)
6432 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
6433 /* skip parameters */
6434 /* XXX: skip parenthesis too */
6437 while (tok
!= ')' && tok
!= -1)
6452 /* enum/struct/union declaration. u is either VT_ENUM or VT_STRUCT */
6453 static void struct_decl(CType
*type
, int u
)
6455 int a
, v
, size
, align
, maxalign
, c
, offset
;
6456 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
;
6461 a
= tok
; /* save decl type */
6466 /* struct already defined ? return it */
6468 expect("struct/union/enum name");
6472 error("invalid type");
6479 /* we put an undefined size for struct/union */
6480 s
= sym_push(v
| SYM_STRUCT
, &type1
, 0, -1);
6481 s
->r
= 0; /* default alignment is zero as gcc */
6482 /* put struct/union/enum name in type */
6490 error("struct/union/enum already defined");
6491 /* cannot be empty */
6493 /* non empty enums are not allowed */
6494 if (a
== TOK_ENUM
) {
6498 expect("identifier");
6504 /* enum symbols have static storage */
6505 ss
= sym_push(v
, &int_type
, VT_CONST
, c
);
6506 ss
->type
.t
|= VT_STATIC
;
6511 /* NOTE: we accept a trailing comma */
6521 while (tok
!= '}') {
6522 parse_btype(&btype
, &ad
);
6528 type_decl(&type1
, &ad
, &v
, TYPE_DIRECT
);
6529 if ((type1
.t
& VT_BTYPE
) == VT_FUNC
||
6530 (type1
.t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
| VT_INLINE
)))
6531 error("invalid type for '%s'",
6532 get_tok_str(v
, NULL
));
6536 bit_size
= expr_const();
6537 /* XXX: handle v = 0 case for messages */
6539 error("negative width in bit-field '%s'",
6540 get_tok_str(v
, NULL
));
6541 if (v
&& bit_size
== 0)
6542 error("zero width for bit-field '%s'",
6543 get_tok_str(v
, NULL
));
6545 size
= type_size(&type1
, &align
);
6547 if (align
< ad
.aligned
)
6549 } else if (ad
.packed
) {
6551 } else if (*tcc_state
->pack_stack_ptr
) {
6552 if (align
> *tcc_state
->pack_stack_ptr
)
6553 align
= *tcc_state
->pack_stack_ptr
;
6556 if (bit_size
>= 0) {
6557 bt
= type1
.t
& VT_BTYPE
;
6563 error("bitfields must have scalar type");
6565 if (bit_size
> bsize
) {
6566 error("width of '%s' exceeds its type",
6567 get_tok_str(v
, NULL
));
6568 } else if (bit_size
== bsize
) {
6569 /* no need for bit fields */
6571 } else if (bit_size
== 0) {
6572 /* XXX: what to do if only padding in a
6574 /* zero size: means to pad */
6578 /* we do not have enough room ? */
6579 if ((bit_pos
+ bit_size
) > bsize
)
6582 /* XXX: handle LSB first */
6583 type1
.t
|= VT_BITFIELD
|
6584 (bit_pos
<< VT_STRUCT_SHIFT
) |
6585 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
6586 bit_pos
+= bit_size
;
6592 /* add new memory data only if starting
6594 if (lbit_pos
== 0) {
6595 if (a
== TOK_STRUCT
) {
6596 c
= (c
+ align
- 1) & -align
;
6604 if (align
> maxalign
)
6608 printf("add field %s offset=%d",
6609 get_tok_str(v
, NULL
), offset
);
6610 if (type1
.t
& VT_BITFIELD
) {
6611 printf(" pos=%d size=%d",
6612 (type1
.t
>> VT_STRUCT_SHIFT
) & 0x3f,
6613 (type1
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
6617 ss
= sym_push(v
| SYM_FIELD
, &type1
, 0, offset
);
6621 if (tok
== ';' || tok
== TOK_EOF
)
6628 /* store size and alignment */
6629 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
6635 /* return 0 if no type declaration. otherwise, return the basic type
6638 static int parse_btype(CType
*type
, AttributeDef
*ad
)
6640 int t
, u
, type_found
, typespec_found
;
6644 memset(ad
, 0, sizeof(AttributeDef
));
6651 /* currently, we really ignore extension */
6661 if ((t
& VT_BTYPE
) != 0)
6662 error("too many basic types");
6678 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
6679 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6680 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
6681 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
6695 if ((t
& VT_BTYPE
) == VT_LONG
) {
6696 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
6703 struct_decl(&type1
, VT_ENUM
);
6706 type
->ref
= type1
.ref
;
6710 struct_decl(&type1
, VT_STRUCT
);
6713 /* type modifiers */
6766 /* GNUC attribute */
6767 case TOK_ATTRIBUTE1
:
6768 case TOK_ATTRIBUTE2
:
6769 parse_attribute(ad
);
6776 parse_expr_type(&type1
);
6782 if (!s
|| !(s
->type
.t
& VT_TYPEDEF
))
6784 t
|= (s
->type
.t
& ~VT_TYPEDEF
);
6785 type
->ref
= s
->type
.ref
;
6792 if ((t
& (VT_SIGNED
|VT_UNSIGNED
)) == (VT_SIGNED
|VT_UNSIGNED
))
6793 error("signed and unsigned modifier");
6794 if (tcc_state
->char_is_unsigned
) {
6795 if ((t
& (VT_SIGNED
|VT_UNSIGNED
|VT_BTYPE
)) == VT_BYTE
)
6800 /* long is never used as type */
6801 if ((t
& VT_BTYPE
) == VT_LONG
)
6802 t
= (t
& ~VT_BTYPE
) | VT_INT
;
6807 /* convert a function parameter type (array to pointer and function to
6808 function pointer) */
6809 static inline void convert_parameter_type(CType
*pt
)
6811 /* remove const and volatile qualifiers (XXX: const could be used
6812 to indicate a const function parameter */
6813 pt
->t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
6814 /* array must be transformed to pointer according to ANSI C */
6816 if ((pt
->t
& VT_BTYPE
) == VT_FUNC
) {
6821 static void post_type(CType
*type
, AttributeDef
*ad
)
6824 Sym
**plast
, *s
, *first
;
6829 /* function declaration */
6834 while (tok
!= ')') {
6835 /* read param name and compute offset */
6836 if (l
!= FUNC_OLD
) {
6837 if (!parse_btype(&pt
, &ad1
)) {
6839 error("invalid type");
6846 if ((pt
.t
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
6848 type_decl(&pt
, &ad1
, &n
, TYPE_DIRECT
| TYPE_ABSTRACT
);
6849 if ((pt
.t
& VT_BTYPE
) == VT_VOID
)
6850 error("parameter declared as void");
6857 convert_parameter_type(&pt
);
6858 s
= sym_push(n
| SYM_FIELD
, &pt
, 0, 0);
6863 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
6870 /* if no parameters, then old type prototype */
6874 t1
= type
->t
& VT_STORAGE
;
6875 /* NOTE: const is ignored in returned type as it has a special
6876 meaning in gcc / C++ */
6877 type
->t
&= ~(VT_STORAGE
| VT_CONSTANT
);
6878 post_type(type
, ad
);
6879 /* we push a anonymous symbol which will contain the function prototype */
6880 s
= sym_push(SYM_FIELD
, type
, ad
->func_call
, l
);
6882 type
->t
= t1
| VT_FUNC
;
6884 } else if (tok
== '[') {
6885 /* array definition */
6891 error("invalid array size");
6894 /* parse next post type */
6895 t1
= type
->t
& VT_STORAGE
;
6896 type
->t
&= ~VT_STORAGE
;
6897 post_type(type
, ad
);
6899 /* we push a anonymous symbol which will contain the array
6901 s
= sym_push(SYM_FIELD
, type
, 0, n
);
6902 type
->t
= t1
| VT_ARRAY
| VT_PTR
;
6907 /* Parse a type declaration (except basic type), and return the type
6908 in 'type'. 'td' is a bitmask indicating which kind of type decl is
6909 expected. 'type' should contain the basic type. 'ad' is the
6910 attribute definition of the basic type. It can be modified by
6913 static void type_decl(CType
*type
, AttributeDef
*ad
, int *v
, int td
)
6916 CType type1
, *type2
;
6919 while (tok
== '*') {
6927 qualifiers
|= VT_CONSTANT
;
6932 qualifiers
|= VT_VOLATILE
;
6940 type
->t
|= qualifiers
;
6943 /* XXX: clarify attribute handling */
6944 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6945 parse_attribute(ad
);
6947 /* recursive type */
6948 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
6949 type1
.t
= 0; /* XXX: same as int */
6952 /* XXX: this is not correct to modify 'ad' at this point, but
6953 the syntax is not clear */
6954 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6955 parse_attribute(ad
);
6956 type_decl(&type1
, ad
, v
, td
);
6959 /* type identifier */
6960 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
6964 if (!(td
& TYPE_ABSTRACT
))
6965 expect("identifier");
6969 post_type(type
, ad
);
6970 if (tok
== TOK_ATTRIBUTE1
|| tok
== TOK_ATTRIBUTE2
)
6971 parse_attribute(ad
);
6974 /* append type at the end of type1 */
6987 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
6988 static int lvalue_type(int t
)
6993 if (bt
== VT_BYTE
|| bt
== VT_BOOL
)
6995 else if (bt
== VT_SHORT
)
6999 if (t
& VT_UNSIGNED
)
7000 r
|= VT_LVAL_UNSIGNED
;
7004 /* indirection with full error checking and bound check */
7005 static void indir(void)
7007 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
7009 if ((vtop
->r
& VT_LVAL
) && !nocode_wanted
)
7011 vtop
->type
= *pointed_type(&vtop
->type
);
7012 /* an array is never an lvalue */
7013 if (!(vtop
->type
.t
& VT_ARRAY
)) {
7014 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7015 /* if bound checking, the referenced pointer must be checked */
7016 if (do_bounds_check
)
7017 vtop
->r
|= VT_MUSTBOUND
;
7021 /* pass a parameter to a function and do type checking and casting */
7022 static void gfunc_param_typed(Sym
*func
, Sym
*arg
)
7027 func_type
= func
->c
;
7028 if (func_type
== FUNC_OLD
||
7029 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
7030 /* default casting : only need to convert float to double */
7031 if ((vtop
->type
.t
& VT_BTYPE
) == VT_FLOAT
) {
7035 } else if (arg
== NULL
) {
7036 error("too many arguments to function");
7039 type
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
7040 gen_assign_cast(&type
);
7044 /* parse an expression of the form '(type)' or '(expr)' and return its
7046 static void parse_expr_type(CType
*type
)
7052 if (parse_btype(type
, &ad
)) {
7053 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7060 static void parse_type(CType
*type
)
7065 if (!parse_btype(type
, &ad
)) {
7068 type_decl(type
, &ad
, &n
, TYPE_ABSTRACT
);
7071 static void vpush_tokc(int t
)
7075 vsetc(&type
, VT_CONST
, &tokc
);
7078 static void unary(void)
7080 int n
, t
, align
, size
, r
;
7085 /* XXX: GCC 2.95.3 does not generate a table although it should be
7099 vpush_tokc(VT_INT
| VT_UNSIGNED
);
7103 vpush_tokc(VT_LLONG
);
7107 vpush_tokc(VT_LLONG
| VT_UNSIGNED
);
7111 vpush_tokc(VT_FLOAT
);
7115 vpush_tokc(VT_DOUBLE
);
7119 vpush_tokc(VT_LDOUBLE
);
7122 case TOK___FUNCTION__
:
7124 goto tok_identifier
;
7130 /* special function name identifier */
7131 len
= strlen(funcname
) + 1;
7132 /* generate char[len] type */
7137 vpush_ref(&type
, data_section
, data_section
->data_offset
, len
);
7138 ptr
= section_ptr_add(data_section
, len
);
7139 memcpy(ptr
, funcname
, len
);
7144 #ifdef TCC_TARGET_PE
7145 t
= VT_SHORT
| VT_UNSIGNED
;
7151 /* string parsing */
7154 if (tcc_state
->warn_write_strings
)
7159 memset(&ad
, 0, sizeof(AttributeDef
));
7160 decl_initializer_alloc(&type
, &ad
, VT_CONST
, 2, 0, 0);
7165 if (parse_btype(&type
, &ad
)) {
7166 type_decl(&type
, &ad
, &n
, TYPE_ABSTRACT
);
7168 /* check ISOC99 compound literal */
7170 /* data is allocated locally by default */
7175 /* all except arrays are lvalues */
7176 if (!(type
.t
& VT_ARRAY
))
7177 r
|= lvalue_type(type
.t
);
7178 memset(&ad
, 0, sizeof(AttributeDef
));
7179 decl_initializer_alloc(&type
, &ad
, r
, 1, 0, 0);
7184 } else if (tok
== '{') {
7185 /* save all registers */
7187 /* statement expression : we do not accept break/continue
7188 inside as GCC does */
7189 block(NULL
, NULL
, NULL
, NULL
, 0, 1);
7204 /* functions names must be treated as function pointers,
7205 except for unary '&' and sizeof. Since we consider that
7206 functions are not lvalues, we only have to handle it
7207 there and in function calls. */
7208 /* arrays can also be used although they are not lvalues */
7209 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
&&
7210 !(vtop
->type
.t
& VT_ARRAY
))
7212 mk_pointer(&vtop
->type
);
7218 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
)
7219 vtop
->c
.i
= !vtop
->c
.i
;
7220 else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
7221 vtop
->c
.i
= vtop
->c
.i
^ 1;
7223 vseti(VT_JMP
, gtst(1, 0));
7233 /* in order to force cast, we add zero */
7235 if ((vtop
->type
.t
& VT_BTYPE
) == VT_PTR
)
7236 error("pointer not accepted for unary plus");
7246 parse_expr_type(&type
);
7250 size
= type_size(&type
, &align
);
7251 if (t
== TOK_SIZEOF
) {
7253 error("sizeof applied to an incomplete type");
7260 case TOK_builtin_types_compatible_p
:
7269 type1
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7270 type2
.t
&= ~(VT_CONSTANT
| VT_VOLATILE
);
7271 vpushi(is_compatible_types(&type1
, &type2
));
7274 case TOK_builtin_constant_p
:
7276 int saved_nocode_wanted
, res
;
7279 saved_nocode_wanted
= nocode_wanted
;
7282 res
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
7284 nocode_wanted
= saved_nocode_wanted
;
7304 goto tok_identifier
;
7306 /* allow to take the address of a label */
7307 if (tok
< TOK_UIDENT
)
7308 expect("label identifier");
7309 s
= label_find(tok
);
7311 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
7313 if (s
->r
== LABEL_DECLARED
)
7314 s
->r
= LABEL_FORWARD
;
7317 s
->type
.t
= VT_VOID
;
7318 mk_pointer(&s
->type
);
7319 s
->type
.t
|= VT_STATIC
;
7321 vset(&s
->type
, VT_CONST
| VT_SYM
, 0);
7330 expect("identifier");
7334 error("'%s' undeclared", get_tok_str(t
, NULL
));
7335 /* for simple function calls, we tolerate undeclared
7336 external reference to int() function */
7337 if (tcc_state
->warn_implicit_function_declaration
)
7338 warning("implicit declaration of function '%s'",
7339 get_tok_str(t
, NULL
));
7340 s
= external_global_sym(t
, &func_old_type
, 0);
7342 if ((s
->type
.t
& (VT_STATIC
| VT_INLINE
| VT_BTYPE
)) ==
7343 (VT_STATIC
| VT_INLINE
| VT_FUNC
)) {
7344 /* if referencing an inline function, then we generate a
7345 symbol to it if not already done. It will have the
7346 effect to generate code for it at the end of the
7347 compilation unit. Inline function as always
7348 generated in the text section. */
7350 put_extern_sym(s
, text_section
, 0, 0);
7351 r
= VT_SYM
| VT_CONST
;
7355 vset(&s
->type
, r
, s
->c
);
7356 /* if forward reference, we must point to s */
7357 if (vtop
->r
& VT_SYM
) {
7364 /* post operations */
7366 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
7369 } else if (tok
== '.' || tok
== TOK_ARROW
) {
7371 if (tok
== TOK_ARROW
)
7376 /* expect pointer on structure */
7377 if ((vtop
->type
.t
& VT_BTYPE
) != VT_STRUCT
)
7378 expect("struct or union");
7382 while ((s
= s
->next
) != NULL
) {
7387 error("field not found");
7388 /* add field offset to pointer */
7389 vtop
->type
= char_pointer_type
; /* change type to 'char *' */
7392 /* change type to field type, and set to lvalue */
7393 vtop
->type
= s
->type
;
7394 /* an array is never an lvalue */
7395 if (!(vtop
->type
.t
& VT_ARRAY
)) {
7396 vtop
->r
|= lvalue_type(vtop
->type
.t
);
7397 /* if bound checking, the referenced pointer must be checked */
7398 if (do_bounds_check
)
7399 vtop
->r
|= VT_MUSTBOUND
;
7402 } else if (tok
== '[') {
7408 } else if (tok
== '(') {
7414 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
) {
7415 /* pointer test (no array accepted) */
7416 if ((vtop
->type
.t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
7417 vtop
->type
= *pointed_type(&vtop
->type
);
7418 if ((vtop
->type
.t
& VT_BTYPE
) != VT_FUNC
)
7422 expect("function pointer");
7425 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
7427 /* get return type */
7430 sa
= s
->next
; /* first parameter */
7432 /* compute first implicit argument if a structure is returned */
7433 if ((s
->type
.t
& VT_BTYPE
) == VT_STRUCT
) {
7434 /* get some space for the returned structure */
7435 size
= type_size(&s
->type
, &align
);
7436 loc
= (loc
- size
) & -align
;
7438 ret
.r
= VT_LOCAL
| VT_LVAL
;
7439 /* pass it as 'int' to avoid structure arg passing
7441 vseti(VT_LOCAL
, loc
);
7447 /* return in register */
7448 if (is_float(ret
.type
.t
)) {
7451 if ((ret
.type
.t
& VT_BTYPE
) == VT_LLONG
)
7460 gfunc_param_typed(s
, sa
);
7470 error("too few arguments to function");
7472 if (!nocode_wanted
) {
7473 gfunc_call(nb_args
);
7475 vtop
-= (nb_args
+ 1);
7478 vsetc(&ret
.type
, ret
.r
, &ret
.c
);
7486 static void uneq(void)
7492 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
7493 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
7494 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
7509 static void expr_prod(void)
7514 while (tok
== '*' || tok
== '/' || tok
== '%') {
7522 static void expr_sum(void)
7527 while (tok
== '+' || tok
== '-') {
7535 static void expr_shift(void)
7540 while (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
7548 static void expr_cmp(void)
7553 while ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
7554 tok
== TOK_ULT
|| tok
== TOK_UGE
) {
7562 static void expr_cmpeq(void)
7567 while (tok
== TOK_EQ
|| tok
== TOK_NE
) {
7575 static void expr_and(void)
7578 while (tok
== '&') {
7585 static void expr_xor(void)
7588 while (tok
== '^') {
7595 static void expr_or(void)
7598 while (tok
== '|') {
7605 /* XXX: fix this mess */
7606 static void expr_land_const(void)
7609 while (tok
== TOK_LAND
) {
7616 /* XXX: fix this mess */
7617 static void expr_lor_const(void)
7620 while (tok
== TOK_LOR
) {
7627 /* only used if non constant */
7628 static void expr_land(void)
7633 if (tok
== TOK_LAND
) {
7637 if (tok
!= TOK_LAND
) {
7647 static void expr_lor(void)
7652 if (tok
== TOK_LOR
) {
7656 if (tok
!= TOK_LOR
) {
7666 /* XXX: better constant handling */
7667 static void expr_eq(void)
7669 int tt
, u
, r1
, r2
, rc
, t1
, t2
, bt1
, bt2
;
7671 CType type
, type1
, type2
;
7680 if (tok
== ':' && gnu_ext
) {
7696 if (vtop
!= vstack
) {
7697 /* needed to avoid having different registers saved in
7699 if (is_float(vtop
->type
.t
))
7706 if (tok
== ':' && gnu_ext
) {
7714 sv
= *vtop
; /* save value to handle it later */
7715 vtop
--; /* no vpop so that FP stack is not flushed */
7723 bt1
= t1
& VT_BTYPE
;
7725 bt2
= t2
& VT_BTYPE
;
7726 /* cast operands to correct type according to ISOC rules */
7727 if (is_float(bt1
) || is_float(bt2
)) {
7728 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
7729 type
.t
= VT_LDOUBLE
;
7730 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
7735 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
7736 /* cast to biggest op */
7738 /* convert to unsigned if it does not fit in a long long */
7739 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
7740 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
7741 type
.t
|= VT_UNSIGNED
;
7742 } else if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
7743 /* XXX: test pointer compatibility */
7745 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
7746 /* XXX: test structure compatibility */
7748 } else if (bt1
== VT_VOID
|| bt2
== VT_VOID
) {
7749 /* NOTE: as an extension, we accept void on only one side */
7752 /* integer operations */
7754 /* convert to unsigned if it does not fit in an integer */
7755 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
7756 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
7757 type
.t
|= VT_UNSIGNED
;
7760 /* now we convert second operand */
7763 if (is_float(type
.t
)) {
7765 } else if ((type
.t
& VT_BTYPE
) == VT_LLONG
) {
7766 /* for long longs, we use fixed registers to avoid having
7767 to handle a complicated move */
7772 /* this is horrible, but we must also convert first
7776 /* put again first value and cast it */
7787 static void gexpr(void)
7798 /* parse an expression and return its type without any side effect. */
7799 static void expr_type(CType
*type
)
7801 int saved_nocode_wanted
;
7803 saved_nocode_wanted
= nocode_wanted
;
7808 nocode_wanted
= saved_nocode_wanted
;
7811 /* parse a unary expression and return its type without any side
7813 static void unary_type(CType
*type
)
7825 /* parse a constant expression and return value in vtop. */
7826 static void expr_const1(void)
7835 /* parse an integer constant and return its value. */
7836 static int expr_const(void)
7840 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
7841 expect("constant expression");
7847 /* return the label token if current token is a label, otherwise
7849 static int is_label(void)
7853 /* fast test first */
7854 if (tok
< TOK_UIDENT
)
7856 /* no need to save tokc because tok is an identifier */
7863 unget_tok(last_tok
);
7868 static void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
,
7869 int case_reg
, int is_expr
)
7874 /* generate line number info */
7876 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
7877 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
7879 last_line_num
= file
->line_num
;
7883 /* default return value is (void) */
7885 vtop
->type
.t
= VT_VOID
;
7888 if (tok
== TOK_IF
) {
7895 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7897 if (c
== TOK_ELSE
) {
7901 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, 0);
7902 gsym(d
); /* patch else jmp */
7905 } else if (tok
== TOK_WHILE
) {
7913 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
7917 } else if (tok
== '{') {
7921 /* record local declaration stack position */
7923 llabel
= local_label_stack
;
7924 /* handle local labels declarations */
7925 if (tok
== TOK_LABEL
) {
7928 if (tok
< TOK_UIDENT
)
7929 expect("label identifier");
7930 label_push(&local_label_stack
, tok
, LABEL_DECLARED
);
7940 while (tok
!= '}') {
7945 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
7948 /* pop locally defined labels */
7949 label_pop(&local_label_stack
, llabel
);
7950 /* pop locally defined symbols */
7951 sym_pop(&local_stack
, s
);
7953 } else if (tok
== TOK_RETURN
) {
7957 gen_assign_cast(&func_vt
);
7958 if ((func_vt
.t
& VT_BTYPE
) == VT_STRUCT
) {
7960 /* if returning structure, must copy it to implicit
7961 first pointer arg location */
7964 vset(&type
, VT_LOCAL
| VT_LVAL
, func_vc
);
7967 /* copy structure value to pointer */
7969 } else if (is_float(func_vt
.t
)) {
7974 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
7977 rsym
= gjmp(rsym
); /* jmp */
7978 } else if (tok
== TOK_BREAK
) {
7981 error("cannot break");
7982 *bsym
= gjmp(*bsym
);
7985 } else if (tok
== TOK_CONTINUE
) {
7988 error("cannot continue");
7989 *csym
= gjmp(*csym
);
7992 } else if (tok
== TOK_FOR
) {
8019 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8024 if (tok
== TOK_DO
) {
8029 block(&a
, &b
, case_sym
, def_sym
, case_reg
, 0);
8040 if (tok
== TOK_SWITCH
) {
8044 /* XXX: other types than integer */
8045 case_reg
= gv(RC_INT
);
8049 b
= gjmp(0); /* jump to first case */
8051 block(&a
, csym
, &b
, &c
, case_reg
, 0);
8052 /* if no default, jmp after switch */
8060 if (tok
== TOK_CASE
) {
8067 if (gnu_ext
&& tok
== TOK_DOTS
) {
8071 warning("empty case range");
8073 /* since a case is like a label, we must skip it with a jmp */
8080 *case_sym
= gtst(1, 0);
8083 *case_sym
= gtst(1, 0);
8087 *case_sym
= gtst(1, *case_sym
);
8092 goto block_after_label
;
8094 if (tok
== TOK_DEFAULT
) {
8100 error("too many 'default'");
8103 goto block_after_label
;
8105 if (tok
== TOK_GOTO
) {
8107 if (tok
== '*' && gnu_ext
) {
8111 if ((vtop
->type
.t
& VT_BTYPE
) != VT_PTR
)
8114 } else if (tok
>= TOK_UIDENT
) {
8115 s
= label_find(tok
);
8116 /* put forward definition if needed */
8118 s
= label_push(&global_label_stack
, tok
, LABEL_FORWARD
);
8120 if (s
->r
== LABEL_DECLARED
)
8121 s
->r
= LABEL_FORWARD
;
8123 /* label already defined */
8124 if (s
->r
& LABEL_FORWARD
)
8125 s
->next
= (void *)gjmp((long)s
->next
);
8127 gjmp_addr((long)s
->next
);
8130 expect("label identifier");
8133 } else if (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
) {
8141 if (s
->r
== LABEL_DEFINED
)
8142 error("duplicate label '%s'", get_tok_str(s
->v
, NULL
));
8143 gsym((long)s
->next
);
8144 s
->r
= LABEL_DEFINED
;
8146 s
= label_push(&global_label_stack
, b
, LABEL_DEFINED
);
8148 s
->next
= (void *)ind
;
8149 /* we accept this, but it is a mistake */
8152 warning("deprecated use of label at end of compound statement");
8156 block(bsym
, csym
, case_sym
, def_sym
, case_reg
, is_expr
);
8159 /* expression case */
8174 /* t is the array or struct type. c is the array or struct
8175 address. cur_index/cur_field is the pointer to the current
8176 value. 'size_only' is true if only size info is needed (only used
8178 static void decl_designator(CType
*type
, Section
*sec
, unsigned long c
,
8179 int *cur_index
, Sym
**cur_field
,
8183 int notfirst
, index
, index_last
, align
, l
, nb_elems
, elem_size
;
8189 if (gnu_ext
&& (l
= is_label()) != 0)
8191 while (tok
== '[' || tok
== '.') {
8193 if (!(type
->t
& VT_ARRAY
))
8194 expect("array type");
8197 index
= expr_const();
8198 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
8199 expect("invalid index");
8200 if (tok
== TOK_DOTS
&& gnu_ext
) {
8202 index_last
= expr_const();
8203 if (index_last
< 0 ||
8204 (s
->c
>= 0 && index_last
>= s
->c
) ||
8206 expect("invalid index");
8212 *cur_index
= index_last
;
8213 type
= pointed_type(type
);
8214 elem_size
= type_size(type
, &align
);
8215 c
+= index
* elem_size
;
8216 /* NOTE: we only support ranges for last designator */
8217 nb_elems
= index_last
- index
+ 1;
8218 if (nb_elems
!= 1) {
8227 if ((type
->t
& VT_BTYPE
) != VT_STRUCT
)
8228 expect("struct/union type");
8241 /* XXX: fix this mess by using explicit storage field */
8243 type1
.t
|= (type
->t
& ~VT_TYPE
);
8257 if (type
->t
& VT_ARRAY
) {
8259 type
= pointed_type(type
);
8260 c
+= index
* type_size(type
, &align
);
8264 error("too many field init");
8265 /* XXX: fix this mess by using explicit storage field */
8267 type1
.t
|= (type
->t
& ~VT_TYPE
);
8272 decl_initializer(type
, sec
, c
, 0, size_only
);
8274 /* XXX: make it more general */
8275 if (!size_only
&& nb_elems
> 1) {
8276 unsigned long c_end
;
8281 error("range init not supported yet for dynamic storage");
8282 c_end
= c
+ nb_elems
* elem_size
;
8283 if (c_end
> sec
->data_allocated
)
8284 section_realloc(sec
, c_end
);
8285 src
= sec
->data
+ c
;
8287 for(i
= 1; i
< nb_elems
; i
++) {
8289 memcpy(dst
, src
, elem_size
);
8295 #define EXPR_CONST 1
8298 /* store a value or an expression directly in global data or in local array */
8299 static void init_putv(CType
*type
, Section
*sec
, unsigned long c
,
8300 int v
, int expr_type
)
8302 int saved_global_expr
, bt
, bit_pos
, bit_size
;
8304 unsigned long long bit_mask
;
8312 /* compound literals must be allocated globally in this case */
8313 saved_global_expr
= global_expr
;
8316 global_expr
= saved_global_expr
;
8317 /* NOTE: symbols are accepted */
8318 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
8319 error("initializer element is not constant");
8327 dtype
.t
&= ~VT_CONSTANT
; /* need to do that to avoid false warning */
8330 /* XXX: not portable */
8331 /* XXX: generate error if incorrect relocation */
8332 gen_assign_cast(&dtype
);
8333 bt
= type
->t
& VT_BTYPE
;
8334 ptr
= sec
->data
+ c
;
8335 /* XXX: make code faster ? */
8336 if (!(type
->t
& VT_BITFIELD
)) {
8341 bit_pos
= (vtop
->type
.t
>> VT_STRUCT_SHIFT
) & 0x3f;
8342 bit_size
= (vtop
->type
.t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
8343 bit_mask
= (1LL << bit_size
) - 1;
8345 if ((vtop
->r
& VT_SYM
) &&
8351 (bt
== VT_INT
&& bit_size
!= 32)))
8352 error("initializer element is not computable at load time");
8355 *(char *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8358 *(short *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8361 *(double *)ptr
= vtop
->c
.d
;
8364 *(long double *)ptr
= vtop
->c
.ld
;
8367 *(long long *)ptr
|= (vtop
->c
.ll
& bit_mask
) << bit_pos
;
8370 if (vtop
->r
& VT_SYM
) {
8371 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
8373 *(int *)ptr
|= (vtop
->c
.i
& bit_mask
) << bit_pos
;
8378 vset(&dtype
, VT_LOCAL
, c
);
8385 /* put zeros for variable based init */
8386 static void init_putz(CType
*t
, Section
*sec
, unsigned long c
, int size
)
8389 /* nothing to do because globals are already set to zero */
8391 vpush_global_sym(&func_old_type
, TOK_memset
);
8399 /* 't' contains the type and storage info. 'c' is the offset of the
8400 object in section 'sec'. If 'sec' is NULL, it means stack based
8401 allocation. 'first' is true if array '{' must be read (multi
8402 dimension implicit array init handling). 'size_only' is true if
8403 size only evaluation is wanted (only for arrays). */
8404 static void decl_initializer(CType
*type
, Section
*sec
, unsigned long c
,
8405 int first
, int size_only
)
8407 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
8408 int size1
, align1
, expr_type
;
8412 if (type
->t
& VT_ARRAY
) {
8416 t1
= pointed_type(type
);
8417 size1
= type_size(t1
, &align1
);
8420 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
8426 /* only parse strings here if correct type (otherwise: handle
8427 them as ((w)char *) expressions */
8428 if ((tok
== TOK_LSTR
&&
8429 #ifdef TCC_TARGET_PE
8430 (t1
->t
& VT_BTYPE
) == VT_SHORT
&& (t1
->t
& VT_UNSIGNED
)) ||
8432 (t1
->t
& VT_BTYPE
) == VT_INT
) ||
8435 (t1
->t
& VT_BTYPE
) == VT_BYTE
)) {
8436 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8441 /* compute maximum number of chars wanted */
8443 cstr_len
= cstr
->size
;
8445 cstr_len
= cstr
->size
/ sizeof(nwchar_t
);
8448 if (n
>= 0 && nb
> (n
- array_length
))
8449 nb
= n
- array_length
;
8452 warning("initializer-string for array is too long");
8453 /* in order to go faster for common case (char
8454 string in global variable, we handle it
8456 if (sec
&& tok
== TOK_STR
&& size1
== 1) {
8457 memcpy(sec
->data
+ c
+ array_length
, cstr
->data
, nb
);
8461 ch
= ((unsigned char *)cstr
->data
)[i
];
8463 ch
= ((nwchar_t
*)cstr
->data
)[i
];
8464 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
8472 /* only add trailing zero if enough storage (no
8473 warning in this case since it is standard) */
8474 if (n
< 0 || array_length
< n
) {
8476 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
8482 while (tok
!= '}') {
8483 decl_designator(type
, sec
, c
, &index
, NULL
, size_only
);
8484 if (n
>= 0 && index
>= n
)
8485 error("index too large");
8486 /* must put zero in holes (note that doing it that way
8487 ensures that it even works with designators) */
8488 if (!size_only
&& array_length
< index
) {
8489 init_putz(t1
, sec
, c
+ array_length
* size1
,
8490 (index
- array_length
) * size1
);
8493 if (index
> array_length
)
8494 array_length
= index
;
8495 /* special test for multi dimensional arrays (may not
8496 be strictly correct if designators are used at the
8498 if (index
>= n
&& no_oblock
)
8507 /* put zeros at the end */
8508 if (!size_only
&& n
>= 0 && array_length
< n
) {
8509 init_putz(t1
, sec
, c
+ array_length
* size1
,
8510 (n
- array_length
) * size1
);
8512 /* patch type size if needed */
8514 s
->c
= array_length
;
8515 } else if ((type
->t
& VT_BTYPE
) == VT_STRUCT
&&
8516 (sec
|| !first
|| tok
== '{')) {
8519 /* NOTE: the previous test is a specific case for automatic
8520 struct/union init */
8521 /* XXX: union needs only one init */
8523 /* XXX: this test is incorrect for local initializers
8524 beginning with ( without {. It would be much more difficult
8525 to do it correctly (ideally, the expression parser should
8526 be used in all cases) */
8532 while (tok
== '(') {
8536 if (!parse_btype(&type1
, &ad1
))
8538 type_decl(&type1
, &ad1
, &n
, TYPE_ABSTRACT
);
8540 if (!is_assignable_types(type
, &type1
))
8541 error("invalid type for cast");
8546 if (first
|| tok
== '{') {
8555 while (tok
!= '}') {
8556 decl_designator(type
, sec
, c
, NULL
, &f
, size_only
);
8558 if (!size_only
&& array_length
< index
) {
8559 init_putz(type
, sec
, c
+ array_length
,
8560 index
- array_length
);
8562 index
= index
+ type_size(&f
->type
, &align1
);
8563 if (index
> array_length
)
8564 array_length
= index
;
8566 if (no_oblock
&& f
== NULL
)
8572 /* put zeros at the end */
8573 if (!size_only
&& array_length
< n
) {
8574 init_putz(type
, sec
, c
+ array_length
,
8583 } else if (tok
== '{') {
8585 decl_initializer(type
, sec
, c
, first
, size_only
);
8587 } else if (size_only
) {
8588 /* just skip expression */
8590 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
8594 else if (tok
== ')')
8599 /* currently, we always use constant expression for globals
8600 (may change for scripting case) */
8601 expr_type
= EXPR_CONST
;
8603 expr_type
= EXPR_ANY
;
8604 init_putv(type
, sec
, c
, 0, expr_type
);
8608 /* parse an initializer for type 't' if 'has_init' is non zero, and
8609 allocate space in local or global data space ('r' is either
8610 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
8611 variable 'v' of scope 'scope' is declared before initializers are
8612 parsed. If 'v' is zero, then a reference to the new object is put
8613 in the value stack. If 'has_init' is 2, a special parsing is done
8614 to handle string constants. */
8615 static void decl_initializer_alloc(CType
*type
, AttributeDef
*ad
, int r
,
8616 int has_init
, int v
, int scope
)
8618 int size
, align
, addr
, data_offset
;
8620 ParseState saved_parse_state
;
8621 TokenString init_str
;
8624 size
= type_size(type
, &align
);
8625 /* If unknown size, we must evaluate it before
8626 evaluating initializers because
8627 initializers can generate global data too
8628 (e.g. string pointers or ISOC99 compound
8629 literals). It also simplifies local
8630 initializers handling */
8631 tok_str_new(&init_str
);
8634 error("unknown type size");
8635 /* get all init string */
8636 if (has_init
== 2) {
8637 /* only get strings */
8638 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
8639 tok_str_add_tok(&init_str
);
8644 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
8646 error("unexpected end of file in initializer");
8647 tok_str_add_tok(&init_str
);
8650 else if (tok
== '}') {
8658 tok_str_add(&init_str
, -1);
8659 tok_str_add(&init_str
, 0);
8662 save_parse_state(&saved_parse_state
);
8664 macro_ptr
= init_str
.str
;
8666 decl_initializer(type
, NULL
, 0, 1, 1);
8667 /* prepare second initializer parsing */
8668 macro_ptr
= init_str
.str
;
8671 /* if still unknown size, error */
8672 size
= type_size(type
, &align
);
8674 error("unknown type size");
8676 /* take into account specified alignment if bigger */
8678 if (ad
->aligned
> align
)
8679 align
= ad
->aligned
;
8680 } else if (ad
->packed
) {
8683 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
8685 if (do_bounds_check
&& (type
->t
& VT_ARRAY
))
8687 loc
= (loc
- size
) & -align
;
8689 /* handles bounds */
8690 /* XXX: currently, since we do only one pass, we cannot track
8691 '&' operators, so we add only arrays */
8692 if (do_bounds_check
&& (type
->t
& VT_ARRAY
)) {
8693 unsigned long *bounds_ptr
;
8694 /* add padding between regions */
8696 /* then add local bound info */
8697 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
8698 bounds_ptr
[0] = addr
;
8699 bounds_ptr
[1] = size
;
8702 /* local variable */
8703 sym_push(v
, type
, r
, addr
);
8705 /* push local reference */
8706 vset(type
, r
, addr
);
8712 if (v
&& scope
== VT_CONST
) {
8713 /* see if the symbol was already defined */
8716 if (!is_compatible_types(&sym
->type
, type
))
8717 error("incompatible types for redefinition of '%s'",
8718 get_tok_str(v
, NULL
));
8719 if (sym
->type
.t
& VT_EXTERN
) {
8720 /* if the variable is extern, it was not allocated */
8721 sym
->type
.t
&= ~VT_EXTERN
;
8722 /* set array size if it was ommited in extern
8724 if ((sym
->type
.t
& VT_ARRAY
) &&
8725 sym
->type
.ref
->c
< 0 &&
8727 sym
->type
.ref
->c
= type
->ref
->c
;
8729 /* we accept several definitions of the same
8730 global variable. this is tricky, because we
8731 must play with the SHN_COMMON type of the symbol */
8732 /* XXX: should check if the variable was already
8733 initialized. It is incorrect to initialized it
8735 /* no init data, we won't add more to the symbol */
8742 /* allocate symbol in corresponding section */
8747 else if (tcc_state
->nocommon
)
8751 data_offset
= sec
->data_offset
;
8752 data_offset
= (data_offset
+ align
- 1) & -align
;
8754 /* very important to increment global pointer at this time
8755 because initializers themselves can create new initializers */
8756 data_offset
+= size
;
8757 /* add padding if bound check */
8758 if (do_bounds_check
)
8760 sec
->data_offset
= data_offset
;
8761 /* allocate section space to put the data */
8762 if (sec
->sh_type
!= SHT_NOBITS
&&
8763 data_offset
> sec
->data_allocated
)
8764 section_realloc(sec
, data_offset
);
8765 /* align section if needed */
8766 if (align
> sec
->sh_addralign
)
8767 sec
->sh_addralign
= align
;
8769 addr
= 0; /* avoid warning */
8773 if (scope
== VT_CONST
) {
8778 sym
= sym_push(v
, type
, r
| VT_SYM
, 0);
8780 /* update symbol definition */
8782 put_extern_sym(sym
, sec
, addr
, size
);
8785 /* put a common area */
8786 put_extern_sym(sym
, NULL
, align
, size
);
8787 /* XXX: find a nicer way */
8788 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
8789 esym
->st_shndx
= SHN_COMMON
;
8794 /* push global reference */
8795 sym
= get_sym_ref(type
, sec
, addr
, size
);
8797 vsetc(type
, VT_CONST
| VT_SYM
, &cval
);
8801 /* handles bounds now because the symbol must be defined
8802 before for the relocation */
8803 if (do_bounds_check
) {
8804 unsigned long *bounds_ptr
;
8806 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
8807 /* then add global bound info */
8808 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
8809 bounds_ptr
[0] = 0; /* relocated */
8810 bounds_ptr
[1] = size
;
8814 decl_initializer(type
, sec
, addr
, 1, 0);
8815 /* restore parse state if needed */
8817 tok_str_free(init_str
.str
);
8818 restore_parse_state(&saved_parse_state
);
8824 void put_func_debug(Sym
*sym
)
8829 /* XXX: we put here a dummy type */
8830 snprintf(buf
, sizeof(buf
), "%s:%c1",
8831 funcname
, sym
->type
.t
& VT_STATIC
? 'f' : 'F');
8832 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
8833 cur_text_section
, sym
->c
);
8838 /* parse an old style function declaration list */
8839 /* XXX: check multiple parameter */
8840 static void func_decl_list(Sym
*func_sym
)
8847 /* parse each declaration */
8848 while (tok
!= '{' && tok
!= ';' && tok
!= ',' && tok
!= TOK_EOF
) {
8849 if (!parse_btype(&btype
, &ad
))
8850 expect("declaration list");
8851 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8852 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8854 /* we accept no variable after */
8858 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
8859 /* find parameter in function parameter list */
8862 if ((s
->v
& ~SYM_FIELD
) == v
)
8866 error("declaration for parameter '%s' but no such parameter",
8867 get_tok_str(v
, NULL
));
8869 /* check that no storage specifier except 'register' was given */
8870 if (type
.t
& VT_STORAGE
)
8871 error("storage class specified for '%s'", get_tok_str(v
, NULL
));
8872 convert_parameter_type(&type
);
8873 /* we can add the type (NOTE: it could be local to the function) */
8875 /* accept other parameters */
8886 /* parse a function defined by symbol 'sym' and generate its code in
8887 'cur_text_section' */
8888 static void gen_function(Sym
*sym
)
8890 ind
= cur_text_section
->data_offset
;
8891 /* NOTE: we patch the symbol size later */
8892 put_extern_sym(sym
, cur_text_section
, ind
, 0);
8893 funcname
= get_tok_str(sym
->v
, NULL
);
8895 /* put debug symbol */
8897 put_func_debug(sym
);
8898 /* push a dummy symbol to enable local sym storage */
8899 sym_push2(&local_stack
, SYM_FIELD
, 0, 0);
8900 gfunc_prolog(&sym
->type
);
8902 block(NULL
, NULL
, NULL
, NULL
, 0, 0);
8905 cur_text_section
->data_offset
= ind
;
8906 label_pop(&global_label_stack
, NULL
);
8907 sym_pop(&local_stack
, NULL
); /* reset local stack */
8908 /* end of function */
8909 /* patch symbol size */
8910 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_size
=
8913 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
8915 funcname
= ""; /* for safety */
8916 func_vt
.t
= VT_VOID
; /* for safety */
8917 ind
= 0; /* for safety */
8920 static void gen_inline_functions(void)
8924 int *str
, inline_generated
;
8926 /* iterate while inline function are referenced */
8928 inline_generated
= 0;
8929 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
8931 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
8932 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
8933 (VT_STATIC
| VT_INLINE
) &&
8935 /* the function was used: generate its code and
8936 convert it to a normal function */
8937 str
= (int *)sym
->r
;
8938 sym
->r
= VT_SYM
| VT_CONST
;
8939 type
->t
&= ~VT_INLINE
;
8943 cur_text_section
= text_section
;
8945 macro_ptr
= NULL
; /* fail safe */
8948 inline_generated
= 1;
8951 if (!inline_generated
)
8955 /* free all remaining inline function tokens */
8956 for(sym
= global_stack
; sym
!= NULL
; sym
= sym
->prev
) {
8958 if (((type
->t
& VT_BTYPE
) == VT_FUNC
) &&
8959 (type
->t
& (VT_STATIC
| VT_INLINE
)) ==
8960 (VT_STATIC
| VT_INLINE
)) {
8961 str
= (int *)sym
->r
;
8963 sym
->r
= 0; /* fail safe */
8968 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
8969 static void decl(int l
)
8977 if (!parse_btype(&btype
, &ad
)) {
8978 /* skip redundant ';' */
8979 /* XXX: find more elegant solution */
8984 if (l
== VT_CONST
&&
8985 (tok
== TOK_ASM1
|| tok
== TOK_ASM2
|| tok
== TOK_ASM3
)) {
8986 /* global asm block */
8990 /* special test for old K&R protos without explicit int
8991 type. Only accepted when defining global data */
8992 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
8996 if (((btype
.t
& VT_BTYPE
) == VT_ENUM
||
8997 (btype
.t
& VT_BTYPE
) == VT_STRUCT
) &&
8999 /* we accept no variable after */
9003 while (1) { /* iterate thru each declaration */
9005 type_decl(&type
, &ad
, &v
, TYPE_DIRECT
);
9009 type_to_str(buf
, sizeof(buf
), &type
, get_tok_str(v
, NULL
));
9010 printf("type = '%s'\n", buf
);
9013 if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9014 /* if old style function prototype, we accept a
9017 if (sym
->c
== FUNC_OLD
)
9018 func_decl_list(sym
);
9023 error("cannot use local functions");
9024 if ((type
.t
& VT_BTYPE
) != VT_FUNC
)
9025 expect("function definition");
9027 /* reject abstract declarators in function definition */
9029 while ((sym
= sym
->next
) != NULL
)
9030 if (!(sym
->v
& ~SYM_FIELD
))
9031 expect("identifier");
9033 /* XXX: cannot do better now: convert extern line to static inline */
9034 if ((type
.t
& (VT_EXTERN
| VT_INLINE
)) == (VT_EXTERN
| VT_INLINE
))
9035 type
.t
= (type
.t
& ~VT_EXTERN
) | VT_STATIC
;
9039 if ((sym
->type
.t
& VT_BTYPE
) != VT_FUNC
)
9041 /* specific case: if not func_call defined, we put
9042 the one of the prototype */
9043 /* XXX: should have default value */
9044 if (sym
->type
.ref
->r
!= FUNC_CDECL
&&
9045 type
.ref
->r
== FUNC_CDECL
)
9046 type
.ref
->r
= sym
->type
.ref
->r
;
9047 if (!is_compatible_types(&sym
->type
, &type
)) {
9049 error("incompatible types for redefinition of '%s'",
9050 get_tok_str(v
, NULL
));
9052 /* if symbol is already defined, then put complete type */
9055 /* put function symbol */
9056 sym
= global_identifier_push(v
, type
.t
, 0);
9057 sym
->type
.ref
= type
.ref
;
9060 /* static inline functions are just recorded as a kind
9061 of macro. Their code will be emitted at the end of
9062 the compilation unit only if they are used */
9063 if ((type
.t
& (VT_INLINE
| VT_STATIC
)) ==
9064 (VT_INLINE
| VT_STATIC
)) {
9065 TokenString func_str
;
9068 tok_str_new(&func_str
);
9074 error("unexpected end of file");
9075 tok_str_add_tok(&func_str
);
9080 } else if (t
== '}') {
9082 if (block_level
== 0)
9086 tok_str_add(&func_str
, -1);
9087 tok_str_add(&func_str
, 0);
9088 sym
->r
= (int)func_str
.str
;
9090 /* compute text section */
9091 cur_text_section
= ad
.section
;
9092 if (!cur_text_section
)
9093 cur_text_section
= text_section
;
9094 sym
->r
= VT_SYM
| VT_CONST
;
9096 #ifdef TCC_TARGET_PE
9098 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_other
|= 1;
9104 if (btype
.t
& VT_TYPEDEF
) {
9105 /* save typedefed type */
9106 /* XXX: test storage specifiers ? */
9107 sym
= sym_push(v
, &type
, 0, 0);
9108 sym
->type
.t
|= VT_TYPEDEF
;
9109 } else if ((type
.t
& VT_BTYPE
) == VT_FUNC
) {
9110 /* external function definition */
9111 /* specific case for func_call attribute */
9113 type
.ref
->r
= ad
.func_call
;
9114 external_sym(v
, &type
, 0);
9116 /* not lvalue if array */
9118 if (!(type
.t
& VT_ARRAY
))
9119 r
|= lvalue_type(type
.t
);
9120 has_init
= (tok
== '=');
9121 if ((btype
.t
& VT_EXTERN
) ||
9122 ((type
.t
& VT_ARRAY
) && (type
.t
& VT_STATIC
) &&
9123 !has_init
&& l
== VT_CONST
&& type
.ref
->c
< 0)) {
9124 /* external variable */
9125 /* NOTE: as GCC, uninitialized global static
9126 arrays of null size are considered as
9128 external_sym(v
, &type
, r
);
9130 if (type
.t
& VT_STATIC
)
9136 decl_initializer_alloc(&type
, &ad
, r
,
9150 /* better than nothing, but needs extension to handle '-E' option
9152 static void preprocess_init(TCCState
*s1
)
9154 s1
->include_stack_ptr
= s1
->include_stack
;
9155 /* XXX: move that before to avoid having to initialize
9156 file->ifdef_stack_ptr ? */
9157 s1
->ifdef_stack_ptr
= s1
->ifdef_stack
;
9158 file
->ifdef_stack_ptr
= s1
->ifdef_stack_ptr
;
9160 /* XXX: not ANSI compliant: bound checking says error */
9162 s1
->pack_stack
[0] = 0;
9163 s1
->pack_stack_ptr
= s1
->pack_stack
;
9166 /* compile the C file opened in 'file'. Return non zero if errors. */
9167 static int tcc_compile(TCCState
*s1
)
9171 volatile int section_sym
;
9174 printf("%s: **** new file\n", file
->filename
);
9176 preprocess_init(s1
);
9179 anon_sym
= SYM_FIRST_ANOM
;
9181 /* file info: full path + filename */
9182 section_sym
= 0; /* avoid warning */
9184 section_sym
= put_elf_sym(symtab_section
, 0, 0,
9185 ELF32_ST_INFO(STB_LOCAL
, STT_SECTION
), 0,
9186 text_section
->sh_num
, NULL
);
9187 getcwd(buf
, sizeof(buf
));
9188 pstrcat(buf
, sizeof(buf
), "/");
9189 put_stabs_r(buf
, N_SO
, 0, 0,
9190 text_section
->data_offset
, text_section
, section_sym
);
9191 put_stabs_r(file
->filename
, N_SO
, 0, 0,
9192 text_section
->data_offset
, text_section
, section_sym
);
9194 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
9195 symbols can be safely used */
9196 put_elf_sym(symtab_section
, 0, 0,
9197 ELF32_ST_INFO(STB_LOCAL
, STT_FILE
), 0,
9198 SHN_ABS
, file
->filename
);
9200 /* define some often used types */
9201 int_type
.t
= VT_INT
;
9203 char_pointer_type
.t
= VT_BYTE
;
9204 mk_pointer(&char_pointer_type
);
9206 func_old_type
.t
= VT_FUNC
;
9207 func_old_type
.ref
= sym_push(SYM_FIELD
, &int_type
, FUNC_CDECL
, FUNC_OLD
);
9210 /* define 'void *alloca(unsigned int)' builtin function */
9215 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
9216 s1
= sym_push(SYM_FIELD
, VT_UNSIGNED
| VT_INT
, 0, 0);
9219 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
9223 define_start
= define_stack
;
9225 if (setjmp(s1
->error_jmp_buf
) == 0) {
9227 s1
->error_set_jmp_enabled
= 1;
9229 ch
= file
->buf_ptr
[0];
9230 tok_flags
= TOK_FLAG_BOL
| TOK_FLAG_BOF
;
9231 parse_flags
= PARSE_FLAG_PREPROCESS
| PARSE_FLAG_TOK_NUM
;
9235 expect("declaration");
9237 /* end of translation unit info */
9239 put_stabs_r(NULL
, N_SO
, 0, 0,
9240 text_section
->data_offset
, text_section
, section_sym
);
9243 s1
->error_set_jmp_enabled
= 0;
9245 /* reset define stack, but leave -Dsymbols (may be incorrect if
9246 they are undefined) */
9247 free_defines(define_start
);
9249 gen_inline_functions();
9251 sym_pop(&global_stack
, NULL
);
9253 return s1
->nb_errors
!= 0 ? -1 : 0;
9257 int tcc_compile_string(TCCState
*s
, const char *str
)
9259 BufferedFile bf1
, *bf
= &bf1
;
9263 /* init file structure */
9265 /* XXX: avoid copying */
9267 buf
= tcc_malloc(len
+ 1);
9270 memcpy(buf
, str
, len
);
9273 bf
->buf_end
= buf
+ len
;
9274 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
9278 ret
= tcc_compile(s
);
9282 /* currently, no need to close */
9287 /* define a preprocessor symbol. A value can also be provided with the '=' operator */
9288 void tcc_define_symbol(TCCState
*s1
, const char *sym
, const char *value
)
9290 BufferedFile bf1
, *bf
= &bf1
;
9292 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
9293 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
9297 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
9299 /* init file structure */
9301 bf
->buf_ptr
= bf
->buffer
;
9302 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
9303 *bf
->buf_end
= CH_EOB
;
9304 bf
->filename
[0] = '\0';
9308 s1
->include_stack_ptr
= s1
->include_stack
;
9310 /* parse with define parser */
9311 ch
= file
->buf_ptr
[0];
9317 /* undefine a preprocessor symbol */
9318 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
9322 ts
= tok_alloc(sym
, strlen(sym
));
9323 s
= define_find(ts
->tok
);
9324 /* undefine symbol by putting an invalid name */
9329 #ifdef CONFIG_TCC_ASM
9331 #ifdef TCC_TARGET_I386
9332 #include "i386-asm.c"
9337 static void asm_instr(void)
9339 error("inline asm() not supported");
9341 static void asm_global_instr(void)
9343 error("inline asm() not supported");
9349 #ifdef TCC_TARGET_COFF
9350 #include "tcccoff.c"
9353 #ifdef TCC_TARGET_PE
9357 /* print the position in the source file of PC value 'pc' by reading
9358 the stabs debug information */
9359 static void rt_printline(unsigned long wanted_pc
)
9361 Stab_Sym
*sym
, *sym_end
;
9362 char func_name
[128], last_func_name
[128];
9363 unsigned long func_addr
, last_pc
, pc
;
9364 const char *incl_files
[INCLUDE_STACK_SIZE
];
9365 int incl_index
, len
, last_line_num
, i
;
9366 const char *str
, *p
;
9368 fprintf(stderr
, "0x%08lx:", wanted_pc
);
9370 func_name
[0] = '\0';
9373 last_func_name
[0] = '\0';
9374 last_pc
= 0xffffffff;
9376 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
9377 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
9378 while (sym
< sym_end
) {
9379 switch(sym
->n_type
) {
9380 /* function start or end */
9382 if (sym
->n_strx
== 0) {
9383 /* we test if between last line and end of function */
9384 pc
= sym
->n_value
+ func_addr
;
9385 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9387 func_name
[0] = '\0';
9390 str
= stabstr_section
->data
+ sym
->n_strx
;
9391 p
= strchr(str
, ':');
9393 pstrcpy(func_name
, sizeof(func_name
), str
);
9396 if (len
> sizeof(func_name
) - 1)
9397 len
= sizeof(func_name
) - 1;
9398 memcpy(func_name
, str
, len
);
9399 func_name
[len
] = '\0';
9401 func_addr
= sym
->n_value
;
9404 /* line number info */
9406 pc
= sym
->n_value
+ func_addr
;
9407 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
9410 last_line_num
= sym
->n_desc
;
9412 strcpy(last_func_name
, func_name
);
9416 str
= stabstr_section
->data
+ sym
->n_strx
;
9418 if (incl_index
< INCLUDE_STACK_SIZE
) {
9419 incl_files
[incl_index
++] = str
;
9427 if (sym
->n_strx
== 0) {
9428 incl_index
= 0; /* end of translation unit */
9430 str
= stabstr_section
->data
+ sym
->n_strx
;
9431 /* do not add path */
9433 if (len
> 0 && str
[len
- 1] != '/')
9441 /* second pass: we try symtab symbols (no line number info) */
9444 Elf32_Sym
*sym
, *sym_end
;
9447 sym_end
= (Elf32_Sym
*)(symtab_section
->data
+ symtab_section
->data_offset
);
9448 for(sym
= (Elf32_Sym
*)symtab_section
->data
+ 1;
9451 type
= ELF32_ST_TYPE(sym
->st_info
);
9452 if (type
== STT_FUNC
) {
9453 if (wanted_pc
>= sym
->st_value
&&
9454 wanted_pc
< sym
->st_value
+ sym
->st_size
) {
9455 pstrcpy(last_func_name
, sizeof(last_func_name
),
9456 strtab_section
->data
+ sym
->st_name
);
9462 /* did not find any info: */
9463 fprintf(stderr
, " ???\n");
9466 if (last_func_name
[0] != '\0') {
9467 fprintf(stderr
, " %s()", last_func_name
);
9469 if (incl_index
> 0) {
9470 fprintf(stderr
, " (%s:%d",
9471 incl_files
[incl_index
- 1], last_line_num
);
9472 for(i
= incl_index
- 2; i
>= 0; i
--)
9473 fprintf(stderr
, ", included from %s", incl_files
[i
]);
9474 fprintf(stderr
, ")");
9476 fprintf(stderr
, "\n");
9479 #if !defined(WIN32) && !defined(CONFIG_TCCBOOT)
9483 /* fix for glibc 2.1 */
9489 /* return the PC at frame level 'level'. Return non zero if not found */
9490 static int rt_get_caller_pc(unsigned long *paddr
,
9491 ucontext_t
*uc
, int level
)
9497 #if defined(__FreeBSD__)
9498 *paddr
= uc
->uc_mcontext
.mc_eip
;
9499 #elif defined(__dietlibc__)
9500 *paddr
= uc
->uc_mcontext
.eip
;
9502 *paddr
= uc
->uc_mcontext
.gregs
[REG_EIP
];
9506 #if defined(__FreeBSD__)
9507 fp
= uc
->uc_mcontext
.mc_ebp
;
9508 #elif defined(__dietlibc__)
9509 fp
= uc
->uc_mcontext
.ebp
;
9511 fp
= uc
->uc_mcontext
.gregs
[REG_EBP
];
9513 for(i
=1;i
<level
;i
++) {
9514 /* XXX: check address validity with program info */
9515 if (fp
<= 0x1000 || fp
>= 0xc0000000)
9517 fp
= ((unsigned long *)fp
)[0];
9519 *paddr
= ((unsigned long *)fp
)[1];
9525 #warning add arch specific rt_get_caller_pc()
9527 static int rt_get_caller_pc(unsigned long *paddr
,
9528 ucontext_t
*uc
, int level
)
9534 /* emit a run time error at position 'pc' */
9535 void rt_error(ucontext_t
*uc
, const char *fmt
, ...)
9542 fprintf(stderr
, "Runtime error: ");
9543 vfprintf(stderr
, fmt
, ap
);
9544 fprintf(stderr
, "\n");
9545 for(i
=0;i
<num_callers
;i
++) {
9546 if (rt_get_caller_pc(&pc
, uc
, i
) < 0)
9549 fprintf(stderr
, "at ");
9551 fprintf(stderr
, "by ");
9558 /* signal handler for fatal errors */
9559 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
9561 ucontext_t
*uc
= puc
;
9565 switch(siginf
->si_code
) {
9568 rt_error(uc
, "division by zero");
9571 rt_error(uc
, "floating point exception");
9577 if (rt_bound_error_msg
&& *rt_bound_error_msg
)
9578 rt_error(uc
, *rt_bound_error_msg
);
9580 rt_error(uc
, "dereferencing invalid pointer");
9583 rt_error(uc
, "illegal instruction");
9586 rt_error(uc
, "abort() called");
9589 rt_error(uc
, "caught signal %d", signum
);
9596 /* do all relocations (needed before using tcc_get_symbol()) */
9597 int tcc_relocate(TCCState
*s1
)
9604 #ifdef TCC_TARGET_PE
9607 tcc_add_runtime(s1
);
9610 relocate_common_syms();
9612 tcc_add_linker_symbols(s1
);
9614 build_got_entries(s1
);
9616 /* compute relocation address : section are relocated in place. We
9617 also alloc the bss space */
9618 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9619 s
= s1
->sections
[i
];
9620 if (s
->sh_flags
& SHF_ALLOC
) {
9621 if (s
->sh_type
== SHT_NOBITS
)
9622 s
->data
= tcc_mallocz(s
->data_offset
);
9623 s
->sh_addr
= (unsigned long)s
->data
;
9627 relocate_syms(s1
, 1);
9629 if (s1
->nb_errors
!= 0)
9632 /* relocate each section */
9633 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9634 s
= s1
->sections
[i
];
9636 relocate_section(s1
, s
);
9639 /* mark executable sections as executable in memory */
9640 for(i
= 1; i
< s1
->nb_sections
; i
++) {
9641 s
= s1
->sections
[i
];
9642 if ((s
->sh_flags
& (SHF_ALLOC
| SHF_EXECINSTR
)) ==
9643 (SHF_ALLOC
| SHF_EXECINSTR
)) {
9647 VirtualProtect(s
->data
, s
->data_offset
,
9648 PAGE_EXECUTE_READWRITE
, &old_protect
);
9652 unsigned long start
, end
;
9653 start
= (unsigned long)(s
->data
) & ~(PAGESIZE
- 1);
9654 end
= (unsigned long)(s
->data
+ s
->data_offset
);
9655 end
= (end
+ PAGESIZE
- 1) & ~(PAGESIZE
- 1);
9656 mprotect((void *)start
, end
- start
,
9657 PROT_READ
| PROT_WRITE
| PROT_EXEC
);
9665 /* launch the compiled program with the given arguments */
9666 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
9668 int (*prog_main
)(int, char **);
9670 if (tcc_relocate(s1
) < 0)
9673 prog_main
= tcc_get_symbol_err(s1
, "main");
9676 #if defined(WIN32) || defined(CONFIG_TCCBOOT)
9677 error("debug mode currently not available for Windows");
9679 struct sigaction sigact
;
9680 /* install TCC signal handlers to print debug info on fatal
9682 sigact
.sa_flags
= SA_SIGINFO
| SA_RESETHAND
;
9683 sigact
.sa_sigaction
= sig_error
;
9684 sigemptyset(&sigact
.sa_mask
);
9685 sigaction(SIGFPE
, &sigact
, NULL
);
9686 sigaction(SIGILL
, &sigact
, NULL
);
9687 sigaction(SIGSEGV
, &sigact
, NULL
);
9688 sigaction(SIGBUS
, &sigact
, NULL
);
9689 sigaction(SIGABRT
, &sigact
, NULL
);
9693 #ifdef CONFIG_TCC_BCHECK
9694 if (do_bounds_check
) {
9695 void (*bound_init
)(void);
9697 /* set error function */
9698 rt_bound_error_msg
= (void *)tcc_get_symbol_err(s1
,
9699 "__bound_error_msg");
9701 /* XXX: use .init section so that it also work in binary ? */
9702 bound_init
= (void *)tcc_get_symbol_err(s1
, "__bound_init");
9706 return (*prog_main
)(argc
, argv
);
9709 TCCState
*tcc_new(void)
9716 s
= tcc_mallocz(sizeof(TCCState
));
9720 s
->output_type
= TCC_OUTPUT_MEMORY
;
9722 /* init isid table */
9724 isidnum_table
[i
] = isid(i
) || isnum(i
);
9726 /* add all tokens */
9728 memset(hash_ident
, 0, TOK_HASH_SIZE
* sizeof(TokenSym
*));
9730 tok_ident
= TOK_IDENT
;
9739 ts
= tok_alloc(p
, r
- p
- 1);
9743 /* we add dummy defines for some special macros to speed up tests
9744 and to have working defined() */
9745 define_push(TOK___LINE__
, MACRO_OBJ
, NULL
, NULL
);
9746 define_push(TOK___FILE__
, MACRO_OBJ
, NULL
, NULL
);
9747 define_push(TOK___DATE__
, MACRO_OBJ
, NULL
, NULL
);
9748 define_push(TOK___TIME__
, MACRO_OBJ
, NULL
, NULL
);
9750 /* standard defines */
9751 tcc_define_symbol(s
, "__STDC__", NULL
);
9752 #if defined(TCC_TARGET_I386)
9753 tcc_define_symbol(s
, "__i386__", NULL
);
9755 #if defined(TCC_TARGET_ARM)
9756 tcc_define_symbol(s
, "__ARM_ARCH_4__", NULL
);
9757 tcc_define_symbol(s
, "__arm_elf__", NULL
);
9758 tcc_define_symbol(s
, "__arm_elf", NULL
);
9759 tcc_define_symbol(s
, "arm_elf", NULL
);
9760 tcc_define_symbol(s
, "__arm__", NULL
);
9761 tcc_define_symbol(s
, "__arm", NULL
);
9762 tcc_define_symbol(s
, "arm", NULL
);
9763 tcc_define_symbol(s
, "__APCS_32__", NULL
);
9766 tcc_define_symbol(s
, "__linux__", NULL
);
9767 tcc_define_symbol(s
, "linux", NULL
);
9769 /* tiny C specific defines */
9770 tcc_define_symbol(s
, "__TINYC__", NULL
);
9772 /* tiny C & gcc defines */
9773 tcc_define_symbol(s
, "__SIZE_TYPE__", "unsigned int");
9774 tcc_define_symbol(s
, "__PTRDIFF_TYPE__", "int");
9775 #ifdef TCC_TARGET_PE
9776 tcc_define_symbol(s
, "__WCHAR_TYPE__", "unsigned short");
9778 tcc_define_symbol(s
, "__WCHAR_TYPE__", "int");
9781 /* default library paths */
9782 #ifdef TCC_TARGET_PE
9785 snprintf(buf
, sizeof(buf
), "%s/lib", tcc_lib_path
);
9786 tcc_add_library_path(s
, buf
);
9789 tcc_add_library_path(s
, "/usr/local/lib");
9790 tcc_add_library_path(s
, "/usr/lib");
9791 tcc_add_library_path(s
, "/lib");
9794 /* no section zero */
9795 dynarray_add((void ***)&s
->sections
, &s
->nb_sections
, NULL
);
9797 /* create standard sections */
9798 text_section
= new_section(s
, ".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
9799 data_section
= new_section(s
, ".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
9800 bss_section
= new_section(s
, ".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
9802 /* symbols are always generated for linking stage */
9803 symtab_section
= new_symtab(s
, ".symtab", SHT_SYMTAB
, 0,
9805 ".hashtab", SHF_PRIVATE
);
9806 strtab_section
= symtab_section
->link
;
9808 /* private symbol table for dynamic symbols */
9809 s
->dynsymtab_section
= new_symtab(s
, ".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
9811 ".dynhashtab", SHF_PRIVATE
);
9812 s
->alacarte_link
= 1;
9814 #ifdef CHAR_IS_UNSIGNED
9815 s
->char_is_unsigned
= 1;
9817 #if defined(TCC_TARGET_PE) && 0
9818 /* XXX: currently the PE linker is not ready to support that */
9819 s
->leading_underscore
= 1;
9824 void tcc_delete(TCCState
*s1
)
9828 /* free -D defines */
9832 n
= tok_ident
- TOK_IDENT
;
9833 for(i
= 0; i
< n
; i
++)
9834 tcc_free(table_ident
[i
]);
9835 tcc_free(table_ident
);
9837 /* free all sections */
9839 free_section(symtab_section
->hash
);
9841 free_section(s1
->dynsymtab_section
->hash
);
9842 free_section(s1
->dynsymtab_section
->link
);
9843 free_section(s1
->dynsymtab_section
);
9845 for(i
= 1; i
< s1
->nb_sections
; i
++)
9846 free_section(s1
->sections
[i
]);
9847 tcc_free(s1
->sections
);
9849 /* free loaded dlls array */
9850 for(i
= 0; i
< s1
->nb_loaded_dlls
; i
++)
9851 tcc_free(s1
->loaded_dlls
[i
]);
9852 tcc_free(s1
->loaded_dlls
);
9855 for(i
= 0; i
< s1
->nb_library_paths
; i
++)
9856 tcc_free(s1
->library_paths
[i
]);
9857 tcc_free(s1
->library_paths
);
9859 /* cached includes */
9860 for(i
= 0; i
< s1
->nb_cached_includes
; i
++)
9861 tcc_free(s1
->cached_includes
[i
]);
9862 tcc_free(s1
->cached_includes
);
9864 for(i
= 0; i
< s1
->nb_include_paths
; i
++)
9865 tcc_free(s1
->include_paths
[i
]);
9866 tcc_free(s1
->include_paths
);
9868 for(i
= 0; i
< s1
->nb_sysinclude_paths
; i
++)
9869 tcc_free(s1
->sysinclude_paths
[i
]);
9870 tcc_free(s1
->sysinclude_paths
);
9875 int tcc_add_include_path(TCCState
*s1
, const char *pathname
)
9879 pathname1
= tcc_strdup(pathname
);
9880 dynarray_add((void ***)&s1
->include_paths
, &s1
->nb_include_paths
, pathname1
);
9884 int tcc_add_sysinclude_path(TCCState
*s1
, const char *pathname
)
9888 pathname1
= tcc_strdup(pathname
);
9889 dynarray_add((void ***)&s1
->sysinclude_paths
, &s1
->nb_sysinclude_paths
, pathname1
);
9893 static int tcc_add_file_internal(TCCState
*s1
, const char *filename
, int flags
)
9895 const char *ext
, *filename1
;
9898 BufferedFile
*saved_file
;
9900 /* find source file type with extension */
9901 filename1
= strrchr(filename
, '/');
9905 filename1
= filename
;
9906 ext
= strrchr(filename1
, '.');
9912 file
= tcc_open(s1
, filename
);
9914 if (flags
& AFF_PRINT_ERROR
) {
9915 error_noabort("file '%s' not found", filename
);
9921 if (!ext
|| !strcmp(ext
, "c")) {
9922 /* C file assumed */
9923 ret
= tcc_compile(s1
);
9925 #ifdef CONFIG_TCC_ASM
9926 if (!strcmp(ext
, "S")) {
9927 /* preprocessed assembler */
9928 ret
= tcc_assemble(s1
, 1);
9929 } else if (!strcmp(ext
, "s")) {
9930 /* non preprocessed assembler */
9931 ret
= tcc_assemble(s1
, 0);
9934 #ifdef TCC_TARGET_PE
9935 if (!strcmp(ext
, "def")) {
9936 ret
= pe_load_def_file(s1
, fdopen(file
->fd
, "rb"));
9941 /* assume executable format: auto guess file type */
9942 ret
= read(fd
, &ehdr
, sizeof(ehdr
));
9943 lseek(fd
, 0, SEEK_SET
);
9945 error_noabort("could not read header");
9947 } else if (ret
!= sizeof(ehdr
)) {
9948 goto try_load_script
;
9951 if (ehdr
.e_ident
[0] == ELFMAG0
&&
9952 ehdr
.e_ident
[1] == ELFMAG1
&&
9953 ehdr
.e_ident
[2] == ELFMAG2
&&
9954 ehdr
.e_ident
[3] == ELFMAG3
) {
9955 file
->line_num
= 0; /* do not display line number if error */
9956 if (ehdr
.e_type
== ET_REL
) {
9957 ret
= tcc_load_object_file(s1
, fd
, 0);
9958 } else if (ehdr
.e_type
== ET_DYN
) {
9959 if (s1
->output_type
== TCC_OUTPUT_MEMORY
) {
9960 #ifdef TCC_TARGET_PE
9964 h
= dlopen(filename
, RTLD_GLOBAL
| RTLD_LAZY
);
9971 ret
= tcc_load_dll(s1
, fd
, filename
,
9972 (flags
& AFF_REFERENCED_DLL
) != 0);
9975 error_noabort("unrecognized ELF file");
9978 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
9979 file
->line_num
= 0; /* do not display line number if error */
9980 ret
= tcc_load_archive(s1
, fd
);
9982 #ifdef TCC_TARGET_COFF
9983 if (*(uint16_t *)(&ehdr
) == COFF_C67_MAGIC
) {
9984 ret
= tcc_load_coff(s1
, fd
);
9988 /* as GNU ld, consider it is an ld script if not recognized */
9990 ret
= tcc_load_ldscript(s1
);
9992 error_noabort("unrecognized file type");
10007 int tcc_add_file(TCCState
*s
, const char *filename
)
10009 return tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
10012 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
10016 pathname1
= tcc_strdup(pathname
);
10017 dynarray_add((void ***)&s
->library_paths
, &s
->nb_library_paths
, pathname1
);
10021 /* find and load a dll. Return non zero if not found */
10022 /* XXX: add '-rpath' option support ? */
10023 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
10028 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10029 snprintf(buf
, sizeof(buf
), "%s/%s",
10030 s
->library_paths
[i
], filename
);
10031 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
10037 /* the library name is the same as the argument of the '-l' option */
10038 int tcc_add_library(TCCState
*s
, const char *libraryname
)
10043 /* first we look for the dynamic library if not static linking */
10044 if (!s
->static_link
) {
10045 #ifdef TCC_TARGET_PE
10046 snprintf(buf
, sizeof(buf
), "%s.def", libraryname
);
10048 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
10050 if (tcc_add_dll(s
, buf
, 0) == 0)
10054 /* then we look for the static library */
10055 for(i
= 0; i
< s
->nb_library_paths
; i
++) {
10056 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
10057 s
->library_paths
[i
], libraryname
);
10058 if (tcc_add_file_internal(s
, buf
, 0) == 0)
10064 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
10066 add_elf_sym(symtab_section
, val
, 0,
10067 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
), 0,
10072 int tcc_set_output_type(TCCState
*s
, int output_type
)
10074 s
->output_type
= output_type
;
10076 if (!s
->nostdinc
) {
10079 /* default include paths */
10080 /* XXX: reverse order needed if -isystem support */
10081 #ifndef TCC_TARGET_PE
10082 tcc_add_sysinclude_path(s
, "/usr/local/include");
10083 tcc_add_sysinclude_path(s
, "/usr/include");
10085 snprintf(buf
, sizeof(buf
), "%s/include", tcc_lib_path
);
10086 tcc_add_sysinclude_path(s
, buf
);
10087 #ifdef TCC_TARGET_PE
10088 snprintf(buf
, sizeof(buf
), "%s/include/winapi", tcc_lib_path
);
10089 tcc_add_sysinclude_path(s
, buf
);
10093 /* if bound checking, then add corresponding sections */
10094 #ifdef CONFIG_TCC_BCHECK
10095 if (do_bounds_check
) {
10096 /* define symbol */
10097 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
10098 /* create bounds sections */
10099 bounds_section
= new_section(s
, ".bounds",
10100 SHT_PROGBITS
, SHF_ALLOC
);
10101 lbounds_section
= new_section(s
, ".lbounds",
10102 SHT_PROGBITS
, SHF_ALLOC
);
10106 if (s
->char_is_unsigned
) {
10107 tcc_define_symbol(s
, "__CHAR_UNSIGNED__", NULL
);
10110 /* add debug sections */
10113 stab_section
= new_section(s
, ".stab", SHT_PROGBITS
, 0);
10114 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
10115 stabstr_section
= new_section(s
, ".stabstr", SHT_STRTAB
, 0);
10116 put_elf_str(stabstr_section
, "");
10117 stab_section
->link
= stabstr_section
;
10118 /* put first entry */
10119 put_stabs("", 0, 0, 0, 0);
10122 /* add libc crt1/crti objects */
10123 #ifndef TCC_TARGET_PE
10124 if ((output_type
== TCC_OUTPUT_EXE
|| output_type
== TCC_OUTPUT_DLL
) &&
10126 if (output_type
!= TCC_OUTPUT_DLL
)
10127 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
10128 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
10134 #define WD_ALL 0x0001 /* warning is activated when using -Wall */
10135 #define FD_INVERT 0x0002 /* invert value before storing */
10137 typedef struct FlagDef
{
10143 static const FlagDef warning_defs
[] = {
10144 { offsetof(TCCState
, warn_unsupported
), 0, "unsupported" },
10145 { offsetof(TCCState
, warn_write_strings
), 0, "write-strings" },
10146 { offsetof(TCCState
, warn_error
), 0, "error" },
10147 { offsetof(TCCState
, warn_implicit_function_declaration
), WD_ALL
,
10148 "implicit-function-declaration" },
10151 static int set_flag(TCCState
*s
, const FlagDef
*flags
, int nb_flags
,
10152 const char *name
, int value
)
10159 if (r
[0] == 'n' && r
[1] == 'o' && r
[2] == '-') {
10163 for(i
= 0, p
= flags
; i
< nb_flags
; i
++, p
++) {
10164 if (!strcmp(r
, p
->name
))
10169 if (p
->flags
& FD_INVERT
)
10171 *(int *)((uint8_t *)s
+ p
->offset
) = value
;
10176 /* set/reset a warning */
10177 int tcc_set_warning(TCCState
*s
, const char *warning_name
, int value
)
10182 if (!strcmp(warning_name
, "all")) {
10183 for(i
= 0, p
= warning_defs
; i
< countof(warning_defs
); i
++, p
++) {
10184 if (p
->flags
& WD_ALL
)
10185 *(int *)((uint8_t *)s
+ p
->offset
) = 1;
10189 return set_flag(s
, warning_defs
, countof(warning_defs
),
10190 warning_name
, value
);
10194 static const FlagDef flag_defs
[] = {
10195 { offsetof(TCCState
, char_is_unsigned
), 0, "unsigned-char" },
10196 { offsetof(TCCState
, char_is_unsigned
), FD_INVERT
, "signed-char" },
10197 { offsetof(TCCState
, nocommon
), FD_INVERT
, "common" },
10198 { offsetof(TCCState
, leading_underscore
), 0, "leading-underscore" },
10201 /* set/reset a flag */
10202 int tcc_set_flag(TCCState
*s
, const char *flag_name
, int value
)
10204 return set_flag(s
, flag_defs
, countof(flag_defs
),
10208 #if !defined(LIBTCC)
10210 /* extract the basename of a file */
10211 static const char *tcc_basename(const char *name
)
10214 p
= strrchr(name
, '/');
10217 p
= strrchr(name
, '\\');
10226 static int64_t getclock_us(void)
10231 return (tb
.time
* 1000LL + tb
.millitm
) * 1000LL;
10234 gettimeofday(&tv
, NULL
);
10235 return tv
.tv_sec
* 1000000LL + tv
.tv_usec
;
10241 printf("tcc version " TCC_VERSION
" - Tiny C Compiler - Copyright (C) 2001-2005 Fabrice Bellard\n"
10242 "usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
10243 " [-Wwarn] [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]\n"
10244 " [infile1 infile2...] [-run infile args...]\n"
10246 "General options:\n"
10247 " -v display current version\n"
10248 " -c compile only - generate an object file\n"
10249 " -o outfile set output filename\n"
10250 " -Bdir set tcc internal library path\n"
10251 " -bench output compilation statistics\n"
10252 " -run run compiled source\n"
10253 " -fflag set or reset (with 'no-' prefix) 'flag' (see man page)\n"
10254 " -Wwarning set or reset (with 'no-' prefix) 'warning' (see man page)\n"
10255 " -w disable all warnings\n"
10256 "Preprocessor options:\n"
10257 " -Idir add include path 'dir'\n"
10258 " -Dsym[=val] define 'sym' with value 'val'\n"
10259 " -Usym undefine 'sym'\n"
10260 "Linker options:\n"
10261 " -Ldir add library path 'dir'\n"
10262 " -llib link with dynamic or static library 'lib'\n"
10263 " -shared generate a shared library\n"
10264 " -static static linking\n"
10265 " -rdynamic export all global symbols to dynamic linker\n"
10266 " -r relocatable output\n"
10267 "Debugger options:\n"
10268 " -g generate runtime debug info\n"
10269 #ifdef CONFIG_TCC_BCHECK
10270 " -b compile with built-in memory and bounds checker (implies -g)\n"
10272 " -bt N show N callers in stack traces\n"
10276 #define TCC_OPTION_HAS_ARG 0x0001
10277 #define TCC_OPTION_NOSEP 0x0002 /* cannot have space before option and arg */
10279 typedef struct TCCOption
{
10307 TCC_OPTION_nostdinc
,
10308 TCC_OPTION_nostdlib
,
10309 TCC_OPTION_print_search_dirs
,
10310 TCC_OPTION_rdynamic
,
10317 static const TCCOption tcc_options
[] = {
10318 { "h", TCC_OPTION_HELP
, 0 },
10319 { "?", TCC_OPTION_HELP
, 0 },
10320 { "I", TCC_OPTION_I
, TCC_OPTION_HAS_ARG
},
10321 { "D", TCC_OPTION_D
, TCC_OPTION_HAS_ARG
},
10322 { "U", TCC_OPTION_U
, TCC_OPTION_HAS_ARG
},
10323 { "L", TCC_OPTION_L
, TCC_OPTION_HAS_ARG
},
10324 { "B", TCC_OPTION_B
, TCC_OPTION_HAS_ARG
},
10325 { "l", TCC_OPTION_l
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10326 { "bench", TCC_OPTION_bench
, 0 },
10327 { "bt", TCC_OPTION_bt
, TCC_OPTION_HAS_ARG
},
10328 #ifdef CONFIG_TCC_BCHECK
10329 { "b", TCC_OPTION_b
, 0 },
10331 { "g", TCC_OPTION_g
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10332 { "c", TCC_OPTION_c
, 0 },
10333 { "static", TCC_OPTION_static
, 0 },
10334 { "shared", TCC_OPTION_shared
, 0 },
10335 { "o", TCC_OPTION_o
, TCC_OPTION_HAS_ARG
},
10336 { "run", TCC_OPTION_run
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10337 { "rdynamic", TCC_OPTION_rdynamic
, 0 },
10338 { "r", TCC_OPTION_r
, 0 },
10339 { "Wl,", TCC_OPTION_Wl
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10340 { "W", TCC_OPTION_W
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10341 { "O", TCC_OPTION_O
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10342 { "m", TCC_OPTION_m
, TCC_OPTION_HAS_ARG
},
10343 { "f", TCC_OPTION_f
, TCC_OPTION_HAS_ARG
| TCC_OPTION_NOSEP
},
10344 { "nostdinc", TCC_OPTION_nostdinc
, 0 },
10345 { "nostdlib", TCC_OPTION_nostdlib
, 0 },
10346 { "print-search-dirs", TCC_OPTION_print_search_dirs
, 0 },
10347 { "v", TCC_OPTION_v
, 0 },
10348 { "w", TCC_OPTION_w
, 0 },
10349 { "pipe", TCC_OPTION_pipe
, 0},
10353 /* convert 'str' into an array of space separated strings */
10354 static int expand_args(char ***pargv
, const char *str
)
10363 while (is_space(*str
))
10368 while (*str
!= '\0' && !is_space(*str
))
10371 arg
= tcc_malloc(len
+ 1);
10372 memcpy(arg
, s1
, len
);
10374 dynarray_add((void ***)&argv
, &argc
, arg
);
10380 static char **files
;
10381 static int nb_files
, nb_libraries
;
10382 static int multiple_files
;
10383 static int print_search_dirs
;
10384 static int output_type
;
10385 static int reloc_output
;
10386 static const char *outfile
;
10388 int parse_args(TCCState
*s
, int argc
, char **argv
)
10391 const TCCOption
*popt
;
10392 const char *optarg
, *p1
, *r1
;
10397 if (optind
>= argc
) {
10398 if (nb_files
== 0 && !print_search_dirs
)
10403 r
= argv
[optind
++];
10405 /* add a new file */
10406 dynarray_add((void ***)&files
, &nb_files
, r
);
10407 if (!multiple_files
) {
10409 /* argv[0] will be this file */
10413 /* find option in table (match only the first chars */
10414 popt
= tcc_options
;
10418 error("invalid option -- '%s'", r
);
10431 if (popt
->flags
& TCC_OPTION_HAS_ARG
) {
10432 if (*r1
!= '\0' || (popt
->flags
& TCC_OPTION_NOSEP
)) {
10435 if (optind
>= argc
)
10436 error("argument to '%s' is missing", r
);
10437 optarg
= argv
[optind
++];
10445 switch(popt
->index
) {
10446 case TCC_OPTION_HELP
:
10451 if (tcc_add_include_path(s
, optarg
) < 0)
10452 error("too many include paths");
10457 sym
= (char *)optarg
;
10458 value
= strchr(sym
, '=');
10463 tcc_define_symbol(s
, sym
, value
);
10467 tcc_undefine_symbol(s
, optarg
);
10470 tcc_add_library_path(s
, optarg
);
10473 /* set tcc utilities path (mainly for tcc development) */
10474 tcc_lib_path
= optarg
;
10477 dynarray_add((void ***)&files
, &nb_files
, r
);
10480 case TCC_OPTION_bench
:
10483 case TCC_OPTION_bt
:
10484 num_callers
= atoi(optarg
);
10486 #ifdef CONFIG_TCC_BCHECK
10488 do_bounds_check
= 1;
10496 multiple_files
= 1;
10497 output_type
= TCC_OUTPUT_OBJ
;
10499 case TCC_OPTION_static
:
10500 s
->static_link
= 1;
10502 case TCC_OPTION_shared
:
10503 output_type
= TCC_OUTPUT_DLL
;
10506 multiple_files
= 1;
10510 /* generate a .o merging several output files */
10512 output_type
= TCC_OUTPUT_OBJ
;
10514 case TCC_OPTION_nostdinc
:
10517 case TCC_OPTION_nostdlib
:
10520 case TCC_OPTION_print_search_dirs
:
10521 print_search_dirs
= 1;
10523 case TCC_OPTION_run
:
10527 argc1
= expand_args(&argv1
, optarg
);
10529 parse_args(s
, argc1
, argv1
);
10531 multiple_files
= 0;
10532 output_type
= TCC_OUTPUT_MEMORY
;
10536 printf("tcc version %s\n", TCC_VERSION
);
10539 if (tcc_set_flag(s
, optarg
, 1) < 0 && s
->warn_unsupported
)
10540 goto unsupported_option
;
10543 if (tcc_set_warning(s
, optarg
, 1) < 0 &&
10544 s
->warn_unsupported
)
10545 goto unsupported_option
;
10550 case TCC_OPTION_rdynamic
:
10553 case TCC_OPTION_Wl
:
10556 if (strstart(optarg
, "-Ttext,", &p
)) {
10557 s
->text_addr
= strtoul(p
, NULL
, 16);
10558 s
->has_text_addr
= 1;
10559 } else if (strstart(optarg
, "--oformat,", &p
)) {
10560 if (strstart(p
, "elf32-", NULL
)) {
10561 s
->output_format
= TCC_OUTPUT_FORMAT_ELF
;
10562 } else if (!strcmp(p
, "binary")) {
10563 s
->output_format
= TCC_OUTPUT_FORMAT_BINARY
;
10565 #ifdef TCC_TARGET_COFF
10566 if (!strcmp(p
, "coff")) {
10567 s
->output_format
= TCC_OUTPUT_FORMAT_COFF
;
10571 error("target %s not found", p
);
10574 error("unsupported linker option '%s'", optarg
);
10579 if (s
->warn_unsupported
) {
10580 unsupported_option
:
10581 warning("unsupported option '%s'", r
);
10590 int main(int argc
, char **argv
)
10594 int nb_objfiles
, ret
, optind
;
10595 char objfilename
[1024];
10596 int64_t start_time
= 0;
10599 /* on win32, we suppose the lib and includes are at the location
10602 static char path
[1024];
10605 GetModuleFileNameA(NULL
, path
, sizeof path
);
10606 p
= d
= strlwr(path
);
10609 if (*d
== '\\') *d
= '/', p
= d
;
10613 tcc_lib_path
= path
;
10618 output_type
= TCC_OUTPUT_EXE
;
10620 multiple_files
= 1;
10625 print_search_dirs
= 0;
10627 optind
= parse_args(s
, argc
- 1, argv
+ 1) + 1;
10629 if (print_search_dirs
) {
10630 /* enough for Linux kernel */
10631 printf("install: %s/\n", tcc_lib_path
);
10635 nb_objfiles
= nb_files
- nb_libraries
;
10637 /* if outfile provided without other options, we output an
10639 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
10640 output_type
= TCC_OUTPUT_EXE
;
10642 /* check -c consistency : only single file handled. XXX: checks file type */
10643 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
10644 /* accepts only a single input file */
10645 if (nb_objfiles
!= 1)
10646 error("cannot specify multiple files with -c");
10647 if (nb_libraries
!= 0)
10648 error("cannot specify libraries with -c");
10651 if (output_type
!= TCC_OUTPUT_MEMORY
) {
10653 /* compute default outfile name */
10654 pstrcpy(objfilename
, sizeof(objfilename
) - 1,
10656 tcc_basename(files
[0]));
10657 #ifdef TCC_TARGET_PE
10658 pe_guess_outfile(objfilename
, output_type
);
10660 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
10661 char *ext
= strrchr(objfilename
, '.');
10663 goto default_outfile
;
10664 /* add .o extension */
10665 strcpy(ext
+ 1, "o");
10668 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
10671 outfile
= objfilename
;
10676 start_time
= getclock_us();
10679 tcc_set_output_type(s
, output_type
);
10681 /* compile or add each files or library */
10682 for(i
= 0;i
< nb_files
; i
++) {
10683 const char *filename
;
10685 filename
= files
[i
];
10686 if (filename
[0] == '-') {
10687 if (tcc_add_library(s
, filename
+ 2) < 0)
10688 error("cannot find %s", filename
);
10690 if (tcc_add_file(s
, filename
) < 0) {
10697 /* free all files */
10702 total_time
= (double)(getclock_us() - start_time
) / 1000000.0;
10703 if (total_time
< 0.001)
10704 total_time
= 0.001;
10705 if (total_bytes
< 1)
10707 printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
10708 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
,
10709 total_time
, (int)(total_lines
/ total_time
),
10710 total_bytes
/ total_time
/ 1000000.0);
10713 if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
10714 ret
= tcc_run(s
, argc
- optind
, argv
+ optind
);
10716 #ifdef TCC_TARGET_PE
10717 if (s
->output_type
!= TCC_OUTPUT_OBJ
) {
10718 ret
= tcc_output_pe(s
, outfile
);
10722 tcc_output_file(s
, outfile
);
10726 /* XXX: cannot do it with bound checking because of the malloc hooks */
10727 if (!do_bounds_check
)
10732 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);