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