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