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