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