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