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