source: EcnlProtoTool/trunk/tcc-0.9.27/tccgen.c@ 331

Last change on this file since 331 was 331, checked in by coas-nagasima, 6 years ago

prototoolに関連するプロジェクトをnewlibからmuslを使うよう変更・更新
ntshellをnewlibの下位の実装から、muslのsyscallの実装に変更・更新
以下のOSSをアップデート
・mruby-1.3.0
・musl-1.1.18
・onigmo-6.1.3
・tcc-0.9.27
以下のOSSを追加
・openssl-1.1.0e
・curl-7.57.0
・zlib-1.2.11
以下のmrbgemsを追加
・iij/mruby-digest
・iij/mruby-env
・iij/mruby-errno
・iij/mruby-iijson
・iij/mruby-ipaddr
・iij/mruby-mock
・iij/mruby-require
・iij/mruby-tls-openssl

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc;charset=UTF-8
File size: 216.0 KB
Line 
1/*
2 * TCC - Tiny C Compiler
3 *
4 * Copyright (c) 2001-2004 Fabrice Bellard
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
20
21#include "tcc.h"
22
23/********************************************************/
24/* global variables */
25
26/* loc : local variable index
27 ind : output code index
28 rsym: return symbol
29 anon_sym: anonymous symbol index
30*/
31ST_DATA int rsym, anon_sym, ind, loc;
32
33ST_DATA Sym *sym_free_first;
34ST_DATA void **sym_pools;
35ST_DATA int nb_sym_pools;
36
37ST_DATA Sym *global_stack;
38ST_DATA Sym *local_stack;
39ST_DATA Sym *define_stack;
40ST_DATA Sym *global_label_stack;
41ST_DATA Sym *local_label_stack;
42static int local_scope;
43static int in_sizeof;
44static int section_sym;
45
46ST_DATA int vlas_in_scope; /* number of VLAs that are currently in scope */
47ST_DATA int vla_sp_root_loc; /* vla_sp_loc for SP before any VLAs were pushed */
48ST_DATA int vla_sp_loc; /* Pointer to variable holding location to store stack pointer on the stack when modifying stack pointer */
49
50ST_DATA SValue __vstack[1+VSTACK_SIZE], *vtop, *pvtop;
51
52ST_DATA int const_wanted; /* true if constant wanted */
53ST_DATA int nocode_wanted; /* no code generation wanted */
54#define NODATA_WANTED (nocode_wanted > 0) /* no static data output wanted either */
55#define STATIC_DATA_WANTED (nocode_wanted & 0xC0000000) /* only static data output */
56ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */
57ST_DATA CType func_vt; /* current function return type (used by return instruction) */
58ST_DATA int func_var; /* true if current function is variadic (used by return instruction) */
59ST_DATA int func_vc;
60ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */
61ST_DATA const char *funcname;
62ST_DATA int g_debug;
63
64ST_DATA CType char_pointer_type, func_old_type, int_type, size_type, ptrdiff_type;
65
66ST_DATA struct switch_t {
67 struct case_t {
68 int64_t v1, v2;
69 int sym;
70 } **p; int n; /* list of case ranges */
71 int def_sym; /* default symbol */
72} *cur_switch; /* current switch */
73
74/* ------------------------------------------------------------------------- */
75
76static void gen_cast(CType *type);
77static void gen_cast_s(int t);
78static inline CType *pointed_type(CType *type);
79static int is_compatible_types(CType *type1, CType *type2);
80static int parse_btype(CType *type, AttributeDef *ad);
81static CType *type_decl(CType *type, AttributeDef *ad, int *v, int td);
82static void parse_expr_type(CType *type);
83static void init_putv(CType *type, Section *sec, unsigned long c);
84static void decl_initializer(CType *type, Section *sec, unsigned long c, int first, int size_only);
85static void block(int *bsym, int *csym, int is_expr);
86static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, int scope);
87static void decl(int l);
88static int decl0(int l, int is_for_loop_init, Sym *);
89static void expr_eq(void);
90static void vla_runtime_type_size(CType *type, int *a);
91static void vla_sp_restore(void);
92static void vla_sp_restore_root(void);
93static int is_compatible_unqualified_types(CType *type1, CType *type2);
94static inline int64_t expr_const64(void);
95static void vpush64(int ty, unsigned long long v);
96static void vpush(CType *type);
97static int gvtst(int inv, int t);
98static void gen_inline_functions(TCCState *s);
99static void skip_or_save_block(TokenString **str);
100static void gv_dup(void);
101
102ST_INLN int is_float(int t)
103{
104 int bt;
105 bt = t & VT_BTYPE;
106 return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
107}
108
109/* we use our own 'finite' function to avoid potential problems with
110 non standard math libs */
111/* XXX: endianness dependent */
112ST_FUNC int ieee_finite(double d)
113{
114 int p[4];
115 memcpy(p, &d, sizeof(double));
116 return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
117}
118
119/* compiling intel long double natively */
120#if (defined __i386__ || defined __x86_64__) \
121 && (defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64)
122# define TCC_IS_NATIVE_387
123#endif
124
125ST_FUNC void test_lvalue(void)
126{
127 if (!(vtop->r & VT_LVAL))
128 expect("lvalue");
129}
130
131ST_FUNC void check_vstack(void)
132{
133 if (pvtop != vtop)
134 tcc_error("internal compiler error: vstack leak (%d)", vtop - pvtop);
135}
136
137/* ------------------------------------------------------------------------- */
138/* vstack debugging aid */
139
140#if 0
141void pv (const char *lbl, int a, int b)
142{
143 int i;
144 for (i = a; i < a + b; ++i) {
145 SValue *p = &vtop[-i];
146 printf("%s vtop[-%d] : type.t:%04x r:%04x r2:%04x c.i:%d\n",
147 lbl, i, p->type.t, p->r, p->r2, (int)p->c.i);
148 }
149}
150#endif
151
152/* ------------------------------------------------------------------------- */
153/* start of translation unit info */
154ST_FUNC void tcc_debug_start(TCCState *s1)
155{
156 if (s1->do_debug) {
157 char buf[512];
158
159 /* file info: full path + filename */
160 section_sym = put_elf_sym(symtab_section, 0, 0,
161 ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
162 text_section->sh_num, NULL);
163 getcwd(buf, sizeof(buf));
164#ifdef _WIN32
165 normalize_slashes(buf);
166#endif
167 pstrcat(buf, sizeof(buf), "/");
168 put_stabs_r(buf, N_SO, 0, 0,
169 text_section->data_offset, text_section, section_sym);
170 put_stabs_r(file->filename, N_SO, 0, 0,
171 text_section->data_offset, text_section, section_sym);
172 last_ind = 0;
173 last_line_num = 0;
174 }
175
176 /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
177 symbols can be safely used */
178 put_elf_sym(symtab_section, 0, 0,
179 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
180 SHN_ABS, file->filename);
181}
182
183/* put end of translation unit info */
184ST_FUNC void tcc_debug_end(TCCState *s1)
185{
186 if (!s1->do_debug)
187 return;
188 put_stabs_r(NULL, N_SO, 0, 0,
189 text_section->data_offset, text_section, section_sym);
190
191}
192
193/* generate line number info */
194ST_FUNC void tcc_debug_line(TCCState *s1)
195{
196 if (!s1->do_debug)
197 return;
198 if ((last_line_num != file->line_num || last_ind != ind)) {
199 put_stabn(N_SLINE, 0, file->line_num, ind - func_ind);
200 last_ind = ind;
201 last_line_num = file->line_num;
202 }
203}
204
205/* put function symbol */
206ST_FUNC void tcc_debug_funcstart(TCCState *s1, Sym *sym)
207{
208 char buf[512];
209
210 if (!s1->do_debug)
211 return;
212
213 /* stabs info */
214 /* XXX: we put here a dummy type */
215 snprintf(buf, sizeof(buf), "%s:%c1",
216 funcname, sym->type.t & VT_STATIC ? 'f' : 'F');
217 put_stabs_r(buf, N_FUN, 0, file->line_num, 0,
218 cur_text_section, sym->c);
219 /* //gr gdb wants a line at the function */
220 put_stabn(N_SLINE, 0, file->line_num, 0);
221
222 last_ind = 0;
223 last_line_num = 0;
224}
225
226/* put function size */
227ST_FUNC void tcc_debug_funcend(TCCState *s1, int size)
228{
229 if (!s1->do_debug)
230 return;
231 put_stabn(N_FUN, 0, 0, size);
232}
233
234/* ------------------------------------------------------------------------- */
235ST_FUNC int tccgen_compile(TCCState *s1)
236{
237 cur_text_section = NULL;
238 funcname = "";
239 anon_sym = SYM_FIRST_ANOM;
240 section_sym = 0;
241 const_wanted = 0;
242 nocode_wanted = 0x80000000;
243
244 /* define some often used types */
245 int_type.t = VT_INT;
246 char_pointer_type.t = VT_BYTE;
247 mk_pointer(&char_pointer_type);
248#if PTR_SIZE == 4
249 size_type.t = VT_INT | VT_UNSIGNED;
250 ptrdiff_type.t = VT_INT;
251#elif LONG_SIZE == 4
252 size_type.t = VT_LLONG | VT_UNSIGNED;
253 ptrdiff_type.t = VT_LLONG;
254#else
255 size_type.t = VT_LONG | VT_LLONG | VT_UNSIGNED;
256 ptrdiff_type.t = VT_LONG | VT_LLONG;
257#endif
258 func_old_type.t = VT_FUNC;
259 func_old_type.ref = sym_push(SYM_FIELD, &int_type, 0, 0);
260 func_old_type.ref->f.func_call = FUNC_CDECL;
261 func_old_type.ref->f.func_type = FUNC_OLD;
262
263 tcc_debug_start(s1);
264
265#ifdef TCC_TARGET_ARM
266 arm_init(s1);
267#endif
268
269#ifdef INC_DEBUG
270 printf("%s: **** new file\n", file->filename);
271#endif
272
273 parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM | PARSE_FLAG_TOK_STR;
274 next();
275 decl(VT_CONST);
276 gen_inline_functions(s1);
277 check_vstack();
278 /* end of translation unit info */
279 tcc_debug_end(s1);
280 return 0;
281}
282
283/* ------------------------------------------------------------------------- */
284ST_FUNC ElfSym *elfsym(Sym *s)
285{
286 if (!s || !s->c)
287 return NULL;
288 return &((ElfSym *)symtab_section->data)[s->c];
289}
290
291/* apply storage attributes to Elf symbol */
292ST_FUNC void update_storage(Sym *sym)
293{
294 ElfSym *esym;
295 int sym_bind, old_sym_bind;
296
297 esym = elfsym(sym);
298 if (!esym)
299 return;
300
301 if (sym->a.visibility)
302 esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1))
303 | sym->a.visibility;
304
305 if (sym->type.t & VT_STATIC)
306 sym_bind = STB_LOCAL;
307 else if (sym->a.weak)
308 sym_bind = STB_WEAK;
309 else
310 sym_bind = STB_GLOBAL;
311 old_sym_bind = ELFW(ST_BIND)(esym->st_info);
312 if (sym_bind != old_sym_bind) {
313 esym->st_info = ELFW(ST_INFO)(sym_bind, ELFW(ST_TYPE)(esym->st_info));
314 }
315
316#ifdef TCC_TARGET_PE
317 if (sym->a.dllimport)
318 esym->st_other |= ST_PE_IMPORT;
319 if (sym->a.dllexport)
320 esym->st_other |= ST_PE_EXPORT;
321#endif
322
323#if 0
324 printf("storage %s: bind=%c vis=%d exp=%d imp=%d\n",
325 get_tok_str(sym->v, NULL),
326 sym_bind == STB_WEAK ? 'w' : sym_bind == STB_LOCAL ? 'l' : 'g',
327 sym->a.visibility,
328 sym->a.dllexport,
329 sym->a.dllimport
330 );
331#endif
332}
333
334/* ------------------------------------------------------------------------- */
335/* update sym->c so that it points to an external symbol in section
336 'section' with value 'value' */
337
338ST_FUNC void put_extern_sym2(Sym *sym, int sh_num,
339 addr_t value, unsigned long size,
340 int can_add_underscore)
341{
342 int sym_type, sym_bind, info, other, t;
343 ElfSym *esym;
344 const char *name;
345 char buf1[256];
346#ifdef CONFIG_TCC_BCHECK
347 char buf[32];
348#endif
349
350 if (!sym->c) {
351 name = get_tok_str(sym->v, NULL);
352#ifdef CONFIG_TCC_BCHECK
353 if (tcc_state->do_bounds_check) {
354 /* XXX: avoid doing that for statics ? */
355 /* if bound checking is activated, we change some function
356 names by adding the "__bound" prefix */
357 switch(sym->v) {
358#ifdef TCC_TARGET_PE
359 /* XXX: we rely only on malloc hooks */
360 case TOK_malloc:
361 case TOK_free:
362 case TOK_realloc:
363 case TOK_memalign:
364 case TOK_calloc:
365#endif
366 case TOK_memcpy:
367 case TOK_memmove:
368 case TOK_memset:
369 case TOK_strlen:
370 case TOK_strcpy:
371 case TOK_alloca:
372 strcpy(buf, "__bound_");
373 strcat(buf, name);
374 name = buf;
375 break;
376 }
377 }
378#endif
379 t = sym->type.t;
380 if ((t & VT_BTYPE) == VT_FUNC) {
381 sym_type = STT_FUNC;
382 } else if ((t & VT_BTYPE) == VT_VOID) {
383 sym_type = STT_NOTYPE;
384 } else {
385 sym_type = STT_OBJECT;
386 }
387 if (t & VT_STATIC)
388 sym_bind = STB_LOCAL;
389 else
390 sym_bind = STB_GLOBAL;
391 other = 0;
392#ifdef TCC_TARGET_PE
393 if (sym_type == STT_FUNC && sym->type.ref) {
394 Sym *ref = sym->type.ref;
395 if (ref->f.func_call == FUNC_STDCALL && can_add_underscore) {
396 sprintf(buf1, "_%s@%d", name, ref->f.func_args * PTR_SIZE);
397 name = buf1;
398 other |= ST_PE_STDCALL;
399 can_add_underscore = 0;
400 }
401 }
402#endif
403 if (tcc_state->leading_underscore && can_add_underscore) {
404 buf1[0] = '_';
405 pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
406 name = buf1;
407 }
408 if (sym->asm_label)
409 name = get_tok_str(sym->asm_label, NULL);
410 info = ELFW(ST_INFO)(sym_bind, sym_type);
411 sym->c = put_elf_sym(symtab_section, value, size, info, other, sh_num, name);
412 } else {
413 esym = elfsym(sym);
414 esym->st_value = value;
415 esym->st_size = size;
416 esym->st_shndx = sh_num;
417 }
418 update_storage(sym);
419}
420
421ST_FUNC void put_extern_sym(Sym *sym, Section *section,
422 addr_t value, unsigned long size)
423{
424 int sh_num = section ? section->sh_num : SHN_UNDEF;
425 put_extern_sym2(sym, sh_num, value, size, 1);
426}
427
428/* add a new relocation entry to symbol 'sym' in section 's' */
429ST_FUNC void greloca(Section *s, Sym *sym, unsigned long offset, int type,
430 addr_t addend)
431{
432 int c = 0;
433
434 if (nocode_wanted && s == cur_text_section)
435 return;
436
437 if (sym) {
438 if (0 == sym->c)
439 put_extern_sym(sym, NULL, 0, 0);
440 c = sym->c;
441 }
442
443 /* now we can add ELF relocation info */
444 put_elf_reloca(symtab_section, s, offset, type, c, addend);
445}
446
447#if PTR_SIZE == 4
448ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
449{
450 greloca(s, sym, offset, type, 0);
451}
452#endif
453
454/* ------------------------------------------------------------------------- */
455/* symbol allocator */
456static Sym *__sym_malloc(void)
457{
458 Sym *sym_pool, *sym, *last_sym;
459 int i;
460
461 sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
462 dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
463
464 last_sym = sym_free_first;
465 sym = sym_pool;
466 for(i = 0; i < SYM_POOL_NB; i++) {
467 sym->next = last_sym;
468 last_sym = sym;
469 sym++;
470 }
471 sym_free_first = last_sym;
472 return last_sym;
473}
474
475static inline Sym *sym_malloc(void)
476{
477 Sym *sym;
478#ifndef SYM_DEBUG
479 sym = sym_free_first;
480 if (!sym)
481 sym = __sym_malloc();
482 sym_free_first = sym->next;
483 return sym;
484#else
485 sym = tcc_malloc(sizeof(Sym));
486 return sym;
487#endif
488}
489
490ST_INLN void sym_free(Sym *sym)
491{
492#ifndef SYM_DEBUG
493 sym->next = sym_free_first;
494 sym_free_first = sym;
495#else
496 tcc_free(sym);
497#endif
498}
499
500/* push, without hashing */
501ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, int c)
502{
503 Sym *s;
504
505 s = sym_malloc();
506 memset(s, 0, sizeof *s);
507 s->v = v;
508 s->type.t = t;
509 s->c = c;
510 /* add in stack */
511 s->prev = *ps;
512 *ps = s;
513 return s;
514}
515
516/* find a symbol and return its associated structure. 's' is the top
517 of the symbol stack */
518ST_FUNC Sym *sym_find2(Sym *s, int v)
519{
520 while (s) {
521 if (s->v == v)
522 return s;
523 else if (s->v == -1)
524 return NULL;
525 s = s->prev;
526 }
527 return NULL;
528}
529
530/* structure lookup */
531ST_INLN Sym *struct_find(int v)
532{
533 v -= TOK_IDENT;
534 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
535 return NULL;
536 return table_ident[v]->sym_struct;
537}
538
539/* find an identifier */
540ST_INLN Sym *sym_find(int v)
541{
542 v -= TOK_IDENT;
543 if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
544 return NULL;
545 return table_ident[v]->sym_identifier;
546}
547
548/* push a given symbol on the symbol stack */
549ST_FUNC Sym *sym_push(int v, CType *type, int r, int c)
550{
551 Sym *s, **ps;
552 TokenSym *ts;
553
554 if (local_stack)
555 ps = &local_stack;
556 else
557 ps = &global_stack;
558 s = sym_push2(ps, v, type->t, c);
559 s->type.ref = type->ref;
560 s->r = r;
561 /* don't record fields or anonymous symbols */
562 /* XXX: simplify */
563 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
564 /* record symbol in token array */
565 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
566 if (v & SYM_STRUCT)
567 ps = &ts->sym_struct;
568 else
569 ps = &ts->sym_identifier;
570 s->prev_tok = *ps;
571 *ps = s;
572 s->sym_scope = local_scope;
573 if (s->prev_tok && s->prev_tok->sym_scope == s->sym_scope)
574 tcc_error("redeclaration of '%s'",
575 get_tok_str(v & ~SYM_STRUCT, NULL));
576 }
577 return s;
578}
579
580/* push a global identifier */
581ST_FUNC Sym *global_identifier_push(int v, int t, int c)
582{
583 Sym *s, **ps;
584 s = sym_push2(&global_stack, v, t, c);
585 /* don't record anonymous symbol */
586 if (v < SYM_FIRST_ANOM) {
587 ps = &table_ident[v - TOK_IDENT]->sym_identifier;
588 /* modify the top most local identifier, so that
589 sym_identifier will point to 's' when popped */
590 while (*ps != NULL && (*ps)->sym_scope)
591 ps = &(*ps)->prev_tok;
592 s->prev_tok = *ps;
593 *ps = s;
594 }
595 return s;
596}
597
598/* pop symbols until top reaches 'b'. If KEEP is non-zero don't really
599 pop them yet from the list, but do remove them from the token array. */
600ST_FUNC void sym_pop(Sym **ptop, Sym *b, int keep)
601{
602 Sym *s, *ss, **ps;
603 TokenSym *ts;
604 int v;
605
606 s = *ptop;
607 while(s != b) {
608 ss = s->prev;
609 v = s->v;
610 /* remove symbol in token array */
611 /* XXX: simplify */
612 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
613 ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
614 if (v & SYM_STRUCT)
615 ps = &ts->sym_struct;
616 else
617 ps = &ts->sym_identifier;
618 *ps = s->prev_tok;
619 }
620 if (!keep)
621 sym_free(s);
622 s = ss;
623 }
624 if (!keep)
625 *ptop = b;
626}
627
628/* ------------------------------------------------------------------------- */
629
630static void vsetc(CType *type, int r, CValue *vc)
631{
632 int v;
633
634 if (vtop >= vstack + (VSTACK_SIZE - 1))
635 tcc_error("memory full (vstack)");
636 /* cannot let cpu flags if other instruction are generated. Also
637 avoid leaving VT_JMP anywhere except on the top of the stack
638 because it would complicate the code generator.
639
640 Don't do this when nocode_wanted. vtop might come from
641 !nocode_wanted regions (see 88_codeopt.c) and transforming
642 it to a register without actually generating code is wrong
643 as their value might still be used for real. All values
644 we push under nocode_wanted will eventually be popped
645 again, so that the VT_CMP/VT_JMP value will be in vtop
646 when code is unsuppressed again.
647
648 Same logic below in vswap(); */
649 if (vtop >= vstack && !nocode_wanted) {
650 v = vtop->r & VT_VALMASK;
651 if (v == VT_CMP || (v & ~1) == VT_JMP)
652 gv(RC_INT);
653 }
654
655 vtop++;
656 vtop->type = *type;
657 vtop->r = r;
658 vtop->r2 = VT_CONST;
659 vtop->c = *vc;
660 vtop->sym = NULL;
661}
662
663ST_FUNC void vswap(void)
664{
665 SValue tmp;
666 /* cannot vswap cpu flags. See comment at vsetc() above */
667 if (vtop >= vstack && !nocode_wanted) {
668 int v = vtop->r & VT_VALMASK;
669 if (v == VT_CMP || (v & ~1) == VT_JMP)
670 gv(RC_INT);
671 }
672 tmp = vtop[0];
673 vtop[0] = vtop[-1];
674 vtop[-1] = tmp;
675}
676
677/* pop stack value */
678ST_FUNC void vpop(void)
679{
680 int v;
681 v = vtop->r & VT_VALMASK;
682#if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
683 /* for x86, we need to pop the FP stack */
684 if (v == TREG_ST0) {
685 o(0xd8dd); /* fstp %st(0) */
686 } else
687#endif
688 if (v == VT_JMP || v == VT_JMPI) {
689 /* need to put correct jump if && or || without test */
690 gsym(vtop->c.i);
691 }
692 vtop--;
693}
694
695/* push constant of type "type" with useless value */
696ST_FUNC void vpush(CType *type)
697{
698 vset(type, VT_CONST, 0);
699}
700
701/* push integer constant */
702ST_FUNC void vpushi(int v)
703{
704 CValue cval;
705 cval.i = v;
706 vsetc(&int_type, VT_CONST, &cval);
707}
708
709/* push a pointer sized constant */
710static void vpushs(addr_t v)
711{
712 CValue cval;
713 cval.i = v;
714 vsetc(&size_type, VT_CONST, &cval);
715}
716
717/* push arbitrary 64bit constant */
718ST_FUNC void vpush64(int ty, unsigned long long v)
719{
720 CValue cval;
721 CType ctype;
722 ctype.t = ty;
723 ctype.ref = NULL;
724 cval.i = v;
725 vsetc(&ctype, VT_CONST, &cval);
726}
727
728/* push long long constant */
729static inline void vpushll(long long v)
730{
731 vpush64(VT_LLONG, v);
732}
733
734ST_FUNC void vset(CType *type, int r, int v)
735{
736 CValue cval;
737
738 cval.i = v;
739 vsetc(type, r, &cval);
740}
741
742static void vseti(int r, int v)
743{
744 CType type;
745 type.t = VT_INT;
746 type.ref = NULL;
747 vset(&type, r, v);
748}
749
750ST_FUNC void vpushv(SValue *v)
751{
752 if (vtop >= vstack + (VSTACK_SIZE - 1))
753 tcc_error("memory full (vstack)");
754 vtop++;
755 *vtop = *v;
756}
757
758static void vdup(void)
759{
760 vpushv(vtop);
761}
762
763/* rotate n first stack elements to the bottom
764 I1 ... In -> I2 ... In I1 [top is right]
765*/
766ST_FUNC void vrotb(int n)
767{
768 int i;
769 SValue tmp;
770
771 tmp = vtop[-n + 1];
772 for(i=-n+1;i!=0;i++)
773 vtop[i] = vtop[i+1];
774 vtop[0] = tmp;
775}
776
777/* rotate the n elements before entry e towards the top
778 I1 ... In ... -> In I1 ... I(n-1) ... [top is right]
779 */
780ST_FUNC void vrote(SValue *e, int n)
781{
782 int i;
783 SValue tmp;
784
785 tmp = *e;
786 for(i = 0;i < n - 1; i++)
787 e[-i] = e[-i - 1];
788 e[-n + 1] = tmp;
789}
790
791/* rotate n first stack elements to the top
792 I1 ... In -> In I1 ... I(n-1) [top is right]
793 */
794ST_FUNC void vrott(int n)
795{
796 vrote(vtop, n);
797}
798
799/* push a symbol value of TYPE */
800static inline void vpushsym(CType *type, Sym *sym)
801{
802 CValue cval;
803 cval.i = 0;
804 vsetc(type, VT_CONST | VT_SYM, &cval);
805 vtop->sym = sym;
806}
807
808/* Return a static symbol pointing to a section */
809ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
810{
811 int v;
812 Sym *sym;
813
814 v = anon_sym++;
815 sym = global_identifier_push(v, type->t | VT_STATIC, 0);
816 sym->type.ref = type->ref;
817 sym->r = VT_CONST | VT_SYM;
818 put_extern_sym(sym, sec, offset, size);
819 return sym;
820}
821
822/* push a reference to a section offset by adding a dummy symbol */
823static void vpush_ref(CType *type, Section *sec, unsigned long offset, unsigned long size)
824{
825 vpushsym(type, get_sym_ref(type, sec, offset, size));
826}
827
828/* define a new external reference to a symbol 'v' of type 'u' */
829ST_FUNC Sym *external_global_sym(int v, CType *type, int r)
830{
831 Sym *s;
832
833 s = sym_find(v);
834 if (!s) {
835 /* push forward reference */
836 s = global_identifier_push(v, type->t | VT_EXTERN, 0);
837 s->type.ref = type->ref;
838 s->r = r | VT_CONST | VT_SYM;
839 } else if (IS_ASM_SYM(s)) {
840 s->type.t = type->t | (s->type.t & VT_EXTERN);
841 s->type.ref = type->ref;
842 update_storage(s);
843 }
844 return s;
845}
846
847/* Merge some type attributes. */
848static void patch_type(Sym *sym, CType *type)
849{
850 if (!(type->t & VT_EXTERN)) {
851 if (!(sym->type.t & VT_EXTERN))
852 tcc_error("redefinition of '%s'", get_tok_str(sym->v, NULL));
853 sym->type.t &= ~VT_EXTERN;
854 }
855
856 if (IS_ASM_SYM(sym)) {
857 /* stay static if both are static */
858 sym->type.t = type->t & (sym->type.t | ~VT_STATIC);
859 sym->type.ref = type->ref;
860 }
861
862 if (!is_compatible_types(&sym->type, type)) {
863 tcc_error("incompatible types for redefinition of '%s'",
864 get_tok_str(sym->v, NULL));
865
866 } else if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
867 int static_proto = sym->type.t & VT_STATIC;
868 /* warn if static follows non-static function declaration */
869 if ((type->t & VT_STATIC) && !static_proto && !(type->t & VT_INLINE))
870 tcc_warning("static storage ignored for redefinition of '%s'",
871 get_tok_str(sym->v, NULL));
872
873 if (0 == (type->t & VT_EXTERN)) {
874 /* put complete type, use static from prototype */
875 sym->type.t = (type->t & ~VT_STATIC) | static_proto;
876 if (type->t & VT_INLINE)
877 sym->type.t = type->t;
878 sym->type.ref = type->ref;
879 }
880
881 } else {
882 if ((sym->type.t & VT_ARRAY) && type->ref->c >= 0) {
883 /* set array size if it was omitted in extern declaration */
884 if (sym->type.ref->c < 0)
885 sym->type.ref->c = type->ref->c;
886 else if (sym->type.ref->c != type->ref->c)
887 tcc_error("conflicting type for '%s'", get_tok_str(sym->v, NULL));
888 }
889 if ((type->t ^ sym->type.t) & VT_STATIC)
890 tcc_warning("storage mismatch for redefinition of '%s'",
891 get_tok_str(sym->v, NULL));
892 }
893}
894
895
896/* Merge some storage attributes. */
897static void patch_storage(Sym *sym, AttributeDef *ad, CType *type)
898{
899 if (type)
900 patch_type(sym, type);
901
902#ifdef TCC_TARGET_PE
903 if (sym->a.dllimport != ad->a.dllimport)
904 tcc_error("incompatible dll linkage for redefinition of '%s'",
905 get_tok_str(sym->v, NULL));
906 sym->a.dllexport |= ad->a.dllexport;
907#endif
908 sym->a.weak |= ad->a.weak;
909 if (ad->a.visibility) {
910 int vis = sym->a.visibility;
911 int vis2 = ad->a.visibility;
912 if (vis == STV_DEFAULT)
913 vis = vis2;
914 else if (vis2 != STV_DEFAULT)
915 vis = (vis < vis2) ? vis : vis2;
916 sym->a.visibility = vis;
917 }
918 if (ad->a.aligned)
919 sym->a.aligned = ad->a.aligned;
920 if (ad->asm_label)
921 sym->asm_label = ad->asm_label;
922 update_storage(sym);
923}
924
925/* define a new external reference to a symbol 'v' */
926static Sym *external_sym(int v, CType *type, int r, AttributeDef *ad)
927{
928 Sym *s;
929 s = sym_find(v);
930 if (!s) {
931 /* push forward reference */
932 s = sym_push(v, type, r | VT_CONST | VT_SYM, 0);
933 s->type.t |= VT_EXTERN;
934 s->a = ad->a;
935 s->sym_scope = 0;
936 } else {
937 if (s->type.ref == func_old_type.ref) {
938 s->type.ref = type->ref;
939 s->r = r | VT_CONST | VT_SYM;
940 s->type.t |= VT_EXTERN;
941 }
942 patch_storage(s, ad, type);
943 }
944 return s;
945}
946
947/* push a reference to global symbol v */
948ST_FUNC void vpush_global_sym(CType *type, int v)
949{
950 vpushsym(type, external_global_sym(v, type, 0));
951}
952
953/* save registers up to (vtop - n) stack entry */
954ST_FUNC void save_regs(int n)
955{
956 SValue *p, *p1;
957 for(p = vstack, p1 = vtop - n; p <= p1; p++)
958 save_reg(p->r);
959}
960
961/* save r to the memory stack, and mark it as being free */
962ST_FUNC void save_reg(int r)
963{
964 save_reg_upstack(r, 0);
965}
966
967/* save r to the memory stack, and mark it as being free,
968 if seen up to (vtop - n) stack entry */
969ST_FUNC void save_reg_upstack(int r, int n)
970{
971 int l, saved, size, align;
972 SValue *p, *p1, sv;
973 CType *type;
974
975 if ((r &= VT_VALMASK) >= VT_CONST)
976 return;
977 if (nocode_wanted)
978 return;
979
980 /* modify all stack values */
981 saved = 0;
982 l = 0;
983 for(p = vstack, p1 = vtop - n; p <= p1; p++) {
984 if ((p->r & VT_VALMASK) == r ||
985 ((p->type.t & VT_BTYPE) == VT_LLONG && (p->r2 & VT_VALMASK) == r)) {
986 /* must save value on stack if not already done */
987 if (!saved) {
988 /* NOTE: must reload 'r' because r might be equal to r2 */
989 r = p->r & VT_VALMASK;
990 /* store register in the stack */
991 type = &p->type;
992 if ((p->r & VT_LVAL) ||
993 (!is_float(type->t) && (type->t & VT_BTYPE) != VT_LLONG))
994#if PTR_SIZE == 8
995 type = &char_pointer_type;
996#else
997 type = &int_type;
998#endif
999 size = type_size(type, &align);
1000 loc = (loc - size) & -align;
1001 sv.type.t = type->t;
1002 sv.r = VT_LOCAL | VT_LVAL;
1003 sv.c.i = loc;
1004 store(r, &sv);
1005#if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
1006 /* x86 specific: need to pop fp register ST0 if saved */
1007 if (r == TREG_ST0) {
1008 o(0xd8dd); /* fstp %st(0) */
1009 }
1010#endif
1011#if PTR_SIZE == 4
1012 /* special long long case */
1013 if ((type->t & VT_BTYPE) == VT_LLONG) {
1014 sv.c.i += 4;
1015 store(p->r2, &sv);
1016 }
1017#endif
1018 l = loc;
1019 saved = 1;
1020 }
1021 /* mark that stack entry as being saved on the stack */
1022 if (p->r & VT_LVAL) {
1023 /* also clear the bounded flag because the
1024 relocation address of the function was stored in
1025 p->c.i */
1026 p->r = (p->r & ~(VT_VALMASK | VT_BOUNDED)) | VT_LLOCAL;
1027 } else {
1028 p->r = lvalue_type(p->type.t) | VT_LOCAL;
1029 }
1030 p->r2 = VT_CONST;
1031 p->c.i = l;
1032 }
1033 }
1034}
1035
1036#ifdef TCC_TARGET_ARM
1037/* find a register of class 'rc2' with at most one reference on stack.
1038 * If none, call get_reg(rc) */
1039ST_FUNC int get_reg_ex(int rc, int rc2)
1040{
1041 int r;
1042 SValue *p;
1043
1044 for(r=0;r<NB_REGS;r++) {
1045 if (reg_classes[r] & rc2) {
1046 int n;
1047 n=0;
1048 for(p = vstack; p <= vtop; p++) {
1049 if ((p->r & VT_VALMASK) == r ||
1050 (p->r2 & VT_VALMASK) == r)
1051 n++;
1052 }
1053 if (n <= 1)
1054 return r;
1055 }
1056 }
1057 return get_reg(rc);
1058}
1059#endif
1060
1061/* find a free register of class 'rc'. If none, save one register */
1062ST_FUNC int get_reg(int rc)
1063{
1064 int r;
1065 SValue *p;
1066
1067 /* find a free register */
1068 for(r=0;r<NB_REGS;r++) {
1069 if (reg_classes[r] & rc) {
1070 if (nocode_wanted)
1071 return r;
1072 for(p=vstack;p<=vtop;p++) {
1073 if ((p->r & VT_VALMASK) == r ||
1074 (p->r2 & VT_VALMASK) == r)
1075 goto notfound;
1076 }
1077 return r;
1078 }
1079 notfound: ;
1080 }
1081
1082 /* no register left : free the first one on the stack (VERY
1083 IMPORTANT to start from the bottom to ensure that we don't
1084 spill registers used in gen_opi()) */
1085 for(p=vstack;p<=vtop;p++) {
1086 /* look at second register (if long long) */
1087 r = p->r2 & VT_VALMASK;
1088 if (r < VT_CONST && (reg_classes[r] & rc))
1089 goto save_found;
1090 r = p->r & VT_VALMASK;
1091 if (r < VT_CONST && (reg_classes[r] & rc)) {
1092 save_found:
1093 save_reg(r);
1094 return r;
1095 }
1096 }
1097 /* Should never comes here */
1098 return -1;
1099}
1100
1101/* move register 's' (of type 't') to 'r', and flush previous value of r to memory
1102 if needed */
1103static void move_reg(int r, int s, int t)
1104{
1105 SValue sv;
1106
1107 if (r != s) {
1108 save_reg(r);
1109 sv.type.t = t;
1110 sv.type.ref = NULL;
1111 sv.r = s;
1112 sv.c.i = 0;
1113 load(r, &sv);
1114 }
1115}
1116
1117/* get address of vtop (vtop MUST BE an lvalue) */
1118ST_FUNC void gaddrof(void)
1119{
1120 vtop->r &= ~VT_LVAL;
1121 /* tricky: if saved lvalue, then we can go back to lvalue */
1122 if ((vtop->r & VT_VALMASK) == VT_LLOCAL)
1123 vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
1124
1125
1126}
1127
1128#ifdef CONFIG_TCC_BCHECK
1129/* generate lvalue bound code */
1130static void gbound(void)
1131{
1132 int lval_type;
1133 CType type1;
1134
1135 vtop->r &= ~VT_MUSTBOUND;
1136 /* if lvalue, then use checking code before dereferencing */
1137 if (vtop->r & VT_LVAL) {
1138 /* if not VT_BOUNDED value, then make one */
1139 if (!(vtop->r & VT_BOUNDED)) {
1140 lval_type = vtop->r & (VT_LVAL_TYPE | VT_LVAL);
1141 /* must save type because we must set it to int to get pointer */
1142 type1 = vtop->type;
1143 vtop->type.t = VT_PTR;
1144 gaddrof();
1145 vpushi(0);
1146 gen_bounded_ptr_add();
1147 vtop->r |= lval_type;
1148 vtop->type = type1;
1149 }
1150 /* then check for dereferencing */
1151 gen_bounded_ptr_deref();
1152 }
1153}
1154#endif
1155
1156static void incr_bf_adr(int o)
1157{
1158 vtop->type = char_pointer_type;
1159 gaddrof();
1160 vpushi(o);
1161 gen_op('+');
1162 vtop->type.t = (vtop->type.t & ~(VT_BTYPE|VT_DEFSIGN))
1163 | (VT_BYTE|VT_UNSIGNED);
1164 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
1165 | (VT_LVAL_BYTE|VT_LVAL_UNSIGNED|VT_LVAL);
1166}
1167
1168/* single-byte load mode for packed or otherwise unaligned bitfields */
1169static void load_packed_bf(CType *type, int bit_pos, int bit_size)
1170{
1171 int n, o, bits;
1172 save_reg_upstack(vtop->r, 1);
1173 vpush64(type->t & VT_BTYPE, 0); // B X
1174 bits = 0, o = bit_pos >> 3, bit_pos &= 7;
1175 do {
1176 vswap(); // X B
1177 incr_bf_adr(o);
1178 vdup(); // X B B
1179 n = 8 - bit_pos;
1180 if (n > bit_size)
1181 n = bit_size;
1182 if (bit_pos)
1183 vpushi(bit_pos), gen_op(TOK_SHR), bit_pos = 0; // X B Y
1184 if (n < 8)
1185 vpushi((1 << n) - 1), gen_op('&');
1186 gen_cast(type);
1187 if (bits)
1188 vpushi(bits), gen_op(TOK_SHL);
1189 vrotb(3); // B Y X
1190 gen_op('|'); // B X
1191 bits += n, bit_size -= n, o = 1;
1192 } while (bit_size);
1193 vswap(), vpop();
1194 if (!(type->t & VT_UNSIGNED)) {
1195 n = ((type->t & VT_BTYPE) == VT_LLONG ? 64 : 32) - bits;
1196 vpushi(n), gen_op(TOK_SHL);
1197 vpushi(n), gen_op(TOK_SAR);
1198 }
1199}
1200
1201/* single-byte store mode for packed or otherwise unaligned bitfields */
1202static void store_packed_bf(int bit_pos, int bit_size)
1203{
1204 int bits, n, o, m, c;
1205
1206 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1207 vswap(); // X B
1208 save_reg_upstack(vtop->r, 1);
1209 bits = 0, o = bit_pos >> 3, bit_pos &= 7;
1210 do {
1211 incr_bf_adr(o); // X B
1212 vswap(); //B X
1213 c ? vdup() : gv_dup(); // B V X
1214 vrott(3); // X B V
1215 if (bits)
1216 vpushi(bits), gen_op(TOK_SHR);
1217 if (bit_pos)
1218 vpushi(bit_pos), gen_op(TOK_SHL);
1219 n = 8 - bit_pos;
1220 if (n > bit_size)
1221 n = bit_size;
1222 if (n < 8) {
1223 m = ((1 << n) - 1) << bit_pos;
1224 vpushi(m), gen_op('&'); // X B V1
1225 vpushv(vtop-1); // X B V1 B
1226 vpushi(m & 0x80 ? ~m & 0x7f : ~m);
1227 gen_op('&'); // X B V1 B1
1228 gen_op('|'); // X B V2
1229 }
1230 vdup(), vtop[-1] = vtop[-2]; // X B B V2
1231 vstore(), vpop(); // X B
1232 bits += n, bit_size -= n, bit_pos = 0, o = 1;
1233 } while (bit_size);
1234 vpop(), vpop();
1235}
1236
1237static int adjust_bf(SValue *sv, int bit_pos, int bit_size)
1238{
1239 int t;
1240 if (0 == sv->type.ref)
1241 return 0;
1242 t = sv->type.ref->auxtype;
1243 if (t != -1 && t != VT_STRUCT) {
1244 sv->type.t = (sv->type.t & ~VT_BTYPE) | t;
1245 sv->r = (sv->r & ~VT_LVAL_TYPE) | lvalue_type(sv->type.t);
1246 }
1247 return t;
1248}
1249
1250/* store vtop a register belonging to class 'rc'. lvalues are
1251 converted to values. Cannot be used if cannot be converted to
1252 register value (such as structures). */
1253ST_FUNC int gv(int rc)
1254{
1255 int r, bit_pos, bit_size, size, align, rc2;
1256
1257 /* NOTE: get_reg can modify vstack[] */
1258 if (vtop->type.t & VT_BITFIELD) {
1259 CType type;
1260
1261 bit_pos = BIT_POS(vtop->type.t);
1262 bit_size = BIT_SIZE(vtop->type.t);
1263 /* remove bit field info to avoid loops */
1264 vtop->type.t &= ~VT_STRUCT_MASK;
1265
1266 type.ref = NULL;
1267 type.t = vtop->type.t & VT_UNSIGNED;
1268 if ((vtop->type.t & VT_BTYPE) == VT_BOOL)
1269 type.t |= VT_UNSIGNED;
1270
1271 r = adjust_bf(vtop, bit_pos, bit_size);
1272
1273 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
1274 type.t |= VT_LLONG;
1275 else
1276 type.t |= VT_INT;
1277
1278 if (r == VT_STRUCT) {
1279 load_packed_bf(&type, bit_pos, bit_size);
1280 } else {
1281 int bits = (type.t & VT_BTYPE) == VT_LLONG ? 64 : 32;
1282 /* cast to int to propagate signedness in following ops */
1283 gen_cast(&type);
1284 /* generate shifts */
1285 vpushi(bits - (bit_pos + bit_size));
1286 gen_op(TOK_SHL);
1287 vpushi(bits - bit_size);
1288 /* NOTE: transformed to SHR if unsigned */
1289 gen_op(TOK_SAR);
1290 }
1291 r = gv(rc);
1292 } else {
1293 if (is_float(vtop->type.t) &&
1294 (vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1295 unsigned long offset;
1296 /* CPUs usually cannot use float constants, so we store them
1297 generically in data segment */
1298 size = type_size(&vtop->type, &align);
1299 if (NODATA_WANTED)
1300 size = 0, align = 1;
1301 offset = section_add(data_section, size, align);
1302 vpush_ref(&vtop->type, data_section, offset, size);
1303 vswap();
1304 init_putv(&vtop->type, data_section, offset);
1305 vtop->r |= VT_LVAL;
1306 }
1307#ifdef CONFIG_TCC_BCHECK
1308 if (vtop->r & VT_MUSTBOUND)
1309 gbound();
1310#endif
1311
1312 r = vtop->r & VT_VALMASK;
1313 rc2 = (rc & RC_FLOAT) ? RC_FLOAT : RC_INT;
1314#ifndef TCC_TARGET_ARM64
1315 if (rc == RC_IRET)
1316 rc2 = RC_LRET;
1317#ifdef TCC_TARGET_X86_64
1318 else if (rc == RC_FRET)
1319 rc2 = RC_QRET;
1320#endif
1321#endif
1322 /* need to reload if:
1323 - constant
1324 - lvalue (need to dereference pointer)
1325 - already a register, but not in the right class */
1326 if (r >= VT_CONST
1327 || (vtop->r & VT_LVAL)
1328 || !(reg_classes[r] & rc)
1329#if PTR_SIZE == 8
1330 || ((vtop->type.t & VT_BTYPE) == VT_QLONG && !(reg_classes[vtop->r2] & rc2))
1331 || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT && !(reg_classes[vtop->r2] & rc2))
1332#else
1333 || ((vtop->type.t & VT_BTYPE) == VT_LLONG && !(reg_classes[vtop->r2] & rc2))
1334#endif
1335 )
1336 {
1337 r = get_reg(rc);
1338#if PTR_SIZE == 8
1339 if (((vtop->type.t & VT_BTYPE) == VT_QLONG) || ((vtop->type.t & VT_BTYPE) == VT_QFLOAT)) {
1340 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
1341#else
1342 if ((vtop->type.t & VT_BTYPE) == VT_LLONG) {
1343 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
1344 unsigned long long ll;
1345#endif
1346 int r2, original_type;
1347 original_type = vtop->type.t;
1348 /* two register type load : expand to two words
1349 temporarily */
1350#if PTR_SIZE == 4
1351 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST) {
1352 /* load constant */
1353 ll = vtop->c.i;
1354 vtop->c.i = ll; /* first word */
1355 load(r, vtop);
1356 vtop->r = r; /* save register value */
1357 vpushi(ll >> 32); /* second word */
1358 } else
1359#endif
1360 if (vtop->r & VT_LVAL) {
1361 /* We do not want to modifier the long long
1362 pointer here, so the safest (and less
1363 efficient) is to save all the other registers
1364 in the stack. XXX: totally inefficient. */
1365 #if 0
1366 save_regs(1);
1367 #else
1368 /* lvalue_save: save only if used further down the stack */
1369 save_reg_upstack(vtop->r, 1);
1370 #endif
1371 /* load from memory */
1372 vtop->type.t = load_type;
1373 load(r, vtop);
1374 vdup();
1375 vtop[-1].r = r; /* save register value */
1376 /* increment pointer to get second word */
1377 vtop->type.t = addr_type;
1378 gaddrof();
1379 vpushi(load_size);
1380 gen_op('+');
1381 vtop->r |= VT_LVAL;
1382 vtop->type.t = load_type;
1383 } else {
1384 /* move registers */
1385 load(r, vtop);
1386 vdup();
1387 vtop[-1].r = r; /* save register value */
1388 vtop->r = vtop[-1].r2;
1389 }
1390 /* Allocate second register. Here we rely on the fact that
1391 get_reg() tries first to free r2 of an SValue. */
1392 r2 = get_reg(rc2);
1393 load(r2, vtop);
1394 vpop();
1395 /* write second register */
1396 vtop->r2 = r2;
1397 vtop->type.t = original_type;
1398 } else if ((vtop->r & VT_LVAL) && !is_float(vtop->type.t)) {
1399 int t1, t;
1400 /* lvalue of scalar type : need to use lvalue type
1401 because of possible cast */
1402 t = vtop->type.t;
1403 t1 = t;
1404 /* compute memory access type */
1405 if (vtop->r & VT_LVAL_BYTE)
1406 t = VT_BYTE;
1407 else if (vtop->r & VT_LVAL_SHORT)
1408 t = VT_SHORT;
1409 if (vtop->r & VT_LVAL_UNSIGNED)
1410 t |= VT_UNSIGNED;
1411 vtop->type.t = t;
1412 load(r, vtop);
1413 /* restore wanted type */
1414 vtop->type.t = t1;
1415 } else {
1416 /* one register type load */
1417 load(r, vtop);
1418 }
1419 }
1420 vtop->r = r;
1421#ifdef TCC_TARGET_C67
1422 /* uses register pairs for doubles */
1423 if ((vtop->type.t & VT_BTYPE) == VT_DOUBLE)
1424 vtop->r2 = r+1;
1425#endif
1426 }
1427 return r;
1428}
1429
1430/* generate vtop[-1] and vtop[0] in resp. classes rc1 and rc2 */
1431ST_FUNC void gv2(int rc1, int rc2)
1432{
1433 int v;
1434
1435 /* generate more generic register first. But VT_JMP or VT_CMP
1436 values must be generated first in all cases to avoid possible
1437 reload errors */
1438 v = vtop[0].r & VT_VALMASK;
1439 if (v != VT_CMP && (v & ~1) != VT_JMP && rc1 <= rc2) {
1440 vswap();
1441 gv(rc1);
1442 vswap();
1443 gv(rc2);
1444 /* test if reload is needed for first register */
1445 if ((vtop[-1].r & VT_VALMASK) >= VT_CONST) {
1446 vswap();
1447 gv(rc1);
1448 vswap();
1449 }
1450 } else {
1451 gv(rc2);
1452 vswap();
1453 gv(rc1);
1454 vswap();
1455 /* test if reload is needed for first register */
1456 if ((vtop[0].r & VT_VALMASK) >= VT_CONST) {
1457 gv(rc2);
1458 }
1459 }
1460}
1461
1462#ifndef TCC_TARGET_ARM64
1463/* wrapper around RC_FRET to return a register by type */
1464static int rc_fret(int t)
1465{
1466#ifdef TCC_TARGET_X86_64
1467 if (t == VT_LDOUBLE) {
1468 return RC_ST0;
1469 }
1470#endif
1471 return RC_FRET;
1472}
1473#endif
1474
1475/* wrapper around REG_FRET to return a register by type */
1476static int reg_fret(int t)
1477{
1478#ifdef TCC_TARGET_X86_64
1479 if (t == VT_LDOUBLE) {
1480 return TREG_ST0;
1481 }
1482#endif
1483 return REG_FRET;
1484}
1485
1486#if PTR_SIZE == 4
1487/* expand 64bit on stack in two ints */
1488static void lexpand(void)
1489{
1490 int u, v;
1491 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1492 v = vtop->r & (VT_VALMASK | VT_LVAL);
1493 if (v == VT_CONST) {
1494 vdup();
1495 vtop[0].c.i >>= 32;
1496 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1497 vdup();
1498 vtop[0].c.i += 4;
1499 } else {
1500 gv(RC_INT);
1501 vdup();
1502 vtop[0].r = vtop[-1].r2;
1503 vtop[0].r2 = vtop[-1].r2 = VT_CONST;
1504 }
1505 vtop[0].type.t = vtop[-1].type.t = VT_INT | u;
1506}
1507#endif
1508
1509#ifdef TCC_TARGET_ARM
1510/* expand long long on stack */
1511ST_FUNC void lexpand_nr(void)
1512{
1513 int u,v;
1514
1515 u = vtop->type.t & (VT_DEFSIGN | VT_UNSIGNED);
1516 vdup();
1517 vtop->r2 = VT_CONST;
1518 vtop->type.t = VT_INT | u;
1519 v=vtop[-1].r & (VT_VALMASK | VT_LVAL);
1520 if (v == VT_CONST) {
1521 vtop[-1].c.i = vtop->c.i;
1522 vtop->c.i = vtop->c.i >> 32;
1523 vtop->r = VT_CONST;
1524 } else if (v == (VT_LVAL|VT_CONST) || v == (VT_LVAL|VT_LOCAL)) {
1525 vtop->c.i += 4;
1526 vtop->r = vtop[-1].r;
1527 } else if (v > VT_CONST) {
1528 vtop--;
1529 lexpand();
1530 } else
1531 vtop->r = vtop[-1].r2;
1532 vtop[-1].r2 = VT_CONST;
1533 vtop[-1].type.t = VT_INT | u;
1534}
1535#endif
1536
1537#if PTR_SIZE == 4
1538/* build a long long from two ints */
1539static void lbuild(int t)
1540{
1541 gv2(RC_INT, RC_INT);
1542 vtop[-1].r2 = vtop[0].r;
1543 vtop[-1].type.t = t;
1544 vpop();
1545}
1546#endif
1547
1548/* convert stack entry to register and duplicate its value in another
1549 register */
1550static void gv_dup(void)
1551{
1552 int rc, t, r, r1;
1553 SValue sv;
1554
1555 t = vtop->type.t;
1556#if PTR_SIZE == 4
1557 if ((t & VT_BTYPE) == VT_LLONG) {
1558 if (t & VT_BITFIELD) {
1559 gv(RC_INT);
1560 t = vtop->type.t;
1561 }
1562 lexpand();
1563 gv_dup();
1564 vswap();
1565 vrotb(3);
1566 gv_dup();
1567 vrotb(4);
1568 /* stack: H L L1 H1 */
1569 lbuild(t);
1570 vrotb(3);
1571 vrotb(3);
1572 vswap();
1573 lbuild(t);
1574 vswap();
1575 } else
1576#endif
1577 {
1578 /* duplicate value */
1579 rc = RC_INT;
1580 sv.type.t = VT_INT;
1581 if (is_float(t)) {
1582 rc = RC_FLOAT;
1583#ifdef TCC_TARGET_X86_64
1584 if ((t & VT_BTYPE) == VT_LDOUBLE) {
1585 rc = RC_ST0;
1586 }
1587#endif
1588 sv.type.t = t;
1589 }
1590 r = gv(rc);
1591 r1 = get_reg(rc);
1592 sv.r = r;
1593 sv.c.i = 0;
1594 load(r1, &sv); /* move r to r1 */
1595 vdup();
1596 /* duplicates value */
1597 if (r != r1)
1598 vtop->r = r1;
1599 }
1600}
1601
1602/* Generate value test
1603 *
1604 * Generate a test for any value (jump, comparison and integers) */
1605ST_FUNC int gvtst(int inv, int t)
1606{
1607 int v = vtop->r & VT_VALMASK;
1608 if (v != VT_CMP && v != VT_JMP && v != VT_JMPI) {
1609 vpushi(0);
1610 gen_op(TOK_NE);
1611 }
1612 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1613 /* constant jmp optimization */
1614 if ((vtop->c.i != 0) != inv)
1615 t = gjmp(t);
1616 vtop--;
1617 return t;
1618 }
1619 return gtst(inv, t);
1620}
1621
1622#if PTR_SIZE == 4
1623/* generate CPU independent (unsigned) long long operations */
1624static void gen_opl(int op)
1625{
1626 int t, a, b, op1, c, i;
1627 int func;
1628 unsigned short reg_iret = REG_IRET;
1629 unsigned short reg_lret = REG_LRET;
1630 SValue tmp;
1631
1632 switch(op) {
1633 case '/':
1634 case TOK_PDIV:
1635 func = TOK___divdi3;
1636 goto gen_func;
1637 case TOK_UDIV:
1638 func = TOK___udivdi3;
1639 goto gen_func;
1640 case '%':
1641 func = TOK___moddi3;
1642 goto gen_mod_func;
1643 case TOK_UMOD:
1644 func = TOK___umoddi3;
1645 gen_mod_func:
1646#ifdef TCC_ARM_EABI
1647 reg_iret = TREG_R2;
1648 reg_lret = TREG_R3;
1649#endif
1650 gen_func:
1651 /* call generic long long function */
1652 vpush_global_sym(&func_old_type, func);
1653 vrott(3);
1654 gfunc_call(2);
1655 vpushi(0);
1656 vtop->r = reg_iret;
1657 vtop->r2 = reg_lret;
1658 break;
1659 case '^':
1660 case '&':
1661 case '|':
1662 case '*':
1663 case '+':
1664 case '-':
1665 //pv("gen_opl A",0,2);
1666 t = vtop->type.t;
1667 vswap();
1668 lexpand();
1669 vrotb(3);
1670 lexpand();
1671 /* stack: L1 H1 L2 H2 */
1672 tmp = vtop[0];
1673 vtop[0] = vtop[-3];
1674 vtop[-3] = tmp;
1675 tmp = vtop[-2];
1676 vtop[-2] = vtop[-3];
1677 vtop[-3] = tmp;
1678 vswap();
1679 /* stack: H1 H2 L1 L2 */
1680 //pv("gen_opl B",0,4);
1681 if (op == '*') {
1682 vpushv(vtop - 1);
1683 vpushv(vtop - 1);
1684 gen_op(TOK_UMULL);
1685 lexpand();
1686 /* stack: H1 H2 L1 L2 ML MH */
1687 for(i=0;i<4;i++)
1688 vrotb(6);
1689 /* stack: ML MH H1 H2 L1 L2 */
1690 tmp = vtop[0];
1691 vtop[0] = vtop[-2];
1692 vtop[-2] = tmp;
1693 /* stack: ML MH H1 L2 H2 L1 */
1694 gen_op('*');
1695 vrotb(3);
1696 vrotb(3);
1697 gen_op('*');
1698 /* stack: ML MH M1 M2 */
1699 gen_op('+');
1700 gen_op('+');
1701 } else if (op == '+' || op == '-') {
1702 /* XXX: add non carry method too (for MIPS or alpha) */
1703 if (op == '+')
1704 op1 = TOK_ADDC1;
1705 else
1706 op1 = TOK_SUBC1;
1707 gen_op(op1);
1708 /* stack: H1 H2 (L1 op L2) */
1709 vrotb(3);
1710 vrotb(3);
1711 gen_op(op1 + 1); /* TOK_xxxC2 */
1712 } else {
1713 gen_op(op);
1714 /* stack: H1 H2 (L1 op L2) */
1715 vrotb(3);
1716 vrotb(3);
1717 /* stack: (L1 op L2) H1 H2 */
1718 gen_op(op);
1719 /* stack: (L1 op L2) (H1 op H2) */
1720 }
1721 /* stack: L H */
1722 lbuild(t);
1723 break;
1724 case TOK_SAR:
1725 case TOK_SHR:
1726 case TOK_SHL:
1727 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1728 t = vtop[-1].type.t;
1729 vswap();
1730 lexpand();
1731 vrotb(3);
1732 /* stack: L H shift */
1733 c = (int)vtop->c.i;
1734 /* constant: simpler */
1735 /* NOTE: all comments are for SHL. the other cases are
1736 done by swapping words */
1737 vpop();
1738 if (op != TOK_SHL)
1739 vswap();
1740 if (c >= 32) {
1741 /* stack: L H */
1742 vpop();
1743 if (c > 32) {
1744 vpushi(c - 32);
1745 gen_op(op);
1746 }
1747 if (op != TOK_SAR) {
1748 vpushi(0);
1749 } else {
1750 gv_dup();
1751 vpushi(31);
1752 gen_op(TOK_SAR);
1753 }
1754 vswap();
1755 } else {
1756 vswap();
1757 gv_dup();
1758 /* stack: H L L */
1759 vpushi(c);
1760 gen_op(op);
1761 vswap();
1762 vpushi(32 - c);
1763 if (op == TOK_SHL)
1764 gen_op(TOK_SHR);
1765 else
1766 gen_op(TOK_SHL);
1767 vrotb(3);
1768 /* stack: L L H */
1769 vpushi(c);
1770 if (op == TOK_SHL)
1771 gen_op(TOK_SHL);
1772 else
1773 gen_op(TOK_SHR);
1774 gen_op('|');
1775 }
1776 if (op != TOK_SHL)
1777 vswap();
1778 lbuild(t);
1779 } else {
1780 /* XXX: should provide a faster fallback on x86 ? */
1781 switch(op) {
1782 case TOK_SAR:
1783 func = TOK___ashrdi3;
1784 goto gen_func;
1785 case TOK_SHR:
1786 func = TOK___lshrdi3;
1787 goto gen_func;
1788 case TOK_SHL:
1789 func = TOK___ashldi3;
1790 goto gen_func;
1791 }
1792 }
1793 break;
1794 default:
1795 /* compare operations */
1796 t = vtop->type.t;
1797 vswap();
1798 lexpand();
1799 vrotb(3);
1800 lexpand();
1801 /* stack: L1 H1 L2 H2 */
1802 tmp = vtop[-1];
1803 vtop[-1] = vtop[-2];
1804 vtop[-2] = tmp;
1805 /* stack: L1 L2 H1 H2 */
1806 /* compare high */
1807 op1 = op;
1808 /* when values are equal, we need to compare low words. since
1809 the jump is inverted, we invert the test too. */
1810 if (op1 == TOK_LT)
1811 op1 = TOK_LE;
1812 else if (op1 == TOK_GT)
1813 op1 = TOK_GE;
1814 else if (op1 == TOK_ULT)
1815 op1 = TOK_ULE;
1816 else if (op1 == TOK_UGT)
1817 op1 = TOK_UGE;
1818 a = 0;
1819 b = 0;
1820 gen_op(op1);
1821 if (op == TOK_NE) {
1822 b = gvtst(0, 0);
1823 } else {
1824 a = gvtst(1, 0);
1825 if (op != TOK_EQ) {
1826 /* generate non equal test */
1827 vpushi(TOK_NE);
1828 vtop->r = VT_CMP;
1829 b = gvtst(0, 0);
1830 }
1831 }
1832 /* compare low. Always unsigned */
1833 op1 = op;
1834 if (op1 == TOK_LT)
1835 op1 = TOK_ULT;
1836 else if (op1 == TOK_LE)
1837 op1 = TOK_ULE;
1838 else if (op1 == TOK_GT)
1839 op1 = TOK_UGT;
1840 else if (op1 == TOK_GE)
1841 op1 = TOK_UGE;
1842 gen_op(op1);
1843 a = gvtst(1, a);
1844 gsym(b);
1845 vseti(VT_JMPI, a);
1846 break;
1847 }
1848}
1849#endif
1850
1851static uint64_t gen_opic_sdiv(uint64_t a, uint64_t b)
1852{
1853 uint64_t x = (a >> 63 ? -a : a) / (b >> 63 ? -b : b);
1854 return (a ^ b) >> 63 ? -x : x;
1855}
1856
1857static int gen_opic_lt(uint64_t a, uint64_t b)
1858{
1859 return (a ^ (uint64_t)1 << 63) < (b ^ (uint64_t)1 << 63);
1860}
1861
1862/* handle integer constant optimizations and various machine
1863 independent opt */
1864static void gen_opic(int op)
1865{
1866 SValue *v1 = vtop - 1;
1867 SValue *v2 = vtop;
1868 int t1 = v1->type.t & VT_BTYPE;
1869 int t2 = v2->type.t & VT_BTYPE;
1870 int c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1871 int c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
1872 uint64_t l1 = c1 ? v1->c.i : 0;
1873 uint64_t l2 = c2 ? v2->c.i : 0;
1874 int shm = (t1 == VT_LLONG) ? 63 : 31;
1875
1876 if (t1 != VT_LLONG && (PTR_SIZE != 8 || t1 != VT_PTR))
1877 l1 = ((uint32_t)l1 |
1878 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1879 if (t2 != VT_LLONG && (PTR_SIZE != 8 || t2 != VT_PTR))
1880 l2 = ((uint32_t)l2 |
1881 (v2->type.t & VT_UNSIGNED ? 0 : -(l2 & 0x80000000)));
1882
1883 if (c1 && c2) {
1884 switch(op) {
1885 case '+': l1 += l2; break;
1886 case '-': l1 -= l2; break;
1887 case '&': l1 &= l2; break;
1888 case '^': l1 ^= l2; break;
1889 case '|': l1 |= l2; break;
1890 case '*': l1 *= l2; break;
1891
1892 case TOK_PDIV:
1893 case '/':
1894 case '%':
1895 case TOK_UDIV:
1896 case TOK_UMOD:
1897 /* if division by zero, generate explicit division */
1898 if (l2 == 0) {
1899 if (const_wanted)
1900 tcc_error("division by zero in constant");
1901 goto general_case;
1902 }
1903 switch(op) {
1904 default: l1 = gen_opic_sdiv(l1, l2); break;
1905 case '%': l1 = l1 - l2 * gen_opic_sdiv(l1, l2); break;
1906 case TOK_UDIV: l1 = l1 / l2; break;
1907 case TOK_UMOD: l1 = l1 % l2; break;
1908 }
1909 break;
1910 case TOK_SHL: l1 <<= (l2 & shm); break;
1911 case TOK_SHR: l1 >>= (l2 & shm); break;
1912 case TOK_SAR:
1913 l1 = (l1 >> 63) ? ~(~l1 >> (l2 & shm)) : l1 >> (l2 & shm);
1914 break;
1915 /* tests */
1916 case TOK_ULT: l1 = l1 < l2; break;
1917 case TOK_UGE: l1 = l1 >= l2; break;
1918 case TOK_EQ: l1 = l1 == l2; break;
1919 case TOK_NE: l1 = l1 != l2; break;
1920 case TOK_ULE: l1 = l1 <= l2; break;
1921 case TOK_UGT: l1 = l1 > l2; break;
1922 case TOK_LT: l1 = gen_opic_lt(l1, l2); break;
1923 case TOK_GE: l1 = !gen_opic_lt(l1, l2); break;
1924 case TOK_LE: l1 = !gen_opic_lt(l2, l1); break;
1925 case TOK_GT: l1 = gen_opic_lt(l2, l1); break;
1926 /* logical */
1927 case TOK_LAND: l1 = l1 && l2; break;
1928 case TOK_LOR: l1 = l1 || l2; break;
1929 default:
1930 goto general_case;
1931 }
1932 if (t1 != VT_LLONG && (PTR_SIZE != 8 || t1 != VT_PTR))
1933 l1 = ((uint32_t)l1 |
1934 (v1->type.t & VT_UNSIGNED ? 0 : -(l1 & 0x80000000)));
1935 v1->c.i = l1;
1936 vtop--;
1937 } else {
1938 /* if commutative ops, put c2 as constant */
1939 if (c1 && (op == '+' || op == '&' || op == '^' ||
1940 op == '|' || op == '*')) {
1941 vswap();
1942 c2 = c1; //c = c1, c1 = c2, c2 = c;
1943 l2 = l1; //l = l1, l1 = l2, l2 = l;
1944 }
1945 if (!const_wanted &&
1946 c1 && ((l1 == 0 &&
1947 (op == TOK_SHL || op == TOK_SHR || op == TOK_SAR)) ||
1948 (l1 == -1 && op == TOK_SAR))) {
1949 /* treat (0 << x), (0 >> x) and (-1 >> x) as constant */
1950 vtop--;
1951 } else if (!const_wanted &&
1952 c2 && ((l2 == 0 && (op == '&' || op == '*')) ||
1953 (op == '|' &&
1954 (l2 == -1 || (l2 == 0xFFFFFFFF && t2 != VT_LLONG))) ||
1955 (l2 == 1 && (op == '%' || op == TOK_UMOD)))) {
1956 /* treat (x & 0), (x * 0), (x | -1) and (x % 1) as constant */
1957 if (l2 == 1)
1958 vtop->c.i = 0;
1959 vswap();
1960 vtop--;
1961 } else if (c2 && (((op == '*' || op == '/' || op == TOK_UDIV ||
1962 op == TOK_PDIV) &&
1963 l2 == 1) ||
1964 ((op == '+' || op == '-' || op == '|' || op == '^' ||
1965 op == TOK_SHL || op == TOK_SHR || op == TOK_SAR) &&
1966 l2 == 0) ||
1967 (op == '&' &&
1968 (l2 == -1 || (l2 == 0xFFFFFFFF && t2 != VT_LLONG))))) {
1969 /* filter out NOP operations like x*1, x-0, x&-1... */
1970 vtop--;
1971 } else if (c2 && (op == '*' || op == TOK_PDIV || op == TOK_UDIV)) {
1972 /* try to use shifts instead of muls or divs */
1973 if (l2 > 0 && (l2 & (l2 - 1)) == 0) {
1974 int n = -1;
1975 while (l2) {
1976 l2 >>= 1;
1977 n++;
1978 }
1979 vtop->c.i = n;
1980 if (op == '*')
1981 op = TOK_SHL;
1982 else if (op == TOK_PDIV)
1983 op = TOK_SAR;
1984 else
1985 op = TOK_SHR;
1986 }
1987 goto general_case;
1988 } else if (c2 && (op == '+' || op == '-') &&
1989 (((vtop[-1].r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM))
1990 || (vtop[-1].r & (VT_VALMASK | VT_LVAL)) == VT_LOCAL)) {
1991 /* symbol + constant case */
1992 if (op == '-')
1993 l2 = -l2;
1994 l2 += vtop[-1].c.i;
1995 /* The backends can't always deal with addends to symbols
1996 larger than +-1<<31. Don't construct such. */
1997 if ((int)l2 != l2)
1998 goto general_case;
1999 vtop--;
2000 vtop->c.i = l2;
2001 } else {
2002 general_case:
2003 /* call low level op generator */
2004 if (t1 == VT_LLONG || t2 == VT_LLONG ||
2005 (PTR_SIZE == 8 && (t1 == VT_PTR || t2 == VT_PTR)))
2006 gen_opl(op);
2007 else
2008 gen_opi(op);
2009 }
2010 }
2011}
2012
2013/* generate a floating point operation with constant propagation */
2014static void gen_opif(int op)
2015{
2016 int c1, c2;
2017 SValue *v1, *v2;
2018#if defined _MSC_VER && defined _AMD64_
2019 /* avoid bad optimization with f1 -= f2 for f1:-0.0, f2:0.0 */
2020 volatile
2021#endif
2022 long double f1, f2;
2023
2024 v1 = vtop - 1;
2025 v2 = vtop;
2026 /* currently, we cannot do computations with forward symbols */
2027 c1 = (v1->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
2028 c2 = (v2->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
2029 if (c1 && c2) {
2030 if (v1->type.t == VT_FLOAT) {
2031 f1 = v1->c.f;
2032 f2 = v2->c.f;
2033 } else if (v1->type.t == VT_DOUBLE) {
2034 f1 = v1->c.d;
2035 f2 = v2->c.d;
2036 } else {
2037 f1 = v1->c.ld;
2038 f2 = v2->c.ld;
2039 }
2040
2041 /* NOTE: we only do constant propagation if finite number (not
2042 NaN or infinity) (ANSI spec) */
2043 if (!ieee_finite(f1) || !ieee_finite(f2))
2044 goto general_case;
2045
2046 switch(op) {
2047 case '+': f1 += f2; break;
2048 case '-': f1 -= f2; break;
2049 case '*': f1 *= f2; break;
2050 case '/':
2051 if (f2 == 0.0) {
2052 if (const_wanted)
2053 tcc_error("division by zero in constant");
2054 goto general_case;
2055 }
2056 f1 /= f2;
2057 break;
2058 /* XXX: also handles tests ? */
2059 default:
2060 goto general_case;
2061 }
2062 /* XXX: overflow test ? */
2063 if (v1->type.t == VT_FLOAT) {
2064 v1->c.f = f1;
2065 } else if (v1->type.t == VT_DOUBLE) {
2066 v1->c.d = f1;
2067 } else {
2068 v1->c.ld = f1;
2069 }
2070 vtop--;
2071 } else {
2072 general_case:
2073 gen_opf(op);
2074 }
2075}
2076
2077static int pointed_size(CType *type)
2078{
2079 int align;
2080 return type_size(pointed_type(type), &align);
2081}
2082
2083static void vla_runtime_pointed_size(CType *type)
2084{
2085 int align;
2086 vla_runtime_type_size(pointed_type(type), &align);
2087}
2088
2089static inline int is_null_pointer(SValue *p)
2090{
2091 if ((p->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
2092 return 0;
2093 return ((p->type.t & VT_BTYPE) == VT_INT && (uint32_t)p->c.i == 0) ||
2094 ((p->type.t & VT_BTYPE) == VT_LLONG && p->c.i == 0) ||
2095 ((p->type.t & VT_BTYPE) == VT_PTR &&
2096 (PTR_SIZE == 4 ? (uint32_t)p->c.i == 0 : p->c.i == 0));
2097}
2098
2099static inline int is_integer_btype(int bt)
2100{
2101 return (bt == VT_BYTE || bt == VT_SHORT ||
2102 bt == VT_INT || bt == VT_LLONG);
2103}
2104
2105/* check types for comparison or subtraction of pointers */
2106static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op)
2107{
2108 CType *type1, *type2, tmp_type1, tmp_type2;
2109 int bt1, bt2;
2110
2111 /* null pointers are accepted for all comparisons as gcc */
2112 if (is_null_pointer(p1) || is_null_pointer(p2))
2113 return;
2114 type1 = &p1->type;
2115 type2 = &p2->type;
2116 bt1 = type1->t & VT_BTYPE;
2117 bt2 = type2->t & VT_BTYPE;
2118 /* accept comparison between pointer and integer with a warning */
2119 if ((is_integer_btype(bt1) || is_integer_btype(bt2)) && op != '-') {
2120 if (op != TOK_LOR && op != TOK_LAND )
2121 tcc_warning("comparison between pointer and integer");
2122 return;
2123 }
2124
2125 /* both must be pointers or implicit function pointers */
2126 if (bt1 == VT_PTR) {
2127 type1 = pointed_type(type1);
2128 } else if (bt1 != VT_FUNC)
2129 goto invalid_operands;
2130
2131 if (bt2 == VT_PTR) {
2132 type2 = pointed_type(type2);
2133 } else if (bt2 != VT_FUNC) {
2134 invalid_operands:
2135 tcc_error("invalid operands to binary %s", get_tok_str(op, NULL));
2136 }
2137 if ((type1->t & VT_BTYPE) == VT_VOID ||
2138 (type2->t & VT_BTYPE) == VT_VOID)
2139 return;
2140 tmp_type1 = *type1;
2141 tmp_type2 = *type2;
2142 tmp_type1.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2143 tmp_type2.t &= ~(VT_DEFSIGN | VT_UNSIGNED | VT_CONSTANT | VT_VOLATILE);
2144 if (!is_compatible_types(&tmp_type1, &tmp_type2)) {
2145 /* gcc-like error if '-' is used */
2146 if (op == '-')
2147 goto invalid_operands;
2148 else
2149 tcc_warning("comparison of distinct pointer types lacks a cast");
2150 }
2151}
2152
2153/* generic gen_op: handles types problems */
2154ST_FUNC void gen_op(int op)
2155{
2156 int u, t1, t2, bt1, bt2, t;
2157 CType type1;
2158
2159redo:
2160 t1 = vtop[-1].type.t;
2161 t2 = vtop[0].type.t;
2162 bt1 = t1 & VT_BTYPE;
2163 bt2 = t2 & VT_BTYPE;
2164
2165 if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
2166 tcc_error("operation on a struct");
2167 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
2168 if (bt2 == VT_FUNC) {
2169 mk_pointer(&vtop->type);
2170 gaddrof();
2171 }
2172 if (bt1 == VT_FUNC) {
2173 vswap();
2174 mk_pointer(&vtop->type);
2175 gaddrof();
2176 vswap();
2177 }
2178 goto redo;
2179 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
2180 /* at least one operand is a pointer */
2181 /* relational op: must be both pointers */
2182 if (op >= TOK_ULT && op <= TOK_LOR) {
2183 check_comparison_pointer_types(vtop - 1, vtop, op);
2184 /* pointers are handled are unsigned */
2185#if PTR_SIZE == 8
2186 t = VT_LLONG | VT_UNSIGNED;
2187#else
2188 t = VT_INT | VT_UNSIGNED;
2189#endif
2190 goto std_op;
2191 }
2192 /* if both pointers, then it must be the '-' op */
2193 if (bt1 == VT_PTR && bt2 == VT_PTR) {
2194 if (op != '-')
2195 tcc_error("cannot use pointers here");
2196 check_comparison_pointer_types(vtop - 1, vtop, op);
2197 /* XXX: check that types are compatible */
2198 if (vtop[-1].type.t & VT_VLA) {
2199 vla_runtime_pointed_size(&vtop[-1].type);
2200 } else {
2201 vpushi(pointed_size(&vtop[-1].type));
2202 }
2203 vrott(3);
2204 gen_opic(op);
2205 vtop->type.t = ptrdiff_type.t;
2206 vswap();
2207 gen_op(TOK_PDIV);
2208 } else {
2209 /* exactly one pointer : must be '+' or '-'. */
2210 if (op != '-' && op != '+')
2211 tcc_error("cannot use pointers here");
2212 /* Put pointer as first operand */
2213 if (bt2 == VT_PTR) {
2214 vswap();
2215 t = t1, t1 = t2, t2 = t;
2216 }
2217#if PTR_SIZE == 4
2218 if ((vtop[0].type.t & VT_BTYPE) == VT_LLONG)
2219 /* XXX: truncate here because gen_opl can't handle ptr + long long */
2220 gen_cast_s(VT_INT);
2221#endif
2222 type1 = vtop[-1].type;
2223 type1.t &= ~VT_ARRAY;
2224 if (vtop[-1].type.t & VT_VLA)
2225 vla_runtime_pointed_size(&vtop[-1].type);
2226 else {
2227 u = pointed_size(&vtop[-1].type);
2228 if (u < 0)
2229 tcc_error("unknown array element size");
2230#if PTR_SIZE == 8
2231 vpushll(u);
2232#else
2233 /* XXX: cast to int ? (long long case) */
2234 vpushi(u);
2235#endif
2236 }
2237 gen_op('*');
2238#if 0
2239/* #ifdef CONFIG_TCC_BCHECK
2240 The main reason to removing this code:
2241 #include <stdio.h>
2242 int main ()
2243 {
2244 int v[10];
2245 int i = 10;
2246 int j = 9;
2247 fprintf(stderr, "v+i-j = %p\n", v+i-j);
2248 fprintf(stderr, "v+(i-j) = %p\n", v+(i-j));
2249 }
2250 When this code is on. then the output looks like
2251 v+i-j = 0xfffffffe
2252 v+(i-j) = 0xbff84000
2253 */
2254 /* if evaluating constant expression, no code should be
2255 generated, so no bound check */
2256 if (tcc_state->do_bounds_check && !const_wanted) {
2257 /* if bounded pointers, we generate a special code to
2258 test bounds */
2259 if (op == '-') {
2260 vpushi(0);
2261 vswap();
2262 gen_op('-');
2263 }
2264 gen_bounded_ptr_add();
2265 } else
2266#endif
2267 {
2268 gen_opic(op);
2269 }
2270 /* put again type if gen_opic() swaped operands */
2271 vtop->type = type1;
2272 }
2273 } else if (is_float(bt1) || is_float(bt2)) {
2274 /* compute bigger type and do implicit casts */
2275 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
2276 t = VT_LDOUBLE;
2277 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
2278 t = VT_DOUBLE;
2279 } else {
2280 t = VT_FLOAT;
2281 }
2282 /* floats can only be used for a few operations */
2283 if (op != '+' && op != '-' && op != '*' && op != '/' &&
2284 (op < TOK_ULT || op > TOK_GT))
2285 tcc_error("invalid operands for binary operation");
2286 goto std_op;
2287 } else if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL) {
2288 t = bt1 == VT_LLONG ? VT_LLONG : VT_INT;
2289 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (t | VT_UNSIGNED))
2290 t |= VT_UNSIGNED;
2291 t |= (VT_LONG & t1);
2292 goto std_op;
2293 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
2294 /* cast to biggest op */
2295 t = VT_LLONG | VT_LONG;
2296 if (bt1 == VT_LLONG)
2297 t &= t1;
2298 if (bt2 == VT_LLONG)
2299 t &= t2;
2300 /* convert to unsigned if it does not fit in a long long */
2301 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED) ||
2302 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED))
2303 t |= VT_UNSIGNED;
2304 goto std_op;
2305 } else {
2306 /* integer operations */
2307 t = VT_INT | (VT_LONG & (t1 | t2));
2308 /* convert to unsigned if it does not fit in an integer */
2309 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED) ||
2310 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED))
2311 t |= VT_UNSIGNED;
2312 std_op:
2313 /* XXX: currently, some unsigned operations are explicit, so
2314 we modify them here */
2315 if (t & VT_UNSIGNED) {
2316 if (op == TOK_SAR)
2317 op = TOK_SHR;
2318 else if (op == '/')
2319 op = TOK_UDIV;
2320 else if (op == '%')
2321 op = TOK_UMOD;
2322 else if (op == TOK_LT)
2323 op = TOK_ULT;
2324 else if (op == TOK_GT)
2325 op = TOK_UGT;
2326 else if (op == TOK_LE)
2327 op = TOK_ULE;
2328 else if (op == TOK_GE)
2329 op = TOK_UGE;
2330 }
2331 vswap();
2332 type1.t = t;
2333 type1.ref = NULL;
2334 gen_cast(&type1);
2335 vswap();
2336 /* special case for shifts and long long: we keep the shift as
2337 an integer */
2338 if (op == TOK_SHR || op == TOK_SAR || op == TOK_SHL)
2339 type1.t = VT_INT;
2340 gen_cast(&type1);
2341 if (is_float(t))
2342 gen_opif(op);
2343 else
2344 gen_opic(op);
2345 if (op >= TOK_ULT && op <= TOK_GT) {
2346 /* relational op: the result is an int */
2347 vtop->type.t = VT_INT;
2348 } else {
2349 vtop->type.t = t;
2350 }
2351 }
2352 // Make sure that we have converted to an rvalue:
2353 if (vtop->r & VT_LVAL)
2354 gv(is_float(vtop->type.t & VT_BTYPE) ? RC_FLOAT : RC_INT);
2355}
2356
2357#ifndef TCC_TARGET_ARM
2358/* generic itof for unsigned long long case */
2359static void gen_cvt_itof1(int t)
2360{
2361#ifdef TCC_TARGET_ARM64
2362 gen_cvt_itof(t);
2363#else
2364 if ((vtop->type.t & (VT_BTYPE | VT_UNSIGNED)) ==
2365 (VT_LLONG | VT_UNSIGNED)) {
2366
2367 if (t == VT_FLOAT)
2368 vpush_global_sym(&func_old_type, TOK___floatundisf);
2369#if LDOUBLE_SIZE != 8
2370 else if (t == VT_LDOUBLE)
2371 vpush_global_sym(&func_old_type, TOK___floatundixf);
2372#endif
2373 else
2374 vpush_global_sym(&func_old_type, TOK___floatundidf);
2375 vrott(2);
2376 gfunc_call(1);
2377 vpushi(0);
2378 vtop->r = reg_fret(t);
2379 } else {
2380 gen_cvt_itof(t);
2381 }
2382#endif
2383}
2384#endif
2385
2386/* generic ftoi for unsigned long long case */
2387static void gen_cvt_ftoi1(int t)
2388{
2389#ifdef TCC_TARGET_ARM64
2390 gen_cvt_ftoi(t);
2391#else
2392 int st;
2393
2394 if (t == (VT_LLONG | VT_UNSIGNED)) {
2395 /* not handled natively */
2396 st = vtop->type.t & VT_BTYPE;
2397 if (st == VT_FLOAT)
2398 vpush_global_sym(&func_old_type, TOK___fixunssfdi);
2399#if LDOUBLE_SIZE != 8
2400 else if (st == VT_LDOUBLE)
2401 vpush_global_sym(&func_old_type, TOK___fixunsxfdi);
2402#endif
2403 else
2404 vpush_global_sym(&func_old_type, TOK___fixunsdfdi);
2405 vrott(2);
2406 gfunc_call(1);
2407 vpushi(0);
2408 vtop->r = REG_IRET;
2409 vtop->r2 = REG_LRET;
2410 } else {
2411 gen_cvt_ftoi(t);
2412 }
2413#endif
2414}
2415
2416/* force char or short cast */
2417static void force_charshort_cast(int t)
2418{
2419 int bits, dbt;
2420
2421 /* cannot cast static initializers */
2422 if (STATIC_DATA_WANTED)
2423 return;
2424
2425 dbt = t & VT_BTYPE;
2426 /* XXX: add optimization if lvalue : just change type and offset */
2427 if (dbt == VT_BYTE)
2428 bits = 8;
2429 else
2430 bits = 16;
2431 if (t & VT_UNSIGNED) {
2432 vpushi((1 << bits) - 1);
2433 gen_op('&');
2434 } else {
2435 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
2436 bits = 64 - bits;
2437 else
2438 bits = 32 - bits;
2439 vpushi(bits);
2440 gen_op(TOK_SHL);
2441 /* result must be signed or the SAR is converted to an SHL
2442 This was not the case when "t" was a signed short
2443 and the last value on the stack was an unsigned int */
2444 vtop->type.t &= ~VT_UNSIGNED;
2445 vpushi(bits);
2446 gen_op(TOK_SAR);
2447 }
2448}
2449
2450/* cast 'vtop' to 'type'. Casting to bitfields is forbidden. */
2451static void gen_cast_s(int t)
2452{
2453 CType type;
2454 type.t = t;
2455 type.ref = NULL;
2456 gen_cast(&type);
2457}
2458
2459static void gen_cast(CType *type)
2460{
2461 int sbt, dbt, sf, df, c, p;
2462
2463 /* special delayed cast for char/short */
2464 /* XXX: in some cases (multiple cascaded casts), it may still
2465 be incorrect */
2466 if (vtop->r & VT_MUSTCAST) {
2467 vtop->r &= ~VT_MUSTCAST;
2468 force_charshort_cast(vtop->type.t);
2469 }
2470
2471 /* bitfields first get cast to ints */
2472 if (vtop->type.t & VT_BITFIELD) {
2473 gv(RC_INT);
2474 }
2475
2476 dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
2477 sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
2478
2479 if (sbt != dbt) {
2480 sf = is_float(sbt);
2481 df = is_float(dbt);
2482 c = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
2483 p = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == (VT_CONST | VT_SYM);
2484#if !defined TCC_IS_NATIVE && !defined TCC_IS_NATIVE_387
2485 c &= dbt != VT_LDOUBLE;
2486#endif
2487 if (c) {
2488 /* constant case: we can do it now */
2489 /* XXX: in ISOC, cannot do it if error in convert */
2490 if (sbt == VT_FLOAT)
2491 vtop->c.ld = vtop->c.f;
2492 else if (sbt == VT_DOUBLE)
2493 vtop->c.ld = vtop->c.d;
2494
2495 if (df) {
2496 if ((sbt & VT_BTYPE) == VT_LLONG) {
2497 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 63))
2498 vtop->c.ld = vtop->c.i;
2499 else
2500 vtop->c.ld = -(long double)-vtop->c.i;
2501 } else if(!sf) {
2502 if ((sbt & VT_UNSIGNED) || !(vtop->c.i >> 31))
2503 vtop->c.ld = (uint32_t)vtop->c.i;
2504 else
2505 vtop->c.ld = -(long double)-(uint32_t)vtop->c.i;
2506 }
2507
2508 if (dbt == VT_FLOAT)
2509 vtop->c.f = (float)vtop->c.ld;
2510 else if (dbt == VT_DOUBLE)
2511 vtop->c.d = (double)vtop->c.ld;
2512 } else if (sf && dbt == (VT_LLONG|VT_UNSIGNED)) {
2513 vtop->c.i = vtop->c.ld;
2514 } else if (sf && dbt == VT_BOOL) {
2515 vtop->c.i = (vtop->c.ld != 0);
2516 } else {
2517 if(sf)
2518 vtop->c.i = vtop->c.ld;
2519 else if (sbt == (VT_LLONG|VT_UNSIGNED))
2520 ;
2521 else if (sbt & VT_UNSIGNED)
2522 vtop->c.i = (uint32_t)vtop->c.i;
2523#if PTR_SIZE == 8
2524 else if (sbt == VT_PTR)
2525 ;
2526#endif
2527 else if (sbt != VT_LLONG)
2528 vtop->c.i = ((uint32_t)vtop->c.i |
2529 -(vtop->c.i & 0x80000000));
2530
2531 if (dbt == (VT_LLONG|VT_UNSIGNED))
2532 ;
2533 else if (dbt == VT_BOOL)
2534 vtop->c.i = (vtop->c.i != 0);
2535#if PTR_SIZE == 8
2536 else if (dbt == VT_PTR)
2537 ;
2538#endif
2539 else if (dbt != VT_LLONG) {
2540 uint32_t m = ((dbt & VT_BTYPE) == VT_BYTE ? 0xff :
2541 (dbt & VT_BTYPE) == VT_SHORT ? 0xffff :
2542 0xffffffff);
2543 vtop->c.i &= m;
2544 if (!(dbt & VT_UNSIGNED))
2545 vtop->c.i |= -(vtop->c.i & ((m >> 1) + 1));
2546 }
2547 }
2548 } else if (p && dbt == VT_BOOL) {
2549 vtop->r = VT_CONST;
2550 vtop->c.i = 1;
2551 } else {
2552 /* non constant case: generate code */
2553 if (sf && df) {
2554 /* convert from fp to fp */
2555 gen_cvt_ftof(dbt);
2556 } else if (df) {
2557 /* convert int to fp */
2558 gen_cvt_itof1(dbt);
2559 } else if (sf) {
2560 /* convert fp to int */
2561 if (dbt == VT_BOOL) {
2562 vpushi(0);
2563 gen_op(TOK_NE);
2564 } else {
2565 /* we handle char/short/etc... with generic code */
2566 if (dbt != (VT_INT | VT_UNSIGNED) &&
2567 dbt != (VT_LLONG | VT_UNSIGNED) &&
2568 dbt != VT_LLONG)
2569 dbt = VT_INT;
2570 gen_cvt_ftoi1(dbt);
2571 if (dbt == VT_INT && (type->t & (VT_BTYPE | VT_UNSIGNED)) != dbt) {
2572 /* additional cast for char/short... */
2573 vtop->type.t = dbt;
2574 gen_cast(type);
2575 }
2576 }
2577#if PTR_SIZE == 4
2578 } else if ((dbt & VT_BTYPE) == VT_LLONG) {
2579 if ((sbt & VT_BTYPE) != VT_LLONG) {
2580 /* scalar to long long */
2581 /* machine independent conversion */
2582 gv(RC_INT);
2583 /* generate high word */
2584 if (sbt == (VT_INT | VT_UNSIGNED)) {
2585 vpushi(0);
2586 gv(RC_INT);
2587 } else {
2588 if (sbt == VT_PTR) {
2589 /* cast from pointer to int before we apply
2590 shift operation, which pointers don't support*/
2591 gen_cast_s(VT_INT);
2592 }
2593 gv_dup();
2594 vpushi(31);
2595 gen_op(TOK_SAR);
2596 }
2597 /* patch second register */
2598 vtop[-1].r2 = vtop->r;
2599 vpop();
2600 }
2601#else
2602 } else if ((dbt & VT_BTYPE) == VT_LLONG ||
2603 (dbt & VT_BTYPE) == VT_PTR ||
2604 (dbt & VT_BTYPE) == VT_FUNC) {
2605 if ((sbt & VT_BTYPE) != VT_LLONG &&
2606 (sbt & VT_BTYPE) != VT_PTR &&
2607 (sbt & VT_BTYPE) != VT_FUNC) {
2608 /* need to convert from 32bit to 64bit */
2609 gv(RC_INT);
2610 if (sbt != (VT_INT | VT_UNSIGNED)) {
2611#if defined(TCC_TARGET_ARM64)
2612 gen_cvt_sxtw();
2613#elif defined(TCC_TARGET_X86_64)
2614 int r = gv(RC_INT);
2615 /* x86_64 specific: movslq */
2616 o(0x6348);
2617 o(0xc0 + (REG_VALUE(r) << 3) + REG_VALUE(r));
2618#else
2619#error
2620#endif
2621 }
2622 }
2623#endif
2624 } else if (dbt == VT_BOOL) {
2625 /* scalar to bool */
2626 vpushi(0);
2627 gen_op(TOK_NE);
2628 } else if ((dbt & VT_BTYPE) == VT_BYTE ||
2629 (dbt & VT_BTYPE) == VT_SHORT) {
2630 if (sbt == VT_PTR) {
2631 vtop->type.t = VT_INT;
2632 tcc_warning("nonportable conversion from pointer to char/short");
2633 }
2634 force_charshort_cast(dbt);
2635#if PTR_SIZE == 4
2636 } else if ((dbt & VT_BTYPE) == VT_INT) {
2637 /* scalar to int */
2638 if ((sbt & VT_BTYPE) == VT_LLONG) {
2639 /* from long long: just take low order word */
2640 lexpand();
2641 vpop();
2642 }
2643 /* if lvalue and single word type, nothing to do because
2644 the lvalue already contains the real type size (see
2645 VT_LVAL_xxx constants) */
2646#endif
2647 }
2648 }
2649 } else if ((dbt & VT_BTYPE) == VT_PTR && !(vtop->r & VT_LVAL)) {
2650 /* if we are casting between pointer types,
2651 we must update the VT_LVAL_xxx size */
2652 vtop->r = (vtop->r & ~VT_LVAL_TYPE)
2653 | (lvalue_type(type->ref->type.t) & VT_LVAL_TYPE);
2654 }
2655 vtop->type = *type;
2656}
2657
2658/* return type size as known at compile time. Put alignment at 'a' */
2659ST_FUNC int type_size(CType *type, int *a)
2660{
2661 Sym *s;
2662 int bt;
2663
2664 bt = type->t & VT_BTYPE;
2665 if (bt == VT_STRUCT) {
2666 /* struct/union */
2667 s = type->ref;
2668 *a = s->r;
2669 return s->c;
2670 } else if (bt == VT_PTR) {
2671 if (type->t & VT_ARRAY) {
2672 int ts;
2673
2674 s = type->ref;
2675 ts = type_size(&s->type, a);
2676
2677 if (ts < 0 && s->c < 0)
2678 ts = -ts;
2679
2680 return ts * s->c;
2681 } else {
2682 *a = PTR_SIZE;
2683 return PTR_SIZE;
2684 }
2685 } else if (IS_ENUM(type->t) && type->ref->c == -1) {
2686 return -1; /* incomplete enum */
2687 } else if (bt == VT_LDOUBLE) {
2688 *a = LDOUBLE_ALIGN;
2689 return LDOUBLE_SIZE;
2690 } else if (bt == VT_DOUBLE || bt == VT_LLONG) {
2691#ifdef TCC_TARGET_I386
2692#ifdef TCC_TARGET_PE
2693 *a = 8;
2694#else
2695 *a = 4;
2696#endif
2697#elif defined(TCC_TARGET_ARM)
2698#ifdef TCC_ARM_EABI
2699 *a = 8;
2700#else
2701 *a = 4;
2702#endif
2703#else
2704 *a = 8;
2705#endif
2706 return 8;
2707 } else if (bt == VT_INT || bt == VT_FLOAT) {
2708 *a = 4;
2709 return 4;
2710 } else if (bt == VT_SHORT) {
2711 *a = 2;
2712 return 2;
2713 } else if (bt == VT_QLONG || bt == VT_QFLOAT) {
2714 *a = 8;
2715 return 16;
2716 } else {
2717 /* char, void, function, _Bool */
2718 *a = 1;
2719 return 1;
2720 }
2721}
2722
2723/* push type size as known at runtime time on top of value stack. Put
2724 alignment at 'a' */
2725ST_FUNC void vla_runtime_type_size(CType *type, int *a)
2726{
2727 if (type->t & VT_VLA) {
2728 type_size(&type->ref->type, a);
2729 vset(&int_type, VT_LOCAL|VT_LVAL, type->ref->c);
2730 } else {
2731 vpushi(type_size(type, a));
2732 }
2733}
2734
2735static void vla_sp_restore(void) {
2736 if (vlas_in_scope) {
2737 gen_vla_sp_restore(vla_sp_loc);
2738 }
2739}
2740
2741static void vla_sp_restore_root(void) {
2742 if (vlas_in_scope) {
2743 gen_vla_sp_restore(vla_sp_root_loc);
2744 }
2745}
2746
2747/* return the pointed type of t */
2748static inline CType *pointed_type(CType *type)
2749{
2750 return &type->ref->type;
2751}
2752
2753/* modify type so that its it is a pointer to type. */
2754ST_FUNC void mk_pointer(CType *type)
2755{
2756 Sym *s;
2757 s = sym_push(SYM_FIELD, type, 0, -1);
2758 type->t = VT_PTR | (type->t & VT_STORAGE);
2759 type->ref = s;
2760}
2761
2762/* compare function types. OLD functions match any new functions */
2763static int is_compatible_func(CType *type1, CType *type2)
2764{
2765 Sym *s1, *s2;
2766
2767 s1 = type1->ref;
2768 s2 = type2->ref;
2769 if (!is_compatible_types(&s1->type, &s2->type))
2770 return 0;
2771 /* check func_call */
2772 if (s1->f.func_call != s2->f.func_call)
2773 return 0;
2774 /* XXX: not complete */
2775 if (s1->f.func_type == FUNC_OLD || s2->f.func_type == FUNC_OLD)
2776 return 1;
2777 if (s1->f.func_type != s2->f.func_type)
2778 return 0;
2779 while (s1 != NULL) {
2780 if (s2 == NULL)
2781 return 0;
2782 if (!is_compatible_unqualified_types(&s1->type, &s2->type))
2783 return 0;
2784 s1 = s1->next;
2785 s2 = s2->next;
2786 }
2787 if (s2)
2788 return 0;
2789 return 1;
2790}
2791
2792/* return true if type1 and type2 are the same. If unqualified is
2793 true, qualifiers on the types are ignored.
2794
2795 - enums are not checked as gcc __builtin_types_compatible_p ()
2796 */
2797static int compare_types(CType *type1, CType *type2, int unqualified)
2798{
2799 int bt1, t1, t2;
2800
2801 t1 = type1->t & VT_TYPE;
2802 t2 = type2->t & VT_TYPE;
2803 if (unqualified) {
2804 /* strip qualifiers before comparing */
2805 t1 &= ~(VT_CONSTANT | VT_VOLATILE);
2806 t2 &= ~(VT_CONSTANT | VT_VOLATILE);
2807 }
2808
2809 /* Default Vs explicit signedness only matters for char */
2810 if ((t1 & VT_BTYPE) != VT_BYTE) {
2811 t1 &= ~VT_DEFSIGN;
2812 t2 &= ~VT_DEFSIGN;
2813 }
2814 /* XXX: bitfields ? */
2815 if (t1 != t2)
2816 return 0;
2817 /* test more complicated cases */
2818 bt1 = t1 & VT_BTYPE;
2819 if (bt1 == VT_PTR) {
2820 type1 = pointed_type(type1);
2821 type2 = pointed_type(type2);
2822 return is_compatible_types(type1, type2);
2823 } else if (bt1 == VT_STRUCT) {
2824 return (type1->ref == type2->ref);
2825 } else if (bt1 == VT_FUNC) {
2826 return is_compatible_func(type1, type2);
2827 } else {
2828 return 1;
2829 }
2830}
2831
2832/* return true if type1 and type2 are exactly the same (including
2833 qualifiers).
2834*/
2835static int is_compatible_types(CType *type1, CType *type2)
2836{
2837 return compare_types(type1,type2,0);
2838}
2839
2840/* return true if type1 and type2 are the same (ignoring qualifiers).
2841*/
2842static int is_compatible_unqualified_types(CType *type1, CType *type2)
2843{
2844 return compare_types(type1,type2,1);
2845}
2846
2847/* print a type. If 'varstr' is not NULL, then the variable is also
2848 printed in the type */
2849/* XXX: union */
2850/* XXX: add array and function pointers */
2851static void type_to_str(char *buf, int buf_size,
2852 CType *type, const char *varstr)
2853{
2854 int bt, v, t;
2855 Sym *s, *sa;
2856 char buf1[256];
2857 const char *tstr;
2858
2859 t = type->t;
2860 bt = t & VT_BTYPE;
2861 buf[0] = '\0';
2862
2863 if (t & VT_EXTERN)
2864 pstrcat(buf, buf_size, "extern ");
2865 if (t & VT_STATIC)
2866 pstrcat(buf, buf_size, "static ");
2867 if (t & VT_TYPEDEF)
2868 pstrcat(buf, buf_size, "typedef ");
2869 if (t & VT_INLINE)
2870 pstrcat(buf, buf_size, "inline ");
2871 if (t & VT_VOLATILE)
2872 pstrcat(buf, buf_size, "volatile ");
2873 if (t & VT_CONSTANT)
2874 pstrcat(buf, buf_size, "const ");
2875
2876 if (((t & VT_DEFSIGN) && bt == VT_BYTE)
2877 || ((t & VT_UNSIGNED)
2878 && (bt == VT_SHORT || bt == VT_INT || bt == VT_LLONG)
2879 && !IS_ENUM(t)
2880 ))
2881 pstrcat(buf, buf_size, (t & VT_UNSIGNED) ? "unsigned " : "signed ");
2882
2883 buf_size -= strlen(buf);
2884 buf += strlen(buf);
2885
2886 switch(bt) {
2887 case VT_VOID:
2888 tstr = "void";
2889 goto add_tstr;
2890 case VT_BOOL:
2891 tstr = "_Bool";
2892 goto add_tstr;
2893 case VT_BYTE:
2894 tstr = "char";
2895 goto add_tstr;
2896 case VT_SHORT:
2897 tstr = "short";
2898 goto add_tstr;
2899 case VT_INT:
2900 tstr = "int";
2901 goto maybe_long;
2902 case VT_LLONG:
2903 tstr = "long long";
2904 maybe_long:
2905 if (t & VT_LONG)
2906 tstr = "long";
2907 if (!IS_ENUM(t))
2908 goto add_tstr;
2909 tstr = "enum ";
2910 goto tstruct;
2911 case VT_FLOAT:
2912 tstr = "float";
2913 goto add_tstr;
2914 case VT_DOUBLE:
2915 tstr = "double";
2916 goto add_tstr;
2917 case VT_LDOUBLE:
2918 tstr = "long double";
2919 add_tstr:
2920 pstrcat(buf, buf_size, tstr);
2921 break;
2922 case VT_STRUCT:
2923 tstr = "struct ";
2924 if (IS_UNION(t))
2925 tstr = "union ";
2926 tstruct:
2927 pstrcat(buf, buf_size, tstr);
2928 v = type->ref->v & ~SYM_STRUCT;
2929 if (v >= SYM_FIRST_ANOM)
2930 pstrcat(buf, buf_size, "<anonymous>");
2931 else
2932 pstrcat(buf, buf_size, get_tok_str(v, NULL));
2933 break;
2934 case VT_FUNC:
2935 s = type->ref;
2936 type_to_str(buf, buf_size, &s->type, varstr);
2937 pstrcat(buf, buf_size, "(");
2938 sa = s->next;
2939 while (sa != NULL) {
2940 type_to_str(buf1, sizeof(buf1), &sa->type, NULL);
2941 pstrcat(buf, buf_size, buf1);
2942 sa = sa->next;
2943 if (sa)
2944 pstrcat(buf, buf_size, ", ");
2945 }
2946 pstrcat(buf, buf_size, ")");
2947 goto no_var;
2948 case VT_PTR:
2949 s = type->ref;
2950 if (t & VT_ARRAY) {
2951 snprintf(buf1, sizeof(buf1), "%s[%d]", varstr ? varstr : "", s->c);
2952 type_to_str(buf, buf_size, &s->type, buf1);
2953 goto no_var;
2954 }
2955 pstrcpy(buf1, sizeof(buf1), "*");
2956 if (t & VT_CONSTANT)
2957 pstrcat(buf1, buf_size, "const ");
2958 if (t & VT_VOLATILE)
2959 pstrcat(buf1, buf_size, "volatile ");
2960 if (varstr)
2961 pstrcat(buf1, sizeof(buf1), varstr);
2962 type_to_str(buf, buf_size, &s->type, buf1);
2963 goto no_var;
2964 }
2965 if (varstr) {
2966 pstrcat(buf, buf_size, " ");
2967 pstrcat(buf, buf_size, varstr);
2968 }
2969 no_var: ;
2970}
2971
2972/* verify type compatibility to store vtop in 'dt' type, and generate
2973 casts if needed. */
2974static void gen_assign_cast(CType *dt)
2975{
2976 CType *st, *type1, *type2;
2977 char buf1[256], buf2[256];
2978 int dbt, sbt;
2979
2980 st = &vtop->type; /* source type */
2981 dbt = dt->t & VT_BTYPE;
2982 sbt = st->t & VT_BTYPE;
2983 if (sbt == VT_VOID || dbt == VT_VOID) {
2984 if (sbt == VT_VOID && dbt == VT_VOID)
2985 ; /*
2986 It is Ok if both are void
2987 A test program:
2988 void func1() {}
2989 void func2() {
2990 return func1();
2991 }
2992 gcc accepts this program
2993 */
2994 else
2995 tcc_error("cannot cast from/to void");
2996 }
2997 if (dt->t & VT_CONSTANT)
2998 tcc_warning("assignment of read-only location");
2999 switch(dbt) {
3000 case VT_PTR:
3001 /* special cases for pointers */
3002 /* '0' can also be a pointer */
3003 if (is_null_pointer(vtop))
3004 goto type_ok;
3005 /* accept implicit pointer to integer cast with warning */
3006 if (is_integer_btype(sbt)) {
3007 tcc_warning("assignment makes pointer from integer without a cast");
3008 goto type_ok;
3009 }
3010 type1 = pointed_type(dt);
3011 /* a function is implicitly a function pointer */
3012 if (sbt == VT_FUNC) {
3013 if ((type1->t & VT_BTYPE) != VT_VOID &&
3014 !is_compatible_types(pointed_type(dt), st))
3015 tcc_warning("assignment from incompatible pointer type");
3016 goto type_ok;
3017 }
3018 if (sbt != VT_PTR)
3019 goto error;
3020 type2 = pointed_type(st);
3021 if ((type1->t & VT_BTYPE) == VT_VOID ||
3022 (type2->t & VT_BTYPE) == VT_VOID) {
3023 /* void * can match anything */
3024 } else {
3025 //printf("types %08x %08x\n", type1->t, type2->t);
3026 /* exact type match, except for qualifiers */
3027 if (!is_compatible_unqualified_types(type1, type2)) {
3028 /* Like GCC don't warn by default for merely changes
3029 in pointer target signedness. Do warn for different
3030 base types, though, in particular for unsigned enums
3031 and signed int targets. */
3032 if ((type1->t & (VT_BTYPE|VT_LONG)) != (type2->t & (VT_BTYPE|VT_LONG))
3033 || IS_ENUM(type1->t) || IS_ENUM(type2->t)
3034 )
3035 tcc_warning("assignment from incompatible pointer type");
3036 }
3037 }
3038 /* check const and volatile */
3039 if ((!(type1->t & VT_CONSTANT) && (type2->t & VT_CONSTANT)) ||
3040 (!(type1->t & VT_VOLATILE) && (type2->t & VT_VOLATILE)))
3041 tcc_warning("assignment discards qualifiers from pointer target type");
3042 break;
3043 case VT_BYTE:
3044 case VT_SHORT:
3045 case VT_INT:
3046 case VT_LLONG:
3047 if (sbt == VT_PTR || sbt == VT_FUNC) {
3048 tcc_warning("assignment makes integer from pointer without a cast");
3049 } else if (sbt == VT_STRUCT) {
3050 goto case_VT_STRUCT;
3051 }
3052 /* XXX: more tests */
3053 break;
3054 case VT_STRUCT:
3055 case_VT_STRUCT:
3056 if (!is_compatible_unqualified_types(dt, st)) {
3057 error:
3058 type_to_str(buf1, sizeof(buf1), st, NULL);
3059 type_to_str(buf2, sizeof(buf2), dt, NULL);
3060 tcc_error("cannot cast '%s' to '%s'", buf1, buf2);
3061 }
3062 break;
3063 }
3064 type_ok:
3065 gen_cast(dt);
3066}
3067
3068/* store vtop in lvalue pushed on stack */
3069ST_FUNC void vstore(void)
3070{
3071 int sbt, dbt, ft, r, t, size, align, bit_size, bit_pos, rc, delayed_cast;
3072
3073 ft = vtop[-1].type.t;
3074 sbt = vtop->type.t & VT_BTYPE;
3075 dbt = ft & VT_BTYPE;
3076 if ((((sbt == VT_INT || sbt == VT_SHORT) && dbt == VT_BYTE) ||
3077 (sbt == VT_INT && dbt == VT_SHORT))
3078 && !(vtop->type.t & VT_BITFIELD)) {
3079 /* optimize char/short casts */
3080 delayed_cast = VT_MUSTCAST;
3081 vtop->type.t = ft & VT_TYPE;
3082 /* XXX: factorize */
3083 if (ft & VT_CONSTANT)
3084 tcc_warning("assignment of read-only location");
3085 } else {
3086 delayed_cast = 0;
3087 if (!(ft & VT_BITFIELD))
3088 gen_assign_cast(&vtop[-1].type);
3089 }
3090
3091 if (sbt == VT_STRUCT) {
3092 /* if structure, only generate pointer */
3093 /* structure assignment : generate memcpy */
3094 /* XXX: optimize if small size */
3095 size = type_size(&vtop->type, &align);
3096
3097 /* destination */
3098 vswap();
3099 vtop->type.t = VT_PTR;
3100 gaddrof();
3101
3102 /* address of memcpy() */
3103#ifdef TCC_ARM_EABI
3104 if(!(align & 7))
3105 vpush_global_sym(&func_old_type, TOK_memcpy8);
3106 else if(!(align & 3))
3107 vpush_global_sym(&func_old_type, TOK_memcpy4);
3108 else
3109#endif
3110 /* Use memmove, rather than memcpy, as dest and src may be same: */
3111 vpush_global_sym(&func_old_type, TOK_memmove);
3112
3113 vswap();
3114 /* source */
3115 vpushv(vtop - 2);
3116 vtop->type.t = VT_PTR;
3117 gaddrof();
3118 /* type size */
3119 vpushi(size);
3120 gfunc_call(3);
3121
3122 /* leave source on stack */
3123 } else if (ft & VT_BITFIELD) {
3124 /* bitfield store handling */
3125
3126 /* save lvalue as expression result (example: s.b = s.a = n;) */
3127 vdup(), vtop[-1] = vtop[-2];
3128
3129 bit_pos = BIT_POS(ft);
3130 bit_size = BIT_SIZE(ft);
3131 /* remove bit field info to avoid loops */
3132 vtop[-1].type.t = ft & ~VT_STRUCT_MASK;
3133
3134 if ((ft & VT_BTYPE) == VT_BOOL) {
3135 gen_cast(&vtop[-1].type);
3136 vtop[-1].type.t = (vtop[-1].type.t & ~VT_BTYPE) | (VT_BYTE | VT_UNSIGNED);
3137 }
3138
3139 r = adjust_bf(vtop - 1, bit_pos, bit_size);
3140 if (r == VT_STRUCT) {
3141 gen_cast_s((ft & VT_BTYPE) == VT_LLONG ? VT_LLONG : VT_INT);
3142 store_packed_bf(bit_pos, bit_size);
3143 } else {
3144 unsigned long long mask = (1ULL << bit_size) - 1;
3145 if ((ft & VT_BTYPE) != VT_BOOL) {
3146 /* mask source */
3147 if ((vtop[-1].type.t & VT_BTYPE) == VT_LLONG)
3148 vpushll(mask);
3149 else
3150 vpushi((unsigned)mask);
3151 gen_op('&');
3152 }
3153 /* shift source */
3154 vpushi(bit_pos);
3155 gen_op(TOK_SHL);
3156 vswap();
3157 /* duplicate destination */
3158 vdup();
3159 vrott(3);
3160 /* load destination, mask and or with source */
3161 if ((vtop->type.t & VT_BTYPE) == VT_LLONG)
3162 vpushll(~(mask << bit_pos));
3163 else
3164 vpushi(~((unsigned)mask << bit_pos));
3165 gen_op('&');
3166 gen_op('|');
3167 /* store result */
3168 vstore();
3169 /* ... and discard */
3170 vpop();
3171 }
3172 } else if (dbt == VT_VOID) {
3173 --vtop;
3174 } else {
3175#ifdef CONFIG_TCC_BCHECK
3176 /* bound check case */
3177 if (vtop[-1].r & VT_MUSTBOUND) {
3178 vswap();
3179 gbound();
3180 vswap();
3181 }
3182#endif
3183 rc = RC_INT;
3184 if (is_float(ft)) {
3185 rc = RC_FLOAT;
3186#ifdef TCC_TARGET_X86_64
3187 if ((ft & VT_BTYPE) == VT_LDOUBLE) {
3188 rc = RC_ST0;
3189 } else if ((ft & VT_BTYPE) == VT_QFLOAT) {
3190 rc = RC_FRET;
3191 }
3192#endif
3193 }
3194 r = gv(rc); /* generate value */
3195 /* if lvalue was saved on stack, must read it */
3196 if ((vtop[-1].r & VT_VALMASK) == VT_LLOCAL) {
3197 SValue sv;
3198 t = get_reg(RC_INT);
3199#if PTR_SIZE == 8
3200 sv.type.t = VT_PTR;
3201#else
3202 sv.type.t = VT_INT;
3203#endif
3204 sv.r = VT_LOCAL | VT_LVAL;
3205 sv.c.i = vtop[-1].c.i;
3206 load(t, &sv);
3207 vtop[-1].r = t | VT_LVAL;
3208 }
3209 /* two word case handling : store second register at word + 4 (or +8 for x86-64) */
3210#if PTR_SIZE == 8
3211 if (((ft & VT_BTYPE) == VT_QLONG) || ((ft & VT_BTYPE) == VT_QFLOAT)) {
3212 int addr_type = VT_LLONG, load_size = 8, load_type = ((vtop->type.t & VT_BTYPE) == VT_QLONG) ? VT_LLONG : VT_DOUBLE;
3213#else
3214 if ((ft & VT_BTYPE) == VT_LLONG) {
3215 int addr_type = VT_INT, load_size = 4, load_type = VT_INT;
3216#endif
3217 vtop[-1].type.t = load_type;
3218 store(r, vtop - 1);
3219 vswap();
3220 /* convert to int to increment easily */
3221 vtop->type.t = addr_type;
3222 gaddrof();
3223 vpushi(load_size);
3224 gen_op('+');
3225 vtop->r |= VT_LVAL;
3226 vswap();
3227 vtop[-1].type.t = load_type;
3228 /* XXX: it works because r2 is spilled last ! */
3229 store(vtop->r2, vtop - 1);
3230 } else {
3231 store(r, vtop - 1);
3232 }
3233
3234 vswap();
3235 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
3236 vtop->r |= delayed_cast;
3237 }
3238}
3239
3240/* post defines POST/PRE add. c is the token ++ or -- */
3241ST_FUNC void inc(int post, int c)
3242{
3243 test_lvalue();
3244 vdup(); /* save lvalue */
3245 if (post) {
3246 gv_dup(); /* duplicate value */
3247 vrotb(3);
3248 vrotb(3);
3249 }
3250 /* add constant */
3251 vpushi(c - TOK_MID);
3252 gen_op('+');
3253 vstore(); /* store value */
3254 if (post)
3255 vpop(); /* if post op, return saved value */
3256}
3257
3258ST_FUNC void parse_mult_str (CString *astr, const char *msg)
3259{
3260 /* read the string */
3261 if (tok != TOK_STR)
3262 expect(msg);
3263 cstr_new(astr);
3264 while (tok == TOK_STR) {
3265 /* XXX: add \0 handling too ? */
3266 cstr_cat(astr, tokc.str.data, -1);
3267 next();
3268 }
3269 cstr_ccat(astr, '\0');
3270}
3271
3272/* If I is >= 1 and a power of two, returns log2(i)+1.
3273 If I is 0 returns 0. */
3274static int exact_log2p1(int i)
3275{
3276 int ret;
3277 if (!i)
3278 return 0;
3279 for (ret = 1; i >= 1 << 8; ret += 8)
3280 i >>= 8;
3281 if (i >= 1 << 4)
3282 ret += 4, i >>= 4;
3283 if (i >= 1 << 2)
3284 ret += 2, i >>= 2;
3285 if (i >= 1 << 1)
3286 ret++;
3287 return ret;
3288}
3289
3290/* Parse __attribute__((...)) GNUC extension. */
3291static void parse_attribute(AttributeDef *ad)
3292{
3293 int t, n;
3294 CString astr;
3295
3296redo:
3297 if (tok != TOK_ATTRIBUTE1 && tok != TOK_ATTRIBUTE2)
3298 return;
3299 next();
3300 skip('(');
3301 skip('(');
3302 while (tok != ')') {
3303 if (tok < TOK_IDENT)
3304 expect("attribute name");
3305 t = tok;
3306 next();
3307 switch(t) {
3308 case TOK_SECTION1:
3309 case TOK_SECTION2:
3310 skip('(');
3311 parse_mult_str(&astr, "section name");
3312 ad->section = find_section(tcc_state, (char *)astr.data);
3313 skip(')');
3314 cstr_free(&astr);
3315 break;
3316 case TOK_ALIAS1:
3317 case TOK_ALIAS2:
3318 skip('(');
3319 parse_mult_str(&astr, "alias(\"target\")");
3320 ad->alias_target = /* save string as token, for later */
3321 tok_alloc((char*)astr.data, astr.size-1)->tok;
3322 skip(')');
3323 cstr_free(&astr);
3324 break;
3325 case TOK_VISIBILITY1:
3326 case TOK_VISIBILITY2:
3327 skip('(');
3328 parse_mult_str(&astr,
3329 "visibility(\"default|hidden|internal|protected\")");
3330 if (!strcmp (astr.data, "default"))
3331 ad->a.visibility = STV_DEFAULT;
3332 else if (!strcmp (astr.data, "hidden"))
3333 ad->a.visibility = STV_HIDDEN;
3334 else if (!strcmp (astr.data, "internal"))
3335 ad->a.visibility = STV_INTERNAL;
3336 else if (!strcmp (astr.data, "protected"))
3337 ad->a.visibility = STV_PROTECTED;
3338 else
3339 expect("visibility(\"default|hidden|internal|protected\")");
3340 skip(')');
3341 cstr_free(&astr);
3342 break;
3343 case TOK_ALIGNED1:
3344 case TOK_ALIGNED2:
3345 if (tok == '(') {
3346 next();
3347 n = expr_const();
3348 if (n <= 0 || (n & (n - 1)) != 0)
3349 tcc_error("alignment must be a positive power of two");
3350 skip(')');
3351 } else {
3352 n = MAX_ALIGN;
3353 }
3354 ad->a.aligned = exact_log2p1(n);
3355 if (n != 1 << (ad->a.aligned - 1))
3356 tcc_error("alignment of %d is larger than implemented", n);
3357 break;
3358 case TOK_PACKED1:
3359 case TOK_PACKED2:
3360 ad->a.packed = 1;
3361 break;
3362 case TOK_WEAK1:
3363 case TOK_WEAK2:
3364 ad->a.weak = 1;
3365 break;
3366 case TOK_UNUSED1:
3367 case TOK_UNUSED2:
3368 /* currently, no need to handle it because tcc does not
3369 track unused objects */
3370 break;
3371 case TOK_NORETURN1:
3372 case TOK_NORETURN2:
3373 /* currently, no need to handle it because tcc does not
3374 track unused objects */
3375 break;
3376 case TOK_CDECL1:
3377 case TOK_CDECL2:
3378 case TOK_CDECL3:
3379 ad->f.func_call = FUNC_CDECL;
3380 break;
3381 case TOK_STDCALL1:
3382 case TOK_STDCALL2:
3383 case TOK_STDCALL3:
3384 ad->f.func_call = FUNC_STDCALL;
3385 break;
3386#ifdef TCC_TARGET_I386
3387 case TOK_REGPARM1:
3388 case TOK_REGPARM2:
3389 skip('(');
3390 n = expr_const();
3391 if (n > 3)
3392 n = 3;
3393 else if (n < 0)
3394 n = 0;
3395 if (n > 0)
3396 ad->f.func_call = FUNC_FASTCALL1 + n - 1;
3397 skip(')');
3398 break;
3399 case TOK_FASTCALL1:
3400 case TOK_FASTCALL2:
3401 case TOK_FASTCALL3:
3402 ad->f.func_call = FUNC_FASTCALLW;
3403 break;
3404#endif
3405 case TOK_MODE:
3406 skip('(');
3407 switch(tok) {
3408 case TOK_MODE_DI:
3409 ad->attr_mode = VT_LLONG + 1;
3410 break;
3411 case TOK_MODE_QI:
3412 ad->attr_mode = VT_BYTE + 1;
3413 break;
3414 case TOK_MODE_HI:
3415 ad->attr_mode = VT_SHORT + 1;
3416 break;
3417 case TOK_MODE_SI:
3418 case TOK_MODE_word:
3419 ad->attr_mode = VT_INT + 1;
3420 break;
3421 default:
3422 tcc_warning("__mode__(%s) not supported\n", get_tok_str(tok, NULL));
3423 break;
3424 }
3425 next();
3426 skip(')');
3427 break;
3428 case TOK_DLLEXPORT:
3429 ad->a.dllexport = 1;
3430 break;
3431 case TOK_DLLIMPORT:
3432 ad->a.dllimport = 1;
3433 break;
3434 default:
3435 if (tcc_state->warn_unsupported)
3436 tcc_warning("'%s' attribute ignored", get_tok_str(t, NULL));
3437 /* skip parameters */
3438 if (tok == '(') {
3439 int parenthesis = 0;
3440 do {
3441 if (tok == '(')
3442 parenthesis++;
3443 else if (tok == ')')
3444 parenthesis--;
3445 next();
3446 } while (parenthesis && tok != -1);
3447 }
3448 break;
3449 }
3450 if (tok != ',')
3451 break;
3452 next();
3453 }
3454 skip(')');
3455 skip(')');
3456 goto redo;
3457}
3458
3459static Sym * find_field (CType *type, int v)
3460{
3461 Sym *s = type->ref;
3462 v |= SYM_FIELD;
3463 while ((s = s->next) != NULL) {
3464 if ((s->v & SYM_FIELD) &&
3465 (s->type.t & VT_BTYPE) == VT_STRUCT &&
3466 (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3467 Sym *ret = find_field (&s->type, v);
3468 if (ret)
3469 return ret;
3470 }
3471 if (s->v == v)
3472 break;
3473 }
3474 return s;
3475}
3476
3477static void struct_add_offset (Sym *s, int offset)
3478{
3479 while ((s = s->next) != NULL) {
3480 if ((s->v & SYM_FIELD) &&
3481 (s->type.t & VT_BTYPE) == VT_STRUCT &&
3482 (s->v & ~SYM_FIELD) >= SYM_FIRST_ANOM) {
3483 struct_add_offset(s->type.ref, offset);
3484 } else
3485 s->c += offset;
3486 }
3487}
3488
3489static void struct_layout(CType *type, AttributeDef *ad)
3490{
3491 int size, align, maxalign, offset, c, bit_pos, bit_size;
3492 int packed, a, bt, prevbt, prev_bit_size;
3493 int pcc = !tcc_state->ms_bitfields;
3494 int pragma_pack = *tcc_state->pack_stack_ptr;
3495 Sym *f;
3496
3497 maxalign = 1;
3498 offset = 0;
3499 c = 0;
3500 bit_pos = 0;
3501 prevbt = VT_STRUCT; /* make it never match */
3502 prev_bit_size = 0;
3503
3504//#define BF_DEBUG
3505
3506 for (f = type->ref->next; f; f = f->next) {
3507 if (f->type.t & VT_BITFIELD)
3508 bit_size = BIT_SIZE(f->type.t);
3509 else
3510 bit_size = -1;
3511 size = type_size(&f->type, &align);
3512 a = f->a.aligned ? 1 << (f->a.aligned - 1) : 0;
3513 packed = 0;
3514
3515 if (pcc && bit_size == 0) {
3516 /* in pcc mode, packing does not affect zero-width bitfields */
3517
3518 } else {
3519 /* in pcc mode, attribute packed overrides if set. */
3520 if (pcc && (f->a.packed || ad->a.packed))
3521 align = packed = 1;
3522
3523 /* pragma pack overrides align if lesser and packs bitfields always */
3524 if (pragma_pack) {
3525 packed = 1;
3526 if (pragma_pack < align)
3527 align = pragma_pack;
3528 /* in pcc mode pragma pack also overrides individual align */
3529 if (pcc && pragma_pack < a)
3530 a = 0;
3531 }
3532 }
3533 /* some individual align was specified */
3534 if (a)
3535 align = a;
3536
3537 if (type->ref->type.t == VT_UNION) {
3538 if (pcc && bit_size >= 0)
3539 size = (bit_size + 7) >> 3;
3540 offset = 0;
3541 if (size > c)
3542 c = size;
3543
3544 } else if (bit_size < 0) {
3545 if (pcc)
3546 c += (bit_pos + 7) >> 3;
3547 c = (c + align - 1) & -align;
3548 offset = c;
3549 if (size > 0)
3550 c += size;
3551 bit_pos = 0;
3552 prevbt = VT_STRUCT;
3553 prev_bit_size = 0;
3554
3555 } else {
3556 /* A bit-field. Layout is more complicated. There are two
3557 options: PCC (GCC) compatible and MS compatible */
3558 if (pcc) {
3559 /* In PCC layout a bit-field is placed adjacent to the
3560 preceding bit-fields, except if:
3561 - it has zero-width
3562 - an individual alignment was given
3563 - it would overflow its base type container and
3564 there is no packing */
3565 if (bit_size == 0) {
3566 new_field:
3567 c = (c + ((bit_pos + 7) >> 3) + align - 1) & -align;
3568 bit_pos = 0;
3569 } else if (f->a.aligned) {
3570 goto new_field;
3571 } else if (!packed) {
3572 int a8 = align * 8;
3573 int ofs = ((c * 8 + bit_pos) % a8 + bit_size + a8 - 1) / a8;
3574 if (ofs > size / align)
3575 goto new_field;
3576 }
3577
3578 /* in pcc mode, long long bitfields have type int if they fit */
3579 if (size == 8 && bit_size <= 32)
3580 f->type.t = (f->type.t & ~VT_BTYPE) | VT_INT, size = 4;
3581
3582 while (bit_pos >= align * 8)
3583 c += align, bit_pos -= align * 8;
3584 offset = c;
3585
3586 /* In PCC layout named bit-fields influence the alignment
3587 of the containing struct using the base types alignment,
3588 except for packed fields (which here have correct align). */
3589 if (f->v & SYM_FIRST_ANOM
3590 // && bit_size // ??? gcc on ARM/rpi does that
3591 )
3592 align = 1;
3593
3594 } else {
3595 bt = f->type.t & VT_BTYPE;
3596 if ((bit_pos + bit_size > size * 8)
3597 || (bit_size > 0) == (bt != prevbt)
3598 ) {
3599 c = (c + align - 1) & -align;
3600 offset = c;
3601 bit_pos = 0;
3602 /* In MS bitfield mode a bit-field run always uses
3603 at least as many bits as the underlying type.
3604 To start a new run it's also required that this
3605 or the last bit-field had non-zero width. */
3606 if (bit_size || prev_bit_size)
3607 c += size;
3608 }
3609 /* In MS layout the records alignment is normally
3610 influenced by the field, except for a zero-width
3611 field at the start of a run (but by further zero-width
3612 fields it is again). */
3613 if (bit_size == 0 && prevbt != bt)
3614 align = 1;
3615 prevbt = bt;
3616 prev_bit_size = bit_size;
3617 }
3618
3619 f->type.t = (f->type.t & ~(0x3f << VT_STRUCT_SHIFT))
3620 | (bit_pos << VT_STRUCT_SHIFT);
3621 bit_pos += bit_size;
3622 }
3623 if (align > maxalign)
3624 maxalign = align;
3625
3626#ifdef BF_DEBUG
3627 printf("set field %s offset %-2d size %-2d align %-2d",
3628 get_tok_str(f->v & ~SYM_FIELD, NULL), offset, size, align);
3629 if (f->type.t & VT_BITFIELD) {
3630 printf(" pos %-2d bits %-2d",
3631 BIT_POS(f->type.t),
3632 BIT_SIZE(f->type.t)
3633 );
3634 }
3635 printf("\n");
3636#endif
3637
3638 if (f->v & SYM_FIRST_ANOM && (f->type.t & VT_BTYPE) == VT_STRUCT) {
3639 Sym *ass;
3640 /* An anonymous struct/union. Adjust member offsets
3641 to reflect the real offset of our containing struct.
3642 Also set the offset of this anon member inside
3643 the outer struct to be zero. Via this it
3644 works when accessing the field offset directly
3645 (from base object), as well as when recursing
3646 members in initializer handling. */
3647 int v2 = f->type.ref->v;
3648 if (!(v2 & SYM_FIELD) &&
3649 (v2 & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3650 Sym **pps;
3651 /* This happens only with MS extensions. The
3652 anon member has a named struct type, so it
3653 potentially is shared with other references.
3654 We need to unshare members so we can modify
3655 them. */
3656 ass = f->type.ref;
3657 f->type.ref = sym_push(anon_sym++ | SYM_FIELD,
3658 &f->type.ref->type, 0,
3659 f->type.ref->c);
3660 pps = &f->type.ref->next;
3661 while ((ass = ass->next) != NULL) {
3662 *pps = sym_push(ass->v, &ass->type, 0, ass->c);
3663 pps = &((*pps)->next);
3664 }
3665 *pps = NULL;
3666 }
3667 struct_add_offset(f->type.ref, offset);
3668 f->c = 0;
3669 } else {
3670 f->c = offset;
3671 }
3672
3673 f->r = 0;
3674 }
3675
3676 if (pcc)
3677 c += (bit_pos + 7) >> 3;
3678
3679 /* store size and alignment */
3680 a = bt = ad->a.aligned ? 1 << (ad->a.aligned - 1) : 1;
3681 if (a < maxalign)
3682 a = maxalign;
3683 type->ref->r = a;
3684 if (pragma_pack && pragma_pack < maxalign && 0 == pcc) {
3685 /* can happen if individual align for some member was given. In
3686 this case MSVC ignores maxalign when aligning the size */
3687 a = pragma_pack;
3688 if (a < bt)
3689 a = bt;
3690 }
3691 c = (c + a - 1) & -a;
3692 type->ref->c = c;
3693
3694#ifdef BF_DEBUG
3695 printf("struct size %-2d align %-2d\n\n", c, a), fflush(stdout);
3696#endif
3697
3698 /* check whether we can access bitfields by their type */
3699 for (f = type->ref->next; f; f = f->next) {
3700 int s, px, cx, c0;
3701 CType t;
3702
3703 if (0 == (f->type.t & VT_BITFIELD))
3704 continue;
3705 f->type.ref = f;
3706 f->auxtype = -1;
3707 bit_size = BIT_SIZE(f->type.t);
3708 if (bit_size == 0)
3709 continue;
3710 bit_pos = BIT_POS(f->type.t);
3711 size = type_size(&f->type, &align);
3712 if (bit_pos + bit_size <= size * 8 && f->c + size <= c)
3713 continue;
3714
3715 /* try to access the field using a different type */
3716 c0 = -1, s = align = 1;
3717 for (;;) {
3718 px = f->c * 8 + bit_pos;
3719 cx = (px >> 3) & -align;
3720 px = px - (cx << 3);
3721 if (c0 == cx)
3722 break;
3723 s = (px + bit_size + 7) >> 3;
3724 if (s > 4) {
3725 t.t = VT_LLONG;
3726 } else if (s > 2) {
3727 t.t = VT_INT;
3728 } else if (s > 1) {
3729 t.t = VT_SHORT;
3730 } else {
3731 t.t = VT_BYTE;
3732 }
3733 s = type_size(&t, &align);
3734 c0 = cx;
3735 }
3736
3737 if (px + bit_size <= s * 8 && cx + s <= c) {
3738 /* update offset and bit position */
3739 f->c = cx;
3740 bit_pos = px;
3741 f->type.t = (f->type.t & ~(0x3f << VT_STRUCT_SHIFT))
3742 | (bit_pos << VT_STRUCT_SHIFT);
3743 if (s != size)
3744 f->auxtype = t.t;
3745#ifdef BF_DEBUG
3746 printf("FIX field %s offset %-2d size %-2d align %-2d "
3747 "pos %-2d bits %-2d\n",
3748 get_tok_str(f->v & ~SYM_FIELD, NULL),
3749 cx, s, align, px, bit_size);
3750#endif
3751 } else {
3752 /* fall back to load/store single-byte wise */
3753 f->auxtype = VT_STRUCT;
3754#ifdef BF_DEBUG
3755 printf("FIX field %s : load byte-wise\n",
3756 get_tok_str(f->v & ~SYM_FIELD, NULL));
3757#endif
3758 }
3759 }
3760}
3761
3762/* enum/struct/union declaration. u is VT_ENUM/VT_STRUCT/VT_UNION */
3763static void struct_decl(CType *type, int u)
3764{
3765 int v, c, size, align, flexible;
3766 int bit_size, bsize, bt;
3767 Sym *s, *ss, **ps;
3768 AttributeDef ad, ad1;
3769 CType type1, btype;
3770
3771 memset(&ad, 0, sizeof ad);
3772 next();
3773 parse_attribute(&ad);
3774 if (tok != '{') {
3775 v = tok;
3776 next();
3777 /* struct already defined ? return it */
3778 if (v < TOK_IDENT)
3779 expect("struct/union/enum name");
3780 s = struct_find(v);
3781 if (s && (s->sym_scope == local_scope || tok != '{')) {
3782 if (u == s->type.t)
3783 goto do_decl;
3784 if (u == VT_ENUM && IS_ENUM(s->type.t))
3785 goto do_decl;
3786 tcc_error("redefinition of '%s'", get_tok_str(v, NULL));
3787 }
3788 } else {
3789 v = anon_sym++;
3790 }
3791 /* Record the original enum/struct/union token. */
3792 type1.t = u == VT_ENUM ? u | VT_INT | VT_UNSIGNED : u;
3793 type1.ref = NULL;
3794 /* we put an undefined size for struct/union */
3795 s = sym_push(v | SYM_STRUCT, &type1, 0, -1);
3796 s->r = 0; /* default alignment is zero as gcc */
3797do_decl:
3798 type->t = s->type.t;
3799 type->ref = s;
3800
3801 if (tok == '{') {
3802 next();
3803 if (s->c != -1)
3804 tcc_error("struct/union/enum already defined");
3805 /* cannot be empty */
3806 /* non empty enums are not allowed */
3807 ps = &s->next;
3808 if (u == VT_ENUM) {
3809 long long ll = 0, pl = 0, nl = 0;
3810 CType t;
3811 t.ref = s;
3812 /* enum symbols have static storage */
3813 t.t = VT_INT|VT_STATIC|VT_ENUM_VAL;
3814 for(;;) {
3815 v = tok;
3816 if (v < TOK_UIDENT)
3817 expect("identifier");
3818 ss = sym_find(v);
3819 if (ss && !local_stack)
3820 tcc_error("redefinition of enumerator '%s'",
3821 get_tok_str(v, NULL));
3822 next();
3823 if (tok == '=') {
3824 next();
3825 ll = expr_const64();
3826 }
3827 ss = sym_push(v, &t, VT_CONST, 0);
3828 ss->enum_val = ll;
3829 *ps = ss, ps = &ss->next;
3830 if (ll < nl)
3831 nl = ll;
3832 if (ll > pl)
3833 pl = ll;
3834 if (tok != ',')
3835 break;
3836 next();
3837 ll++;
3838 /* NOTE: we accept a trailing comma */
3839 if (tok == '}')
3840 break;
3841 }
3842 skip('}');
3843 /* set integral type of the enum */
3844 t.t = VT_INT;
3845 if (nl >= 0) {
3846 if (pl != (unsigned)pl)
3847 t.t = (LONG_SIZE==8 ? VT_LLONG|VT_LONG : VT_LLONG);
3848 t.t |= VT_UNSIGNED;
3849 } else if (pl != (int)pl || nl != (int)nl)
3850 t.t = (LONG_SIZE==8 ? VT_LLONG|VT_LONG : VT_LLONG);
3851 s->type.t = type->t = t.t | VT_ENUM;
3852 s->c = 0;
3853 /* set type for enum members */
3854 for (ss = s->next; ss; ss = ss->next) {
3855 ll = ss->enum_val;
3856 if (ll == (int)ll) /* default is int if it fits */
3857 continue;
3858 if (t.t & VT_UNSIGNED) {
3859 ss->type.t |= VT_UNSIGNED;
3860 if (ll == (unsigned)ll)
3861 continue;
3862 }
3863 ss->type.t = (ss->type.t & ~VT_BTYPE)
3864 | (LONG_SIZE==8 ? VT_LLONG|VT_LONG : VT_LLONG);
3865 }
3866 } else {
3867 c = 0;
3868 flexible = 0;
3869 while (tok != '}') {
3870 if (!parse_btype(&btype, &ad1)) {
3871 skip(';');
3872 continue;
3873 }
3874 while (1) {
3875 if (flexible)
3876 tcc_error("flexible array member '%s' not at the end of struct",
3877 get_tok_str(v, NULL));
3878 bit_size = -1;
3879 v = 0;
3880 type1 = btype;
3881 if (tok != ':') {
3882 if (tok != ';')
3883 type_decl(&type1, &ad1, &v, TYPE_DIRECT);
3884 if (v == 0) {
3885 if ((type1.t & VT_BTYPE) != VT_STRUCT)
3886 expect("identifier");
3887 else {
3888 int v = btype.ref->v;
3889 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
3890 if (tcc_state->ms_extensions == 0)
3891 expect("identifier");
3892 }
3893 }
3894 }
3895 if (type_size(&type1, &align) < 0) {
3896 if ((u == VT_STRUCT) && (type1.t & VT_ARRAY) && c)
3897 flexible = 1;
3898 else
3899 tcc_error("field '%s' has incomplete type",
3900 get_tok_str(v, NULL));
3901 }
3902 if ((type1.t & VT_BTYPE) == VT_FUNC ||
3903 (type1.t & VT_STORAGE))
3904 tcc_error("invalid type for '%s'",
3905 get_tok_str(v, NULL));
3906 }
3907 if (tok == ':') {
3908 next();
3909 bit_size = expr_const();
3910 /* XXX: handle v = 0 case for messages */
3911 if (bit_size < 0)
3912 tcc_error("negative width in bit-field '%s'",
3913 get_tok_str(v, NULL));
3914 if (v && bit_size == 0)
3915 tcc_error("zero width for bit-field '%s'",
3916 get_tok_str(v, NULL));
3917 parse_attribute(&ad1);
3918 }
3919 size = type_size(&type1, &align);
3920 if (bit_size >= 0) {
3921 bt = type1.t & VT_BTYPE;
3922 if (bt != VT_INT &&
3923 bt != VT_BYTE &&
3924 bt != VT_SHORT &&
3925 bt != VT_BOOL &&
3926 bt != VT_LLONG)
3927 tcc_error("bitfields must have scalar type");
3928 bsize = size * 8;
3929 if (bit_size > bsize) {
3930 tcc_error("width of '%s' exceeds its type",
3931 get_tok_str(v, NULL));
3932 } else if (bit_size == bsize
3933 && !ad.a.packed && !ad1.a.packed) {
3934 /* no need for bit fields */
3935 ;
3936 } else if (bit_size == 64) {
3937 tcc_error("field width 64 not implemented");
3938 } else {
3939 type1.t = (type1.t & ~VT_STRUCT_MASK)
3940 | VT_BITFIELD
3941 | (bit_size << (VT_STRUCT_SHIFT + 6));
3942 }
3943 }
3944 if (v != 0 || (type1.t & VT_BTYPE) == VT_STRUCT) {
3945 /* Remember we've seen a real field to check
3946 for placement of flexible array member. */
3947 c = 1;
3948 }
3949 /* If member is a struct or bit-field, enforce
3950 placing into the struct (as anonymous). */
3951 if (v == 0 &&
3952 ((type1.t & VT_BTYPE) == VT_STRUCT ||
3953 bit_size >= 0)) {
3954 v = anon_sym++;
3955 }
3956 if (v) {
3957 ss = sym_push(v | SYM_FIELD, &type1, 0, 0);
3958 ss->a = ad1.a;
3959 *ps = ss;
3960 ps = &ss->next;
3961 }
3962 if (tok == ';' || tok == TOK_EOF)
3963 break;
3964 skip(',');
3965 }
3966 skip(';');
3967 }
3968 skip('}');
3969 parse_attribute(&ad);
3970 struct_layout(type, &ad);
3971 }
3972 }
3973}
3974
3975static void sym_to_attr(AttributeDef *ad, Sym *s)
3976{
3977 if (s->a.aligned && 0 == ad->a.aligned)
3978 ad->a.aligned = s->a.aligned;
3979 if (s->f.func_call && 0 == ad->f.func_call)
3980 ad->f.func_call = s->f.func_call;
3981 if (s->f.func_type && 0 == ad->f.func_type)
3982 ad->f.func_type = s->f.func_type;
3983 if (s->a.packed)
3984 ad->a.packed = 1;
3985}
3986
3987/* Add type qualifiers to a type. If the type is an array then the qualifiers
3988 are added to the element type, copied because it could be a typedef. */
3989static void parse_btype_qualify(CType *type, int qualifiers)
3990{
3991 while (type->t & VT_ARRAY) {
3992 type->ref = sym_push(SYM_FIELD, &type->ref->type, 0, type->ref->c);
3993 type = &type->ref->type;
3994 }
3995 type->t |= qualifiers;
3996}
3997
3998/* return 0 if no type declaration. otherwise, return the basic type
3999 and skip it.
4000 */
4001static int parse_btype(CType *type, AttributeDef *ad)
4002{
4003 int t, u, bt, st, type_found, typespec_found, g;
4004 Sym *s;
4005 CType type1;
4006
4007 memset(ad, 0, sizeof(AttributeDef));
4008 type_found = 0;
4009 typespec_found = 0;
4010 t = VT_INT;
4011 bt = st = -1;
4012 type->ref = NULL;
4013
4014 while(1) {
4015 switch(tok) {
4016 case TOK_EXTENSION:
4017 /* currently, we really ignore extension */
4018 next();
4019 continue;
4020
4021 /* basic types */
4022 case TOK_CHAR:
4023 u = VT_BYTE;
4024 basic_type:
4025 next();
4026 basic_type1:
4027 if (u == VT_SHORT || u == VT_LONG) {
4028 if (st != -1 || (bt != -1 && bt != VT_INT))
4029 tmbt: tcc_error("too many basic types");
4030 st = u;
4031 } else {
4032 if (bt != -1 || (st != -1 && u != VT_INT))
4033 goto tmbt;
4034 bt = u;
4035 }
4036 if (u != VT_INT)
4037 t = (t & ~(VT_BTYPE|VT_LONG)) | u;
4038 typespec_found = 1;
4039 break;
4040 case TOK_VOID:
4041 u = VT_VOID;
4042 goto basic_type;
4043 case TOK_SHORT:
4044 u = VT_SHORT;
4045 goto basic_type;
4046 case TOK_INT:
4047 u = VT_INT;
4048 goto basic_type;
4049 case TOK_LONG:
4050 if ((t & VT_BTYPE) == VT_DOUBLE) {
4051 t = (t & ~(VT_BTYPE|VT_LONG)) | VT_LDOUBLE;
4052 } else if ((t & (VT_BTYPE|VT_LONG)) == VT_LONG) {
4053 t = (t & ~(VT_BTYPE|VT_LONG)) | VT_LLONG;
4054 } else {
4055 u = VT_LONG;
4056 goto basic_type;
4057 }
4058 next();
4059 break;
4060#ifdef TCC_TARGET_ARM64
4061 case TOK_UINT128:
4062 /* GCC's __uint128_t appears in some Linux header files. Make it a
4063 synonym for long double to get the size and alignment right. */
4064 u = VT_LDOUBLE;
4065 goto basic_type;
4066#endif
4067 case TOK_BOOL:
4068 u = VT_BOOL;
4069 goto basic_type;
4070 case TOK_FLOAT:
4071 u = VT_FLOAT;
4072 goto basic_type;
4073 case TOK_DOUBLE:
4074 if ((t & (VT_BTYPE|VT_LONG)) == VT_LONG) {
4075 t = (t & ~(VT_BTYPE|VT_LONG)) | VT_LDOUBLE;
4076 } else {
4077 u = VT_DOUBLE;
4078 goto basic_type;
4079 }
4080 next();
4081 break;
4082 case TOK_ENUM:
4083 struct_decl(&type1, VT_ENUM);
4084 basic_type2:
4085 u = type1.t;
4086 type->ref = type1.ref;
4087 goto basic_type1;
4088 case TOK_STRUCT:
4089 struct_decl(&type1, VT_STRUCT);
4090 goto basic_type2;
4091 case TOK_UNION:
4092 struct_decl(&type1, VT_UNION);
4093 goto basic_type2;
4094
4095 /* type modifiers */
4096 case TOK_CONST1:
4097 case TOK_CONST2:
4098 case TOK_CONST3:
4099 type->t = t;
4100 parse_btype_qualify(type, VT_CONSTANT);
4101 t = type->t;
4102 next();
4103 break;
4104 case TOK_VOLATILE1:
4105 case TOK_VOLATILE2:
4106 case TOK_VOLATILE3:
4107 type->t = t;
4108 parse_btype_qualify(type, VT_VOLATILE);
4109 t = type->t;
4110 next();
4111 break;
4112 case TOK_SIGNED1:
4113 case TOK_SIGNED2:
4114 case TOK_SIGNED3:
4115 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == (VT_DEFSIGN|VT_UNSIGNED))
4116 tcc_error("signed and unsigned modifier");
4117 t |= VT_DEFSIGN;
4118 next();
4119 typespec_found = 1;
4120 break;
4121 case TOK_REGISTER:
4122 case TOK_AUTO:
4123 case TOK_RESTRICT1:
4124 case TOK_RESTRICT2:
4125 case TOK_RESTRICT3:
4126 next();
4127 break;
4128 case TOK_UNSIGNED:
4129 if ((t & (VT_DEFSIGN|VT_UNSIGNED)) == VT_DEFSIGN)
4130 tcc_error("signed and unsigned modifier");
4131 t |= VT_DEFSIGN | VT_UNSIGNED;
4132 next();
4133 typespec_found = 1;
4134 break;
4135
4136 /* storage */
4137 case TOK_EXTERN:
4138 g = VT_EXTERN;
4139 goto storage;
4140 case TOK_STATIC:
4141 g = VT_STATIC;
4142 goto storage;
4143 case TOK_TYPEDEF:
4144 g = VT_TYPEDEF;
4145 goto storage;
4146 storage:
4147 if (t & (VT_EXTERN|VT_STATIC|VT_TYPEDEF) & ~g)
4148 tcc_error("multiple storage classes");
4149 t |= g;
4150 next();
4151 break;
4152 case TOK_INLINE1:
4153 case TOK_INLINE2:
4154 case TOK_INLINE3:
4155 t |= VT_INLINE;
4156 next();
4157 break;
4158
4159 /* GNUC attribute */
4160 case TOK_ATTRIBUTE1:
4161 case TOK_ATTRIBUTE2:
4162 parse_attribute(ad);
4163 if (ad->attr_mode) {
4164 u = ad->attr_mode -1;
4165 t = (t & ~(VT_BTYPE|VT_LONG)) | u;
4166 }
4167 break;
4168 /* GNUC typeof */
4169 case TOK_TYPEOF1:
4170 case TOK_TYPEOF2:
4171 case TOK_TYPEOF3:
4172 next();
4173 parse_expr_type(&type1);
4174 /* remove all storage modifiers except typedef */
4175 type1.t &= ~(VT_STORAGE&~VT_TYPEDEF);
4176 if (type1.ref)
4177 sym_to_attr(ad, type1.ref);
4178 goto basic_type2;
4179 default:
4180 if (typespec_found)
4181 goto the_end;
4182 s = sym_find(tok);
4183 if (!s || !(s->type.t & VT_TYPEDEF))
4184 goto the_end;
4185 t &= ~(VT_BTYPE|VT_LONG);
4186 u = t & ~(VT_CONSTANT | VT_VOLATILE), t ^= u;
4187 type->t = (s->type.t & ~VT_TYPEDEF) | u;
4188 type->ref = s->type.ref;
4189 if (t)
4190 parse_btype_qualify(type, t);
4191 t = type->t;
4192 /* get attributes from typedef */
4193 sym_to_attr(ad, s);
4194 next();
4195 typespec_found = 1;
4196 st = bt = -2;
4197 break;
4198 }
4199 type_found = 1;
4200 }
4201the_end:
4202 if (tcc_state->char_is_unsigned) {
4203 if ((t & (VT_DEFSIGN|VT_BTYPE)) == VT_BYTE)
4204 t |= VT_UNSIGNED;
4205 }
4206 /* VT_LONG is used just as a modifier for VT_INT / VT_LLONG */
4207 bt = t & (VT_BTYPE|VT_LONG);
4208 if (bt == VT_LONG)
4209 t |= LONG_SIZE == 8 ? VT_LLONG : VT_INT;
4210#ifdef TCC_TARGET_PE
4211 if (bt == VT_LDOUBLE)
4212 t = (t & ~(VT_BTYPE|VT_LONG)) | VT_DOUBLE;
4213#endif
4214 type->t = t;
4215 return type_found;
4216}
4217
4218/* convert a function parameter type (array to pointer and function to
4219 function pointer) */
4220static inline void convert_parameter_type(CType *pt)
4221{
4222 /* remove const and volatile qualifiers (XXX: const could be used
4223 to indicate a const function parameter */
4224 pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
4225 /* array must be transformed to pointer according to ANSI C */
4226 pt->t &= ~VT_ARRAY;
4227 if ((pt->t & VT_BTYPE) == VT_FUNC) {
4228 mk_pointer(pt);
4229 }
4230}
4231
4232ST_FUNC void parse_asm_str(CString *astr)
4233{
4234 skip('(');
4235 parse_mult_str(astr, "string constant");
4236}
4237
4238/* Parse an asm label and return the token */
4239static int asm_label_instr(void)
4240{
4241 int v;
4242 CString astr;
4243
4244 next();
4245 parse_asm_str(&astr);
4246 skip(')');
4247#ifdef ASM_DEBUG
4248 printf("asm_alias: \"%s\"\n", (char *)astr.data);
4249#endif
4250 v = tok_alloc(astr.data, astr.size - 1)->tok;
4251 cstr_free(&astr);
4252 return v;
4253}
4254
4255static int post_type(CType *type, AttributeDef *ad, int storage, int td)
4256{
4257 int n, l, t1, arg_size, align;
4258 Sym **plast, *s, *first;
4259 AttributeDef ad1;
4260 CType pt;
4261
4262 if (tok == '(') {
4263 /* function type, or recursive declarator (return if so) */
4264 next();
4265 if (td && !(td & TYPE_ABSTRACT))
4266 return 0;
4267 if (tok == ')')
4268 l = 0;
4269 else if (parse_btype(&pt, &ad1))
4270 l = FUNC_NEW;
4271 else if (td)
4272 return 0;
4273 else
4274 l = FUNC_OLD;
4275 first = NULL;
4276 plast = &first;
4277 arg_size = 0;
4278 if (l) {
4279 for(;;) {
4280 /* read param name and compute offset */
4281 if (l != FUNC_OLD) {
4282 if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')')
4283 break;
4284 type_decl(&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
4285 if ((pt.t & VT_BTYPE) == VT_VOID)
4286 tcc_error("parameter declared as void");
4287 arg_size += (type_size(&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
4288 } else {
4289 n = tok;
4290 if (n < TOK_UIDENT)
4291 expect("identifier");
4292 pt.t = VT_VOID; /* invalid type */
4293 next();
4294 }
4295 convert_parameter_type(&pt);
4296 s = sym_push(n | SYM_FIELD, &pt, 0, 0);
4297 *plast = s;
4298 plast = &s->next;
4299 if (tok == ')')
4300 break;
4301 skip(',');
4302 if (l == FUNC_NEW && tok == TOK_DOTS) {
4303 l = FUNC_ELLIPSIS;
4304 next();
4305 break;
4306 }
4307 if (l == FUNC_NEW && !parse_btype(&pt, &ad1))
4308 tcc_error("invalid type");
4309 }
4310 } else
4311 /* if no parameters, then old type prototype */
4312 l = FUNC_OLD;
4313 skip(')');
4314 /* NOTE: const is ignored in returned type as it has a special
4315 meaning in gcc / C++ */
4316 type->t &= ~VT_CONSTANT;
4317 /* some ancient pre-K&R C allows a function to return an array
4318 and the array brackets to be put after the arguments, such
4319 that "int c()[]" means something like "int[] c()" */
4320 if (tok == '[') {
4321 next();
4322 skip(']'); /* only handle simple "[]" */
4323 mk_pointer(type);
4324 }
4325 /* we push a anonymous symbol which will contain the function prototype */
4326 ad->f.func_args = arg_size;
4327 ad->f.func_type = l;
4328 s = sym_push(SYM_FIELD, type, 0, 0);
4329 s->a = ad->a;
4330 s->f = ad->f;
4331 s->next = first;
4332 type->t = VT_FUNC;
4333 type->ref = s;
4334 } else if (tok == '[') {
4335 int saved_nocode_wanted = nocode_wanted;
4336 /* array definition */
4337 next();
4338 if (tok == TOK_RESTRICT1)
4339 next();
4340 n = -1;
4341 t1 = 0;
4342 if (tok != ']') {
4343 if (!local_stack || (storage & VT_STATIC))
4344 vpushi(expr_const());
4345 else {
4346 /* VLAs (which can only happen with local_stack && !VT_STATIC)
4347 length must always be evaluated, even under nocode_wanted,
4348 so that its size slot is initialized (e.g. under sizeof
4349 or typeof). */
4350 nocode_wanted = 0;
4351 gexpr();
4352 }
4353 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4354 n = vtop->c.i;
4355 if (n < 0)
4356 tcc_error("invalid array size");
4357 } else {
4358 if (!is_integer_btype(vtop->type.t & VT_BTYPE))
4359 tcc_error("size of variable length array should be an integer");
4360 t1 = VT_VLA;
4361 }
4362 }
4363 skip(']');
4364 /* parse next post type */
4365 post_type(type, ad, storage, 0);
4366 if (type->t == VT_FUNC)
4367 tcc_error("declaration of an array of functions");
4368 t1 |= type->t & VT_VLA;
4369
4370 if (t1 & VT_VLA) {
4371 loc -= type_size(&int_type, &align);
4372 loc &= -align;
4373 n = loc;
4374
4375 vla_runtime_type_size(type, &align);
4376 gen_op('*');
4377 vset(&int_type, VT_LOCAL|VT_LVAL, n);
4378 vswap();
4379 vstore();
4380 }
4381 if (n != -1)
4382 vpop();
4383 nocode_wanted = saved_nocode_wanted;
4384
4385 /* we push an anonymous symbol which will contain the array
4386 element type */
4387 s = sym_push(SYM_FIELD, type, 0, n);
4388 type->t = (t1 ? VT_VLA : VT_ARRAY) | VT_PTR;
4389 type->ref = s;
4390 }
4391 return 1;
4392}
4393
4394/* Parse a type declarator (except basic type), and return the type
4395 in 'type'. 'td' is a bitmask indicating which kind of type decl is
4396 expected. 'type' should contain the basic type. 'ad' is the
4397 attribute definition of the basic type. It can be modified by
4398 type_decl(). If this (possibly abstract) declarator is a pointer chain
4399 it returns the innermost pointed to type (equals *type, but is a different
4400 pointer), otherwise returns type itself, that's used for recursive calls. */
4401static CType *type_decl(CType *type, AttributeDef *ad, int *v, int td)
4402{
4403 CType *post, *ret;
4404 int qualifiers, storage;
4405
4406 /* recursive type, remove storage bits first, apply them later again */
4407 storage = type->t & VT_STORAGE;
4408 type->t &= ~VT_STORAGE;
4409 post = ret = type;
4410
4411 while (tok == '*') {
4412 qualifiers = 0;
4413 redo:
4414 next();
4415 switch(tok) {
4416 case TOK_CONST1:
4417 case TOK_CONST2:
4418 case TOK_CONST3:
4419 qualifiers |= VT_CONSTANT;
4420 goto redo;
4421 case TOK_VOLATILE1:
4422 case TOK_VOLATILE2:
4423 case TOK_VOLATILE3:
4424 qualifiers |= VT_VOLATILE;
4425 goto redo;
4426 case TOK_RESTRICT1:
4427 case TOK_RESTRICT2:
4428 case TOK_RESTRICT3:
4429 goto redo;
4430 /* XXX: clarify attribute handling */
4431 case TOK_ATTRIBUTE1:
4432 case TOK_ATTRIBUTE2:
4433 parse_attribute(ad);
4434 break;
4435 }
4436 mk_pointer(type);
4437 type->t |= qualifiers;
4438 if (ret == type)
4439 /* innermost pointed to type is the one for the first derivation */
4440 ret = pointed_type(type);
4441 }
4442
4443 if (tok == '(') {
4444 /* This is possibly a parameter type list for abstract declarators
4445 ('int ()'), use post_type for testing this. */
4446 if (!post_type(type, ad, 0, td)) {
4447 /* It's not, so it's a nested declarator, and the post operations
4448 apply to the innermost pointed to type (if any). */
4449 /* XXX: this is not correct to modify 'ad' at this point, but
4450 the syntax is not clear */
4451 parse_attribute(ad);
4452 post = type_decl(type, ad, v, td);
4453 skip(')');
4454 }
4455 } else if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
4456 /* type identifier */
4457 *v = tok;
4458 next();
4459 } else {
4460 if (!(td & TYPE_ABSTRACT))
4461 expect("identifier");
4462 *v = 0;
4463 }
4464 post_type(post, ad, storage, 0);
4465 parse_attribute(ad);
4466 type->t |= storage;
4467 return ret;
4468}
4469
4470/* compute the lvalue VT_LVAL_xxx needed to match type t. */
4471ST_FUNC int lvalue_type(int t)
4472{
4473 int bt, r;
4474 r = VT_LVAL;
4475 bt = t & VT_BTYPE;
4476 if (bt == VT_BYTE || bt == VT_BOOL)
4477 r |= VT_LVAL_BYTE;
4478 else if (bt == VT_SHORT)
4479 r |= VT_LVAL_SHORT;
4480 else
4481 return r;
4482 if (t & VT_UNSIGNED)
4483 r |= VT_LVAL_UNSIGNED;
4484 return r;
4485}
4486
4487/* indirection with full error checking and bound check */
4488ST_FUNC void indir(void)
4489{
4490 if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
4491 if ((vtop->type.t & VT_BTYPE) == VT_FUNC)
4492 return;
4493 expect("pointer");
4494 }
4495 if (vtop->r & VT_LVAL)
4496 gv(RC_INT);
4497 vtop->type = *pointed_type(&vtop->type);
4498 /* Arrays and functions are never lvalues */
4499 if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
4500 && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
4501 vtop->r |= lvalue_type(vtop->type.t);
4502 /* if bound checking, the referenced pointer must be checked */
4503#ifdef CONFIG_TCC_BCHECK
4504 if (tcc_state->do_bounds_check)
4505 vtop->r |= VT_MUSTBOUND;
4506#endif
4507 }
4508}
4509
4510/* pass a parameter to a function and do type checking and casting */
4511static void gfunc_param_typed(Sym *func, Sym *arg)
4512{
4513 int func_type;
4514 CType type;
4515
4516 func_type = func->f.func_type;
4517 if (func_type == FUNC_OLD ||
4518 (func_type == FUNC_ELLIPSIS && arg == NULL)) {
4519 /* default casting : only need to convert float to double */
4520 if ((vtop->type.t & VT_BTYPE) == VT_FLOAT) {
4521 gen_cast_s(VT_DOUBLE);
4522 } else if (vtop->type.t & VT_BITFIELD) {
4523 type.t = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
4524 type.ref = vtop->type.ref;
4525 gen_cast(&type);
4526 }
4527 } else if (arg == NULL) {
4528 tcc_error("too many arguments to function");
4529 } else {
4530 type = arg->type;
4531 type.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
4532 gen_assign_cast(&type);
4533 }
4534}
4535
4536/* parse an expression and return its type without any side effect. */
4537static void expr_type(CType *type, void (*expr_fn)(void))
4538{
4539 nocode_wanted++;
4540 expr_fn();
4541 *type = vtop->type;
4542 vpop();
4543 nocode_wanted--;
4544}
4545
4546/* parse an expression of the form '(type)' or '(expr)' and return its
4547 type */
4548static void parse_expr_type(CType *type)
4549{
4550 int n;
4551 AttributeDef ad;
4552
4553 skip('(');
4554 if (parse_btype(type, &ad)) {
4555 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4556 } else {
4557 expr_type(type, gexpr);
4558 }
4559 skip(')');
4560}
4561
4562static void parse_type(CType *type)
4563{
4564 AttributeDef ad;
4565 int n;
4566
4567 if (!parse_btype(type, &ad)) {
4568 expect("type");
4569 }
4570 type_decl(type, &ad, &n, TYPE_ABSTRACT);
4571}
4572
4573static void parse_builtin_params(int nc, const char *args)
4574{
4575 char c, sep = '(';
4576 CType t;
4577 if (nc)
4578 nocode_wanted++;
4579 next();
4580 while ((c = *args++)) {
4581 skip(sep);
4582 sep = ',';
4583 switch (c) {
4584 case 'e': expr_eq(); continue;
4585 case 't': parse_type(&t); vpush(&t); continue;
4586 default: tcc_error("internal error"); break;
4587 }
4588 }
4589 skip(')');
4590 if (nc)
4591 nocode_wanted--;
4592}
4593
4594ST_FUNC void unary(void)
4595{
4596 int n, t, align, size, r, sizeof_caller;
4597 CType type;
4598 Sym *s;
4599 AttributeDef ad;
4600
4601 sizeof_caller = in_sizeof;
4602 in_sizeof = 0;
4603 type.ref = NULL;
4604 /* XXX: GCC 2.95.3 does not generate a table although it should be
4605 better here */
4606 tok_next:
4607 switch(tok) {
4608 case TOK_EXTENSION:
4609 next();
4610 goto tok_next;
4611 case TOK_LCHAR:
4612#ifdef TCC_TARGET_PE
4613 t = VT_SHORT|VT_UNSIGNED;
4614 goto push_tokc;
4615#endif
4616 case TOK_CINT:
4617 case TOK_CCHAR:
4618 t = VT_INT;
4619 push_tokc:
4620 type.t = t;
4621 vsetc(&type, VT_CONST, &tokc);
4622 next();
4623 break;
4624 case TOK_CUINT:
4625 t = VT_INT | VT_UNSIGNED;
4626 goto push_tokc;
4627 case TOK_CLLONG:
4628 t = VT_LLONG;
4629 goto push_tokc;
4630 case TOK_CULLONG:
4631 t = VT_LLONG | VT_UNSIGNED;
4632 goto push_tokc;
4633 case TOK_CFLOAT:
4634 t = VT_FLOAT;
4635 goto push_tokc;
4636 case TOK_CDOUBLE:
4637 t = VT_DOUBLE;
4638 goto push_tokc;
4639 case TOK_CLDOUBLE:
4640 t = VT_LDOUBLE;
4641 goto push_tokc;
4642 case TOK_CLONG:
4643 t = (LONG_SIZE == 8 ? VT_LLONG : VT_INT) | VT_LONG;
4644 goto push_tokc;
4645 case TOK_CULONG:
4646 t = (LONG_SIZE == 8 ? VT_LLONG : VT_INT) | VT_LONG | VT_UNSIGNED;
4647 goto push_tokc;
4648 case TOK___FUNCTION__:
4649 if (!gnu_ext)
4650 goto tok_identifier;
4651 /* fall thru */
4652 case TOK___FUNC__:
4653 {
4654 void *ptr;
4655 int len;
4656 /* special function name identifier */
4657 len = strlen(funcname) + 1;
4658 /* generate char[len] type */
4659 type.t = VT_BYTE;
4660 mk_pointer(&type);
4661 type.t |= VT_ARRAY;
4662 type.ref->c = len;
4663 vpush_ref(&type, data_section, data_section->data_offset, len);
4664 if (!NODATA_WANTED) {
4665 ptr = section_ptr_add(data_section, len);
4666 memcpy(ptr, funcname, len);
4667 }
4668 next();
4669 }
4670 break;
4671 case TOK_LSTR:
4672#ifdef TCC_TARGET_PE
4673 t = VT_SHORT | VT_UNSIGNED;
4674#else
4675 t = VT_INT;
4676#endif
4677 goto str_init;
4678 case TOK_STR:
4679 /* string parsing */
4680 t = VT_BYTE;
4681 if (tcc_state->char_is_unsigned)
4682 t = VT_BYTE | VT_UNSIGNED;
4683 str_init:
4684 if (tcc_state->warn_write_strings)
4685 t |= VT_CONSTANT;
4686 type.t = t;
4687 mk_pointer(&type);
4688 type.t |= VT_ARRAY;
4689 memset(&ad, 0, sizeof(AttributeDef));
4690 decl_initializer_alloc(&type, &ad, VT_CONST, 2, 0, 0);
4691 break;
4692 case '(':
4693 next();
4694 /* cast ? */
4695 if (parse_btype(&type, &ad)) {
4696 type_decl(&type, &ad, &n, TYPE_ABSTRACT);
4697 skip(')');
4698 /* check ISOC99 compound literal */
4699 if (tok == '{') {
4700 /* data is allocated locally by default */
4701 if (global_expr)
4702 r = VT_CONST;
4703 else
4704 r = VT_LOCAL;
4705 /* all except arrays are lvalues */
4706 if (!(type.t & VT_ARRAY))
4707 r |= lvalue_type(type.t);
4708 memset(&ad, 0, sizeof(AttributeDef));
4709 decl_initializer_alloc(&type, &ad, r, 1, 0, 0);
4710 } else {
4711 if (sizeof_caller) {
4712 vpush(&type);
4713 return;
4714 }
4715 unary();
4716 gen_cast(&type);
4717 }
4718 } else if (tok == '{') {
4719 int saved_nocode_wanted = nocode_wanted;
4720 if (const_wanted)
4721 tcc_error("expected constant");
4722 /* save all registers */
4723 save_regs(0);
4724 /* statement expression : we do not accept break/continue
4725 inside as GCC does. We do retain the nocode_wanted state,
4726 as statement expressions can't ever be entered from the
4727 outside, so any reactivation of code emission (from labels
4728 or loop heads) can be disabled again after the end of it. */
4729 block(NULL, NULL, 1);
4730 nocode_wanted = saved_nocode_wanted;
4731 skip(')');
4732 } else {
4733 gexpr();
4734 skip(')');
4735 }
4736 break;
4737 case '*':
4738 next();
4739 unary();
4740 indir();
4741 break;
4742 case '&':
4743 next();
4744 unary();
4745 /* functions names must be treated as function pointers,
4746 except for unary '&' and sizeof. Since we consider that
4747 functions are not lvalues, we only have to handle it
4748 there and in function calls. */
4749 /* arrays can also be used although they are not lvalues */
4750 if ((vtop->type.t & VT_BTYPE) != VT_FUNC &&
4751 !(vtop->type.t & VT_ARRAY))
4752 test_lvalue();
4753 mk_pointer(&vtop->type);
4754 gaddrof();
4755 break;
4756 case '!':
4757 next();
4758 unary();
4759 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
4760 gen_cast_s(VT_BOOL);
4761 vtop->c.i = !vtop->c.i;
4762 } else if ((vtop->r & VT_VALMASK) == VT_CMP)
4763 vtop->c.i ^= 1;
4764 else {
4765 save_regs(1);
4766 vseti(VT_JMP, gvtst(1, 0));
4767 }
4768 break;
4769 case '~':
4770 next();
4771 unary();
4772 vpushi(-1);
4773 gen_op('^');
4774 break;
4775 case '+':
4776 next();
4777 unary();
4778 if ((vtop->type.t & VT_BTYPE) == VT_PTR)
4779 tcc_error("pointer not accepted for unary plus");
4780 /* In order to force cast, we add zero, except for floating point
4781 where we really need an noop (otherwise -0.0 will be transformed
4782 into +0.0). */
4783 if (!is_float(vtop->type.t)) {
4784 vpushi(0);
4785 gen_op('+');
4786 }
4787 break;
4788 case TOK_SIZEOF:
4789 case TOK_ALIGNOF1:
4790 case TOK_ALIGNOF2:
4791 t = tok;
4792 next();
4793 in_sizeof++;
4794 expr_type(&type, unary); /* Perform a in_sizeof = 0; */
4795 s = vtop[1].sym; /* hack: accessing previous vtop */
4796 size = type_size(&type, &align);
4797 if (s && s->a.aligned)
4798 align = 1 << (s->a.aligned - 1);
4799 if (t == TOK_SIZEOF) {
4800 if (!(type.t & VT_VLA)) {
4801 if (size < 0)
4802 tcc_error("sizeof applied to an incomplete type");
4803 vpushs(size);
4804 } else {
4805 vla_runtime_type_size(&type, &align);
4806 }
4807 } else {
4808 vpushs(align);
4809 }
4810 vtop->type.t |= VT_UNSIGNED;
4811 break;
4812
4813 case TOK_builtin_expect:
4814 /* __builtin_expect is a no-op for now */
4815 parse_builtin_params(0, "ee");
4816 vpop();
4817 break;
4818 case TOK_builtin_types_compatible_p:
4819 parse_builtin_params(0, "tt");
4820 vtop[-1].type.t &= ~(VT_CONSTANT | VT_VOLATILE);
4821 vtop[0].type.t &= ~(VT_CONSTANT | VT_VOLATILE);
4822 n = is_compatible_types(&vtop[-1].type, &vtop[0].type);
4823 vtop -= 2;
4824 vpushi(n);
4825 break;
4826 case TOK_builtin_choose_expr:
4827 {
4828 int64_t c;
4829 next();
4830 skip('(');
4831 c = expr_const64();
4832 skip(',');
4833 if (!c) {
4834 nocode_wanted++;
4835 }
4836 expr_eq();
4837 if (!c) {
4838 vpop();
4839 nocode_wanted--;
4840 }
4841 skip(',');
4842 if (c) {
4843 nocode_wanted++;
4844 }
4845 expr_eq();
4846 if (c) {
4847 vpop();
4848 nocode_wanted--;
4849 }
4850 skip(')');
4851 }
4852 break;
4853 case TOK_builtin_constant_p:
4854 parse_builtin_params(1, "e");
4855 n = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
4856 vtop--;
4857 vpushi(n);
4858 break;
4859 case TOK_builtin_frame_address:
4860 case TOK_builtin_return_address:
4861 {
4862 int tok1 = tok;
4863 int level;
4864 next();
4865 skip('(');
4866 if (tok != TOK_CINT) {
4867 tcc_error("%s only takes positive integers",
4868 tok1 == TOK_builtin_return_address ?
4869 "__builtin_return_address" :
4870 "__builtin_frame_address");
4871 }
4872 level = (uint32_t)tokc.i;
4873 next();
4874 skip(')');
4875 type.t = VT_VOID;
4876 mk_pointer(&type);
4877 vset(&type, VT_LOCAL, 0); /* local frame */
4878 while (level--) {
4879 mk_pointer(&vtop->type);
4880 indir(); /* -> parent frame */
4881 }
4882 if (tok1 == TOK_builtin_return_address) {
4883 // assume return address is just above frame pointer on stack
4884 vpushi(PTR_SIZE);
4885 gen_op('+');
4886 mk_pointer(&vtop->type);
4887 indir();
4888 }
4889 }
4890 break;
4891#ifdef TCC_TARGET_X86_64
4892#ifdef TCC_TARGET_PE
4893 case TOK_builtin_va_start:
4894 parse_builtin_params(0, "ee");
4895 r = vtop->r & VT_VALMASK;
4896 if (r == VT_LLOCAL)
4897 r = VT_LOCAL;
4898 if (r != VT_LOCAL)
4899 tcc_error("__builtin_va_start expects a local variable");
4900 vtop->r = r;
4901 vtop->type = char_pointer_type;
4902 vtop->c.i += 8;
4903 vstore();
4904 break;
4905#else
4906 case TOK_builtin_va_arg_types:
4907 parse_builtin_params(0, "t");
4908 vpushi(classify_x86_64_va_arg(&vtop->type));
4909 vswap();
4910 vpop();
4911 break;
4912#endif
4913#endif
4914
4915#ifdef TCC_TARGET_ARM64
4916 case TOK___va_start: {
4917 parse_builtin_params(0, "ee");
4918 //xx check types
4919 gen_va_start();
4920 vpushi(0);
4921 vtop->type.t = VT_VOID;
4922 break;
4923 }
4924 case TOK___va_arg: {
4925 parse_builtin_params(0, "et");
4926 type = vtop->type;
4927 vpop();
4928 //xx check types
4929 gen_va_arg(&type);
4930 vtop->type = type;
4931 break;
4932 }
4933 case TOK___arm64_clear_cache: {
4934 parse_builtin_params(0, "ee");
4935 gen_clear_cache();
4936 vpushi(0);
4937 vtop->type.t = VT_VOID;
4938 break;
4939 }
4940#endif
4941 /* pre operations */
4942 case TOK_INC:
4943 case TOK_DEC:
4944 t = tok;
4945 next();
4946 unary();
4947 inc(0, t);
4948 break;
4949 case '-':
4950 next();
4951 unary();
4952 t = vtop->type.t & VT_BTYPE;
4953 if (is_float(t)) {
4954 /* In IEEE negate(x) isn't subtract(0,x), but rather
4955 subtract(-0, x). */
4956 vpush(&vtop->type);
4957 if (t == VT_FLOAT)
4958 vtop->c.f = -1.0 * 0.0;
4959 else if (t == VT_DOUBLE)
4960 vtop->c.d = -1.0 * 0.0;
4961 else
4962 vtop->c.ld = -1.0 * 0.0;
4963 } else
4964 vpushi(0);
4965 vswap();
4966 gen_op('-');
4967 break;
4968 case TOK_LAND:
4969 if (!gnu_ext)
4970 goto tok_identifier;
4971 next();
4972 /* allow to take the address of a label */
4973 if (tok < TOK_UIDENT)
4974 expect("label identifier");
4975 s = label_find(tok);
4976 if (!s) {
4977 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
4978 } else {
4979 if (s->r == LABEL_DECLARED)
4980 s->r = LABEL_FORWARD;
4981 }
4982 if (!s->type.t) {
4983 s->type.t = VT_VOID;
4984 mk_pointer(&s->type);
4985 s->type.t |= VT_STATIC;
4986 }
4987 vpushsym(&s->type, s);
4988 next();
4989 break;
4990
4991 case TOK_GENERIC:
4992 {
4993 CType controlling_type;
4994 int has_default = 0;
4995 int has_match = 0;
4996 int learn = 0;
4997 TokenString *str = NULL;
4998
4999 next();
5000 skip('(');
5001 expr_type(&controlling_type, expr_eq);
5002 controlling_type.t &= ~(VT_CONSTANT | VT_VOLATILE | VT_ARRAY);
5003 for (;;) {
5004 learn = 0;
5005 skip(',');
5006 if (tok == TOK_DEFAULT) {
5007 if (has_default)
5008 tcc_error("too many 'default'");
5009 has_default = 1;
5010 if (!has_match)
5011 learn = 1;
5012 next();
5013 } else {
5014 AttributeDef ad_tmp;
5015 int itmp;
5016 CType cur_type;
5017 parse_btype(&cur_type, &ad_tmp);
5018 type_decl(&cur_type, &ad_tmp, &itmp, TYPE_ABSTRACT);
5019 if (compare_types(&controlling_type, &cur_type, 0)) {
5020 if (has_match) {
5021 tcc_error("type match twice");
5022 }
5023 has_match = 1;
5024 learn = 1;
5025 }
5026 }
5027 skip(':');
5028 if (learn) {
5029 if (str)
5030 tok_str_free(str);
5031 skip_or_save_block(&str);
5032 } else {
5033 skip_or_save_block(NULL);
5034 }
5035 if (tok == ')')
5036 break;
5037 }
5038 if (!str) {
5039 char buf[60];
5040 type_to_str(buf, sizeof buf, &controlling_type, NULL);
5041 tcc_error("type '%s' does not match any association", buf);
5042 }
5043 begin_macro(str, 1);
5044 next();
5045 expr_eq();
5046 if (tok != TOK_EOF)
5047 expect(",");
5048 end_macro();
5049 next();
5050 break;
5051 }
5052 // special qnan , snan and infinity values
5053 case TOK___NAN__:
5054 vpush64(VT_DOUBLE, 0x7ff8000000000000ULL);
5055 next();
5056 break;
5057 case TOK___SNAN__:
5058 vpush64(VT_DOUBLE, 0x7ff0000000000001ULL);
5059 next();
5060 break;
5061 case TOK___INF__:
5062 vpush64(VT_DOUBLE, 0x7ff0000000000000ULL);
5063 next();
5064 break;
5065
5066 default:
5067 tok_identifier:
5068 t = tok;
5069 next();
5070 if (t < TOK_UIDENT)
5071 expect("identifier");
5072 s = sym_find(t);
5073 if (!s || IS_ASM_SYM(s)) {
5074 const char *name = get_tok_str(t, NULL);
5075 if (tok != '(')
5076 tcc_error("'%s' undeclared", name);
5077 /* for simple function calls, we tolerate undeclared
5078 external reference to int() function */
5079 if (tcc_state->warn_implicit_function_declaration
5080#ifdef TCC_TARGET_PE
5081 /* people must be warned about using undeclared WINAPI functions
5082 (which usually start with uppercase letter) */
5083 || (name[0] >= 'A' && name[0] <= 'Z')
5084#endif
5085 )
5086 tcc_warning("implicit declaration of function '%s'", name);
5087 s = external_global_sym(t, &func_old_type, 0);
5088 }
5089
5090 r = s->r;
5091 /* A symbol that has a register is a local register variable,
5092 which starts out as VT_LOCAL value. */
5093 if ((r & VT_VALMASK) < VT_CONST)
5094 r = (r & ~VT_VALMASK) | VT_LOCAL;
5095
5096 vset(&s->type, r, s->c);
5097 /* Point to s as backpointer (even without r&VT_SYM).
5098 Will be used by at least the x86 inline asm parser for
5099 regvars. */
5100 vtop->sym = s;
5101
5102 if (r & VT_SYM) {
5103 vtop->c.i = 0;
5104 } else if (r == VT_CONST && IS_ENUM_VAL(s->type.t)) {
5105 vtop->c.i = s->enum_val;
5106 }
5107 break;
5108 }
5109
5110 /* post operations */
5111 while (1) {
5112 if (tok == TOK_INC || tok == TOK_DEC) {
5113 inc(1, tok);
5114 next();
5115 } else if (tok == '.' || tok == TOK_ARROW || tok == TOK_CDOUBLE) {
5116 int qualifiers;
5117 /* field */
5118 if (tok == TOK_ARROW)
5119 indir();
5120 qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
5121 test_lvalue();
5122 gaddrof();
5123 /* expect pointer on structure */
5124 if ((vtop->type.t & VT_BTYPE) != VT_STRUCT)
5125 expect("struct or union");
5126 if (tok == TOK_CDOUBLE)
5127 expect("field name");
5128 next();
5129 if (tok == TOK_CINT || tok == TOK_CUINT)
5130 expect("field name");
5131 s = find_field(&vtop->type, tok);
5132 if (!s)
5133 tcc_error("field not found: %s", get_tok_str(tok & ~SYM_FIELD, &tokc));
5134 /* add field offset to pointer */
5135 vtop->type = char_pointer_type; /* change type to 'char *' */
5136 vpushi(s->c);
5137 gen_op('+');
5138 /* change type to field type, and set to lvalue */
5139 vtop->type = s->type;
5140 vtop->type.t |= qualifiers;
5141 /* an array is never an lvalue */
5142 if (!(vtop->type.t & VT_ARRAY)) {
5143 vtop->r |= lvalue_type(vtop->type.t);
5144#ifdef CONFIG_TCC_BCHECK
5145 /* if bound checking, the referenced pointer must be checked */
5146 if (tcc_state->do_bounds_check && (vtop->r & VT_VALMASK) != VT_LOCAL)
5147 vtop->r |= VT_MUSTBOUND;
5148#endif
5149 }
5150 next();
5151 } else if (tok == '[') {
5152 next();
5153 gexpr();
5154 gen_op('+');
5155 indir();
5156 skip(']');
5157 } else if (tok == '(') {
5158 SValue ret;
5159 Sym *sa;
5160 int nb_args, ret_nregs, ret_align, regsize, variadic;
5161
5162 /* function call */
5163 if ((vtop->type.t & VT_BTYPE) != VT_FUNC) {
5164 /* pointer test (no array accepted) */
5165 if ((vtop->type.t & (VT_BTYPE | VT_ARRAY)) == VT_PTR) {
5166 vtop->type = *pointed_type(&vtop->type);
5167 if ((vtop->type.t & VT_BTYPE) != VT_FUNC)
5168 goto error_func;
5169 } else {
5170 error_func:
5171 expect("function pointer");
5172 }
5173 } else {
5174 vtop->r &= ~VT_LVAL; /* no lvalue */
5175 }
5176 /* get return type */
5177 s = vtop->type.ref;
5178 next();
5179 sa = s->next; /* first parameter */
5180 nb_args = regsize = 0;
5181 ret.r2 = VT_CONST;
5182 /* compute first implicit argument if a structure is returned */
5183 if ((s->type.t & VT_BTYPE) == VT_STRUCT) {
5184 variadic = (s->f.func_type == FUNC_ELLIPSIS);
5185 ret_nregs = gfunc_sret(&s->type, variadic, &ret.type,
5186 &ret_align, &regsize);
5187 if (!ret_nregs) {
5188 /* get some space for the returned structure */
5189 size = type_size(&s->type, &align);
5190#ifdef TCC_TARGET_ARM64
5191 /* On arm64, a small struct is return in registers.
5192 It is much easier to write it to memory if we know
5193 that we are allowed to write some extra bytes, so
5194 round the allocated space up to a power of 2: */
5195 if (size < 16)
5196 while (size & (size - 1))
5197 size = (size | (size - 1)) + 1;
5198#endif
5199 loc = (loc - size) & -align;
5200 ret.type = s->type;
5201 ret.r = VT_LOCAL | VT_LVAL;
5202 /* pass it as 'int' to avoid structure arg passing
5203 problems */
5204 vseti(VT_LOCAL, loc);
5205 ret.c = vtop->c;
5206 nb_args++;
5207 }
5208 } else {
5209 ret_nregs = 1;
5210 ret.type = s->type;
5211 }
5212
5213 if (ret_nregs) {
5214 /* return in register */
5215 if (is_float(ret.type.t)) {
5216 ret.r = reg_fret(ret.type.t);
5217#ifdef TCC_TARGET_X86_64
5218 if ((ret.type.t & VT_BTYPE) == VT_QFLOAT)
5219 ret.r2 = REG_QRET;
5220#endif
5221 } else {
5222#ifndef TCC_TARGET_ARM64
5223#ifdef TCC_TARGET_X86_64
5224 if ((ret.type.t & VT_BTYPE) == VT_QLONG)
5225#else
5226 if ((ret.type.t & VT_BTYPE) == VT_LLONG)
5227#endif
5228 ret.r2 = REG_LRET;
5229#endif
5230 ret.r = REG_IRET;
5231 }
5232 ret.c.i = 0;
5233 }
5234 if (tok != ')') {
5235 for(;;) {
5236 expr_eq();
5237 gfunc_param_typed(s, sa);
5238 nb_args++;
5239 if (sa)
5240 sa = sa->next;
5241 if (tok == ')')
5242 break;
5243 skip(',');
5244 }
5245 }
5246 if (sa)
5247 tcc_error("too few arguments to function");
5248 skip(')');
5249 gfunc_call(nb_args);
5250
5251 /* return value */
5252 for (r = ret.r + ret_nregs + !ret_nregs; r-- > ret.r;) {
5253 vsetc(&ret.type, r, &ret.c);
5254 vtop->r2 = ret.r2; /* Loop only happens when r2 is VT_CONST */
5255 }
5256
5257 /* handle packed struct return */
5258 if (((s->type.t & VT_BTYPE) == VT_STRUCT) && ret_nregs) {
5259 int addr, offset;
5260
5261 size = type_size(&s->type, &align);
5262 /* We're writing whole regs often, make sure there's enough
5263 space. Assume register size is power of 2. */
5264 if (regsize > align)
5265 align = regsize;
5266 loc = (loc - size) & -align;
5267 addr = loc;
5268 offset = 0;
5269 for (;;) {
5270 vset(&ret.type, VT_LOCAL | VT_LVAL, addr + offset);
5271 vswap();
5272 vstore();
5273 vtop--;
5274 if (--ret_nregs == 0)
5275 break;
5276 offset += regsize;
5277 }
5278 vset(&s->type, VT_LOCAL | VT_LVAL, addr);
5279 }
5280 } else {
5281 break;
5282 }
5283 }
5284}
5285
5286ST_FUNC void expr_prod(void)
5287{
5288 int t;
5289
5290 unary();
5291 while (tok == '*' || tok == '/' || tok == '%') {
5292 t = tok;
5293 next();
5294 unary();
5295 gen_op(t);
5296 }
5297}
5298
5299ST_FUNC void expr_sum(void)
5300{
5301 int t;
5302
5303 expr_prod();
5304 while (tok == '+' || tok == '-') {
5305 t = tok;
5306 next();
5307 expr_prod();
5308 gen_op(t);
5309 }
5310}
5311
5312static void expr_shift(void)
5313{
5314 int t;
5315
5316 expr_sum();
5317 while (tok == TOK_SHL || tok == TOK_SAR) {
5318 t = tok;
5319 next();
5320 expr_sum();
5321 gen_op(t);
5322 }
5323}
5324
5325static void expr_cmp(void)
5326{
5327 int t;
5328
5329 expr_shift();
5330 while ((tok >= TOK_ULE && tok <= TOK_GT) ||
5331 tok == TOK_ULT || tok == TOK_UGE) {
5332 t = tok;
5333 next();
5334 expr_shift();
5335 gen_op(t);
5336 }
5337}
5338
5339static void expr_cmpeq(void)
5340{
5341 int t;
5342
5343 expr_cmp();
5344 while (tok == TOK_EQ || tok == TOK_NE) {
5345 t = tok;
5346 next();
5347 expr_cmp();
5348 gen_op(t);
5349 }
5350}
5351
5352static void expr_and(void)
5353{
5354 expr_cmpeq();
5355 while (tok == '&') {
5356 next();
5357 expr_cmpeq();
5358 gen_op('&');
5359 }
5360}
5361
5362static void expr_xor(void)
5363{
5364 expr_and();
5365 while (tok == '^') {
5366 next();
5367 expr_and();
5368 gen_op('^');
5369 }
5370}
5371
5372static void expr_or(void)
5373{
5374 expr_xor();
5375 while (tok == '|') {
5376 next();
5377 expr_xor();
5378 gen_op('|');
5379 }
5380}
5381
5382static void expr_land(void)
5383{
5384 expr_or();
5385 if (tok == TOK_LAND) {
5386 int t = 0;
5387 for(;;) {
5388 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5389 gen_cast_s(VT_BOOL);
5390 if (vtop->c.i) {
5391 vpop();
5392 } else {
5393 nocode_wanted++;
5394 while (tok == TOK_LAND) {
5395 next();
5396 expr_or();
5397 vpop();
5398 }
5399 nocode_wanted--;
5400 if (t)
5401 gsym(t);
5402 gen_cast_s(VT_INT);
5403 break;
5404 }
5405 } else {
5406 if (!t)
5407 save_regs(1);
5408 t = gvtst(1, t);
5409 }
5410 if (tok != TOK_LAND) {
5411 if (t)
5412 vseti(VT_JMPI, t);
5413 else
5414 vpushi(1);
5415 break;
5416 }
5417 next();
5418 expr_or();
5419 }
5420 }
5421}
5422
5423static void expr_lor(void)
5424{
5425 expr_land();
5426 if (tok == TOK_LOR) {
5427 int t = 0;
5428 for(;;) {
5429 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
5430 gen_cast_s(VT_BOOL);
5431 if (!vtop->c.i) {
5432 vpop();
5433 } else {
5434 nocode_wanted++;
5435 while (tok == TOK_LOR) {
5436 next();
5437 expr_land();
5438 vpop();
5439 }
5440 nocode_wanted--;
5441 if (t)
5442 gsym(t);
5443 gen_cast_s(VT_INT);
5444 break;
5445 }
5446 } else {
5447 if (!t)
5448 save_regs(1);
5449 t = gvtst(0, t);
5450 }
5451 if (tok != TOK_LOR) {
5452 if (t)
5453 vseti(VT_JMP, t);
5454 else
5455 vpushi(0);
5456 break;
5457 }
5458 next();
5459 expr_land();
5460 }
5461 }
5462}
5463
5464/* Assuming vtop is a value used in a conditional context
5465 (i.e. compared with zero) return 0 if it's false, 1 if
5466 true and -1 if it can't be statically determined. */
5467static int condition_3way(void)
5468{
5469 int c = -1;
5470 if ((vtop->r & (VT_VALMASK | VT_LVAL)) == VT_CONST &&
5471 (!(vtop->r & VT_SYM) || !vtop->sym->a.weak)) {
5472 vdup();
5473 gen_cast_s(VT_BOOL);
5474 c = vtop->c.i;
5475 vpop();
5476 }
5477 return c;
5478}
5479
5480static void expr_cond(void)
5481{
5482 int tt, u, r1, r2, rc, t1, t2, bt1, bt2, islv, c, g;
5483 SValue sv;
5484 CType type, type1, type2;
5485
5486 expr_lor();
5487 if (tok == '?') {
5488 next();
5489 c = condition_3way();
5490 g = (tok == ':' && gnu_ext);
5491 if (c < 0) {
5492 /* needed to avoid having different registers saved in
5493 each branch */
5494 if (is_float(vtop->type.t)) {
5495 rc = RC_FLOAT;
5496#ifdef TCC_TARGET_X86_64
5497 if ((vtop->type.t & VT_BTYPE) == VT_LDOUBLE) {
5498 rc = RC_ST0;
5499 }
5500#endif
5501 } else
5502 rc = RC_INT;
5503 gv(rc);
5504 save_regs(1);
5505 if (g)
5506 gv_dup();
5507 tt = gvtst(1, 0);
5508
5509 } else {
5510 if (!g)
5511 vpop();
5512 tt = 0;
5513 }
5514
5515 if (1) {
5516 if (c == 0)
5517 nocode_wanted++;
5518 if (!g)
5519 gexpr();
5520
5521 type1 = vtop->type;
5522 sv = *vtop; /* save value to handle it later */
5523 vtop--; /* no vpop so that FP stack is not flushed */
5524 skip(':');
5525
5526 u = 0;
5527 if (c < 0)
5528 u = gjmp(0);
5529 gsym(tt);
5530
5531 if (c == 0)
5532 nocode_wanted--;
5533 if (c == 1)
5534 nocode_wanted++;
5535 expr_cond();
5536 if (c == 1)
5537 nocode_wanted--;
5538
5539 type2 = vtop->type;
5540 t1 = type1.t;
5541 bt1 = t1 & VT_BTYPE;
5542 t2 = type2.t;
5543 bt2 = t2 & VT_BTYPE;
5544 type.ref = NULL;
5545
5546 /* cast operands to correct type according to ISOC rules */
5547 if (is_float(bt1) || is_float(bt2)) {
5548 if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
5549 type.t = VT_LDOUBLE;
5550
5551 } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
5552 type.t = VT_DOUBLE;
5553 } else {
5554 type.t = VT_FLOAT;
5555 }
5556 } else if (bt1 == VT_LLONG || bt2 == VT_LLONG) {
5557 /* cast to biggest op */
5558 type.t = VT_LLONG | VT_LONG;
5559 if (bt1 == VT_LLONG)
5560 type.t &= t1;
5561 if (bt2 == VT_LLONG)
5562 type.t &= t2;
5563 /* convert to unsigned if it does not fit in a long long */
5564 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED) ||
5565 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_LLONG | VT_UNSIGNED))
5566 type.t |= VT_UNSIGNED;
5567 } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
5568 /* If one is a null ptr constant the result type
5569 is the other. */
5570 if (is_null_pointer (vtop))
5571 type = type1;
5572 else if (is_null_pointer (&sv))
5573 type = type2;
5574 /* XXX: test pointer compatibility, C99 has more elaborate
5575 rules here. */
5576 else
5577 type = type1;
5578 } else if (bt1 == VT_FUNC || bt2 == VT_FUNC) {
5579 /* XXX: test function pointer compatibility */
5580 type = bt1 == VT_FUNC ? type1 : type2;
5581 } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
5582 /* XXX: test structure compatibility */
5583 type = bt1 == VT_STRUCT ? type1 : type2;
5584 } else if (bt1 == VT_VOID || bt2 == VT_VOID) {
5585 /* NOTE: as an extension, we accept void on only one side */
5586 type.t = VT_VOID;
5587 } else {
5588 /* integer operations */
5589 type.t = VT_INT | (VT_LONG & (t1 | t2));
5590 /* convert to unsigned if it does not fit in an integer */
5591 if ((t1 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED) ||
5592 (t2 & (VT_BTYPE | VT_UNSIGNED | VT_BITFIELD)) == (VT_INT | VT_UNSIGNED))
5593 type.t |= VT_UNSIGNED;
5594 }
5595 /* keep structs lvalue by transforming `(expr ? a : b)` to `*(expr ? &a : &b)` so
5596 that `(expr ? a : b).mem` does not error with "lvalue expected" */
5597 islv = (vtop->r & VT_LVAL) && (sv.r & VT_LVAL) && VT_STRUCT == (type.t & VT_BTYPE);
5598 islv &= c < 0;
5599
5600 /* now we convert second operand */
5601 if (c != 1) {
5602 gen_cast(&type);
5603 if (islv) {
5604 mk_pointer(&vtop->type);
5605 gaddrof();
5606 } else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5607 gaddrof();
5608 }
5609
5610 rc = RC_INT;
5611 if (is_float(type.t)) {
5612 rc = RC_FLOAT;
5613#ifdef TCC_TARGET_X86_64
5614 if ((type.t & VT_BTYPE) == VT_LDOUBLE) {
5615 rc = RC_ST0;
5616 }
5617#endif
5618 } else if ((type.t & VT_BTYPE) == VT_LLONG) {
5619 /* for long longs, we use fixed registers to avoid having
5620 to handle a complicated move */
5621 rc = RC_IRET;
5622 }
5623
5624 tt = r2 = 0;
5625 if (c < 0) {
5626 r2 = gv(rc);
5627 tt = gjmp(0);
5628 }
5629 gsym(u);
5630
5631 /* this is horrible, but we must also convert first
5632 operand */
5633 if (c != 0) {
5634 *vtop = sv;
5635 gen_cast(&type);
5636 if (islv) {
5637 mk_pointer(&vtop->type);
5638 gaddrof();
5639 } else if (VT_STRUCT == (vtop->type.t & VT_BTYPE))
5640 gaddrof();
5641 }
5642
5643 if (c < 0) {
5644 r1 = gv(rc);
5645 move_reg(r2, r1, type.t);
5646 vtop->r = r2;
5647 gsym(tt);
5648 if (islv)
5649 indir();
5650 }
5651 }
5652 }
5653}
5654
5655static void expr_eq(void)
5656{
5657 int t;
5658
5659 expr_cond();
5660 if (tok == '=' ||
5661 (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
5662 tok == TOK_A_XOR || tok == TOK_A_OR ||
5663 tok == TOK_A_SHL || tok == TOK_A_SAR) {
5664 test_lvalue();
5665 t = tok;
5666 next();
5667 if (t == '=') {
5668 expr_eq();
5669 } else {
5670 vdup();
5671 expr_eq();
5672 gen_op(t & 0x7f);
5673 }
5674 vstore();
5675 }
5676}
5677
5678ST_FUNC void gexpr(void)
5679{
5680 while (1) {
5681 expr_eq();
5682 if (tok != ',')
5683 break;
5684 vpop();
5685 next();
5686 }
5687}
5688
5689/* parse a constant expression and return value in vtop. */
5690static void expr_const1(void)
5691{
5692 const_wanted++;
5693 nocode_wanted++;
5694 expr_cond();
5695 nocode_wanted--;
5696 const_wanted--;
5697}
5698
5699/* parse an integer constant and return its value. */
5700static inline int64_t expr_const64(void)
5701{
5702 int64_t c;
5703 expr_const1();
5704 if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST)
5705 expect("constant expression");
5706 c = vtop->c.i;
5707 vpop();
5708 return c;
5709}
5710
5711/* parse an integer constant and return its value.
5712 Complain if it doesn't fit 32bit (signed or unsigned). */
5713ST_FUNC int expr_const(void)
5714{
5715 int c;
5716 int64_t wc = expr_const64();
5717 c = wc;
5718 if (c != wc && (unsigned)c != wc)
5719 tcc_error("constant exceeds 32 bit");
5720 return c;
5721}
5722
5723/* return the label token if current token is a label, otherwise
5724 return zero */
5725static int is_label(void)
5726{
5727 int last_tok;
5728
5729 /* fast test first */
5730 if (tok < TOK_UIDENT)
5731 return 0;
5732 /* no need to save tokc because tok is an identifier */
5733 last_tok = tok;
5734 next();
5735 if (tok == ':') {
5736 return last_tok;
5737 } else {
5738 unget_tok(last_tok);
5739 return 0;
5740 }
5741}
5742
5743#ifndef TCC_TARGET_ARM64
5744static void gfunc_return(CType *func_type)
5745{
5746 if ((func_type->t & VT_BTYPE) == VT_STRUCT) {
5747 CType type, ret_type;
5748 int ret_align, ret_nregs, regsize;
5749 ret_nregs = gfunc_sret(func_type, func_var, &ret_type,
5750 &ret_align, &regsize);
5751 if (0 == ret_nregs) {
5752 /* if returning structure, must copy it to implicit
5753 first pointer arg location */
5754 type = *func_type;
5755 mk_pointer(&type);
5756 vset(&type, VT_LOCAL | VT_LVAL, func_vc);
5757 indir();
5758 vswap();
5759 /* copy structure value to pointer */
5760 vstore();
5761 } else {
5762 /* returning structure packed into registers */
5763 int r, size, addr, align;
5764 size = type_size(func_type,&align);
5765 if ((vtop->r != (VT_LOCAL | VT_LVAL) ||
5766 (vtop->c.i & (ret_align-1)))
5767 && (align & (ret_align-1))) {
5768 loc = (loc - size) & -ret_align;
5769 addr = loc;
5770 type = *func_type;
5771 vset(&type, VT_LOCAL | VT_LVAL, addr);
5772 vswap();
5773 vstore();
5774 vpop();
5775 vset(&ret_type, VT_LOCAL | VT_LVAL, addr);
5776 }
5777 vtop->type = ret_type;
5778 if (is_float(ret_type.t))
5779 r = rc_fret(ret_type.t);
5780 else
5781 r = RC_IRET;
5782
5783 if (ret_nregs == 1)
5784 gv(r);
5785 else {
5786 for (;;) {
5787 vdup();
5788 gv(r);
5789 vpop();
5790 if (--ret_nregs == 0)
5791 break;
5792 /* We assume that when a structure is returned in multiple
5793 registers, their classes are consecutive values of the
5794 suite s(n) = 2^n */
5795 r <<= 1;
5796 vtop->c.i += regsize;
5797 }
5798 }
5799 }
5800 } else if (is_float(func_type->t)) {
5801 gv(rc_fret(func_type->t));
5802 } else {
5803 gv(RC_IRET);
5804 }
5805 vtop--; /* NOT vpop() because on x86 it would flush the fp stack */
5806}
5807#endif
5808
5809static int case_cmp(const void *pa, const void *pb)
5810{
5811 int64_t a = (*(struct case_t**) pa)->v1;
5812 int64_t b = (*(struct case_t**) pb)->v1;
5813 return a < b ? -1 : a > b;
5814}
5815
5816static void gcase(struct case_t **base, int len, int *bsym)
5817{
5818 struct case_t *p;
5819 int e;
5820 int ll = (vtop->type.t & VT_BTYPE) == VT_LLONG;
5821 gv(RC_INT);
5822 while (len > 4) {
5823 /* binary search */
5824 p = base[len/2];
5825 vdup();
5826 if (ll)
5827 vpushll(p->v2);
5828 else
5829 vpushi(p->v2);
5830 gen_op(TOK_LE);
5831 e = gtst(1, 0);
5832 vdup();
5833 if (ll)
5834 vpushll(p->v1);
5835 else
5836 vpushi(p->v1);
5837 gen_op(TOK_GE);
5838 gtst_addr(0, p->sym); /* v1 <= x <= v2 */
5839 /* x < v1 */
5840 gcase(base, len/2, bsym);
5841 if (cur_switch->def_sym)
5842 gjmp_addr(cur_switch->def_sym);
5843 else
5844 *bsym = gjmp(*bsym);
5845 /* x > v2 */
5846 gsym(e);
5847 e = len/2 + 1;
5848 base += e; len -= e;
5849 }
5850 /* linear scan */
5851 while (len--) {
5852 p = *base++;
5853 vdup();
5854 if (ll)
5855 vpushll(p->v2);
5856 else
5857 vpushi(p->v2);
5858 if (p->v1 == p->v2) {
5859 gen_op(TOK_EQ);
5860 gtst_addr(0, p->sym);
5861 } else {
5862 gen_op(TOK_LE);
5863 e = gtst(1, 0);
5864 vdup();
5865 if (ll)
5866 vpushll(p->v1);
5867 else
5868 vpushi(p->v1);
5869 gen_op(TOK_GE);
5870 gtst_addr(0, p->sym);
5871 gsym(e);
5872 }
5873 }
5874}
5875
5876static void block(int *bsym, int *csym, int is_expr)
5877{
5878 int a, b, c, d, cond;
5879 Sym *s;
5880
5881 /* generate line number info */
5882 if (tcc_state->do_debug)
5883 tcc_debug_line(tcc_state);
5884
5885 if (is_expr) {
5886 /* default return value is (void) */
5887 vpushi(0);
5888 vtop->type.t = VT_VOID;
5889 }
5890
5891 if (tok == TOK_IF) {
5892 /* if test */
5893 int saved_nocode_wanted = nocode_wanted;
5894 next();
5895 skip('(');
5896 gexpr();
5897 skip(')');
5898 cond = condition_3way();
5899 if (cond == 1)
5900 a = 0, vpop();
5901 else
5902 a = gvtst(1, 0);
5903 if (cond == 0)
5904 nocode_wanted |= 0x20000000;
5905 block(bsym, csym, 0);
5906 if (cond != 1)
5907 nocode_wanted = saved_nocode_wanted;
5908 c = tok;
5909 if (c == TOK_ELSE) {
5910 next();
5911 d = gjmp(0);
5912 gsym(a);
5913 if (cond == 1)
5914 nocode_wanted |= 0x20000000;
5915 block(bsym, csym, 0);
5916 gsym(d); /* patch else jmp */
5917 if (cond != 0)
5918 nocode_wanted = saved_nocode_wanted;
5919 } else
5920 gsym(a);
5921 } else if (tok == TOK_WHILE) {
5922 int saved_nocode_wanted;
5923 nocode_wanted &= ~0x20000000;
5924 next();
5925 d = ind;
5926 vla_sp_restore();
5927 skip('(');
5928 gexpr();
5929 skip(')');
5930 a = gvtst(1, 0);
5931 b = 0;
5932 ++local_scope;
5933 saved_nocode_wanted = nocode_wanted;
5934 block(&a, &b, 0);
5935 nocode_wanted = saved_nocode_wanted;
5936 --local_scope;
5937 gjmp_addr(d);
5938 gsym(a);
5939 gsym_addr(b, d);
5940 } else if (tok == '{') {
5941 Sym *llabel;
5942 int block_vla_sp_loc = vla_sp_loc, saved_vlas_in_scope = vlas_in_scope;
5943
5944 next();
5945 /* record local declaration stack position */
5946 s = local_stack;
5947 llabel = local_label_stack;
5948 ++local_scope;
5949
5950 /* handle local labels declarations */
5951 if (tok == TOK_LABEL) {
5952 next();
5953 for(;;) {
5954 if (tok < TOK_UIDENT)
5955 expect("label identifier");
5956 label_push(&local_label_stack, tok, LABEL_DECLARED);
5957 next();
5958 if (tok == ',') {
5959 next();
5960 } else {
5961 skip(';');
5962 break;
5963 }
5964 }
5965 }
5966 while (tok != '}') {
5967 if ((a = is_label()))
5968 unget_tok(a);
5969 else
5970 decl(VT_LOCAL);
5971 if (tok != '}') {
5972 if (is_expr)
5973 vpop();
5974 block(bsym, csym, is_expr);
5975 }
5976 }
5977 /* pop locally defined labels */
5978 label_pop(&local_label_stack, llabel, is_expr);
5979 /* pop locally defined symbols */
5980 --local_scope;
5981 /* In the is_expr case (a statement expression is finished here),
5982 vtop might refer to symbols on the local_stack. Either via the
5983 type or via vtop->sym. We can't pop those nor any that in turn
5984 might be referred to. To make it easier we don't roll back
5985 any symbols in that case; some upper level call to block() will
5986 do that. We do have to remove such symbols from the lookup
5987 tables, though. sym_pop will do that. */
5988 sym_pop(&local_stack, s, is_expr);
5989
5990 /* Pop VLA frames and restore stack pointer if required */
5991 if (vlas_in_scope > saved_vlas_in_scope) {
5992 vla_sp_loc = saved_vlas_in_scope ? block_vla_sp_loc : vla_sp_root_loc;
5993 vla_sp_restore();
5994 }
5995 vlas_in_scope = saved_vlas_in_scope;
5996
5997 next();
5998 } else if (tok == TOK_RETURN) {
5999 next();
6000 if (tok != ';') {
6001 gexpr();
6002 gen_assign_cast(&func_vt);
6003 if ((func_vt.t & VT_BTYPE) == VT_VOID)
6004 vtop--;
6005 else
6006 gfunc_return(&func_vt);
6007 }
6008 skip(';');
6009 /* jump unless last stmt in top-level block */
6010 if (tok != '}' || local_scope != 1)
6011 rsym = gjmp(rsym);
6012 nocode_wanted |= 0x20000000;
6013 } else if (tok == TOK_BREAK) {
6014 /* compute jump */
6015 if (!bsym)
6016 tcc_error("cannot break");
6017 *bsym = gjmp(*bsym);
6018 next();
6019 skip(';');
6020 nocode_wanted |= 0x20000000;
6021 } else if (tok == TOK_CONTINUE) {
6022 /* compute jump */
6023 if (!csym)
6024 tcc_error("cannot continue");
6025 vla_sp_restore_root();
6026 *csym = gjmp(*csym);
6027 next();
6028 skip(';');
6029 } else if (tok == TOK_FOR) {
6030 int e;
6031 int saved_nocode_wanted;
6032 nocode_wanted &= ~0x20000000;
6033 next();
6034 skip('(');
6035 s = local_stack;
6036 ++local_scope;
6037 if (tok != ';') {
6038 /* c99 for-loop init decl? */
6039 if (!decl0(VT_LOCAL, 1, NULL)) {
6040 /* no, regular for-loop init expr */
6041 gexpr();
6042 vpop();
6043 }
6044 }
6045 skip(';');
6046 d = ind;
6047 c = ind;
6048 vla_sp_restore();
6049 a = 0;
6050 b = 0;
6051 if (tok != ';') {
6052 gexpr();
6053 a = gvtst(1, 0);
6054 }
6055 skip(';');
6056 if (tok != ')') {
6057 e = gjmp(0);
6058 c = ind;
6059 vla_sp_restore();
6060 gexpr();
6061 vpop();
6062 gjmp_addr(d);
6063 gsym(e);
6064 }
6065 skip(')');
6066 saved_nocode_wanted = nocode_wanted;
6067 block(&a, &b, 0);
6068 nocode_wanted = saved_nocode_wanted;
6069 gjmp_addr(c);
6070 gsym(a);
6071 gsym_addr(b, c);
6072 --local_scope;
6073 sym_pop(&local_stack, s, 0);
6074
6075 } else
6076 if (tok == TOK_DO) {
6077 int saved_nocode_wanted;
6078 nocode_wanted &= ~0x20000000;
6079 next();
6080 a = 0;
6081 b = 0;
6082 d = ind;
6083 vla_sp_restore();
6084 saved_nocode_wanted = nocode_wanted;
6085 block(&a, &b, 0);
6086 skip(TOK_WHILE);
6087 skip('(');
6088 gsym(b);
6089 gexpr();
6090 c = gvtst(0, 0);
6091 gsym_addr(c, d);
6092 nocode_wanted = saved_nocode_wanted;
6093 skip(')');
6094 gsym(a);
6095 skip(';');
6096 } else
6097 if (tok == TOK_SWITCH) {
6098 struct switch_t *saved, sw;
6099 int saved_nocode_wanted = nocode_wanted;
6100 SValue switchval;
6101 next();
6102 skip('(');
6103 gexpr();
6104 skip(')');
6105 switchval = *vtop--;
6106 a = 0;
6107 b = gjmp(0); /* jump to first case */
6108 sw.p = NULL; sw.n = 0; sw.def_sym = 0;
6109 saved = cur_switch;
6110 cur_switch = &sw;
6111 block(&a, csym, 0);
6112 nocode_wanted = saved_nocode_wanted;
6113 a = gjmp(a); /* add implicit break */
6114 /* case lookup */
6115 gsym(b);
6116 qsort(sw.p, sw.n, sizeof(void*), case_cmp);
6117 for (b = 1; b < sw.n; b++)
6118 if (sw.p[b - 1]->v2 >= sw.p[b]->v1)
6119 tcc_error("duplicate case value");
6120 /* Our switch table sorting is signed, so the compared
6121 value needs to be as well when it's 64bit. */
6122 if ((switchval.type.t & VT_BTYPE) == VT_LLONG)
6123 switchval.type.t &= ~VT_UNSIGNED;
6124 vpushv(&switchval);
6125 gcase(sw.p, sw.n, &a);
6126 vpop();
6127 if (sw.def_sym)
6128 gjmp_addr(sw.def_sym);
6129 dynarray_reset(&sw.p, &sw.n);
6130 cur_switch = saved;
6131 /* break label */
6132 gsym(a);
6133 } else
6134 if (tok == TOK_CASE) {
6135 struct case_t *cr = tcc_malloc(sizeof(struct case_t));
6136 if (!cur_switch)
6137 expect("switch");
6138 nocode_wanted &= ~0x20000000;
6139 next();
6140 cr->v1 = cr->v2 = expr_const64();
6141 if (gnu_ext && tok == TOK_DOTS) {
6142 next();
6143 cr->v2 = expr_const64();
6144 if (cr->v2 < cr->v1)
6145 tcc_warning("empty case range");
6146 }
6147 cr->sym = ind;
6148 dynarray_add(&cur_switch->p, &cur_switch->n, cr);
6149 skip(':');
6150 is_expr = 0;
6151 goto block_after_label;
6152 } else
6153 if (tok == TOK_DEFAULT) {
6154 next();
6155 skip(':');
6156 if (!cur_switch)
6157 expect("switch");
6158 if (cur_switch->def_sym)
6159 tcc_error("too many 'default'");
6160 cur_switch->def_sym = ind;
6161 is_expr = 0;
6162 goto block_after_label;
6163 } else
6164 if (tok == TOK_GOTO) {
6165 next();
6166 if (tok == '*' && gnu_ext) {
6167 /* computed goto */
6168 next();
6169 gexpr();
6170 if ((vtop->type.t & VT_BTYPE) != VT_PTR)
6171 expect("pointer");
6172 ggoto();
6173 } else if (tok >= TOK_UIDENT) {
6174 s = label_find(tok);
6175 /* put forward definition if needed */
6176 if (!s) {
6177 s = label_push(&global_label_stack, tok, LABEL_FORWARD);
6178 } else {
6179 if (s->r == LABEL_DECLARED)
6180 s->r = LABEL_FORWARD;
6181 }
6182 vla_sp_restore_root();
6183 if (s->r & LABEL_FORWARD)
6184 s->jnext = gjmp(s->jnext);
6185 else
6186 gjmp_addr(s->jnext);
6187 next();
6188 } else {
6189 expect("label identifier");
6190 }
6191 skip(';');
6192 } else if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
6193 asm_instr();
6194 } else {
6195 b = is_label();
6196 if (b) {
6197 /* label case */
6198 next();
6199 s = label_find(b);
6200 if (s) {
6201 if (s->r == LABEL_DEFINED)
6202 tcc_error("duplicate label '%s'", get_tok_str(s->v, NULL));
6203 gsym(s->jnext);
6204 s->r = LABEL_DEFINED;
6205 } else {
6206 s = label_push(&global_label_stack, b, LABEL_DEFINED);
6207 }
6208 s->jnext = ind;
6209 vla_sp_restore();
6210 /* we accept this, but it is a mistake */
6211 block_after_label:
6212 nocode_wanted &= ~0x20000000;
6213 if (tok == '}') {
6214 tcc_warning("deprecated use of label at end of compound statement");
6215 } else {
6216 if (is_expr)
6217 vpop();
6218 block(bsym, csym, is_expr);
6219 }
6220 } else {
6221 /* expression case */
6222 if (tok != ';') {
6223 if (is_expr) {
6224 vpop();
6225 gexpr();
6226 } else {
6227 gexpr();
6228 vpop();
6229 }
6230 }
6231 skip(';');
6232 }
6233 }
6234}
6235
6236/* This skips over a stream of tokens containing balanced {} and ()
6237 pairs, stopping at outer ',' ';' and '}' (or matching '}' if we started
6238 with a '{'). If STR then allocates and stores the skipped tokens
6239 in *STR. This doesn't check if () and {} are nested correctly,
6240 i.e. "({)}" is accepted. */
6241static void skip_or_save_block(TokenString **str)
6242{
6243 int braces = tok == '{';
6244 int level = 0;
6245 if (str)
6246 *str = tok_str_alloc();
6247
6248 while ((level > 0 || (tok != '}' && tok != ',' && tok != ';' && tok != ')'))) {
6249 int t;
6250 if (tok == TOK_EOF) {
6251 if (str || level > 0)
6252 tcc_error("unexpected end of file");
6253 else
6254 break;
6255 }
6256 if (str)
6257 tok_str_add_tok(*str);
6258 t = tok;
6259 next();
6260 if (t == '{' || t == '(') {
6261 level++;
6262 } else if (t == '}' || t == ')') {
6263 level--;
6264 if (level == 0 && braces && t == '}')
6265 break;
6266 }
6267 }
6268 if (str) {
6269 tok_str_add(*str, -1);
6270 tok_str_add(*str, 0);
6271 }
6272}
6273
6274#define EXPR_CONST 1
6275#define EXPR_ANY 2
6276
6277static void parse_init_elem(int expr_type)
6278{
6279 int saved_global_expr;
6280 switch(expr_type) {
6281 case EXPR_CONST:
6282 /* compound literals must be allocated globally in this case */
6283 saved_global_expr = global_expr;
6284 global_expr = 1;
6285 expr_const1();
6286 global_expr = saved_global_expr;
6287 /* NOTE: symbols are accepted, as well as lvalue for anon symbols
6288 (compound literals). */
6289 if (((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST
6290 && ((vtop->r & (VT_SYM|VT_LVAL)) != (VT_SYM|VT_LVAL)
6291 || vtop->sym->v < SYM_FIRST_ANOM))
6292#ifdef TCC_TARGET_PE
6293 || ((vtop->r & VT_SYM) && vtop->sym->a.dllimport)
6294#endif
6295 )
6296 tcc_error("initializer element is not constant");
6297 break;
6298 case EXPR_ANY:
6299 expr_eq();
6300 break;
6301 }
6302}
6303
6304/* put zeros for variable based init */
6305static void init_putz(Section *sec, unsigned long c, int size)
6306{
6307 if (sec) {
6308 /* nothing to do because globals are already set to zero */
6309 } else {
6310 vpush_global_sym(&func_old_type, TOK_memset);
6311 vseti(VT_LOCAL, c);
6312#ifdef TCC_TARGET_ARM
6313 vpushs(size);
6314 vpushi(0);
6315#else
6316 vpushi(0);
6317 vpushs(size);
6318#endif
6319 gfunc_call(3);
6320 }
6321}
6322
6323/* t is the array or struct type. c is the array or struct
6324 address. cur_field is the pointer to the current
6325 field, for arrays the 'c' member contains the current start
6326 index. 'size_only' is true if only size info is needed (only used
6327 in arrays). al contains the already initialized length of the
6328 current container (starting at c). This returns the new length of that. */
6329static int decl_designator(CType *type, Section *sec, unsigned long c,
6330 Sym **cur_field, int size_only, int al)
6331{
6332 Sym *s, *f;
6333 int index, index_last, align, l, nb_elems, elem_size;
6334 unsigned long corig = c;
6335
6336 elem_size = 0;
6337 nb_elems = 1;
6338 if (gnu_ext && (l = is_label()) != 0)
6339 goto struct_field;
6340 /* NOTE: we only support ranges for last designator */
6341 while (nb_elems == 1 && (tok == '[' || tok == '.')) {
6342 if (tok == '[') {
6343 if (!(type->t & VT_ARRAY))
6344 expect("array type");
6345 next();
6346 index = index_last = expr_const();
6347 if (tok == TOK_DOTS && gnu_ext) {
6348 next();
6349 index_last = expr_const();
6350 }
6351 skip(']');
6352 s = type->ref;
6353 if (index < 0 || (s->c >= 0 && index_last >= s->c) ||
6354 index_last < index)
6355 tcc_error("invalid index");
6356 if (cur_field)
6357 (*cur_field)->c = index_last;
6358 type = pointed_type(type);
6359 elem_size = type_size(type, &align);
6360 c += index * elem_size;
6361 nb_elems = index_last - index + 1;
6362 } else {
6363 next();
6364 l = tok;
6365 struct_field:
6366 next();
6367 if ((type->t & VT_BTYPE) != VT_STRUCT)
6368 expect("struct/union type");
6369 f = find_field(type, l);
6370 if (!f)
6371 expect("field");
6372 if (cur_field)
6373 *cur_field = f;
6374 type = &f->type;
6375 c += f->c;
6376 }
6377 cur_field = NULL;
6378 }
6379 if (!cur_field) {
6380 if (tok == '=') {
6381 next();
6382 } else if (!gnu_ext) {
6383 expect("=");
6384 }
6385 } else {
6386 if (type->t & VT_ARRAY) {
6387 index = (*cur_field)->c;
6388 if (type->ref->c >= 0 && index >= type->ref->c)
6389 tcc_error("index too large");
6390 type = pointed_type(type);
6391 c += index * type_size(type, &align);
6392 } else {
6393 f = *cur_field;
6394 while (f && (f->v & SYM_FIRST_ANOM) && (f->type.t & VT_BITFIELD))
6395 *cur_field = f = f->next;
6396 if (!f)
6397 tcc_error("too many field init");
6398 type = &f->type;
6399 c += f->c;
6400 }
6401 }
6402 /* must put zero in holes (note that doing it that way
6403 ensures that it even works with designators) */
6404 if (!size_only && c - corig > al)
6405 init_putz(sec, corig + al, c - corig - al);
6406 decl_initializer(type, sec, c, 0, size_only);
6407
6408 /* XXX: make it more general */
6409 if (!size_only && nb_elems > 1) {
6410 unsigned long c_end;
6411 uint8_t *src, *dst;
6412 int i;
6413
6414 if (!sec) {
6415 vset(type, VT_LOCAL|VT_LVAL, c);
6416 for (i = 1; i < nb_elems; i++) {
6417 vset(type, VT_LOCAL|VT_LVAL, c + elem_size * i);
6418 vswap();
6419 vstore();
6420 }
6421 vpop();
6422 } else if (!NODATA_WANTED) {
6423 c_end = c + nb_elems * elem_size;
6424 if (c_end > sec->data_allocated)
6425 section_realloc(sec, c_end);
6426 src = sec->data + c;
6427 dst = src;
6428 for(i = 1; i < nb_elems; i++) {
6429 dst += elem_size;
6430 memcpy(dst, src, elem_size);
6431 }
6432 }
6433 }
6434 c += nb_elems * type_size(type, &align);
6435 if (c - corig > al)
6436 al = c - corig;
6437 return al;
6438}
6439
6440/* store a value or an expression directly in global data or in local array */
6441static void init_putv(CType *type, Section *sec, unsigned long c)
6442{
6443 int bt;
6444 void *ptr;
6445 CType dtype;
6446
6447 dtype = *type;
6448 dtype.t &= ~VT_CONSTANT; /* need to do that to avoid false warning */
6449
6450 if (sec) {
6451 int size, align;
6452 /* XXX: not portable */
6453 /* XXX: generate error if incorrect relocation */
6454 gen_assign_cast(&dtype);
6455 bt = type->t & VT_BTYPE;
6456
6457 if ((vtop->r & VT_SYM)
6458 && bt != VT_PTR
6459 && bt != VT_FUNC
6460 && (bt != (PTR_SIZE == 8 ? VT_LLONG : VT_INT)
6461 || (type->t & VT_BITFIELD))
6462 && !((vtop->r & VT_CONST) && vtop->sym->v >= SYM_FIRST_ANOM)
6463 )
6464 tcc_error("initializer element is not computable at load time");
6465
6466 if (NODATA_WANTED) {
6467 vtop--;
6468 return;
6469 }
6470
6471 size = type_size(type, &align);
6472 section_reserve(sec, c + size);
6473 ptr = sec->data + c;
6474
6475 /* XXX: make code faster ? */
6476 if ((vtop->r & (VT_SYM|VT_CONST)) == (VT_SYM|VT_CONST) &&
6477 vtop->sym->v >= SYM_FIRST_ANOM &&
6478 /* XXX This rejects compound literals like
6479 '(void *){ptr}'. The problem is that '&sym' is
6480 represented the same way, which would be ruled out
6481 by the SYM_FIRST_ANOM check above, but also '"string"'
6482 in 'char *p = "string"' is represented the same
6483 with the type being VT_PTR and the symbol being an
6484 anonymous one. That is, there's no difference in vtop
6485 between '(void *){x}' and '&(void *){x}'. Ignore
6486 pointer typed entities here. Hopefully no real code
6487 will every use compound literals with scalar type. */
6488 (vtop->type.t & VT_BTYPE) != VT_PTR) {
6489 /* These come from compound literals, memcpy stuff over. */
6490 Section *ssec;
6491 ElfSym *esym;
6492 ElfW_Rel *rel;
6493 esym = elfsym(vtop->sym);
6494 ssec = tcc_state->sections[esym->st_shndx];
6495 memmove (ptr, ssec->data + esym->st_value, size);
6496 if (ssec->reloc) {
6497 /* We need to copy over all memory contents, and that
6498 includes relocations. Use the fact that relocs are
6499 created it order, so look from the end of relocs
6500 until we hit one before the copied region. */
6501 int num_relocs = ssec->reloc->data_offset / sizeof(*rel);
6502 rel = (ElfW_Rel*)(ssec->reloc->data + ssec->reloc->data_offset);
6503 while (num_relocs--) {
6504 rel--;
6505 if (rel->r_offset >= esym->st_value + size)
6506 continue;
6507 if (rel->r_offset < esym->st_value)
6508 break;
6509 /* Note: if the same fields are initialized multiple
6510 times (possible with designators) then we possibly
6511 add multiple relocations for the same offset here.
6512 That would lead to wrong code, the last reloc needs
6513 to win. We clean this up later after the whole
6514 initializer is parsed. */
6515 put_elf_reloca(symtab_section, sec,
6516 c + rel->r_offset - esym->st_value,
6517 ELFW(R_TYPE)(rel->r_info),
6518 ELFW(R_SYM)(rel->r_info),
6519#if PTR_SIZE == 8
6520 rel->r_addend
6521#else
6522 0
6523#endif
6524 );
6525 }
6526 }
6527 } else {
6528 if (type->t & VT_BITFIELD) {
6529 int bit_pos, bit_size, bits, n;
6530 unsigned char *p, v, m;
6531 bit_pos = BIT_POS(vtop->type.t);
6532 bit_size = BIT_SIZE(vtop->type.t);
6533 p = (unsigned char*)ptr + (bit_pos >> 3);
6534 bit_pos &= 7, bits = 0;
6535 while (bit_size) {
6536 n = 8 - bit_pos;
6537 if (n > bit_size)
6538 n = bit_size;
6539 v = vtop->c.i >> bits << bit_pos;
6540 m = ((1 << n) - 1) << bit_pos;
6541 *p = (*p & ~m) | (v & m);
6542 bits += n, bit_size -= n, bit_pos = 0, ++p;
6543 }
6544 } else
6545 switch(bt) {
6546 /* XXX: when cross-compiling we assume that each type has the
6547 same representation on host and target, which is likely to
6548 be wrong in the case of long double */
6549 case VT_BOOL:
6550 vtop->c.i = vtop->c.i != 0;
6551 case VT_BYTE:
6552 *(char *)ptr |= vtop->c.i;
6553 break;
6554 case VT_SHORT:
6555 *(short *)ptr |= vtop->c.i;
6556 break;
6557 case VT_FLOAT:
6558 *(float*)ptr = vtop->c.f;
6559 break;
6560 case VT_DOUBLE:
6561 *(double *)ptr = vtop->c.d;
6562 break;
6563 case VT_LDOUBLE:
6564#if defined TCC_IS_NATIVE_387
6565 if (sizeof (long double) >= 10) /* zero pad ten-byte LD */
6566 memcpy(ptr, &vtop->c.ld, 10);
6567#ifdef __TINYC__
6568 else if (sizeof (long double) == sizeof (double))
6569 __asm__("fldl %1\nfstpt %0\n" : "=m" (*ptr) : "m" (vtop->c.ld));
6570#endif
6571 else if (vtop->c.ld == 0.0)
6572 ;
6573 else
6574#endif
6575 if (sizeof(long double) == LDOUBLE_SIZE)
6576 *(long double*)ptr = vtop->c.ld;
6577 else if (sizeof(double) == LDOUBLE_SIZE)
6578 *(double *)ptr = (double)vtop->c.ld;
6579 else
6580 tcc_error("can't cross compile long double constants");
6581 break;
6582#if PTR_SIZE != 8
6583 case VT_LLONG:
6584 *(long long *)ptr |= vtop->c.i;
6585 break;
6586#else
6587 case VT_LLONG:
6588#endif
6589 case VT_PTR:
6590 {
6591 addr_t val = vtop->c.i;
6592#if PTR_SIZE == 8
6593 if (vtop->r & VT_SYM)
6594 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
6595 else
6596 *(addr_t *)ptr |= val;
6597#else
6598 if (vtop->r & VT_SYM)
6599 greloc(sec, vtop->sym, c, R_DATA_PTR);
6600 *(addr_t *)ptr |= val;
6601#endif
6602 break;
6603 }
6604 default:
6605 {
6606 int val = vtop->c.i;
6607#if PTR_SIZE == 8
6608 if (vtop->r & VT_SYM)
6609 greloca(sec, vtop->sym, c, R_DATA_PTR, val);
6610 else
6611 *(int *)ptr |= val;
6612#else
6613 if (vtop->r & VT_SYM)
6614 greloc(sec, vtop->sym, c, R_DATA_PTR);
6615 *(int *)ptr |= val;
6616#endif
6617 break;
6618 }
6619 }
6620 }
6621 vtop--;
6622 } else {
6623 vset(&dtype, VT_LOCAL|VT_LVAL, c);
6624 vswap();
6625 vstore();
6626 vpop();
6627 }
6628}
6629
6630/* 't' contains the type and storage info. 'c' is the offset of the
6631 object in section 'sec'. If 'sec' is NULL, it means stack based
6632 allocation. 'first' is true if array '{' must be read (multi
6633 dimension implicit array init handling). 'size_only' is true if
6634 size only evaluation is wanted (only for arrays). */
6635static void decl_initializer(CType *type, Section *sec, unsigned long c,
6636 int first, int size_only)
6637{
6638 int len, n, no_oblock, nb, i;
6639 int size1, align1;
6640 int have_elem;
6641 Sym *s, *f;
6642 Sym indexsym;
6643 CType *t1;
6644
6645 /* If we currently are at an '}' or ',' we have read an initializer
6646 element in one of our callers, and not yet consumed it. */
6647 have_elem = tok == '}' || tok == ',';
6648 if (!have_elem && tok != '{' &&
6649 /* In case of strings we have special handling for arrays, so
6650 don't consume them as initializer value (which would commit them
6651 to some anonymous symbol). */
6652 tok != TOK_LSTR && tok != TOK_STR &&
6653 !size_only) {
6654 parse_init_elem(!sec ? EXPR_ANY : EXPR_CONST);
6655 have_elem = 1;
6656 }
6657
6658 if (have_elem &&
6659 !(type->t & VT_ARRAY) &&
6660 /* Use i_c_parameter_t, to strip toplevel qualifiers.
6661 The source type might have VT_CONSTANT set, which is
6662 of course assignable to non-const elements. */
6663 is_compatible_unqualified_types(type, &vtop->type)) {
6664 init_putv(type, sec, c);
6665 } else if (type->t & VT_ARRAY) {
6666 s = type->ref;
6667 n = s->c;
6668 t1 = pointed_type(type);
6669 size1 = type_size(t1, &align1);
6670
6671 no_oblock = 1;
6672 if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
6673 tok == '{') {
6674 if (tok != '{')
6675 tcc_error("character array initializer must be a literal,"
6676 " optionally enclosed in braces");
6677 skip('{');
6678 no_oblock = 0;
6679 }
6680
6681 /* only parse strings here if correct type (otherwise: handle
6682 them as ((w)char *) expressions */
6683 if ((tok == TOK_LSTR &&
6684#ifdef TCC_TARGET_PE
6685 (t1->t & VT_BTYPE) == VT_SHORT && (t1->t & VT_UNSIGNED)
6686#else
6687 (t1->t & VT_BTYPE) == VT_INT
6688#endif
6689 ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_BYTE)) {
6690 len = 0;
6691 while (tok == TOK_STR || tok == TOK_LSTR) {
6692 int cstr_len, ch;
6693
6694 /* compute maximum number of chars wanted */
6695 if (tok == TOK_STR)
6696 cstr_len = tokc.str.size;
6697 else
6698 cstr_len = tokc.str.size / sizeof(nwchar_t);
6699 cstr_len--;
6700 nb = cstr_len;
6701 if (n >= 0 && nb > (n - len))
6702 nb = n - len;
6703 if (!size_only) {
6704 if (cstr_len > nb)
6705 tcc_warning("initializer-string for array is too long");
6706 /* in order to go faster for common case (char
6707 string in global variable, we handle it
6708 specifically */
6709 if (sec && tok == TOK_STR && size1 == 1) {
6710 if (!NODATA_WANTED)
6711 memcpy(sec->data + c + len, tokc.str.data, nb);
6712 } else {
6713 for(i=0;i<nb;i++) {
6714 if (tok == TOK_STR)
6715 ch = ((unsigned char *)tokc.str.data)[i];
6716 else
6717 ch = ((nwchar_t *)tokc.str.data)[i];
6718 vpushi(ch);
6719 init_putv(t1, sec, c + (len + i) * size1);
6720 }
6721 }
6722 }
6723 len += nb;
6724 next();
6725 }
6726 /* only add trailing zero if enough storage (no
6727 warning in this case since it is standard) */
6728 if (n < 0 || len < n) {
6729 if (!size_only) {
6730 vpushi(0);
6731 init_putv(t1, sec, c + (len * size1));
6732 }
6733 len++;
6734 }
6735 len *= size1;
6736 } else {
6737 indexsym.c = 0;
6738 f = &indexsym;
6739
6740 do_init_list:
6741 len = 0;
6742 while (tok != '}' || have_elem) {
6743 len = decl_designator(type, sec, c, &f, size_only, len);
6744 have_elem = 0;
6745 if (type->t & VT_ARRAY) {
6746 ++indexsym.c;
6747 /* special test for multi dimensional arrays (may not
6748 be strictly correct if designators are used at the
6749 same time) */
6750 if (no_oblock && len >= n*size1)
6751 break;
6752 } else {
6753 if (s->type.t == VT_UNION)
6754 f = NULL;
6755 else
6756 f = f->next;
6757 if (no_oblock && f == NULL)
6758 break;
6759 }
6760
6761 if (tok == '}')
6762 break;
6763 skip(',');
6764 }
6765 }
6766 /* put zeros at the end */
6767 if (!size_only && len < n*size1)
6768 init_putz(sec, c + len, n*size1 - len);
6769 if (!no_oblock)
6770 skip('}');
6771 /* patch type size if needed, which happens only for array types */
6772 if (n < 0)
6773 s->c = size1 == 1 ? len : ((len + size1 - 1)/size1);
6774 } else if ((type->t & VT_BTYPE) == VT_STRUCT) {
6775 size1 = 1;
6776 no_oblock = 1;
6777 if (first || tok == '{') {
6778 skip('{');
6779 no_oblock = 0;
6780 }
6781 s = type->ref;
6782 f = s->next;
6783 n = s->c;
6784 goto do_init_list;
6785 } else if (tok == '{') {
6786 next();
6787 decl_initializer(type, sec, c, first, size_only);
6788 skip('}');
6789 } else if (size_only) {
6790 /* If we supported only ISO C we wouldn't have to accept calling
6791 this on anything than an array size_only==1 (and even then
6792 only on the outermost level, so no recursion would be needed),
6793 because initializing a flex array member isn't supported.
6794 But GNU C supports it, so we need to recurse even into
6795 subfields of structs and arrays when size_only is set. */
6796 /* just skip expression */
6797 skip_or_save_block(NULL);
6798 } else {
6799 if (!have_elem) {
6800 /* This should happen only when we haven't parsed
6801 the init element above for fear of committing a
6802 string constant to memory too early. */
6803 if (tok != TOK_STR && tok != TOK_LSTR)
6804 expect("string constant");
6805 parse_init_elem(!sec ? EXPR_ANY : EXPR_CONST);
6806 }
6807 init_putv(type, sec, c);
6808 }
6809}
6810
6811/* parse an initializer for type 't' if 'has_init' is non zero, and
6812 allocate space in local or global data space ('r' is either
6813 VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
6814 variable 'v' of scope 'scope' is declared before initializers
6815 are parsed. If 'v' is zero, then a reference to the new object
6816 is put in the value stack. If 'has_init' is 2, a special parsing
6817 is done to handle string constants. */
6818static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
6819 int has_init, int v, int scope)
6820{
6821 int size, align, addr;
6822 TokenString *init_str = NULL;
6823
6824 Section *sec;
6825 Sym *flexible_array;
6826 Sym *sym = NULL;
6827 int saved_nocode_wanted = nocode_wanted;
6828#ifdef CONFIG_TCC_BCHECK
6829 int bcheck = tcc_state->do_bounds_check && !NODATA_WANTED;
6830#endif
6831
6832 if (type->t & VT_STATIC)
6833 nocode_wanted |= NODATA_WANTED ? 0x40000000 : 0x80000000;
6834
6835 flexible_array = NULL;
6836 if ((type->t & VT_BTYPE) == VT_STRUCT) {
6837 Sym *field = type->ref->next;
6838 if (field) {
6839 while (field->next)
6840 field = field->next;
6841 if (field->type.t & VT_ARRAY && field->type.ref->c < 0)
6842 flexible_array = field;
6843 }
6844 }
6845
6846 size = type_size(type, &align);
6847 /* If unknown size, we must evaluate it before
6848 evaluating initializers because
6849 initializers can generate global data too
6850 (e.g. string pointers or ISOC99 compound
6851 literals). It also simplifies local
6852 initializers handling */
6853 if (size < 0 || (flexible_array && has_init)) {
6854 if (!has_init)
6855 tcc_error("unknown type size");
6856 /* get all init string */
6857 if (has_init == 2) {
6858 init_str = tok_str_alloc();
6859 /* only get strings */
6860 while (tok == TOK_STR || tok == TOK_LSTR) {
6861 tok_str_add_tok(init_str);
6862 next();
6863 }
6864 tok_str_add(init_str, -1);
6865 tok_str_add(init_str, 0);
6866 } else {
6867 skip_or_save_block(&init_str);
6868 }
6869 unget_tok(0);
6870
6871 /* compute size */
6872 begin_macro(init_str, 1);
6873 next();
6874 decl_initializer(type, NULL, 0, 1, 1);
6875 /* prepare second initializer parsing */
6876 macro_ptr = init_str->str;
6877 next();
6878
6879 /* if still unknown size, error */
6880 size = type_size(type, &align);
6881 if (size < 0)
6882 tcc_error("unknown type size");
6883 }
6884 /* If there's a flex member and it was used in the initializer
6885 adjust size. */
6886 if (flexible_array &&
6887 flexible_array->type.ref->c > 0)
6888 size += flexible_array->type.ref->c
6889 * pointed_size(&flexible_array->type);
6890 /* take into account specified alignment if bigger */
6891 if (ad->a.aligned) {
6892 int speca = 1 << (ad->a.aligned - 1);
6893 if (speca > align)
6894 align = speca;
6895 } else if (ad->a.packed) {
6896 align = 1;
6897 }
6898
6899 if (NODATA_WANTED)
6900 size = 0, align = 1;
6901
6902 if ((r & VT_VALMASK) == VT_LOCAL) {
6903 sec = NULL;
6904#ifdef CONFIG_TCC_BCHECK
6905 if (bcheck && (type->t & VT_ARRAY)) {
6906 loc--;
6907 }
6908#endif
6909 loc = (loc - size) & -align;
6910 addr = loc;
6911#ifdef CONFIG_TCC_BCHECK
6912 /* handles bounds */
6913 /* XXX: currently, since we do only one pass, we cannot track
6914 '&' operators, so we add only arrays */
6915 if (bcheck && (type->t & VT_ARRAY)) {
6916 addr_t *bounds_ptr;
6917 /* add padding between regions */
6918 loc--;
6919 /* then add local bound info */
6920 bounds_ptr = section_ptr_add(lbounds_section, 2 * sizeof(addr_t));
6921 bounds_ptr[0] = addr;
6922 bounds_ptr[1] = size;
6923 }
6924#endif
6925 if (v) {
6926 /* local variable */
6927#ifdef CONFIG_TCC_ASM
6928 if (ad->asm_label) {
6929 int reg = asm_parse_regvar(ad->asm_label);
6930 if (reg >= 0)
6931 r = (r & ~VT_VALMASK) | reg;
6932 }
6933#endif
6934 sym = sym_push(v, type, r, addr);
6935 sym->a = ad->a;
6936 } else {
6937 /* push local reference */
6938 vset(type, r, addr);
6939 }
6940 } else {
6941 if (v && scope == VT_CONST) {
6942 /* see if the symbol was already defined */
6943 sym = sym_find(v);
6944 if (sym) {
6945 patch_storage(sym, ad, type);
6946 /* we accept several definitions of the same global variable. */
6947 if (!has_init && sym->c && elfsym(sym)->st_shndx != SHN_UNDEF)
6948 goto no_alloc;
6949 }
6950 }
6951
6952 /* allocate symbol in corresponding section */
6953 sec = ad->section;
6954 if (!sec) {
6955 if (has_init)
6956 sec = data_section;
6957 else if (tcc_state->nocommon)
6958 sec = bss_section;
6959 }
6960
6961 if (sec) {
6962 addr = section_add(sec, size, align);
6963#ifdef CONFIG_TCC_BCHECK
6964 /* add padding if bound check */
6965 if (bcheck)
6966 section_add(sec, 1, 1);
6967#endif
6968 } else {
6969 addr = align; /* SHN_COMMON is special, symbol value is align */
6970 sec = common_section;
6971 }
6972
6973 if (v) {
6974 if (!sym) {
6975 sym = sym_push(v, type, r | VT_SYM, 0);
6976 patch_storage(sym, ad, NULL);
6977 }
6978 /* Local statics have a scope until now (for
6979 warnings), remove it here. */
6980 sym->sym_scope = 0;
6981 /* update symbol definition */
6982 put_extern_sym(sym, sec, addr, size);
6983 } else {
6984 /* push global reference */
6985 sym = get_sym_ref(type, sec, addr, size);
6986 vpushsym(type, sym);
6987 vtop->r |= r;
6988 }
6989
6990#ifdef CONFIG_TCC_BCHECK
6991 /* handles bounds now because the symbol must be defined
6992 before for the relocation */
6993 if (bcheck) {
6994 addr_t *bounds_ptr;
6995
6996 greloca(bounds_section, sym, bounds_section->data_offset, R_DATA_PTR, 0);
6997 /* then add global bound info */
6998 bounds_ptr = section_ptr_add(bounds_section, 2 * sizeof(addr_t));
6999 bounds_ptr[0] = 0; /* relocated */
7000 bounds_ptr[1] = size;
7001 }
7002#endif
7003 }
7004
7005 if (type->t & VT_VLA) {
7006 int a;
7007
7008 if (NODATA_WANTED)
7009 goto no_alloc;
7010
7011 /* save current stack pointer */
7012 if (vlas_in_scope == 0) {
7013 if (vla_sp_root_loc == -1)
7014 vla_sp_root_loc = (loc -= PTR_SIZE);
7015 gen_vla_sp_save(vla_sp_root_loc);
7016 }
7017
7018 vla_runtime_type_size(type, &a);
7019 gen_vla_alloc(type, a);
7020#if defined TCC_TARGET_PE && defined TCC_TARGET_X86_64
7021 /* on _WIN64, because of the function args scratch area, the
7022 result of alloca differs from RSP and is returned in RAX. */
7023 gen_vla_result(addr), addr = (loc -= PTR_SIZE);
7024#endif
7025 gen_vla_sp_save(addr);
7026 vla_sp_loc = addr;
7027 vlas_in_scope++;
7028
7029 } else if (has_init) {
7030 size_t oldreloc_offset = 0;
7031 if (sec && sec->reloc)
7032 oldreloc_offset = sec->reloc->data_offset;
7033 decl_initializer(type, sec, addr, 1, 0);
7034 if (sec && sec->reloc)
7035 squeeze_multi_relocs(sec, oldreloc_offset);
7036 /* patch flexible array member size back to -1, */
7037 /* for possible subsequent similar declarations */
7038 if (flexible_array)
7039 flexible_array->type.ref->c = -1;
7040 }
7041
7042 no_alloc:
7043 /* restore parse state if needed */
7044 if (init_str) {
7045 end_macro();
7046 next();
7047 }
7048
7049 nocode_wanted = saved_nocode_wanted;
7050}
7051
7052/* parse a function defined by symbol 'sym' and generate its code in
7053 'cur_text_section' */
7054static void gen_function(Sym *sym)
7055{
7056 nocode_wanted = 0;
7057 ind = cur_text_section->data_offset;
7058 /* NOTE: we patch the symbol size later */
7059 put_extern_sym(sym, cur_text_section, ind, 0);
7060 funcname = get_tok_str(sym->v, NULL);
7061 func_ind = ind;
7062 /* Initialize VLA state */
7063 vla_sp_loc = -1;
7064 vla_sp_root_loc = -1;
7065 /* put debug symbol */
7066 tcc_debug_funcstart(tcc_state, sym);
7067 /* push a dummy symbol to enable local sym storage */
7068 sym_push2(&local_stack, SYM_FIELD, 0, 0);
7069 local_scope = 1; /* for function parameters */
7070 gfunc_prolog(&sym->type);
7071 local_scope = 0;
7072 rsym = 0;
7073 block(NULL, NULL, 0);
7074 nocode_wanted = 0;
7075 gsym(rsym);
7076 gfunc_epilog();
7077 cur_text_section->data_offset = ind;
7078 label_pop(&global_label_stack, NULL, 0);
7079 /* reset local stack */
7080 local_scope = 0;
7081 sym_pop(&local_stack, NULL, 0);
7082 /* end of function */
7083 /* patch symbol size */
7084 elfsym(sym)->st_size = ind - func_ind;
7085 tcc_debug_funcend(tcc_state, ind - func_ind);
7086 /* It's better to crash than to generate wrong code */
7087 cur_text_section = NULL;
7088 funcname = ""; /* for safety */
7089 func_vt.t = VT_VOID; /* for safety */
7090 func_var = 0; /* for safety */
7091 ind = 0; /* for safety */
7092 nocode_wanted = 0x80000000;
7093 check_vstack();
7094}
7095
7096static void gen_inline_functions(TCCState *s)
7097{
7098 Sym *sym;
7099 int inline_generated, i, ln;
7100 struct InlineFunc *fn;
7101
7102 ln = file->line_num;
7103 /* iterate while inline function are referenced */
7104 do {
7105 inline_generated = 0;
7106 for (i = 0; i < s->nb_inline_fns; ++i) {
7107 fn = s->inline_fns[i];
7108 sym = fn->sym;
7109 if (sym && sym->c) {
7110 /* the function was used: generate its code and
7111 convert it to a normal function */
7112 fn->sym = NULL;
7113 if (file)
7114 pstrcpy(file->filename, sizeof file->filename, fn->filename);
7115 sym->type.t &= ~VT_INLINE;
7116
7117 begin_macro(fn->func_str, 1);
7118 next();
7119 cur_text_section = text_section;
7120 gen_function(sym);
7121 end_macro();
7122
7123 inline_generated = 1;
7124 }
7125 }
7126 } while (inline_generated);
7127 file->line_num = ln;
7128}
7129
7130ST_FUNC void free_inline_functions(TCCState *s)
7131{
7132 int i;
7133 /* free tokens of unused inline functions */
7134 for (i = 0; i < s->nb_inline_fns; ++i) {
7135 struct InlineFunc *fn = s->inline_fns[i];
7136 if (fn->sym)
7137 tok_str_free(fn->func_str);
7138 }
7139 dynarray_reset(&s->inline_fns, &s->nb_inline_fns);
7140}
7141
7142/* 'l' is VT_LOCAL or VT_CONST to define default storage type, or VT_CMP
7143 if parsing old style parameter decl list (and FUNC_SYM is set then) */
7144static int decl0(int l, int is_for_loop_init, Sym *func_sym)
7145{
7146 int v, has_init, r;
7147 CType type, btype;
7148 Sym *sym;
7149 AttributeDef ad;
7150
7151 while (1) {
7152 if (!parse_btype(&btype, &ad)) {
7153 if (is_for_loop_init)
7154 return 0;
7155 /* skip redundant ';' if not in old parameter decl scope */
7156 if (tok == ';' && l != VT_CMP) {
7157 next();
7158 continue;
7159 }
7160 if (l != VT_CONST)
7161 break;
7162 if (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3) {
7163 /* global asm block */
7164 asm_global_instr();
7165 continue;
7166 }
7167 if (tok >= TOK_UIDENT) {
7168 /* special test for old K&R protos without explicit int
7169 type. Only accepted when defining global data */
7170 btype.t = VT_INT;
7171 } else {
7172 if (tok != TOK_EOF)
7173 expect("declaration");
7174 break;
7175 }
7176 }
7177 if (tok == ';') {
7178 if ((btype.t & VT_BTYPE) == VT_STRUCT) {
7179 int v = btype.ref->v;
7180 if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) >= SYM_FIRST_ANOM)
7181 tcc_warning("unnamed struct/union that defines no instances");
7182 next();
7183 continue;
7184 }
7185 if (IS_ENUM(btype.t)) {
7186 next();
7187 continue;
7188 }
7189 }
7190 while (1) { /* iterate thru each declaration */
7191 type = btype;
7192 /* If the base type itself was an array type of unspecified
7193 size (like in 'typedef int arr[]; arr x = {1};') then
7194 we will overwrite the unknown size by the real one for
7195 this decl. We need to unshare the ref symbol holding
7196 that size. */
7197 if ((type.t & VT_ARRAY) && type.ref->c < 0) {
7198 type.ref = sym_push(SYM_FIELD, &type.ref->type, 0, type.ref->c);
7199 }
7200 type_decl(&type, &ad, &v, TYPE_DIRECT);
7201#if 0
7202 {
7203 char buf[500];
7204 type_to_str(buf, sizeof(buf), &type, get_tok_str(v, NULL));
7205 printf("type = '%s'\n", buf);
7206 }
7207#endif
7208 if ((type.t & VT_BTYPE) == VT_FUNC) {
7209 if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
7210 tcc_error("function without file scope cannot be static");
7211 }
7212 /* if old style function prototype, we accept a
7213 declaration list */
7214 sym = type.ref;
7215 if (sym->f.func_type == FUNC_OLD && l == VT_CONST)
7216 decl0(VT_CMP, 0, sym);
7217 }
7218
7219 if (gnu_ext && (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
7220 ad.asm_label = asm_label_instr();
7221 /* parse one last attribute list, after asm label */
7222 parse_attribute(&ad);
7223 if (tok == '{')
7224 expect(";");
7225 }
7226
7227#ifdef TCC_TARGET_PE
7228 if (ad.a.dllimport || ad.a.dllexport) {
7229 if (type.t & (VT_STATIC|VT_TYPEDEF))
7230 tcc_error("cannot have dll linkage with static or typedef");
7231 if (ad.a.dllimport) {
7232 if ((type.t & VT_BTYPE) == VT_FUNC)
7233 ad.a.dllimport = 0;
7234 else
7235 type.t |= VT_EXTERN;
7236 }
7237 }
7238#endif
7239 if (tok == '{') {
7240 if (l != VT_CONST)
7241 tcc_error("cannot use local functions");
7242 if ((type.t & VT_BTYPE) != VT_FUNC)
7243 expect("function definition");
7244
7245 /* reject abstract declarators in function definition
7246 make old style params without decl have int type */
7247 sym = type.ref;
7248 while ((sym = sym->next) != NULL) {
7249 if (!(sym->v & ~SYM_FIELD))
7250 expect("identifier");
7251 if (sym->type.t == VT_VOID)
7252 sym->type = int_type;
7253 }
7254
7255 /* XXX: cannot do better now: convert extern line to static inline */
7256 if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE))
7257 type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
7258
7259 /* put function symbol */
7260 sym = external_global_sym(v, &type, 0);
7261 type.t &= ~VT_EXTERN;
7262 patch_storage(sym, &ad, &type);
7263
7264 /* static inline functions are just recorded as a kind
7265 of macro. Their code will be emitted at the end of
7266 the compilation unit only if they are used */
7267 if ((type.t & (VT_INLINE | VT_STATIC)) ==
7268 (VT_INLINE | VT_STATIC)) {
7269 struct InlineFunc *fn;
7270 const char *filename;
7271
7272 filename = file ? file->filename : "";
7273 fn = tcc_malloc(sizeof *fn + strlen(filename));
7274 strcpy(fn->filename, filename);
7275 fn->sym = sym;
7276 skip_or_save_block(&fn->func_str);
7277 dynarray_add(&tcc_state->inline_fns,
7278 &tcc_state->nb_inline_fns, fn);
7279 } else {
7280 /* compute text section */
7281 cur_text_section = ad.section;
7282 if (!cur_text_section)
7283 cur_text_section = text_section;
7284 gen_function(sym);
7285 }
7286 break;
7287 } else {
7288 if (l == VT_CMP) {
7289 /* find parameter in function parameter list */
7290 for (sym = func_sym->next; sym; sym = sym->next)
7291 if ((sym->v & ~SYM_FIELD) == v)
7292 goto found;
7293 tcc_error("declaration for parameter '%s' but no such parameter",
7294 get_tok_str(v, NULL));
7295found:
7296 if (type.t & VT_STORAGE) /* 'register' is okay */
7297 tcc_error("storage class specified for '%s'",
7298 get_tok_str(v, NULL));
7299 if (sym->type.t != VT_VOID)
7300 tcc_error("redefinition of parameter '%s'",
7301 get_tok_str(v, NULL));
7302 convert_parameter_type(&type);
7303 sym->type = type;
7304 } else if (type.t & VT_TYPEDEF) {
7305 /* save typedefed type */
7306 /* XXX: test storage specifiers ? */
7307 sym = sym_find(v);
7308 if (sym && sym->sym_scope == local_scope) {
7309 if (!is_compatible_types(&sym->type, &type)
7310 || !(sym->type.t & VT_TYPEDEF))
7311 tcc_error("incompatible redefinition of '%s'",
7312 get_tok_str(v, NULL));
7313 sym->type = type;
7314 } else {
7315 sym = sym_push(v, &type, 0, 0);
7316 }
7317 sym->a = ad.a;
7318 sym->f = ad.f;
7319 } else {
7320 r = 0;
7321 if ((type.t & VT_BTYPE) == VT_FUNC) {
7322 /* external function definition */
7323 /* specific case for func_call attribute */
7324 type.ref->f = ad.f;
7325 } else if (!(type.t & VT_ARRAY)) {
7326 /* not lvalue if array */
7327 r |= lvalue_type(type.t);
7328 }
7329 has_init = (tok == '=');
7330 if (has_init && (type.t & VT_VLA))
7331 tcc_error("variable length array cannot be initialized");
7332 if (((type.t & VT_EXTERN) && (!has_init || l != VT_CONST)) ||
7333 ((type.t & VT_BTYPE) == VT_FUNC) ||
7334 ((type.t & VT_ARRAY) && (type.t & VT_STATIC) &&
7335 !has_init && l == VT_CONST && type.ref->c < 0)) {
7336 /* external variable or function */
7337 /* NOTE: as GCC, uninitialized global static
7338 arrays of null size are considered as
7339 extern */
7340 type.t |= VT_EXTERN;
7341 sym = external_sym(v, &type, r, &ad);
7342 if (ad.alias_target) {
7343 ElfSym *esym;
7344 Sym *alias_target;
7345 alias_target = sym_find(ad.alias_target);
7346 esym = elfsym(alias_target);
7347 if (!esym)
7348 tcc_error("unsupported forward __alias__ attribute");
7349 /* Local statics have a scope until now (for
7350 warnings), remove it here. */
7351 sym->sym_scope = 0;
7352 put_extern_sym2(sym, esym->st_shndx, esym->st_value, esym->st_size, 0);
7353 }
7354 } else {
7355 if (type.t & VT_STATIC)
7356 r |= VT_CONST;
7357 else
7358 r |= l;
7359 if (has_init)
7360 next();
7361 else if (l == VT_CONST)
7362 /* uninitialized global variables may be overridden */
7363 type.t |= VT_EXTERN;
7364 decl_initializer_alloc(&type, &ad, r, has_init, v, l);
7365 }
7366 }
7367 if (tok != ',') {
7368 if (is_for_loop_init)
7369 return 1;
7370 skip(';');
7371 break;
7372 }
7373 next();
7374 }
7375 ad.a.aligned = 0;
7376 }
7377 }
7378 return 0;
7379}
7380
7381static void decl(int l)
7382{
7383 decl0(l, 0, NULL);
7384}
7385
7386/* ------------------------------------------------------------------------- */
Note: See TracBrowser for help on using the repository browser.