2 * TCC - Tiny C Compiler
4 * Copyright (c) 2001, 2002 Fabrice Bellard
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program 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
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
31 #include <sys/ucontext.h>
35 #ifndef CONFIG_TCC_STATIC
42 /* preprocessor debug */
47 /* target selection */
48 //#define TCC_TARGET_I386 /* i386 code generator */
49 //#define TCC_TARGET_IL /* .NET CLI generator */
51 /* default target is I386 */
52 #if !defined(TCC_TARGET_I386) && !defined(TCC_TARGET_IL)
53 #define TCC_TARGET_I386
56 #if !defined(WIN32) && !defined(TCC_UCLIBC) && !defined(TCC_TARGET_IL)
57 #define CONFIG_TCC_BCHECK /* enable bound checking code */
60 #ifndef CONFIG_TCC_PREFIX
61 #define CONFIG_TCC_PREFIX "/usr/local"
64 /* path to find crt1.o, crti.o and crtn.o. Only needed when generating
65 executables or dlls */
66 #define CONFIG_TCC_CRT_PREFIX "/usr/lib"
68 #define INCLUDE_STACK_SIZE 32
69 #define IFDEF_STACK_SIZE 64
70 #define VSTACK_SIZE 64
71 #define STRING_MAX_SIZE 1024
73 #define TOK_HASH_SIZE 2048 /* must be a power of two */
74 #define TOK_ALLOC_INCR 512 /* must be a power of two */
75 #define SYM_HASH_SIZE 1031
77 /* token symbol management */
78 typedef struct TokenSym
{
79 struct TokenSym
*hash_next
;
80 int tok
; /* token number */
85 typedef struct CString
{
86 int size
; /* size in bytes */
87 void *data
; /* either 'char *' or 'int *' */
89 void *data_allocated
; /* if non NULL, data has been malloced */
93 typedef union CValue
{
99 unsigned int ul
; /* address (should be unsigned long on 64 bit cpu) */
101 unsigned long long ull
;
102 struct CString
*cstr
;
108 typedef struct SValue
{
110 unsigned short r
; /* register + flags */
111 unsigned short r2
; /* second register, used for 'long long'
112 type. If not used, set to VT_CONST */
113 CValue c
; /* constant, if VT_CONST */
114 struct Sym
*sym
; /* symbol, if (VT_SYM | VT_CONST) */
117 /* symbol management */
119 int v
; /* symbol token */
120 int t
; /* associated type */
121 int r
; /* associated register */
122 int c
; /* associated number */
123 struct Sym
*next
; /* next related symbol */
124 struct Sym
*prev
; /* prev symbol in stack */
125 struct Sym
*hash_next
; /* next symbol in hash table */
128 typedef struct SymStack
{
130 struct Sym
*hash
[SYM_HASH_SIZE
];
133 /* section definition */
134 /* XXX: use directly ELF structure for parameters ? */
135 /* special flag to indicate that the section should not be linked to
137 #define SHF_PRIVATE 0x80000000
139 typedef struct Section
{
140 unsigned long data_offset
; /* current data offset */
141 unsigned char *data
; /* section data */
142 unsigned long data_allocated
; /* used for realloc() handling */
143 int sh_name
; /* elf section name (only used during output) */
144 int sh_num
; /* elf section number */
145 int sh_type
; /* elf section type */
146 int sh_flags
; /* elf section flags */
147 int sh_info
; /* elf section info */
148 int sh_addralign
; /* elf section alignment */
149 int sh_entsize
; /* elf entry size */
150 unsigned long sh_size
; /* section size (only used during output) */
151 unsigned long sh_addr
; /* address at which the section is relocated */
152 unsigned long sh_offset
; /* address at which the section is relocated */
153 int nb_hashed_syms
; /* used to resize the hash table */
154 struct Section
*link
; /* link to another section */
155 struct Section
*reloc
; /* corresponding section for relocation, if any */
156 struct Section
*hash
; /* hash table for symbols */
157 struct Section
*next
;
158 char name
[64]; /* section name */
161 typedef struct DLLReference
{
166 /* GNUC attribute definition */
167 typedef struct AttributeDef
{
170 unsigned char func_call
; /* FUNC_CDECL or FUNC_STDCALL */
173 #define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
174 #define SYM_FIELD 0x20000000 /* struct/union field symbol space */
175 #define SYM_FIRST_ANOM (1 << (31 - VT_STRUCT_SHIFT)) /* first anonymous sym */
177 /* stored in 'Sym.c' field */
178 #define FUNC_NEW 1 /* ansi function prototype */
179 #define FUNC_OLD 2 /* old function prototype */
180 #define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
182 /* stored in 'Sym.r' field */
183 #define FUNC_CDECL 0 /* standard c call */
184 #define FUNC_STDCALL 1 /* pascal c call */
186 /* field 'Sym.t' for macros */
187 #define MACRO_OBJ 0 /* object like macro */
188 #define MACRO_FUNC 1 /* function like macro */
190 /* field 'Sym.t' for labels */
191 #define LABEL_FORWARD 1 /* label is forward defined */
193 /* type_decl() types */
194 #define TYPE_ABSTRACT 1 /* type without variable */
195 #define TYPE_DIRECT 2 /* type with variable */
197 #define IO_BUF_SIZE 8192
199 typedef struct BufferedFile
{
200 unsigned char *buf_ptr
;
201 unsigned char *buf_end
;
203 int line_num
; /* current line number - here to simply code */
204 char filename
[1024]; /* current filename - here to simplify code */
205 unsigned char buffer
[IO_BUF_SIZE
+ 1]; /* extra size for CH_EOB char */
208 #define CH_EOB 0 /* end of buffer or '\0' char in file */
209 #define CH_EOF (-1) /* end of file */
211 /* parsing state (used to save parser state to reparse part of the
212 source several times) */
213 typedef struct ParseState
{
220 /* used to record tokens */
221 typedef struct TokenString
{
228 struct BufferedFile
*file
;
229 int ch
, ch1
, tok
, tok1
;
231 CString tokcstr
; /* current parsed string, if any */
232 int return_linefeed
; /* if true, line feed is returned as a token */
236 int nb_sections
; /* number of sections, including first dummy section */
237 Section
*text_section
, *data_section
, *bss_section
; /* predefined sections */
238 Section
*cur_text_section
; /* current section where function code is
240 /* bound check related sections */
241 Section
*bounds_section
; /* contains global data bound description */
242 Section
*lbounds_section
; /* contains local data bound description */
243 /* symbol sections */
244 Section
*symtab_section
, *strtab_section
;
245 /* temporary dynamic symbol sections (for dll loading) */
246 Section
*dynsymtab_section
;
247 /* exported dynamic symbol section */
251 unsigned long *got_offsets
;
254 /* give the correspondance from symtab indexes to dynsym indexes */
255 int *symtab_to_dynsym
;
257 /* array of all loaded dlls (including those referenced by loaded
259 DLLReference
**loaded_dlls
;
263 Section
*stab_section
, *stabstr_section
;
265 char **library_paths
;
266 int nb_library_paths
;
268 /* loc : local variable index
269 ind : output code index
271 anon_sym: anonymous symbol index
274 prog
, ind
, loc
, const_wanted
;
275 int global_expr
; /* true if compound literals must be allocated
276 globally (used during initializers parsing */
277 int func_vt
, func_vc
; /* current function return type (used by
278 return instruction) */
279 int last_line_num
, last_ind
, func_ind
; /* debug last line number and pc */
281 TokenSym
**table_ident
;
282 TokenSym
*hash_ident
[TOK_HASH_SIZE
];
283 char token_buf
[STRING_MAX_SIZE
+ 1];
285 SymStack define_stack
, global_stack
, local_stack
, label_stack
;
287 SValue vstack
[VSTACK_SIZE
], *vtop
;
288 int *macro_ptr
, *macro_ptr_allocated
;
289 BufferedFile
*include_stack
[INCLUDE_STACK_SIZE
], **include_stack_ptr
;
290 int ifdef_stack
[IFDEF_STACK_SIZE
], *ifdef_stack_ptr
;
291 char **include_paths
;
292 int nb_include_paths
;
293 char **sysinclude_paths
;
294 int nb_sysinclude_paths
;
295 int char_pointer_type
;
298 /* compile with debug symbol (and use them if error during execution) */
301 /* compile with built-in memory and bounds checker */
302 int do_bounds_check
= 0;
304 /* display benchmark infos */
309 /* use GNU C extensions */
312 /* use Tiny C extensions */
315 /* if true, static linking is performed */
318 /* give the path of the tcc libraries */
319 static const char *tcc_lib_path
= CONFIG_TCC_PREFIX
"/lib/tcc";
325 /* The current value can be: */
326 #define VT_VALMASK 0x00ff
327 #define VT_CONST 0x00f0 /* constant in vc
328 (must be first non register value) */
329 #define VT_LLOCAL 0x00f1 /* lvalue, offset on stack */
330 #define VT_LOCAL 0x00f2 /* offset on stack */
331 #define VT_CMP 0x00f3 /* the value is stored in processor flags (in vc) */
332 #define VT_JMP 0x00f4 /* value is the consequence of jmp true (even) */
333 #define VT_JMPI 0x00f5 /* value is the consequence of jmp false (odd) */
334 #define VT_LVAL 0x0100 /* var is an lvalue */
335 #define VT_SYM 0x0200 /* a symbol value is added */
336 #define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
337 char/short stored in integer registers) */
338 #define VT_MUSTBOUND 0x0800 /* bound checking must be done before
339 dereferencing value */
340 #define VT_BOUNDED 0x8000 /* value is bounded. The address of the
341 bounding function call point is in vc */
342 #define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
343 #define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
344 #define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
345 #define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
348 #define VT_STRUCT_SHIFT 12 /* structure/enum name shift (20 bits left) */
350 #define VT_INT 0 /* integer type */
351 #define VT_BYTE 1 /* signed byte type */
352 #define VT_SHORT 2 /* short type */
353 #define VT_VOID 3 /* void type */
354 #define VT_PTR 4 /* pointer */
355 #define VT_ENUM 5 /* enum definition */
356 #define VT_FUNC 6 /* function type */
357 #define VT_STRUCT 7 /* struct/union definition */
358 #define VT_FLOAT 8 /* IEEE float */
359 #define VT_DOUBLE 9 /* IEEE double */
360 #define VT_LDOUBLE 10 /* IEEE long double */
361 #define VT_BOOL 11 /* ISOC99 boolean type */
362 #define VT_LLONG 12 /* 64 bit integer */
363 #define VT_LONG 13 /* long integer (NEVER USED as type, only
365 #define VT_BTYPE 0x000f /* mask for basic type */
366 #define VT_UNSIGNED 0x0010 /* unsigned type */
367 #define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
368 #define VT_BITFIELD 0x0040 /* bitfield modifier */
371 #define VT_EXTERN 0x00000080 /* extern definition */
372 #define VT_STATIC 0x00000100 /* static variable */
373 #define VT_TYPEDEF 0x00000200 /* typedef definition */
375 /* type mask (except storage) */
376 #define VT_TYPE (~(VT_EXTERN | VT_STATIC | VT_TYPEDEF))
380 /* warning: the following compare tokens depend on i386 asm code */
392 #define TOK_LAND 0xa0
396 #define TOK_MID 0xa3 /* inc/dec, to void constant */
398 #define TOK_UDIV 0xb0 /* unsigned division */
399 #define TOK_UMOD 0xb1 /* unsigned modulo */
400 #define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
401 #define TOK_CINT 0xb3 /* number in tokc */
402 #define TOK_CCHAR 0xb4 /* char constant in tokc */
403 #define TOK_STR 0xb5 /* pointer to string in tokc */
404 #define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
405 #define TOK_LCHAR 0xb7
406 #define TOK_LSTR 0xb8
407 #define TOK_CFLOAT 0xb9 /* float constant */
408 #define TOK_LINENUM 0xba /* line number info */
409 #define TOK_CDOUBLE 0xc0 /* double constant */
410 #define TOK_CLDOUBLE 0xc1 /* long double constant */
411 #define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
412 #define TOK_ADDC1 0xc3 /* add with carry generation */
413 #define TOK_ADDC2 0xc4 /* add with carry use */
414 #define TOK_SUBC1 0xc5 /* add with carry generation */
415 #define TOK_SUBC2 0xc6 /* add with carry use */
416 #define TOK_CUINT 0xc8 /* unsigned int constant */
417 #define TOK_CLLONG 0xc9 /* long long constant */
418 #define TOK_CULLONG 0xca /* unsigned long long constant */
419 #define TOK_ARROW 0xcb
420 #define TOK_DOTS 0xcc /* three dots */
421 #define TOK_SHR 0xcd /* unsigned shift right */
423 #define TOK_SHL 0x01 /* shift left */
424 #define TOK_SAR 0x02 /* signed shift right */
426 /* assignement operators : normal operator or 0x80 */
427 #define TOK_A_MOD 0xa5
428 #define TOK_A_AND 0xa6
429 #define TOK_A_MUL 0xaa
430 #define TOK_A_ADD 0xab
431 #define TOK_A_SUB 0xad
432 #define TOK_A_DIV 0xaf
433 #define TOK_A_XOR 0xde
434 #define TOK_A_OR 0xfc
435 #define TOK_A_SHL 0x81
436 #define TOK_A_SAR 0x82
438 /* WARNING: the content of this string encodes token numbers */
439 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";
441 #define TOK_EOF (-1) /* end of file */
442 #define TOK_LINEFEED 10 /* line feed */
444 /* all identificators and strings have token above that */
445 #define TOK_IDENT 256
466 /* ignored types Must have contiguous values */
472 TOK___SIGNED__
, /* gcc keyword */
475 TOK___INLINE__
, /* gcc keyword */
478 /* unsupported type */
492 /* preprocessor only */
493 TOK_UIDENT
, /* first "user" ident (not keyword) */
494 TOK_DEFINE
= TOK_UIDENT
,
505 #define DEF(id, str) id,
511 "int\0void\0char\0if\0else\0while\0break\0return\0for\0extern\0static\0"
512 "unsigned\0goto\0do\0continue\0switch\0case\0const\0volatile\0long\0"
513 "register\0signed\0__signed__\0auto\0inline\0__inline__\0restrict\0"
514 "float\0double\0_Bool\0short\0struct\0union\0typedef\0default\0enum\0"
515 "sizeof\0__attribute__\0"
516 /* the following are not keywords. They are included to ease parsing */
517 "define\0include\0ifdef\0ifndef\0elif\0endif\0"
518 "defined\0undef\0error\0line\0"
519 /* builtin functions */
520 #define DEF(id, str) str "\0"
526 #define snprintf _snprintf
529 #if defined(WIN32) || defined(TCC_UCLIBC)
530 /* currently incorrect */
531 long double strtold(const char *nptr
, char **endptr
)
533 return (long double)strtod(nptr
, endptr
);
535 float strtof(const char *nptr
, char **endptr
)
537 return (float)strtod(nptr
, endptr
);
540 /* XXX: need to define this to use them in non ISOC99 context */
541 extern float strtof (const char *__nptr
, char **__endptr
);
542 extern long double strtold (const char *__nptr
, char **__endptr
);
545 static char *pstrcpy(char *buf
, int buf_size
, const char *s
);
546 static char *pstrcat(char *buf
, int buf_size
, const char *s
);
550 void next_nomacro(void);
551 static int expr_const(void);
555 static void decl_initializer(int t
, Section
*sec
, unsigned long c
,
556 int first
, int size_only
);
557 static void decl_initializer_alloc(int t
, AttributeDef
*ad
, int r
,
558 int has_init
, int v
, int scope
);
560 void gv2(int rc1
, int rc2
);
561 void move_reg(int r
, int s
);
562 void save_regs(int n
);
563 void save_reg(int r
);
569 void macro_subst(TokenString
*tok_str
,
570 Sym
**nested_list
, int *macro_str
);
571 int save_reg_forced(int r
);
573 void force_charshort_cast(int t
);
574 void gen_cast(int t
);
576 Sym
*sym_find(int v
);
577 Sym
*sym_push(int v
, int t
, int r
, int c
);
580 int type_size(int t
, int *a
);
581 int pointed_type(int t
);
582 int pointed_size(int t
);
583 static int lvalue_type(int t
);
584 int is_compatible_types(int t1
, int t2
);
585 int parse_btype(int *type_ptr
, AttributeDef
*ad
);
586 int type_decl(AttributeDef
*ad
, int *v
, int t
, int td
);
588 void error(const char *fmt
, ...);
589 void rt_error(unsigned long pc
, const char *fmt
, ...);
591 void vset(int t
, int r
, int v
);
592 void type_to_str(char *buf
, int buf_size
,
593 int t
, const char *varstr
);
594 char *get_tok_str(int v
, CValue
*cv
);
595 static Sym
*get_sym_ref(int t
, Section
*sec
,
596 unsigned long offset
, unsigned long size
);
597 static Sym
*external_global_sym(int v
, int u
, int r
);
599 /* section generation */
600 static void section_realloc(Section
*sec
, unsigned long new_size
);
601 static void *section_ptr_add(Section
*sec
, unsigned long size
);
602 static void put_extern_sym(Sym
*sym
, Section
*section
,
603 unsigned long value
, unsigned long size
);
604 static void greloc(Section
*s
, Sym
*sym
, unsigned long addr
, int type
);
605 static int put_elf_str(Section
*s
, const char *sym
);
606 static int put_elf_sym(Section
*s
,
607 unsigned long value
, unsigned long size
,
608 int info
, int other
, int shndx
, const char *name
);
609 static int add_elf_sym(Section
*s
, unsigned long value
, unsigned long size
,
610 int info
, int sh_num
, const char *name
);
611 static void put_elf_reloc(Section
*symtab
, Section
*s
, unsigned long offset
,
612 int type
, int symbol
);
613 static void put_stabs(const char *str
, int type
, int other
, int desc
,
614 unsigned long value
);
615 static void put_stabs_r(const char *str
, int type
, int other
, int desc
,
616 unsigned long value
, Section
*sec
, int sym_index
);
617 static void put_stabn(int type
, int other
, int desc
, int value
);
618 static void put_stabd(int type
, int other
, int desc
);
619 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
);
621 #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
622 #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
623 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
);
625 /* true if float/double/long double type */
626 static inline int is_float(int t
)
630 return bt
== VT_LDOUBLE
|| bt
== VT_DOUBLE
|| bt
== VT_FLOAT
;
633 #ifdef TCC_TARGET_I386
634 #include "i386-gen.c"
640 #ifdef CONFIG_TCC_STATIC
642 #define RTLD_LAZY 0x001
643 #define RTLD_NOW 0x002
644 #define RTLD_GLOBAL 0x100
646 /* dummy function for profiling */
647 void *dlopen(const char *filename
, int flag
)
652 const char *dlerror(void)
657 typedef struct TCCSyms
{
662 #define TCCSYM(a) { #a, &a, },
664 /* add the symbol you want here if no dynamic linking is done */
665 static TCCSyms tcc_syms
[] = {
673 void *dlsym(void *handle
, const char *symbol
)
677 while (p
->str
!= NULL
) {
678 if (!strcmp(p
->str
, symbol
))
687 /********************************************************/
689 /* we use our own 'finite' function to avoid potential problems with
690 non standard math libs */
691 /* XXX: endianness dependant */
692 int ieee_finite(double d
)
695 return ((unsigned)((p
[1] | 0x800fffff) + 1)) >> 31;
698 /* copy a string and truncate it. */
699 static char *pstrcpy(char *buf
, int buf_size
, const char *s
)
706 q_end
= buf
+ buf_size
- 1;
718 /* strcat and truncate. */
719 static char *pstrcat(char *buf
, int buf_size
, const char *s
)
724 pstrcpy(buf
+ len
, buf_size
- len
, s
);
728 /* memory management */
734 static inline void tcc_free(void *ptr
)
737 mem_cur_size
-= malloc_usable_size(ptr
);
742 static void *tcc_malloc(unsigned long size
)
747 error("memory full");
749 mem_cur_size
+= malloc_usable_size(ptr
);
750 if (mem_cur_size
> mem_max_size
)
751 mem_max_size
= mem_cur_size
;
756 static void *tcc_mallocz(unsigned long size
)
759 ptr
= tcc_malloc(size
);
760 memset(ptr
, 0, size
);
764 static inline void *tcc_realloc(void *ptr
, unsigned long size
)
768 mem_cur_size
-= malloc_usable_size(ptr
);
770 ptr1
= realloc(ptr
, size
);
772 /* NOTE: count not correct if alloc error, but not critical */
773 mem_cur_size
+= malloc_usable_size(ptr1
);
774 if (mem_cur_size
> mem_max_size
)
775 mem_max_size
= mem_cur_size
;
780 static char *tcc_strdup(const char *str
)
783 ptr
= tcc_malloc(strlen(str
) + 1);
788 #define free(p) use_tcc_free(p)
789 #define malloc(s) use_tcc_malloc(s)
790 #define realloc(p, s) use_tcc_realloc(p, s)
792 static void dynarray_add(void ***ptab
, int *nb_ptr
, void *data
)
799 /* every power of two we double array size */
800 if ((nb
& (nb
- 1)) == 0) {
805 pp
= tcc_realloc(pp
, nb_alloc
* sizeof(void *));
807 error("memory full");
814 Section
*new_section(const char *name
, int sh_type
, int sh_flags
)
818 sec
= tcc_mallocz(sizeof(Section
));
819 pstrcpy(sec
->name
, sizeof(sec
->name
), name
);
820 sec
->sh_type
= sh_type
;
821 sec
->sh_flags
= sh_flags
;
828 sec
->sh_addralign
= 4;
831 sec
->sh_addralign
= 1;
834 sec
->sh_addralign
= 32; /* default conservative alignment */
838 /* only add section if not private */
839 if (!(sh_flags
& SHF_PRIVATE
)) {
840 sec
->sh_num
= nb_sections
;
841 dynarray_add((void ***)§ions
, &nb_sections
, sec
);
846 /* realloc section and set its content to zero */
847 static void section_realloc(Section
*sec
, unsigned long new_size
)
852 size
= sec
->data_allocated
;
855 while (size
< new_size
)
857 data
= tcc_realloc(sec
->data
, size
);
859 error("memory full");
860 memset(data
+ sec
->data_allocated
, 0, size
- sec
->data_allocated
);
862 sec
->data_allocated
= size
;
865 /* reserve at least 'size' bytes in section 'sec' from
867 static void *section_ptr_add(Section
*sec
, unsigned long size
)
869 unsigned long offset
, offset1
;
871 offset
= sec
->data_offset
;
872 offset1
= offset
+ size
;
873 if (offset1
> sec
->data_allocated
)
874 section_realloc(sec
, offset1
);
875 sec
->data_offset
= offset1
;
876 return sec
->data
+ offset
;
879 /* return a reference to a section, and create it if it does not
881 Section
*find_section(const char *name
)
885 for(i
= 1; i
< nb_sections
; i
++) {
887 if (!strcmp(name
, sec
->name
))
890 /* sections are created as PROGBITS */
891 return new_section(name
, SHT_PROGBITS
, SHF_ALLOC
);
894 /* update sym->c so that it points to an external symbol in section
895 'section' with value 'value' */
896 static void put_extern_sym(Sym
*sym
, Section
*section
,
897 unsigned long value
, unsigned long size
)
899 int sym_type
, sym_bind
, sh_num
, info
;
905 sh_num
= section
->sh_num
;
909 if ((sym
->t
& VT_BTYPE
) == VT_FUNC
)
912 sym_type
= STT_OBJECT
;
913 if (sym
->t
& VT_STATIC
)
914 sym_bind
= STB_LOCAL
;
916 sym_bind
= STB_GLOBAL
;
918 name
= get_tok_str(sym
->v
, NULL
);
919 #ifdef CONFIG_TCC_BCHECK
920 if (do_bounds_check
) {
921 /* if bound checking is activated, we change some function
922 names by adding the "__bound" prefix */
934 strcpy(buf
, "__bound_");
941 info
= ELF32_ST_INFO(sym_bind
, sym_type
);
942 sym
->c
= add_elf_sym(symtab_section
, value
, size
, info
, sh_num
, name
);
944 esym
= &((Elf32_Sym
*)symtab_section
->data
)[sym
->c
];
945 esym
->st_value
= value
;
946 esym
->st_size
= size
;
947 esym
->st_shndx
= sh_num
;
951 /* add a new relocation entry to symbol 'sym' in section 's' */
952 static void greloc(Section
*s
, Sym
*sym
, unsigned long offset
, int type
)
955 put_extern_sym(sym
, NULL
, 0, 0);
956 /* now we can add ELF relocation info */
957 put_elf_reloc(symtab_section
, s
, offset
, type
, sym
->c
);
960 static inline int isid(int c
)
962 return (c
>= 'a' && c
<= 'z') ||
963 (c
>= 'A' && c
<= 'Z') ||
967 static inline int isnum(int c
)
969 return c
>= '0' && c
<= '9';
972 static inline int isoct(int c
)
974 return c
>= '0' && c
<= '7';
977 static inline int toup(int c
)
979 if (ch
>= 'a' && ch
<= 'z')
980 return ch
- 'a' + 'A';
990 for(f
= include_stack
; f
< include_stack_ptr
; f
++)
991 fprintf(stderr
, "In file included from %s:%d:\n",
992 (*f
)->filename
, (*f
)->line_num
);
993 if (file
->line_num
> 0) {
994 fprintf(stderr
, "%s:%d: ", file
->filename
, file
->line_num
);
996 fprintf(stderr
, "%s: ", file
->filename
);
999 fprintf(stderr
, "tcc: ");
1003 void error(const char *fmt
, ...)
1008 vfprintf(stderr
, fmt
, ap
);
1009 fprintf(stderr
, "\n");
1014 void expect(const char *msg
)
1016 error("%s expected", msg
);
1019 void warning(const char *fmt
, ...)
1025 fprintf(stderr
, "warning: ");
1026 vfprintf(stderr
, fmt
, ap
);
1027 fprintf(stderr
, "\n");
1034 error("'%c' expected", c
);
1038 void test_lvalue(void)
1040 if (!(vtop
->r
& VT_LVAL
))
1044 TokenSym
*tok_alloc(const char *str
, int len
)
1046 TokenSym
*ts
, **pts
, **ptable
;
1053 h
= (h
* 263 + ((unsigned char *)str
)[i
]) & (TOK_HASH_SIZE
- 1);
1055 pts
= &hash_ident
[h
];
1060 if (ts
->len
== len
&& !memcmp(ts
->str
, str
, len
))
1062 pts
= &(ts
->hash_next
);
1065 if (tok_ident
>= SYM_FIRST_ANOM
)
1066 error("memory full");
1068 /* expand token table if needed */
1069 i
= tok_ident
- TOK_IDENT
;
1070 if ((i
% TOK_ALLOC_INCR
) == 0) {
1071 ptable
= tcc_realloc(table_ident
, (i
+ TOK_ALLOC_INCR
) * sizeof(TokenSym
*));
1073 error("memory full");
1074 table_ident
= ptable
;
1077 ts
= tcc_malloc(sizeof(TokenSym
) + len
);
1078 table_ident
[i
] = ts
;
1079 ts
->tok
= tok_ident
++;
1081 ts
->hash_next
= NULL
;
1082 memcpy(ts
->str
, str
, len
+ 1);
1087 /* CString handling */
1089 static void cstr_realloc(CString
*cstr
, int new_size
)
1094 size
= cstr
->size_allocated
;
1096 size
= 8; /* no need to allocate a too small first string */
1097 while (size
< new_size
)
1099 data
= tcc_realloc(cstr
->data_allocated
, size
);
1101 error("memory full");
1102 cstr
->data_allocated
= data
;
1103 cstr
->size_allocated
= size
;
1108 static void cstr_ccat(CString
*cstr
, int ch
)
1111 size
= cstr
->size
+ 1;
1112 if (size
> cstr
->size_allocated
)
1113 cstr_realloc(cstr
, size
);
1114 ((unsigned char *)cstr
->data
)[size
- 1] = ch
;
1118 static void cstr_cat(CString
*cstr
, const char *str
)
1130 /* add a wide char */
1131 static void cstr_wccat(CString
*cstr
, int ch
)
1134 size
= cstr
->size
+ sizeof(int);
1135 if (size
> cstr
->size_allocated
)
1136 cstr_realloc(cstr
, size
);
1137 *(int *)(((unsigned char *)cstr
->data
) + size
- sizeof(int)) = ch
;
1141 static void cstr_new(CString
*cstr
)
1143 memset(cstr
, 0, sizeof(CString
));
1146 /* free string and reset it to NULL */
1147 static void cstr_free(CString
*cstr
)
1149 tcc_free(cstr
->data_allocated
);
1153 #define cstr_reset(cstr) cstr_free(cstr)
1155 /* XXX: unicode ? */
1156 static void add_char(CString
*cstr
, int c
)
1158 if (c
== '\'' || c
== '\"' || c
== '\\') {
1159 /* XXX: could be more precise if char or string */
1160 cstr_ccat(cstr
, '\\');
1162 if (c
>= 32 && c
<= 126) {
1165 cstr_ccat(cstr
, '\\');
1167 cstr_ccat(cstr
, 'n');
1169 cstr_ccat(cstr
, '0' + ((c
>> 6) & 7));
1170 cstr_ccat(cstr
, '0' + ((c
>> 3) & 7));
1171 cstr_ccat(cstr
, '0' + (c
& 7));
1176 /* XXX: buffer overflow */
1177 /* XXX: float tokens */
1178 char *get_tok_str(int v
, CValue
*cv
)
1180 static char buf
[STRING_MAX_SIZE
+ 1];
1181 static CString cstr_buf
;
1187 /* NOTE: to go faster, we give a fixed buffer for small strings */
1188 cstr_reset(&cstr_buf
);
1189 cstr_buf
.data
= buf
;
1190 cstr_buf
.size_allocated
= sizeof(buf
);
1196 /* XXX: not exact */
1197 sprintf(p
, "%u", cv
->ui
);
1201 cstr_ccat(&cstr_buf
, '\'');
1202 add_char(&cstr_buf
, cv
->i
);
1203 cstr_ccat(&cstr_buf
, '\'');
1204 cstr_ccat(&cstr_buf
, '\0');
1209 cstr_ccat(&cstr_buf
, '\"');
1211 len
= cstr
->size
- 1;
1213 add_char(&cstr_buf
, ((unsigned char *)cstr
->data
)[i
]);
1215 len
= (cstr
->size
/ sizeof(int)) - 1;
1217 add_char(&cstr_buf
, ((int *)cstr
->data
)[i
]);
1219 cstr_ccat(&cstr_buf
, '\"');
1220 cstr_ccat(&cstr_buf
, '\0');
1229 return strcpy(p
, "<<=");
1231 return strcpy(p
, ">>=");
1233 if (v
< TOK_IDENT
) {
1234 /* search in two bytes table */
1248 } else if (v
< tok_ident
) {
1249 return table_ident
[v
- TOK_IDENT
]->str
;
1250 } else if (v
>= SYM_FIRST_ANOM
) {
1251 /* special name for anonymous symbol */
1252 sprintf(p
, "L.%u", v
- SYM_FIRST_ANOM
);
1254 /* should never happen */
1259 return cstr_buf
.data
;
1262 /* push, without hashing */
1263 Sym
*sym_push2(Sym
**ps
, int v
, int t
, int c
)
1266 s
= tcc_malloc(sizeof(Sym
));
1277 /* find a symbol and return its associated structure. 's' is the top
1278 of the symbol stack */
1279 Sym
*sym_find2(Sym
*s
, int v
)
1289 #define HASH_SYM(v) ((unsigned)(v) % SYM_HASH_SIZE)
1291 /* find a symbol and return its associated structure. 'st' is the
1293 Sym
*sym_find1(SymStack
*st
, int v
)
1297 s
= st
->hash
[HASH_SYM(v
)];
1306 Sym
*sym_push1(SymStack
*st
, int v
, int t
, int c
)
1309 s
= sym_push2(&st
->top
, v
, t
, c
);
1310 /* add in hash table */
1312 ps
= &st
->hash
[HASH_SYM(v
)];
1319 /* find a symbol in the right symbol space */
1320 Sym
*sym_find(int v
)
1323 s
= sym_find1(&local_stack
, v
);
1325 s
= sym_find1(&global_stack
, v
);
1329 /* push a given symbol on the symbol stack */
1330 Sym
*sym_push(int v
, int t
, int r
, int c
)
1333 if (local_stack
.top
)
1334 s
= sym_push1(&local_stack
, v
, t
, c
);
1336 s
= sym_push1(&global_stack
, v
, t
, c
);
1341 /* pop symbols until top reaches 'b' */
1342 void sym_pop(SymStack
*st
, Sym
*b
)
1349 /* free hash table entry, except if symbol was freed (only
1350 used for #undef symbols) */
1352 st
->hash
[HASH_SYM(s
->v
)] = s
->hash_next
;
1359 /* undefined a hashed symbol (used for #undef). Its name is set to
1361 void sym_undef(SymStack
*st
, Sym
*s
)
1364 ss
= &st
->hash
[HASH_SYM(s
->v
)];
1365 while (*ss
!= NULL
) {
1368 ss
= &(*ss
)->hash_next
;
1376 BufferedFile
*tcc_open(const char *filename
)
1381 fd
= open(filename
, O_RDONLY
);
1384 bf
= tcc_malloc(sizeof(BufferedFile
));
1390 bf
->buf_ptr
= bf
->buffer
;
1391 bf
->buf_end
= bf
->buffer
;
1392 bf
->buffer
[0] = CH_EOB
; /* put eob symbol */
1393 pstrcpy(bf
->filename
, sizeof(bf
->filename
), filename
);
1395 // printf("opening '%s'\n", filename);
1399 void tcc_close(BufferedFile
*bf
)
1401 total_lines
+= bf
->line_num
;
1406 /* read one char. MUST call tcc_fillbuf if CH_EOB is read */
1407 #define TCC_GETC(bf) (*(bf)->buf_ptr++)
1409 /* fill input buffer and return next char */
1410 int tcc_getc_slow(BufferedFile
*bf
)
1413 /* only tries to read if really end of buffer */
1414 if (bf
->buf_ptr
>= bf
->buf_end
) {
1416 len
= read(bf
->fd
, bf
->buffer
, IO_BUF_SIZE
);
1423 bf
->buf_ptr
= bf
->buffer
;
1424 bf
->buf_end
= bf
->buffer
+ len
;
1425 *bf
->buf_end
= CH_EOB
;
1427 if (bf
->buf_ptr
< bf
->buf_end
) {
1428 return *bf
->buf_ptr
++;
1430 bf
->buf_ptr
= bf
->buf_end
;
1435 /* no need to put that inline */
1436 void handle_eob(void)
1439 ch1
= tcc_getc_slow(file
);
1443 if (include_stack_ptr
== include_stack
)
1445 /* add end of include file debug info */
1447 put_stabd(N_EINCL
, 0, 0);
1449 /* pop include stack */
1451 include_stack_ptr
--;
1452 file
= *include_stack_ptr
;
1456 /* read next char from current input file */
1457 static inline void inp(void)
1459 ch1
= TCC_GETC(file
);
1460 /* end of buffer/file handling */
1465 // printf("ch1=%c 0x%x\n", ch1, ch1);
1468 /* handle '\\n' and '\\r\n' */
1469 static void handle_stray(void)
1474 } else if (ch1
== '\r') {
1477 error("invalid character after '\\'");
1484 } while (ch
== '\\');
1487 /* input with '\\n' handling. Also supports '\\r\n' for horrible MSDOS
1489 static inline void minp(void)
1498 /* same as minp, but also skip comments */
1499 static void cinp(void)
1506 /* single line C++ comments */
1508 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1510 ch
= ' '; /* return space */
1511 } else if (ch1
== '*') {
1514 while (ch1
!= CH_EOF
) {
1517 if (c
== '*' && ch1
== '/') {
1519 ch
= ' '; /* return space */
1531 /* space exlcuding newline */
1532 static inline int is_space(int ch
)
1534 return ch
== ' ' || ch
== '\t' || ch
== '\v' || ch
== '\f' || ch
== '\r';
1537 static inline void skip_spaces(void)
1539 while (is_space(ch
))
1543 /* skip block of text until #else, #elif or #endif. skip also pairs of
1545 void preprocess_skip(void)
1550 while (ch
!= '\n') {
1561 (tok
== TOK_ELSE
|| tok
== TOK_ELIF
|| tok
== TOK_ENDIF
))
1563 if (tok
== TOK_IF
|| tok
== TOK_IFDEF
|| tok
== TOK_IFNDEF
)
1565 else if (tok
== TOK_ENDIF
)
1571 /* ParseState handling */
1573 /* XXX: currently, no include file info is stored. Thus, we cannot display
1574 accurate messages if the function or data definition spans multiple
1577 /* save current parse state in 's' */
1578 void save_parse_state(ParseState
*s
)
1580 s
->line_num
= file
->line_num
;
1581 s
->macro_ptr
= macro_ptr
;
1586 /* restore parse state from 's' */
1587 void restore_parse_state(ParseState
*s
)
1589 file
->line_num
= s
->line_num
;
1590 macro_ptr
= s
->macro_ptr
;
1595 /* return the number of additionnal 'ints' necessary to store the
1597 static inline int tok_ext_size(int t
)
1615 return LDOUBLE_SIZE
/ 4;
1621 /* token string handling */
1623 static inline void tok_str_new(TokenString
*s
)
1627 s
->last_line_num
= -1;
1630 static void tok_str_free(int *str
)
1641 if (t
== TOK_STR
|| t
== TOK_LSTR
) {
1642 /* XXX: use a macro to be portable on 64 bit ? */
1643 cstr
= (CString
*)(*p
++);
1647 p
+= tok_ext_size(t
);
1653 static void tok_str_add(TokenString
*s
, int t
)
1659 if ((len
& 63) == 0) {
1660 str
= tcc_realloc(str
, (len
+ 64) * sizeof(int));
1669 static void tok_str_add2(TokenString
*s
, int t
, CValue
*cv
)
1672 CString
*cstr
, *cstr1
;
1676 if (t
== TOK_STR
|| t
== TOK_LSTR
) {
1677 /* special case: need to duplicate string */
1679 cstr
= tcc_malloc(sizeof(CString
));
1682 cstr
->size_allocated
= size
;
1683 cstr
->data_allocated
= tcc_malloc(size
);
1684 cstr
->data
= cstr
->data_allocated
;
1685 memcpy(cstr
->data_allocated
, cstr1
->data_allocated
, size
);
1687 tok_str_add(s
, cv1
.tab
[0]);
1689 n
= tok_ext_size(t
);
1691 tok_str_add(s
, cv
->tab
[i
]);
1695 /* add the current parse token in token string 's' */
1696 static void tok_str_add_tok(TokenString
*s
)
1700 /* save line number info */
1701 if (file
->line_num
!= s
->last_line_num
) {
1702 s
->last_line_num
= file
->line_num
;
1703 cval
.i
= s
->last_line_num
;
1704 tok_str_add2(s
, TOK_LINENUM
, &cval
);
1706 tok_str_add2(s
, tok
, &tokc
);
1709 /* get a token from an integer array and increment pointer accordingly */
1710 static int tok_get(int **tok_str
, CValue
*cv
)
1716 n
= tok_ext_size(t
);
1723 /* eval an expression for #if/#elif */
1724 int expr_preprocess(void)
1730 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
) {
1731 next(); /* do macro subst */
1732 if (tok
== TOK_DEFINED
) {
1737 c
= sym_find1(&define_stack
, tok
) != 0;
1742 } else if (tok
>= TOK_IDENT
) {
1743 /* if undefined macro */
1747 tok_str_add_tok(&str
);
1749 tok_str_add(&str
, -1); /* simulate end of file */
1750 tok_str_add(&str
, 0);
1751 /* now evaluate C constant expression */
1752 macro_ptr
= str
.str
;
1756 tok_str_free(str
.str
);
1760 #if defined(DEBUG) || defined(PP_DEBUG)
1761 void tok_print(int *str
)
1767 t
= tok_get(&str
, &cval
);
1770 printf(" %s", get_tok_str(t
, &cval
));
1776 /* parse after #define */
1777 void parse_define(void)
1779 Sym
*s
, *first
, **ps
;
1780 int v
, t
, varg
, is_vaargs
;
1784 /* XXX: should check if same macro (ANSI) */
1787 /* '(' must be just after macro definition for MACRO_FUNC */
1792 while (tok
!= ')') {
1796 if (varg
== TOK_DOTS
) {
1797 varg
= TOK___VA_ARGS__
;
1799 } else if (tok
== TOK_DOTS
&& gnu_ext
) {
1803 if (varg
< TOK_IDENT
)
1804 error("badly punctuated parameter list");
1805 s
= sym_push1(&define_stack
, varg
| SYM_FIELD
, is_vaargs
, 0);
1817 if (ch
== '\n' || ch
== CH_EOF
)
1820 tok_str_add2(&str
, tok
, &tokc
);
1822 tok_str_add(&str
, 0);
1824 printf("define %s %d: ", get_tok_str(v
, NULL
), t
);
1827 s
= sym_push1(&define_stack
, v
, t
, (int)str
.str
);
1831 void preprocess(void)
1834 char buf
[1024], *q
, *p
;
1839 return_linefeed
= 1; /* linefeed will be returned as a token */
1843 if (tok
== TOK_DEFINE
) {
1846 } else if (tok
== TOK_UNDEF
) {
1848 s
= sym_find1(&define_stack
, tok
);
1849 /* undefine symbol by putting an invalid name */
1851 sym_undef(&define_stack
, s
);
1852 } else if (tok
== TOK_INCLUDE
) {
1857 } else if (ch
== '\"') {
1862 while (ch
!= c
&& ch
!= '\n' && ch
!= CH_EOF
) {
1863 if ((q
- buf
) < sizeof(buf
) - 1)
1868 /* eat all spaces and comments after include */
1869 /* XXX: slightly incorrect */
1870 while (ch1
!= '\n' && ch1
!= CH_EOF
)
1873 /* computed #include : either we have only strings or
1874 we have anything enclosed in '<>' */
1877 if (tok
== TOK_STR
) {
1878 while (tok
!= TOK_LINEFEED
) {
1879 if (tok
!= TOK_STR
) {
1881 error("'#include' expects \"FILENAME\" or <FILENAME>");
1883 pstrcat(buf
, sizeof(buf
), (char *)tokc
.cstr
->data
);
1889 while (tok
!= TOK_LINEFEED
) {
1890 pstrcat(buf
, sizeof(buf
), get_tok_str(tok
, &tokc
));
1894 /* check syntax and remove '<>' */
1895 if (len
< 2 || buf
[0] != '<' || buf
[len
- 1] != '>')
1896 goto include_syntax
;
1897 memmove(buf
, buf
+ 1, len
- 2);
1898 buf
[len
- 2] = '\0';
1903 if (include_stack_ptr
>= include_stack
+ INCLUDE_STACK_SIZE
)
1904 error("memory full");
1906 /* first search in current dir if "header.h" */
1908 p
= strrchr(file
->filename
, '/');
1910 size
= p
+ 1 - file
->filename
;
1911 if (size
> sizeof(buf1
) - 1)
1912 size
= sizeof(buf1
) - 1;
1913 memcpy(buf1
, file
->filename
, size
);
1915 pstrcat(buf1
, sizeof(buf1
), buf
);
1920 /* now search in all the include paths */
1921 n
= nb_include_paths
+ nb_sysinclude_paths
;
1922 for(i
= 0; i
< n
; i
++) {
1924 if (i
< nb_include_paths
)
1925 path
= include_paths
[i
];
1927 path
= sysinclude_paths
[i
- nb_include_paths
];
1928 pstrcpy(buf1
, sizeof(buf1
), path
);
1929 pstrcat(buf1
, sizeof(buf1
), "/");
1930 pstrcat(buf1
, sizeof(buf1
), buf
);
1935 error("include file '%s' not found", buf
);
1938 /* push current file in stack */
1939 /* XXX: fix current line init */
1940 *include_stack_ptr
++ = file
;
1942 /* add include file debug info */
1944 put_stabs(file
->filename
, N_BINCL
, 0, 0, 0);
1948 } else if (tok
== TOK_IFNDEF
) {
1951 } else if (tok
== TOK_IF
) {
1952 c
= expr_preprocess();
1954 } else if (tok
== TOK_IFDEF
) {
1958 c
= (sym_find1(&define_stack
, tok
) != 0) ^ c
;
1960 if (ifdef_stack_ptr
>= ifdef_stack
+ IFDEF_STACK_SIZE
)
1961 error("memory full");
1962 *ifdef_stack_ptr
++ = c
;
1964 } else if (tok
== TOK_ELSE
) {
1965 if (ifdef_stack_ptr
== ifdef_stack
)
1966 error("#else without matching #if");
1967 if (ifdef_stack_ptr
[-1] & 2)
1968 error("#else after #else");
1969 c
= (ifdef_stack_ptr
[-1] ^= 3);
1971 } else if (tok
== TOK_ELIF
) {
1972 if (ifdef_stack_ptr
== ifdef_stack
)
1973 error("#elif without matching #if");
1974 c
= ifdef_stack_ptr
[-1];
1976 error("#elif after #else");
1977 /* last #if/#elif expression was true: we skip */
1980 c
= expr_preprocess();
1981 ifdef_stack_ptr
[-1] = c
;
1988 } else if (tok
== TOK_ENDIF
) {
1989 if (ifdef_stack_ptr
== ifdef_stack
)
1990 error("#endif without matching #if");
1992 } else if (tok
== TOK_LINE
) {
1995 if (tok
!= TOK_CINT
)
1999 if (tok
!= TOK_LINEFEED
) {
2002 pstrcpy(file
->filename
, sizeof(file
->filename
),
2003 (char *)tokc
.cstr
->data
);
2005 /* NOTE: we do it there to avoid problems with linefeed */
2006 file
->line_num
= line_num
;
2007 } else if (tok
== TOK_ERROR
) {
2010 /* ignore other preprocess commands or #! for C scripts */
2011 while (tok
!= TOK_LINEFEED
&& tok
!= TOK_EOF
)
2014 return_linefeed
= 0;
2017 /* read a number in base b */
2018 static int getn(int b
)
2023 if (ch
>= 'a' && ch
<= 'f')
2025 else if (ch
>= 'A' && ch
<= 'F')
2031 if (t
< 0 || t
>= b
)
2039 /* read a character for string or char constant and eval escape codes */
2040 static int getq(void)
2048 /* at most three octal digits */
2052 c
= c
* 8 + ch
- '0';
2055 c
= c
* 8 + ch
- '0';
2060 } else if (ch
== 'x') {
2078 else if (ch
== 'e' && gnu_ext
)
2080 else if (ch
== '\'' || ch
== '\"' || ch
== '\\' || ch
== '?')
2083 error("invalid escaped char");
2086 } else if (c
== '\r' && ch
== '\n') {
2093 /* we use 64 bit numbers */
2096 /* bn = (bn << shift) | or_val */
2097 void bn_lshift(unsigned int *bn
, int shift
, int or_val
)
2101 for(i
=0;i
<BN_SIZE
;i
++) {
2103 bn
[i
] = (v
<< shift
) | or_val
;
2104 or_val
= v
>> (32 - shift
);
2108 void bn_zero(unsigned int *bn
)
2111 for(i
=0;i
<BN_SIZE
;i
++) {
2116 void parse_number(void)
2118 int b
, t
, shift
, frac_bits
, s
, exp_val
;
2120 unsigned int bn
[BN_SIZE
];
2130 /* special dot handling */
2131 if (ch
>= '0' && ch
<= '9') {
2132 goto float_frac_parse
;
2133 } else if (ch
== '.') {
2144 } else if (t
== '0') {
2145 if (ch
== 'x' || ch
== 'X') {
2149 } else if (tcc_ext
&& (ch
== 'b' || ch
== 'B')) {
2155 /* parse all digits. cannot check octal numbers at this stage
2156 because of floating point constants */
2158 if (ch
>= 'a' && ch
<= 'f')
2160 else if (ch
>= 'A' && ch
<= 'F')
2168 if (q
>= token_buf
+ STRING_MAX_SIZE
) {
2170 error("number too long");
2176 ((ch
== 'e' || ch
== 'E') && b
== 10) ||
2177 ((ch
== 'p' || ch
== 'P') && (b
== 16 || b
== 2))) {
2179 /* NOTE: strtox should support that for hexa numbers, but
2180 non ISOC99 libcs do not support it, so we prefer to do
2182 /* hexadecimal or binary floats */
2183 /* XXX: handle overflows */
2195 } else if (t
>= 'a') {
2197 } else if (t
>= 'A') {
2202 bn_lshift(bn
, shift
, t
);
2209 if (t
>= 'a' && t
<= 'f') {
2211 } else if (t
>= 'A' && t
<= 'F') {
2213 } else if (t
>= '0' && t
<= '9') {
2219 error("invalid digit");
2220 bn_lshift(bn
, shift
, t
);
2225 if (ch
!= 'p' && ch
!= 'P')
2226 error("exponent expected");
2232 } else if (ch
== '-') {
2236 if (ch
< '0' || ch
> '9')
2237 error("exponent digits expected");
2238 while (ch
>= '0' && ch
<= '9') {
2239 exp_val
= exp_val
* 10 + ch
- '0';
2242 exp_val
= exp_val
* s
;
2244 /* now we can generate the number */
2245 /* XXX: should patch directly float number */
2246 d
= (double)bn
[1] * 4294967296.0 + (double)bn
[0];
2247 d
= ldexp(d
, exp_val
- frac_bits
);
2252 /* float : should handle overflow */
2254 } else if (t
== 'L') {
2257 /* XXX: not large enough */
2258 tokc
.ld
= (long double)d
;
2264 /* decimal floats */
2266 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2271 while (ch
>= '0' && ch
<= '9') {
2272 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2278 if (ch
== 'e' || ch
== 'E') {
2279 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2283 if (ch
== '-' || ch
== '+') {
2284 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2289 if (ch
< '0' || ch
> '9')
2290 error("exponent digits expected");
2291 while (ch
>= '0' && ch
<= '9') {
2292 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2304 tokc
.f
= strtof(token_buf
, NULL
);
2305 } else if (t
== 'L') {
2308 tokc
.ld
= strtold(token_buf
, NULL
);
2311 tokc
.d
= strtod(token_buf
, NULL
);
2315 unsigned long long n
, n1
;
2318 /* integer number */
2321 if (b
== 10 && *q
== '0') {
2328 /* no need for checks except for base 10 / 8 errors */
2331 } else if (t
>= 'a') {
2333 } else if (t
>= 'A') {
2338 error("invalid digit");
2342 /* detect overflow */
2344 error("integer constant overflow");
2347 /* XXX: not exactly ANSI compliant */
2348 if ((n
& 0xffffffff00000000LL
) != 0) {
2353 } else if (n
> 0x7fffffff) {
2363 error("three 'l' in integer constant");
2366 if (tok
== TOK_CINT
)
2368 else if (tok
== TOK_CUINT
)
2372 } else if (t
== 'U') {
2373 if (tok
== TOK_CINT
)
2375 else if (tok
== TOK_CLLONG
)
2382 if (tok
== TOK_CINT
|| tok
== TOK_CUINT
)
2390 /* return next token without macro substitution */
2391 void next_nomacro1(void)
2399 while (ch
== '\n') {
2400 /* during preprocessor parsing, '\n' is a token */
2401 if (return_linefeed
) {
2408 /* preprocessor command if # at start of line after
2431 while (isid(ch
) || isnum(ch
)) {
2432 if (q
>= token_buf
+ STRING_MAX_SIZE
)
2433 error("ident too long");
2438 ts
= tok_alloc(token_buf
, q
- token_buf
);
2440 } else if (isnum(ch
) || ch
== '.') {
2442 } else if (ch
== '\'') {
2447 /* this cast is needed if >= 128 */
2448 if (tok
== TOK_CCHAR
)
2454 } else if (ch
== '\"') {
2458 cstr_reset(&tokcstr
);
2459 while (ch
!= '\"') {
2462 error("unterminated string");
2464 cstr_ccat(&tokcstr
, b
);
2466 cstr_wccat(&tokcstr
, b
);
2469 cstr_ccat(&tokcstr
, '\0');
2471 cstr_wccat(&tokcstr
, '\0');
2472 tokc
.cstr
= &tokcstr
;
2480 if (*q
== tok
&& q
[1] == ch
) {
2483 /* three chars tests */
2484 if (tok
== TOK_SHL
|| tok
== TOK_SAR
) {
2489 } else if (tok
== TOK_DOTS
) {
2491 error("parse error");
2498 /* single char substitutions */
2501 else if (tok
== '>')
2506 /* return next token without macro substitution. Can read input from
2514 tok
= tok_get(¯o_ptr
, &tokc
);
2515 if (tok
== TOK_LINENUM
) {
2516 file
->line_num
= tokc
.i
;
2525 /* substitute args in macro_str and return allocated string */
2526 int *macro_arg_subst(Sym
**nested_list
, int *macro_str
, Sym
*args
)
2528 int *st
, last_tok
, t
, notfirst
;
2537 t
= tok_get(¯o_str
, &cval
);
2542 t
= tok_get(¯o_str
, &cval
);
2545 s
= sym_find2(args
, t
);
2552 cstr_ccat(&cstr
, ' ');
2553 t
= tok_get(&st
, &cval
);
2554 cstr_cat(&cstr
, get_tok_str(t
, &cval
));
2557 cstr_ccat(&cstr
, '\0');
2559 printf("stringize: %s\n", (char *)cstr
.data
);
2563 tok_str_add2(&str
, TOK_STR
, &cval
);
2566 tok_str_add2(&str
, t
, &cval
);
2568 } else if (t
>= TOK_IDENT
) {
2569 s
= sym_find2(args
, t
);
2572 /* if '##' is present before or after, no arg substitution */
2573 if (*macro_str
== TOK_TWOSHARPS
|| last_tok
== TOK_TWOSHARPS
) {
2574 /* special case for var arg macros : ## eats the
2575 ',' if empty VA_ARGS riable. */
2576 /* XXX: test of the ',' is not 100%
2577 reliable. should fix it to avoid security
2579 if (gnu_ext
&& s
->t
&& *st
== 0 &&
2580 last_tok
== TOK_TWOSHARPS
&&
2581 str
.len
>= 2 && str
.str
[str
.len
- 2] == ',') {
2582 /* suppress ',' '##' */
2587 t1
= tok_get(&st
, &cval
);
2590 tok_str_add2(&str
, t1
, &cval
);
2594 macro_subst(&str
, nested_list
, st
);
2597 tok_str_add(&str
, t
);
2600 tok_str_add2(&str
, t
, &cval
);
2604 tok_str_add(&str
, 0);
2608 /* handle the '##' operator */
2609 int *macro_twosharps(int *macro_str
)
2616 TokenString macro_str1
;
2618 tok_str_new(¯o_str1
);
2624 while (*macro_ptr
== TOK_TWOSHARPS
) {
2626 macro_ptr1
= macro_ptr
;
2629 t
= tok_get(¯o_ptr
, &cval
);
2630 /* XXX: we handle only most common cases:
2631 ident + ident or ident + number */
2632 if (tok
>= TOK_IDENT
&&
2633 (t
>= TOK_IDENT
|| t
== TOK_CINT
)) {
2634 p
= get_tok_str(tok
, &tokc
);
2635 pstrcpy(token_buf
, sizeof(token_buf
), p
);
2636 p
= get_tok_str(t
, &cval
);
2637 pstrcat(token_buf
, sizeof(token_buf
), p
);
2638 ts
= tok_alloc(token_buf
, 0);
2639 tok
= ts
->tok
; /* modify current token */
2641 /* cannot merge tokens: skip '##' */
2642 macro_ptr
= macro_ptr1
;
2647 tok_str_add2(¯o_str1
, tok
, &tokc
);
2649 tok_str_add(¯o_str1
, 0);
2650 return macro_str1
.str
;
2653 /* do macro substitution of macro_str and add result to
2654 (tok_str,tok_len). If macro_str is NULL, then input stream token is
2655 substituted. 'nested_list' is the list of all macros we got inside
2656 to avoid recursing. */
2657 void macro_subst(TokenString
*tok_str
,
2658 Sym
**nested_list
, int *macro_str
)
2660 Sym
*s
, *args
, *sa
, *sa1
;
2661 int parlevel
, *mstr
, t
, *saved_macro_ptr
;
2662 int mstr_allocated
, *macro_str1
;
2668 saved_macro_ptr
= macro_ptr
;
2669 macro_ptr
= macro_str
;
2672 /* first scan for '##' operator handling */
2673 macro_str1
= macro_twosharps(macro_str
);
2674 macro_ptr
= macro_str1
;
2681 if ((s
= sym_find1(&define_stack
, tok
)) != NULL
) {
2682 /* if symbol is a macro, prepare substitution */
2683 /* if nested substitution, do nothing */
2684 if (sym_find2(*nested_list
, tok
))
2687 /* special macros */
2688 if (tok
== TOK___LINE__
) {
2689 cval
.i
= file
->line_num
;
2690 tok_str_add2(tok_str
, TOK_CINT
, &cval
);
2691 } else if (tok
== TOK___FILE__
) {
2692 cstrval
= file
->filename
;
2694 tok_str_add2(tok_str
, TOK_STR
, &cval
);
2695 } else if (tok
== TOK___DATE__
) {
2696 cstrval
= "Jan 1 2002";
2698 } else if (tok
== TOK___TIME__
) {
2699 cstrval
= "00:00:00";
2702 cstr_cat(&cstr
, cstrval
);
2703 cstr_ccat(&cstr
, '\0');
2705 tok_str_add2(tok_str
, TOK_STR
, &cval
);
2710 if (s
->t
== MACRO_FUNC
) {
2711 /* NOTE: we do not use next_nomacro to avoid eating the
2712 next token. XXX: find better solution */
2716 while (is_space(ch
) || ch
== '\n')
2720 if (t
!= '(') /* no macro subst */
2723 /* argument macro */
2728 /* NOTE: empty args are allowed, except if no args */
2730 /* handle '()' case */
2731 if (!args
&& tok
== ')')
2734 error("macro '%s' used with too many args",
2735 get_tok_str(s
->v
, 0));
2738 /* NOTE: non zero sa->t indicates VA_ARGS */
2739 while ((parlevel
> 0 ||
2741 (tok
!= ',' || sa
->t
))) &&
2745 else if (tok
== ')')
2747 tok_str_add2(&str
, tok
, &tokc
);
2750 tok_str_add(&str
, 0);
2751 sym_push2(&args
, sa
->v
& ~SYM_FIELD
, sa
->t
, (int)str
.str
);
2754 /* special case for gcc var args: add an empty
2755 var arg argument if it is omitted */
2756 if (sa
&& sa
->t
&& gnu_ext
)
2766 error("macro '%s' used with too few args",
2767 get_tok_str(s
->v
, 0));
2770 /* now subst each arg */
2771 mstr
= macro_arg_subst(nested_list
, mstr
, args
);
2776 tok_str_free((int *)sa
->c
);
2782 sym_push2(nested_list
, s
->v
, 0, 0);
2783 macro_subst(tok_str
, nested_list
, mstr
);
2784 /* pop nested defined symbol */
2786 *nested_list
= sa1
->prev
;
2793 /* no need to add if reading input stream */
2796 tok_str_add2(tok_str
, tok
, &tokc
);
2798 /* only replace one macro while parsing input stream */
2802 macro_ptr
= saved_macro_ptr
;
2804 tok_str_free(macro_str1
);
2807 /* return next token with macro substitution */
2813 /* special 'ungettok' case for label parsing */
2821 /* if not reading from macro substituted string, then try
2823 /* XXX: optimize non macro case */
2826 macro_subst(&str
, &nested_list
, NULL
);
2828 tok_str_add(&str
, 0);
2829 macro_ptr
= str
.str
;
2830 macro_ptr_allocated
= str
.str
;
2838 /* end of macro string: free it */
2839 tok_str_free(macro_ptr_allocated
);
2846 printf("token = %s\n", get_tok_str(tok
, &tokc
));
2850 void swap(int *p
, int *q
)
2858 void vsetc(int t
, int r
, CValue
*vc
)
2860 if (vtop
>= vstack
+ VSTACK_SIZE
)
2861 error("memory full");
2862 /* cannot let cpu flags if other instruction are generated */
2863 /* XXX: VT_JMP test too ? */
2864 if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
2869 vtop
->r2
= VT_CONST
;
2873 /* push integer constant */
2878 vsetc(VT_INT
, VT_CONST
, &cval
);
2881 /* Return a static symbol pointing to a section */
2882 static Sym
*get_sym_ref(int t
, Section
*sec
,
2883 unsigned long offset
, unsigned long size
)
2889 sym
= sym_push1(&global_stack
, v
, t
| VT_STATIC
, 0);
2890 sym
->r
= VT_CONST
| VT_SYM
;
2891 put_extern_sym(sym
, sec
, offset
, size
);
2895 /* push a reference to a section offset by adding a dummy symbol */
2896 static void vpush_ref(int t
, Section
*sec
, unsigned long offset
, unsigned long size
)
2901 vsetc(t
, VT_CONST
| VT_SYM
, &cval
);
2902 vtop
->sym
= get_sym_ref(t
, sec
, offset
, size
);
2905 /* define a new external reference to a symbol 'v' of type 'u' */
2906 static Sym
*external_global_sym(int v
, int u
, int r
)
2912 /* push forward reference */
2913 s
= sym_push1(&global_stack
,
2914 v
, u
| VT_EXTERN
, 0);
2915 s
->r
= r
| VT_CONST
| VT_SYM
;
2920 /* define a new external reference to a symbol 'v' of type 'u' */
2921 static Sym
*external_sym(int v
, int u
, int r
)
2927 /* push forward reference */
2928 s
= sym_push(v
, u
| VT_EXTERN
, r
| VT_CONST
| VT_SYM
, 0);
2933 /* push a reference to global symbol v */
2934 static void vpush_global_sym(int t
, int v
)
2939 sym
= external_global_sym(v
, t
, 0);
2941 vsetc(t
, VT_CONST
| VT_SYM
, &cval
);
2945 void vset(int t
, int r
, int v
)
2962 void vpushv(SValue
*v
)
2964 if (vtop
>= vstack
+ VSTACK_SIZE
)
2965 error("memory full");
2975 /* save r to the memory stack, and mark it as being free */
2976 void save_reg(int r
)
2978 int l
, saved
, t
, size
, align
;
2981 /* modify all stack values */
2984 for(p
=vstack
;p
<=vtop
;p
++) {
2985 if ((p
->r
& VT_VALMASK
) == r
||
2986 (p
->r2
& VT_VALMASK
) == r
) {
2987 /* must save value on stack if not already done */
2989 /* store register in the stack */
2991 if ((p
->r
& VT_LVAL
) ||
2992 (!is_float(t
) && (t
& VT_BTYPE
) != VT_LLONG
))
2994 size
= type_size(t
, &align
);
2995 loc
= (loc
- size
) & -align
;
2997 sv
.r
= VT_LOCAL
| VT_LVAL
;
3000 #ifdef TCC_TARGET_I386
3001 /* x86 specific: need to pop fp register ST0 if saved */
3003 o(0xd9dd); /* fstp %st(1) */
3006 /* special long long case */
3007 if ((t
& VT_BTYPE
) == VT_LLONG
) {
3014 /* mark that stack entry as being saved on the stack */
3015 if (p
->r
& VT_LVAL
) {
3016 /* also suppress the bounded flag because the
3017 relocation address of the function was stored in
3019 p
->r
= (p
->r
& ~(VT_VALMASK
| VT_BOUNDED
)) | VT_LLOCAL
;
3021 p
->r
= lvalue_type(p
->t
) | VT_LOCAL
;
3029 /* find a free register of class 'rc'. If none, save one register */
3035 /* find a free register */
3036 for(r
=0;r
<NB_REGS
;r
++) {
3037 if (reg_classes
[r
] & rc
) {
3038 for(p
=vstack
;p
<=vtop
;p
++) {
3039 if ((p
->r
& VT_VALMASK
) == r
||
3040 (p
->r2
& VT_VALMASK
) == r
)
3048 /* no register left : free the first one on the stack (VERY
3049 IMPORTANT to start from the bottom to ensure that we don't
3050 spill registers used in gen_opi()) */
3051 for(p
=vstack
;p
<=vtop
;p
++) {
3052 r
= p
->r
& VT_VALMASK
;
3053 if (r
< VT_CONST
&& (reg_classes
[r
] & rc
)) {
3061 /* save registers up to (vtop - n) stack entry */
3062 void save_regs(int n
)
3067 for(p
= vstack
;p
<= p1
; p
++) {
3068 r
= p
->r
& VT_VALMASK
;
3075 /* move register 's' to 'r', and flush previous value of r to memory
3077 void move_reg(int r
, int s
)
3090 /* get address of vtop (vtop MUST BE an lvalue) */
3093 vtop
->r
&= ~VT_LVAL
;
3094 /* tricky: if saved lvalue, then we can go back to lvalue */
3095 if ((vtop
->r
& VT_VALMASK
) == VT_LLOCAL
)
3096 vtop
->r
= (vtop
->r
& ~(VT_VALMASK
| VT_LVAL_TYPE
)) | VT_LOCAL
| VT_LVAL
;
3099 #ifdef CONFIG_TCC_BCHECK
3100 /* generate lvalue bound code */
3105 vtop
->r
&= ~VT_MUSTBOUND
;
3106 /* if lvalue, then use checking code before dereferencing */
3107 if (vtop
->r
& VT_LVAL
) {
3108 /* if not VT_BOUNDED value, then make one */
3109 if (!(vtop
->r
& VT_BOUNDED
)) {
3110 lval_type
= vtop
->r
& (VT_LVAL_TYPE
| VT_LVAL
);
3111 /* must save type because we must set it to int to get pointer */
3116 gen_bounded_ptr_add();
3117 vtop
->r
|= lval_type
;
3120 /* then check for dereferencing */
3121 gen_bounded_ptr_deref();
3126 /* store vtop a register belonging to class 'rc'. lvalues are
3127 converted to values. Cannot be used if cannot be converted to
3128 register value (such as structures). */
3131 int r
, r2
, rc2
, bit_pos
, bit_size
, size
, align
, i
;
3132 unsigned long long ll
;
3134 /* NOTE: get_reg can modify vstack[] */
3135 if (vtop
->t
& VT_BITFIELD
) {
3136 bit_pos
= (vtop
->t
>> VT_STRUCT_SHIFT
) & 0x3f;
3137 bit_size
= (vtop
->t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
3138 /* remove bit field info to avoid loops */
3139 vtop
->t
&= ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
3140 /* generate shifts */
3141 vpushi(32 - (bit_pos
+ bit_size
));
3143 vpushi(32 - bit_size
);
3144 /* NOTE: transformed to SHR if unsigned */
3148 if (is_float(vtop
->t
) &&
3149 (vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
3152 unsigned long offset
;
3154 /* XXX: unify with initializers handling ? */
3155 /* CPUs usually cannot use float constants, so we store them
3156 generically in data segment */
3157 size
= type_size(vtop
->t
, &align
);
3158 offset
= (data_section
->data_offset
+ align
- 1) & -align
;
3159 data_section
->data_offset
= offset
;
3160 /* XXX: not portable yet */
3161 ptr
= section_ptr_add(data_section
, size
);
3164 ptr
[i
] = vtop
->c
.tab
[i
];
3165 sym
= get_sym_ref(vtop
->t
, data_section
, offset
, size
<< 2);
3166 vtop
->r
|= VT_LVAL
| VT_SYM
;
3170 #ifdef CONFIG_TCC_BCHECK
3171 if (vtop
->r
& VT_MUSTBOUND
)
3175 r
= vtop
->r
& VT_VALMASK
;
3176 /* need to reload if:
3178 - lvalue (need to dereference pointer)
3179 - already a register, but not in the right class */
3180 if (r
>= VT_CONST
||
3181 (vtop
->r
& VT_LVAL
) ||
3182 !(reg_classes
[r
] & rc
) ||
3183 ((vtop
->t
& VT_BTYPE
) == VT_LLONG
&&
3184 !(reg_classes
[vtop
->r2
] & rc
))) {
3186 if ((vtop
->t
& VT_BTYPE
) == VT_LLONG
) {
3187 /* two register type load : expand to two words
3189 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) == VT_CONST
) {
3192 vtop
->c
.ui
= ll
; /* first word */
3194 vtop
->r
= r
; /* save register value */
3195 vpushi(ll
>> 32); /* second word */
3196 } else if (r
>= VT_CONST
||
3197 (vtop
->r
& VT_LVAL
)) {
3198 /* load from memory */
3201 vtop
[-1].r
= r
; /* save register value */
3202 /* increment pointer to get second word */
3209 /* move registers */
3212 vtop
[-1].r
= r
; /* save register value */
3213 vtop
->r
= vtop
[-1].r2
;
3215 /* allocate second register */
3222 /* write second register */
3224 } else if ((vtop
->r
& VT_LVAL
) && !is_float(vtop
->t
)) {
3226 /* lvalue of scalar type : need to use lvalue type
3227 because of possible cast */
3230 /* compute memory access type */
3231 if (vtop
->r
& VT_LVAL_BYTE
)
3233 else if (vtop
->r
& VT_LVAL_SHORT
)
3235 if (vtop
->r
& VT_LVAL_UNSIGNED
)
3239 /* restore wanted type */
3242 /* one register type load */
3251 /* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
3252 void gv2(int rc1
, int rc2
)
3254 /* generate more generic register first */
3260 /* test if reload is needed for first register */
3261 if ((vtop
[-1].r
& VT_VALMASK
) >= VT_CONST
) {
3271 /* test if reload is needed for first register */
3272 if ((vtop
[0].r
& VT_VALMASK
) >= VT_CONST
) {
3278 /* expand long long on stack in two int registers */
3283 u
= vtop
->t
& VT_UNSIGNED
;
3286 vtop
[0].r
= vtop
[-1].r2
;
3287 vtop
[0].r2
= VT_CONST
;
3288 vtop
[-1].r2
= VT_CONST
;
3289 vtop
[0].t
= VT_INT
| u
;
3290 vtop
[-1].t
= VT_INT
| u
;
3293 /* build a long long from two ints */
3296 gv2(RC_INT
, RC_INT
);
3297 vtop
[-1].r2
= vtop
[0].r
;
3302 /* rotate n first stack elements to the bottom */
3309 for(i
=-n
+1;i
!=0;i
++)
3310 vtop
[i
] = vtop
[i
+1];
3314 /* pop stack value */
3318 v
= vtop
->r
& VT_VALMASK
;
3319 #ifdef TCC_TARGET_I386
3320 /* for x86, we need to pop the FP stack */
3322 o(0xd9dd); /* fstp %st(1) */
3325 if (v
== VT_JMP
|| v
== VT_JMPI
) {
3326 /* need to put correct jump if && or || without test */
3332 /* convert stack entry to register and duplicate its value in another
3340 if ((t
& VT_BTYPE
) == VT_LLONG
) {
3347 /* stack: H L L1 H1 */
3355 /* duplicate value */
3366 load(r1
, &sv
); /* move r to r1 */
3368 /* duplicates value */
3373 /* generate CPU independent (unsigned) long long operations */
3374 void gen_opl(int op
)
3376 int t
, a
, b
, op1
, c
, i
;
3384 func
= TOK___divdi3
;
3387 func
= TOK___udivdi3
;
3390 func
= TOK___moddi3
;
3393 func
= TOK___umoddi3
;
3395 /* call generic long long function */
3396 gfunc_start(&gf
, FUNC_CDECL
);
3399 vpush_global_sym(func_old_type
, func
);
3403 vtop
->r2
= REG_LRET
;
3416 /* stack: L1 H1 L2 H2 */
3421 vtop
[-2] = vtop
[-3];
3424 /* stack: H1 H2 L1 L2 */
3430 /* stack: H1 H2 L1 L2 ML MH */
3433 /* stack: ML MH H1 H2 L1 L2 */
3437 /* stack: ML MH H1 L2 H2 L1 */
3442 /* stack: ML MH M1 M2 */
3445 } else if (op
== '+' || op
== '-') {
3446 /* XXX: add non carry method too (for MIPS or alpha) */
3452 /* stack: H1 H2 (L1 op L2) */
3455 gen_op(op1
+ 1); /* TOK_xxxC2 */
3458 /* stack: H1 H2 (L1 op L2) */
3461 /* stack: (L1 op L2) H1 H2 */
3463 /* stack: (L1 op L2) (H1 op H2) */
3471 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) {
3476 /* stack: L H shift */
3478 /* constant: simpler */
3479 /* NOTE: all comments are for SHL. the other cases are
3480 done by swaping words */
3491 if (op
!= TOK_SAR
) {
3521 /* XXX: should provide a faster fallback on x86 ? */
3524 func
= TOK___sardi3
;
3527 func
= TOK___shrdi3
;
3530 func
= TOK___shldi3
;
3536 /* compare operations */
3542 /* stack: L1 H1 L2 H2 */
3544 vtop
[-1] = vtop
[-2];
3546 /* stack: L1 L2 H1 H2 */
3549 /* when values are equal, we need to compare low words. since
3550 the jump is inverted, we invert the test too. */
3553 else if (op1
== TOK_GT
)
3555 else if (op1
== TOK_ULT
)
3557 else if (op1
== TOK_UGT
)
3562 if (op1
!= TOK_NE
) {
3566 /* generate non equal test */
3567 /* XXX: NOT PORTABLE yet */
3571 #ifdef TCC_TARGET_I386
3572 b
= psym(0x850f, 0);
3574 error("not implemented");
3582 vset(VT_INT
, VT_JMPI
, a
);
3587 /* handle integer constant optimizations and various machine
3589 void gen_opic(int op
)
3596 /* currently, we cannot do computations with forward symbols */
3597 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
3598 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
3602 case '+': v1
->c
.i
+= fc
; break;
3603 case '-': v1
->c
.i
-= fc
; break;
3604 case '&': v1
->c
.i
&= fc
; break;
3605 case '^': v1
->c
.i
^= fc
; break;
3606 case '|': v1
->c
.i
|= fc
; break;
3607 case '*': v1
->c
.i
*= fc
; break;
3614 /* if division by zero, generate explicit division */
3617 error("division by zero in constant");
3621 default: v1
->c
.i
/= fc
; break;
3622 case '%': v1
->c
.i
%= fc
; break;
3623 case TOK_UDIV
: v1
->c
.i
= (unsigned)v1
->c
.i
/ fc
; break;
3624 case TOK_UMOD
: v1
->c
.i
= (unsigned)v1
->c
.i
% fc
; break;
3627 case TOK_SHL
: v1
->c
.i
<<= fc
; break;
3628 case TOK_SHR
: v1
->c
.i
= (unsigned)v1
->c
.i
>> fc
; break;
3629 case TOK_SAR
: v1
->c
.i
>>= fc
; break;
3631 case TOK_ULT
: v1
->c
.i
= (unsigned)v1
->c
.i
< (unsigned)fc
; break;
3632 case TOK_UGE
: v1
->c
.i
= (unsigned)v1
->c
.i
>= (unsigned)fc
; break;
3633 case TOK_EQ
: v1
->c
.i
= v1
->c
.i
== fc
; break;
3634 case TOK_NE
: v1
->c
.i
= v1
->c
.i
!= fc
; break;
3635 case TOK_ULE
: v1
->c
.i
= (unsigned)v1
->c
.i
<= (unsigned)fc
; break;
3636 case TOK_UGT
: v1
->c
.i
= (unsigned)v1
->c
.i
> (unsigned)fc
; break;
3637 case TOK_LT
: v1
->c
.i
= v1
->c
.i
< fc
; break;
3638 case TOK_GE
: v1
->c
.i
= v1
->c
.i
>= fc
; break;
3639 case TOK_LE
: v1
->c
.i
= v1
->c
.i
<= fc
; break;
3640 case TOK_GT
: v1
->c
.i
= v1
->c
.i
> fc
; break;
3642 case TOK_LAND
: v1
->c
.i
= v1
->c
.i
&& fc
; break;
3643 case TOK_LOR
: v1
->c
.i
= v1
->c
.i
|| fc
; break;
3649 /* if commutative ops, put c2 as constant */
3650 if (c1
&& (op
== '+' || op
== '&' || op
== '^' ||
3651 op
== '|' || op
== '*')) {
3656 if (c2
&& (((op
== '*' || op
== '/' || op
== TOK_UDIV
||
3659 ((op
== '+' || op
== '-' || op
== '|' || op
== '^' ||
3660 op
== TOK_SHL
|| op
== TOK_SHR
|| op
== TOK_SAR
) &&
3666 } else if (c2
&& (op
== '*' || op
== TOK_PDIV
|| op
== TOK_UDIV
)) {
3667 /* try to use shifts instead of muls or divs */
3668 if (fc
> 0 && (fc
& (fc
- 1)) == 0) {
3677 else if (op
== TOK_PDIV
)
3683 } else if (c2
&& (op
== '+' || op
== '-') &&
3684 (vtop
[-1].r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) ==
3685 (VT_CONST
| VT_SYM
)) {
3686 /* symbol + constant case */
3693 /* call low level op generator */
3699 /* generate a floating point operation with constant propagation */
3700 void gen_opif(int op
)
3708 /* currently, we cannot do computations with forward symbols */
3709 c1
= (v1
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
3710 c2
= (v2
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
3712 if (v1
->t
== VT_FLOAT
) {
3715 } else if (v1
->t
== VT_DOUBLE
) {
3723 /* NOTE: we only do constant propagation if finite number (not
3724 NaN or infinity) (ANSI spec) */
3725 if (!ieee_finite(f1
) || !ieee_finite(f2
))
3729 case '+': f1
+= f2
; break;
3730 case '-': f1
-= f2
; break;
3731 case '*': f1
*= f2
; break;
3735 error("division by zero in constant");
3740 /* XXX: also handles tests ? */
3744 /* XXX: overflow test ? */
3745 if (v1
->t
== VT_FLOAT
) {
3747 } else if (v1
->t
== VT_DOUBLE
) {
3759 int pointed_size(int t
)
3761 return type_size(pointed_type(t
), &t
);
3765 void check_pointer_types(SValue
*p1
, SValue
*p2
)
3767 char buf1
[256], buf2
[256];
3771 if (!is_compatible_types(t1
, t2
)) {
3772 type_to_str(buf1
, sizeof(buf1
), t1
, NULL
);
3773 type_to_str(buf2
, sizeof(buf2
), t2
, NULL
);
3774 error("incompatible pointers '%s' and '%s'", buf1
, buf2
);
3779 /* generic gen_op: handles types problems */
3782 int u
, t1
, t2
, bt1
, bt2
, t
;
3786 bt1
= t1
& VT_BTYPE
;
3787 bt2
= t2
& VT_BTYPE
;
3789 if (bt1
== VT_PTR
|| bt2
== VT_PTR
) {
3790 /* at least one operand is a pointer */
3791 /* relationnal op: must be both pointers */
3792 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
3793 // check_pointer_types(vtop, vtop - 1);
3794 /* pointers are handled are unsigned */
3795 t
= VT_INT
| VT_UNSIGNED
;
3798 /* if both pointers, then it must be the '-' op */
3799 if ((t1
& VT_BTYPE
) == VT_PTR
&&
3800 (t2
& VT_BTYPE
) == VT_PTR
) {
3802 error("cannot use pointers here");
3803 // check_pointer_types(vtop - 1, vtop);
3804 /* XXX: check that types are compatible */
3805 u
= pointed_size(t1
);
3807 /* set to integer type */
3812 /* exactly one pointer : must be '+' or '-'. */
3813 if (op
!= '-' && op
!= '+')
3814 error("cannot use pointers here");
3815 /* Put pointer as first operand */
3816 if ((t2
& VT_BTYPE
) == VT_PTR
) {
3820 /* XXX: cast to int ? (long long case) */
3821 vpushi(pointed_size(vtop
[-1].t
));
3823 #ifdef CONFIG_TCC_BCHECK
3824 /* if evaluating constant expression, no code should be
3825 generated, so no bound check */
3826 if (do_bounds_check
&& !const_wanted
) {
3827 /* if bounded pointers, we generate a special code to
3834 gen_bounded_ptr_add();
3840 /* put again type if gen_opic() swaped operands */
3843 } else if (is_float(bt1
) || is_float(bt2
)) {
3844 /* compute bigger type and do implicit casts */
3845 if (bt1
== VT_LDOUBLE
|| bt2
== VT_LDOUBLE
) {
3847 } else if (bt1
== VT_DOUBLE
|| bt2
== VT_DOUBLE
) {
3852 /* floats can only be used for a few operations */
3853 if (op
!= '+' && op
!= '-' && op
!= '*' && op
!= '/' &&
3854 (op
< TOK_ULT
|| op
> TOK_GT
))
3855 error("invalid operands for binary operation");
3857 } else if (bt1
== VT_LLONG
|| bt2
== VT_LLONG
) {
3858 /* cast to biggest op */
3860 /* convert to unsigned if it does not fit in a long long */
3861 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
) ||
3862 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_LLONG
| VT_UNSIGNED
))
3866 /* integer operations */
3868 /* convert to unsigned if it does not fit in an integer */
3869 if ((t1
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
) ||
3870 (t2
& (VT_BTYPE
| VT_UNSIGNED
)) == (VT_INT
| VT_UNSIGNED
))
3873 /* XXX: currently, some unsigned operations are explicit, so
3874 we modify them here */
3875 if (t
& VT_UNSIGNED
) {
3882 else if (op
== TOK_LT
)
3884 else if (op
== TOK_GT
)
3886 else if (op
== TOK_LE
)
3888 else if (op
== TOK_GE
)
3894 /* special case for shifts and long long: we keep the shift as
3896 if (op
== TOK_SHR
|| op
== TOK_SAR
|| op
== TOK_SHL
)
3902 else if ((t
& VT_BTYPE
) == VT_LLONG
)
3906 if (op
>= TOK_ULT
&& op
<= TOK_GT
) {
3907 /* relationnal op: the result is an int */
3915 /* generic itof for unsigned long long case */
3916 void gen_cvt_itof1(int t
)
3920 if ((vtop
->t
& (VT_BTYPE
| VT_UNSIGNED
)) ==
3921 (VT_LLONG
| VT_UNSIGNED
)) {
3923 gfunc_start(&gf
, FUNC_CDECL
);
3926 vpush_global_sym(func_old_type
, TOK___ulltof
);
3927 else if (t
== VT_DOUBLE
)
3928 vpush_global_sym(func_old_type
, TOK___ulltod
);
3930 vpush_global_sym(func_old_type
, TOK___ulltold
);
3939 /* generic ftoi for unsigned long long case */
3940 void gen_cvt_ftoi1(int t
)
3945 if (t
== (VT_LLONG
| VT_UNSIGNED
)) {
3946 /* not handled natively */
3947 gfunc_start(&gf
, FUNC_CDECL
);
3948 st
= vtop
->t
& VT_BTYPE
;
3951 vpush_global_sym(func_old_type
, TOK___fixunssfdi
);
3952 else if (st
== VT_DOUBLE
)
3953 vpush_global_sym(func_old_type
, TOK___fixunsdfdi
);
3955 vpush_global_sym(func_old_type
, TOK___fixunsxfdi
);
3959 vtop
->r2
= REG_LRET
;
3965 /* force char or short cast */
3966 void force_charshort_cast(int t
)
3970 /* XXX: add optimization if lvalue : just change type and offset */
3975 if (t
& VT_UNSIGNED
) {
3976 vpushi((1 << bits
) - 1);
3987 /* cast 'vtop' to 't' type */
3988 void gen_cast(int t
)
3990 int sbt
, dbt
, sf
, df
, c
;
3992 /* special delayed cast for char/short */
3993 /* XXX: in some cases (multiple cascaded casts), it may still
3995 if (vtop
->r
& VT_MUSTCAST
) {
3996 vtop
->r
&= ~VT_MUSTCAST
;
3997 force_charshort_cast(vtop
->t
);
4000 dbt
= t
& (VT_BTYPE
| VT_UNSIGNED
);
4001 sbt
= vtop
->t
& (VT_BTYPE
| VT_UNSIGNED
);
4006 c
= (vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
;
4008 /* convert from fp to fp */
4010 /* constant case: we can do it now */
4011 /* XXX: in ISOC, cannot do it if error in convert */
4012 if (dbt
== VT_FLOAT
&& sbt
== VT_DOUBLE
)
4013 vtop
->c
.f
= (float)vtop
->c
.d
;
4014 else if (dbt
== VT_FLOAT
&& sbt
== VT_LDOUBLE
)
4015 vtop
->c
.f
= (float)vtop
->c
.ld
;
4016 else if (dbt
== VT_DOUBLE
&& sbt
== VT_FLOAT
)
4017 vtop
->c
.d
= (double)vtop
->c
.f
;
4018 else if (dbt
== VT_DOUBLE
&& sbt
== VT_LDOUBLE
)
4019 vtop
->c
.d
= (double)vtop
->c
.ld
;
4020 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_FLOAT
)
4021 vtop
->c
.ld
= (long double)vtop
->c
.f
;
4022 else if (dbt
== VT_LDOUBLE
&& sbt
== VT_DOUBLE
)
4023 vtop
->c
.ld
= (long double)vtop
->c
.d
;
4025 /* non constant case: generate code */
4029 /* convert int to fp */
4032 case VT_LLONG
| VT_UNSIGNED
:
4034 /* XXX: add const cases for long long */
4036 case VT_INT
| VT_UNSIGNED
:
4038 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.ui
; break;
4039 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.ui
; break;
4040 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.ui
; break;
4045 case VT_FLOAT
: vtop
->c
.f
= (float)vtop
->c
.i
; break;
4046 case VT_DOUBLE
: vtop
->c
.d
= (double)vtop
->c
.i
; break;
4047 case VT_LDOUBLE
: vtop
->c
.ld
= (long double)vtop
->c
.i
; break;
4056 /* convert fp to int */
4057 /* we handle char/short/etc... with generic code */
4058 if (dbt
!= (VT_INT
| VT_UNSIGNED
) &&
4059 dbt
!= (VT_LLONG
| VT_UNSIGNED
) &&
4064 case VT_LLONG
| VT_UNSIGNED
:
4066 /* XXX: add const cases for long long */
4068 case VT_INT
| VT_UNSIGNED
:
4070 case VT_FLOAT
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
4071 case VT_DOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
4072 case VT_LDOUBLE
: vtop
->c
.ui
= (unsigned int)vtop
->c
.d
; break;
4078 case VT_FLOAT
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
4079 case VT_DOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
4080 case VT_LDOUBLE
: vtop
->c
.i
= (int)vtop
->c
.d
; break;
4088 if (dbt
== VT_INT
&& (t
& (VT_BTYPE
| VT_UNSIGNED
)) != dbt
) {
4089 /* additionnal cast for char/short/bool... */
4093 } else if ((dbt
& VT_BTYPE
) == VT_LLONG
) {
4094 if ((sbt
& VT_BTYPE
) != VT_LLONG
) {
4095 /* scalar to long long */
4097 if (sbt
== (VT_INT
| VT_UNSIGNED
))
4098 vtop
->c
.ll
= vtop
->c
.ui
;
4100 vtop
->c
.ll
= vtop
->c
.i
;
4102 /* machine independant conversion */
4104 /* generate high word */
4105 if (sbt
== (VT_INT
| VT_UNSIGNED
)) {
4113 /* patch second register */
4114 vtop
[-1].r2
= vtop
->r
;
4118 } else if (dbt
== VT_BOOL
) {
4119 /* scalar to bool */
4122 } else if ((dbt
& VT_BTYPE
) == VT_BYTE
||
4123 (dbt
& VT_BTYPE
) == VT_SHORT
) {
4124 force_charshort_cast(t
);
4125 } else if ((dbt
& VT_BTYPE
) == VT_INT
) {
4127 if (sbt
== VT_LLONG
) {
4128 /* from long long: just take low order word */
4132 /* if lvalue and single word type, nothing to do because
4133 the lvalue already contains the real type size (see
4134 VT_LVAL_xxx constants) */
4140 /* return type size. Put alignment at 'a' */
4141 int type_size(int t
, int *a
)
4147 if (bt
== VT_STRUCT
) {
4149 s
= sym_find(((unsigned)t
>> VT_STRUCT_SHIFT
) | SYM_STRUCT
);
4150 *a
= 4; /* XXX: cannot store it yet. Doing that is safe */
4152 } else if (bt
== VT_PTR
) {
4154 s
= sym_find(((unsigned)t
>> VT_STRUCT_SHIFT
));
4155 return type_size(s
->t
, a
) * s
->c
;
4160 } else if (bt
== VT_LDOUBLE
) {
4162 return LDOUBLE_SIZE
;
4163 } else if (bt
== VT_DOUBLE
|| bt
== VT_LLONG
) {
4166 } else if (bt
== VT_INT
|| bt
== VT_ENUM
|| bt
== VT_FLOAT
) {
4169 } else if (bt
== VT_SHORT
) {
4173 /* char, void, function, _Bool */
4179 /* return the pointed type of t */
4180 int pointed_type(int t
)
4183 s
= sym_find(((unsigned)t
>> VT_STRUCT_SHIFT
));
4184 return s
->t
| (t
& ~VT_TYPE
);
4187 int mk_pointer(int t
)
4191 sym_push(p
, t
, 0, -1);
4192 return VT_PTR
| (p
<< VT_STRUCT_SHIFT
) | (t
& ~VT_TYPE
);
4195 int is_compatible_types(int t1
, int t2
)
4202 bt1
= t1
& VT_BTYPE
;
4203 bt2
= t2
& VT_BTYPE
;
4204 if (bt1
== VT_PTR
) {
4205 t1
= pointed_type(t1
);
4206 /* if function, then convert implicitely to function pointer */
4207 if (bt2
!= VT_FUNC
) {
4210 t2
= pointed_type(t2
);
4212 /* void matches everything */
4215 if (t1
== VT_VOID
|| t2
== VT_VOID
)
4217 return is_compatible_types(t1
, t2
);
4218 } else if (bt1
== VT_STRUCT
|| bt2
== VT_STRUCT
) {
4220 } else if (bt1
== VT_FUNC
) {
4223 s1
= sym_find(((unsigned)t1
>> VT_STRUCT_SHIFT
));
4224 s2
= sym_find(((unsigned)t2
>> VT_STRUCT_SHIFT
));
4225 if (!is_compatible_types(s1
->t
, s2
->t
))
4227 /* XXX: not complete */
4228 if (s1
->c
== FUNC_OLD
|| s2
->c
== FUNC_OLD
)
4232 while (s1
!= NULL
) {
4235 if (!is_compatible_types(s1
->t
, s2
->t
))
4244 /* XXX: not complete */
4249 /* print a type. If 'varstr' is not NULL, then the variable is also
4250 printed in the type */
4252 /* XXX: add array and function pointers */
4253 void type_to_str(char *buf
, int buf_size
,
4254 int t
, const char *varstr
)
4264 if (t
& VT_UNSIGNED
)
4265 pstrcat(buf
, buf_size
, "unsigned ");
4295 tstr
= "long double";
4297 pstrcat(buf
, buf_size
, tstr
);
4301 if (bt
== VT_STRUCT
)
4305 pstrcat(buf
, buf_size
, tstr
);
4306 v
= (unsigned)t
>> VT_STRUCT_SHIFT
;
4307 if (v
>= SYM_FIRST_ANOM
)
4308 pstrcat(buf
, buf_size
, "<anonymous>");
4310 pstrcat(buf
, buf_size
, get_tok_str(v
, NULL
));
4313 s
= sym_find((unsigned)t
>> VT_STRUCT_SHIFT
);
4314 type_to_str(buf
, buf_size
, s
->t
, varstr
);
4315 pstrcat(buf
, buf_size
, "(");
4317 while (sa
!= NULL
) {
4318 type_to_str(buf1
, sizeof(buf1
), sa
->t
, NULL
);
4319 pstrcat(buf
, buf_size
, buf1
);
4322 pstrcat(buf
, buf_size
, ", ");
4324 pstrcat(buf
, buf_size
, ")");
4327 s
= sym_find((unsigned)t
>> VT_STRUCT_SHIFT
);
4328 pstrcpy(buf1
, sizeof(buf1
), "*");
4330 pstrcat(buf1
, sizeof(buf1
), varstr
);
4331 type_to_str(buf
, buf_size
, s
->t
, buf1
);
4335 pstrcat(buf
, buf_size
, " ");
4336 pstrcat(buf
, buf_size
, varstr
);
4341 /* verify type compatibility to store vtop in 'dt' type, and generate
4343 void gen_assign_cast(int dt
)
4346 char buf1
[256], buf2
[256];
4348 st
= vtop
->t
; /* source type */
4349 if ((dt
& VT_BTYPE
) == VT_PTR
) {
4350 /* special cases for pointers */
4351 /* a function is implicitely a function pointer */
4352 if ((st
& VT_BTYPE
) == VT_FUNC
) {
4353 if (!is_compatible_types(pointed_type(dt
), st
))
4358 /* '0' can also be a pointer */
4359 if ((st
& VT_BTYPE
) == VT_INT
&&
4360 ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
) &&
4364 if (!is_compatible_types(dt
, st
)) {
4366 type_to_str(buf1
, sizeof(buf1
), st
, NULL
);
4367 type_to_str(buf2
, sizeof(buf2
), dt
, NULL
);
4368 error("cannot cast '%s' to '%s'", buf1
, buf2
);
4374 /* store vtop in lvalue pushed on stack */
4377 int sbt
, dbt
, ft
, r
, t
, size
, align
, bit_size
, bit_pos
, rc
, delayed_cast
;
4381 sbt
= vtop
->t
& VT_BTYPE
;
4382 dbt
= ft
& VT_BTYPE
;
4383 if (((sbt
== VT_INT
|| sbt
== VT_SHORT
) && dbt
== VT_BYTE
) ||
4384 (sbt
== VT_INT
&& dbt
== VT_SHORT
)) {
4385 /* optimize char/short casts */
4386 delayed_cast
= VT_MUSTCAST
;
4387 vtop
->t
= ft
& VT_TYPE
;
4390 gen_assign_cast(ft
& VT_TYPE
);
4393 if (sbt
== VT_STRUCT
) {
4394 /* if structure, only generate pointer */
4395 /* structure assignment : generate memcpy */
4396 /* XXX: optimize if small size */
4398 gfunc_start(&gf
, FUNC_CDECL
);
4400 size
= type_size(vtop
->t
, &align
);
4414 vpush_global_sym(func_old_type
, TOK_memcpy
);
4416 /* leave source on stack */
4417 } else if (ft
& VT_BITFIELD
) {
4418 /* bitfield store handling */
4419 bit_pos
= (ft
>> VT_STRUCT_SHIFT
) & 0x3f;
4420 bit_size
= (ft
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f;
4421 /* remove bit field info to avoid loops */
4422 vtop
[-1].t
= ft
& ~(VT_BITFIELD
| (-1 << VT_STRUCT_SHIFT
));
4424 /* duplicate destination */
4426 vtop
[-1] = vtop
[-2];
4428 /* mask and shift source */
4429 vpushi((1 << bit_size
) - 1);
4433 /* load destination, mask and or with source */
4435 vpushi(~(((1 << bit_size
) - 1) << bit_pos
));
4441 #ifdef CONFIG_TCC_BCHECK
4442 /* bound check case */
4443 if (vtop
[-1].r
& VT_MUSTBOUND
) {
4452 r
= gv(rc
); /* generate value */
4453 /* if lvalue was saved on stack, must read it */
4454 if ((vtop
[-1].r
& VT_VALMASK
) == VT_LLOCAL
) {
4456 t
= get_reg(RC_INT
);
4458 sv
.r
= VT_LOCAL
| VT_LVAL
;
4459 sv
.c
.ul
= vtop
[-1].c
.ul
;
4461 vtop
[-1].r
= t
| VT_LVAL
;
4464 /* two word case handling : store second register at word + 4 */
4465 if ((ft
& VT_BTYPE
) == VT_LLONG
) {
4467 /* convert to int to increment easily */
4474 /* XXX: it works because r2 is spilled last ! */
4475 store(vtop
->r2
, vtop
- 1);
4478 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
4479 vtop
->r
|= delayed_cast
;
4483 /* post defines POST/PRE add. c is the token ++ or -- */
4484 void inc(int post
, int c
)
4487 vdup(); /* save lvalue */
4489 gv_dup(); /* duplicate value */
4494 vpushi(c
- TOK_MID
);
4496 vstore(); /* store value */
4498 vpop(); /* if post op, return saved value */
4501 /* Parse GNUC __attribute__ extension. Currently, the following
4502 extensions are recognized:
4503 - aligned(n) : set data/function alignment.
4504 - section(x) : generate data/code in this section.
4505 - unused : currently ignored, but may be used someday.
4507 void parse_attribute(AttributeDef
*ad
)
4514 while (tok
!= ')') {
4515 if (tok
< TOK_IDENT
)
4516 expect("attribute name");
4521 case TOK___SECTION__
:
4524 expect("section name");
4525 ad
->section
= find_section((char *)tokc
.cstr
->data
);
4530 case TOK___ALIGNED__
:
4533 if (n
<= 0 || (n
& (n
- 1)) != 0)
4534 error("alignment must be a positive power of two");
4539 case TOK___UNUSED__
:
4540 /* currently, no need to handle it because tcc does not
4541 track unused objects */
4544 case TOK___NORETURN__
:
4545 /* currently, no need to handle it because tcc does not
4546 track unused objects */
4551 ad
->func_call
= FUNC_CDECL
;
4555 case TOK___STDCALL__
:
4556 ad
->func_call
= FUNC_STDCALL
;
4559 warning("'%s' attribute ignored", get_tok_str(t
, NULL
));
4560 /* skip parameters */
4561 /* XXX: skip parenthesis too */
4564 while (tok
!= ')' && tok
!= -1)
4578 /* enum/struct/union declaration */
4579 int struct_decl(int u
)
4581 int a
, t
, b
, v
, size
, align
, maxalign
, c
, offset
;
4582 int bit_size
, bit_pos
, bsize
, bt
, lbit_pos
;
4586 a
= tok
; /* save decl type */
4591 /* struct already defined ? return it */
4592 /* XXX: check consistency */
4593 s
= sym_find(v
| SYM_STRUCT
);
4596 error("invalid type");
4602 s
= sym_push(v
| SYM_STRUCT
, a
, 0, 0);
4603 /* put struct/union/enum name in type */
4605 u
= u
| (v
<< VT_STRUCT_SHIFT
);
4610 error("struct/union/enum already defined");
4611 /* cannot be empty */
4618 if (a
== TOK_ENUM
) {
4625 /* enum symbols have static storage */
4626 sym_push(v
, VT_STATIC
| VT_INT
, VT_CONST
, c
);
4631 parse_btype(&b
, &ad
);
4636 t
= type_decl(&ad
, &v
, b
, TYPE_DIRECT
);
4637 if ((t
& VT_BTYPE
) == VT_FUNC
||
4638 (t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
)))
4639 error("invalid type for '%s'",
4640 get_tok_str(v
, NULL
));
4646 bit_size
= expr_const();
4647 /* XXX: handle v = 0 case for messages */
4649 error("negative width in bit-field '%s'",
4650 get_tok_str(v
, NULL
));
4651 if (v
&& bit_size
== 0)
4652 error("zero width for bit-field '%s'",
4653 get_tok_str(v
, NULL
));
4655 size
= type_size(t
, &align
);
4657 if (bit_size
>= 0) {
4662 error("bitfields must have scalar type");
4664 if (bit_size
> bsize
) {
4665 error("width of '%s' exceeds its type",
4666 get_tok_str(v
, NULL
));
4667 } else if (bit_size
== bsize
) {
4668 /* no need for bit fields */
4670 } else if (bit_size
== 0) {
4671 /* XXX: what to do if only padding in a
4673 /* zero size: means to pad */
4677 /* we do not have enough room ? */
4678 if ((bit_pos
+ bit_size
) > bsize
)
4681 /* XXX: handle LSB first */
4683 (bit_pos
<< VT_STRUCT_SHIFT
) |
4684 (bit_size
<< (VT_STRUCT_SHIFT
+ 6));
4685 bit_pos
+= bit_size
;
4691 /* add new memory data only if starting
4693 if (lbit_pos
== 0) {
4694 if (a
== TOK_STRUCT
) {
4695 c
= (c
+ align
- 1) & -align
;
4703 if (align
> maxalign
)
4707 printf("add field %s offset=%d",
4708 get_tok_str(v
, NULL
), offset
);
4709 if (t
& VT_BITFIELD
) {
4710 printf(" pos=%d size=%d",
4711 (t
>> VT_STRUCT_SHIFT
) & 0x3f,
4712 (t
>> (VT_STRUCT_SHIFT
+ 6)) & 0x3f);
4716 ss
= sym_push(v
| SYM_FIELD
, t
, 0, offset
);
4720 if (tok
== ';' || tok
== -1)
4730 /* size for struct/union, dummy for enum */
4731 s
->c
= (c
+ maxalign
- 1) & -maxalign
;
4736 /* return 0 if no type declaration. otherwise, return the basic type
4739 int parse_btype(int *type_ptr
, AttributeDef
*ad
)
4741 int t
, u
, type_found
;
4744 memset(ad
, 0, sizeof(AttributeDef
));
4755 if ((t
& VT_BTYPE
) != 0)
4756 error("too many basic types");
4770 if ((t
& VT_BTYPE
) == VT_DOUBLE
) {
4771 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
4772 } else if ((t
& VT_BTYPE
) == VT_LONG
) {
4773 t
= (t
& ~VT_BTYPE
) | VT_LLONG
;
4787 if ((t
& VT_BTYPE
) == VT_LONG
) {
4788 t
= (t
& ~VT_BTYPE
) | VT_LDOUBLE
;
4795 u
= struct_decl(VT_ENUM
);
4799 u
= struct_decl(VT_STRUCT
);
4802 /* type modifiers */
4807 case TOK___SIGNED__
:
4810 case TOK___INLINE__
:
4832 /* GNUC attribute */
4833 case TOK___ATTRIBUTE__
:
4834 parse_attribute(ad
);
4838 if (!s
|| !(s
->t
& VT_TYPEDEF
))
4840 t
|= (s
->t
& ~VT_TYPEDEF
);
4847 /* long is never used as type */
4848 if ((t
& VT_BTYPE
) == VT_LONG
)
4849 t
= (t
& ~VT_BTYPE
) | VT_INT
;
4854 int post_type(int t
, AttributeDef
*ad
)
4856 int p
, n
, pt
, l
, t1
;
4857 Sym
**plast
, *s
, *first
;
4861 /* function declaration */
4866 while (tok
!= ')') {
4867 /* read param name and compute offset */
4868 if (l
!= FUNC_OLD
) {
4869 if (!parse_btype(&pt
, &ad1
)) {
4871 error("invalid type");
4878 if ((pt
& VT_BTYPE
) == VT_VOID
&& tok
== ')')
4880 pt
= type_decl(&ad1
, &n
, pt
, TYPE_DIRECT
| TYPE_ABSTRACT
);
4881 if ((pt
& VT_BTYPE
) == VT_VOID
)
4882 error("parameter declared as void");
4889 /* array must be transformed to pointer according to ANSI C */
4891 s
= sym_push(n
| SYM_FIELD
, pt
, 0, 0);
4896 if (l
== FUNC_NEW
&& tok
== TOK_DOTS
) {
4903 /* if no parameters, then old type prototype */
4907 t1
= t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
);
4908 t
= post_type(t
& ~(VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
), ad
);
4909 /* we push a anonymous symbol which will contain the function prototype */
4911 s
= sym_push(p
, t
, ad
->func_call
, l
);
4913 t
= t1
| VT_FUNC
| (p
<< VT_STRUCT_SHIFT
);
4914 } else if (tok
== '[') {
4915 /* array definition */
4921 error("invalid array size");
4924 /* parse next post type */
4925 t1
= t
& (VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
);
4926 t
= post_type(t
& ~(VT_TYPEDEF
| VT_STATIC
| VT_EXTERN
), ad
);
4928 /* we push a anonymous symbol which will contain the array
4931 sym_push(p
, t
, 0, n
);
4932 t
= t1
| VT_ARRAY
| VT_PTR
| (p
<< VT_STRUCT_SHIFT
);
4937 /* Read a type declaration (except basic type), and return the
4938 type. 'td' is a bitmask indicating which kind of type decl is
4939 expected. 't' should contain the basic type. 'ad' is the attribute
4940 definition of the basic type. It can be modified by type_decl(). */
4941 int type_decl(AttributeDef
*ad
, int *v
, int t
, int td
)
4946 while (tok
== '*') {
4948 while (tok
== TOK_CONST
|| tok
== TOK_VOLATILE
|| tok
== TOK_RESTRICT
)
4953 /* recursive type */
4954 /* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
4957 /* XXX: this is not correct to modify 'ad' at this point, but
4958 the syntax is not clear */
4959 if (tok
== TOK___ATTRIBUTE__
)
4960 parse_attribute(ad
);
4961 u
= type_decl(ad
, v
, 0, td
);
4965 /* type identifier */
4966 if (tok
>= TOK_IDENT
&& (td
& TYPE_DIRECT
)) {
4970 if (!(td
& TYPE_ABSTRACT
))
4971 expect("identifier");
4975 /* append t at the end of u */
4976 t
= post_type(t
, ad
);
4977 if (tok
== TOK___ATTRIBUTE__
)
4978 parse_attribute(ad
);
4983 s
= sym_find((unsigned)p
>> VT_STRUCT_SHIFT
);
4993 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
4994 static int lvalue_type(int t
)
5001 else if (bt
== VT_SHORT
)
5005 if (t
& VT_UNSIGNED
)
5006 r
|= VT_LVAL_UNSIGNED
;
5010 /* indirection with full error checking and bound check */
5011 static void indir(void)
5013 if ((vtop
->t
& VT_BTYPE
) != VT_PTR
)
5015 if (vtop
->r
& VT_LVAL
)
5017 vtop
->t
= pointed_type(vtop
->t
);
5018 /* an array is never an lvalue */
5019 if (!(vtop
->t
& VT_ARRAY
)) {
5020 vtop
->r
|= lvalue_type(vtop
->t
);
5021 /* if bound checking, the referenced pointer must be checked */
5022 if (do_bounds_check
)
5023 vtop
->r
|= VT_MUSTBOUND
;
5027 /* pass a parameter to a function and do type checking and casting */
5028 void gfunc_param_typed(GFuncContext
*gf
, Sym
*func
, Sym
*arg
)
5031 func_type
= func
->c
;
5032 if (func_type
== FUNC_OLD
||
5033 (func_type
== FUNC_ELLIPSIS
&& arg
== NULL
)) {
5034 /* default casting : only need to convert float to double */
5035 if ((vtop
->t
& VT_BTYPE
) == VT_FLOAT
)
5036 gen_cast(VT_DOUBLE
);
5037 } else if (arg
== NULL
) {
5038 error("too many arguments to function");
5040 gen_assign_cast(arg
->t
);
5047 int n
, t
, ft
, align
, size
, r
;
5052 if (tok
== TOK_CINT
|| tok
== TOK_CCHAR
|| tok
== TOK_LCHAR
) {
5055 } else if (tok
== TOK_CUINT
) {
5056 vsetc(VT_INT
| VT_UNSIGNED
, VT_CONST
, &tokc
);
5058 } else if (tok
== TOK_CLLONG
) {
5059 vsetc(VT_LLONG
, VT_CONST
, &tokc
);
5061 } else if (tok
== TOK_CULLONG
) {
5062 vsetc(VT_LLONG
| VT_UNSIGNED
, VT_CONST
, &tokc
);
5064 } else if (tok
== TOK_CFLOAT
) {
5065 vsetc(VT_FLOAT
, VT_CONST
, &tokc
);
5067 } else if (tok
== TOK_CDOUBLE
) {
5068 vsetc(VT_DOUBLE
, VT_CONST
, &tokc
);
5070 } else if (tok
== TOK_CLDOUBLE
) {
5071 vsetc(VT_LDOUBLE
, VT_CONST
, &tokc
);
5073 } else if (tok
== TOK___FUNC__
|| (tok
== TOK___FUNCTION__
&& gnu_ext
)) {
5076 /* special function name identifier */
5078 len
= strlen(funcname
) + 1;
5079 /* generate char[len] type */
5080 t
= VT_ARRAY
| mk_pointer(VT_BYTE
);
5081 s
= sym_find(((unsigned)t
>> VT_STRUCT_SHIFT
));
5083 vpush_ref(t
, data_section
, data_section
->data_offset
, len
);
5084 ptr
= section_ptr_add(data_section
, len
);
5085 memcpy(ptr
, funcname
, len
);
5087 } else if (tok
== TOK_LSTR
) {
5090 } else if (tok
== TOK_STR
) {
5091 /* string parsing */
5094 t
= VT_ARRAY
| mk_pointer(t
);
5095 memset(&ad
, 0, sizeof(AttributeDef
));
5096 decl_initializer_alloc(t
, &ad
, VT_CONST
, 2, 0, 0);
5102 if (parse_btype(&t
, &ad
)) {
5103 ft
= type_decl(&ad
, &n
, t
, TYPE_ABSTRACT
);
5105 /* check ISOC99 compound literal */
5107 /* data is allocated locally by default */
5112 /* all except arrays are lvalues */
5113 if (!(ft
& VT_ARRAY
))
5114 r
|= lvalue_type(ft
);
5115 memset(&ad
, 0, sizeof(AttributeDef
));
5116 decl_initializer_alloc(ft
, &ad
, r
, 1, 0, 0);
5125 } else if (t
== '*') {
5128 } else if (t
== '&') {
5130 /* functions names must be treated as function pointers,
5131 except for unary '&' and sizeof. Since we consider that
5132 functions are not lvalues, we only have to handle it
5133 there and in function calls. */
5134 /* arrays can also be used although they are not lvalues */
5135 if ((vtop
->t
& VT_BTYPE
) != VT_FUNC
&&
5136 !(vtop
->t
& VT_ARRAY
))
5138 vtop
->t
= mk_pointer(vtop
->t
);
5143 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) == VT_CONST
)
5144 vtop
->c
.i
= !vtop
->c
.i
;
5145 else if ((vtop
->r
& VT_VALMASK
) == VT_CMP
)
5146 vtop
->c
.i
= vtop
->c
.i
^ 1;
5148 vset(VT_INT
, VT_JMP
, gtst(1, 0));
5156 /* in order to force cast, we add zero */
5158 if ((vtop
->t
& VT_BTYPE
) == VT_PTR
)
5159 error("pointer not accepted for unary plus");
5163 if (t
== TOK_SIZEOF
) {
5166 if (parse_btype(&t
, &ad
)) {
5167 t
= type_decl(&ad
, &n
, t
, TYPE_ABSTRACT
);
5169 /* XXX: some code could be generated: add eval
5181 vpushi(type_size(t
, &t
));
5183 if (t
== TOK_INC
|| t
== TOK_DEC
) {
5186 } else if (t
== '-') {
5193 expect("identifier");
5197 error("'%s' undeclared", get_tok_str(t
, NULL
));
5198 /* for simple function calls, we tolerate undeclared
5199 external reference to int() function */
5200 s
= external_global_sym(t
, func_old_type
, 0);
5202 vset(s
->t
, s
->r
, s
->c
);
5203 /* if forward reference, we must point to s */
5204 if (vtop
->r
& VT_SYM
) {
5211 /* post operations */
5213 if (tok
== TOK_INC
|| tok
== TOK_DEC
) {
5216 } else if (tok
== '.' || tok
== TOK_ARROW
) {
5218 if (tok
== TOK_ARROW
)
5223 /* expect pointer on structure */
5224 if ((vtop
->t
& VT_BTYPE
) != VT_STRUCT
)
5225 expect("struct or union");
5226 s
= sym_find(((unsigned)vtop
->t
>> VT_STRUCT_SHIFT
) | SYM_STRUCT
);
5229 while ((s
= s
->next
) != NULL
) {
5234 error("field not found");
5235 /* add field offset to pointer */
5236 vtop
->t
= char_pointer_type
; /* change type to 'char *' */
5239 /* change type to field type, and set to lvalue */
5241 /* an array is never an lvalue */
5242 if (!(vtop
->t
& VT_ARRAY
))
5243 vtop
->r
|= lvalue_type(vtop
->t
);
5245 } else if (tok
== '[') {
5251 } else if (tok
== '(') {
5256 if ((vtop
->t
& VT_BTYPE
) != VT_FUNC
) {
5257 /* pointer test (no array accepted) */
5258 if ((vtop
->t
& (VT_BTYPE
| VT_ARRAY
)) == VT_PTR
) {
5259 vtop
->t
= pointed_type(vtop
->t
);
5260 if ((vtop
->t
& VT_BTYPE
) != VT_FUNC
)
5264 expect("function pointer");
5267 vtop
->r
&= ~VT_LVAL
; /* no lvalue */
5269 /* get return type */
5270 s
= sym_find((unsigned)vtop
->t
>> VT_STRUCT_SHIFT
);
5271 save_regs(0); /* save used temporary registers */
5272 gfunc_start(&gf
, s
->r
);
5274 sa
= s
->next
; /* first parameter */
5275 #ifdef INVERT_FUNC_PARAMS
5279 ParseState saved_parse_state
;
5282 /* read each argument and store it on a stack */
5288 while ((parlevel
> 0 || (tok
!= ')' && tok
!= ',')) &&
5292 else if (tok
== ')')
5294 tok_str_add_tok(&str
);
5297 tok_str_add(&str
, -1); /* end of file added */
5298 tok_str_add(&str
, 0);
5299 s1
= sym_push2(&args
, 0, 0, (int)str
.str
);
5300 s1
->next
= sa
; /* add reference to argument */
5309 /* now generate code in reverse order by reading the stack */
5310 save_parse_state(&saved_parse_state
);
5312 macro_ptr
= (int *)args
->c
;
5316 expect("',' or ')'");
5317 gfunc_param_typed(&gf
, s
, args
->next
);
5319 tok_str_free((int *)args
->c
);
5323 restore_parse_state(&saved_parse_state
);
5326 /* compute first implicit argument if a structure is returned */
5327 if ((s
->t
& VT_BTYPE
) == VT_STRUCT
) {
5328 /* get some space for the returned structure */
5329 size
= type_size(s
->t
, &align
);
5330 loc
= (loc
- size
) & -align
;
5332 ret
.r
= VT_LOCAL
| VT_LVAL
;
5333 /* pass it as 'int' to avoid structure arg passing
5335 vset(VT_INT
, VT_LOCAL
, loc
);
5341 /* return in register */
5342 if (is_float(ret
.t
)) {
5345 if ((ret
.t
& VT_BTYPE
) == VT_LLONG
)
5351 #ifndef INVERT_FUNC_PARAMS
5355 gfunc_param_typed(&gf
, s
, sa
);
5365 error("too few arguments to function");
5369 vsetc(ret
.t
, ret
.r
, &ret
.c
);
5383 (tok
>= TOK_A_MOD
&& tok
<= TOK_A_DIV
) ||
5384 tok
== TOK_A_XOR
|| tok
== TOK_A_OR
||
5385 tok
== TOK_A_SHL
|| tok
== TOK_A_SAR
) {
5408 while ((l
== 0 && (tok
== '*' || tok
== '/' || tok
== '%')) ||
5409 (l
== 1 && (tok
== '+' || tok
== '-')) ||
5410 (l
== 2 && (tok
== TOK_SHL
|| tok
== TOK_SAR
)) ||
5411 (l
== 3 && ((tok
>= TOK_ULE
&& tok
<= TOK_GT
) ||
5412 tok
== TOK_ULT
|| tok
== TOK_UGE
)) ||
5413 (l
== 4 && (tok
== TOK_EQ
|| tok
== TOK_NE
)) ||
5414 (l
== 5 && tok
== '&') ||
5415 (l
== 6 && tok
== '^') ||
5416 (l
== 7 && tok
== '|') ||
5417 (l
== 8 && tok
== TOK_LAND
) ||
5418 (l
== 9 && tok
== TOK_LOR
)) {
5427 /* only used if non constant */
5435 if (tok
!= TOK_LAND
) {
5438 vset(VT_INT
, VT_JMPI
, t
);
5455 if (tok
!= TOK_LOR
) {
5458 vset(VT_INT
, VT_JMP
, t
);
5468 /* XXX: better constant handling */
5471 int t
, u
, c
, r1
, r2
, rc
;
5491 save_regs(1); /* we need to save all registers here except
5492 at the top because it is a branch point */
5495 /* XXX: long long handling ? */
5497 if (is_float(vtop
->t
))
5500 vtop
--; /* no vpop so that FP stack is not flushed */
5525 /* parse a constant expression and return value in vtop. */
5526 static void expr_const1(void)
5535 /* parse an integer constant and return its value. */
5536 static int expr_const(void)
5540 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
| VT_SYM
)) != VT_CONST
)
5541 expect("constant expression");
5547 /* return the label token if current token is a label, otherwise
5554 /* fast test first */
5555 if (tok
< TOK_UIDENT
)
5557 /* no need to save tokc since we expect an identifier */
5565 /* XXX: may not work in all cases (macros ?) */
5574 void block(int *bsym
, int *csym
, int *case_sym
, int *def_sym
, int case_reg
)
5579 /* generate line number info */
5581 (last_line_num
!= file
->line_num
|| last_ind
!= ind
)) {
5582 put_stabn(N_SLINE
, 0, file
->line_num
, ind
- func_ind
);
5584 last_line_num
= file
->line_num
;
5587 if (tok
== TOK_IF
) {
5594 block(bsym
, csym
, case_sym
, def_sym
, case_reg
);
5596 if (c
== TOK_ELSE
) {
5600 block(bsym
, csym
, case_sym
, def_sym
, case_reg
);
5601 gsym(d
); /* patch else jmp */
5604 } else if (tok
== TOK_WHILE
) {
5612 block(&a
, &b
, case_sym
, def_sym
, case_reg
);
5616 } else if (tok
== '{') {
5619 s
= local_stack
.top
;
5620 while (tok
!= '}') {
5623 block(bsym
, csym
, case_sym
, def_sym
, case_reg
);
5625 /* pop locally defined symbols */
5626 sym_pop(&local_stack
, s
);
5628 } else if (tok
== TOK_RETURN
) {
5632 gen_assign_cast(func_vt
);
5633 if ((func_vt
& VT_BTYPE
) == VT_STRUCT
) {
5634 /* if returning structure, must copy it to implicit
5635 first pointer arg location */
5636 vset(mk_pointer(func_vt
), VT_LOCAL
| VT_LVAL
, func_vc
);
5639 /* copy structure value to pointer */
5641 } else if (is_float(func_vt
)) {
5646 vtop
--; /* NOT vpop() because on x86 it would flush the fp stack */
5649 rsym
= gjmp(rsym
); /* jmp */
5650 } else if (tok
== TOK_BREAK
) {
5653 error("cannot break");
5654 *bsym
= gjmp(*bsym
);
5657 } else if (tok
== TOK_CONTINUE
) {
5660 error("cannot continue");
5661 *csym
= gjmp(*csym
);
5664 } else if (tok
== TOK_FOR
) {
5691 block(&a
, &b
, case_sym
, def_sym
, case_reg
);
5696 if (tok
== TOK_DO
) {
5701 block(&a
, &b
, case_sym
, def_sym
, case_reg
);
5712 if (tok
== TOK_SWITCH
) {
5716 /* XXX: other types than integer */
5717 case_reg
= gv(RC_INT
);
5721 b
= gjmp(0); /* jump to first case */
5723 block(&a
, csym
, &b
, &c
, case_reg
);
5724 /* if no default, jmp after switch */
5732 if (tok
== TOK_CASE
) {
5739 if (gnu_ext
&& tok
== TOK_DOTS
) {
5743 warning("empty case range");
5745 /* since a case is like a label, we must skip it with a jmp */
5748 vset(VT_INT
, case_reg
, 0);
5752 *case_sym
= gtst(1, 0);
5755 *case_sym
= gtst(1, 0);
5756 vset(VT_INT
, case_reg
, 0);
5759 *case_sym
= gtst(1, *case_sym
);
5763 block(bsym
, csym
, case_sym
, def_sym
, case_reg
);
5765 if (tok
== TOK_DEFAULT
) {
5771 error("too many 'default'");
5773 block(bsym
, csym
, case_sym
, def_sym
, case_reg
);
5775 if (tok
== TOK_GOTO
) {
5777 s
= sym_find1(&label_stack
, tok
);
5778 /* put forward definition if needed */
5780 s
= sym_push1(&label_stack
, tok
, LABEL_FORWARD
, 0);
5781 /* label already defined */
5782 if (s
->t
& LABEL_FORWARD
)
5792 s
= sym_find1(&label_stack
, b
);
5794 if (!(s
->t
& LABEL_FORWARD
))
5795 error("multiple defined label");
5800 sym_push1(&label_stack
, b
, 0, ind
);
5802 /* we accept this, but it is a mistake */
5804 warning("deprecated use of label at end of compound statement");
5806 block(bsym
, csym
, case_sym
, def_sym
, case_reg
);
5808 /* expression case */
5818 /* t is the array or struct type. c is the array or struct
5819 address. cur_index/cur_field is the pointer to the current
5820 value. 'size_only' is true if only size info is needed (only used
5822 static void decl_designator(int t
, Section
*sec
, unsigned long c
,
5823 int *cur_index
, Sym
**cur_field
,
5827 int notfirst
, index
, align
, l
;
5830 if (gnu_ext
&& (l
= is_label()) != 0)
5833 while (tok
== '[' || tok
== '.') {
5835 if (!(t
& VT_ARRAY
))
5836 expect("array type");
5837 s
= sym_find(((unsigned)t
>> VT_STRUCT_SHIFT
));
5839 index
= expr_const();
5840 if (index
< 0 || (s
->c
>= 0 && index
>= s
->c
))
5841 expect("invalid index");
5845 t
= pointed_type(t
);
5846 c
+= index
* type_size(t
, &align
);
5852 if ((t
& VT_BTYPE
) != VT_STRUCT
)
5853 expect("struct/union type");
5854 s
= sym_find(((unsigned)t
>> VT_STRUCT_SHIFT
) | SYM_STRUCT
);
5866 t
= f
->t
| (t
& ~VT_TYPE
);
5881 t
= pointed_type(t
);
5882 c
+= index
* type_size(t
, &align
);
5886 error("too many field init");
5887 t
= f
->t
| (t
& ~VT_TYPE
);
5891 decl_initializer(t
, sec
, c
, 0, size_only
);
5895 #define EXPR_CONST 1
5898 /* store a value or an expression directly in global data or in local array */
5899 static void init_putv(int t
, Section
*sec
, unsigned long c
,
5900 int v
, int expr_type
)
5902 int saved_global_expr
, bt
;
5910 /* compound literals must be allocated globally in this case */
5911 saved_global_expr
= global_expr
;
5914 global_expr
= saved_global_expr
;
5915 /* NOTE: symbols are accepted */
5916 if ((vtop
->r
& (VT_VALMASK
| VT_LVAL
)) != VT_CONST
)
5917 error("initializer element is not constant");
5925 /* XXX: not portable */
5926 /* XXX: generate error if incorrect relocation */
5929 ptr
= sec
->data
+ c
;
5930 if ((vtop
->r
& VT_SYM
) &&
5936 error("initializer element is not computable at load time");
5939 *(char *)ptr
= vtop
->c
.i
;
5942 *(short *)ptr
= vtop
->c
.i
;
5945 *(double *)ptr
= vtop
->c
.d
;
5948 *(long double *)ptr
= vtop
->c
.ld
;
5951 *(long long *)ptr
= vtop
->c
.ll
;
5954 if (vtop
->r
& VT_SYM
) {
5955 greloc(sec
, vtop
->sym
, c
, R_DATA_32
);
5957 *(int *)ptr
= vtop
->c
.i
;
5962 vset(t
, VT_LOCAL
, c
);
5969 /* put zeros for variable based init */
5970 static void init_putz(int t
, Section
*sec
, unsigned long c
, int size
)
5975 /* nothing to do because globals are already set to zero */
5977 gfunc_start(&gf
, FUNC_CDECL
);
5982 vset(VT_INT
, VT_LOCAL
, c
);
5984 vpush_global_sym(func_old_type
, TOK_memset
);
5989 /* 't' contains the type and storage info. 'c' is the offset of the
5990 object in section 'sec'. If 'sec' is NULL, it means stack based
5991 allocation. 'first' is true if array '{' must be read (multi
5992 dimension implicit array init handling). 'size_only' is true if
5993 size only evaluation is wanted (only for arrays). */
5994 static void decl_initializer(int t
, Section
*sec
, unsigned long c
,
5995 int first
, int size_only
)
5997 int index
, array_length
, n
, no_oblock
, nb
, parlevel
, i
;
5998 int t1
, size1
, align1
, expr_type
;
6002 s
= sym_find(((unsigned)t
>> VT_STRUCT_SHIFT
));
6005 t1
= pointed_type(t
);
6006 size1
= type_size(t1
, &align1
);
6009 if ((first
&& tok
!= TOK_LSTR
&& tok
!= TOK_STR
) ||
6015 /* only parse strings here if correct type (otherwise: handle
6016 them as ((w)char *) expressions */
6017 if ((tok
== TOK_LSTR
&&
6018 (t1
& VT_BTYPE
) == VT_INT
) ||
6020 (t1
& VT_BTYPE
) == VT_BYTE
)) {
6021 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
6026 /* compute maximum number of chars wanted */
6028 cstr_len
= cstr
->size
;
6030 cstr_len
= cstr
->size
/ sizeof(int);
6033 if (n
>= 0 && nb
> (n
- array_length
))
6034 nb
= n
- array_length
;
6037 warning("initializer-string for array is too long");
6040 ch
= ((unsigned char *)cstr
->data
)[i
];
6042 ch
= ((int *)cstr
->data
)[i
];
6043 init_putv(t1
, sec
, c
+ (array_length
+ i
) * size1
,
6050 /* only add trailing zero if enough storage (no
6051 warning in this case since it is standard) */
6052 if (n
< 0 || array_length
< n
) {
6054 init_putv(t1
, sec
, c
+ (array_length
* size1
), 0, EXPR_VAL
);
6060 while (tok
!= '}') {
6061 decl_designator(t
, sec
, c
, &index
, NULL
, size_only
);
6062 if (n
>= 0 && index
>= n
)
6063 error("index too large");
6064 /* must put zero in holes (note that doing it that way
6065 ensures that it even works with designators) */
6066 if (!size_only
&& array_length
< index
) {
6067 init_putz(t1
, sec
, c
+ array_length
* size1
,
6068 (index
- array_length
) * size1
);
6071 if (index
> array_length
)
6072 array_length
= index
;
6073 /* special test for multi dimensional arrays (may not
6074 be strictly correct if designators are used at the
6076 if (index
>= n
&& no_oblock
)
6085 /* put zeros at the end */
6086 if (!size_only
&& n
>= 0 && array_length
< n
) {
6087 init_putz(t1
, sec
, c
+ array_length
* size1
,
6088 (n
- array_length
) * size1
);
6090 /* patch type size if needed */
6092 s
->c
= array_length
;
6093 } else if ((t
& VT_BTYPE
) == VT_STRUCT
&& tok
== '{') {
6094 /* XXX: union needs only one init */
6096 s
= sym_find(((unsigned)t
>> VT_STRUCT_SHIFT
) | SYM_STRUCT
);
6101 while (tok
!= '}') {
6102 decl_designator(t
, sec
, c
, NULL
, &f
, size_only
);
6103 /* fill with zero between fields */
6105 if (!size_only
&& array_length
< index
) {
6106 init_putz(t
, sec
, c
+ array_length
,
6107 index
- array_length
);
6109 index
= index
+ type_size(f
->t
, &align1
);
6110 if (index
> array_length
)
6111 array_length
= index
;
6117 /* put zeros at the end */
6118 if (!size_only
&& array_length
< n
) {
6119 init_putz(t
, sec
, c
+ array_length
,
6123 } else if (tok
== '{') {
6125 decl_initializer(t
, sec
, c
, first
, size_only
);
6127 } else if (size_only
) {
6128 /* just skip expression */
6130 while ((parlevel
> 0 || (tok
!= '}' && tok
!= ',')) &&
6134 else if (tok
== ')')
6139 /* currently, we always use constant expression for globals
6140 (may change for scripting case) */
6141 expr_type
= EXPR_CONST
;
6143 expr_type
= EXPR_ANY
;
6144 init_putv(t
, sec
, c
, 0, expr_type
);
6148 /* parse an initializer for type 't' if 'has_init' is non zero, and
6149 allocate space in local or global data space ('r' is either
6150 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
6151 variable 'v' of scope 'scope' is declared before initializers are
6152 parsed. If 'v' is zero, then a reference to the new object is put
6153 in the value stack. If 'has_init' is 2, a special parsing is done
6154 to handle string constants. */
6155 static void decl_initializer_alloc(int t
, AttributeDef
*ad
, int r
,
6156 int has_init
, int v
, int scope
)
6158 int size
, align
, addr
, data_offset
;
6160 ParseState saved_parse_state
;
6161 TokenString init_str
;
6164 size
= type_size(t
, &align
);
6165 /* If unknown size, we must evaluate it before
6166 evaluating initializers because
6167 initializers can generate global data too
6168 (e.g. string pointers or ISOC99 compound
6169 literals). It also simplifies local
6170 initializers handling */
6171 tok_str_new(&init_str
);
6174 error("unknown type size");
6175 /* get all init string */
6176 if (has_init
== 2) {
6177 /* only get strings */
6178 while (tok
== TOK_STR
|| tok
== TOK_LSTR
) {
6179 tok_str_add_tok(&init_str
);
6184 while (level
> 0 || (tok
!= ',' && tok
!= ';')) {
6186 error("unexpected end of file in initializer");
6187 tok_str_add_tok(&init_str
);
6190 else if (tok
== '}') {
6198 tok_str_add(&init_str
, -1);
6199 tok_str_add(&init_str
, 0);
6202 save_parse_state(&saved_parse_state
);
6204 macro_ptr
= init_str
.str
;
6206 decl_initializer(t
, NULL
, 0, 1, 1);
6207 /* prepare second initializer parsing */
6208 macro_ptr
= init_str
.str
;
6211 /* if still unknown size, error */
6212 size
= type_size(t
, &align
);
6214 error("unknown type size");
6216 /* take into account specified alignment if bigger */
6217 if (ad
->aligned
> align
)
6218 align
= ad
->aligned
;
6219 if ((r
& VT_VALMASK
) == VT_LOCAL
) {
6221 if (do_bounds_check
&& (t
& VT_ARRAY
))
6223 #ifdef TCC_TARGET_IL
6224 /* XXX: ugly patch to allocate local variables for IL, just
6229 loc
= (loc
- size
) & -align
;
6232 /* handles bounds */
6233 /* XXX: currently, since we do only one pass, we cannot track
6234 '&' operators, so we add only arrays */
6235 if (do_bounds_check
&& (t
& VT_ARRAY
)) {
6236 unsigned long *bounds_ptr
;
6237 /* add padding between regions */
6239 /* then add local bound info */
6240 bounds_ptr
= section_ptr_add(lbounds_section
, 2 * sizeof(unsigned long));
6241 bounds_ptr
[0] = addr
;
6242 bounds_ptr
[1] = size
;
6245 /* compute section */
6253 data_offset
= sec
->data_offset
;
6254 data_offset
= (data_offset
+ align
- 1) & -align
;
6256 /* very important to increment global pointer at this time
6257 because initializers themselves can create new initializers */
6258 data_offset
+= size
;
6259 /* add padding if bound check */
6260 if (do_bounds_check
)
6262 sec
->data_offset
= data_offset
;
6263 /* allocate section space to put the data */
6264 if (sec
->sh_type
!= SHT_NOBITS
&&
6265 data_offset
> sec
->data_allocated
)
6266 section_realloc(sec
, data_offset
);
6270 /* local variable */
6271 sym_push(v
, t
, r
, addr
);
6273 /* push local reference */
6280 if (scope
== VT_CONST
) {
6281 /* global scope: see if already defined */
6285 if (!is_compatible_types(sym
->t
, t
))
6286 error("incompatible types for redefinition of '%s'",
6287 get_tok_str(v
, NULL
));
6288 if (!(sym
->t
& VT_EXTERN
))
6289 error("redefinition of '%s'", get_tok_str(v
, NULL
));
6290 sym
->t
&= ~VT_EXTERN
;
6293 sym
= sym_push(v
, t
, r
| VT_SYM
, 0);
6295 put_extern_sym(sym
, sec
, addr
, size
);
6299 /* push global reference */
6300 sym
= get_sym_ref(t
, sec
, addr
, size
);
6302 vsetc(t
, VT_CONST
| VT_SYM
, &cval
);
6306 /* handles bounds now because the symbol must be defined
6307 before for the relocation */
6308 if (do_bounds_check
) {
6309 unsigned long *bounds_ptr
;
6311 greloc(bounds_section
, sym
, bounds_section
->data_offset
, R_DATA_32
);
6312 /* then add global bound info */
6313 bounds_ptr
= section_ptr_add(bounds_section
, 2 * sizeof(long));
6314 bounds_ptr
[0] = 0; /* relocated */
6315 bounds_ptr
[1] = size
;
6319 decl_initializer(t
, sec
, addr
, 1, 0);
6320 /* restore parse state if needed */
6322 tok_str_free(init_str
.str
);
6323 restore_parse_state(&saved_parse_state
);
6328 void put_func_debug(Sym
*sym
)
6333 /* XXX: we put here a dummy type */
6334 snprintf(buf
, sizeof(buf
), "%s:%c1",
6335 funcname
, sym
->t
& VT_STATIC
? 'f' : 'F');
6336 put_stabs_r(buf
, N_FUN
, 0, file
->line_num
, 0,
6337 cur_text_section
, sym
->c
);
6342 /* not finished : try to put some local vars in registers */
6343 //#define CONFIG_REG_VARS
6345 #ifdef CONFIG_REG_VARS
6346 void add_var_ref(int t
)
6348 printf("%s:%d: &%s\n",
6349 file
->filename
, file
->line_num
,
6350 get_tok_str(t
, NULL
));
6353 /* first pass on a function with heuristic to extract variable usage
6354 and pointer references to local variables for register allocation */
6355 void analyse_function(void)
6362 /* any symbol coming after '&' is considered as being a
6363 variable whose reference is taken. It is highly unaccurate
6364 but it is difficult to do better without a complete parse */
6367 /* if '& number', then no need to examine next tokens */
6368 if (tok
== TOK_CINT
||
6370 tok
== TOK_CLLONG
||
6371 tok
== TOK_CULLONG
) {
6373 } else if (tok
>= TOK_UIDENT
) {
6374 /* if '& ident [' or '& ident ->', then ident address
6378 if (tok
!= '[' && tok
!= TOK_ARROW
)
6382 while (tok
!= '}' && tok
!= ';' &&
6383 !((tok
== ',' || tok
== ')') && level
== 0)) {
6384 if (tok
>= TOK_UIDENT
) {
6386 } else if (tok
== '(') {
6388 } else if (tok
== ')') {
6401 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
6404 int t
, b
, v
, has_init
, r
;
6409 if (!parse_btype(&b
, &ad
)) {
6410 /* skip redundant ';' */
6411 /* XXX: find more elegant solution */
6416 /* special test for old K&R protos without explicit int
6417 type. Only accepted when defining global data */
6418 if (l
== VT_LOCAL
|| tok
< TOK_DEFINE
)
6422 if (((b
& VT_BTYPE
) == VT_ENUM
||
6423 (b
& VT_BTYPE
) == VT_STRUCT
) &&
6425 /* we accept no variable after */
6429 while (1) { /* iterate thru each declaration */
6430 t
= type_decl(&ad
, &v
, b
, TYPE_DIRECT
);
6434 type_to_str(buf
, sizeof(buf
), t
, get_tok_str(v
, NULL
));
6435 printf("type = '%s'\n", buf
);
6439 #ifdef CONFIG_REG_VARS
6440 TokenString func_str
;
6441 ParseState saved_parse_state
;
6446 error("cannot use local functions");
6448 expect("function definition");
6450 #ifdef CONFIG_REG_VARS
6451 /* parse all function code and record it */
6453 tok_str_new(&func_str
);
6459 error("unexpected end of file");
6460 tok_str_add_tok(&func_str
);
6465 } else if (t
== '}') {
6467 if (block_level
== 0)
6471 tok_str_add(&func_str
, -1);
6472 tok_str_add(&func_str
, 0);
6474 save_parse_state(&saved_parse_state
);
6476 macro_ptr
= func_str
.str
;
6481 /* compute text section */
6482 cur_text_section
= ad
.section
;
6483 if (!cur_text_section
)
6484 cur_text_section
= text_section
;
6485 ind
= cur_text_section
->data_offset
;
6486 funcname
= get_tok_str(v
, NULL
);
6489 /* if symbol is already defined, then put complete type */
6492 /* put function symbol */
6493 sym
= sym_push1(&global_stack
, v
, t
, 0);
6495 /* NOTE: we patch the symbol size later */
6496 put_extern_sym(sym
, cur_text_section
, ind
, 0);
6498 sym
->r
= VT_SYM
| VT_CONST
;
6499 /* put debug symbol */
6501 put_func_debug(sym
);
6502 /* push a dummy symbol to enable local sym storage */
6503 sym_push1(&local_stack
, 0, 0, 0);
6507 #ifdef CONFIG_REG_VARS
6508 macro_ptr
= func_str
.str
;
6511 block(NULL
, NULL
, NULL
, NULL
, 0);
6514 cur_text_section
->data_offset
= ind
;
6515 sym_pop(&label_stack
, NULL
); /* reset label stack */
6516 sym_pop(&local_stack
, NULL
); /* reset local stack */
6517 /* end of function */
6518 /* patch symbol size */
6519 ((Elf32_Sym
*)symtab_section
->data
)[sym
->c
].st_size
=
6522 put_stabn(N_FUN
, 0, 0, ind
- func_ind
);
6524 funcname
= ""; /* for safety */
6525 func_vt
= VT_VOID
; /* for safety */
6526 ind
= 0; /* for safety */
6528 #ifdef CONFIG_REG_VARS
6529 tok_str_free(func_str
.str
);
6530 restore_parse_state(&saved_parse_state
);
6534 if (b
& VT_TYPEDEF
) {
6535 /* save typedefed type */
6536 /* XXX: test storage specifiers ? */
6537 sym_push(v
, t
| VT_TYPEDEF
, 0, 0);
6538 } else if ((t
& VT_BTYPE
) == VT_FUNC
) {
6539 /* external function definition */
6540 external_sym(v
, t
, 0);
6542 /* not lvalue if array */
6544 if (!(t
& VT_ARRAY
))
6545 r
|= lvalue_type(t
);
6546 if (b
& VT_EXTERN
) {
6547 /* external variable */
6548 external_sym(v
, t
, r
);
6554 has_init
= (tok
== '=');
6557 decl_initializer_alloc(t
, &ad
, r
,
6571 /* compile the C file opened in 'file'. Return non zero if errors. */
6572 static int tcc_compile(TCCState
*s
)
6574 Sym
*define_start
, *sym
;
6579 include_stack_ptr
= include_stack
;
6580 ifdef_stack_ptr
= ifdef_stack
;
6582 /* XXX: not ANSI compliant: bound checking says error */
6584 anon_sym
= SYM_FIRST_ANOM
;
6586 /* file info: full path + filename */
6587 section_sym
= 0; /* avoid warning */
6589 section_sym
= put_elf_sym(symtab_section
, 0, 0,
6590 ELF32_ST_INFO(STB_LOCAL
, STT_SECTION
), 0,
6591 text_section
->sh_num
, NULL
);
6592 getcwd(buf
, sizeof(buf
));
6593 pstrcat(buf
, sizeof(buf
), "/");
6594 put_stabs_r(buf
, N_SO
, 0, 0,
6595 text_section
->data_offset
, text_section
, section_sym
);
6596 put_stabs_r(file
->filename
, N_SO
, 0, 0,
6597 text_section
->data_offset
, text_section
, section_sym
);
6599 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
6600 symbols can be safely used */
6601 put_elf_sym(symtab_section
, 0, 0,
6602 ELF32_ST_INFO(STB_LOCAL
, STT_FILE
), 0,
6603 SHN_ABS
, file
->filename
);
6605 /* define common 'char *' type because it is often used internally
6606 for arrays and struct dereference */
6607 char_pointer_type
= mk_pointer(VT_BYTE
);
6608 /* define an old type function 'int func()' */
6610 sym
= sym_push(p
, 0, FUNC_CDECL
, FUNC_OLD
);
6611 func_old_type
= VT_FUNC
| (p
<< VT_STRUCT_SHIFT
);
6613 /* define 'void *alloca(unsigned int)' builtin function */
6618 sym
= sym_push(p
, mk_pointer(VT_VOID
), FUNC_CDECL
, FUNC_NEW
);
6619 s1
= sym_push(0, VT_UNSIGNED
| VT_INT
, 0, 0);
6622 sym_push(TOK_alloca
, VT_FUNC
| (p
<< VT_STRUCT_SHIFT
), VT_CONST
, 0);
6626 define_start
= define_stack
.top
;
6628 ch
= '\n'; /* needed to parse correctly first preprocessor command */
6632 expect("declaration");
6634 /* end of translation unit info */
6636 put_stabs_r(NULL
, N_SO
, 0, 0,
6637 text_section
->data_offset
, text_section
, section_sym
);
6640 /* reset define stack, but leave -Dsymbols (may be incorrect if
6641 they are undefined) */
6642 sym_pop(&define_stack
, define_start
);
6644 sym_pop(&global_stack
, NULL
);
6649 int tcc_compile_string(TCCState
*s
, const char *str
)
6651 BufferedFile bf1
, *bf
= &bf1
;
6654 /* init file structure */
6656 bf
->buf_ptr
= (char *)str
;
6657 bf
->buf_end
= (char *)str
+ strlen(bf
->buffer
);
6658 pstrcpy(bf
->filename
, sizeof(bf
->filename
), "<string>");
6662 ret
= tcc_compile(s
);
6664 /* currently, no need to close */
6668 /* define a symbol. A value can also be provided with the '=' operator */
6669 void tcc_define_symbol(TCCState
*s
, const char *sym
, const char *value
)
6671 BufferedFile bf1
, *bf
= &bf1
;
6673 pstrcpy(bf
->buffer
, IO_BUF_SIZE
, sym
);
6674 pstrcat(bf
->buffer
, IO_BUF_SIZE
, " ");
6678 pstrcat(bf
->buffer
, IO_BUF_SIZE
, value
);
6680 /* init file structure */
6682 bf
->buf_ptr
= bf
->buffer
;
6683 bf
->buf_end
= bf
->buffer
+ strlen(bf
->buffer
);
6684 bf
->filename
[0] = '\0';
6688 include_stack_ptr
= include_stack
;
6690 /* parse with define parser */
6692 ch
= '\n'; /* needed to parse correctly first preprocessor command */
6698 void tcc_undefine_symbol(TCCState
*s1
, const char *sym
)
6702 ts
= tok_alloc(sym
, 0);
6703 s
= sym_find1(&define_stack
, tok
);
6704 /* undefine symbol by putting an invalid name */
6706 sym_undef(&define_stack
, s
);
6711 /* print the position in the source file of PC value 'pc' by reading
6712 the stabs debug information */
6713 static void rt_printline(unsigned long wanted_pc
)
6715 Stab_Sym
*sym
, *sym_end
;
6716 char func_name
[128], last_func_name
[128];
6717 unsigned long func_addr
, last_pc
, pc
;
6718 const char *incl_files
[INCLUDE_STACK_SIZE
];
6719 int incl_index
, len
, last_line_num
, i
;
6720 const char *str
, *p
;
6722 func_name
[0] = '\0';
6725 last_func_name
[0] = '\0';
6726 last_pc
= 0xffffffff;
6728 sym
= (Stab_Sym
*)stab_section
->data
+ 1;
6729 sym_end
= (Stab_Sym
*)(stab_section
->data
+ stab_section
->data_offset
);
6730 while (sym
< sym_end
) {
6731 switch(sym
->n_type
) {
6732 /* function start or end */
6734 if (sym
->n_strx
== 0) {
6735 func_name
[0] = '\0';
6738 str
= stabstr_section
->data
+ sym
->n_strx
;
6739 p
= strchr(str
, ':');
6741 pstrcpy(func_name
, sizeof(func_name
), str
);
6744 if (len
> sizeof(func_name
) - 1)
6745 len
= sizeof(func_name
) - 1;
6746 memcpy(func_name
, str
, len
);
6747 func_name
[len
] = '\0';
6749 func_addr
= sym
->n_value
;
6752 /* line number info */
6754 pc
= sym
->n_value
+ func_addr
;
6755 if (wanted_pc
>= last_pc
&& wanted_pc
< pc
)
6758 last_line_num
= sym
->n_desc
;
6760 strcpy(last_func_name
, func_name
);
6764 str
= stabstr_section
->data
+ sym
->n_strx
;
6766 if (incl_index
< INCLUDE_STACK_SIZE
) {
6767 incl_files
[incl_index
++] = str
;
6775 if (sym
->n_strx
== 0) {
6776 incl_index
= 0; /* end of translation unit */
6778 str
= stabstr_section
->data
+ sym
->n_strx
;
6779 /* do not add path */
6781 if (len
> 0 && str
[len
- 1] != '/')
6788 /* did not find line number info: */
6789 fprintf(stderr
, "(no debug info, pc=0x%08lx): ", wanted_pc
);
6792 for(i
= 0; i
< incl_index
- 1; i
++)
6793 fprintf(stderr
, "In file included from %s\n",
6795 if (incl_index
> 0) {
6796 fprintf(stderr
, "%s:%d: ",
6797 incl_files
[incl_index
- 1], last_line_num
);
6799 if (last_func_name
[0] != '\0') {
6800 fprintf(stderr
, "in function '%s()': ", last_func_name
);
6804 /* emit a run time error at position 'pc' */
6805 void rt_error(unsigned long pc
, const char *fmt
, ...)
6811 vfprintf(stderr
, fmt
, ap
);
6812 fprintf(stderr
, "\n");
6818 /* signal handler for fatal errors */
6819 static void sig_error(int signum
, siginfo_t
*siginf
, void *puc
)
6821 struct ucontext
*uc
= puc
;
6825 pc
= uc
->uc_mcontext
.gregs
[14];
6827 #error please put the right sigcontext field
6832 switch(siginf
->si_code
) {
6835 rt_error(pc
, "division by zero");
6838 rt_error(pc
, "floating point exception");
6844 rt_error(pc
, "dereferencing invalid pointer");
6847 rt_error(pc
, "illegal instruction");
6850 rt_error(pc
, "abort() called");
6853 rt_error(pc
, "caught signal %d", signum
);
6860 /* launch the compiled program with the given arguments */
6861 int tcc_run(TCCState
*s1
, int argc
, char **argv
)
6864 int (*prog_main
)(int, char **);
6867 tcc_add_runtime(s1
);
6869 relocate_common_syms();
6871 /* compute relocation address : section are relocated in place. We
6872 also alloc the bss space */
6873 for(i
= 1; i
< nb_sections
; i
++) {
6875 if (s
->sh_flags
& SHF_ALLOC
) {
6877 if (s
->sh_type
== SHT_NOBITS
) {
6878 data
= tcc_mallocz(s
->data_offset
);
6882 s
->sh_addr
= (unsigned long)data
;
6888 /* relocate each section */
6889 for(i
= 1; i
< nb_sections
; i
++) {
6892 relocate_section(s1
, s
);
6895 prog_main
= (void *)get_elf_sym_val("main");
6899 error("debug mode currently not available for Windows");
6901 struct sigaction sigact
;
6902 /* install TCC signal handlers to print debug info on fatal
6904 sigact
.sa_flags
= SA_SIGINFO
| SA_ONESHOT
;
6905 sigact
.sa_sigaction
= sig_error
;
6906 sigemptyset(&sigact
.sa_mask
);
6907 sigaction(SIGFPE
, &sigact
, NULL
);
6908 sigaction(SIGILL
, &sigact
, NULL
);
6909 sigaction(SIGSEGV
, &sigact
, NULL
);
6910 sigaction(SIGBUS
, &sigact
, NULL
);
6911 sigaction(SIGABRT
, &sigact
, NULL
);
6915 #ifdef CONFIG_TCC_BCHECK
6916 if (do_bounds_check
) {
6917 void (*bound_init
)(void);
6918 void **bound_error_func
;
6920 /* set error function */
6921 bound_error_func
= (void **)get_elf_sym_val("__bound_error_func");
6922 *bound_error_func
= rt_error
;
6924 /* XXX: use .init section so that it also work in binary ? */
6925 bound_init
= (void *)get_elf_sym_val("__bound_init");
6929 return (*prog_main
)(argc
, argv
);
6932 TCCState
*tcc_new(void)
6937 s
= tcc_malloc(sizeof(TCCState
));
6940 s
->output_type
= TCC_OUTPUT_MEMORY
;
6942 /* default include paths */
6943 tcc_add_sysinclude_path(s
, "/usr/local/include");
6944 tcc_add_sysinclude_path(s
, "/usr/include");
6945 tcc_add_sysinclude_path(s
, CONFIG_TCC_PREFIX
"/lib/tcc/include");
6947 /* add all tokens */
6948 tok_ident
= TOK_IDENT
;
6953 tok_alloc(p
, r
- p
- 1);
6957 /* we add dummy defines for some special macros to speed up tests
6958 and to have working defined() */
6959 sym_push1(&define_stack
, TOK___LINE__
, MACRO_OBJ
, 0);
6960 sym_push1(&define_stack
, TOK___FILE__
, MACRO_OBJ
, 0);
6961 sym_push1(&define_stack
, TOK___DATE__
, MACRO_OBJ
, 0);
6962 sym_push1(&define_stack
, TOK___TIME__
, MACRO_OBJ
, 0);
6964 /* standard defines */
6965 tcc_define_symbol(s
, "__STDC__", NULL
);
6966 #if defined(TCC_TARGET_I386)
6967 tcc_define_symbol(s
, "__i386__", NULL
);
6970 tcc_define_symbol(s
, "linux", NULL
);
6972 /* tiny C specific defines */
6973 tcc_define_symbol(s
, "__TINYC__", NULL
);
6975 /* default library paths */
6976 tcc_add_library_path(s
, "/usr/local/lib");
6977 tcc_add_library_path(s
, "/usr/lib");
6978 tcc_add_library_path(s
, "/lib");
6980 /* no section zero */
6981 dynarray_add((void ***)§ions
, &nb_sections
, NULL
);
6983 /* create standard sections */
6984 text_section
= new_section(".text", SHT_PROGBITS
, SHF_ALLOC
| SHF_EXECINSTR
);
6985 data_section
= new_section(".data", SHT_PROGBITS
, SHF_ALLOC
| SHF_WRITE
);
6986 bss_section
= new_section(".bss", SHT_NOBITS
, SHF_ALLOC
| SHF_WRITE
);
6988 /* symbols are always generated for linking stage */
6989 symtab_section
= new_symtab(".symtab", SHT_SYMTAB
, 0,
6991 ".hashtab", SHF_PRIVATE
);
6992 strtab_section
= symtab_section
->link
;
6994 /* private symbol table for dynamic symbols */
6995 dynsymtab_section
= new_symtab(".dynsymtab", SHT_SYMTAB
, SHF_PRIVATE
,
6997 ".dynhashtab", SHF_PRIVATE
);
7001 void tcc_delete(TCCState
*s
)
7006 int tcc_add_include_path(TCCState
*s
, const char *pathname
)
7010 pathname1
= tcc_strdup(pathname
);
7011 dynarray_add((void ***)&include_paths
, &nb_include_paths
, pathname1
);
7015 int tcc_add_sysinclude_path(TCCState
*s
, const char *pathname
)
7019 pathname1
= tcc_strdup(pathname
);
7020 dynarray_add((void ***)&sysinclude_paths
, &nb_sysinclude_paths
, pathname1
);
7024 static int tcc_add_file_internal(TCCState
*s
, const char *filename
, int flags
)
7029 BufferedFile
*saved_file
;
7031 /* find source file type with extension */
7032 ext
= strrchr(filename
, '.');
7038 file
= tcc_open(filename
);
7040 if (flags
& AFF_PRINT_ERROR
) {
7041 error("file '%s' not found", filename
);
7048 if (!ext
|| !strcmp(ext
, "c")) {
7049 /* C file assumed */
7053 /* assume executable format: auto guess file type */
7054 if (read(fd
, &ehdr
, sizeof(ehdr
)) != sizeof(ehdr
))
7055 error("could not read header");
7056 lseek(fd
, 0, SEEK_SET
);
7058 if (ehdr
.e_ident
[0] == ELFMAG0
&&
7059 ehdr
.e_ident
[1] == ELFMAG1
&&
7060 ehdr
.e_ident
[2] == ELFMAG2
&&
7061 ehdr
.e_ident
[3] == ELFMAG3
) {
7062 file
->line_num
= 0; /* do not display line number if error */
7063 if (ehdr
.e_type
== ET_REL
) {
7064 tcc_load_object_file(s
, fd
, 0);
7065 } else if (ehdr
.e_type
== ET_DYN
) {
7066 tcc_load_dll(s
, fd
, filename
, (flags
& AFF_REFERENCED_DLL
) != 0);
7068 error("unrecognized ELF file");
7070 } else if (memcmp((char *)&ehdr
, ARMAG
, 8) == 0) {
7071 file
->line_num
= 0; /* do not display line number if error */
7072 tcc_load_archive(s
, fd
);
7074 /* as GNU ld, consider it is an ld script if not recognized */
7075 if (tcc_load_ldscript(s
) < 0)
7076 error("unrecognized file type");
7084 void tcc_add_file(TCCState
*s
, const char *filename
)
7086 tcc_add_file_internal(s
, filename
, AFF_PRINT_ERROR
);
7089 int tcc_add_library_path(TCCState
*s
, const char *pathname
)
7093 pathname1
= tcc_strdup(pathname
);
7094 dynarray_add((void ***)&library_paths
, &nb_library_paths
, pathname1
);
7098 /* find and load a dll. Return non zero if not found */
7099 /* XXX: add '-rpath' option support ? */
7100 static int tcc_add_dll(TCCState
*s
, const char *filename
, int flags
)
7105 for(i
= 0; i
< nb_library_paths
; i
++) {
7106 snprintf(buf
, sizeof(buf
), "%s/%s",
7107 library_paths
[i
], filename
);
7108 if (tcc_add_file_internal(s
, buf
, flags
) == 0)
7114 /* the library name is the same as the argument of the '-l' option */
7115 int tcc_add_library(TCCState
*s
, const char *libraryname
)
7121 /* first we look for the dynamic library if not static linking */
7123 snprintf(buf
, sizeof(buf
), "lib%s.so", libraryname
);
7124 /* if we output to memory, then we simply we dlopen(). */
7125 if (s
->output_type
== TCC_OUTPUT_MEMORY
) {
7126 /* Since the libc is already loaded, we don't need to load it again */
7127 if (!strcmp(libraryname
, "c"))
7129 h
= dlopen(buf
, RTLD_GLOBAL
| RTLD_LAZY
);
7133 if (tcc_add_dll(s
, buf
, 0) == 0)
7138 /* then we look for the static library */
7139 for(i
= 0; i
< nb_library_paths
; i
++) {
7140 snprintf(buf
, sizeof(buf
), "%s/lib%s.a",
7141 library_paths
[i
], libraryname
);
7142 if (tcc_add_file_internal(s
, buf
, 0) == 0)
7148 int tcc_add_symbol(TCCState
*s
, const char *name
, unsigned long val
)
7150 add_elf_sym(symtab_section
, val
, 0,
7151 ELF32_ST_INFO(STB_GLOBAL
, STT_NOTYPE
),
7156 int tcc_set_output_type(TCCState
*s
, int output_type
)
7158 s
->output_type
= output_type
;
7160 /* if bound checking, then add corresponding sections */
7161 #ifdef CONFIG_TCC_BCHECK
7162 if (do_bounds_check
) {
7164 tcc_define_symbol(s
, "__BOUNDS_CHECKING_ON", NULL
);
7165 /* create bounds sections */
7166 bounds_section
= new_section(".bounds",
7167 SHT_PROGBITS
, SHF_ALLOC
);
7168 lbounds_section
= new_section(".lbounds",
7169 SHT_PROGBITS
, SHF_ALLOC
);
7173 /* add debug sections */
7176 stab_section
= new_section(".stab", SHT_PROGBITS
, 0);
7177 stab_section
->sh_entsize
= sizeof(Stab_Sym
);
7178 stabstr_section
= new_section(".stabstr", SHT_STRTAB
, 0);
7179 put_elf_str(stabstr_section
, "");
7180 stab_section
->link
= stabstr_section
;
7181 /* put first entry */
7182 put_stabs("", 0, 0, 0, 0);
7185 /* add libc crt1/crti objects */
7186 if (output_type
== TCC_OUTPUT_EXE
||
7187 output_type
== TCC_OUTPUT_DLL
) {
7188 if (output_type
!= TCC_OUTPUT_DLL
)
7189 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crt1.o");
7190 tcc_add_file(s
, CONFIG_TCC_CRT_PREFIX
"/crti.o");
7195 #if !defined(LIBTCC)
7199 printf("tcc version 0.9.11 - Tiny C Compiler - Copyright (C) 2001, 2002 Fabrice Bellard\n"
7200 "usage: tcc [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]\n"
7201 " [-g] [-b] [-Ldir] [-llib] [-shared] [-static]\n"
7202 " [--] infile1 [infile2... --] [infile_args...]\n"
7204 "General options:\n"
7205 " -c compile only - generate an object file\n"
7206 " -o outfile set output filename\n"
7207 " -- allows multiples input files if no -o option given. Also\n"
7208 " separate input files from runtime arguments\n"
7209 " -Bdir set tcc internal library path\n"
7210 " -bench output compilation statistics\n"
7211 "Preprocessor options:\n"
7212 " -Idir add include path 'dir'\n"
7213 " -Dsym[=val] define 'sym' with value 'val'\n"
7214 " -Usym undefine 'sym'\n"
7215 "C compiler options:\n"
7216 " -g generate runtime debug info\n"
7217 #ifdef CONFIG_TCC_BCHECK
7218 " -b compile with built-in memory and bounds checker (implies -g)\n"
7221 " -Ldir add library path 'dir'\n"
7222 " -llib link with dynamic or static library 'lib'\n"
7223 " -shared generate a shared library\n"
7224 " -static static linking\n"
7225 " -r relocatable output\n"
7229 int main(int argc
, char **argv
)
7232 int optind
, output_type
, multiple_files
, i
, reloc_output
;
7235 int nb_files
, nb_libraries
, nb_objfiles
;
7236 char objfilename
[1024];
7239 output_type
= TCC_OUTPUT_MEMORY
;
7249 if (optind
>= argc
) {
7257 /* add a new file */
7258 dynarray_add((void ***)&files
, &nb_files
, r
);
7259 if (!multiple_files
) {
7261 /* argv[0] will be this file */
7264 } else if (r
[1] == '-') {
7265 /* '--' enables multiple files input and also ends several file input */
7266 if (multiple_files
) {
7267 optind
--; /* argv[0] will be '--' */
7271 } else if (r
[1] == 'h' || r
[1] == '?') {
7275 } else if (r
[1] == 'I') {
7276 if (tcc_add_include_path(s
, r
+ 2) < 0)
7277 error("too many include paths");
7278 } else if (r
[1] == 'D') {
7281 value
= strchr(sym
, '=');
7286 tcc_define_symbol(s
, sym
, value
);
7287 } else if (r
[1] == 'U') {
7288 tcc_undefine_symbol(s
, r
+ 2);
7289 } else if (r
[1] == 'L') {
7290 tcc_add_library_path(s
, r
+ 2);
7291 } else if (r
[1] == 'B') {
7292 /* set tcc utilities path (mainly for tcc development) */
7293 tcc_lib_path
= r
+ 2;
7294 } else if (r
[1] == 'l') {
7295 dynarray_add((void ***)&files
, &nb_files
, r
);
7297 } else if (!strcmp(r
+ 1, "bench")) {
7300 #ifdef CONFIG_TCC_BCHECK
7302 do_bounds_check
= 1;
7308 } else if (r
[1] == 'c') {
7310 output_type
= TCC_OUTPUT_OBJ
;
7311 } else if (!strcmp(r
+ 1, "static")) {
7313 } else if (!strcmp(r
+ 1, "shared")) {
7314 output_type
= TCC_OUTPUT_DLL
;
7315 } else if (r
[1] == 'o') {
7319 outfile
= argv
[optind
++];
7320 } else if (r
[1] == 'r') {
7321 /* generate a .o merging several output files */
7323 output_type
= TCC_OUTPUT_OBJ
;
7325 error("invalid option -- '%s'", r
);
7329 nb_objfiles
= nb_files
- nb_libraries
;
7331 /* if outfile provided without other options, we output an
7333 if (outfile
&& output_type
== TCC_OUTPUT_MEMORY
)
7334 output_type
= TCC_OUTPUT_EXE
;
7336 /* check -c consistency : only single file handled. XXX: checks file type */
7337 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
7338 /* accepts only a single input file */
7339 if (nb_objfiles
!= 1)
7340 error("cannot specify multiple files with -c");
7341 if (nb_libraries
!= 0)
7342 error("cannot specify libraries with -c");
7345 /* compute default outfile name */
7346 if (output_type
!= TCC_OUTPUT_MEMORY
&& !outfile
) {
7347 if (output_type
== TCC_OUTPUT_OBJ
&& !reloc_output
) {
7349 /* add .o extension */
7350 pstrcpy(objfilename
, sizeof(objfilename
) - 1, files
[0]);
7351 ext
= strrchr(objfilename
, '.');
7353 goto default_outfile
;
7354 strcpy(ext
+ 1, "o");
7357 pstrcpy(objfilename
, sizeof(objfilename
), "a.out");
7359 outfile
= objfilename
;
7362 tcc_set_output_type(s
, output_type
);
7364 /* compile or add each files or library */
7365 for(i
= 0;i
< nb_files
; i
++) {
7366 const char *filename
;
7368 filename
= files
[i
];
7369 if (filename
[0] == '-') {
7370 if (tcc_add_library(s
, filename
+ 2) < 0)
7371 error("cannot find %s", filename
);
7373 tcc_add_file(s
, filename
);
7378 printf("total: %d idents, %d lines, %d bytes\n",
7379 tok_ident
- TOK_IDENT
, total_lines
, total_bytes
);
7381 printf("memory: %d bytes, max = %d bytes\n", mem_cur_size
, mem_max_size
);
7385 if (s
->output_type
!= TCC_OUTPUT_MEMORY
) {
7386 tcc_output_file(s
, outfile
);
7389 return tcc_run(s
, argc
- optind
, argv
+ optind
);