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