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 #define TCC_ERR(...) do {				\
24 	tcc_error (__VA_ARGS__);			\
25 	return;								\
26 } while (0)
27 /* callback pointer */
28 ST_DATA char **tcc_cb_ptr;
29 
30 /********************************************************/
31 /* global variables */
32 
33 /* loc : local variable index
34    ind : output code index
35    rsym: return symbol
36    anon_sym: anonymous symbol index
37 */
38 ST_DATA int rsym, anon_sym = SYM_FIRST_ANOM, ind, loc;
39 ST_DATA Sym *sym_free_first;
40 ST_DATA void **sym_pools;
41 ST_DATA int nb_sym_pools;
42 
43 static int arraysize = 0;
44 
45 static const char *global_symname = NULL;
46 static const char *global_type = NULL;
47 
48 ST_DATA Sym *global_stack;
49 ST_DATA Sym *local_stack;
50 ST_DATA Sym *scope_stack_bottom;
51 ST_DATA Sym *define_stack;
52 ST_DATA Sym *global_label_stack;
53 ST_DATA Sym *local_label_stack;
54 
55 ST_DATA int vla_sp_loc_tmp;	/* vla_sp_loc is set to this when the value won't be needed later */
56 ST_DATA int vla_sp_root_loc;	/* vla_sp_loc for SP before any VLAs were pushed */
57 ST_DATA int *vla_sp_loc;/* Pointer to variable holding location to store stack pointer on the stack when modifying stack pointer */
58 ST_DATA int vla_flags;	/* VLA_* flags */
59 
60 ST_DATA SValue __vstack[1 + VSTACK_SIZE], *vtop;
61 
62 ST_DATA int const_wanted;	/* true if constant wanted */
63 ST_DATA int nocode_wanted;	/* true if no code generation wanted for an expression */
64 ST_DATA int global_expr;	/* true if compound literals must be allocated globally (used during initializers parsing */
65 ST_DATA CType func_vt;	/* current function return type (used by return instruction) */
66 ST_DATA int func_vc;
67 ST_DATA int last_line_num, last_ind, func_ind;	/* debug last line number and pc */
68 ST_DATA char *funcname;
69 ST_DATA char *dir_name;
70 
71 ST_DATA CType char_pointer_type, func_old_type;
72 ST_DATA CType int8_type, int16_type, int32_type, int64_type, size_type;
73 
74 /* ------------------------------------------------------------------------- */
75 static inline CType *pointed_type(CType *type);
76 static int is_compatible_types(CType *type1, CType *type2);
77 static int parse_btype(CType *type, AttributeDef *ad);
78 static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
79 static void parse_expr_type(CType *type);
80 static void decl_initializer(CType *type, unsigned long c, int first, int size_only);
81 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, char *asm_label, int scope);
82 static int decl0(int l, int is_for_loop_init);
83 static void expr_eq(void);
84 static void unary_type(CType *type);
85 static int is_compatible_parameter_types(CType *type1, CType *type2);
86 static void expr_type(CType *type);
87 
88 /* ------------------------------------------------------------------------- */
is_structured(CType * t)89 ST_INLN bool is_structured(CType *t) {
90 	return (t->t & VT_BTYPE) == VT_STRUCT || (t->t & VT_BTYPE) == VT_UNION;
91 }
92 
is_struct(CType * t)93 ST_INLN bool is_struct(CType *t) {
94 	return (t->t & VT_BTYPE) == VT_STRUCT;
95 }
96 
is_union(CType * t)97 ST_INLN bool is_union(CType *t) {
98 	return (t->t & VT_BTYPE) == VT_UNION;
99 }
100 
is_enum(CType * t)101 ST_INLN bool is_enum(CType *t) {
102 	return (t->t & VT_BTYPE) == VT_ENUM;
103 }
104 
is_float(int t)105 ST_INLN bool is_float(int t) {
106 	int bt;
107 	bt = t & VT_BTYPE;
108 	return bt == VT_LDOUBLE || bt == VT_DOUBLE || bt == VT_FLOAT || bt == VT_QFLOAT;
109 }
110 
not_structured(CType * t)111 ST_INLN bool not_structured(CType *t) {
112 	return (t->t & VT_BTYPE) != VT_STRUCT && (t->t & VT_BTYPE) != VT_UNION;
113 }
114 
115 /* ------------------------------------------------------------------------- */
116 /* we use our own 'finite' function to avoid potential problems with
117    non standard math libs */
118 /* XXX: endianness dependent */
ieee_finite(double d)119 ST_FUNC int ieee_finite(double d) {
120 	int *p = (int *) &d;
121 	return ((unsigned) ((p[1] | 0x800fffff) + 1)) >> 31;
122 }
123 
test_lvalue(void)124 ST_FUNC void test_lvalue(void) {
125 	if (!(vtop->r & VT_LVAL)) {
126 		expect ("lvalue");
127 	}
128 }
129 
130 /* ------------------------------------------------------------------------- */
131 /* symbol allocator */
__sym_malloc(void)132 static Sym *__sym_malloc(void) {
133 	Sym *sym_pool, *sym, *last_sym;
134 	int i;
135 	int sym_pool_size = SYM_POOL_NB * sizeof(Sym);
136 	sym_pool = malloc (sym_pool_size);
137 	memset (sym_pool, 0, sym_pool_size);
138 	dynarray_add (&sym_pools, &nb_sym_pools, sym_pool);
139 
140 	last_sym = sym_free_first;
141 	sym = sym_pool;
142 	for (i = 0; i < SYM_POOL_NB; i++) {
143 		sym->next = last_sym;
144 		last_sym = sym;
145 		sym++;
146 	}
147 	sym_free_first = last_sym;
148 	return last_sym;
149 }
150 
sym_malloc(void)151 static inline Sym *sym_malloc(void) {
152 	Sym *sym;
153 	sym = sym_free_first;
154 	if (!sym) {
155 		sym = __sym_malloc ();
156 	}
157 	sym_free_first = sym->next;
158 	return sym;
159 }
160 
sym_free(Sym * sym)161 ST_INLN void sym_free(Sym *sym) {
162 	sym->next = sym_free_first;
163 	free (sym->asm_label);
164 	sym_free_first = sym;
165 }
166 
167 /* push, without hashing */
sym_push2(Sym ** ps,int v,int t,long long c)168 ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long long c) {
169 	Sym *s;
170 	if (ps == &local_stack) {
171 		for (s = *ps; s && s != scope_stack_bottom; s = s->prev) {
172 			if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM && s->v == v) {
173 				tcc_error ("incompatible types for redefinition of '%s'",
174 					get_tok_str (v, NULL));
175 				return NULL;
176 			}
177 		}
178 	}
179 	// printf (" %d %ld set symbol '%s'\n", t, c, get_tok_str(v, NULL));
180 	// s = *ps;
181 	s = sym_malloc ();
182 	s->asm_label = NULL;
183 	s->v = v;
184 	s->type.t = t;
185 	s->type.ref = NULL;
186 #ifdef _WIN64
187 	s->d = NULL;
188 #endif
189 	s->c = c;
190 	s->next = NULL;
191 	/* add in stack */
192 	s->prev = *ps;
193 	*ps = s;
194 	return s;
195 }
196 
197 /* find a symbol and return its associated structure. 's' is the top
198    of the symbol stack */
sym_find2(Sym * s,int v)199 ST_FUNC Sym *sym_find2(Sym *s, int v) {
200 	while (s) {
201 		if (s->v == v) {
202 			return s;
203 		}
204 		s = s->prev;
205 	}
206 	return NULL;
207 }
208 
209 /* structure lookup */
struct_find(int v)210 ST_INLN Sym *struct_find(int v) {
211 	v -= TOK_IDENT;
212 	if ((unsigned) v >= (unsigned) (tok_ident - TOK_IDENT)) {
213 		return NULL;
214 	}
215 	return table_ident[v]->sym_struct;
216 }
217 
218 /* find an identifier */
sym_find(int v)219 ST_INLN Sym *sym_find(int v) {
220 	v -= TOK_IDENT;
221 	if ((unsigned) v >= (unsigned) (tok_ident - TOK_IDENT)) {
222 		return NULL;
223 	}
224 	return table_ident[v]->sym_identifier;
225 }
226 
227 // TODO: Add better way to store the meta information
228 // about the pushed type
tcc_sym_push(char * typename,int typesize,int meta)229 int tcc_sym_push(char *typename, int typesize, int meta) {
230 	CType *new_type = (CType *) malloc (sizeof(CType));
231 	if (!new_type) {
232 		return 0;
233 	}
234 	new_type->ref = sym_malloc ();
235 	new_type->t = meta;
236 
237 	if (!sym_push (0, new_type, 0, 0)) {
238 		return 0;
239 	}
240 
241 	free (new_type);
242 	return 1;
243 }
244 
dump_type(CType * type,int depth)245 void dump_type(CType *type, int depth) {
246 	if (depth <= 0) {
247 		return;
248 	}
249 	eprintf ("------------------------\n");
250 	int bt = type->t & VT_BTYPE;
251 	eprintf ("BTYPE = %d ", bt);
252 	switch (bt) {
253 	case VT_UNION: eprintf ("[UNION]\n");
254 		break;
255 	case VT_STRUCT: eprintf ("[STRUCT]\n");
256 		break;
257 	case VT_PTR: eprintf ("[PTR]\n");
258 		break;
259 	case VT_ENUM: eprintf ("[ENUM]\n");
260 		break;
261 	case VT_INT64: eprintf ("[INT64_T]\n");
262 		break;
263 	case VT_INT32: eprintf ("[INT32_T]\n");
264 		break;
265 	case VT_INT16: eprintf ("[INT16_T]\n");
266 		break;
267 	case VT_INT8: eprintf ("[INT8_T]\n");
268 		break;
269 	default:
270 		eprintf ("\n");
271 		break;
272 	}
273 	if (type->ref) {
274 		eprintf ("v = %d\n", type->ref->v);
275 		char *varstr = NULL;
276 		varstr = get_tok_str (type->ref->v, NULL);
277 		if (varstr) {
278 			eprintf ("var = %s\n", varstr);
279 		}
280 		if (type->ref->asm_label) {
281 			eprintf ("asm_label = %s\n", type->ref->asm_label);
282 		}
283 		eprintf ("r = %d\n", type->ref->r);
284 		eprintf ("associated type:\n");
285 		// dump_type(&(type->ref->type), --depth);
286 	}
287 }
288 
289 /* push a given symbol on the symbol stack */
sym_push(int v,CType * type,int r,long long c)290 ST_FUNC Sym *sym_push(int v, CType *type, int r, long long c) {
291 	Sym *s, **ps;
292 	TokenSym *ts;
293 
294 	if (local_stack) {
295 		ps = &local_stack;
296 	} else {
297 		ps = &global_stack;
298 	}
299 	// dump_type(type, 5);
300 	s = sym_push2 (ps, v, type->t, c);
301 	if (!s) {
302 		return NULL;
303 	}
304 	s->type.ref = type->ref;
305 	s->r = r;
306 	/* don't record fields or anonymous symbols */
307 	/* XXX: simplify */
308 	if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
309 		int i = (v & ~SYM_STRUCT);
310 		if (i < TOK_IDENT) {
311 			return NULL;
312 		}
313 		// ts = table_ident[i - TOK_IDENT];
314 		/* record symbol in token array */
315 		ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
316 		if (v & SYM_STRUCT) {
317 			ps = &ts->sym_struct;
318 		} else {
319 			ps = &ts->sym_identifier;
320 		}
321 		s->prev_tok = *ps;
322 		*ps = s;
323 	}
324 	return s;
325 }
326 
327 /* push a global identifier */
global_identifier_push(int v,int t,long long c)328 ST_FUNC Sym *global_identifier_push(int v, int t, long long c) {
329 	Sym *s, **ps;
330 	s = sym_push2 (&global_stack, v, t, c);
331 	/* don't record anonymous symbol */
332 	if (s && v < SYM_FIRST_ANOM) {
333 		int i = (v & ~SYM_STRUCT);
334 		if (i < TOK_IDENT) {
335 			eprintf ("Not found\n");
336 			return NULL;
337 		}
338 		ps = &table_ident[i - TOK_IDENT]->sym_identifier;
339 		/* modify the top most local identifier, so that
340 		   sym_identifier will point to 's' when popped */
341 		while (*ps) {
342 			ps = &(*ps)->prev_tok;
343 		}
344 		s->prev_tok = NULL;
345 		*ps = s;
346 	}
347 	return s;
348 }
349 
350 /* pop symbols until top reaches 'b' */
sym_pop(Sym ** ptop,Sym * b)351 ST_FUNC void sym_pop(Sym **ptop, Sym *b) {
352 	Sym *s, *ss, **ps;
353 	TokenSym *ts;
354 	int v;
355 	if (!b) {
356 		return;
357 	}
358 
359 	s = *ptop;
360 	while (s != b) {
361 		ss = s->prev;
362 		v = s->v;
363 		/* remove symbol in token array */
364 		/* XXX: simplify */
365 		if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
366 			int i = (v & ~SYM_STRUCT);
367 			if (i < TOK_IDENT) {
368 				eprintf ("Not found\n");
369 				return;
370 			}
371 			ts = table_ident[i - TOK_IDENT]; //(v & ~SYM_STRUCT) - TOK_IDENT];
372 			if (v & SYM_STRUCT) {
373 				ps = &ts->sym_struct;
374 			} else {
375 				ps = &ts->sym_identifier;
376 			}
377 			*ps = s->prev_tok;
378 		}
379 		sym_free (s);
380 		s = ss;
381 	}
382 	*ptop = b;
383 }
384 
weaken_symbol(Sym * sym)385 static void weaken_symbol(Sym *sym) {
386 	sym->type.t |= VT_WEAK;
387 }
388 
389 /* ------------------------------------------------------------------------- */
390 
swap(int * p,int * q)391 ST_FUNC void swap(int *p, int *q) {
392 	int t;
393 	t = *p;
394 	*p = *q;
395 	*q = t;
396 }
397 
vsetc(CType * type,int r,CValue * vc)398 static void vsetc(CType *type, int r, CValue *vc) {
399 	if (vtop >= vstack + (VSTACK_SIZE - 1)) {
400 		TCC_ERR ("memory full");
401 	}
402 	vtop++;
403 	vtop->type = *type;
404 	vtop->r = r;
405 	vtop->r2 = VT_CONST;
406 	vtop->c = *vc;
407 }
408 
409 /* push constant of type "type" with useless value */
vpush(CType * type)410 void vpush(CType *type) {
411 	CValue cval = { 0 };
412 	vsetc (type, VT_CONST, &cval);
413 }
414 
415 /* push integer constant */
vpushi(int v)416 ST_FUNC void vpushi(int v) {
417 	CValue cval = { 0 };
418 	cval.i = v;
419 	vsetc (&int32_type, VT_CONST, &cval);
420 }
421 
422 /* push a pointer sized constant */
vpushs(long long v)423 static void vpushs(long long v) {
424 	CValue cval;
425 	if (PTR_SIZE == 4) {
426 		cval.i = (int) v;
427 	} else {
428 		cval.ull = v;
429 	}
430 	vsetc (&size_type, VT_CONST, &cval);
431 }
432 
433 /* push arbitrary 64 bit constant */
vpush64(int ty,unsigned long long v)434 void vpush64(int ty, unsigned long long v) {
435 	CValue cval;
436 	CType ctype;
437 	ctype.t = ty;
438 	ctype.ref = NULL;
439 	cval.ull = v;
440 	vsetc (&ctype, VT_CONST, &cval);
441 }
442 
443 /* push long long constant */
vpushll(long long v)444 ST_FUNC void vpushll(long long v) {
445 	CValue cval;
446 	cval.ll = v;
447 	vsetc (&int64_type, VT_CONST, &cval);
448 }
449 
vset(CType * type,int r,int v)450 ST_FUNC void vset(CType *type, int r, int v) {
451 	CValue cval;
452 
453 	cval.i = v;
454 	vsetc (type, r, &cval);
455 }
456 
vseti(int r,int v)457 static void vseti(int r, int v) {
458 	CType type = { 0 };
459 	type.t = VT_INT32;
460 	type.ref = NULL;
461 	vset (&type, r, v);
462 }
463 
vswap(void)464 ST_FUNC void vswap(void) {
465 	SValue tmp;
466 	/* cannot let cpu flags if other instruction are generated. Also
467 	   avoid leaving VT_JMP anywhere except on the top of the stack
468 	   because it would complicate the code generator. */
469 	tmp = vtop[0];
470 	vtop[0] = vtop[-1];
471 	vtop[-1] = tmp;
472 
473 /* XXX: +2% overall speed possible with optimized memswap
474  *
475  *  memswap(&vtop[0], &vtop[1], sizeof *vtop);
476  */
477 }
478 
vpushv(SValue * v)479 ST_FUNC void vpushv(SValue *v) {
480 	if (vtop >= vstack + (VSTACK_SIZE - 1)) {
481 		TCC_ERR ("memory full");
482 	}
483 	vtop++;
484 	*vtop = *v;
485 }
486 
vdup(void)487 static void vdup(void) {
488 	vpushv (vtop);
489 }
490 
491 /* get address of vtop (vtop MUST BE an lvalue) */
gaddrof(void)492 static void gaddrof(void) {
493 	vtop->r &= ~VT_LVAL;
494 	/* tricky: if saved lvalue, then we can go back to lvalue */
495 	if ((vtop->r & VT_VALMASK) == VT_LLOCAL) {
496 		vtop->r = (vtop->r & ~(VT_VALMASK | VT_LVAL_TYPE)) | VT_LOCAL | VT_LVAL;
497 	}
498 }
499 
pointed_size(CType * type)500 static int pointed_size(CType *type) {
501 	int align;
502 	return type_size (pointed_type (type), &align);
503 }
504 
is_integer_btype(int bt)505 static inline int is_integer_btype(int bt) {
506 	return bt == VT_INT8 || bt == VT_INT16 || bt == VT_INT32 || bt == VT_INT64;
507 }
508 
509 /* return type size as known at compile time. Put alignment at 'a' */
type_size(CType * type,int * a)510 ST_FUNC int type_size(CType *type, int *a) {
511 	Sym *s;
512 	int bt;
513 
514 	bt = type->t & VT_BTYPE;
515 	if (is_structured(type)) {
516 		/* struct/union */
517 		s = type->ref;
518 		*a = s->r;
519 		return s->c;
520 	} else if (bt == VT_PTR) {
521 		if (type->t & VT_ARRAY) {
522 			int ts;
523 
524 			s = type->ref;
525 			ts = type_size (&s->type, a);
526 
527 			if (ts < 0 && s->c < 0) {
528 				ts = -ts;
529 			}
530 
531 			return ts * s->c;
532 		} else {
533 			*a = PTR_SIZE;
534 			return PTR_SIZE;
535 		}
536 	} else if (bt == VT_LDOUBLE) {
537 		*a = LDOUBLE_ALIGN;
538 		return LDOUBLE_SIZE;
539 	} else if (bt == VT_DOUBLE || bt == VT_INT64) {
540 		if (!strncmp (tcc_state->arch, "x86", 3) && tcc_state->bits == 32) {
541 			if (!strncmp (tcc_state->os, "windows", 7)) {
542 				*a = 8;
543 			} else {
544 				*a = 4;
545 			}
546 		} else if (!strncmp (tcc_state->arch, "arm", 3)) {
547 			/* It was like originally:
548 			        #ifdef TCC_ARM_EABI
549 			                *a = 8;
550 			        #else
551 			        *a = 4;
552 			        #endif
553 			        FIXME: Determine EABI then too
554 			*/
555 			*a = 8;
556 		} else {
557 			*a = 8;
558 		}
559 		return 8;
560 	} else if (bt == VT_ENUM) {
561 		/* Non standard, but still widely used
562 		 * and implemented in GCC, MSVC */
563 		*a = 8;
564 		return 8;
565 	} else if (bt == VT_INT32 || bt == VT_FLOAT) {
566 		*a = 4;
567 		return 4;
568 	} else if (bt == VT_INT16) {
569 		*a = 2;
570 		return 2;
571 	} else if (bt == VT_QLONG || bt == VT_QFLOAT) {
572 		*a = 8;
573 		return 16;
574 	} else {
575 		/* char, void, function, _Bool */
576 		*a = 1;
577 		return 1;
578 	}
579 }
580 
581 /* return the pointed type of t */
pointed_type(CType * type)582 static inline CType *pointed_type(CType *type) {
583 	return &type->ref->type;
584 }
585 
586 /* modify type so that its it is a pointer to type. */
mk_pointer(CType * type)587 ST_FUNC void mk_pointer(CType *type) {
588 	Sym *s;
589 	s = sym_push (SYM_FIELD, type, 0, -1);
590 	if (!s) {
591 		return;
592 	}
593 	type->t = VT_PTR | (type->t & ~VT_TYPE);
594 	type->ref = s;
595 }
596 
597 /* compare function types. OLD functions match any new functions */
is_compatible_func(CType * type1,CType * type2)598 static int is_compatible_func(CType *type1, CType *type2) {
599 	Sym *s1, *s2;
600 
601 	s1 = type1->ref;
602 	s2 = type2->ref;
603 	if (!is_compatible_types (&s1->type, &s2->type)) {
604 		return 0;
605 	}
606 	/* check func_call */
607 	if (FUNC_CALL (s1->r) != FUNC_CALL (s2->r)) {
608 		return 0;
609 	}
610 	/* XXX: not complete */
611 	if (s1->c == FUNC_OLD || s2->c == FUNC_OLD) {
612 		return 1;
613 	}
614 	if (s1->c != s2->c) {
615 		return 0;
616 	}
617 	while (s1 != NULL) {
618 		if (s2 == NULL) {
619 			return 0;
620 		}
621 		if (!is_compatible_parameter_types (&s1->type, &s2->type)) {
622 			return 0;
623 		}
624 		s1 = s1->next;
625 		s2 = s2->next;
626 	}
627 	if (s2) {
628 		return 0;
629 	}
630 	return 1;
631 }
632 
633 /* return true if type1 and type2 are the same.  If unqualified is
634    true, qualifiers on the types are ignored.
635 
636    - enums are not checked as gcc __builtin_types_compatible_p ()
637  */
compare_types(CType * type1,CType * type2,int unqualified)638 static int compare_types(CType *type1, CType *type2, int unqualified) {
639 	int t1 = type1->t & VT_TYPE;
640 	int t2 = type2->t & VT_TYPE;
641 	if (unqualified) {
642 		/* strip qualifiers before comparing */
643 		t1 &= ~(VT_CONSTANT | VT_VOLATILE);
644 		t2 &= ~(VT_CONSTANT | VT_VOLATILE);
645 	}
646 	/* XXX: bitfields ? */
647 	if (t1 != t2) {
648 		return 0;
649 	}
650 	/* test more complicated cases */
651 	int bt1 = t1 & VT_BTYPE;
652 	if (bt1 == VT_PTR) {
653 		type1 = pointed_type (type1);
654 		type2 = pointed_type (type2);
655 		return is_compatible_types (type1, type2);
656 	} else if (bt1 == VT_STRUCT || bt1 == VT_UNION) {
657 		return type1->ref == type2->ref;
658 	} else if (bt1 == VT_FUNC) {
659 		return is_compatible_func (type1, type2);
660 	} else {
661 		return 1;
662 	}
663 }
664 
665 /* return true if type1 and type2 are exactly the same (including
666    qualifiers).
667 */
is_compatible_types(CType * type1,CType * type2)668 static int is_compatible_types(CType *type1, CType *type2) {
669 	return compare_types (type1, type2, 0);
670 }
671 
672 /* return true if type1 and type2 are the same (ignoring qualifiers).
673 */
is_compatible_parameter_types(CType * type1,CType * type2)674 static int is_compatible_parameter_types(CType *type1, CType *type2) {
675 	return compare_types (type1, type2, 1);
676 }
677 
678 /* print a type. If 'varstr' is not NULL, then the variable is also
679    printed in the type */
680 /* XXX: union */
681 /* XXX: add array and function pointers */
type_to_str(char * buf,int buf_size,CType * type,const char * varstr)682 static void type_to_str(char *buf, int buf_size, CType *type, const char *varstr) {
683 	int bt, v, t;
684 	Sym *s, *sa;
685 	char buf1[256];
686 	const char *tstr;
687 	t = type->t & VT_TYPE;
688 	bt = t & VT_BTYPE;
689 	buf[0] = '\0';
690 	if (t & VT_CONSTANT) {
691 		pstrcat (buf, buf_size, "const ");
692 	}
693 	if (t & VT_VOLATILE) {
694 		pstrcat (buf, buf_size, "volatile ");
695 	}
696 	switch (bt) {
697 	case VT_VOID:
698 		tstr = "void";
699 		goto add_tstr;
700 	case VT_BOOL:
701 		tstr = "bool";
702 		goto add_tstr;
703 	case VT_INT8:
704 		if (t & VT_UNSIGNED) {
705 			tstr = "uint8_t";
706 		} else {
707 			if (t & VT_CHAR) {
708 				tstr = "char";
709 			} else {
710 				tstr = "int8_t";
711 			}
712 		}
713 		goto add_tstr;
714 	case VT_INT16:
715 		if (t & VT_UNSIGNED) {
716 			tstr = "uint16_t";
717 		} else {
718 			tstr = "int16_t";
719 		}
720 		goto add_tstr;
721 	case VT_INT32:
722 		if (t & VT_UNSIGNED) {
723 			tstr = "uint32_t";
724 		} else {
725 			tstr = "int32_t";
726 		}
727 		goto add_tstr;
728 	case VT_LONG:
729 		tstr = "long";
730 		goto add_tstr;
731 	case VT_INT64:
732 		if (t & VT_UNSIGNED) {
733 			tstr = "uint64_t";
734 		} else {
735 			tstr = "int64_t";
736 		}
737 		goto add_tstr;
738 	case VT_FLOAT:
739 		tstr = "float";
740 		goto add_tstr;
741 	case VT_DOUBLE:
742 		tstr = "double";
743 		goto add_tstr;
744 	case VT_LDOUBLE:
745 		tstr = "long double";
746 add_tstr:
747 		pstrcat (buf, buf_size, tstr);
748 		if ((t & VT_UNSIGNED) && (bt != VT_INT8) &&
749 		    (bt != VT_INT16) && (bt != VT_INT32) &&
750 		    (bt != VT_INT64)) {
751 			pstrcat (buf, buf_size, "unsigned ");
752 		}
753 		break;
754 	case VT_ENUM:
755 	case VT_STRUCT:
756 	case VT_UNION:
757 		if (bt == VT_STRUCT) {
758 			tstr = "struct";
759 		} else if (bt == VT_UNION) {
760 			tstr = "union";
761 		} else {
762 			tstr = "enum";
763 		}
764 		pstrcat (buf, buf_size, tstr);
765 		v = type->ref->v & ~SYM_STRUCT;
766 		if (v < SYM_FIRST_ANOM) {
767 			pstrcat (buf, buf_size, " ");
768 			pstrcat (buf, buf_size, get_tok_str (v, NULL));
769 		}
770 		break;
771 	case VT_FUNC:
772 		s = type->ref;
773 		type_to_str (buf, buf_size, &s->type, varstr);
774 		pstrcat (buf, buf_size, "(");
775 		sa = s->next;
776 		while (sa != NULL) {
777 			type_to_str (buf1, sizeof(buf1), &sa->type, NULL);
778 			pstrcat (buf, buf_size, buf1);
779 			sa = sa->next;
780 			if (sa) {
781 				pstrcat (buf, buf_size, ", ");
782 			}
783 		}
784 		pstrcat (buf, buf_size, ")");
785 		goto no_var;
786 	case VT_PTR:
787 		s = type->ref;
788 		if (t & VT_ARRAY) {
789 			type_to_str (buf, buf_size, &s->type, NULL);
790 		} else {
791 			pstrcpy (buf1, sizeof(buf1), "*");
792 			if (varstr) {
793 				pstrcat (buf1, sizeof(buf1), varstr);
794 			}
795 			type_to_str (buf, buf_size, &s->type, buf1);
796 		}
797 		goto no_var;
798 	}
799 	if (varstr) {
800 		pstrcat (buf, buf_size, " ");
801 		pstrcat (buf, buf_size, varstr);
802 	}
803 no_var:
804 	;
805 }
806 
807 /* Parse GNUC __attribute__ extension. Currently, the following
808    extensions are recognized:
809    - aligned(n) : set data/function alignment.
810    - packed : force data alignment to 1
811    - unused : currently ignored, but may be used someday.
812    - regparm(n) : pass function parameters in registers (i386 only)
813  */
parse_attribute(AttributeDef * ad)814 static void parse_attribute(AttributeDef *ad) {
815 	int t;
816 	long long n;
817 
818 	while (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
819 		next ();
820 		skip ('(');
821 		skip ('(');
822 		while (tok != ')') {
823 			if (tok < TOK_IDENT) {
824 				expect ("attribute name");
825 			}
826 			t = tok;
827 			next ();
828 			switch (t) {
829 			case TOK_ALIAS1:
830 			case TOK_ALIAS2:
831 				skip ('(');
832 				if (tok != TOK_STR) {
833 					expect ("alias(\"target\")");
834 				}
835 				ad->alias_target =	/* save string as token, for later */
836 						   tok_alloc ((char *) tokc.cstr->data, tokc.cstr->size - 1)->tok;
837 				next ();
838 				skip (')');
839 				break;
840 			case TOK_ALIGNED1:
841 			case TOK_ALIGNED2:
842 				if (tok == '(') {
843 					next ();
844 					n = expr_const ();
845 					if (n <= 0 || (n & (n - 1)) != 0) {
846 						TCC_ERR ("alignment must be a positive power of two");
847 					}
848 					skip (')');
849 				} else {
850 					n = MAX_ALIGN;
851 				}
852 				ad->aligned = n;
853 				break;
854 			case TOK_PACKED1:
855 			case TOK_PACKED2:
856 				ad->packed = 1;
857 				break;
858 			case TOK_WEAK1:
859 			case TOK_WEAK2:
860 				ad->weak = 1;
861 				break;
862 			case TOK_UNUSED1:
863 			case TOK_UNUSED2:
864 				/* currently, no need to handle it because tcc does not
865 				   track unused objects */
866 				break;
867 			case TOK_NORETURN1:
868 			case TOK_NORETURN2:
869 				/* currently, no need to handle it because tcc does not
870 				   track unused objects */
871 				break;
872 			case TOK_CDECL1:
873 			case TOK_CDECL2:
874 			case TOK_CDECL3:
875 				ad->func_call = FUNC_CDECL;
876 				break;
877 			case TOK_STDCALL1:
878 			case TOK_STDCALL2:
879 			case TOK_STDCALL3:
880 				ad->func_call = FUNC_STDCALL;
881 				break;
882 #ifdef TCC_TARGET_I386
883 			case TOK_REGPARM1:
884 			case TOK_REGPARM2:
885 				skip ('(');
886 				n = expr_const ();
887 				if (n > 3) {
888 					n = 3;
889 				} else if (n < 0) {
890 					n = 0;
891 				}
892 				if (n > 0) {
893 					ad->func_call = FUNC_FASTCALL1 + n - 1;
894 				}
895 				skip (')');
896 				break;
897 			case TOK_FASTCALL1:
898 			case TOK_FASTCALL2:
899 			case TOK_FASTCALL3:
900 				ad->func_call = FUNC_FASTCALLW;
901 				break;
902 #endif
903 			case TOK_MODE:
904 				skip ('(');
905 				switch (tok) {
906 				case TOK_MODE_DI:
907 					ad->mode = VT_INT64 + 1;
908 					break;
909 				case TOK_MODE_HI:
910 					ad->mode = VT_INT16 + 1;
911 					break;
912 				case TOK_MODE_SI:
913 					ad->mode = VT_INT32 + 1;
914 					break;
915 				default:
916 					tcc_warning ("__mode__(%s) not supported\n", get_tok_str (tok, NULL));
917 					break;
918 				}
919 				next ();
920 				skip (')');
921 				break;
922 			case TOK_DLLEXPORT:
923 				ad->func_export = 1;
924 				break;
925 			case TOK_DLLIMPORT:
926 				ad->func_import = 1;
927 				break;
928 			default:
929 				if (tcc_state->warn_unsupported) {
930 					tcc_warning ("'%s' attribute ignored", get_tok_str (t, NULL));
931 				}
932 				/* skip parameters */
933 				if (tok == '(') {
934 					int parenthesis = 0;
935 					do {
936 						if (tok == '(') {
937 							parenthesis++;
938 						} else if (tok == ')') {
939 							parenthesis--;
940 						}
941 						next ();
942 					} while (parenthesis && tok != -1);
943 				}
944 				break;
945 			}
946 			if (tok != ',') {
947 				break;
948 			}
949 			next ();
950 		}
951 		skip (')');
952 		skip (')');
953 	}
954 }
955 
956 /* enum/struct/union declaration. u is either VT_ENUM, VT_STRUCT or VT_UNION */
struct_decl(CType * type,int u,bool is_typedef)957 static void struct_decl(CType *type, int u, bool is_typedef) {
958 	int a, v, size, align, maxalign, offset;
959 	long long c = 0;
960 	int bit_size, bit_pos, bsize, bt, lbit_pos, prevbt;
961 	char buf[STRING_MAX_SIZE + 1];
962 	Sym *s, *ss, *ass, **ps;
963 	AttributeDef ad;
964 	const char *name = NULL;
965 	bool autonamed = false;
966 	STACK_NEW0 (CType, type1);
967 	STACK_NEW0 (CType, btype);
968 
969 	a = tok;/* save decl type */
970 	next ();
971 	name = get_tok_str (tok, NULL);
972 	if (tok != '{') {
973 		v = tok;
974 		next ();
975 		/* struct already defined ? return it */
976 		if (v < TOK_IDENT) {
977 			expect ("struct/union/enum name");
978 		}
979 		s = struct_find (v);
980 		if (s) {
981 			if (s->type.t != a) {
982 				TCC_ERR ("invalid type");
983 			}
984 			goto do_decl;
985 		}
986 	} else {
987 		v = anon_sym++;
988 		snprintf (buf, sizeof(buf), "%u", v - SYM_FIRST_ANOM);
989 		name = buf;
990 		autonamed = true;
991 	}
992 	type1.t = a;
993 	/* we put an undefined size for struct/union/enum */
994 	s = sym_push (v | SYM_STRUCT, &type1, 0, -1);
995 	if (!s) {
996 		return;
997 	}
998 	s->r = 0;	/* default alignment is zero as gcc */
999 	/* put struct/union/enum name in type */
1000 	/* TODO: Extract this part into the separate functions per type */
1001 do_decl:
1002 	type->t = u;
1003 	type->ref = s;
1004 
1005 	if (tok == '{') {
1006 		next ();
1007 		if (s->c != -1) {
1008 			TCC_ERR ("struct/union/enum already defined");
1009 		}
1010 		/* cannot be empty */
1011 		c = 0LL;
1012 		/* non empty enums are not allowed */
1013 		if (a == TOK_ENUM) {
1014 			if (!strcmp (name, "{")) {
1015 				// UNNAMED
1016 				fprintf (stderr, "anonymous enums are ignored\n");
1017 			}
1018 			while (tcc_nerr () == 0) {
1019 				v = tok;
1020 				if (v < TOK_UIDENT) {
1021 					expect ("identifier");
1022 				}
1023 				next ();
1024 				if (tok == '=') {
1025 					next ();
1026 					c = expr_const ();
1027 				}
1028 				// TODO: use is_typedef here
1029 				if (strcmp (name, "{")) {
1030 					char *varstr = get_tok_str (v, NULL);
1031 					tcc_appendf ("%s=enum\n", name);
1032 					tcc_appendf ("[+]enum.%s=%s\n",name, varstr);
1033 					tcc_appendf ("enum.%s.%s=0x%"PFMT64x "\n", name, varstr, c);
1034 					tcc_appendf ("enum.%s.0x%"PFMT64x "=%s\n", name, c, varstr);
1035 					// TODO: if token already defined throw an error
1036 					// if (varstr isInside (arrayOfvars)) { erprintf ("ERROR: DUP VAR IN ENUM\n"); }
1037 				}
1038 				/* enum symbols have static storage */
1039 				ss = sym_push (v, &int64_type, VT_CONST, c);
1040 				if (!ss) {
1041 					return;
1042 				}
1043 				ss->type.t |= VT_STATIC;
1044 				if (tok != ',') {
1045 					break;
1046 				}
1047 				next ();
1048 				c++;
1049 				/* NOTE: we accept a trailing comma */
1050 				if (tok == '}') {
1051 					break;
1052 				}
1053 			}
1054 			skip ('}');
1055 		} else {
1056 			maxalign = 1;
1057 			ps = &s->next;
1058 			prevbt = VT_INT32;
1059 			bit_pos = 0;
1060 			offset = 0;
1061 
1062 			const char *ctype = (a == TOK_UNION)? "union": "struct";
1063 			if (!is_typedef || !autonamed) {
1064 				tcc_appendf ("%s=%s\n", name, ctype);
1065 			}
1066 
1067 			while (tok != '}') {
1068 				if (!parse_btype (&btype, &ad)) {
1069 					expect ("bracket");
1070 					break;
1071 				}
1072 				while (tcc_nerr () == 0) {
1073 					bit_size = -1;
1074 					v = 0;
1075 					memcpy (&type1, &btype, sizeof(type1));
1076 					if (tok != ':') {
1077 						type_decl (&type1, &ad, &v, TYPE_DIRECT | TYPE_ABSTRACT);
1078 						if (v == 0 && not_structured(&type1)) {
1079 							expect ("identifier");
1080 						}
1081 						if ((type1.t & VT_BTYPE) == VT_FUNC ||
1082 						    (type1.t & (VT_TYPEDEF | VT_STATIC | VT_EXTERN | VT_INLINE))) {
1083 							TCC_ERR ("invalid type for '%s'",
1084 								get_tok_str (v, NULL));
1085 						}
1086 					}
1087 					if (tok == ':') {
1088 						next ();
1089 						bit_size = (int) expr_const ();
1090 						/* XXX: handle v = 0 case for messages */
1091 						if (bit_size < 0) {
1092 							TCC_ERR ("negative width in bit-field '%s'",
1093 								get_tok_str (v, NULL));
1094 						}
1095 						if (v && bit_size == 0) {
1096 							TCC_ERR ("zero width for bit-field '%s'",
1097 								get_tok_str (v, NULL));
1098 						}
1099 					}
1100 					size = type_size (&type1, &align);
1101 					if (ad.aligned) {
1102 						if (align < ad.aligned) {
1103 							align = ad.aligned;
1104 						}
1105 					} else if (ad.packed) {
1106 						align = 1;
1107 					} else if (*tcc_state->pack_stack_ptr) {
1108 						if (align > *tcc_state->pack_stack_ptr) {
1109 							align = *tcc_state->pack_stack_ptr;
1110 						}
1111 					}
1112 					lbit_pos = 0;
1113 					// FIXME: Here it handles bitfields only in a way
1114 					// of the same endianess as the host system (this code was compiled for)
1115 					// It should depend on the endianess of the `asm.arch` instead.
1116 					if (bit_size >= 0) {
1117 						bt = type1.t & VT_BTYPE;
1118 						if (bt != VT_INT8 &&
1119 						    bt != VT_INT16 &&
1120 						    bt != VT_INT32 &&
1121 						    bt != VT_INT64 &&
1122 						    bt != VT_ENUM &&
1123 						    bt != VT_BOOL) {
1124 							TCC_ERR ("bitfields must have scalar type");
1125 						}
1126 						bsize = size * 8;
1127 						if (bit_size > bsize) {
1128 							TCC_ERR ("width of '%s' exceeds its type",
1129 								get_tok_str (v, NULL));
1130 						} else if (bit_size == bsize) {
1131 							/* no need for bit fields */
1132 							bit_pos = 0;
1133 						} else if (bit_size == 0) {
1134 							/* XXX: what to do if only padding in a
1135 							   structure ? */
1136 							/* zero size: means to pad */
1137 							bit_pos = 0;
1138 						} else {
1139 							/* we do not have enough room ?
1140 							   did the type change?
1141 							   is it a union? */
1142 							if ((bit_pos + bit_size) > bsize ||
1143 							    bt != prevbt || a == TOK_UNION) {
1144 								bit_pos = 0;
1145 							}
1146 							lbit_pos = bit_pos;
1147 							/* XXX: handle LSB first */
1148 							type1.t |= VT_BITFIELD |
1149 								   (bit_pos << VT_STRUCT_SHIFT) |
1150 								   (bit_size << (VT_STRUCT_SHIFT + 6));
1151 							bit_pos += bit_size;
1152 						}
1153 						prevbt = bt;
1154 					} else {
1155 						bit_pos = 0;
1156 					}
1157 					if (v != 0 || is_structured(&type1)) {
1158 						/* add new memory data only if starting
1159 						   bit field */
1160 						if (lbit_pos == 0) {
1161 							if (a == TOK_STRUCT) {
1162 								c = (c + align - 1) & - align;
1163 								offset = c;
1164 								if (size > 0) {
1165 									c += size;
1166 								}
1167 							} else {
1168 								offset = 0;
1169 								if (size > c) {
1170 									c = size;
1171 								}
1172 							}
1173 							if (align > maxalign) {
1174 								maxalign = align;
1175 							}
1176 						}
1177 #if 1
1178 						// TODO: Don't use such a small limit?
1179 						char b[1024];
1180 						char *varstr = get_tok_str (v, NULL);
1181 						type_to_str (b, sizeof(b), &type1, NULL);
1182 						{
1183 							int type_bt = type1.t & VT_BTYPE;
1184 							//eprintf("2: %s.%s = %s\n", ctype, name, varstr);
1185 							if (is_typedef && autonamed) {
1186 								tcc_typedef_appendf ("[+]typedef.%%s.fields=%s\n", varstr);
1187 								tcc_typedef_appendf ("typedef.%%s.%s.meta=%d\n", varstr, type_bt);
1188 								tcc_typedef_appendf ("typedef.%%s.%s=%s,%d,%d\n", varstr, b, offset, arraysize);
1189 							} else {
1190 								tcc_appendf ("[+]%s.%s=%s\n",
1191 									ctype, name, varstr);
1192 								tcc_appendf ("%s.%s.%s.meta=%d\n",
1193 									ctype, name, varstr, type_bt);
1194 								/* compact form */
1195 								tcc_appendf ("%s.%s.%s=%s,%d,%d\n",
1196 									ctype, name, varstr, b, offset, arraysize);
1197 							}
1198 #if 0
1199 							eprintf ("%s.%s.%s.type=%s\n", ctype, name, varstr, b);
1200 							eprintf ("%s.%s.%s.offset=%d\n", ctype, name, varstr, offset);
1201 							eprintf ("%s.%s.%s.array=%d\n", ctype, name, varstr, arraysize);
1202 #endif
1203 							// (%s) field (%s) offset=%d array=%d", name, b, get_tok_str(v, NULL), offset, arraysize);
1204 							arraysize = 0;
1205 							if (type1.t & VT_BITFIELD) {
1206 								tcc_appendf ("%s.%s.%s.bitfield.pos=%d\n",
1207 									ctype, name, varstr, (type1.t >> VT_STRUCT_SHIFT) & 0x3f);
1208 								tcc_appendf ("%s.%s.%s.bitfield.size=%d\n",
1209 									ctype, name, varstr, (type1.t >> (VT_STRUCT_SHIFT + 6)) & 0x3f);
1210 							}
1211 							// printf("\n");
1212 						}
1213 #endif
1214 					}
1215 					if (v == 0 && is_structured (&type1)) {
1216 						ass = type1.ref;
1217 						while ((ass = ass->next) != NULL) {
1218 							ss = sym_push (ass->v, &ass->type, 0, offset + ass->c);
1219 							if (!ss) {
1220 								return;
1221 							}
1222 							*ps = ss;
1223 							ps = &ss->next;
1224 						}
1225 					} else if (v) {
1226 						ss = sym_push (v | SYM_FIELD, &type1, 0, offset);
1227 						if (!ss) {
1228 							return;
1229 						}
1230 						*ps = ss;
1231 						ps = &ss->next;
1232 					}
1233 					if (tok == ';' || tok == TOK_EOF) {
1234 						break;
1235 					}
1236 					skip (',');
1237 				}
1238 				skip (';');
1239 			}
1240 			skip ('}');
1241 			/* store size and alignment */
1242 			s->c = (c + maxalign - 1) & - maxalign;
1243 			s->r = maxalign;
1244 		}
1245 	}
1246 }
1247 
1248 /* return 0 if no type declaration. otherwise, return the basic type
1249    and skip it.
1250  */
parse_btype(CType * type,AttributeDef * ad)1251 static int parse_btype(CType *type, AttributeDef *ad) {
1252 	int t, u, type_found, typespec_found, typedef_found;
1253 	Sym *s;
1254 	STACK_NEW0 (CType, type1);
1255 
1256 	memset (ad, 0, sizeof(AttributeDef));
1257 	type_found = 0;
1258 	typespec_found = 0;
1259 	typedef_found = 0;
1260 	/* FIXME: Make this dependent on the target */
1261 	t = 0;	/* default for 'int' */
1262 	while (tcc_nerr () == 0) {
1263 		switch (tok) {
1264 		case TOK_EXTENSION:
1265 			/* currently, we really ignore extension */
1266 			next ();
1267 			continue;
1268 
1269 		/*  ------------------------------------------------------------------  */
1270 		/*	basic types */
1271 		/*  ------------------------------------------------------------------  */
1272 
1273 		/* int8_t, uint8_t, char */
1274 		case TOK_UINT8:
1275 			t |= VT_UNSIGNED;
1276 			/* fall through */
1277 		case TOK_INT8:
1278 			u = VT_INT8;
1279 			goto basic_type;
1280 		case TOK_CHAR:
1281 			u = VT_INT8;
1282 			/* Mark as character type, for strings */
1283 			t |= VT_CHAR;
1284 basic_type:
1285 			next ();
1286 basic_type1:
1287 			if ((t & VT_BTYPE) != 0) {
1288 				tcc_error ("too many basic types");
1289 				return 0;
1290 			}
1291 			t |= u;
1292 			typespec_found = 1;
1293 			break;
1294 
1295 		/* void* */
1296 		case TOK_VOID:
1297 			u = VT_VOID;
1298 			goto basic_type;
1299 
1300 		/* int16_t, uint16_t, short */
1301 		case TOK_UINT16:
1302 			t |= VT_UNSIGNED;
1303 			/* fall through */
1304 		case TOK_INT16:
1305 		case TOK_SHORT:
1306 			u = VT_INT16;
1307 			goto basic_type;
1308 
1309 		/* int32_t, uint32_t, int */
1310 		case TOK_UINT32:
1311 			t |= VT_UNSIGNED;
1312 			/* fall through */
1313 		case TOK_INT32:
1314 			u = VT_INT32;
1315 			goto basic_type;
1316 		case TOK_INT:
1317 			next ();
1318 			typespec_found = 1;
1319 			break;
1320 
1321 		/* int64_t, uint64_t, long, long long */
1322 		case TOK_UINT64:
1323 			t |= VT_UNSIGNED;
1324 			/* fall through */
1325 		case TOK_INT64:
1326 			u = VT_INT64;
1327 			goto basic_type;
1328 		case TOK_LONG:
1329 			next ();
1330 			// FIXME: Better handling long and long long types
1331 			if ((t & VT_BTYPE) == VT_DOUBLE) {
1332 				if (strncmp (tcc_state->os, "windows", 7)) {
1333 					t = (t & ~VT_BTYPE) | VT_LDOUBLE;
1334 				}
1335 			} else if ((t & VT_BTYPE) == VT_LONG) {
1336 				t = (t & ~VT_BTYPE) | VT_INT64;
1337 			} else {
1338 				u = VT_LONG;
1339 				goto basic_type1;
1340 			}
1341 			break;
1342 		case TOK_BOOL:
1343 		case TOK_STDBOOL:
1344 			u = VT_BOOL;
1345 			goto basic_type;
1346 		case TOK_FLOAT:
1347 			u = VT_FLOAT;
1348 			goto basic_type;
1349 		case TOK_DOUBLE:
1350 			next ();
1351 			if ((t & VT_BTYPE) == VT_LONG) {
1352 				if (!strncmp (tcc_state->os, "windows", 7)) {
1353 					t = (t & ~VT_BTYPE) | VT_DOUBLE;
1354 				} else {
1355 					t = (t & ~VT_BTYPE) | VT_LDOUBLE;
1356 				}
1357 			} else {
1358 				u = VT_DOUBLE;
1359 				goto basic_type1;
1360 			}
1361 			break;
1362 		case TOK_ENUM:
1363 			struct_decl (&type1, VT_ENUM, (bool)(t & VT_ENUM));
1364 basic_type2:
1365 			u = type1.t;
1366 			type->ref = type1.ref;
1367 			goto basic_type1;
1368 		case TOK_STRUCT:
1369 			struct_decl (&type1, VT_STRUCT, (bool)(t & VT_TYPEDEF));
1370 			goto basic_type2;
1371 		case TOK_UNION:
1372 			struct_decl (&type1, VT_UNION, (bool)(t & VT_UNION));
1373 			goto basic_type2;
1374 
1375 		/* type modifiers */
1376 		case TOK_CONST1:
1377 		case TOK_CONST2:
1378 		case TOK_CONST3:
1379 			t |= VT_CONSTANT;
1380 			next ();
1381 			break;
1382 		case TOK_VOLATILE1:
1383 		case TOK_VOLATILE2:
1384 		case TOK_VOLATILE3:
1385 			t |= VT_VOLATILE;
1386 			next ();
1387 			break;
1388 		case TOK_SIGNED1:
1389 		case TOK_SIGNED2:
1390 		case TOK_SIGNED3:
1391 			typespec_found = 1;
1392 			t |= VT_SIGNED;
1393 			next ();
1394 			break;
1395 		case TOK_REGISTER:
1396 		case TOK_AUTO:
1397 		case TOK_RESTRICT1:
1398 		case TOK_RESTRICT2:
1399 		case TOK_RESTRICT3:
1400 			next ();
1401 			break;
1402 		case TOK_UNSIGNED:
1403 			t |= VT_UNSIGNED;
1404 			next ();
1405 			typespec_found = 1;
1406 			break;
1407 
1408 		/* storage */
1409 		case TOK_EXTERN:
1410 			t |= VT_EXTERN;
1411 			next ();
1412 			break;
1413 		case TOK_STATIC:
1414 			t |= VT_STATIC;
1415 			next ();
1416 			break;
1417 		case TOK_TYPEDEF:
1418 			t |= VT_TYPEDEF;
1419 			next ();
1420 			break;
1421 		case TOK_INLINE1:
1422 		case TOK_INLINE2:
1423 		case TOK_INLINE3:
1424 			t |= VT_INLINE;
1425 			next ();
1426 			break;
1427 
1428 		/* GNUC attribute */
1429 		case TOK_ATTRIBUTE1:
1430 		case TOK_ATTRIBUTE2:
1431 			parse_attribute (ad);
1432 			if (ad->mode) {
1433 				u = ad->mode - 1;
1434 				t = (t & ~VT_BTYPE) | u;
1435 			}
1436 			break;
1437 		/* GNUC typeof */
1438 		case TOK_TYPEOF1:
1439 		case TOK_TYPEOF2:
1440 		case TOK_TYPEOF3:
1441 			next ();
1442 			parse_expr_type (&type1);
1443 			/* remove all storage modifiers except typedef */
1444 			type1.t &= ~(VT_STORAGE & ~VT_TYPEDEF);
1445 			goto basic_type2;
1446 		default:
1447 			if (typespec_found || typedef_found) {
1448 				goto the_end;
1449 			}
1450 			s = sym_find (tok);
1451 			if (!s || !(s->type.t & VT_TYPEDEF)) {
1452 				goto the_end;
1453 			}
1454 			typedef_found = 1;
1455 			t |= (s->type.t & ~VT_TYPEDEF);
1456 			type->ref = s->type.ref;
1457 			if (s->r) {
1458 				/* get attributes from typedef */
1459 				if (0 == ad->aligned) {
1460 					ad->aligned = FUNC_ALIGN (s->r);
1461 				}
1462 				if (0 == ad->func_call) {
1463 					ad->func_call = FUNC_CALL (s->r);
1464 				}
1465 				ad->packed |= FUNC_PACKED (s->r);
1466 			}
1467 			next ();
1468 			typespec_found = 1;
1469 			break;
1470 		}
1471 		type_found = 1;
1472 	}
1473 the_end:
1474 	if ((t & (VT_SIGNED | VT_UNSIGNED)) == (VT_SIGNED | VT_UNSIGNED)) {
1475 		tcc_error ("signed and unsigned modifier");
1476 		return 0;
1477 	}
1478 	if (tcc_state->char_is_unsigned) {
1479 		if ((t & (VT_SIGNED | VT_UNSIGNED | VT_BTYPE)) == VT_INT8) {
1480 			t |= VT_UNSIGNED;
1481 		}
1482 	}
1483 	t &= ~VT_SIGNED;
1484 
1485 	/* long is never used as type */
1486 	if ((t & VT_BTYPE) == VT_LONG) {
1487 		if (!strncmp (tcc_state->os, "windows", 7) ||
1488 		    (!strncmp (tcc_state->arch, "x86", 3) && tcc_state->bits == 32)) {
1489 			t = (t & ~VT_BTYPE) | VT_INT32;
1490 		} else {
1491 			t = (t & ~VT_BTYPE) | VT_INT64;
1492 		}
1493 	}
1494 	type->t = t;
1495 
1496 	return type_found;
1497 }
1498 
1499 /* convert a function parameter type (array to pointer and function to
1500    function pointer) */
convert_parameter_type(CType * pt)1501 static inline void convert_parameter_type(CType *pt) {
1502 	/* remove const and volatile qualifiers (XXX: const could be used
1503 	   to indicate a const function parameter */
1504 	pt->t &= ~(VT_CONSTANT | VT_VOLATILE);
1505 	/* array must be transformed to pointer according to ANSI C */
1506 	pt->t &= ~VT_ARRAY;
1507 	if ((pt->t & VT_BTYPE) == VT_FUNC) {
1508 		mk_pointer (pt);
1509 	}
1510 }
1511 
post_type(CType * type,AttributeDef * ad)1512 static void post_type(CType *type, AttributeDef *ad) {
1513 	int n, l, t1, arg_size, align;
1514 	Sym **plast, *s, *first;
1515 	AttributeDef ad1;
1516 	CType pt;
1517 	char *symname = NULL;
1518 	int narg = 0;
1519 
1520 	if (tok == '(') {
1521 		/* function declaration */
1522 		next ();
1523 		l = 0;
1524 		first = NULL;
1525 		plast = &first;
1526 		{
1527 			const char *ret_type = global_type;
1528 			free (symname);
1529 			symname = strdup (global_symname);
1530 			tcc_appendf ("func.%s.ret=%s\n", symname, ret_type);
1531 			tcc_appendf ("func.%s.cc=%s\n", symname, "cdecl");	// TODO
1532 			tcc_appendf ("%s=func\n", symname);
1533 		}
1534 		arg_size = 0;
1535 		if (tok != ')') {
1536 			while (tcc_nerr () == 0) {
1537 				/* read param name and compute offset */
1538 				if (l != FUNC_OLD) {
1539 					if (!parse_btype (&pt, &ad1)) {
1540 						if (l) {
1541 							TCC_ERR ("invalid type");
1542 						} else {
1543 							l = FUNC_OLD;
1544 							goto old_proto;
1545 						}
1546 					}
1547 					l = FUNC_NEW;
1548 					if ((pt.t & VT_BTYPE) == VT_VOID && tok == ')') {
1549 						break;
1550 					}
1551 					type_decl (&pt, &ad1, &n, TYPE_DIRECT | TYPE_ABSTRACT);
1552 					if ((pt.t & VT_BTYPE) == VT_VOID) {
1553 						TCC_ERR ("parameter declared as void");
1554 					}
1555 					arg_size += (type_size (&pt, &align) + PTR_SIZE - 1) / PTR_SIZE;
1556 				} else {
1557 old_proto:
1558 					n = tok;
1559 					if (n < TOK_UIDENT) {
1560 						expect ("identifier");
1561 					}
1562 					pt.t = VT_INT32;
1563 					next ();
1564 				}
1565 				convert_parameter_type (&pt);
1566 				s = sym_push (n | SYM_FIELD, &pt, 0, 0);
1567 				if (!s) {
1568 					return;
1569 				} else {
1570 					char kind[1024];
1571 					type_to_str (kind, sizeof (kind), &pt, NULL);
1572 					tcc_appendf ("func.%s.arg.%d=%s,%s\n",
1573 						symname, narg, kind, global_symname);
1574 					narg++;
1575 				}
1576 				*plast = s;
1577 				plast = &s->next;
1578 				if (tok == ')') {
1579 					break;
1580 				}
1581 				skip (',');
1582 				if (l == FUNC_NEW && tok == TOK_DOTS) {
1583 					l = FUNC_ELLIPSIS;
1584 					next ();
1585 					break;
1586 				}
1587 			}
1588 		}
1589 		tcc_appendf ("func.%s.args=%d\n", symname, narg);
1590 		/* if no parameters, then old type prototype */
1591 		if (l == 0) {
1592 			l = FUNC_OLD;
1593 		}
1594 		skip (')');
1595 		/* NOTE: const is ignored in returned type as it has a special
1596 		   meaning in gcc / C++ */
1597 		type->t &= ~VT_CONSTANT;
1598 		/* some ancient pre-K&R C allows a function to return an array
1599 		   and the array brackets to be put after the arguments, such
1600 		   that "int c()[]" means something like "int[] c()" */
1601 		if (tok == '[') {
1602 			next ();
1603 			skip (']');	/* only handle simple "[]" */
1604 			type->t |= VT_PTR;
1605 		}
1606 		/* we push a anonymous symbol which will contain the function prototype */
1607 		ad->func_args = arg_size;
1608 		s = sym_push (SYM_FIELD, type, INT_ATTR (ad), l);
1609 		if (!s) {
1610 			return;
1611 		}
1612 		s->next = first;
1613 		type->t = VT_FUNC;
1614 		type->ref = s;
1615 		R_FREE (symname);
1616 	} else if (tok == '[') {
1617 		/* array definition */
1618 		next ();
1619 		if (tok == TOK_RESTRICT1) {
1620 			next ();
1621 		}
1622 		n = -1;
1623 		t1 = 0;
1624 		if (tok != ']') {
1625 			if (!local_stack || nocode_wanted) {
1626 				vpushll (expr_const ());
1627 			} else {
1628 				gexpr ();
1629 			}
1630 			if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST) {
1631 				n = vtop->c.i;
1632 				if (n < 0) {
1633 					TCC_ERR ("invalid array size");
1634 				}
1635 			} else {
1636 				if (!is_integer_btype (vtop->type.t & VT_BTYPE)) {
1637 					TCC_ERR ("size of variable length array should be an integer");
1638 				}
1639 				t1 = VT_VLA;
1640 			}
1641 		}
1642 		skip (']');
1643 		/* parse next post type */
1644 		post_type (type, ad);
1645 
1646 		/* we push an anonymous symbol which will contain the array
1647 		   element type */
1648 		arraysize = n;
1649 #if 0
1650 		if (n < 0) {
1651 			printf ("array with no size []\n");
1652 		} else {
1653 			printf ("PUSH SIZE %d\n", n);
1654 		}
1655 #endif
1656 		s = sym_push (SYM_FIELD, type, 0, n);
1657 		if (!s) {
1658 			return;
1659 		}
1660 		type->t = (t1? VT_VLA: VT_ARRAY) | VT_PTR;
1661 		type->ref = s;
1662 	}
1663 }
1664 
1665 /* Parse a type declaration (except basic type), and return the type
1666    in 'type'. 'td' is a bitmask indicating which kind of type decl is
1667    expected. 'type' should contain the basic type. 'ad' is the
1668    attribute definition of the basic type. It can be modified by
1669    type_decl().
1670  */
type_decl(CType * type,AttributeDef * ad,int * v,int td)1671 static void type_decl(CType *type, AttributeDef *ad, int *v, int td) {
1672 	Sym *s;
1673 	int qualifiers, storage;
1674 	CType *type1 = R_NEW0 (CType);
1675 	CType *type2 = R_NEW0 (CType);
1676 	if (!type1 || !type2) {
1677 		free (type1);
1678 		free (type2);
1679 		return;
1680 	}
1681 
1682 	while (tok == '*') {
1683 		qualifiers = 0;
1684 redo:
1685 		next ();
1686 		switch (tok) {
1687 		case TOK_CONST1:
1688 		case TOK_CONST2:
1689 		case TOK_CONST3:
1690 			qualifiers |= VT_CONSTANT;
1691 			goto redo;
1692 		case TOK_VOLATILE1:
1693 		case TOK_VOLATILE2:
1694 		case TOK_VOLATILE3:
1695 			qualifiers |= VT_VOLATILE;
1696 			goto redo;
1697 		case TOK_RESTRICT1:
1698 		case TOK_RESTRICT2:
1699 		case TOK_RESTRICT3:
1700 			goto redo;
1701 		}
1702 		mk_pointer (type);
1703 		type->t |= qualifiers;
1704 	}
1705 
1706 	/* XXX: clarify attribute handling */
1707 	if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
1708 		parse_attribute (ad);
1709 	}
1710 
1711 	/* recursive type */
1712 	/* XXX: incorrect if abstract type for functions (e.g. 'int ()') */
1713 	type1->t = 0;	/* XXX: same as int */
1714 	if (tok == '(') {
1715 		next ();
1716 		/* XXX: this is not correct to modify 'ad' at this point, but
1717 		   the syntax is not clear */
1718 		if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
1719 			parse_attribute (ad);
1720 		}
1721 		type_decl (type1, ad, v, td);
1722 		skip (')');
1723 	} else {
1724 		/* type identifier */
1725 		if (tok >= TOK_IDENT && (td & TYPE_DIRECT)) {
1726 			*v = tok;
1727 			next ();
1728 		} else {
1729 			if (!(td & TYPE_ABSTRACT)) {
1730 				expect ("identifier");
1731 			}
1732 			*v = 0;
1733 		}
1734 	}
1735 	storage = type->t & VT_STORAGE;
1736 	type->t &= ~VT_STORAGE;
1737 	if (storage & VT_STATIC) {
1738 		int saved_nocode_wanted = nocode_wanted;
1739 		nocode_wanted = 1;
1740 // eprintf ("STATIC %s\n", get_tok_str(*v, NULL));
1741 		post_type (type, ad);
1742 		nocode_wanted = saved_nocode_wanted;
1743 	} else {
1744 		static char kind[1024];
1745 		char *name = get_tok_str (*v, NULL);
1746 		type_to_str (kind, sizeof(kind), type, NULL);
1747 		// eprintf ("---%d %s STATIC %s\n", td, kind, name);
1748 		global_symname = name;
1749 		global_type = kind;
1750 		post_type (type, ad);
1751 	}
1752 	type->t |= storage;
1753 	if (tok == TOK_ATTRIBUTE1 || tok == TOK_ATTRIBUTE2) {
1754 		parse_attribute (ad);
1755 	}
1756 
1757 	if (!type1->t) {
1758 		free (type1);
1759 		free (type2);
1760 		return;
1761 	}
1762 	/* append type at the end of type1 */
1763 	type2 = type1;
1764 	for (;;) {
1765 		s = type2->ref;
1766 		type2 = &s->type;
1767 		if (!type2->t) {
1768 			*type2 = *type;
1769 			break;
1770 		}
1771 	}
1772 	memcpy (type, type1, sizeof(*type));
1773 }
1774 
1775 /* compute the lvalue VT_LVAL_xxx needed to match type t. */
lvalue_type(int t)1776 ST_FUNC int lvalue_type(int t) {
1777 	int bt, r;
1778 	r = VT_LVAL;
1779 	bt = t & VT_BTYPE;
1780 	if (bt == VT_INT8 || bt == VT_BOOL) {
1781 		r |= VT_LVAL_BYTE;
1782 	} else if (bt == VT_INT16) {
1783 		r |= VT_LVAL_SHORT;
1784 	} else {
1785 		return r;
1786 	}
1787 	if (t & VT_UNSIGNED) {
1788 		r |= VT_LVAL_UNSIGNED;
1789 	}
1790 	return r;
1791 }
1792 
1793 /* indirection with full error checking and bound check */
indir(void)1794 ST_FUNC void indir(void) {
1795 	if ((vtop->type.t & VT_BTYPE) != VT_PTR) {
1796 		if ((vtop->type.t & VT_BTYPE) == VT_FUNC) {
1797 			return;
1798 		}
1799 		expect ("pointer");
1800 	}
1801 	vtop->type = *pointed_type (&vtop->type);
1802 	/* Arrays and functions are never lvalues */
1803 	if (!(vtop->type.t & VT_ARRAY) && !(vtop->type.t & VT_VLA)
1804 	    && (vtop->type.t & VT_BTYPE) != VT_FUNC) {
1805 		vtop->r |= lvalue_type (vtop->type.t);
1806 		/* if bound checking, the referenced pointer must be checked */
1807 #ifdef CONFIG_TCC_BCHECK
1808 		if (tcc_state->do_bounds_check) {
1809 			vtop->r |= VT_MUSTBOUND;
1810 		}
1811 #endif
1812 	}
1813 }
1814 
1815 /* parse an expression of the form '(type)' or '(expr)' and return its
1816    type */
parse_expr_type(CType * type)1817 static void parse_expr_type(CType *type) {
1818 	int n;
1819 	AttributeDef ad;
1820 
1821 	skip ('(');
1822 	if (parse_btype (type, &ad)) {
1823 		type_decl (type, &ad, &n, TYPE_ABSTRACT);
1824 	} else {
1825 		expr_type (type);
1826 	}
1827 	skip (')');
1828 }
1829 
parse_type(CType * type)1830 static void parse_type(CType *type) {
1831 	AttributeDef ad;
1832 	int n;
1833 
1834 	if (!parse_btype (type, &ad)) {
1835 		expect ("type");
1836 	}
1837 	type_decl (type, &ad, &n, TYPE_ABSTRACT);
1838 }
1839 
vpush_tokc(int t)1840 static void vpush_tokc(int t) {
1841 	CType type = { 0 };
1842 	type.t = t;
1843 	type.ref = NULL;
1844 	vsetc (&type, VT_CONST, &tokc);
1845 }
1846 
unary(void)1847 ST_FUNC void unary(void) {
1848 	int n, t, align, size, r, sizeof_caller;
1849 	CType type = { 0 };
1850 	Sym *s;
1851 	AttributeDef ad;
1852 	static int in_sizeof = 0;
1853 
1854 	sizeof_caller = in_sizeof;
1855 	in_sizeof = 0;
1856 	/* XXX: GCC 2.95.3 does not generate a table although it should be
1857 	   better here */
1858 tok_next:
1859 	switch (tok) {
1860 	case TOK_EXTENSION:
1861 		next ();
1862 		goto tok_next;
1863 	case TOK_CINT:
1864 	case TOK_CCHAR:
1865 	case TOK_LCHAR:
1866 		vpushi (tokc.i);
1867 		next ();
1868 		break;
1869 	case TOK_CUINT:
1870 		vpush_tokc (VT_INT32 | VT_UNSIGNED);
1871 		next ();
1872 		break;
1873 	case TOK_CLLONG:
1874 		vpush_tokc (VT_INT64);
1875 		next ();
1876 		break;
1877 	case TOK_CULLONG:
1878 		vpush_tokc (VT_INT64 | VT_UNSIGNED);
1879 		next ();
1880 		break;
1881 	case TOK_CFLOAT:
1882 		vpush_tokc (VT_FLOAT);
1883 		next ();
1884 		break;
1885 	case TOK_CDOUBLE:
1886 		vpush_tokc (VT_DOUBLE);
1887 		next ();
1888 		break;
1889 	case TOK_CLDOUBLE:
1890 		vpush_tokc (VT_LDOUBLE);
1891 		next ();
1892 		break;
1893 	case TOK___FUNCTION__:
1894 		if (!gnu_ext) {
1895 			goto tok_identifier;
1896 		}
1897 	/* fall thru */
1898 	case TOK___FUNC__:
1899 	{
1900 		// void *ptr = NULL;
1901 		int len;
1902 		/* special function name identifier */
1903 		len = strlen (funcname) + 1;
1904 		/* generate char[len] type */
1905 		type.t = VT_INT8;
1906 		mk_pointer (&type);
1907 		type.t |= VT_ARRAY;
1908 		if (type.ref) {
1909 			type.ref->c = len;
1910 		}
1911 		// XXX ptr is NULL HERE WTF
1912 		// memcpy(ptr, funcname, len);
1913 		next ();
1914 	}
1915 	break;
1916 	case TOK_LSTR:
1917 		if (!strncmp (tcc_state->os, "windows", 7)) {
1918 			t = VT_INT16 | VT_UNSIGNED;
1919 		} else {
1920 			t = VT_INT32;
1921 		}
1922 		goto str_init;
1923 	case TOK_STR:
1924 		/* string parsing */
1925 		t = VT_INT8;
1926 str_init:
1927 		if (tcc_state->warn_write_strings) {
1928 			t |= VT_CONSTANT;
1929 		}
1930 		type.t = t;
1931 		mk_pointer (&type);
1932 		type.t |= VT_ARRAY;
1933 		memset (&ad, 0, sizeof(AttributeDef));
1934 		decl_initializer_alloc (&type, &ad, VT_CONST, 2, 0, NULL, 0);
1935 		break;
1936 	case '(':
1937 		next ();
1938 		/* cast ? */
1939 		if (parse_btype (&type, &ad)) {
1940 			type_decl (&type, &ad, &n, TYPE_ABSTRACT);
1941 			skip (')');
1942 			/* check ISOC99 compound literal */
1943 			if (tok == '{') {
1944 				/* data is allocated locally by default */
1945 				if (global_expr) {
1946 					r = VT_CONST;
1947 				} else {
1948 					r = VT_LOCAL;
1949 				}
1950 				/* all except arrays are lvalues */
1951 				if (!(type.t & VT_ARRAY)) {
1952 					r |= lvalue_type (type.t);
1953 				}
1954 				memset (&ad, 0, sizeof(AttributeDef));
1955 				decl_initializer_alloc (&type, &ad, r, 1, 0, NULL, 0);
1956 			} else {
1957 				if (sizeof_caller) {
1958 					vpush (&type);
1959 					return;
1960 				}
1961 				unary ();
1962 			}
1963 		} else if (tok == '{') {
1964 			/* statement expression : we do not accept break/continue
1965 			   inside as GCC does */
1966 			skip (')');
1967 		} else {
1968 			gexpr ();
1969 			skip (')');
1970 		}
1971 		break;
1972 	case '*':
1973 		next ();
1974 		unary ();
1975 		indir ();
1976 		break;
1977 	case '!':
1978 		next ();
1979 		unary ();
1980 		if ((vtop->r & VT_VALMASK) == VT_CMP) {
1981 			vtop->c.i = vtop->c.i ^ 1;
1982 		}
1983 		break;
1984 	case TOK_SIZEOF:
1985 	case TOK_ALIGNOF1:
1986 	case TOK_ALIGNOF2:
1987 		t = tok;
1988 		next ();
1989 		in_sizeof++;
1990 		unary_type (&type);	// Perform a in_sizeof = 0;
1991 		size = type_size (&type, &align);
1992 		if (t == TOK_SIZEOF) {
1993 			if (!(type.t & VT_VLA)) {
1994 				if (size < 0) {
1995 					TCC_ERR ("sizeof applied to an incomplete type");
1996 				}
1997 				vpushs (size);
1998 			}
1999 		} else {
2000 			vpushs (align);
2001 		}
2002 		vtop->type.t |= VT_UNSIGNED;
2003 		break;
2004 
2005 	case TOK_builtin_types_compatible_p:
2006 	{
2007 		STACK_NEW0 (CType, type1);
2008 		STACK_NEW0 (CType, type2);
2009 		next ();
2010 		skip ('(');
2011 		parse_type (&type1);
2012 		skip (',');
2013 		parse_type (&type2);
2014 		skip (')');
2015 		type1.t &= ~(VT_CONSTANT | VT_VOLATILE);
2016 		type2.t &= ~(VT_CONSTANT | VT_VOLATILE);
2017 		vpushi (is_compatible_types (&type1, &type2));
2018 	}
2019 	break;
2020 	case TOK_builtin_constant_p:
2021 	{
2022 		int saved_nocode_wanted;
2023 		long long res;
2024 		next ();
2025 		skip ('(');
2026 		saved_nocode_wanted = nocode_wanted;
2027 		nocode_wanted = 1;
2028 		gexpr ();
2029 		res = (vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
2030 		nocode_wanted = saved_nocode_wanted;
2031 		skip (')');
2032 		vpushll (res);
2033 	}
2034 	break;
2035 	case TOK_builtin_frame_address:
2036 	{
2037 		int level;
2038 		CType type = { 0  };
2039 		next ();
2040 		skip ('(');
2041 		if (tok != TOK_CINT || tokc.i < 0) {
2042 			TCC_ERR ("__builtin_frame_address only takes positive integers");
2043 		}
2044 		level = tokc.i;
2045 		next ();
2046 		skip (')');
2047 		type.t = VT_VOID;
2048 		mk_pointer (&type);
2049 		vset (&type, VT_LOCAL, 0);	/* local frame */
2050 		while (level--) {
2051 			mk_pointer (&vtop->type);
2052 			indir ();		/* -> parent frame */
2053 		}
2054 	}
2055 	break;
2056 	case TOK_builtin_va_start:
2057 		if (!strncmp (tcc_state->arch, "x86", 3) && tcc_state->bits == 64 &&
2058 		    !strncmp (tcc_state->os, "windows", 7)) {
2059 			next ();
2060 			skip ('(');
2061 			expr_eq ();
2062 			skip (',');
2063 			expr_eq ();
2064 			skip (')');
2065 			if ((vtop->r & VT_VALMASK) != VT_LOCAL) {
2066 				TCC_ERR ("__builtin_va_start expects a local variable");
2067 			}
2068 			vtop->r &= ~(VT_LVAL | VT_REF);
2069 			vtop->type = char_pointer_type;
2070 		}
2071 		break;
2072 	case TOK_builtin_va_arg_types:
2073 		if (!(!strncmp (tcc_state->arch, "x86", 3) && tcc_state->bits == 64 &&
2074 		      !strncmp (tcc_state->os, "windows", 7))) {
2075 			CType type = { 0  };
2076 			next ();
2077 			skip ('(');
2078 			parse_type (&type);
2079 			skip (')');
2080 			// FIXME: Handle this too
2081 			// vpushll(classify_x86_64_va_arg(&type));
2082 		}
2083 		break;
2084 
2085 	// special qnan , snan and infinity values
2086 	case TOK___NAN__:
2087 		vpush64 (VT_DOUBLE, 0x7ff8000000000000ULL);
2088 		next ();
2089 		break;
2090 	case TOK___SNAN__:
2091 		vpush64 (VT_DOUBLE, 0x7ff0000000000001ULL);
2092 		next ();
2093 		break;
2094 	case TOK___INF__:
2095 		vpush64 (VT_DOUBLE, 0x7ff0000000000000ULL);
2096 		next ();
2097 		break;
2098 
2099 	default:
2100 tok_identifier:
2101 		t = tok;
2102 		next ();
2103 		if (t < TOK_UIDENT) {
2104 			expect ("identifier");
2105 		}
2106 		s = sym_find (t);
2107 		if (!s) {
2108 			if (tok != '(') {
2109 				TCC_ERR ("'%s' undeclared", get_tok_str (t, NULL));
2110 			}
2111 		}
2112 		if (!s) {
2113 			TCC_ERR ("invalid declaration '%s'", get_tok_str (t, NULL));
2114 		} else {
2115 			if ((s->type.t & (VT_STATIC | VT_INLINE | VT_BTYPE)) ==
2116 			    (VT_STATIC | VT_INLINE | VT_FUNC)) {
2117 				/* if referencing an inline function, then we generate a
2118 				   symbol to it if not already done. It will have the
2119 				   effect to generate code for it at the end of the
2120 				   compilation unit. */
2121 				r = VT_SYM | VT_CONST;
2122 			} else {
2123 				r = s->r;
2124 			}
2125 			vset (&s->type, r, s->c);
2126 			/* if forward reference, we must point to s */
2127 			if (vtop->r & VT_SYM) {
2128 				vtop->sym = s;
2129 				vtop->c.ul = 0;
2130 			}
2131 		}
2132 		break;
2133 	}
2134 
2135 	/* post operations */
2136 	while (1) {
2137 		if (tok == '.' || tok == TOK_ARROW) {
2138 			int qualifiers;
2139 			/* field */
2140 			if (tok == TOK_ARROW) {
2141 				indir ();
2142 			}
2143 			qualifiers = vtop->type.t & (VT_CONSTANT | VT_VOLATILE);
2144 			test_lvalue ();
2145 			gaddrof ();
2146 			next ();
2147 			/* expect pointer on structure */
2148 			if (not_structured(&vtop->type)) {
2149 				expect ("struct or union");
2150 			}
2151 			s = vtop->type.ref;
2152 			/* find field */
2153 			tok |= SYM_FIELD;
2154 			while ((s = s->next) != NULL) {
2155 				if (s->v == tok) {
2156 					break;
2157 				}
2158 			}
2159 			if (!s) {
2160 				TCC_ERR ("field not found: %s", get_tok_str (tok & ~SYM_FIELD, NULL));
2161 			}
2162 			/* add field offset to pointer */
2163 			vtop->type = char_pointer_type;	/* change type to 'char *' */
2164 			vpushi (s->c);
2165 			/* change type to field type, and set to lvalue */
2166 			vtop->type = s->type;
2167 			vtop->type.t |= qualifiers;
2168 			/* an array is never an lvalue */
2169 			if (!(vtop->type.t & VT_ARRAY)) {
2170 				vtop->r |= lvalue_type (vtop->type.t);
2171 #ifdef CONFIG_TCC_BCHECK
2172 				/* if bound checking, the referenced pointer must be checked */
2173 				if (tcc_state->do_bounds_check) {
2174 					vtop->r |= VT_MUSTBOUND;
2175 				}
2176 #endif
2177 			}
2178 			next ();
2179 		} else if (tok == '[') {
2180 			next ();
2181 			gexpr ();
2182 			indir ();
2183 			skip (']');
2184 			/*
2185 			} else if (tok == '(') {
2186 			SValue ret;
2187 			Sym *sa;
2188 			int nb_args, sret;
2189 			*/
2190 		} else {
2191 			break;
2192 		}
2193 	}
2194 }
2195 
expr_prod(void)2196 ST_FUNC void expr_prod(void) {
2197 	unary ();
2198 	while (tok == '*' || tok == '/' || tok == '%') {
2199 		next ();
2200 		unary ();
2201 	}
2202 }
2203 
expr_sum(void)2204 ST_FUNC void expr_sum(void) {
2205 	expr_prod ();
2206 	while (tok == '+' || tok == '-') {
2207 		next ();
2208 		expr_prod ();
2209 	}
2210 }
2211 
expr_shift(void)2212 static void expr_shift(void) {
2213 	expr_sum ();
2214 	while (tok == TOK_SHL || tok == TOK_SAR) {
2215 		next ();
2216 		expr_sum ();
2217 	}
2218 }
2219 
expr_cmp(void)2220 static void expr_cmp(void) {
2221 	expr_shift ();
2222 	while ((tok >= TOK_ULE && tok <= TOK_GT) ||
2223 	       tok == TOK_ULT || tok == TOK_UGE) {
2224 		next ();
2225 		expr_shift ();
2226 	}
2227 }
2228 
expr_cmpeq(void)2229 static void expr_cmpeq(void) {
2230 	expr_cmp ();
2231 	while (tok == TOK_EQ || tok == TOK_NE) {
2232 		next ();
2233 		expr_cmp ();
2234 	}
2235 }
2236 
expr_and(void)2237 static void expr_and(void) {
2238 	expr_cmpeq ();
2239 	while (tok == '&') {
2240 		next ();
2241 		expr_cmpeq ();
2242 	}
2243 }
2244 
expr_xor(void)2245 static void expr_xor(void) {
2246 	expr_and ();
2247 	while (tok == '^') {
2248 		next ();
2249 		expr_and ();
2250 	}
2251 }
2252 
expr_or(void)2253 static void expr_or(void) {
2254 	expr_xor ();
2255 	while (tok == '|') {
2256 		next ();
2257 		expr_xor ();
2258 	}
2259 }
2260 
2261 /* XXX: fix this mess */
expr_land_const(void)2262 static void expr_land_const(void) {
2263 	expr_or ();
2264 	while (tok == TOK_LAND) {
2265 		next ();
2266 		expr_or ();
2267 	}
2268 }
2269 
2270 /* XXX: fix this mess */
expr_lor_const(void)2271 static void expr_lor_const(void) {
2272 	expr_land_const ();
2273 	while (tok == TOK_LOR) {
2274 		next ();
2275 		expr_land_const ();
2276 	}
2277 }
2278 
2279 /* only used if non constant */
expr_land(void)2280 static void expr_land(void) {
2281 	expr_or ();
2282 	if (tok == TOK_LAND) {
2283 		while (tcc_nerr () == 0) {
2284 			if (tok != TOK_LAND) {
2285 				break;
2286 			}
2287 			next ();
2288 			expr_or ();
2289 		}
2290 	}
2291 }
2292 
expr_lor(void)2293 static void expr_lor(void) {
2294 	expr_land ();
2295 	if (tok == TOK_LOR) {
2296 		while (tcc_nerr () == 0) {
2297 			if (tok != TOK_LOR) {
2298 				break;
2299 			}
2300 			next ();
2301 			expr_land ();
2302 		}
2303 	}
2304 }
2305 
2306 /* XXX: better constant handling */
expr_cond(void)2307 static void expr_cond(void) {
2308 	if (const_wanted) {
2309 		expr_lor_const ();
2310 		if (tok == '?') {
2311 			vdup ();
2312 			next ();
2313 			if (tok != ':' || !gnu_ext) {
2314 				gexpr ();
2315 			}
2316 			skip (':');
2317 			expr_cond ();
2318 		}
2319 	} else {
2320 		expr_lor ();
2321 	}
2322 }
2323 
expr_eq(void)2324 static void expr_eq(void) {
2325 	int t;
2326 
2327 	expr_cond ();
2328 	if (tok == '=' ||
2329 	    (tok >= TOK_A_MOD && tok <= TOK_A_DIV) ||
2330 	    tok == TOK_A_XOR || tok == TOK_A_OR ||
2331 	    tok == TOK_A_SHL || tok == TOK_A_SAR) {
2332 		test_lvalue ();
2333 		t = tok;
2334 		next ();
2335 		if (t == '=') {
2336 			expr_eq ();
2337 		} else {
2338 			vdup ();
2339 			expr_eq ();
2340 		}
2341 	}
2342 }
2343 
gexpr(void)2344 ST_FUNC void gexpr(void) {
2345 	while (tcc_nerr () == 0) {
2346 		expr_eq ();
2347 		if (tok != ',') {
2348 			break;
2349 		}
2350 		next ();
2351 	}
2352 }
2353 
2354 /* parse an expression and return its type without any side effect. */
expr_type(CType * type)2355 static void expr_type(CType *type) {
2356 	int saved_nocode_wanted;
2357 
2358 	saved_nocode_wanted = nocode_wanted;
2359 	nocode_wanted = 1;
2360 	gexpr ();
2361 	*type = vtop->type;
2362 	nocode_wanted = saved_nocode_wanted;
2363 }
2364 
2365 /* parse a unary expression and return its type without any side
2366    effect. */
unary_type(CType * type)2367 static void unary_type(CType *type) {
2368 	int a = nocode_wanted;
2369 	nocode_wanted = 1;
2370 	unary ();
2371 	*type = vtop->type;
2372 	nocode_wanted = a;
2373 }
2374 
2375 /* parse a constant expression and return value in vtop.  */
expr_const1(void)2376 static void expr_const1(void) {
2377 	int a;
2378 	a = const_wanted;
2379 	const_wanted = 1;
2380 	expr_cond ();
2381 	const_wanted = a;
2382 }
2383 
2384 /* parse an integer constant and return its value. */
expr_const(void)2385 ST_FUNC long long expr_const(void) {
2386 	long long c = 0LL;
2387 	expr_const1 ();
2388 	if ((vtop->r & (VT_VALMASK | VT_LVAL | VT_SYM)) != VT_CONST) {
2389 		expect ("constant expression");
2390 	}
2391 	c = vtop->c.ll;
2392 	return c;
2393 }
2394 
2395 /* return the label token if current token is a label, otherwise
2396    return zero */
is_label(void)2397 static int is_label(void) {
2398 	int last_tok;
2399 
2400 	/* fast test first */
2401 	if (tok < TOK_UIDENT) {
2402 		return 0;
2403 	}
2404 	/* no need to save tokc because tok is an identifier */
2405 	last_tok = tok;
2406 	next ();
2407 	if (tok == ':') {
2408 		next ();
2409 		return last_tok;
2410 	} else {
2411 		unget_tok (last_tok);
2412 		return 0;
2413 	}
2414 }
2415 
2416 /* t is the array or struct type. c is the array or struct
2417    address. cur_index/cur_field is the pointer to the current
2418    value. 'size_only' is true if only size info is needed (only used
2419    in arrays) */
decl_designator(CType * type,unsigned long c,long long * cur_index,Sym ** cur_field,int size_only)2420 static void decl_designator(CType *type, unsigned long c,
2421 			    long long *cur_index, Sym **cur_field,
2422 			    int size_only)
2423 {
2424 	Sym *s, *f = NULL;
2425 	long long index, index_last;
2426 	int notfirst, align, l, nb_elems, elem_size;
2427 	STACK_NEW0 (CType, type1);
2428 
2429 	notfirst = 0;
2430 	if (gnu_ext && (l = is_label ()) != 0) {
2431 		goto struct_field;
2432 	}
2433 	while (tok == '[' || tok == '.') {
2434 		if (tok == '[') {
2435 			if (!(type->t & VT_ARRAY)) {
2436 				expect ("array type");
2437 			}
2438 			s = type->ref;
2439 			next ();
2440 			index = expr_const ();
2441 			if (index < 0 || (s->c >= 0 && index >= s->c)) {
2442 				expect ("invalid index");
2443 			}
2444 			if (tok == TOK_DOTS && gnu_ext) {
2445 				next ();
2446 				index_last = expr_const ();
2447 				if (index_last < 0 ||
2448 				    (s->c >= 0 && index_last >= s->c) ||
2449 				    index_last < index) {
2450 					expect ("invalid index");
2451 				}
2452 			} else {
2453 				index_last = index;
2454 			}
2455 			skip (']');
2456 			if (!notfirst && cur_index) {
2457 				*cur_index = index_last;
2458 			}
2459 			type = pointed_type (type);
2460 			elem_size = type_size (type, &align);
2461 			c += index * elem_size;
2462 			/* NOTE: we only support ranges for last designator */
2463 			nb_elems = index_last - index + 1;
2464 			if (nb_elems != 1) {
2465 				notfirst = 1;
2466 				break;
2467 			}
2468 		} else {
2469 			next ();
2470 			l = tok;
2471 			next ();
2472 struct_field:
2473 			if (not_structured(type)) {
2474 				expect ("struct/union type");
2475 			}
2476 			s = type->ref;
2477 			l |= SYM_FIELD;
2478 			f = s->next;
2479 			while (f) {
2480 				if (f->v == l) {
2481 					break;
2482 				}
2483 				f = f->next;
2484 			}
2485 			if (!f) {
2486 				expect ("field");
2487 			}
2488 			if (!notfirst && cur_field) {
2489 				*cur_field = f;
2490 			}
2491 			/* XXX: fix this mess by using explicit storage field */
2492 			if (f) {
2493 				type1 = f->type;
2494 				type1.t |= (type->t & ~VT_TYPE);
2495 				type = &type1;
2496 				c += f->c;
2497 			}
2498 		}
2499 		notfirst = 1;
2500 	}
2501 	if (notfirst) {
2502 		if (tok == '=') {
2503 			next ();
2504 		} else {
2505 			if (!gnu_ext) {
2506 				expect ("=");
2507 			}
2508 		}
2509 	} else {
2510 		if (type->t & VT_ARRAY) {
2511 			index = cur_index ? *cur_index : 0;
2512 			type = pointed_type (type);
2513 			c += index * type_size (type, &align);
2514 		} else {
2515 			f = cur_field ? *cur_field : NULL;
2516 			if (!f) {
2517 				TCC_ERR ("too many field init");
2518 			}
2519 			/* XXX: fix this mess by using explicit storage field */
2520 			if (f) {
2521 				type1 = f->type;
2522 				type1.t |= (type->t & ~VT_TYPE);
2523 				type = &type1;
2524 				c += f->c;
2525 			}
2526 		}
2527 	}
2528 	decl_initializer (type, c, 0, size_only);
2529 }
2530 
2531 #define EXPR_VAL   0
2532 #define EXPR_CONST 1
2533 #define EXPR_ANY   2
2534 
2535 /* store a value or an expression directly in global data or in local array */
init_putv(CType * type,unsigned long c,long long v,int expr_type)2536 static void init_putv(CType *type, unsigned long c, long long v, int expr_type) {
2537 	int saved_global_expr;
2538 	CType dtype;
2539 
2540 	switch (expr_type) {
2541 	case EXPR_VAL:
2542 		vpushll (v);
2543 		break;
2544 	case EXPR_CONST:
2545 		/* compound literals must be allocated globally in this case */
2546 		saved_global_expr = global_expr;
2547 		global_expr = 1;
2548 		expr_const1 ();
2549 		global_expr = saved_global_expr;
2550 		/* NOTE: symbols are accepted */
2551 		if ((vtop->r & (VT_VALMASK | VT_LVAL)) != VT_CONST) {
2552 			TCC_ERR ("initializer element is not constant");
2553 		}
2554 		break;
2555 	case EXPR_ANY:
2556 		expr_eq ();
2557 		break;
2558 	}
2559 
2560 	dtype = *type;
2561 	dtype.t &= ~VT_CONSTANT;/* need to do that to avoid false warning */
2562 
2563 	vset (&dtype, VT_LOCAL | VT_LVAL, c);
2564 	vswap ();
2565 }
2566 
2567 /* put zeros for variable based init */
init_putz(CType * t,unsigned long c,int size)2568 static void init_putz(CType *t, unsigned long c, int size) {
2569 	vseti (VT_LOCAL, c);
2570 	vpushi (0);
2571 	vpushs (size);
2572 }
2573 
2574 /* 't' contains the type and storage info. 'c' is the offset of the
2575    object in section 'sec'. If 'sec' is NULL, it means stack based
2576    allocation. 'first' is true if array '{' must be read (multi
2577    dimension implicit array init handling). 'size_only' is true if
2578    size only evaluation is wanted (only for arrays). */
decl_initializer(CType * type,unsigned long c,int first,int size_only)2579 static void decl_initializer(CType *type, unsigned long c, int first, int size_only) {
2580 	long long index;
2581 	int array_length, n, no_oblock, nb, parlevel, parlevel1, i;
2582 	int size1, align1, expr_type;
2583 	Sym *s, *f;
2584 	CType *t1;
2585 
2586 	if (type->t & VT_ARRAY) {
2587 		s = type->ref;
2588 		n = s->c;
2589 		array_length = 0;
2590 		t1 = pointed_type (type);
2591 		size1 = type_size (t1, &align1);
2592 
2593 		no_oblock = 1;
2594 		if ((first && tok != TOK_LSTR && tok != TOK_STR) ||
2595 		    tok == '{') {
2596 			if (tok != '{') {
2597 				TCC_ERR ("character array initializer must be a literal,"
2598 					" optionally enclosed in braces");
2599 			}
2600 			skip ('{');
2601 			no_oblock = 0;
2602 		}
2603 
2604 		/* only parse strings here if correct type (otherwise: handle
2605 		   them as ((w)char *) expressions */
2606 		if ((tok == TOK_LSTR &&
2607 /* FIXME: Handle platform here ! */
2608 #ifdef TCC_TARGET_PE
2609 		     (t1->t & VT_BTYPE) == VT_INT16 && (t1->t & VT_UNSIGNED)
2610 #else
2611 		     (t1->t & VT_BTYPE) == VT_INT32
2612 #endif
2613 		    ) || (tok == TOK_STR && (t1->t & VT_BTYPE) == VT_INT8)) {
2614 			while (tcc_nerr() == 0 && (tok == TOK_STR || tok == TOK_LSTR)) {
2615 				int cstr_len, ch;
2616 				CString *cstr;
2617 
2618 				cstr = tokc.cstr;
2619 				/* compute maximum number of chars wanted */
2620 				if (tok == TOK_STR) {
2621 					cstr_len = cstr->size;
2622 				} else {
2623 					cstr_len = cstr->size / sizeof(nwchar_t);
2624 				}
2625 				cstr_len--;
2626 				nb = cstr_len;
2627 				if (n >= 0 && nb > (n - array_length)) {
2628 					nb = n - array_length;
2629 				}
2630 				if (!size_only) {
2631 					if (cstr_len > nb) {
2632 						tcc_warning ("initializer-string for array is too long");
2633 					}
2634 					/* in order to go faster for common case (char
2635 					   string in global variable, we handle it
2636 					   specifically */
2637 					for (i = 0; i < nb; i++) {
2638 						if (tok == TOK_STR) {
2639 							ch = ((unsigned char *) cstr->data)[i];
2640 						} else {
2641 							ch = ((nwchar_t *) cstr->data)[i];
2642 						}
2643 						init_putv (t1, c + (array_length + i) * size1,
2644 							ch, EXPR_VAL);
2645 					}
2646 				}
2647 				array_length += nb;
2648 				next ();
2649 			}
2650 			/* only add trailing zero if enough storage (no
2651 			   warning in this case since it is standard) */
2652 			if (n < 0 || array_length < n) {
2653 				if (!size_only) {
2654 					init_putv (t1, c + (array_length * size1), 0, EXPR_VAL);
2655 				}
2656 				array_length++;
2657 			}
2658 		} else {
2659 			index = 0;
2660 			while (tok != '}') {
2661 				decl_designator (type, c, &index, NULL, size_only);
2662 				if (n >= 0 && index >= n) {
2663 					TCC_ERR ("index too large");
2664 				}
2665 				/* must put zero in holes (note that doing it that way
2666 				   ensures that it even works with designators) */
2667 				if (!size_only && array_length < index) {
2668 					init_putz (t1, c + array_length * size1,
2669 						(index - array_length) * size1);
2670 				}
2671 				index++;
2672 				if (index > array_length) {
2673 					array_length = index;
2674 				}
2675 				/* special test for multi dimensional arrays (may not
2676 				   be strictly correct if designators are used at the
2677 				   same time) */
2678 				if (index >= n && no_oblock) {
2679 					break;
2680 				}
2681 				if (tok == '}') {
2682 					break;
2683 				}
2684 				skip (',');
2685 			}
2686 		}
2687 		if (!no_oblock) {
2688 			skip ('}');
2689 		}
2690 		/* put zeros at the end */
2691 		if (!size_only && n >= 0 && array_length < n) {
2692 			init_putz (t1, c + array_length * size1,
2693 				(n - array_length) * size1);
2694 		}
2695 		/* patch type size if needed */
2696 		if (n < 0) {
2697 			s->c = array_length;
2698 		}
2699 	} else if (is_structured(type) && (!first || tok == '{')) {
2700 		int par_count;
2701 
2702 		/* NOTE: the previous test is a specific case for automatic
2703 		   struct/union init */
2704 		/* XXX: union needs only one init */
2705 
2706 		/* XXX: this test is incorrect for local initializers
2707 		   beginning with ( without {. It would be much more difficult
2708 		   to do it correctly (ideally, the expression parser should
2709 		   be used in all cases) */
2710 		par_count = 0;
2711 		if (tok == '(') {
2712 			AttributeDef ad1;
2713 			STACK_NEW0 (CType, type1);
2714 			next ();
2715 			while (tok == '(') {
2716 				par_count++;
2717 				next ();
2718 			}
2719 			if (!parse_btype (&type1, &ad1)) {
2720 				expect ("cast");
2721 			}
2722 			type_decl (&type1, &ad1, &n, TYPE_ABSTRACT);
2723 #if 0
2724 			if (!is_assignable_types (type, &type1)) {
2725 				tcc_error ("invalid type for cast");
2726 			}
2727 #endif
2728 			skip (')');
2729 		}
2730 		no_oblock = 1;
2731 		if (first || tok == '{') {
2732 			skip ('{');
2733 			no_oblock = 0;
2734 		}
2735 		s = type->ref;
2736 		f = s->next;
2737 		array_length = 0;
2738 		index = 0;
2739 		n = s->c;
2740 		while (tok != '}') {
2741 			decl_designator (type, c, NULL, &f, size_only);
2742 			index = f->c;
2743 			if (!size_only && array_length < index) {
2744 				init_putz (type, c + array_length,
2745 					index - array_length);
2746 			}
2747 			index = index + type_size (&f->type, &align1);
2748 			if (index > array_length) {
2749 				array_length = index;
2750 			}
2751 
2752 			/* gr: skip fields from same union - ugly. */
2753 			while (f->next) {
2754 				///printf("index: %2d %08x -- %2d %08x\n", f->c, f->type.t, f->next->c, f->next->type.t);
2755 				/* test for same offset */
2756 				if (f->next->c != f->c) {
2757 					break;
2758 				}
2759 				/* if yes, test for bitfield shift */
2760 				if ((f->type.t & VT_BITFIELD) && (f->next->type.t & VT_BITFIELD)) {
2761 					int bit_pos_1 = (f->type.t >> VT_STRUCT_SHIFT) & 0x3f;
2762 					int bit_pos_2 = (f->next->type.t >> VT_STRUCT_SHIFT) & 0x3f;
2763 					// printf("bitfield %d %d\n", bit_pos_1, bit_pos_2);
2764 					if (bit_pos_1 != bit_pos_2) {
2765 						break;
2766 					}
2767 				}
2768 				f = f->next;
2769 			}
2770 
2771 			f = f->next;
2772 			if (no_oblock && f == NULL) {
2773 				break;
2774 			}
2775 			if (tok == '}') {
2776 				break;
2777 			}
2778 			skip (',');
2779 		}
2780 		/* put zeros at the end */
2781 		if (!size_only && array_length < n) {
2782 			init_putz (type, c + array_length,
2783 				n - array_length);
2784 		}
2785 		if (!no_oblock) {
2786 			skip ('}');
2787 		}
2788 		while (par_count) {
2789 			skip (')');
2790 			par_count--;
2791 		}
2792 	} else if (tok == '{') {
2793 		next ();
2794 		decl_initializer (type, c, first, size_only);
2795 		skip ('}');
2796 	} else if (size_only) {
2797 		/* just skip expression */
2798 		parlevel = parlevel1 = 0;
2799 		while ((parlevel > 0 || parlevel1 > 0 ||
2800 			(tok != '}' && tok != ',')) && tok != -1) {
2801 			if (tok == '(') {
2802 				parlevel++;
2803 			} else if (tok == ')') {
2804 				parlevel--;
2805 			} else if (tok == '{') {
2806 				parlevel1++;
2807 			} else if (tok == '}') {
2808 				parlevel1--;
2809 			}
2810 			next ();
2811 		}
2812 	} else {
2813 		/* currently, we always use constant expression for globals
2814 		   (may change for scripting case) */
2815 		expr_type = EXPR_CONST;
2816 		init_putv (type, c, 0, expr_type);
2817 	}
2818 }
2819 
2820 /* parse an initializer for type 't' if 'has_init' is non zero, and
2821    allocate space in local or global data space ('r' is either
2822    VT_LOCAL or VT_CONST). If 'v' is non zero, then an associated
2823    variable 'v' with an associated name represented by 'asm_label' of
2824    scope 'scope' is declared before initializers are parsed. If 'v' is
2825    zero, then a reference to the new object is put in the value stack.
2826    If 'has_init' is 2, a special parsing is done to handle string
2827    constants. */
decl_initializer_alloc(CType * type,AttributeDef * ad,int r,int has_init,int v,char * asm_label,int scope)2828 static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r, int has_init, int v, char *asm_label, int scope) {
2829 	int size, align, addr;
2830 	int level;
2831 	ParseState saved_parse_state = {
2832 		0
2833 	};
2834 	TokenString init_str;
2835 	Sym *flexible_array;
2836 
2837 	flexible_array = NULL;
2838 	if (is_struct(type)) {
2839 		Sym *field;
2840 		field = type->ref;
2841 		while (field && field->next)
2842 			field = field->next;
2843 		if (field && (field->type.t & VT_ARRAY) && (field->type.ref->c < 0)) {
2844 			flexible_array = field;
2845 		}
2846 	}
2847 
2848 	size = type_size (type, &align);
2849 	/* If unknown size, we must evaluate it before
2850 	   evaluating initializers because
2851 	   initializers can generate global data too
2852 	   (e.g. string pointers or ISOC99 compound
2853 	   literals). It also simplifies local
2854 	   initializers handling */
2855 	tok_str_new (&init_str);
2856 	if (size < 0 || (flexible_array && has_init)) {
2857 		if (!has_init) {
2858 			TCC_ERR ("unknown type size");
2859 		}
2860 		/* get all init string */
2861 		if (has_init == 2) {
2862 			/* only get strings */
2863 			while (tok == TOK_STR || tok == TOK_LSTR) {
2864 				tok_str_add_tok (&init_str);
2865 				next ();
2866 			}
2867 		} else {
2868 			level = 0;
2869 			while (tcc_nerr() == 0 && (level > 0 || (tok != ',' && tok != ';'))) {
2870 				if (tok < 0) {
2871 					TCC_ERR ("unexpected end of file in initializer");
2872 				}
2873 				tok_str_add_tok (&init_str);
2874 				if (tok == '{') {
2875 					level++;
2876 				} else if (tok == '}') {
2877 					level--;
2878 					if (level <= 0) {
2879 						next ();
2880 						break;
2881 					}
2882 				}
2883 				next ();
2884 			}
2885 		}
2886 		tok_str_add (&init_str, -1);
2887 		tok_str_add (&init_str, 0);
2888 
2889 		/* compute size */
2890 		save_parse_state (&saved_parse_state);
2891 
2892 		macro_ptr = init_str.str;
2893 		next ();
2894 		decl_initializer (type, 0, 1, 1);
2895 		/* prepare second initializer parsing */
2896 		macro_ptr = init_str.str;
2897 		next ();
2898 
2899 		/* if still unknown size, error */
2900 		size = type_size (type, &align);
2901 		if (size < 0) {
2902 			TCC_ERR ("unknown type size");
2903 		}
2904 	}
2905 	if (flexible_array) {
2906 		size += flexible_array->type.ref->c * pointed_size (&flexible_array->type);
2907 	}
2908 	/* take into account specified alignment if bigger */
2909 	if (ad->aligned) {
2910 		if (ad->aligned > align) {
2911 			align = ad->aligned;
2912 		}
2913 	} else if (ad->packed) {
2914 		align = 1;
2915 	}
2916 	if ((r & VT_VALMASK) == VT_LOCAL) {
2917 		loc = (loc - size) & - align;
2918 		addr = loc;
2919 		if (v) {
2920 			/* local variable */
2921 			sym_push (v, type, r, addr);
2922 		} else {
2923 			/* push local reference */
2924 			vset (type, r, addr);
2925 		}
2926 	} else {
2927 		Sym *sym;
2928 
2929 		sym = NULL;
2930 		if (v && scope == VT_CONST) {
2931 			/* see if the symbol was already defined */
2932 			sym = sym_find (v);
2933 			if (sym) {
2934 				if (!is_compatible_types (&sym->type, type)) {
2935 					TCC_ERR ("incompatible types for redefinition of '%s'",
2936 						get_tok_str (v, NULL));
2937 				}
2938 				if (sym->type.t & VT_EXTERN) {
2939 					/* if the variable is extern, it was not allocated */
2940 					sym->type.t &= ~VT_EXTERN;
2941 					/* set array size if it was ommited in extern
2942 					   declaration */
2943 					if ((sym->type.t & VT_ARRAY) &&
2944 					    sym->type.ref->c < 0 &&
2945 					    type->ref->c >= 0) {
2946 						sym->type.ref->c = type->ref->c;
2947 					}
2948 				} else {
2949 					/* we accept several definitions of the same
2950 					   global variable. this is tricky, because we
2951 					   must play with the SHN_COMMON type of the symbol */
2952 					/* XXX: should check if the variable was already
2953 					   initialized. It is incorrect to initialized it
2954 					   twice */
2955 					/* no init data, we won't add more to the symbol */
2956 					if (!has_init) {
2957 						goto no_alloc;
2958 					}
2959 				}
2960 			}
2961 		}
2962 
2963 		if (v) {
2964 			if (scope != VT_CONST || !sym) {
2965 				sym = sym_push (v, type, r | VT_SYM, 0);
2966 				sym->asm_label = asm_label;
2967 			}
2968 		} else {
2969 			CValue cval = { 0 };
2970 			vsetc (type, VT_CONST | VT_SYM, &cval);
2971 			vtop->sym = sym;
2972 		}
2973 		/* patch symbol weakness */
2974 		if ((type->t & VT_WEAK) && sym) {
2975 			weaken_symbol (sym);
2976 		}
2977 	}
2978 no_alloc:
2979 	;
2980 }
2981 
2982 /* parse an old style function declaration list */
2983 /* XXX: check multiple parameter */
func_decl_list(Sym * func_sym)2984 static void func_decl_list(Sym *func_sym) {
2985 	AttributeDef ad;
2986 	int v;
2987 	Sym *s = NULL;
2988 	CType btype, type;
2989 
2990 	/* parse each declaration */
2991 	while (tcc_nerr () == 0 && tok != '{' && tok != ';' && tok != ',' && tok != TOK_EOF &&
2992 	       tok != TOK_ASM1 && tok != TOK_ASM2 && tok != TOK_ASM3) {
2993 		if (!parse_btype (&btype, &ad)) {
2994 			expect ("declaration list");
2995 		}
2996 		if ((is_enum(&btype) || is_structured(&btype)) && tok == ';') {
2997 			/* we accept no variable after */
2998 		} else {
2999 			while (tcc_nerr () == 0) {
3000 				int found;
3001 				type = btype;
3002 				type_decl (&type, &ad, &v, TYPE_DIRECT);
3003 				/* find parameter in function parameter list */
3004 				s = func_sym;
3005 				found = 0;
3006 				while ((s = s->next) != NULL) {
3007 					if ((s->v & ~SYM_FIELD) == v) {
3008 						found = 1;
3009 						break;
3010 					}
3011 				}
3012 				if (found == 0) {
3013 					TCC_ERR ("declaration for parameter '%s' but no such parameter",
3014 						get_tok_str (v, NULL));
3015 				}
3016 				/* check that no storage specifier except 'register' was given */
3017 				if (type.t & VT_STORAGE) {
3018 					TCC_ERR ("storage class specified for '%s'", get_tok_str (v, NULL));
3019 				}
3020 				convert_parameter_type (&type);
3021 				/* we can add the type (NOTE: it could be local to the function) */
3022 				if (s) {
3023 					s->type = type;
3024 				}
3025 				/* accept other parameters */
3026 				if (tok == ',') {
3027 					next ();
3028 				} else {
3029 					break;
3030 				}
3031 			}
3032 		}
3033 		skip (';');
3034 	}
3035 }
3036 
3037 /* 'l' is VT_LOCAL or VT_CONST to define default storage type */
decl0(int l,int is_for_loop_init)3038 static int decl0(int l, int is_for_loop_init) {
3039 	int v, has_init, r;
3040 	CType type = {.t = 0, .ref = NULL}, btype = {.t = 0, .ref = NULL};
3041 	Sym *sym = NULL;
3042 	AttributeDef ad;
3043 
3044 	while (tcc_nerr () == 0) {
3045 		if (!parse_btype (&btype, &ad)) {
3046 			if (is_for_loop_init) {
3047 				return 0;
3048 			}
3049 			/* skip redundant ';' */
3050 			/* XXX: find more elegant solution */
3051 			if (tok == ';') {
3052 				next ();
3053 				continue;
3054 			}
3055 			if (l == VT_CONST &&
3056 			    (tok == TOK_ASM1 || tok == TOK_ASM2 || tok == TOK_ASM3)) {
3057 				/* global asm block */
3058 #if 1
3059 				eprintf ("global asm not supported\n");
3060 				return 1;
3061 #endif
3062 				// asm_global_instr();
3063 				continue;
3064 			}
3065 			/* special test for old K&R protos without explicit int
3066 			   type. Only accepted when defining global data */
3067 			if (l == VT_LOCAL || tok < TOK_DEFINE) {
3068 				break;
3069 			}
3070 			btype.t = VT_INT32;
3071 		}
3072 		if ((is_enum(&btype) || is_structured(&btype)) && tok == ';') {
3073 			/* we accept no variable after */
3074 			next ();
3075 			continue;
3076 		}
3077 		/* iterate thru each declaration */
3078 		while (tcc_nerr () == 0) {
3079 			type = btype;
3080 			type_decl (&type, &ad, &v, TYPE_DIRECT);
3081 #if 0
3082 			{
3083 				char buf[500];
3084 				type_to_str (buf, sizeof(buf), t, get_tok_str (v, NULL));
3085 				printf ("type = '%s'\n", buf);
3086 			}
3087 #endif
3088 			if ((type.t & VT_BTYPE) == VT_FUNC) {
3089 				if ((type.t & VT_STATIC) && (l == VT_LOCAL)) {
3090 					tcc_error ("function without file scope cannot be static");
3091 					return 1;
3092 				}
3093 				/* if old style function prototype, we accept a
3094 				   declaration list */
3095 				sym = type.ref;
3096 				if (sym->c == FUNC_OLD) {
3097 					func_decl_list (sym);
3098 				}
3099 			}
3100 
3101 			if (ad.weak) {
3102 				type.t |= VT_WEAK;
3103 			}
3104 #ifdef TCC_TARGET_PE
3105 			if (ad.func_import) {
3106 				type.t |= VT_IMPORT;
3107 			}
3108 			if (ad.func_export) {
3109 				type.t |= VT_EXPORT;
3110 			}
3111 #endif
3112 			if (tok == '{') {
3113 				if (l == VT_LOCAL) {
3114 					tcc_error ("cannot use local functions");
3115 					return 1;
3116 				}
3117 				if ((type.t & VT_BTYPE) != VT_FUNC) {
3118 					expect ("function definition");
3119 				}
3120 
3121 				/* reject abstract declarators in function definition */
3122 				sym = type.ref;
3123 				if (sym) {
3124 					while ((sym = sym->next) != NULL)
3125 						if (!(sym->v & ~SYM_FIELD)) {
3126 							expect ("identifier");
3127 						}
3128 				} else {
3129 					return 0; // XXX unmatching braces in typedef?
3130 				}
3131 
3132 				/* XXX: cannot do better now: convert extern line to static inline */
3133 				if ((type.t & (VT_EXTERN | VT_INLINE)) == (VT_EXTERN | VT_INLINE)) {
3134 					type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
3135 				}
3136 
3137 				sym = sym_find (v);
3138 				if (sym) {
3139 					if ((sym->type.t & VT_BTYPE) != VT_FUNC) {
3140 						goto func_error1;
3141 					}
3142 
3143 					r = sym->type.ref->r;
3144 					/* use func_call from prototype if not defined */
3145 					if (FUNC_CALL (r) != FUNC_CDECL
3146 					    && FUNC_CALL (type.ref->r) == FUNC_CDECL) {
3147 						FUNC_CALL (type.ref->r) = FUNC_CALL (r);
3148 					}
3149 
3150 					/* use export from prototype */
3151 					if (FUNC_EXPORT (r)) {
3152 						FUNC_EXPORT (type.ref->r) = 1;
3153 					}
3154 
3155 					/* use static from prototype */
3156 					if (sym->type.t & VT_STATIC) {
3157 						type.t = (type.t & ~VT_EXTERN) | VT_STATIC;
3158 					}
3159 
3160 					if (!is_compatible_types (&sym->type, &type)) {
3161 func_error1:
3162 						tcc_error ("incompatible types for redefinition of '%s'",
3163 							get_tok_str (v, NULL));
3164 						return 1;
3165 					}
3166 					/* if symbol is already defined, then put complete type */
3167 					sym->type = type;
3168 				} else {
3169 					/* put function symbol */
3170 					sym = global_identifier_push (v, type.t, 0);
3171 					if (!sym) {
3172 						return 1;
3173 					}
3174 					sym->type.ref = type.ref;
3175 				}
3176 				break;
3177 			} else {
3178 				if (btype.t & VT_TYPEDEF) {
3179 					/* save typedefed type  */
3180 					/* XXX: test storage specifiers ? */
3181 					if (tok != ';') {
3182 						v = tok;
3183 						next();
3184 					}
3185 					sym = sym_push (v, &type, INT_ATTR (&ad), 0);
3186 					if (!sym) {
3187 						return 1;
3188 					}
3189 					sym->type.t |= VT_TYPEDEF;
3190 					/* Provide SDB with typedefs' info */
3191 					const char *alias = NULL;
3192 					char buf[500];
3193 					alias = get_tok_str(v, NULL);
3194 					type_to_str(buf, sizeof(buf), &sym->type, NULL);
3195 					tcc_appendf ("%s=typedef\n", alias);
3196 					tcc_appendf ("typedef.%s=%s\n", alias, buf);
3197 					tcc_typedef_alias_fields (alias);
3198 				} else {
3199 					r = 0;
3200 					if ((type.t & VT_BTYPE) == VT_FUNC) {
3201 						/* external function definition */
3202 						/* specific case for func_call attribute */
3203 						type.ref->r = INT_ATTR (&ad);
3204 					} else if (!(type.t & VT_ARRAY)) {
3205 						/* not lvalue if array */
3206 						r |= lvalue_type (type.t);
3207 					}
3208 					has_init = (tok == '=');
3209 					if (has_init && (type.t & VT_VLA)) {
3210 						tcc_error ("Variable length array cannot be initialized");
3211 						return 1;
3212 					}
3213 				}
3214 				if (tok != ',') {
3215 					if (is_for_loop_init) {
3216 						return 1;
3217 					}
3218 					skip (';');
3219 					break;
3220 				}
3221 				next ();
3222 			}
3223 			ad.aligned = 0;
3224 		}
3225 	}
3226 	return 0;
3227 }
3228 
decl(int l)3229 ST_FUNC void decl(int l) {
3230 	decl0 (l, 0);
3231 }
3232