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