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