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