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