]> de.git.xonotic.org Git - xonotic/gmqcc.git/blob - ast.c
Get rid of some code duplication
[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 /*
859     self->expression.vtype = funcexpr->expression.next->expression.vtype;
860     if (funcexpr->expression.next->expression.next)
861         self->expression.next = ast_type_copy(ctx, funcexpr->expression.next->expression.next);
862 */
863     ast_type_adopt(self, funcexpr->expression.next);
864
865     return self;
866 }
867
868 void ast_call_delete(ast_call *self)
869 {
870     size_t i;
871     for (i = 0; i < vec_size(self->params); ++i)
872         ast_unref(self->params[i]);
873     vec_free(self->params);
874
875     if (self->func)
876         ast_unref(self->func);
877
878     ast_expression_delete((ast_expression*)self);
879     mem_d(self);
880 }
881
882 bool ast_call_check_types(ast_call *self)
883 {
884     size_t i;
885     bool   retval = true;
886     const  ast_expression *func = self->func;
887     size_t count = vec_size(self->params);
888     if (count > vec_size(func->expression.params))
889         count = vec_size(func->expression.params);
890
891     for (i = 0; i < count; ++i) {
892         if (!ast_compare_type(self->params[i], (ast_expression*)(func->expression.params[i]))) {
893             char texp[1024];
894             char tgot[1024];
895             ast_type_to_string(self->params[i], tgot, sizeof(tgot));
896             ast_type_to_string((ast_expression*)func->expression.params[i], texp, sizeof(texp));
897             compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
898                      (unsigned int)(i+1), texp, tgot);
899             /* we don't immediately return */
900             retval = false;
901         }
902     }
903     return retval;
904 }
905
906 ast_store* ast_store_new(lex_ctx ctx, int op,
907                          ast_expression *dest, ast_expression *source)
908 {
909     ast_instantiate(ast_store, ctx, ast_store_delete);
910     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
911
912     ast_side_effects(self) = true;
913
914     self->op = op;
915     self->dest = dest;
916     self->source = source;
917
918     self->expression.vtype = dest->expression.vtype;
919     if (dest->expression.next) {
920         self->expression.next = ast_type_copy(ctx, dest);
921         if (!self->expression.next) {
922             ast_delete(self);
923             return NULL;
924         }
925     }
926     else
927         self->expression.next = NULL;
928
929     return self;
930 }
931
932 void ast_store_delete(ast_store *self)
933 {
934     ast_unref(self->dest);
935     ast_unref(self->source);
936     ast_expression_delete((ast_expression*)self);
937     mem_d(self);
938 }
939
940 ast_block* ast_block_new(lex_ctx ctx)
941 {
942     ast_instantiate(ast_block, ctx, ast_block_delete);
943     ast_expression_init((ast_expression*)self,
944                         (ast_expression_codegen*)&ast_block_codegen);
945
946     self->locals  = NULL;
947     self->exprs   = NULL;
948     self->collect = NULL;
949
950     return self;
951 }
952
953 void ast_block_add_expr(ast_block *self, ast_expression *e)
954 {
955     ast_propagate_effects(self, e);
956     vec_push(self->exprs, e);
957 }
958
959 void ast_block_collect(ast_block *self, ast_expression *expr)
960 {
961     vec_push(self->collect, expr);
962     expr->expression.node.keep = true;
963 }
964
965 void ast_block_delete(ast_block *self)
966 {
967     size_t i;
968     for (i = 0; i < vec_size(self->exprs); ++i)
969         ast_unref(self->exprs[i]);
970     vec_free(self->exprs);
971     for (i = 0; i < vec_size(self->locals); ++i)
972         ast_delete(self->locals[i]);
973     vec_free(self->locals);
974     for (i = 0; i < vec_size(self->collect); ++i)
975         ast_delete(self->collect[i]);
976     vec_free(self->collect);
977     ast_expression_delete((ast_expression*)self);
978     mem_d(self);
979 }
980
981 bool ast_block_set_type(ast_block *self, ast_expression *from)
982 {
983     if (self->expression.next)
984         ast_delete(self->expression.next);
985     self->expression.vtype = from->expression.vtype;
986     if (from->expression.next) {
987         self->expression.next = ast_type_copy(self->expression.node.context, from->expression.next);
988         if (!self->expression.next)
989             return false;
990     }
991     else
992         self->expression.next = NULL;
993     return true;
994 }
995
996 ast_function* ast_function_new(lex_ctx ctx, const char *name, ast_value *vtype)
997 {
998     ast_instantiate(ast_function, ctx, ast_function_delete);
999
1000     if (!vtype ||
1001         vtype->hasvalue ||
1002         vtype->expression.vtype != TYPE_FUNCTION)
1003     {
1004         compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1005                  (int)!vtype,
1006                  (int)vtype->hasvalue,
1007                  vtype->expression.vtype);
1008         mem_d(self);
1009         return NULL;
1010     }
1011
1012     self->vtype  = vtype;
1013     self->name   = name ? util_strdup(name) : NULL;
1014     self->blocks = NULL;
1015
1016     self->labelcount = 0;
1017     self->builtin = 0;
1018
1019     self->ir_func = NULL;
1020     self->curblock = NULL;
1021
1022     self->breakblock    = NULL;
1023     self->continueblock = NULL;
1024
1025     vtype->hasvalue = true;
1026     vtype->constval.vfunc = self;
1027
1028     return self;
1029 }
1030
1031 void ast_function_delete(ast_function *self)
1032 {
1033     size_t i;
1034     if (self->name)
1035         mem_d((void*)self->name);
1036     if (self->vtype) {
1037         /* ast_value_delete(self->vtype); */
1038         self->vtype->hasvalue = false;
1039         self->vtype->constval.vfunc = NULL;
1040         /* We use unref - if it was stored in a global table it is supposed
1041          * to be deleted from *there*
1042          */
1043         ast_unref(self->vtype);
1044     }
1045     for (i = 0; i < vec_size(self->blocks); ++i)
1046         ast_delete(self->blocks[i]);
1047     vec_free(self->blocks);
1048     mem_d(self);
1049 }
1050
1051 const char* ast_function_label(ast_function *self, const char *prefix)
1052 {
1053     size_t id;
1054     size_t len;
1055     char  *from;
1056
1057     if (!opts_dump && !opts_dumpfin)
1058         return NULL;
1059
1060     id  = (self->labelcount++);
1061     len = strlen(prefix);
1062
1063     from = self->labelbuf + sizeof(self->labelbuf)-1;
1064     *from-- = 0;
1065     do {
1066         unsigned int digit = id % 10;
1067         *from = digit + '0';
1068         id /= 10;
1069     } while (id);
1070     memcpy(from - len, prefix, len);
1071     return from - len;
1072 }
1073
1074 /*********************************************************************/
1075 /* AST codegen part
1076  * by convention you must never pass NULL to the 'ir_value **out'
1077  * parameter. If you really don't care about the output, pass a dummy.
1078  * But I can't imagine a pituation where the output is truly unnecessary.
1079  */
1080
1081 void _ast_codegen_output_type(ast_expression_common *self, ir_value *out)
1082 {
1083     if (out->vtype == TYPE_FIELD)
1084         out->fieldtype = self->next->expression.vtype;
1085     if (out->vtype == TYPE_FUNCTION)
1086         out->outtype = self->next->expression.vtype;
1087 }
1088
1089 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1090 #define codegen_output_type_expr(a,o) (_ast_codegen_output_type(a,(o)))
1091
1092 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1093 {
1094     (void)func;
1095     (void)lvalue;
1096     /* NOTE: This is the codegen for a variable used in an expression.
1097      * It is not the codegen to generate the value. For this purpose,
1098      * ast_local_codegen and ast_global_codegen are to be used before this
1099      * is executed. ast_function_codegen should take care of its locals,
1100      * and the ast-user should take care of ast_global_codegen to be used
1101      * on all the globals.
1102      */
1103     if (!self->ir_v) {
1104         char typename[1024];
1105         ast_type_to_string((ast_expression*)self, typename, sizeof(typename));
1106         compile_error(ast_ctx(self), "ast_value used before generated %s %s", typename, self->name);
1107         return false;
1108     }
1109     *out = self->ir_v;
1110     return true;
1111 }
1112
1113 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1114 {
1115     ir_value *v = NULL;
1116
1117     if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1118     {
1119         ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->expression.vtype);
1120         if (!func)
1121             return false;
1122         func->context = ast_ctx(self);
1123         func->value->context = ast_ctx(self);
1124
1125         self->constval.vfunc->ir_func = func;
1126         self->ir_v = func->value;
1127         /* The function is filled later on ast_function_codegen... */
1128         return true;
1129     }
1130
1131     if (isfield && self->expression.vtype == TYPE_FIELD) {
1132         ast_expression *fieldtype = self->expression.next;
1133
1134         if (self->hasvalue) {
1135             compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1136             goto error;
1137         }
1138
1139         if (fieldtype->expression.vtype == TYPE_ARRAY) {
1140             size_t ai;
1141             char   *name;
1142             size_t  namelen;
1143
1144             ast_expression_common *elemtype;
1145             int                    vtype;
1146             ast_value             *array = (ast_value*)fieldtype;
1147
1148             if (!ast_istype(fieldtype, ast_value)) {
1149                 compile_error(ast_ctx(self), "internal error: ast_value required");
1150                 return false;
1151             }
1152
1153             /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1154             if (!array->expression.count || array->expression.count > opts_max_array_size)
1155                 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1156
1157             elemtype = &array->expression.next->expression;
1158             vtype = elemtype->vtype;
1159
1160             v = ir_builder_create_field(ir, self->name, vtype);
1161             if (!v) {
1162                 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1163                 return false;
1164             }
1165             v->context = ast_ctx(self);
1166             array->ir_v = self->ir_v = v;
1167
1168             namelen = strlen(self->name);
1169             name    = (char*)mem_a(namelen + 16);
1170             strcpy(name, self->name);
1171
1172             array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1173             array->ir_values[0] = v;
1174             for (ai = 1; ai < array->expression.count; ++ai) {
1175                 snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1176                 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1177                 if (!array->ir_values[ai]) {
1178                     mem_d(name);
1179                     compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1180                     return false;
1181                 }
1182                 array->ir_values[ai]->context = ast_ctx(self);
1183             }
1184             mem_d(name);
1185         }
1186         else
1187         {
1188             v = ir_builder_create_field(ir, self->name, self->expression.next->expression.vtype);
1189             if (!v)
1190                 return false;
1191             v->context = ast_ctx(self);
1192             self->ir_v = v;
1193         }
1194         return true;
1195     }
1196
1197     if (self->expression.vtype == TYPE_ARRAY) {
1198         size_t ai;
1199         char   *name;
1200         size_t  namelen;
1201
1202         ast_expression_common *elemtype = &self->expression.next->expression;
1203         int vtype = elemtype->vtype;
1204
1205         /* same as with field arrays */
1206         if (!self->expression.count || self->expression.count > opts_max_array_size)
1207             compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)self->expression.count);
1208
1209         v = ir_builder_create_global(ir, self->name, vtype);
1210         if (!v) {
1211             compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1212             return false;
1213         }
1214         v->context = ast_ctx(self);
1215
1216         namelen = strlen(self->name);
1217         name    = (char*)mem_a(namelen + 16);
1218         strcpy(name, self->name);
1219
1220         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1221         self->ir_values[0] = v;
1222         for (ai = 1; ai < self->expression.count; ++ai) {
1223             snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1224             self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1225             if (!self->ir_values[ai]) {
1226                 mem_d(name);
1227                 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1228                 return false;
1229             }
1230             self->ir_values[ai]->context = ast_ctx(self);
1231         }
1232         mem_d(name);
1233     }
1234     else
1235     {
1236         /* Arrays don't do this since there's no "array" value which spans across the
1237          * whole thing.
1238          */
1239         v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1240         if (!v) {
1241             compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1242             return false;
1243         }
1244         codegen_output_type(self, v);
1245         v->context = ast_ctx(self);
1246     }
1247
1248     if (self->hasvalue) {
1249         switch (self->expression.vtype)
1250         {
1251             case TYPE_FLOAT:
1252                 if (!ir_value_set_float(v, self->constval.vfloat))
1253                     goto error;
1254                 break;
1255             case TYPE_VECTOR:
1256                 if (!ir_value_set_vector(v, self->constval.vvec))
1257                     goto error;
1258                 break;
1259             case TYPE_STRING:
1260                 if (!ir_value_set_string(v, self->constval.vstring))
1261                     goto error;
1262                 break;
1263             case TYPE_ARRAY:
1264                 compile_error(ast_ctx(self), "TODO: global constant array");
1265                 break;
1266             case TYPE_FUNCTION:
1267                 compile_error(ast_ctx(self), "global of type function not properly generated");
1268                 goto error;
1269                 /* Cannot generate an IR value for a function,
1270                  * need a pointer pointing to a function rather.
1271                  */
1272             case TYPE_FIELD:
1273                 if (!self->constval.vfield) {
1274                     compile_error(ast_ctx(self), "field constant without vfield set");
1275                     goto error;
1276                 }
1277                 if (!self->constval.vfield->ir_v) {
1278                     compile_error(ast_ctx(self), "field constant generated before its field");
1279                     goto error;
1280                 }
1281                 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1282                     goto error;
1283                 break;
1284             default:
1285                 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1286                 break;
1287         }
1288     }
1289
1290     /* link us to the ir_value */
1291     v->cvq = self->cvq;
1292     self->ir_v = v;
1293     return true;
1294
1295 error: /* clean up */
1296     ir_value_delete(v);
1297     return false;
1298 }
1299
1300 bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1301 {
1302     ir_value *v = NULL;
1303     if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1304     {
1305         /* Do we allow local functions? I think not...
1306          * this is NOT a function pointer atm.
1307          */
1308         return false;
1309     }
1310
1311     if (self->expression.vtype == TYPE_ARRAY) {
1312         size_t ai;
1313         char   *name;
1314         size_t  namelen;
1315
1316         ast_expression_common *elemtype = &self->expression.next->expression;
1317         int vtype = elemtype->vtype;
1318
1319         if (param) {
1320             compile_error(ast_ctx(self), "array-parameters are not supported");
1321             return false;
1322         }
1323
1324         /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1325         if (!self->expression.count || self->expression.count > opts_max_array_size) {
1326             compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)self->expression.count);
1327         }
1328
1329         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1330         if (!self->ir_values) {
1331             compile_error(ast_ctx(self), "failed to allocate array values");
1332             return false;
1333         }
1334
1335         v = ir_function_create_local(func, self->name, vtype, param);
1336         if (!v) {
1337             compile_error(ast_ctx(self), "ir_function_create_local failed");
1338             return false;
1339         }
1340         v->context = ast_ctx(self);
1341
1342         namelen = strlen(self->name);
1343         name    = (char*)mem_a(namelen + 16);
1344         strcpy(name, self->name);
1345
1346         self->ir_values[0] = v;
1347         for (ai = 1; ai < self->expression.count; ++ai) {
1348             snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1349             self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1350             if (!self->ir_values[ai]) {
1351                 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1352                 return false;
1353             }
1354             self->ir_values[ai]->context = ast_ctx(self);
1355         }
1356     }
1357     else
1358     {
1359         v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1360         if (!v)
1361             return false;
1362         codegen_output_type(self, v);
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 (!ast_generate_accessors(self, func->owner))
1395         return false;
1396     return true;
1397
1398 error: /* clean up */
1399     ir_value_delete(v);
1400     return false;
1401 }
1402
1403 bool ast_generate_accessors(ast_value *asvalue, ir_builder *ir)
1404 {
1405     if (asvalue->setter) {
1406         if (!ast_global_codegen  (asvalue->setter, ir, false) ||
1407             !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
1408             !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
1409         {
1410             compile_error(ast_ctx(asvalue), "internal error: failed to generate setter for `%s`", asvalue->name);
1411             return false;
1412         }
1413     }
1414     if (asvalue->getter) {
1415         if (!ast_global_codegen  (asvalue->getter, ir, false) ||
1416             !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
1417             !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
1418         {
1419             compile_error(ast_ctx(asvalue), "internal error: failed to generate getter for `%s`", asvalue->name);
1420             return false;
1421         }
1422     }
1423     return true;
1424 }
1425
1426 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1427 {
1428     ir_function *irf;
1429     ir_value    *dummy;
1430     ast_expression_common *ec;
1431     size_t    i;
1432
1433     (void)ir;
1434
1435     irf = self->ir_func;
1436     if (!irf) {
1437         compile_error(ast_ctx(self), "ast_function's related ast_value was not generated yet");
1438         return false;
1439     }
1440
1441     /* fill the parameter list */
1442     ec = &self->vtype->expression;
1443     for (i = 0; i < vec_size(ec->params); ++i)
1444     {
1445         if (ec->params[i]->expression.vtype == TYPE_FIELD)
1446             vec_push(irf->params, ec->params[i]->expression.next->expression.vtype);
1447         else
1448             vec_push(irf->params, ec->params[i]->expression.vtype);
1449         if (!self->builtin) {
1450             if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1451                 return false;
1452         }
1453     }
1454
1455     if (self->builtin) {
1456         irf->builtin = self->builtin;
1457         return true;
1458     }
1459
1460     if (!vec_size(self->blocks)) {
1461         compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1462         return false;
1463     }
1464
1465     self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1466     if (!self->curblock) {
1467         compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1468         return false;
1469     }
1470
1471     for (i = 0; i < vec_size(self->blocks); ++i) {
1472         ast_expression_codegen *gen = self->blocks[i]->expression.codegen;
1473         if (!(*gen)((ast_expression*)self->blocks[i], self, false, &dummy))
1474             return false;
1475     }
1476
1477     /* TODO: check return types */
1478     if (!self->curblock->is_return)
1479     {
1480         if (!self->vtype->expression.next ||
1481             self->vtype->expression.next->expression.vtype == TYPE_VOID)
1482         {
1483             return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1484         }
1485         else if (vec_size(self->curblock->entries))
1486         {
1487             /* error("missing return"); */
1488             if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1489                                 "control reaches end of non-void function (`%s`) via %s",
1490                                 self->name, self->curblock->label))
1491             {
1492                 return false;
1493             }
1494             return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1495         }
1496     }
1497     return true;
1498 }
1499
1500 /* Note, you will not see ast_block_codegen generate ir_blocks.
1501  * To the AST and the IR, blocks are 2 different things.
1502  * In the AST it represents a block of code, usually enclosed in
1503  * curly braces {...}.
1504  * While in the IR it represents a block in terms of control-flow.
1505  */
1506 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1507 {
1508     size_t i;
1509
1510     /* We don't use this
1511      * Note: an ast-representation using the comma-operator
1512      * of the form: (a, b, c) = x should not assign to c...
1513      */
1514     if (lvalue) {
1515         compile_error(ast_ctx(self), "not an l-value (code-block)");
1516         return false;
1517     }
1518
1519     if (self->expression.outr) {
1520         *out = self->expression.outr;
1521         return true;
1522     }
1523
1524     /* output is NULL at first, we'll have each expression
1525      * assign to out output, thus, a comma-operator represention
1526      * using an ast_block will return the last generated value,
1527      * so: (b, c) + a  executed both b and c, and returns c,
1528      * which is then added to a.
1529      */
1530     *out = NULL;
1531
1532     /* generate locals */
1533     for (i = 0; i < vec_size(self->locals); ++i)
1534     {
1535         if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1536             if (opts_debug)
1537                 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1538             return false;
1539         }
1540     }
1541
1542     for (i = 0; i < vec_size(self->exprs); ++i)
1543     {
1544         ast_expression_codegen *gen = self->exprs[i]->expression.codegen;
1545         if (func->curblock->final && !ast_istype(self->exprs[i], ast_label)) {
1546             compile_error(ast_ctx(self->exprs[i]), "unreachable statement");
1547             return false;
1548         }
1549         if (!(*gen)(self->exprs[i], func, false, out))
1550             return false;
1551     }
1552
1553     self->expression.outr = *out;
1554
1555     return true;
1556 }
1557
1558 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1559 {
1560     ast_expression_codegen *cgen;
1561     ir_value *left  = NULL;
1562     ir_value *right = NULL;
1563
1564     ast_value       *arr;
1565     ast_value       *idx = 0;
1566     ast_array_index *ai = NULL;
1567
1568     if (lvalue && self->expression.outl) {
1569         *out = self->expression.outl;
1570         return true;
1571     }
1572
1573     if (!lvalue && self->expression.outr) {
1574         *out = self->expression.outr;
1575         return true;
1576     }
1577
1578     if (ast_istype(self->dest, ast_array_index))
1579     {
1580
1581         ai = (ast_array_index*)self->dest;
1582         idx = (ast_value*)ai->index;
1583
1584         if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
1585             ai = NULL;
1586     }
1587
1588     if (ai) {
1589         /* we need to call the setter */
1590         ir_value  *iridx, *funval;
1591         ir_instr  *call;
1592
1593         if (lvalue) {
1594             compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1595             return false;
1596         }
1597
1598         arr = (ast_value*)ai->array;
1599         if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1600             compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
1601             return false;
1602         }
1603
1604         cgen = idx->expression.codegen;
1605         if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1606             return false;
1607
1608         cgen = arr->setter->expression.codegen;
1609         if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
1610             return false;
1611
1612         cgen = self->source->expression.codegen;
1613         if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1614             return false;
1615
1616         call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval);
1617         if (!call)
1618             return false;
1619         ir_call_param(call, iridx);
1620         ir_call_param(call, right);
1621         self->expression.outr = right;
1622     }
1623     else
1624     {
1625         /* regular code */
1626
1627         cgen = self->dest->expression.codegen;
1628         /* lvalue! */
1629         if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
1630             return false;
1631         self->expression.outl = left;
1632
1633         cgen = self->source->expression.codegen;
1634         /* rvalue! */
1635         if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1636             return false;
1637
1638         if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
1639             return false;
1640         self->expression.outr = right;
1641     }
1642
1643     /* Theoretically, an assinment returns its left side as an
1644      * lvalue, if we don't need an lvalue though, we return
1645      * the right side as an rvalue, otherwise we have to
1646      * somehow know whether or not we need to dereference the pointer
1647      * on the left side - that is: OP_LOAD if it was an address.
1648      * Also: in original QC we cannot OP_LOADP *anyway*.
1649      */
1650     *out = (lvalue ? left : right);
1651
1652     return true;
1653 }
1654
1655 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
1656 {
1657     ast_expression_codegen *cgen;
1658     ir_value *left, *right;
1659
1660     /* A binary operation cannot yield an l-value */
1661     if (lvalue) {
1662         compile_error(ast_ctx(self), "not an l-value (binop)");
1663         return false;
1664     }
1665
1666     if (self->expression.outr) {
1667         *out = self->expression.outr;
1668         return true;
1669     }
1670
1671     if (OPTS_FLAG(SHORT_LOGIC) &&
1672         (self->op == INSTR_AND || self->op == INSTR_OR))
1673     {
1674         /* short circuit evaluation */
1675         ir_block *other, *merge;
1676         ir_block *from_left, *from_right;
1677         ir_instr *phi;
1678         size_t    merge_id;
1679         uint16_t  notop;
1680
1681         /* Note about casting to true boolean values:
1682          * We use a single NOT for sub expressions, and an
1683          * overall NOT at the end, and for that purpose swap
1684          * all the jump conditions in order for the NOT to get
1685          * doubled.
1686          * ie: (a && b) usually becomes (!!a ? !!b : !!a)
1687          * but we translate this to (!(!a ? !a : !b))
1688          */
1689
1690         merge_id = vec_size(func->ir_func->blocks);
1691         merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
1692
1693         cgen = self->left->expression.codegen;
1694         if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
1695             return false;
1696         if (!OPTS_FLAG(PERL_LOGIC)) {
1697             notop = type_not_instr[left->vtype];
1698             if (notop == AINSTR_END) {
1699                 compile_error(ast_ctx(self), "don't know how to cast to bool...");
1700                 return false;
1701             }
1702             left = ir_block_create_unary(func->curblock, ast_ctx(self),
1703                                          ast_function_label(func, "sce_not"),
1704                                          notop,
1705                                          left);
1706         }
1707         from_left = func->curblock;
1708
1709         other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
1710         if ( !(self->op == INSTR_OR) != !OPTS_FLAG(PERL_LOGIC) ) {
1711             if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
1712                 return false;
1713         } else {
1714             if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
1715                 return false;
1716         }
1717         /* use the likely flag */
1718         vec_last(func->curblock->instr)->likely = true;
1719
1720         func->curblock = other;
1721         cgen = self->right->expression.codegen;
1722         if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
1723             return false;
1724         if (!OPTS_FLAG(PERL_LOGIC)) {
1725             notop = type_not_instr[right->vtype];
1726             if (notop == AINSTR_END) {
1727                 compile_error(ast_ctx(self), "don't know how to cast to bool...");
1728                 return false;
1729             }
1730             right = ir_block_create_unary(func->curblock, ast_ctx(self),
1731                                           ast_function_label(func, "sce_not"),
1732                                           notop,
1733                                           right);
1734         }
1735         from_right = func->curblock;
1736
1737         if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
1738             return false;
1739
1740         vec_remove(func->ir_func->blocks, merge_id, 1);
1741         vec_push(func->ir_func->blocks, merge);
1742
1743         func->curblock = merge;
1744         phi = ir_block_create_phi(func->curblock, ast_ctx(self), ast_function_label(func, "sce_value"), TYPE_FLOAT);
1745         ir_phi_add(phi, from_left, left);
1746         ir_phi_add(phi, from_right, right);
1747         *out = ir_phi_value(phi);
1748         if (!OPTS_FLAG(PERL_LOGIC)) {
1749             notop = type_not_instr[(*out)->vtype];
1750             if (notop == AINSTR_END) {
1751                 compile_error(ast_ctx(self), "don't know how to cast to bool...");
1752                 return false;
1753             }
1754             *out = ir_block_create_unary(func->curblock, ast_ctx(self),
1755                                          ast_function_label(func, "sce_final_not"),
1756                                          notop,
1757                                          *out);
1758         }
1759         if (!*out)
1760             return false;
1761         self->expression.outr = *out;
1762         return true;
1763     }
1764
1765     cgen = self->left->expression.codegen;
1766     if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
1767         return false;
1768
1769     cgen = self->right->expression.codegen;
1770     if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
1771         return false;
1772
1773     *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
1774                                  self->op, left, right);
1775     if (!*out)
1776         return false;
1777     self->expression.outr = *out;
1778
1779     return true;
1780 }
1781
1782 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
1783 {
1784     ast_expression_codegen *cgen;
1785     ir_value *leftl = NULL, *leftr, *right, *bin;
1786
1787     ast_value       *arr;
1788     ast_value       *idx = 0;
1789     ast_array_index *ai = NULL;
1790     ir_value        *iridx = NULL;
1791
1792     if (lvalue && self->expression.outl) {
1793         *out = self->expression.outl;
1794         return true;
1795     }
1796
1797     if (!lvalue && self->expression.outr) {
1798         *out = self->expression.outr;
1799         return true;
1800     }
1801
1802     if (ast_istype(self->dest, ast_array_index))
1803     {
1804
1805         ai = (ast_array_index*)self->dest;
1806         idx = (ast_value*)ai->index;
1807
1808         if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
1809             ai = NULL;
1810     }
1811
1812     /* for a binstore we need both an lvalue and an rvalue for the left side */
1813     /* rvalue of destination! */
1814     if (ai) {
1815         cgen = idx->expression.codegen;
1816         if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1817             return false;
1818     }
1819     cgen = self->dest->expression.codegen;
1820     if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
1821         return false;
1822
1823     /* source as rvalue only */
1824     cgen = self->source->expression.codegen;
1825     if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1826         return false;
1827
1828     /* now the binary */
1829     bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
1830                                 self->opbin, leftr, right);
1831     self->expression.outr = bin;
1832
1833
1834     if (ai) {
1835         /* we need to call the setter */
1836         ir_value  *funval;
1837         ir_instr  *call;
1838
1839         if (lvalue) {
1840             compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1841             return false;
1842         }
1843
1844         arr = (ast_value*)ai->array;
1845         if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1846             compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
1847             return false;
1848         }
1849
1850         cgen = arr->setter->expression.codegen;
1851         if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
1852             return false;
1853
1854         call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval);
1855         if (!call)
1856             return false;
1857         ir_call_param(call, iridx);
1858         ir_call_param(call, bin);
1859         self->expression.outr = bin;
1860     } else {
1861         /* now store them */
1862         cgen = self->dest->expression.codegen;
1863         /* lvalue of destination */
1864         if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
1865             return false;
1866         self->expression.outl = leftl;
1867
1868         if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
1869             return false;
1870         self->expression.outr = bin;
1871     }
1872
1873     /* Theoretically, an assinment returns its left side as an
1874      * lvalue, if we don't need an lvalue though, we return
1875      * the right side as an rvalue, otherwise we have to
1876      * somehow know whether or not we need to dereference the pointer
1877      * on the left side - that is: OP_LOAD if it was an address.
1878      * Also: in original QC we cannot OP_LOADP *anyway*.
1879      */
1880     *out = (lvalue ? leftl : bin);
1881
1882     return true;
1883 }
1884
1885 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
1886 {
1887     ast_expression_codegen *cgen;
1888     ir_value *operand;
1889
1890     /* An unary operation cannot yield an l-value */
1891     if (lvalue) {
1892         compile_error(ast_ctx(self), "not an l-value (binop)");
1893         return false;
1894     }
1895
1896     if (self->expression.outr) {
1897         *out = self->expression.outr;
1898         return true;
1899     }
1900
1901     cgen = self->operand->expression.codegen;
1902     /* lvalue! */
1903     if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
1904         return false;
1905
1906     *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
1907                                  self->op, operand);
1908     if (!*out)
1909         return false;
1910     self->expression.outr = *out;
1911
1912     return true;
1913 }
1914
1915 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
1916 {
1917     ast_expression_codegen *cgen;
1918     ir_value *operand;
1919
1920     *out = NULL;
1921
1922     /* In the context of a return operation, we don't actually return
1923      * anything...
1924      */
1925     if (lvalue) {
1926         compile_error(ast_ctx(self), "return-expression is not an l-value");
1927         return false;
1928     }
1929
1930     if (self->expression.outr) {
1931         compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
1932         return false;
1933     }
1934     self->expression.outr = (ir_value*)1;
1935
1936     if (self->operand) {
1937         cgen = self->operand->expression.codegen;
1938         /* lvalue! */
1939         if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
1940             return false;
1941
1942         if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
1943             return false;
1944     } else {
1945         if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
1946             return false;
1947     }
1948
1949     return true;
1950 }
1951
1952 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
1953 {
1954     ast_expression_codegen *cgen;
1955     ir_value *ent, *field;
1956
1957     /* This function needs to take the 'lvalue' flag into account!
1958      * As lvalue we provide a field-pointer, as rvalue we provide the
1959      * value in a temp.
1960      */
1961
1962     if (lvalue && self->expression.outl) {
1963         *out = self->expression.outl;
1964         return true;
1965     }
1966
1967     if (!lvalue && self->expression.outr) {
1968         *out = self->expression.outr;
1969         return true;
1970     }
1971
1972     cgen = self->entity->expression.codegen;
1973     if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
1974         return false;
1975
1976     cgen = self->field->expression.codegen;
1977     if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
1978         return false;
1979
1980     if (lvalue) {
1981         /* address! */
1982         *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
1983                                             ent, field);
1984     } else {
1985         *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
1986                                              ent, field, self->expression.vtype);
1987         codegen_output_type(self, *out);
1988     }
1989     if (!*out) {
1990         compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
1991                  (lvalue ? "ADDRESS" : "FIELD"),
1992                  type_name[self->expression.vtype]);
1993         return false;
1994     }
1995
1996     if (lvalue)
1997         self->expression.outl = *out;
1998     else
1999         self->expression.outr = *out;
2000
2001     /* Hm that should be it... */
2002     return true;
2003 }
2004
2005 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2006 {
2007     ast_expression_codegen *cgen;
2008     ir_value *vec;
2009
2010     /* in QC this is always an lvalue */
2011     (void)lvalue;
2012     if (self->expression.outl) {
2013         *out = self->expression.outl;
2014         return true;
2015     }
2016
2017     cgen = self->owner->expression.codegen;
2018     if (!(*cgen)((ast_expression*)(self->owner), func, true, &vec))
2019         return false;
2020
2021     if (vec->vtype != TYPE_VECTOR &&
2022         !(vec->vtype == TYPE_FIELD && self->owner->expression.next->expression.vtype == TYPE_VECTOR))
2023     {
2024         return false;
2025     }
2026
2027     *out = ir_value_vector_member(vec, self->field);
2028     self->expression.outl = *out;
2029
2030     return (*out != NULL);
2031 }
2032
2033 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2034 {
2035     ast_value *arr;
2036     ast_value *idx;
2037
2038     if (!lvalue && self->expression.outr) {
2039         *out = self->expression.outr;
2040     }
2041     if (lvalue && self->expression.outl) {
2042         *out = self->expression.outl;
2043     }
2044
2045     if (!ast_istype(self->array, ast_value)) {
2046         compile_error(ast_ctx(self), "array indexing this way is not supported");
2047         /* note this would actually be pointer indexing because the left side is
2048          * not an actual array but (hopefully) an indexable expression.
2049          * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2050          * support this path will be filled.
2051          */
2052         return false;
2053     }
2054
2055     arr = (ast_value*)self->array;
2056     idx = (ast_value*)self->index;
2057
2058     if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2059         /* Time to use accessor functions */
2060         ast_expression_codegen *cgen;
2061         ir_value               *iridx, *funval;
2062         ir_instr               *call;
2063
2064         if (lvalue) {
2065             compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2066             return false;
2067         }
2068
2069         if (!arr->getter) {
2070             compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2071             return false;
2072         }
2073
2074         cgen = self->index->expression.codegen;
2075         if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2076             return false;
2077
2078         cgen = arr->getter->expression.codegen;
2079         if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2080             return false;
2081
2082         call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval);
2083         if (!call)
2084             return false;
2085         ir_call_param(call, iridx);
2086
2087         *out = ir_call_value(call);
2088         self->expression.outr = *out;
2089         return true;
2090     }
2091
2092     if (idx->expression.vtype == TYPE_FLOAT) {
2093         unsigned int arridx = idx->constval.vfloat;
2094         if (arridx >= self->array->expression.count)
2095         {
2096             compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2097             return false;
2098         }
2099         *out = arr->ir_values[arridx];
2100     }
2101     else if (idx->expression.vtype == TYPE_INTEGER) {
2102         unsigned int arridx = idx->constval.vint;
2103         if (arridx >= self->array->expression.count)
2104         {
2105             compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2106             return false;
2107         }
2108         *out = arr->ir_values[arridx];
2109     }
2110     else {
2111         compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2112         return false;
2113     }
2114     return true;
2115 }
2116
2117 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2118 {
2119     ast_expression_codegen *cgen;
2120
2121     ir_value *condval;
2122     ir_value *dummy;
2123
2124     ir_block *cond = func->curblock;
2125     ir_block *ontrue;
2126     ir_block *onfalse;
2127     ir_block *ontrue_endblock = NULL;
2128     ir_block *onfalse_endblock = NULL;
2129     ir_block *merge = NULL;
2130
2131     /* We don't output any value, thus also don't care about r/lvalue */
2132     (void)out;
2133     (void)lvalue;
2134
2135     if (self->expression.outr) {
2136         compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2137         return false;
2138     }
2139     self->expression.outr = (ir_value*)1;
2140
2141     /* generate the condition */
2142     cgen = self->cond->expression.codegen;
2143     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2144         return false;
2145     /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2146     cond = func->curblock;
2147
2148     /* on-true path */
2149
2150     if (self->on_true) {
2151         /* create on-true block */
2152         ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2153         if (!ontrue)
2154             return false;
2155
2156         /* enter the block */
2157         func->curblock = ontrue;
2158
2159         /* generate */
2160         cgen = self->on_true->expression.codegen;
2161         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2162             return false;
2163
2164         /* we now need to work from the current endpoint */
2165         ontrue_endblock = func->curblock;
2166     } else
2167         ontrue = NULL;
2168
2169     /* on-false path */
2170     if (self->on_false) {
2171         /* create on-false block */
2172         onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2173         if (!onfalse)
2174             return false;
2175
2176         /* enter the block */
2177         func->curblock = onfalse;
2178
2179         /* generate */
2180         cgen = self->on_false->expression.codegen;
2181         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2182             return false;
2183
2184         /* we now need to work from the current endpoint */
2185         onfalse_endblock = func->curblock;
2186     } else
2187         onfalse = NULL;
2188
2189     /* Merge block were they all merge in to */
2190     if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2191     {
2192         merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2193         if (!merge)
2194             return false;
2195         /* add jumps ot the merge block */
2196         if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2197             return false;
2198         if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2199             return false;
2200
2201         /* Now enter the merge block */
2202         func->curblock = merge;
2203     }
2204
2205     /* we create the if here, that way all blocks are ordered :)
2206      */
2207     if (!ir_block_create_if(cond, ast_ctx(self), condval,
2208                             (ontrue  ? ontrue  : merge),
2209                             (onfalse ? onfalse : merge)))
2210     {
2211         return false;
2212     }
2213
2214     return true;
2215 }
2216
2217 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2218 {
2219     ast_expression_codegen *cgen;
2220
2221     ir_value *condval;
2222     ir_value *trueval, *falseval;
2223     ir_instr *phi;
2224
2225     ir_block *cond = func->curblock;
2226     ir_block *cond_out = NULL;
2227     ir_block *ontrue, *ontrue_out = NULL;
2228     ir_block *onfalse, *onfalse_out = NULL;
2229     ir_block *merge;
2230
2231     /* Ternary can never create an lvalue... */
2232     if (lvalue)
2233         return false;
2234
2235     /* In theory it shouldn't be possible to pass through a node twice, but
2236      * in case we add any kind of optimization pass for the AST itself, it
2237      * may still happen, thus we remember a created ir_value and simply return one
2238      * if it already exists.
2239      */
2240     if (self->expression.outr) {
2241         *out = self->expression.outr;
2242         return true;
2243     }
2244
2245     /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2246
2247     /* generate the condition */
2248     func->curblock = cond;
2249     cgen = self->cond->expression.codegen;
2250     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2251         return false;
2252     cond_out = func->curblock;
2253
2254     /* create on-true block */
2255     ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2256     if (!ontrue)
2257         return false;
2258     else
2259     {
2260         /* enter the block */
2261         func->curblock = ontrue;
2262
2263         /* generate */
2264         cgen = self->on_true->expression.codegen;
2265         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2266             return false;
2267
2268         ontrue_out = func->curblock;
2269     }
2270
2271     /* create on-false block */
2272     onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2273     if (!onfalse)
2274         return false;
2275     else
2276     {
2277         /* enter the block */
2278         func->curblock = onfalse;
2279
2280         /* generate */
2281         cgen = self->on_false->expression.codegen;
2282         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2283             return false;
2284
2285         onfalse_out = func->curblock;
2286     }
2287
2288     /* create merge block */
2289     merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2290     if (!merge)
2291         return false;
2292     /* jump to merge block */
2293     if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2294         return false;
2295     if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2296         return false;
2297
2298     /* create if instruction */
2299     if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2300         return false;
2301
2302     /* Now enter the merge block */
2303     func->curblock = merge;
2304
2305     /* Here, now, we need a PHI node
2306      * but first some sanity checking...
2307      */
2308     if (trueval->vtype != falseval->vtype) {
2309         /* error("ternary with different types on the two sides"); */
2310         return false;
2311     }
2312
2313     /* create PHI */
2314     phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), trueval->vtype);
2315     if (!phi)
2316         return false;
2317     ir_phi_add(phi, ontrue_out,  trueval);
2318     ir_phi_add(phi, onfalse_out, falseval);
2319
2320     self->expression.outr = ir_phi_value(phi);
2321     *out = self->expression.outr;
2322
2323     return true;
2324 }
2325
2326 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2327 {
2328     ast_expression_codegen *cgen;
2329
2330     ir_value *dummy      = NULL;
2331     ir_value *precond    = NULL;
2332     ir_value *postcond   = NULL;
2333
2334     /* Since we insert some jumps "late" so we have blocks
2335      * ordered "nicely", we need to keep track of the actual end-blocks
2336      * of expressions to add the jumps to.
2337      */
2338     ir_block *bbody      = NULL, *end_bbody      = NULL;
2339     ir_block *bprecond   = NULL, *end_bprecond   = NULL;
2340     ir_block *bpostcond  = NULL, *end_bpostcond  = NULL;
2341     ir_block *bincrement = NULL, *end_bincrement = NULL;
2342     ir_block *bout       = NULL, *bin            = NULL;
2343
2344     /* let's at least move the outgoing block to the end */
2345     size_t    bout_id;
2346
2347     /* 'break' and 'continue' need to be able to find the right blocks */
2348     ir_block *bcontinue     = NULL;
2349     ir_block *bbreak        = NULL;
2350
2351     ir_block *old_bcontinue = NULL;
2352     ir_block *old_bbreak    = NULL;
2353
2354     ir_block *tmpblock      = NULL;
2355
2356     (void)lvalue;
2357     (void)out;
2358
2359     if (self->expression.outr) {
2360         compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2361         return false;
2362     }
2363     self->expression.outr = (ir_value*)1;
2364
2365     /* NOTE:
2366      * Should we ever need some kind of block ordering, better make this function
2367      * move blocks around than write a block ordering algorithm later... after all
2368      * the ast and ir should work together, not against each other.
2369      */
2370
2371     /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2372      * anyway if for example it contains a ternary.
2373      */
2374     if (self->initexpr)
2375     {
2376         cgen = self->initexpr->expression.codegen;
2377         if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2378             return false;
2379     }
2380
2381     /* Store the block from which we enter this chaos */
2382     bin = func->curblock;
2383
2384     /* The pre-loop condition needs its own block since we
2385      * need to be able to jump to the start of that expression.
2386      */
2387     if (self->precond)
2388     {
2389         bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2390         if (!bprecond)
2391             return false;
2392
2393         /* the pre-loop-condition the least important place to 'continue' at */
2394         bcontinue = bprecond;
2395
2396         /* enter */
2397         func->curblock = bprecond;
2398
2399         /* generate */
2400         cgen = self->precond->expression.codegen;
2401         if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2402             return false;
2403
2404         end_bprecond = func->curblock;
2405     } else {
2406         bprecond = end_bprecond = NULL;
2407     }
2408
2409     /* Now the next blocks won't be ordered nicely, but we need to
2410      * generate them this early for 'break' and 'continue'.
2411      */
2412     if (self->increment) {
2413         bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2414         if (!bincrement)
2415             return false;
2416         bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2417     } else {
2418         bincrement = end_bincrement = NULL;
2419     }
2420
2421     if (self->postcond) {
2422         bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2423         if (!bpostcond)
2424             return false;
2425         bcontinue = bpostcond; /* postcond comes before the increment */
2426     } else {
2427         bpostcond = end_bpostcond = NULL;
2428     }
2429
2430     bout_id = vec_size(func->ir_func->blocks);
2431     bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2432     if (!bout)
2433         return false;
2434     bbreak = bout;
2435
2436     /* The loop body... */
2437     /* if (self->body) */
2438     {
2439         bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2440         if (!bbody)
2441             return false;
2442
2443         /* enter */
2444         func->curblock = bbody;
2445
2446         old_bbreak          = func->breakblock;
2447         old_bcontinue       = func->continueblock;
2448         func->breakblock    = bbreak;
2449         func->continueblock = bcontinue;
2450         if (!func->continueblock)
2451             func->continueblock = bbody;
2452
2453         /* generate */
2454         if (self->body) {
2455             cgen = self->body->expression.codegen;
2456             if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2457                 return false;
2458         }
2459
2460         end_bbody = func->curblock;
2461         func->breakblock    = old_bbreak;
2462         func->continueblock = old_bcontinue;
2463     }
2464
2465     /* post-loop-condition */
2466     if (self->postcond)
2467     {
2468         /* enter */
2469         func->curblock = bpostcond;
2470
2471         /* generate */
2472         cgen = self->postcond->expression.codegen;
2473         if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2474             return false;
2475
2476         end_bpostcond = func->curblock;
2477     }
2478
2479     /* The incrementor */
2480     if (self->increment)
2481     {
2482         /* enter */
2483         func->curblock = bincrement;
2484
2485         /* generate */
2486         cgen = self->increment->expression.codegen;
2487         if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2488             return false;
2489
2490         end_bincrement = func->curblock;
2491     }
2492
2493     /* In any case now, we continue from the outgoing block */
2494     func->curblock = bout;
2495
2496     /* Now all blocks are in place */
2497     /* From 'bin' we jump to whatever comes first */
2498     if      (bprecond)   tmpblock = bprecond;
2499     else if (bbody)      tmpblock = bbody;
2500     else if (bpostcond)  tmpblock = bpostcond;
2501     else                 tmpblock = bout;
2502     if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2503         return false;
2504
2505     /* From precond */
2506     if (bprecond)
2507     {
2508         ir_block *ontrue, *onfalse;
2509         if      (bbody)      ontrue = bbody;
2510         else if (bincrement) ontrue = bincrement;
2511         else if (bpostcond)  ontrue = bpostcond;
2512         else                 ontrue = bprecond;
2513         onfalse = bout;
2514         if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
2515             return false;
2516     }
2517
2518     /* from body */
2519     if (bbody)
2520     {
2521         if      (bincrement) tmpblock = bincrement;
2522         else if (bpostcond)  tmpblock = bpostcond;
2523         else if (bprecond)   tmpblock = bprecond;
2524         else                 tmpblock = bbody;
2525         if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
2526             return false;
2527     }
2528
2529     /* from increment */
2530     if (bincrement)
2531     {
2532         if      (bpostcond)  tmpblock = bpostcond;
2533         else if (bprecond)   tmpblock = bprecond;
2534         else if (bbody)      tmpblock = bbody;
2535         else                 tmpblock = bout;
2536         if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
2537             return false;
2538     }
2539
2540     /* from postcond */
2541     if (bpostcond)
2542     {
2543         ir_block *ontrue, *onfalse;
2544         if      (bprecond)   ontrue = bprecond;
2545         else if (bbody)      ontrue = bbody;
2546         else if (bincrement) ontrue = bincrement;
2547         else                 ontrue = bpostcond;
2548         onfalse = bout;
2549         if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
2550             return false;
2551     }
2552
2553     /* Move 'bout' to the end */
2554     vec_remove(func->ir_func->blocks, bout_id, 1);
2555     vec_push(func->ir_func->blocks, bout);
2556
2557     return true;
2558 }
2559
2560 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
2561 {
2562     ir_block *target;
2563
2564     *out = NULL;
2565
2566     if (lvalue) {
2567         compile_error(ast_ctx(self), "break/continue expression is not an l-value");
2568         return false;
2569     }
2570
2571     if (self->expression.outr) {
2572         compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
2573         return false;
2574     }
2575     self->expression.outr = (ir_value*)1;
2576
2577     if (self->is_continue)
2578         target = func->continueblock;
2579     else
2580         target = func->breakblock;
2581
2582     if (!target) {
2583         compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
2584         return false;
2585     }
2586
2587     if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
2588         return false;
2589     return true;
2590 }
2591
2592 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
2593 {
2594     ast_expression_codegen *cgen;
2595
2596     ast_switch_case *def_case  = NULL;
2597     ir_block        *def_bfall = NULL;
2598
2599     ir_value *dummy     = NULL;
2600     ir_value *irop      = NULL;
2601     ir_block *old_break = NULL;
2602     ir_block *bout      = NULL;
2603     ir_block *bfall     = NULL;
2604     size_t    bout_id;
2605     size_t    c;
2606
2607     char      typestr[1024];
2608     uint16_t  cmpinstr;
2609
2610     if (lvalue) {
2611         compile_error(ast_ctx(self), "switch expression is not an l-value");
2612         return false;
2613     }
2614
2615     if (self->expression.outr) {
2616         compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
2617         return false;
2618     }
2619     self->expression.outr = (ir_value*)1;
2620
2621     (void)lvalue;
2622     (void)out;
2623
2624     cgen = self->operand->expression.codegen;
2625     if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
2626         return false;
2627
2628     if (!vec_size(self->cases))
2629         return true;
2630
2631     cmpinstr = type_eq_instr[irop->vtype];
2632     if (cmpinstr >= AINSTR_END) {
2633         ast_type_to_string(self->operand, typestr, sizeof(typestr));
2634         compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
2635         return false;
2636     }
2637
2638     bout_id = vec_size(func->ir_func->blocks);
2639     bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
2640     if (!bout)
2641         return false;
2642
2643     /* setup the break block */
2644     old_break        = func->breakblock;
2645     func->breakblock = bout;
2646
2647     /* Now create all cases */
2648     for (c = 0; c < vec_size(self->cases); ++c) {
2649         ir_value *cond, *val;
2650         ir_block *bcase, *bnot;
2651         size_t bnot_id;
2652
2653         ast_switch_case *swcase = &self->cases[c];
2654
2655         if (swcase->value) {
2656             /* A regular case */
2657             /* generate the condition operand */
2658             cgen = swcase->value->expression.codegen;
2659             if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
2660                 return false;
2661             /* generate the condition */
2662             cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
2663             if (!cond)
2664                 return false;
2665
2666             bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
2667             bnot_id = vec_size(func->ir_func->blocks);
2668             bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
2669             if (!bcase || !bnot)
2670                 return false;
2671             if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
2672                 return false;
2673
2674             /* Make the previous case-end fall through */
2675             if (bfall && !bfall->final) {
2676                 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
2677                     return false;
2678             }
2679
2680             /* enter the case */
2681             func->curblock = bcase;
2682             cgen = swcase->code->expression.codegen;
2683             if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
2684                 return false;
2685
2686             /* remember this block to fall through from */
2687             bfall = func->curblock;
2688
2689             /* enter the else and move it down */
2690             func->curblock = bnot;
2691             vec_remove(func->ir_func->blocks, bnot_id, 1);
2692             vec_push(func->ir_func->blocks, bnot);
2693         } else {
2694             /* The default case */
2695             /* Remember where to fall through from: */
2696             def_bfall = bfall;
2697             bfall     = NULL;
2698             /* remember which case it was */
2699             def_case  = swcase;
2700         }
2701     }
2702
2703     /* Jump from the last bnot to bout */
2704     if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
2705         /*
2706         astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
2707         */
2708         return false;
2709     }
2710
2711     /* If there was a default case, put it down here */
2712     if (def_case) {
2713         ir_block *bcase;
2714
2715         /* No need to create an extra block */
2716         bcase = func->curblock;
2717
2718         /* Insert the fallthrough jump */
2719         if (def_bfall && !def_bfall->final) {
2720             if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
2721                 return false;
2722         }
2723
2724         /* Now generate the default code */
2725         cgen = def_case->code->expression.codegen;
2726         if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
2727             return false;
2728     }
2729
2730     /* Jump from the last bnot to bout */
2731     if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
2732         return false;
2733     /* enter the outgoing block */
2734     func->curblock = bout;
2735
2736     /* restore the break block */
2737     func->breakblock = old_break;
2738
2739     /* Move 'bout' to the end, it's nicer */
2740     vec_remove(func->ir_func->blocks, bout_id, 1);
2741     vec_push(func->ir_func->blocks, bout);
2742
2743     return true;
2744 }
2745
2746 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
2747 {
2748     size_t i;
2749     ir_value *dummy;
2750
2751     *out = NULL;
2752     if (lvalue) {
2753         compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
2754         return false;
2755     }
2756
2757     /* simply create a new block and jump to it */
2758     self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
2759     if (!self->irblock) {
2760         compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
2761         return false;
2762     }
2763     if (!func->curblock->final) {
2764         if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
2765             return false;
2766     }
2767
2768     /* enter the new block */
2769     func->curblock = self->irblock;
2770
2771     /* Generate all the leftover gotos */
2772     for (i = 0; i < vec_size(self->gotos); ++i) {
2773         if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
2774             return false;
2775     }
2776
2777     return true;
2778 }
2779
2780 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
2781 {
2782     *out = NULL;
2783     if (lvalue) {
2784         compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
2785         return false;
2786     }
2787
2788     if (self->target->irblock) {
2789         if (self->irblock_from) {
2790             /* we already tried once, this is the callback */
2791             self->irblock_from->final = false;
2792             if (!ir_block_create_jump(self->irblock_from, ast_ctx(self), self->target->irblock)) {
2793                 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
2794                 return false;
2795             }
2796         }
2797         else
2798         {
2799             if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->target->irblock)) {
2800                 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
2801                 return false;
2802             }
2803         }
2804     }
2805     else
2806     {
2807         /* the target has not yet been created...
2808          * close this block in a sneaky way:
2809          */
2810         func->curblock->final = true;
2811         self->irblock_from = func->curblock;
2812         ast_label_register_goto(self->target, self);
2813     }
2814
2815     return true;
2816 }
2817
2818 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
2819 {
2820     ast_expression_codegen *cgen;
2821     ir_value              **params;
2822     ir_instr               *callinstr;
2823     size_t i;
2824
2825     ir_value *funval = NULL;
2826
2827     /* return values are never lvalues */
2828     if (lvalue) {
2829         compile_error(ast_ctx(self), "not an l-value (function call)");
2830         return false;
2831     }
2832
2833     if (self->expression.outr) {
2834         *out = self->expression.outr;
2835         return true;
2836     }
2837
2838     cgen = self->func->expression.codegen;
2839     if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
2840         return false;
2841     if (!funval)
2842         return false;
2843
2844     params = NULL;
2845
2846     /* parameters */
2847     for (i = 0; i < vec_size(self->params); ++i)
2848     {
2849         ir_value *param;
2850         ast_expression *expr = self->params[i];
2851
2852         cgen = expr->expression.codegen;
2853         if (!(*cgen)(expr, func, false, &param))
2854             goto error;
2855         if (!param)
2856             goto error;
2857         vec_push(params, param);
2858     }
2859
2860     callinstr = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "call"), funval);
2861     if (!callinstr)
2862         goto error;
2863
2864     for (i = 0; i < vec_size(params); ++i) {
2865         ir_call_param(callinstr, params[i]);
2866     }
2867
2868     *out = ir_call_value(callinstr);
2869     self->expression.outr = *out;
2870
2871     codegen_output_type(self, *out);
2872
2873     vec_free(params);
2874     return true;
2875 error:
2876     vec_free(params);
2877     return false;
2878 }