.c -> .cpp
[xonotic/gmqcc.git] / ast.cpp
1 #include <stdlib.h>
2 #include <string.h>
3
4 #include "gmqcc.h"
5 #include "ast.h"
6 #include "parser.h"
7
8 #define ast_instantiate(T, ctx, destroyfn)                          \
9     T* self = (T*)mem_a(sizeof(T));                                 \
10     if (!self) {                                                    \
11         return NULL;                                                \
12     }                                                               \
13     ast_node_init((ast_node*)self, ctx, TYPE_##T);                  \
14     ( (ast_node*)self )->destroy = (ast_node_delete*)destroyfn
15
16 /*
17  * forward declarations, these need not be in ast.h for obvious
18  * static reasons.
19  */
20 static bool ast_member_codegen(ast_member*, ast_function*, bool lvalue, ir_value**);
21 static void ast_array_index_delete(ast_array_index*);
22 static bool ast_array_index_codegen(ast_array_index*, ast_function*, bool lvalue, ir_value**);
23 static void ast_argpipe_delete(ast_argpipe*);
24 static bool ast_argpipe_codegen(ast_argpipe*, ast_function*, bool lvalue, ir_value**);
25 static void ast_store_delete(ast_store*);
26 static bool ast_store_codegen(ast_store*, ast_function*, bool lvalue, ir_value**);
27 static void ast_ifthen_delete(ast_ifthen*);
28 static bool ast_ifthen_codegen(ast_ifthen*, ast_function*, bool lvalue, ir_value**);
29 static void ast_ternary_delete(ast_ternary*);
30 static bool ast_ternary_codegen(ast_ternary*, ast_function*, bool lvalue, ir_value**);
31 static void ast_loop_delete(ast_loop*);
32 static bool ast_loop_codegen(ast_loop*, ast_function*, bool lvalue, ir_value**);
33 static void ast_breakcont_delete(ast_breakcont*);
34 static bool ast_breakcont_codegen(ast_breakcont*, ast_function*, bool lvalue, ir_value**);
35 static void ast_switch_delete(ast_switch*);
36 static bool ast_switch_codegen(ast_switch*, ast_function*, bool lvalue, ir_value**);
37 static void ast_label_delete(ast_label*);
38 static void ast_label_register_goto(ast_label*, ast_goto*);
39 static bool ast_label_codegen(ast_label*, ast_function*, bool lvalue, ir_value**);
40 static bool ast_goto_codegen(ast_goto*, ast_function*, bool lvalue, ir_value**);
41 static void ast_goto_delete(ast_goto*);
42 static void ast_call_delete(ast_call*);
43 static bool ast_call_codegen(ast_call*, ast_function*, bool lvalue, ir_value**);
44 static bool ast_block_codegen(ast_block*, ast_function*, bool lvalue, ir_value**);
45 static void ast_unary_delete(ast_unary*);
46 static bool ast_unary_codegen(ast_unary*, ast_function*, bool lvalue, ir_value**);
47 static void ast_entfield_delete(ast_entfield*);
48 static bool ast_entfield_codegen(ast_entfield*, ast_function*, bool lvalue, ir_value**);
49 static void ast_return_delete(ast_return*);
50 static bool ast_return_codegen(ast_return*, ast_function*, bool lvalue, ir_value**);
51 static void ast_binstore_delete(ast_binstore*);
52 static bool ast_binstore_codegen(ast_binstore*, ast_function*, bool lvalue, ir_value**);
53 static void ast_binary_delete(ast_binary*);
54 static bool ast_binary_codegen(ast_binary*, ast_function*, bool lvalue, ir_value**);
55 static bool ast_state_codegen(ast_state*, ast_function*, bool lvalue, ir_value**);
56
57 /* It must not be possible to get here. */
58 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
59 {
60     (void)self;
61     con_err("ast node missing destroy()\n");
62     exit(EXIT_FAILURE);
63 }
64
65 /* Initialize main ast node aprts */
66 static void ast_node_init(ast_node *self, lex_ctx_t ctx, int nodetype)
67 {
68     self->context = ctx;
69     self->destroy = &_ast_node_destroy;
70     self->keep    = false;
71     self->nodetype = nodetype;
72     self->side_effects = false;
73 }
74
75 /* weight and side effects */
76 static void _ast_propagate_effects(ast_node *self, ast_node *other)
77 {
78     if (ast_side_effects(other))
79         ast_side_effects(self) = true;
80 }
81 #define ast_propagate_effects(s,o) _ast_propagate_effects(((ast_node*)(s)), ((ast_node*)(o)))
82
83 /* General expression initialization */
84 static void ast_expression_init(ast_expression *self,
85                                 ast_expression_codegen *codegen)
86 {
87     self->codegen  = codegen;
88     self->vtype    = TYPE_VOID;
89     self->next     = NULL;
90     self->outl     = NULL;
91     self->outr     = NULL;
92     self->params   = NULL;
93     self->count    = 0;
94     self->varparam = NULL;
95     self->flags    = 0;
96     if (OPTS_OPTION_BOOL(OPTION_COVERAGE))
97         self->flags |= AST_FLAG_BLOCK_COVERAGE;
98 }
99
100 static void ast_expression_delete(ast_expression *self)
101 {
102     size_t i;
103     if (self->next)
104         ast_delete(self->next);
105     for (i = 0; i < vec_size(self->params); ++i) {
106         ast_delete(self->params[i]);
107     }
108     vec_free(self->params);
109     if (self->varparam)
110         ast_delete(self->varparam);
111 }
112
113 static void ast_expression_delete_full(ast_expression *self)
114 {
115     ast_expression_delete(self);
116     mem_d(self);
117 }
118
119 ast_value* ast_value_copy(const ast_value *self)
120 {
121     size_t i;
122     const ast_expression *fromex;
123     ast_expression       *selfex;
124     ast_value *cp = ast_value_new(self->expression.node.context, self->name, self->expression.vtype);
125     if (self->expression.next) {
126         cp->expression.next = ast_type_copy(self->expression.node.context, self->expression.next);
127     }
128     fromex   = &self->expression;
129     selfex = &cp->expression;
130     selfex->count    = fromex->count;
131     selfex->flags    = fromex->flags;
132     for (i = 0; i < vec_size(fromex->params); ++i) {
133         ast_value *v = ast_value_copy(fromex->params[i]);
134         vec_push(selfex->params, v);
135     }
136     return cp;
137 }
138
139 void ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
140 {
141     size_t i;
142     const ast_expression *fromex;
143     ast_expression       *selfex;
144     self->vtype = other->vtype;
145     if (other->next) {
146         self->next = (ast_expression*)ast_type_copy(ast_ctx(self), other->next);
147     }
148     fromex = other;
149     selfex = self;
150     selfex->count    = fromex->count;
151     selfex->flags    = fromex->flags;
152     for (i = 0; i < vec_size(fromex->params); ++i) {
153         ast_value *v = ast_value_copy(fromex->params[i]);
154         vec_push(selfex->params, v);
155     }
156 }
157
158 static ast_expression* ast_shallow_type(lex_ctx_t ctx, int vtype)
159 {
160     ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
161     ast_expression_init(self, NULL);
162     self->codegen = NULL;
163     self->next    = NULL;
164     self->vtype   = vtype;
165     return self;
166 }
167
168 ast_expression* ast_type_copy(lex_ctx_t ctx, const ast_expression *ex)
169 {
170     size_t i;
171     const ast_expression *fromex;
172     ast_expression       *selfex;
173
174     if (!ex)
175         return NULL;
176     else
177     {
178         ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
179         ast_expression_init(self, NULL);
180
181         fromex = ex;
182         selfex = self;
183
184         /* This may never be codegen()d */
185         selfex->codegen = NULL;
186
187         selfex->vtype = fromex->vtype;
188         if (fromex->next)
189             selfex->next = ast_type_copy(ctx, fromex->next);
190         else
191             selfex->next = NULL;
192
193         selfex->count    = fromex->count;
194         selfex->flags    = fromex->flags;
195         for (i = 0; i < vec_size(fromex->params); ++i) {
196             ast_value *v = ast_value_copy(fromex->params[i]);
197             vec_push(selfex->params, v);
198         }
199
200         return self;
201     }
202 }
203
204 bool ast_compare_type(ast_expression *a, ast_expression *b)
205 {
206     if (a->vtype == TYPE_NIL ||
207         b->vtype == TYPE_NIL)
208         return true;
209     if (a->vtype != b->vtype)
210         return false;
211     if (!a->next != !b->next)
212         return false;
213     if (vec_size(a->params) != vec_size(b->params))
214         return false;
215     if ((a->flags & AST_FLAG_TYPE_MASK) !=
216         (b->flags & AST_FLAG_TYPE_MASK) )
217     {
218         return false;
219     }
220     if (vec_size(a->params)) {
221         size_t i;
222         for (i = 0; i < vec_size(a->params); ++i) {
223             if (!ast_compare_type((ast_expression*)a->params[i],
224                                   (ast_expression*)b->params[i]))
225                 return false;
226         }
227     }
228     if (a->next)
229         return ast_compare_type(a->next, b->next);
230     return true;
231 }
232
233 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
234 {
235     const char *typestr;
236     size_t typelen;
237     size_t i;
238
239     if (!e) {
240         if (pos + 6 >= bufsize)
241             goto full;
242         util_strncpy(buf + pos, "(null)", 6);
243         return pos + 6;
244     }
245
246     if (pos + 1 >= bufsize)
247         goto full;
248
249     switch (e->vtype) {
250         case TYPE_VARIANT:
251             util_strncpy(buf + pos, "(variant)", 9);
252             return pos + 9;
253
254         case TYPE_FIELD:
255             buf[pos++] = '.';
256             return ast_type_to_string_impl(e->next, buf, bufsize, pos);
257
258         case TYPE_POINTER:
259             if (pos + 3 >= bufsize)
260                 goto full;
261             buf[pos++] = '*';
262             buf[pos++] = '(';
263             pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
264             if (pos + 1 >= bufsize)
265                 goto full;
266             buf[pos++] = ')';
267             return pos;
268
269         case TYPE_FUNCTION:
270             pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
271             if (pos + 2 >= bufsize)
272                 goto full;
273             if (!vec_size(e->params)) {
274                 buf[pos++] = '(';
275                 buf[pos++] = ')';
276                 return pos;
277             }
278             buf[pos++] = '(';
279             pos = ast_type_to_string_impl((ast_expression*)(e->params[0]), buf, bufsize, pos);
280             for (i = 1; i < vec_size(e->params); ++i) {
281                 if (pos + 2 >= bufsize)
282                     goto full;
283                 buf[pos++] = ',';
284                 buf[pos++] = ' ';
285                 pos = ast_type_to_string_impl((ast_expression*)(e->params[i]), buf, bufsize, pos);
286             }
287             if (pos + 1 >= bufsize)
288                 goto full;
289             buf[pos++] = ')';
290             return pos;
291
292         case TYPE_ARRAY:
293             pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
294             if (pos + 1 >= bufsize)
295                 goto full;
296             buf[pos++] = '[';
297             pos += util_snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->count);
298             if (pos + 1 >= bufsize)
299                 goto full;
300             buf[pos++] = ']';
301             return pos;
302
303         default:
304             typestr = type_name[e->vtype];
305             typelen = strlen(typestr);
306             if (pos + typelen >= bufsize)
307                 goto full;
308             util_strncpy(buf + pos, typestr, typelen);
309             return pos + typelen;
310     }
311
312 full:
313     buf[bufsize-3] = '.';
314     buf[bufsize-2] = '.';
315     buf[bufsize-1] = '.';
316     return bufsize;
317 }
318
319 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
320 {
321     size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
322     buf[pos] = 0;
323 }
324
325 static bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out);
326 ast_value* ast_value_new(lex_ctx_t ctx, const char *name, int t)
327 {
328     ast_instantiate(ast_value, ctx, ast_value_delete);
329     ast_expression_init((ast_expression*)self,
330                         (ast_expression_codegen*)&ast_value_codegen);
331     self->expression.node.keep = true; /* keep */
332
333     self->name = name ? util_strdup(name) : NULL;
334     self->expression.vtype = t;
335     self->expression.next  = NULL;
336     self->isfield  = false;
337     self->cvq      = CV_NONE;
338     self->hasvalue = false;
339     self->isimm    = false;
340     self->inexact  = false;
341     self->uses     = 0;
342     memset(&self->constval, 0, sizeof(self->constval));
343     self->initlist = NULL;
344
345     self->ir_v           = NULL;
346     self->ir_values      = NULL;
347     self->ir_value_count = 0;
348
349     self->setter = NULL;
350     self->getter = NULL;
351     self->desc   = NULL;
352
353     self->argcounter = NULL;
354     self->intrinsic = false;
355
356     return self;
357 }
358
359 void ast_value_delete(ast_value* self)
360 {
361     if (self->name)
362         mem_d((void*)self->name);
363     if (self->argcounter)
364         mem_d((void*)self->argcounter);
365     if (self->hasvalue) {
366         switch (self->expression.vtype)
367         {
368         case TYPE_STRING:
369             mem_d((void*)self->constval.vstring);
370             break;
371         case TYPE_FUNCTION:
372             /* unlink us from the function node */
373             self->constval.vfunc->vtype = NULL;
374             break;
375         /* NOTE: delete function? currently collected in
376          * the parser structure
377          */
378         default:
379             break;
380         }
381     }
382     if (self->ir_values)
383         mem_d(self->ir_values);
384
385     if (self->desc)
386         mem_d(self->desc);
387
388     if (self->initlist) {
389         if (self->expression.next->vtype == TYPE_STRING) {
390             /* strings are allocated, free them */
391             size_t i, len = vec_size(self->initlist);
392             /* in theory, len should be expression.count
393              * but let's not take any chances */
394             for (i = 0; i < len; ++i) {
395                 if (self->initlist[i].vstring)
396                     mem_d(self->initlist[i].vstring);
397             }
398         }
399         vec_free(self->initlist);
400     }
401
402     ast_expression_delete((ast_expression*)self);
403     mem_d(self);
404 }
405
406 void ast_value_params_add(ast_value *self, ast_value *p)
407 {
408     vec_push(self->expression.params, p);
409 }
410
411 bool ast_value_set_name(ast_value *self, const char *name)
412 {
413     if (self->name)
414         mem_d((void*)self->name);
415     self->name = util_strdup(name);
416     return !!self->name;
417 }
418
419 ast_binary* ast_binary_new(lex_ctx_t ctx, int op,
420                            ast_expression* left, ast_expression* right)
421 {
422     ast_instantiate(ast_binary, ctx, ast_binary_delete);
423     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
424
425     if (ast_istype(right, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
426         ast_unary      *unary  = ((ast_unary*)right);
427         ast_expression *normal = unary->operand;
428
429         /* make a-(-b) => a + b */
430         if (unary->op == VINSTR_NEG_F || unary->op == VINSTR_NEG_V) {
431             if (op == INSTR_SUB_F) {
432                 op = INSTR_ADD_F;
433                 right = normal;
434                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
435             } else if (op == INSTR_SUB_V) {
436                 op = INSTR_ADD_V;
437                 right = normal;
438                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
439             }
440         }
441     }
442
443     self->op = op;
444     self->left = left;
445     self->right = right;
446     self->right_first = false;
447
448     ast_propagate_effects(self, left);
449     ast_propagate_effects(self, right);
450
451     if (op >= INSTR_EQ_F && op <= INSTR_GT)
452         self->expression.vtype = TYPE_FLOAT;
453     else if (op == INSTR_AND || op == INSTR_OR) {
454         if (OPTS_FLAG(PERL_LOGIC))
455             ast_type_adopt(self, right);
456         else
457             self->expression.vtype = TYPE_FLOAT;
458     }
459     else if (op == INSTR_BITAND || op == INSTR_BITOR)
460         self->expression.vtype = TYPE_FLOAT;
461     else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
462         self->expression.vtype = TYPE_VECTOR;
463     else if (op == INSTR_MUL_V)
464         self->expression.vtype = TYPE_FLOAT;
465     else
466         self->expression.vtype = left->vtype;
467
468     /* references all */
469     self->refs = AST_REF_ALL;
470
471     return self;
472 }
473
474 void ast_binary_delete(ast_binary *self)
475 {
476     if (self->refs & AST_REF_LEFT)  ast_unref(self->left);
477     if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
478
479     ast_expression_delete((ast_expression*)self);
480     mem_d(self);
481 }
482
483 ast_binstore* ast_binstore_new(lex_ctx_t ctx, int storop, int op,
484                                ast_expression* left, ast_expression* right)
485 {
486     ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
487     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
488
489     ast_side_effects(self) = true;
490
491     self->opstore = storop;
492     self->opbin   = op;
493     self->dest    = left;
494     self->source  = right;
495
496     self->keep_dest = false;
497
498     ast_type_adopt(self, left);
499     return self;
500 }
501
502 void ast_binstore_delete(ast_binstore *self)
503 {
504     if (!self->keep_dest)
505         ast_unref(self->dest);
506     ast_unref(self->source);
507     ast_expression_delete((ast_expression*)self);
508     mem_d(self);
509 }
510
511 ast_unary* ast_unary_new(lex_ctx_t ctx, int op,
512                          ast_expression *expr)
513 {
514     ast_instantiate(ast_unary, ctx, ast_unary_delete);
515     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
516
517     self->op      = op;
518     self->operand = expr;
519
520
521     if (ast_istype(expr, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
522         ast_unary *prev = (ast_unary*)((ast_unary*)expr)->operand;
523
524         /* Handle for double negation */
525         if (((ast_unary*)expr)->op == op)
526             prev = (ast_unary*)((ast_unary*)expr)->operand;
527
528         if (ast_istype(prev, ast_unary)) {
529             ast_expression_delete((ast_expression*)self);
530             mem_d(self);
531             ++opts_optimizationcount[OPTIM_PEEPHOLE];
532             return prev;
533         }
534     }
535
536     ast_propagate_effects(self, expr);
537
538     if ((op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) || op == VINSTR_NEG_F) {
539         self->expression.vtype = TYPE_FLOAT;
540     } else if (op == VINSTR_NEG_V) {
541         self->expression.vtype = TYPE_VECTOR;
542     } else {
543         compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
544     }
545
546     return self;
547 }
548
549 void ast_unary_delete(ast_unary *self)
550 {
551     if (self->operand) ast_unref(self->operand);
552     ast_expression_delete((ast_expression*)self);
553     mem_d(self);
554 }
555
556 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
557 {
558     ast_instantiate(ast_return, ctx, ast_return_delete);
559     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
560
561     self->operand = expr;
562
563     if (expr)
564         ast_propagate_effects(self, expr);
565
566     return self;
567 }
568
569 void ast_return_delete(ast_return *self)
570 {
571     if (self->operand)
572         ast_unref(self->operand);
573     ast_expression_delete((ast_expression*)self);
574     mem_d(self);
575 }
576
577 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
578 {
579     if (field->vtype != TYPE_FIELD) {
580         compile_error(ctx, "ast_entfield_new with expression not of type field");
581         return NULL;
582     }
583     return ast_entfield_new_force(ctx, entity, field, field->next);
584 }
585
586 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
587 {
588     ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
589
590     if (!outtype) {
591         mem_d(self);
592         /* Error: field has no type... */
593         return NULL;
594     }
595
596     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
597
598     self->entity = entity;
599     self->field  = field;
600     ast_propagate_effects(self, entity);
601     ast_propagate_effects(self, field);
602
603     ast_type_adopt(self, outtype);
604     return self;
605 }
606
607 void ast_entfield_delete(ast_entfield *self)
608 {
609     ast_unref(self->entity);
610     ast_unref(self->field);
611     ast_expression_delete((ast_expression*)self);
612     mem_d(self);
613 }
614
615 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
616 {
617     ast_instantiate(ast_member, ctx, ast_member_delete);
618     if (field >= 3) {
619         mem_d(self);
620         return NULL;
621     }
622
623     if (owner->vtype != TYPE_VECTOR &&
624         owner->vtype != TYPE_FIELD) {
625         compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
626         mem_d(self);
627         return NULL;
628     }
629
630     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
631     self->expression.node.keep = true; /* keep */
632
633     if (owner->vtype == TYPE_VECTOR) {
634         self->expression.vtype = TYPE_FLOAT;
635         self->expression.next  = NULL;
636     } else {
637         self->expression.vtype = TYPE_FIELD;
638         self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
639     }
640
641     self->rvalue = false;
642     self->owner  = owner;
643     ast_propagate_effects(self, owner);
644
645     self->field = field;
646     if (name)
647         self->name = util_strdup(name);
648     else
649         self->name = NULL;
650
651     return self;
652 }
653
654 void ast_member_delete(ast_member *self)
655 {
656     /* The owner is always an ast_value, which has .keep=true,
657      * also: ast_members are usually deleted after the owner, thus
658      * this will cause invalid access
659     ast_unref(self->owner);
660      * once we allow (expression).x to access a vector-member, we need
661      * to change this: preferably by creating an alternate ast node for this
662      * purpose that is not garbage-collected.
663     */
664     ast_expression_delete((ast_expression*)self);
665     mem_d(self->name);
666     mem_d(self);
667 }
668
669 bool ast_member_set_name(ast_member *self, const char *name)
670 {
671     if (self->name)
672         mem_d((void*)self->name);
673     self->name = util_strdup(name);
674     return !!self->name;
675 }
676
677 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
678 {
679     ast_expression *outtype;
680     ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
681
682     outtype = array->next;
683     if (!outtype) {
684         mem_d(self);
685         /* Error: field has no type... */
686         return NULL;
687     }
688
689     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
690
691     self->array = array;
692     self->index = index;
693     ast_propagate_effects(self, array);
694     ast_propagate_effects(self, index);
695
696     ast_type_adopt(self, outtype);
697     if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
698         if (self->expression.vtype != TYPE_ARRAY) {
699             compile_error(ast_ctx(self), "array_index node on type");
700             ast_array_index_delete(self);
701             return NULL;
702         }
703         self->array = outtype;
704         self->expression.vtype = TYPE_FIELD;
705     }
706
707     return self;
708 }
709
710 void ast_array_index_delete(ast_array_index *self)
711 {
712     if (self->array)
713         ast_unref(self->array);
714     if (self->index)
715         ast_unref(self->index);
716     ast_expression_delete((ast_expression*)self);
717     mem_d(self);
718 }
719
720 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
721 {
722     ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete);
723     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
724     self->index = index;
725     self->expression.vtype = TYPE_NOEXPR;
726     return self;
727 }
728
729 void ast_argpipe_delete(ast_argpipe *self)
730 {
731     if (self->index)
732         ast_unref(self->index);
733     ast_expression_delete((ast_expression*)self);
734     mem_d(self);
735 }
736
737 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
738 {
739     ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
740     if (!ontrue && !onfalse) {
741         /* because it is invalid */
742         mem_d(self);
743         return NULL;
744     }
745     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
746
747     self->cond     = cond;
748     self->on_true  = ontrue;
749     self->on_false = onfalse;
750     ast_propagate_effects(self, cond);
751     if (ontrue)
752         ast_propagate_effects(self, ontrue);
753     if (onfalse)
754         ast_propagate_effects(self, onfalse);
755
756     return self;
757 }
758
759 void ast_ifthen_delete(ast_ifthen *self)
760 {
761     ast_unref(self->cond);
762     if (self->on_true)
763         ast_unref(self->on_true);
764     if (self->on_false)
765         ast_unref(self->on_false);
766     ast_expression_delete((ast_expression*)self);
767     mem_d(self);
768 }
769
770 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
771 {
772     ast_expression *exprtype = ontrue;
773     ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
774     /* This time NEITHER must be NULL */
775     if (!ontrue || !onfalse) {
776         mem_d(self);
777         return NULL;
778     }
779     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
780
781     self->cond     = cond;
782     self->on_true  = ontrue;
783     self->on_false = onfalse;
784     ast_propagate_effects(self, cond);
785     ast_propagate_effects(self, ontrue);
786     ast_propagate_effects(self, onfalse);
787
788     if (ontrue->vtype == TYPE_NIL)
789         exprtype = onfalse;
790     ast_type_adopt(self, exprtype);
791
792     return self;
793 }
794
795 void ast_ternary_delete(ast_ternary *self)
796 {
797     /* the if()s are only there because computed-gotos can set them
798      * to NULL
799      */
800     if (self->cond)     ast_unref(self->cond);
801     if (self->on_true)  ast_unref(self->on_true);
802     if (self->on_false) ast_unref(self->on_false);
803     ast_expression_delete((ast_expression*)self);
804     mem_d(self);
805 }
806
807 ast_loop* ast_loop_new(lex_ctx_t ctx,
808                        ast_expression *initexpr,
809                        ast_expression *precond, bool pre_not,
810                        ast_expression *postcond, bool post_not,
811                        ast_expression *increment,
812                        ast_expression *body)
813 {
814     ast_instantiate(ast_loop, ctx, ast_loop_delete);
815     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
816
817     self->initexpr  = initexpr;
818     self->precond   = precond;
819     self->postcond  = postcond;
820     self->increment = increment;
821     self->body      = body;
822
823     self->pre_not   = pre_not;
824     self->post_not  = post_not;
825
826     if (initexpr)
827         ast_propagate_effects(self, initexpr);
828     if (precond)
829         ast_propagate_effects(self, precond);
830     if (postcond)
831         ast_propagate_effects(self, postcond);
832     if (increment)
833         ast_propagate_effects(self, increment);
834     if (body)
835         ast_propagate_effects(self, body);
836
837     return self;
838 }
839
840 void ast_loop_delete(ast_loop *self)
841 {
842     if (self->initexpr)
843         ast_unref(self->initexpr);
844     if (self->precond)
845         ast_unref(self->precond);
846     if (self->postcond)
847         ast_unref(self->postcond);
848     if (self->increment)
849         ast_unref(self->increment);
850     if (self->body)
851         ast_unref(self->body);
852     ast_expression_delete((ast_expression*)self);
853     mem_d(self);
854 }
855
856 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
857 {
858     ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
859     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
860
861     self->is_continue = iscont;
862     self->levels      = levels;
863
864     return self;
865 }
866
867 void ast_breakcont_delete(ast_breakcont *self)
868 {
869     ast_expression_delete((ast_expression*)self);
870     mem_d(self);
871 }
872
873 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
874 {
875     ast_instantiate(ast_switch, ctx, ast_switch_delete);
876     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
877
878     self->operand = op;
879     self->cases   = NULL;
880
881     ast_propagate_effects(self, op);
882
883     return self;
884 }
885
886 void ast_switch_delete(ast_switch *self)
887 {
888     size_t i;
889     ast_unref(self->operand);
890
891     for (i = 0; i < vec_size(self->cases); ++i) {
892         if (self->cases[i].value)
893             ast_unref(self->cases[i].value);
894         ast_unref(self->cases[i].code);
895     }
896     vec_free(self->cases);
897
898     ast_expression_delete((ast_expression*)self);
899     mem_d(self);
900 }
901
902 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
903 {
904     ast_instantiate(ast_label, ctx, ast_label_delete);
905     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
906
907     self->expression.vtype = TYPE_NOEXPR;
908
909     self->name      = util_strdup(name);
910     self->irblock   = NULL;
911     self->gotos     = NULL;
912     self->undefined = undefined;
913
914     return self;
915 }
916
917 void ast_label_delete(ast_label *self)
918 {
919     mem_d((void*)self->name);
920     vec_free(self->gotos);
921     ast_expression_delete((ast_expression*)self);
922     mem_d(self);
923 }
924
925 static void ast_label_register_goto(ast_label *self, ast_goto *g)
926 {
927     vec_push(self->gotos, g);
928 }
929
930 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
931 {
932     ast_instantiate(ast_goto, ctx, ast_goto_delete);
933     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
934
935     self->name    = util_strdup(name);
936     self->target  = NULL;
937     self->irblock_from = NULL;
938
939     return self;
940 }
941
942 void ast_goto_delete(ast_goto *self)
943 {
944     mem_d((void*)self->name);
945     ast_expression_delete((ast_expression*)self);
946     mem_d(self);
947 }
948
949 void ast_goto_set_label(ast_goto *self, ast_label *label)
950 {
951     self->target = label;
952 }
953
954 ast_state* ast_state_new(lex_ctx_t ctx, ast_expression *frame, ast_expression *think)
955 {
956     ast_instantiate(ast_state, ctx, ast_state_delete);
957     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_state_codegen);
958     self->framenum  = frame;
959     self->nextthink = think;
960     return self;
961 }
962
963 void ast_state_delete(ast_state *self)
964 {
965     if (self->framenum)
966         ast_unref(self->framenum);
967     if (self->nextthink)
968         ast_unref(self->nextthink);
969
970     ast_expression_delete((ast_expression*)self);
971     mem_d(self);
972 }
973
974 ast_call* ast_call_new(lex_ctx_t ctx,
975                        ast_expression *funcexpr)
976 {
977     ast_instantiate(ast_call, ctx, ast_call_delete);
978     if (!funcexpr->next) {
979         compile_error(ctx, "not a function");
980         mem_d(self);
981         return NULL;
982     }
983     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
984
985     ast_side_effects(self) = true;
986
987     self->params   = NULL;
988     self->func     = funcexpr;
989     self->va_count = NULL;
990
991     ast_type_adopt(self, funcexpr->next);
992
993     return self;
994 }
995
996 void ast_call_delete(ast_call *self)
997 {
998     size_t i;
999     for (i = 0; i < vec_size(self->params); ++i)
1000         ast_unref(self->params[i]);
1001     vec_free(self->params);
1002
1003     if (self->func)
1004         ast_unref(self->func);
1005
1006     if (self->va_count)
1007         ast_unref(self->va_count);
1008
1009     ast_expression_delete((ast_expression*)self);
1010     mem_d(self);
1011 }
1012
1013 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
1014 {
1015     char texp[1024];
1016     char tgot[1024];
1017     if (!exp_type)
1018         return true;
1019     if (!va_type || !ast_compare_type(va_type, exp_type))
1020     {
1021         if (va_type && exp_type)
1022         {
1023             ast_type_to_string(va_type,  tgot, sizeof(tgot));
1024             ast_type_to_string(exp_type, texp, sizeof(texp));
1025             if (OPTS_FLAG(UNSAFE_VARARGS)) {
1026                 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1027                                     "piped variadic argument differs in type: constrained to type %s, expected type %s",
1028                                     tgot, texp))
1029                     return false;
1030             } else {
1031                 compile_error(ast_ctx(self),
1032                               "piped variadic argument differs in type: constrained to type %s, expected type %s",
1033                               tgot, texp);
1034                 return false;
1035             }
1036         }
1037         else
1038         {
1039             ast_type_to_string(exp_type, texp, sizeof(texp));
1040             if (OPTS_FLAG(UNSAFE_VARARGS)) {
1041                 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1042                                     "piped variadic argument may differ in type: expected type %s",
1043                                     texp))
1044                     return false;
1045             } else {
1046                 compile_error(ast_ctx(self),
1047                               "piped variadic argument may differ in type: expected type %s",
1048                               texp);
1049                 return false;
1050             }
1051         }
1052     }
1053     return true;
1054 }
1055
1056 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1057 {
1058     char texp[1024];
1059     char tgot[1024];
1060     size_t i;
1061     bool   retval = true;
1062     const  ast_expression *func = self->func;
1063     size_t count = vec_size(self->params);
1064     if (count > vec_size(func->params))
1065         count = vec_size(func->params);
1066
1067     for (i = 0; i < count; ++i) {
1068         if (ast_istype(self->params[i], ast_argpipe)) {
1069             /* warn about type safety instead */
1070             if (i+1 != count) {
1071                 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1072                 return false;
1073             }
1074             if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->params[i]))
1075                 retval = false;
1076         }
1077         else if (!ast_compare_type(self->params[i], (ast_expression*)(func->params[i])))
1078         {
1079             ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1080             ast_type_to_string((ast_expression*)func->params[i], texp, sizeof(texp));
1081             compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1082                      (unsigned int)(i+1), texp, tgot);
1083             /* we don't immediately return */
1084             retval = false;
1085         }
1086     }
1087     count = vec_size(self->params);
1088     if (count > vec_size(func->params) && func->varparam) {
1089         for (; i < count; ++i) {
1090             if (ast_istype(self->params[i], ast_argpipe)) {
1091                 /* warn about type safety instead */
1092                 if (i+1 != count) {
1093                     compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1094                     return false;
1095                 }
1096                 if (!ast_call_check_vararg(self, va_type, func->varparam))
1097                     retval = false;
1098             }
1099             else if (!ast_compare_type(self->params[i], func->varparam))
1100             {
1101                 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1102                 ast_type_to_string(func->varparam, texp, sizeof(texp));
1103                 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1104                          (unsigned int)(i+1), texp, tgot);
1105                 /* we don't immediately return */
1106                 retval = false;
1107             }
1108         }
1109     }
1110     return retval;
1111 }
1112
1113 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1114                          ast_expression *dest, ast_expression *source)
1115 {
1116     ast_instantiate(ast_store, ctx, ast_store_delete);
1117     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1118
1119     ast_side_effects(self) = true;
1120
1121     self->op = op;
1122     self->dest = dest;
1123     self->source = source;
1124
1125     ast_type_adopt(self, dest);
1126
1127     return self;
1128 }
1129
1130 void ast_store_delete(ast_store *self)
1131 {
1132     ast_unref(self->dest);
1133     ast_unref(self->source);
1134     ast_expression_delete((ast_expression*)self);
1135     mem_d(self);
1136 }
1137
1138 ast_block* ast_block_new(lex_ctx_t ctx)
1139 {
1140     ast_instantiate(ast_block, ctx, ast_block_delete);
1141     ast_expression_init((ast_expression*)self,
1142                         (ast_expression_codegen*)&ast_block_codegen);
1143
1144     self->locals  = NULL;
1145     self->exprs   = NULL;
1146     self->collect = NULL;
1147
1148     return self;
1149 }
1150
1151 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1152 {
1153     ast_propagate_effects(self, e);
1154     vec_push(self->exprs, e);
1155     if (self->expression.next) {
1156         ast_delete(self->expression.next);
1157         self->expression.next = NULL;
1158     }
1159     ast_type_adopt(self, e);
1160     return true;
1161 }
1162
1163 void ast_block_collect(ast_block *self, ast_expression *expr)
1164 {
1165     vec_push(self->collect, expr);
1166     expr->node.keep = true;
1167 }
1168
1169 void ast_block_delete(ast_block *self)
1170 {
1171     size_t i;
1172     for (i = 0; i < vec_size(self->exprs); ++i)
1173         ast_unref(self->exprs[i]);
1174     vec_free(self->exprs);
1175     for (i = 0; i < vec_size(self->locals); ++i)
1176         ast_delete(self->locals[i]);
1177     vec_free(self->locals);
1178     for (i = 0; i < vec_size(self->collect); ++i)
1179         ast_delete(self->collect[i]);
1180     vec_free(self->collect);
1181     ast_expression_delete((ast_expression*)self);
1182     mem_d(self);
1183 }
1184
1185 void ast_block_set_type(ast_block *self, ast_expression *from)
1186 {
1187     if (self->expression.next)
1188         ast_delete(self->expression.next);
1189     ast_type_adopt(self, from);
1190 }
1191
1192 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1193 {
1194     ast_instantiate(ast_function, ctx, ast_function_delete);
1195
1196     if (!vtype) {
1197         compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1198         goto cleanup;
1199     } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1200         compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1201                  (int)!vtype,
1202                  (int)vtype->hasvalue,
1203                  vtype->expression.vtype);
1204         goto cleanup;
1205     }
1206
1207     self->vtype  = vtype;
1208     self->name   = name ? util_strdup(name) : NULL;
1209     self->blocks = NULL;
1210
1211     self->labelcount = 0;
1212     self->builtin = 0;
1213
1214     self->ir_func = NULL;
1215     self->curblock = NULL;
1216
1217     self->breakblocks    = NULL;
1218     self->continueblocks = NULL;
1219
1220     vtype->hasvalue = true;
1221     vtype->constval.vfunc = self;
1222
1223     self->varargs          = NULL;
1224     self->argc             = NULL;
1225     self->fixedparams      = NULL;
1226     self->return_value     = NULL;
1227
1228     self->static_names     = NULL;
1229     self->static_count     = 0;
1230
1231     return self;
1232
1233 cleanup:
1234     mem_d(self);
1235     return NULL;
1236 }
1237
1238 void ast_function_delete(ast_function *self)
1239 {
1240     size_t i;
1241     if (self->name)
1242         mem_d((void*)self->name);
1243     if (self->vtype) {
1244         /* ast_value_delete(self->vtype); */
1245         self->vtype->hasvalue = false;
1246         self->vtype->constval.vfunc = NULL;
1247         /* We use unref - if it was stored in a global table it is supposed
1248          * to be deleted from *there*
1249          */
1250         ast_unref(self->vtype);
1251     }
1252     for (i = 0; i < vec_size(self->static_names); ++i)
1253         mem_d(self->static_names[i]);
1254     vec_free(self->static_names);
1255     for (i = 0; i < vec_size(self->blocks); ++i)
1256         ast_delete(self->blocks[i]);
1257     vec_free(self->blocks);
1258     vec_free(self->breakblocks);
1259     vec_free(self->continueblocks);
1260     if (self->varargs)
1261         ast_delete(self->varargs);
1262     if (self->argc)
1263         ast_delete(self->argc);
1264     if (self->fixedparams)
1265         ast_unref(self->fixedparams);
1266     if (self->return_value)
1267         ast_unref(self->return_value);
1268     mem_d(self);
1269 }
1270
1271 const char* ast_function_label(ast_function *self, const char *prefix)
1272 {
1273     size_t id;
1274     size_t len;
1275     char  *from;
1276
1277     if (!OPTS_OPTION_BOOL(OPTION_DUMP)    &&
1278         !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1279         !OPTS_OPTION_BOOL(OPTION_DEBUG))
1280     {
1281         return NULL;
1282     }
1283
1284     id  = (self->labelcount++);
1285     len = strlen(prefix);
1286
1287     from = self->labelbuf + sizeof(self->labelbuf)-1;
1288     *from-- = 0;
1289     do {
1290         *from-- = (id%10) + '0';
1291         id /= 10;
1292     } while (id);
1293     ++from;
1294     memcpy(from - len, prefix, len);
1295     return from - len;
1296 }
1297
1298 /*********************************************************************/
1299 /* AST codegen part
1300  * by convention you must never pass NULL to the 'ir_value **out'
1301  * parameter. If you really don't care about the output, pass a dummy.
1302  * But I can't imagine a pituation where the output is truly unnecessary.
1303  */
1304
1305 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1306 {
1307     if (out->vtype == TYPE_FIELD)
1308         out->fieldtype = self->next->vtype;
1309     if (out->vtype == TYPE_FUNCTION)
1310         out->outtype = self->next->vtype;
1311 }
1312
1313 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1314
1315 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1316 {
1317     (void)func;
1318     (void)lvalue;
1319     if (self->expression.vtype == TYPE_NIL) {
1320         *out = func->ir_func->owner->nil;
1321         return true;
1322     }
1323     /* NOTE: This is the codegen for a variable used in an expression.
1324      * It is not the codegen to generate the value. For this purpose,
1325      * ast_local_codegen and ast_global_codegen are to be used before this
1326      * is executed. ast_function_codegen should take care of its locals,
1327      * and the ast-user should take care of ast_global_codegen to be used
1328      * on all the globals.
1329      */
1330     if (!self->ir_v) {
1331         char tname[1024]; /* typename is reserved in C++ */
1332         ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1333         compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1334         return false;
1335     }
1336     *out = self->ir_v;
1337     return true;
1338 }
1339
1340 static bool ast_global_array_set(ast_value *self)
1341 {
1342     size_t count = vec_size(self->initlist);
1343     size_t i;
1344
1345     if (count > self->expression.count) {
1346         compile_error(ast_ctx(self), "too many elements in initializer");
1347         count = self->expression.count;
1348     }
1349     else if (count < self->expression.count) {
1350         /* add this?
1351         compile_warning(ast_ctx(self), "not all elements are initialized");
1352         */
1353     }
1354
1355     for (i = 0; i != count; ++i) {
1356         switch (self->expression.next->vtype) {
1357             case TYPE_FLOAT:
1358                 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1359                     return false;
1360                 break;
1361             case TYPE_VECTOR:
1362                 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1363                     return false;
1364                 break;
1365             case TYPE_STRING:
1366                 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1367                     return false;
1368                 break;
1369             case TYPE_ARRAY:
1370                 /* we don't support them in any other place yet either */
1371                 compile_error(ast_ctx(self), "TODO: nested arrays");
1372                 return false;
1373             case TYPE_FUNCTION:
1374                 /* this requiers a bit more work - similar to the fields I suppose */
1375                 compile_error(ast_ctx(self), "global of type function not properly generated");
1376                 return false;
1377             case TYPE_FIELD:
1378                 if (!self->initlist[i].vfield) {
1379                     compile_error(ast_ctx(self), "field constant without vfield set");
1380                     return false;
1381                 }
1382                 if (!self->initlist[i].vfield->ir_v) {
1383                     compile_error(ast_ctx(self), "field constant generated before its field");
1384                     return false;
1385                 }
1386                 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1387                     return false;
1388                 break;
1389             default:
1390                 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1391                 break;
1392         }
1393     }
1394     return true;
1395 }
1396
1397 static bool check_array(ast_value *self, ast_value *array)
1398 {
1399     if (array->expression.flags & AST_FLAG_ARRAY_INIT && !array->initlist) {
1400         compile_error(ast_ctx(self), "array without size: %s", self->name);
1401         return false;
1402     }
1403     /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1404     if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1405         compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1406         return false;
1407     }
1408     return true;
1409 }
1410
1411 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1412 {
1413     ir_value *v = NULL;
1414
1415     if (self->expression.vtype == TYPE_NIL) {
1416         compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1417         return false;
1418     }
1419
1420     if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1421     {
1422         ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1423         if (!func)
1424             return false;
1425         func->context = ast_ctx(self);
1426         func->value->context = ast_ctx(self);
1427
1428         self->constval.vfunc->ir_func = func;
1429         self->ir_v = func->value;
1430         if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1431             self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1432         if (self->expression.flags & AST_FLAG_ERASEABLE)
1433             self->ir_v->flags |= IR_FLAG_ERASABLE;
1434         if (self->expression.flags & AST_FLAG_BLOCK_COVERAGE)
1435             func->flags |= IR_FLAG_BLOCK_COVERAGE;
1436         /* The function is filled later on ast_function_codegen... */
1437         return true;
1438     }
1439
1440     if (isfield && self->expression.vtype == TYPE_FIELD) {
1441         ast_expression *fieldtype = self->expression.next;
1442
1443         if (self->hasvalue) {
1444             compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1445             goto error;
1446         }
1447
1448         if (fieldtype->vtype == TYPE_ARRAY) {
1449             size_t ai;
1450             char   *name;
1451             size_t  namelen;
1452
1453             ast_expression *elemtype;
1454             int             vtype;
1455             ast_value      *array = (ast_value*)fieldtype;
1456
1457             if (!ast_istype(fieldtype, ast_value)) {
1458                 compile_error(ast_ctx(self), "internal error: ast_value required");
1459                 return false;
1460             }
1461
1462             if (!check_array(self, array))
1463                 return false;
1464
1465             elemtype = array->expression.next;
1466             vtype = elemtype->vtype;
1467
1468             v = ir_builder_create_field(ir, self->name, vtype);
1469             if (!v) {
1470                 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1471                 return false;
1472             }
1473             v->context = ast_ctx(self);
1474             v->unique_life = true;
1475             v->locked      = true;
1476             array->ir_v = self->ir_v = v;
1477
1478             if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1479                 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1480             if (self->expression.flags & AST_FLAG_ERASEABLE)
1481                 self->ir_v->flags |= IR_FLAG_ERASABLE;
1482
1483             namelen = strlen(self->name);
1484             name    = (char*)mem_a(namelen + 16);
1485             util_strncpy(name, self->name, namelen);
1486
1487             array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1488             array->ir_values[0] = v;
1489             for (ai = 1; ai < array->expression.count; ++ai) {
1490                 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1491                 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1492                 if (!array->ir_values[ai]) {
1493                     mem_d(name);
1494                     compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1495                     return false;
1496                 }
1497                 array->ir_values[ai]->context = ast_ctx(self);
1498                 array->ir_values[ai]->unique_life = true;
1499                 array->ir_values[ai]->locked      = true;
1500                 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1501                     self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1502             }
1503             mem_d(name);
1504         }
1505         else
1506         {
1507             v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1508             if (!v)
1509                 return false;
1510             v->context = ast_ctx(self);
1511             self->ir_v = v;
1512             if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1513                 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1514
1515             if (self->expression.flags & AST_FLAG_ERASEABLE)
1516                 self->ir_v->flags |= IR_FLAG_ERASABLE;
1517         }
1518         return true;
1519     }
1520
1521     if (self->expression.vtype == TYPE_ARRAY) {
1522         size_t ai;
1523         char   *name;
1524         size_t  namelen;
1525
1526         ast_expression *elemtype = self->expression.next;
1527         int vtype = elemtype->vtype;
1528
1529         if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1530             compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1531             return false;
1532         }
1533
1534         /* same as with field arrays */
1535         if (!check_array(self, self))
1536             return false;
1537
1538         v = ir_builder_create_global(ir, self->name, vtype);
1539         if (!v) {
1540             compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1541             return false;
1542         }
1543         v->context = ast_ctx(self);
1544         v->unique_life = true;
1545         v->locked      = true;
1546
1547         if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1548             v->flags |= IR_FLAG_INCLUDE_DEF;
1549         if (self->expression.flags & AST_FLAG_ERASEABLE)
1550             self->ir_v->flags |= IR_FLAG_ERASABLE;
1551
1552         namelen = strlen(self->name);
1553         name    = (char*)mem_a(namelen + 16);
1554         util_strncpy(name, self->name, namelen);
1555
1556         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1557         self->ir_values[0] = v;
1558         for (ai = 1; ai < self->expression.count; ++ai) {
1559             util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1560             self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1561             if (!self->ir_values[ai]) {
1562                 mem_d(name);
1563                 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1564                 return false;
1565             }
1566             self->ir_values[ai]->context = ast_ctx(self);
1567             self->ir_values[ai]->unique_life = true;
1568             self->ir_values[ai]->locked      = true;
1569             if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1570                 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1571         }
1572         mem_d(name);
1573     }
1574     else
1575     {
1576         /* Arrays don't do this since there's no "array" value which spans across the
1577          * whole thing.
1578          */
1579         v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1580         if (!v) {
1581             compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1582             return false;
1583         }
1584         codegen_output_type(self, v);
1585         v->context = ast_ctx(self);
1586     }
1587
1588     /* link us to the ir_value */
1589     v->cvq = self->cvq;
1590     self->ir_v = v;
1591
1592     if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1593         self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1594     if (self->expression.flags & AST_FLAG_ERASEABLE)
1595         self->ir_v->flags |= IR_FLAG_ERASABLE;
1596
1597     /* initialize */
1598     if (self->hasvalue) {
1599         switch (self->expression.vtype)
1600         {
1601             case TYPE_FLOAT:
1602                 if (!ir_value_set_float(v, self->constval.vfloat))
1603                     goto error;
1604                 break;
1605             case TYPE_VECTOR:
1606                 if (!ir_value_set_vector(v, self->constval.vvec))
1607                     goto error;
1608                 break;
1609             case TYPE_STRING:
1610                 if (!ir_value_set_string(v, self->constval.vstring))
1611                     goto error;
1612                 break;
1613             case TYPE_ARRAY:
1614                 ast_global_array_set(self);
1615                 break;
1616             case TYPE_FUNCTION:
1617                 compile_error(ast_ctx(self), "global of type function not properly generated");
1618                 goto error;
1619                 /* Cannot generate an IR value for a function,
1620                  * need a pointer pointing to a function rather.
1621                  */
1622             case TYPE_FIELD:
1623                 if (!self->constval.vfield) {
1624                     compile_error(ast_ctx(self), "field constant without vfield set");
1625                     goto error;
1626                 }
1627                 if (!self->constval.vfield->ir_v) {
1628                     compile_error(ast_ctx(self), "field constant generated before its field");
1629                     goto error;
1630                 }
1631                 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1632                     goto error;
1633                 break;
1634             default:
1635                 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1636                 break;
1637         }
1638     }
1639     return true;
1640
1641 error: /* clean up */
1642     if(v) ir_value_delete(v);
1643     return false;
1644 }
1645
1646 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1647 {
1648     ir_value *v = NULL;
1649
1650     if (self->expression.vtype == TYPE_NIL) {
1651         compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1652         return false;
1653     }
1654
1655     if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1656     {
1657         /* Do we allow local functions? I think not...
1658          * this is NOT a function pointer atm.
1659          */
1660         return false;
1661     }
1662
1663     if (self->expression.vtype == TYPE_ARRAY) {
1664         size_t ai;
1665         char   *name;
1666         size_t  namelen;
1667
1668         ast_expression *elemtype = self->expression.next;
1669         int vtype = elemtype->vtype;
1670
1671         func->flags |= IR_FLAG_HAS_ARRAYS;
1672
1673         if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1674             compile_error(ast_ctx(self), "array-parameters are not supported");
1675             return false;
1676         }
1677
1678         /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1679         if (!check_array(self, self))
1680             return false;
1681
1682         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1683         if (!self->ir_values) {
1684             compile_error(ast_ctx(self), "failed to allocate array values");
1685             return false;
1686         }
1687
1688         v = ir_function_create_local(func, self->name, vtype, param);
1689         if (!v) {
1690             compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1691             return false;
1692         }
1693         v->context = ast_ctx(self);
1694         v->unique_life = true;
1695         v->locked      = true;
1696
1697         namelen = strlen(self->name);
1698         name    = (char*)mem_a(namelen + 16);
1699         util_strncpy(name, self->name, namelen);
1700
1701         self->ir_values[0] = v;
1702         for (ai = 1; ai < self->expression.count; ++ai) {
1703             util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1704             self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1705             if (!self->ir_values[ai]) {
1706                 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1707                 return false;
1708             }
1709             self->ir_values[ai]->context = ast_ctx(self);
1710             self->ir_values[ai]->unique_life = true;
1711             self->ir_values[ai]->locked      = true;
1712         }
1713         mem_d(name);
1714     }
1715     else
1716     {
1717         v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1718         if (!v)
1719             return false;
1720         codegen_output_type(self, v);
1721         v->context = ast_ctx(self);
1722     }
1723
1724     /* A constant local... hmmm...
1725      * I suppose the IR will have to deal with this
1726      */
1727     if (self->hasvalue) {
1728         switch (self->expression.vtype)
1729         {
1730             case TYPE_FLOAT:
1731                 if (!ir_value_set_float(v, self->constval.vfloat))
1732                     goto error;
1733                 break;
1734             case TYPE_VECTOR:
1735                 if (!ir_value_set_vector(v, self->constval.vvec))
1736                     goto error;
1737                 break;
1738             case TYPE_STRING:
1739                 if (!ir_value_set_string(v, self->constval.vstring))
1740                     goto error;
1741                 break;
1742             default:
1743                 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1744                 break;
1745         }
1746     }
1747
1748     /* link us to the ir_value */
1749     v->cvq = self->cvq;
1750     self->ir_v = v;
1751
1752     if (!ast_generate_accessors(self, func->owner))
1753         return false;
1754     return true;
1755
1756 error: /* clean up */
1757     ir_value_delete(v);
1758     return false;
1759 }
1760
1761 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1762 {
1763     size_t i;
1764     bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1765     if (!self->setter || !self->getter)
1766         return true;
1767     for (i = 0; i < self->expression.count; ++i) {
1768         if (!self->ir_values) {
1769             compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1770             return false;
1771         }
1772         if (!self->ir_values[i]) {
1773             compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1774             return false;
1775         }
1776         if (self->ir_values[i]->life) {
1777             compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1778             return false;
1779         }
1780     }
1781
1782     opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1783     if (self->setter) {
1784         if (!ast_global_codegen  (self->setter, ir, false) ||
1785             !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1786             !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1787         {
1788             compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1789             opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1790             return false;
1791         }
1792     }
1793     if (self->getter) {
1794         if (!ast_global_codegen  (self->getter, ir, false) ||
1795             !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1796             !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1797         {
1798             compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1799             opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1800             return false;
1801         }
1802     }
1803     for (i = 0; i < self->expression.count; ++i) {
1804         vec_free(self->ir_values[i]->life);
1805     }
1806     opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1807     return true;
1808 }
1809
1810 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1811 {
1812     ir_function *irf;
1813     ir_value    *dummy;
1814     ast_expression         *ec;
1815     ast_expression_codegen *cgen;
1816
1817     size_t    i;
1818
1819     (void)ir;
1820
1821     irf = self->ir_func;
1822     if (!irf) {
1823         compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1824         return false;
1825     }
1826
1827     /* fill the parameter list */
1828     ec = &self->vtype->expression;
1829     for (i = 0; i < vec_size(ec->params); ++i)
1830     {
1831         if (ec->params[i]->expression.vtype == TYPE_FIELD)
1832             vec_push(irf->params, ec->params[i]->expression.next->vtype);
1833         else
1834             vec_push(irf->params, ec->params[i]->expression.vtype);
1835         if (!self->builtin) {
1836             if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1837                 return false;
1838         }
1839     }
1840
1841     if (self->varargs) {
1842         if (!ast_local_codegen(self->varargs, self->ir_func, true))
1843             return false;
1844         irf->max_varargs = self->varargs->expression.count;
1845     }
1846
1847     if (self->builtin) {
1848         irf->builtin = self->builtin;
1849         return true;
1850     }
1851
1852     /* have a local return value variable? */
1853     if (self->return_value) {
1854         if (!ast_local_codegen(self->return_value, self->ir_func, false))
1855             return false;
1856     }
1857
1858     if (!vec_size(self->blocks)) {
1859         compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1860         return false;
1861     }
1862
1863     irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1864     if (!self->curblock) {
1865         compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1866         return false;
1867     }
1868
1869     if (self->argc) {
1870         ir_value *va_count;
1871         ir_value *fixed;
1872         ir_value *sub;
1873         if (!ast_local_codegen(self->argc, self->ir_func, true))
1874             return false;
1875         cgen = self->argc->expression.codegen;
1876         if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1877             return false;
1878         cgen = self->fixedparams->expression.codegen;
1879         if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1880             return false;
1881         sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1882                                     ast_function_label(self, "va_count"), INSTR_SUB_F,
1883                                     ir_builder_get_va_count(ir), fixed);
1884         if (!sub)
1885             return false;
1886         if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1887                                       va_count, sub))
1888         {
1889             return false;
1890         }
1891     }
1892
1893     for (i = 0; i < vec_size(self->blocks); ++i) {
1894         cgen = self->blocks[i]->expression.codegen;
1895         if (!(*cgen)((ast_expression*)self->blocks[i], self, false, &dummy))
1896             return false;
1897     }
1898
1899     /* TODO: check return types */
1900     if (!self->curblock->final)
1901     {
1902         if (!self->vtype->expression.next ||
1903             self->vtype->expression.next->vtype == TYPE_VOID)
1904         {
1905             return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1906         }
1907         else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1908         {
1909             if (self->return_value) {
1910                 cgen = self->return_value->expression.codegen;
1911                 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1912                     return false;
1913                 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1914             }
1915             else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1916                                 "control reaches end of non-void function (`%s`) via %s",
1917                                 self->name, self->curblock->label))
1918             {
1919                 return false;
1920             }
1921             return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1922         }
1923     }
1924     return true;
1925 }
1926
1927 static bool starts_a_label(ast_expression *ex)
1928 {
1929     while (ex && ast_istype(ex, ast_block)) {
1930         ast_block *b = (ast_block*)ex;
1931         ex = b->exprs[0];
1932     }
1933     if (!ex)
1934         return false;
1935     return ast_istype(ex, ast_label);
1936 }
1937
1938 /* Note, you will not see ast_block_codegen generate ir_blocks.
1939  * To the AST and the IR, blocks are 2 different things.
1940  * In the AST it represents a block of code, usually enclosed in
1941  * curly braces {...}.
1942  * While in the IR it represents a block in terms of control-flow.
1943  */
1944 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1945 {
1946     size_t i;
1947
1948     /* We don't use this
1949      * Note: an ast-representation using the comma-operator
1950      * of the form: (a, b, c) = x should not assign to c...
1951      */
1952     if (lvalue) {
1953         compile_error(ast_ctx(self), "not an l-value (code-block)");
1954         return false;
1955     }
1956
1957     if (self->expression.outr) {
1958         *out = self->expression.outr;
1959         return true;
1960     }
1961
1962     /* output is NULL at first, we'll have each expression
1963      * assign to out output, thus, a comma-operator represention
1964      * using an ast_block will return the last generated value,
1965      * so: (b, c) + a  executed both b and c, and returns c,
1966      * which is then added to a.
1967      */
1968     *out = NULL;
1969
1970     /* generate locals */
1971     for (i = 0; i < vec_size(self->locals); ++i)
1972     {
1973         if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1974             if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1975                 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1976             return false;
1977         }
1978     }
1979
1980     for (i = 0; i < vec_size(self->exprs); ++i)
1981     {
1982         ast_expression_codegen *gen;
1983         if (func->curblock->final && !starts_a_label(self->exprs[i])) {
1984             if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
1985                 return false;
1986             continue;
1987         }
1988         gen = self->exprs[i]->codegen;
1989         if (!(*gen)(self->exprs[i], func, false, out))
1990             return false;
1991     }
1992
1993     self->expression.outr = *out;
1994
1995     return true;
1996 }
1997
1998 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1999 {
2000     ast_expression_codegen *cgen;
2001     ir_value *left  = NULL;
2002     ir_value *right = NULL;
2003
2004     ast_value       *arr;
2005     ast_value       *idx = 0;
2006     ast_array_index *ai = NULL;
2007
2008     if (lvalue && self->expression.outl) {
2009         *out = self->expression.outl;
2010         return true;
2011     }
2012
2013     if (!lvalue && self->expression.outr) {
2014         *out = self->expression.outr;
2015         return true;
2016     }
2017
2018     if (ast_istype(self->dest, ast_array_index))
2019     {
2020
2021         ai = (ast_array_index*)self->dest;
2022         idx = (ast_value*)ai->index;
2023
2024         if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2025             ai = NULL;
2026     }
2027
2028     if (ai) {
2029         /* we need to call the setter */
2030         ir_value  *iridx, *funval;
2031         ir_instr  *call;
2032
2033         if (lvalue) {
2034             compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2035             return false;
2036         }
2037
2038         arr = (ast_value*)ai->array;
2039         if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2040             compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2041             return false;
2042         }
2043
2044         cgen = idx->expression.codegen;
2045         if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2046             return false;
2047
2048         cgen = arr->setter->expression.codegen;
2049         if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2050             return false;
2051
2052         cgen = self->source->codegen;
2053         if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2054             return false;
2055
2056         call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2057         if (!call)
2058             return false;
2059         ir_call_param(call, iridx);
2060         ir_call_param(call, right);
2061         self->expression.outr = right;
2062     }
2063     else
2064     {
2065         /* regular code */
2066
2067         cgen = self->dest->codegen;
2068         /* lvalue! */
2069         if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
2070             return false;
2071         self->expression.outl = left;
2072
2073         cgen = self->source->codegen;
2074         /* rvalue! */
2075         if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2076             return false;
2077
2078         if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2079             return false;
2080         self->expression.outr = right;
2081     }
2082
2083     /* Theoretically, an assinment returns its left side as an
2084      * lvalue, if we don't need an lvalue though, we return
2085      * the right side as an rvalue, otherwise we have to
2086      * somehow know whether or not we need to dereference the pointer
2087      * on the left side - that is: OP_LOAD if it was an address.
2088      * Also: in original QC we cannot OP_LOADP *anyway*.
2089      */
2090     *out = (lvalue ? left : right);
2091
2092     return true;
2093 }
2094
2095 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2096 {
2097     ast_expression_codegen *cgen;
2098     ir_value *left, *right;
2099
2100     /* A binary operation cannot yield an l-value */
2101     if (lvalue) {
2102         compile_error(ast_ctx(self), "not an l-value (binop)");
2103         return false;
2104     }
2105
2106     if (self->expression.outr) {
2107         *out = self->expression.outr;
2108         return true;
2109     }
2110
2111     if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2112         (self->op == INSTR_AND || self->op == INSTR_OR))
2113     {
2114         /* NOTE: The short-logic path will ignore right_first */
2115
2116         /* short circuit evaluation */
2117         ir_block *other, *merge;
2118         ir_block *from_left, *from_right;
2119         ir_instr *phi;
2120         size_t    merge_id;
2121
2122         /* prepare end-block */
2123         merge_id = vec_size(func->ir_func->blocks);
2124         merge    = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2125
2126         /* generate the left expression */
2127         cgen = self->left->codegen;
2128         if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2129             return false;
2130         /* remember the block */
2131         from_left = func->curblock;
2132
2133         /* create a new block for the right expression */
2134         other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2135         if (self->op == INSTR_AND) {
2136             /* on AND: left==true -> other */
2137             if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2138                 return false;
2139         } else {
2140             /* on OR: left==false -> other */
2141             if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2142                 return false;
2143         }
2144         /* use the likely flag */
2145         vec_last(func->curblock->instr)->likely = true;
2146
2147         /* enter the right-expression's block */
2148         func->curblock = other;
2149         /* generate */
2150         cgen = self->right->codegen;
2151         if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2152             return false;
2153         /* remember block */
2154         from_right = func->curblock;
2155
2156         /* jump to the merge block */
2157         if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2158             return false;
2159
2160         vec_remove(func->ir_func->blocks, merge_id, 1);
2161         vec_push(func->ir_func->blocks, merge);
2162
2163         func->curblock = merge;
2164         phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2165                                   ast_function_label(func, "sce_value"),
2166                                   self->expression.vtype);
2167         ir_phi_add(phi, from_left, left);
2168         ir_phi_add(phi, from_right, right);
2169         *out = ir_phi_value(phi);
2170         if (!*out)
2171             return false;
2172
2173         if (!OPTS_FLAG(PERL_LOGIC)) {
2174             /* cast-to-bool */
2175             if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2176                 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2177                                              ast_function_label(func, "sce_bool_v"),
2178                                              INSTR_NOT_V, *out);
2179                 if (!*out)
2180                     return false;
2181                 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2182                                              ast_function_label(func, "sce_bool"),
2183                                              INSTR_NOT_F, *out);
2184                 if (!*out)
2185                     return false;
2186             }
2187             else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2188                 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2189                                              ast_function_label(func, "sce_bool_s"),
2190                                              INSTR_NOT_S, *out);
2191                 if (!*out)
2192                     return false;
2193                 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2194                                              ast_function_label(func, "sce_bool"),
2195                                              INSTR_NOT_F, *out);
2196                 if (!*out)
2197                     return false;
2198             }
2199             else {
2200                 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2201                                              ast_function_label(func, "sce_bool"),
2202                                              INSTR_AND, *out, *out);
2203                 if (!*out)
2204                     return false;
2205             }
2206         }
2207
2208         self->expression.outr = *out;
2209         codegen_output_type(self, *out);
2210         return true;
2211     }
2212
2213     if (self->right_first) {
2214         cgen = self->right->codegen;
2215         if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2216             return false;
2217         cgen = self->left->codegen;
2218         if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2219             return false;
2220     } else {
2221         cgen = self->left->codegen;
2222         if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2223             return false;
2224         cgen = self->right->codegen;
2225         if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2226             return false;
2227     }
2228
2229     *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2230                                  self->op, left, right);
2231     if (!*out)
2232         return false;
2233     self->expression.outr = *out;
2234     codegen_output_type(self, *out);
2235
2236     return true;
2237 }
2238
2239 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2240 {
2241     ast_expression_codegen *cgen;
2242     ir_value *leftl = NULL, *leftr, *right, *bin;
2243
2244     ast_value       *arr;
2245     ast_value       *idx = 0;
2246     ast_array_index *ai = NULL;
2247     ir_value        *iridx = NULL;
2248
2249     if (lvalue && self->expression.outl) {
2250         *out = self->expression.outl;
2251         return true;
2252     }
2253
2254     if (!lvalue && self->expression.outr) {
2255         *out = self->expression.outr;
2256         return true;
2257     }
2258
2259     if (ast_istype(self->dest, ast_array_index))
2260     {
2261
2262         ai = (ast_array_index*)self->dest;
2263         idx = (ast_value*)ai->index;
2264
2265         if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2266             ai = NULL;
2267     }
2268
2269     /* for a binstore we need both an lvalue and an rvalue for the left side */
2270     /* rvalue of destination! */
2271     if (ai) {
2272         cgen = idx->expression.codegen;
2273         if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2274             return false;
2275     }
2276     cgen = self->dest->codegen;
2277     if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2278         return false;
2279
2280     /* source as rvalue only */
2281     cgen = self->source->codegen;
2282     if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2283         return false;
2284
2285     /* now the binary */
2286     bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2287                                 self->opbin, leftr, right);
2288     self->expression.outr = bin;
2289
2290
2291     if (ai) {
2292         /* we need to call the setter */
2293         ir_value  *funval;
2294         ir_instr  *call;
2295
2296         if (lvalue) {
2297             compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2298             return false;
2299         }
2300
2301         arr = (ast_value*)ai->array;
2302         if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2303             compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2304             return false;
2305         }
2306
2307         cgen = arr->setter->expression.codegen;
2308         if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2309             return false;
2310
2311         call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2312         if (!call)
2313             return false;
2314         ir_call_param(call, iridx);
2315         ir_call_param(call, bin);
2316         self->expression.outr = bin;
2317     } else {
2318         /* now store them */
2319         cgen = self->dest->codegen;
2320         /* lvalue of destination */
2321         if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2322             return false;
2323         self->expression.outl = leftl;
2324
2325         if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2326             return false;
2327         self->expression.outr = bin;
2328     }
2329
2330     /* Theoretically, an assinment returns its left side as an
2331      * lvalue, if we don't need an lvalue though, we return
2332      * the right side as an rvalue, otherwise we have to
2333      * somehow know whether or not we need to dereference the pointer
2334      * on the left side - that is: OP_LOAD if it was an address.
2335      * Also: in original QC we cannot OP_LOADP *anyway*.
2336      */
2337     *out = (lvalue ? leftl : bin);
2338
2339     return true;
2340 }
2341
2342 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2343 {
2344     ast_expression_codegen *cgen;
2345     ir_value *operand;
2346
2347     /* An unary operation cannot yield an l-value */
2348     if (lvalue) {
2349         compile_error(ast_ctx(self), "not an l-value (binop)");
2350         return false;
2351     }
2352
2353     if (self->expression.outr) {
2354         *out = self->expression.outr;
2355         return true;
2356     }
2357
2358     cgen = self->operand->codegen;
2359     /* lvalue! */
2360     if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2361         return false;
2362
2363     *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2364                                  self->op, operand);
2365     if (!*out)
2366         return false;
2367     self->expression.outr = *out;
2368
2369     return true;
2370 }
2371
2372 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2373 {
2374     ast_expression_codegen *cgen;
2375     ir_value *operand;
2376
2377     *out = NULL;
2378
2379     /* In the context of a return operation, we don't actually return
2380      * anything...
2381      */
2382     if (lvalue) {
2383         compile_error(ast_ctx(self), "return-expression is not an l-value");
2384         return false;
2385     }
2386
2387     if (self->expression.outr) {
2388         compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2389         return false;
2390     }
2391     self->expression.outr = (ir_value*)1;
2392
2393     if (self->operand) {
2394         cgen = self->operand->codegen;
2395         /* lvalue! */
2396         if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2397             return false;
2398
2399         if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2400             return false;
2401     } else {
2402         if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2403             return false;
2404     }
2405
2406     return true;
2407 }
2408
2409 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2410 {
2411     ast_expression_codegen *cgen;
2412     ir_value *ent, *field;
2413
2414     /* This function needs to take the 'lvalue' flag into account!
2415      * As lvalue we provide a field-pointer, as rvalue we provide the
2416      * value in a temp.
2417      */
2418
2419     if (lvalue && self->expression.outl) {
2420         *out = self->expression.outl;
2421         return true;
2422     }
2423
2424     if (!lvalue && self->expression.outr) {
2425         *out = self->expression.outr;
2426         return true;
2427     }
2428
2429     cgen = self->entity->codegen;
2430     if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2431         return false;
2432
2433     cgen = self->field->codegen;
2434     if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2435         return false;
2436
2437     if (lvalue) {
2438         /* address! */
2439         *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2440                                             ent, field);
2441     } else {
2442         *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2443                                              ent, field, self->expression.vtype);
2444         /* Done AFTER error checking:
2445         codegen_output_type(self, *out);
2446         */
2447     }
2448     if (!*out) {
2449         compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2450                  (lvalue ? "ADDRESS" : "FIELD"),
2451                  type_name[self->expression.vtype]);
2452         return false;
2453     }
2454     if (!lvalue)
2455         codegen_output_type(self, *out);
2456
2457     if (lvalue)
2458         self->expression.outl = *out;
2459     else
2460         self->expression.outr = *out;
2461
2462     /* Hm that should be it... */
2463     return true;
2464 }
2465
2466 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2467 {
2468     ast_expression_codegen *cgen;
2469     ir_value *vec;
2470
2471     /* in QC this is always an lvalue */
2472     if (lvalue && self->rvalue) {
2473         compile_error(ast_ctx(self), "not an l-value (member access)");
2474         return false;
2475     }
2476     if (self->expression.outl) {
2477         *out = self->expression.outl;
2478         return true;
2479     }
2480
2481     cgen = self->owner->codegen;
2482     if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2483         return false;
2484
2485     if (vec->vtype != TYPE_VECTOR &&
2486         !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2487     {
2488         return false;
2489     }
2490
2491     *out = ir_value_vector_member(vec, self->field);
2492     self->expression.outl = *out;
2493
2494     return (*out != NULL);
2495 }
2496
2497 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2498 {
2499     ast_value *arr;
2500     ast_value *idx;
2501
2502     if (!lvalue && self->expression.outr) {
2503         *out = self->expression.outr;
2504         return true;
2505     }
2506     if (lvalue && self->expression.outl) {
2507         *out = self->expression.outl;
2508         return true;
2509     }
2510
2511     if (!ast_istype(self->array, ast_value)) {
2512         compile_error(ast_ctx(self), "array indexing this way is not supported");
2513         /* note this would actually be pointer indexing because the left side is
2514          * not an actual array but (hopefully) an indexable expression.
2515          * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2516          * support this path will be filled.
2517          */
2518         return false;
2519     }
2520
2521     arr = (ast_value*)self->array;
2522     idx = (ast_value*)self->index;
2523
2524     if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2525         /* Time to use accessor functions */
2526         ast_expression_codegen *cgen;
2527         ir_value               *iridx, *funval;
2528         ir_instr               *call;
2529
2530         if (lvalue) {
2531             compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2532             return false;
2533         }
2534
2535         if (!arr->getter) {
2536             compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2537             return false;
2538         }
2539
2540         cgen = self->index->codegen;
2541         if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2542             return false;
2543
2544         cgen = arr->getter->expression.codegen;
2545         if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2546             return false;
2547
2548         call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2549         if (!call)
2550             return false;
2551         ir_call_param(call, iridx);
2552
2553         *out = ir_call_value(call);
2554         self->expression.outr = *out;
2555         (*out)->vtype = self->expression.vtype;
2556         codegen_output_type(self, *out);
2557         return true;
2558     }
2559
2560     if (idx->expression.vtype == TYPE_FLOAT) {
2561         unsigned int arridx = idx->constval.vfloat;
2562         if (arridx >= self->array->count)
2563         {
2564             compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2565             return false;
2566         }
2567         *out = arr->ir_values[arridx];
2568     }
2569     else if (idx->expression.vtype == TYPE_INTEGER) {
2570         unsigned int arridx = idx->constval.vint;
2571         if (arridx >= self->array->count)
2572         {
2573             compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2574             return false;
2575         }
2576         *out = arr->ir_values[arridx];
2577     }
2578     else {
2579         compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2580         return false;
2581     }
2582     (*out)->vtype = self->expression.vtype;
2583     codegen_output_type(self, *out);
2584     return true;
2585 }
2586
2587 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2588 {
2589     *out = NULL;
2590     if (lvalue) {
2591         compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2592         return false;
2593     }
2594     (void)func;
2595     (void)out;
2596     compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2597     return false;
2598 }
2599
2600 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2601 {
2602     ast_expression_codegen *cgen;
2603
2604     ir_value *condval;
2605     ir_value *dummy;
2606
2607     ir_block *cond;
2608     ir_block *ontrue;
2609     ir_block *onfalse;
2610     ir_block *ontrue_endblock = NULL;
2611     ir_block *onfalse_endblock = NULL;
2612     ir_block *merge = NULL;
2613     int       fold  = 0;
2614
2615     /* We don't output any value, thus also don't care about r/lvalue */
2616     (void)out;
2617     (void)lvalue;
2618
2619     if (self->expression.outr) {
2620         compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2621         return false;
2622     }
2623     self->expression.outr = (ir_value*)1;
2624
2625     /* generate the condition */
2626     cgen = self->cond->codegen;
2627     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2628         return false;
2629     /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2630     cond = func->curblock;
2631
2632     /* try constant folding away the condition */
2633     if ((fold = fold_cond_ifthen(condval, func, self)) != -1)
2634         return fold;
2635
2636     if (self->on_true) {
2637         /* create on-true block */
2638         ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2639         if (!ontrue)
2640             return false;
2641
2642         /* enter the block */
2643         func->curblock = ontrue;
2644
2645         /* generate */
2646         cgen = self->on_true->codegen;
2647         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2648             return false;
2649
2650         /* we now need to work from the current endpoint */
2651         ontrue_endblock = func->curblock;
2652     } else
2653         ontrue = NULL;
2654
2655     /* on-false path */
2656     if (self->on_false) {
2657         /* create on-false block */
2658         onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2659         if (!onfalse)
2660             return false;
2661
2662         /* enter the block */
2663         func->curblock = onfalse;
2664
2665         /* generate */
2666         cgen = self->on_false->codegen;
2667         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2668             return false;
2669
2670         /* we now need to work from the current endpoint */
2671         onfalse_endblock = func->curblock;
2672     } else
2673         onfalse = NULL;
2674
2675     /* Merge block were they all merge in to */
2676     if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2677     {
2678         merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2679         if (!merge)
2680             return false;
2681         /* add jumps ot the merge block */
2682         if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2683             return false;
2684         if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2685             return false;
2686
2687         /* Now enter the merge block */
2688         func->curblock = merge;
2689     }
2690
2691     /* we create the if here, that way all blocks are ordered :)
2692      */
2693     if (!ir_block_create_if(cond, ast_ctx(self), condval,
2694                             (ontrue  ? ontrue  : merge),
2695                             (onfalse ? onfalse : merge)))
2696     {
2697         return false;
2698     }
2699
2700     return true;
2701 }
2702
2703 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2704 {
2705     ast_expression_codegen *cgen;
2706
2707     ir_value *condval;
2708     ir_value *trueval, *falseval;
2709     ir_instr *phi;
2710
2711     ir_block *cond = func->curblock;
2712     ir_block *cond_out = NULL;
2713     ir_block *ontrue, *ontrue_out = NULL;
2714     ir_block *onfalse, *onfalse_out = NULL;
2715     ir_block *merge;
2716     int       fold  = 0;
2717
2718     /* Ternary can never create an lvalue... */
2719     if (lvalue)
2720         return false;
2721
2722     /* In theory it shouldn't be possible to pass through a node twice, but
2723      * in case we add any kind of optimization pass for the AST itself, it
2724      * may still happen, thus we remember a created ir_value and simply return one
2725      * if it already exists.
2726      */
2727     if (self->expression.outr) {
2728         *out = self->expression.outr;
2729         return true;
2730     }
2731
2732     /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2733
2734     /* generate the condition */
2735     func->curblock = cond;
2736     cgen = self->cond->codegen;
2737     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2738         return false;
2739     cond_out = func->curblock;
2740
2741     /* try constant folding away the condition */
2742     if ((fold = fold_cond_ternary(condval, func, self)) != -1)
2743         return fold;
2744
2745     /* create on-true block */
2746     ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2747     if (!ontrue)
2748         return false;
2749     else
2750     {
2751         /* enter the block */
2752         func->curblock = ontrue;
2753
2754         /* generate */
2755         cgen = self->on_true->codegen;
2756         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2757             return false;
2758
2759         ontrue_out = func->curblock;
2760     }
2761
2762     /* create on-false block */
2763     onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2764     if (!onfalse)
2765         return false;
2766     else
2767     {
2768         /* enter the block */
2769         func->curblock = onfalse;
2770
2771         /* generate */
2772         cgen = self->on_false->codegen;
2773         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2774             return false;
2775
2776         onfalse_out = func->curblock;
2777     }
2778
2779     /* create merge block */
2780     merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2781     if (!merge)
2782         return false;
2783     /* jump to merge block */
2784     if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2785         return false;
2786     if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2787         return false;
2788
2789     /* create if instruction */
2790     if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2791         return false;
2792
2793     /* Now enter the merge block */
2794     func->curblock = merge;
2795
2796     /* Here, now, we need a PHI node
2797      * but first some sanity checking...
2798      */
2799     if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2800         /* error("ternary with different types on the two sides"); */
2801         compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2802         return false;
2803     }
2804
2805     /* create PHI */
2806     phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2807     if (!phi) {
2808         compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2809         return false;
2810     }
2811     ir_phi_add(phi, ontrue_out,  trueval);
2812     ir_phi_add(phi, onfalse_out, falseval);
2813
2814     self->expression.outr = ir_phi_value(phi);
2815     *out = self->expression.outr;
2816
2817     codegen_output_type(self, *out);
2818
2819     return true;
2820 }
2821
2822 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2823 {
2824     ast_expression_codegen *cgen;
2825
2826     ir_value *dummy      = NULL;
2827     ir_value *precond    = NULL;
2828     ir_value *postcond   = NULL;
2829
2830     /* Since we insert some jumps "late" so we have blocks
2831      * ordered "nicely", we need to keep track of the actual end-blocks
2832      * of expressions to add the jumps to.
2833      */
2834     ir_block *bbody      = NULL, *end_bbody      = NULL;
2835     ir_block *bprecond   = NULL, *end_bprecond   = NULL;
2836     ir_block *bpostcond  = NULL, *end_bpostcond  = NULL;
2837     ir_block *bincrement = NULL, *end_bincrement = NULL;
2838     ir_block *bout       = NULL, *bin            = NULL;
2839
2840     /* let's at least move the outgoing block to the end */
2841     size_t    bout_id;
2842
2843     /* 'break' and 'continue' need to be able to find the right blocks */
2844     ir_block *bcontinue     = NULL;
2845     ir_block *bbreak        = NULL;
2846
2847     ir_block *tmpblock      = NULL;
2848
2849     (void)lvalue;
2850     (void)out;
2851
2852     if (self->expression.outr) {
2853         compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2854         return false;
2855     }
2856     self->expression.outr = (ir_value*)1;
2857
2858     /* NOTE:
2859      * Should we ever need some kind of block ordering, better make this function
2860      * move blocks around than write a block ordering algorithm later... after all
2861      * the ast and ir should work together, not against each other.
2862      */
2863
2864     /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2865      * anyway if for example it contains a ternary.
2866      */
2867     if (self->initexpr)
2868     {
2869         cgen = self->initexpr->codegen;
2870         if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2871             return false;
2872     }
2873
2874     /* Store the block from which we enter this chaos */
2875     bin = func->curblock;
2876
2877     /* The pre-loop condition needs its own block since we
2878      * need to be able to jump to the start of that expression.
2879      */
2880     if (self->precond)
2881     {
2882         bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2883         if (!bprecond)
2884             return false;
2885
2886         /* the pre-loop-condition the least important place to 'continue' at */
2887         bcontinue = bprecond;
2888
2889         /* enter */
2890         func->curblock = bprecond;
2891
2892         /* generate */
2893         cgen = self->precond->codegen;
2894         if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2895             return false;
2896
2897         end_bprecond = func->curblock;
2898     } else {
2899         bprecond = end_bprecond = NULL;
2900     }
2901
2902     /* Now the next blocks won't be ordered nicely, but we need to
2903      * generate them this early for 'break' and 'continue'.
2904      */
2905     if (self->increment) {
2906         bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2907         if (!bincrement)
2908             return false;
2909         bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2910     } else {
2911         bincrement = end_bincrement = NULL;
2912     }
2913
2914     if (self->postcond) {
2915         bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2916         if (!bpostcond)
2917             return false;
2918         bcontinue = bpostcond; /* postcond comes before the increment */
2919     } else {
2920         bpostcond = end_bpostcond = NULL;
2921     }
2922
2923     bout_id = vec_size(func->ir_func->blocks);
2924     bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2925     if (!bout)
2926         return false;
2927     bbreak = bout;
2928
2929     /* The loop body... */
2930     /* if (self->body) */
2931     {
2932         bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2933         if (!bbody)
2934             return false;
2935
2936         /* enter */
2937         func->curblock = bbody;
2938
2939         vec_push(func->breakblocks,    bbreak);
2940         if (bcontinue)
2941             vec_push(func->continueblocks, bcontinue);
2942         else
2943             vec_push(func->continueblocks, bbody);
2944
2945         /* generate */
2946         if (self->body) {
2947             cgen = self->body->codegen;
2948             if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2949                 return false;
2950         }
2951
2952         end_bbody = func->curblock;
2953         vec_pop(func->breakblocks);
2954         vec_pop(func->continueblocks);
2955     }
2956
2957     /* post-loop-condition */
2958     if (self->postcond)
2959     {
2960         /* enter */
2961         func->curblock = bpostcond;
2962
2963         /* generate */
2964         cgen = self->postcond->codegen;
2965         if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2966             return false;
2967
2968         end_bpostcond = func->curblock;
2969     }
2970
2971     /* The incrementor */
2972     if (self->increment)
2973     {
2974         /* enter */
2975         func->curblock = bincrement;
2976
2977         /* generate */
2978         cgen = self->increment->codegen;
2979         if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2980             return false;
2981
2982         end_bincrement = func->curblock;
2983     }
2984
2985     /* In any case now, we continue from the outgoing block */
2986     func->curblock = bout;
2987
2988     /* Now all blocks are in place */
2989     /* From 'bin' we jump to whatever comes first */
2990     if      (bprecond)   tmpblock = bprecond;
2991     else                 tmpblock = bbody;    /* can never be null */
2992
2993     /* DEAD CODE
2994     else if (bpostcond)  tmpblock = bpostcond;
2995     else                 tmpblock = bout;
2996     */
2997
2998     if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2999         return false;
3000
3001     /* From precond */
3002     if (bprecond)
3003     {
3004         ir_block *ontrue, *onfalse;
3005         ontrue = bbody; /* can never be null */
3006
3007         /* all of this is dead code
3008         else if (bincrement) ontrue = bincrement;
3009         else                 ontrue = bpostcond;
3010         */
3011
3012         onfalse = bout;
3013         if (self->pre_not) {
3014             tmpblock = ontrue;
3015             ontrue   = onfalse;
3016             onfalse  = tmpblock;
3017         }
3018         if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
3019             return false;
3020     }
3021
3022     /* from body */
3023     if (bbody)
3024     {
3025         if      (bincrement) tmpblock = bincrement;
3026         else if (bpostcond)  tmpblock = bpostcond;
3027         else if (bprecond)   tmpblock = bprecond;
3028         else                 tmpblock = bbody;
3029         if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
3030             return false;
3031     }
3032
3033     /* from increment */
3034     if (bincrement)
3035     {
3036         if      (bpostcond)  tmpblock = bpostcond;
3037         else if (bprecond)   tmpblock = bprecond;
3038         else if (bbody)      tmpblock = bbody;
3039         else                 tmpblock = bout;
3040         if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
3041             return false;
3042     }
3043
3044     /* from postcond */
3045     if (bpostcond)
3046     {
3047         ir_block *ontrue, *onfalse;
3048         if      (bprecond)   ontrue = bprecond;
3049         else                 ontrue = bbody; /* can never be null */
3050
3051         /* all of this is dead code
3052         else if (bincrement) ontrue = bincrement;
3053         else                 ontrue = bpostcond;
3054         */
3055
3056         onfalse = bout;
3057         if (self->post_not) {
3058             tmpblock = ontrue;
3059             ontrue   = onfalse;
3060             onfalse  = tmpblock;
3061         }
3062         if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
3063             return false;
3064     }
3065
3066     /* Move 'bout' to the end */
3067     vec_remove(func->ir_func->blocks, bout_id, 1);
3068     vec_push(func->ir_func->blocks, bout);
3069
3070     return true;
3071 }
3072
3073 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
3074 {
3075     ir_block *target;
3076
3077     *out = NULL;
3078
3079     if (lvalue) {
3080         compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3081         return false;
3082     }
3083
3084     if (self->expression.outr) {
3085         compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3086         return false;
3087     }
3088     self->expression.outr = (ir_value*)1;
3089
3090     if (self->is_continue)
3091         target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
3092     else
3093         target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
3094
3095     if (!target) {
3096         compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3097         return false;
3098     }
3099
3100     if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3101         return false;
3102     return true;
3103 }
3104
3105 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3106 {
3107     ast_expression_codegen *cgen;
3108
3109     ast_switch_case *def_case     = NULL;
3110     ir_block        *def_bfall    = NULL;
3111     ir_block        *def_bfall_to = NULL;
3112     bool set_def_bfall_to = false;
3113
3114     ir_value *dummy     = NULL;
3115     ir_value *irop      = NULL;
3116     ir_block *bout      = NULL;
3117     ir_block *bfall     = NULL;
3118     size_t    bout_id;
3119     size_t    c;
3120
3121     char      typestr[1024];
3122     uint16_t  cmpinstr;
3123
3124     if (lvalue) {
3125         compile_error(ast_ctx(self), "switch expression is not an l-value");
3126         return false;
3127     }
3128
3129     if (self->expression.outr) {
3130         compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3131         return false;
3132     }
3133     self->expression.outr = (ir_value*)1;
3134
3135     (void)lvalue;
3136     (void)out;
3137
3138     cgen = self->operand->codegen;
3139     if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3140         return false;
3141
3142     if (!vec_size(self->cases))
3143         return true;
3144
3145     cmpinstr = type_eq_instr[irop->vtype];
3146     if (cmpinstr >= VINSTR_END) {
3147         ast_type_to_string(self->operand, typestr, sizeof(typestr));
3148         compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3149         return false;
3150     }
3151
3152     bout_id = vec_size(func->ir_func->blocks);
3153     bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3154     if (!bout)
3155         return false;
3156
3157     /* setup the break block */
3158     vec_push(func->breakblocks, bout);
3159
3160     /* Now create all cases */
3161     for (c = 0; c < vec_size(self->cases); ++c) {
3162         ir_value *cond, *val;
3163         ir_block *bcase, *bnot;
3164         size_t bnot_id;
3165
3166         ast_switch_case *swcase = &self->cases[c];
3167
3168         if (swcase->value) {
3169             /* A regular case */
3170             /* generate the condition operand */
3171             cgen = swcase->value->codegen;
3172             if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3173                 return false;
3174             /* generate the condition */
3175             cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3176             if (!cond)
3177                 return false;
3178
3179             bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3180             bnot_id = vec_size(func->ir_func->blocks);
3181             bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3182             if (!bcase || !bnot)
3183                 return false;
3184             if (set_def_bfall_to) {
3185                 set_def_bfall_to = false;
3186                 def_bfall_to = bcase;
3187             }
3188             if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3189                 return false;
3190
3191             /* Make the previous case-end fall through */
3192             if (bfall && !bfall->final) {
3193                 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3194                     return false;
3195             }
3196
3197             /* enter the case */
3198             func->curblock = bcase;
3199             cgen = swcase->code->codegen;
3200             if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3201                 return false;
3202
3203             /* remember this block to fall through from */
3204             bfall = func->curblock;
3205
3206             /* enter the else and move it down */
3207             func->curblock = bnot;
3208             vec_remove(func->ir_func->blocks, bnot_id, 1);
3209             vec_push(func->ir_func->blocks, bnot);
3210         } else {
3211             /* The default case */
3212             /* Remember where to fall through from: */
3213             def_bfall = bfall;
3214             bfall     = NULL;
3215             /* remember which case it was */
3216             def_case  = swcase;
3217             /* And the next case will be remembered */
3218             set_def_bfall_to = true;
3219         }
3220     }
3221
3222     /* Jump from the last bnot to bout */
3223     if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3224         /*
3225         astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3226         */
3227         return false;
3228     }
3229
3230     /* If there was a default case, put it down here */
3231     if (def_case) {
3232         ir_block *bcase;
3233
3234         /* No need to create an extra block */
3235         bcase = func->curblock;
3236
3237         /* Insert the fallthrough jump */
3238         if (def_bfall && !def_bfall->final) {
3239             if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3240                 return false;
3241         }
3242
3243         /* Now generate the default code */
3244         cgen = def_case->code->codegen;
3245         if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3246             return false;
3247
3248         /* see if we need to fall through */
3249         if (def_bfall_to && !func->curblock->final)
3250         {
3251             if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3252                 return false;
3253         }
3254     }
3255
3256     /* Jump from the last bnot to bout */
3257     if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3258         return false;
3259     /* enter the outgoing block */
3260     func->curblock = bout;
3261
3262     /* restore the break block */
3263     vec_pop(func->breakblocks);
3264
3265     /* Move 'bout' to the end, it's nicer */
3266     vec_remove(func->ir_func->blocks, bout_id, 1);
3267     vec_push(func->ir_func->blocks, bout);
3268
3269     return true;
3270 }
3271
3272 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3273 {
3274     size_t i;
3275     ir_value *dummy;
3276
3277     if (self->undefined) {
3278         compile_error(ast_ctx(self), "internal error: ast_label never defined");
3279         return false;
3280     }
3281
3282     *out = NULL;
3283     if (lvalue) {
3284         compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3285         return false;
3286     }
3287
3288     /* simply create a new block and jump to it */
3289     self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3290     if (!self->irblock) {
3291         compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3292         return false;
3293     }
3294     if (!func->curblock->final) {
3295         if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3296             return false;
3297     }
3298
3299     /* enter the new block */
3300     func->curblock = self->irblock;
3301
3302     /* Generate all the leftover gotos */
3303     for (i = 0; i < vec_size(self->gotos); ++i) {
3304         if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3305             return false;
3306     }
3307
3308     return true;
3309 }
3310
3311 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3312 {
3313     *out = NULL;
3314     if (lvalue) {
3315         compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3316         return false;
3317     }
3318
3319     if (self->target->irblock) {
3320         if (self->irblock_from) {
3321             /* we already tried once, this is the callback */
3322             self->irblock_from->final = false;
3323             if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3324                 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3325                 return false;
3326             }
3327         }
3328         else
3329         {
3330             if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3331                 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3332                 return false;
3333             }
3334         }
3335     }
3336     else
3337     {
3338         /* the target has not yet been created...
3339          * close this block in a sneaky way:
3340          */
3341         func->curblock->final = true;
3342         self->irblock_from = func->curblock;
3343         ast_label_register_goto(self->target, self);
3344     }
3345
3346     return true;
3347 }
3348
3349 #include <stdio.h>
3350 bool ast_state_codegen(ast_state *self, ast_function *func, bool lvalue, ir_value **out)
3351 {
3352     ast_expression_codegen *cgen;
3353
3354     ir_value *frameval, *thinkval;
3355
3356     if (lvalue) {
3357         compile_error(ast_ctx(self), "not an l-value (state operation)");
3358         return false;
3359     }
3360     if (self->expression.outr) {
3361         compile_error(ast_ctx(self), "internal error: ast_state cannot be reused!");
3362         return false;
3363     }
3364     *out = NULL;
3365
3366     cgen = self->framenum->codegen;
3367     if (!(*cgen)((ast_expression*)(self->framenum), func, false, &frameval))
3368         return false;
3369     if (!frameval)
3370         return false;
3371
3372     cgen = self->nextthink->codegen;
3373     if (!(*cgen)((ast_expression*)(self->nextthink), func, false, &thinkval))
3374         return false;
3375     if (!frameval)
3376         return false;
3377
3378     if (!ir_block_create_state_op(func->curblock, ast_ctx(self), frameval, thinkval)) {
3379         compile_error(ast_ctx(self), "failed to create STATE instruction");
3380         return false;
3381     }
3382
3383     self->expression.outr = (ir_value*)1;
3384     return true;
3385 }
3386
3387 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3388 {
3389     ast_expression_codegen *cgen;
3390     ir_value              **params;
3391     ir_instr               *callinstr;
3392     size_t i;
3393
3394     ir_value *funval = NULL;
3395
3396     /* return values are never lvalues */
3397     if (lvalue) {
3398         compile_error(ast_ctx(self), "not an l-value (function call)");
3399         return false;
3400     }
3401
3402     if (self->expression.outr) {
3403         *out = self->expression.outr;
3404         return true;
3405     }
3406
3407     cgen = self->func->codegen;
3408     if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3409         return false;
3410     if (!funval)
3411         return false;
3412
3413     params = NULL;
3414
3415     /* parameters */
3416     for (i = 0; i < vec_size(self->params); ++i)
3417     {
3418         ir_value *param;
3419         ast_expression *expr = self->params[i];
3420
3421         cgen = expr->codegen;
3422         if (!(*cgen)(expr, func, false, &param))
3423             goto error;
3424         if (!param)
3425             goto error;
3426         vec_push(params, param);
3427     }
3428
3429     /* varargs counter */
3430     if (self->va_count) {
3431         ir_value   *va_count;
3432         ir_builder *builder = func->curblock->owner->owner;
3433         cgen = self->va_count->codegen;
3434         if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3435             return false;
3436         if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3437                                       ir_builder_get_va_count(builder), va_count))
3438         {
3439             return false;
3440         }
3441     }
3442
3443     callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3444                                      ast_function_label(func, "call"),
3445                                      funval, !!(self->func->flags & AST_FLAG_NORETURN));
3446     if (!callinstr)
3447         goto error;
3448
3449     for (i = 0; i < vec_size(params); ++i) {
3450         ir_call_param(callinstr, params[i]);
3451     }
3452
3453     *out = ir_call_value(callinstr);
3454     self->expression.outr = *out;
3455
3456     codegen_output_type(self, *out);
3457
3458     vec_free(params);
3459     return true;
3460 error:
3461     vec_free(params);
3462     return false;
3463 }