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