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