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