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