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