]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ast.c
-fperl-logic, off by default, so casting to boolean now
[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     self->phi_out  = NULL;
655
656     return self;
657 }
658
659 void ast_ternary_delete(ast_ternary *self)
660 {
661     ast_unref(self->cond);
662     ast_unref(self->on_true);
663     ast_unref(self->on_false);
664     ast_expression_delete((ast_expression*)self);
665     mem_d(self);
666 }
667
668 ast_loop* ast_loop_new(lex_ctx ctx,
669                        ast_expression *initexpr,
670                        ast_expression *precond,
671                        ast_expression *postcond,
672                        ast_expression *increment,
673                        ast_expression *body)
674 {
675     ast_instantiate(ast_loop, ctx, ast_loop_delete);
676     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
677
678     self->initexpr  = initexpr;
679     self->precond   = precond;
680     self->postcond  = postcond;
681     self->increment = increment;
682     self->body      = body;
683
684     return self;
685 }
686
687 void ast_loop_delete(ast_loop *self)
688 {
689     if (self->initexpr)
690         ast_unref(self->initexpr);
691     if (self->precond)
692         ast_unref(self->precond);
693     if (self->postcond)
694         ast_unref(self->postcond);
695     if (self->increment)
696         ast_unref(self->increment);
697     if (self->body)
698         ast_unref(self->body);
699     ast_expression_delete((ast_expression*)self);
700     mem_d(self);
701 }
702
703 ast_breakcont* ast_breakcont_new(lex_ctx ctx, bool iscont)
704 {
705     ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
706     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
707
708     self->is_continue = iscont;
709
710     return self;
711 }
712
713 void ast_breakcont_delete(ast_breakcont *self)
714 {
715     ast_expression_delete((ast_expression*)self);
716     mem_d(self);
717 }
718
719 ast_switch* ast_switch_new(lex_ctx ctx, ast_expression *op)
720 {
721     ast_instantiate(ast_switch, ctx, ast_switch_delete);
722     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
723
724     self->operand = op;
725     self->cases   = NULL;
726
727     return self;
728 }
729
730 void ast_switch_delete(ast_switch *self)
731 {
732     size_t i;
733     ast_unref(self->operand);
734
735     for (i = 0; i < vec_size(self->cases); ++i) {
736         if (self->cases[i].value)
737             ast_unref(self->cases[i].value);
738         ast_unref(self->cases[i].code);
739     }
740     vec_free(self->cases);
741
742     ast_expression_delete((ast_expression*)self);
743     mem_d(self);
744 }
745
746 ast_call* ast_call_new(lex_ctx ctx,
747                        ast_expression *funcexpr)
748 {
749     ast_instantiate(ast_call, ctx, ast_call_delete);
750     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
751
752     self->params = NULL;
753     self->func   = funcexpr;
754
755     self->expression.vtype = funcexpr->expression.next->expression.vtype;
756     if (funcexpr->expression.next->expression.next)
757         self->expression.next = ast_type_copy(ctx, funcexpr->expression.next->expression.next);
758
759     return self;
760 }
761
762 void ast_call_delete(ast_call *self)
763 {
764     size_t i;
765     for (i = 0; i < vec_size(self->params); ++i)
766         ast_unref(self->params[i]);
767     vec_free(self->params);
768
769     if (self->func)
770         ast_unref(self->func);
771
772     ast_expression_delete((ast_expression*)self);
773     mem_d(self);
774 }
775
776 bool ast_call_check_types(ast_call *self)
777 {
778     size_t i;
779     bool   retval = true;
780     const  ast_expression *func = self->func;
781     size_t count = vec_size(self->params);
782     if (count > vec_size(func->expression.params))
783         count = vec_size(func->expression.params);
784
785     for (i = 0; i < count; ++i) {
786         if (!ast_compare_type(self->params[i], (ast_expression*)(func->expression.params[i]))) {
787             asterror(ast_ctx(self), "invalid type for parameter %u in function call",
788                      (unsigned int)(i+1));
789             /* we don't immediately return */
790             retval = false;
791         }
792     }
793     return retval;
794 }
795
796 ast_store* ast_store_new(lex_ctx ctx, int op,
797                          ast_expression *dest, ast_expression *source)
798 {
799     ast_instantiate(ast_store, ctx, ast_store_delete);
800     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
801
802     self->op = op;
803     self->dest = dest;
804     self->source = source;
805
806     self->expression.vtype = dest->expression.vtype;
807     if (dest->expression.next) {
808         self->expression.next = ast_type_copy(ctx, dest);
809         if (!self->expression.next) {
810             ast_delete(self);
811             return NULL;
812         }
813     }
814     else
815         self->expression.next = NULL;
816
817     return self;
818 }
819
820 void ast_store_delete(ast_store *self)
821 {
822     ast_unref(self->dest);
823     ast_unref(self->source);
824     ast_expression_delete((ast_expression*)self);
825     mem_d(self);
826 }
827
828 ast_block* ast_block_new(lex_ctx ctx)
829 {
830     ast_instantiate(ast_block, ctx, ast_block_delete);
831     ast_expression_init((ast_expression*)self,
832                         (ast_expression_codegen*)&ast_block_codegen);
833
834     self->locals  = NULL;
835     self->exprs   = NULL;
836     self->collect = NULL;
837
838     return self;
839 }
840
841 void ast_block_collect(ast_block *self, ast_expression *expr)
842 {
843     vec_push(self->collect, expr);
844     expr->expression.node.keep = true;
845 }
846
847 void ast_block_delete(ast_block *self)
848 {
849     size_t i;
850     for (i = 0; i < vec_size(self->exprs); ++i)
851         ast_unref(self->exprs[i]);
852     vec_free(self->exprs);
853     for (i = 0; i < vec_size(self->locals); ++i)
854         ast_delete(self->locals[i]);
855     vec_free(self->locals);
856     for (i = 0; i < vec_size(self->collect); ++i)
857         ast_delete(self->collect[i]);
858     vec_free(self->collect);
859     ast_expression_delete((ast_expression*)self);
860     mem_d(self);
861 }
862
863 bool ast_block_set_type(ast_block *self, ast_expression *from)
864 {
865     if (self->expression.next)
866         ast_delete(self->expression.next);
867     self->expression.vtype = from->expression.vtype;
868     if (from->expression.next) {
869         self->expression.next = ast_type_copy(self->expression.node.context, from->expression.next);
870         if (!self->expression.next)
871             return false;
872     }
873     else
874         self->expression.next = NULL;
875     return true;
876 }
877
878 ast_function* ast_function_new(lex_ctx ctx, const char *name, ast_value *vtype)
879 {
880     ast_instantiate(ast_function, ctx, ast_function_delete);
881
882     if (!vtype ||
883         vtype->isconst ||
884         vtype->expression.vtype != TYPE_FUNCTION)
885     {
886         mem_d(self);
887         return NULL;
888     }
889
890     self->vtype  = vtype;
891     self->name   = name ? util_strdup(name) : NULL;
892     self->blocks = NULL;
893
894     self->labelcount = 0;
895     self->builtin = 0;
896
897     self->ir_func = NULL;
898     self->curblock = NULL;
899
900     self->breakblock    = NULL;
901     self->continueblock = NULL;
902
903     vtype->isconst = true;
904     vtype->constval.vfunc = self;
905
906     return self;
907 }
908
909 void ast_function_delete(ast_function *self)
910 {
911     size_t i;
912     if (self->name)
913         mem_d((void*)self->name);
914     if (self->vtype) {
915         /* ast_value_delete(self->vtype); */
916         self->vtype->isconst = false;
917         self->vtype->constval.vfunc = NULL;
918         /* We use unref - if it was stored in a global table it is supposed
919          * to be deleted from *there*
920          */
921         ast_unref(self->vtype);
922     }
923     for (i = 0; i < vec_size(self->blocks); ++i)
924         ast_delete(self->blocks[i]);
925     vec_free(self->blocks);
926     mem_d(self);
927 }
928
929 const char* ast_function_label(ast_function *self, const char *prefix)
930 {
931     size_t id;
932     size_t len;
933     char  *from;
934
935     if (!opts_dump)
936         return NULL;
937
938     id  = (self->labelcount++);
939     len = strlen(prefix);
940
941     from = self->labelbuf + sizeof(self->labelbuf)-1;
942     *from-- = 0;
943     do {
944         unsigned int digit = id % 10;
945         *from = digit + '0';
946         id /= 10;
947     } while (id);
948     memcpy(from - len, prefix, len);
949     return from - len;
950 }
951
952 /*********************************************************************/
953 /* AST codegen part
954  * by convention you must never pass NULL to the 'ir_value **out'
955  * parameter. If you really don't care about the output, pass a dummy.
956  * But I can't imagine a pituation where the output is truly unnecessary.
957  */
958
959 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
960 {
961     /* NOTE: This is the codegen for a variable used in an expression.
962      * It is not the codegen to generate the value. For this purpose,
963      * ast_local_codegen and ast_global_codegen are to be used before this
964      * is executed. ast_function_codegen should take care of its locals,
965      * and the ast-user should take care of ast_global_codegen to be used
966      * on all the globals.
967      */
968     if (!self->ir_v) {
969         char typename[1024];
970         ast_type_to_string((ast_expression*)self, typename, sizeof(typename));
971         asterror(ast_ctx(self), "ast_value used before generated %s %s", typename, self->name);
972         return false;
973     }
974     *out = self->ir_v;
975     return true;
976 }
977
978 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
979 {
980     ir_value *v = NULL;
981
982     if (self->isconst && self->expression.vtype == TYPE_FUNCTION)
983     {
984         ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->expression.vtype);
985         if (!func)
986             return false;
987         func->context = ast_ctx(self);
988         func->value->context = ast_ctx(self);
989
990         self->constval.vfunc->ir_func = func;
991         self->ir_v = func->value;
992         /* The function is filled later on ast_function_codegen... */
993         return true;
994     }
995
996     if (isfield && self->expression.vtype == TYPE_FIELD) {
997         ast_expression *fieldtype = self->expression.next;
998
999         if (self->isconst) {
1000             asterror(ast_ctx(self), "TODO: constant field pointers with value");
1001             goto error;
1002         }
1003
1004         if (fieldtype->expression.vtype == TYPE_ARRAY) {
1005             size_t ai;
1006             char   *name;
1007             size_t  namelen;
1008
1009             ast_expression_common *elemtype;
1010             int                    vtype;
1011             ast_value             *array = (ast_value*)fieldtype;
1012
1013             if (!ast_istype(fieldtype, ast_value)) {
1014                 asterror(ast_ctx(self), "internal error: ast_value required");
1015                 return false;
1016             }
1017
1018             /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1019             if (!array->expression.count || array->expression.count > opts_max_array_size)
1020                 asterror(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1021
1022             elemtype = &array->expression.next->expression;
1023             vtype = elemtype->vtype;
1024
1025             v = ir_builder_create_field(ir, self->name, vtype);
1026             if (!v) {
1027                 asterror(ast_ctx(self), "ir_builder_create_global failed");
1028                 return false;
1029             }
1030             if (vtype == TYPE_FIELD)
1031                 v->fieldtype = elemtype->next->expression.vtype;
1032             v->context = ast_ctx(self);
1033             array->ir_v = self->ir_v = v;
1034
1035             namelen = strlen(self->name);
1036             name    = (char*)mem_a(namelen + 16);
1037             strcpy(name, self->name);
1038
1039             array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1040             array->ir_values[0] = v;
1041             for (ai = 1; ai < array->expression.count; ++ai) {
1042                 snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1043                 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1044                 if (!array->ir_values[ai]) {
1045                     mem_d(name);
1046                     asterror(ast_ctx(self), "ir_builder_create_global failed");
1047                     return false;
1048                 }
1049                 if (vtype == TYPE_FIELD)
1050                     array->ir_values[ai]->fieldtype = elemtype->next->expression.vtype;
1051                 array->ir_values[ai]->context = ast_ctx(self);
1052             }
1053             mem_d(name);
1054         }
1055         else
1056         {
1057             v = ir_builder_create_field(ir, self->name, self->expression.next->expression.vtype);
1058             if (!v)
1059                 return false;
1060             v->context = ast_ctx(self);
1061             self->ir_v = v;
1062         }
1063         return true;
1064     }
1065
1066     if (self->expression.vtype == TYPE_ARRAY) {
1067         size_t ai;
1068         char   *name;
1069         size_t  namelen;
1070
1071         ast_expression_common *elemtype = &self->expression.next->expression;
1072         int vtype = elemtype->vtype;
1073
1074         /* same as with field arrays */
1075         if (!self->expression.count || self->expression.count > opts_max_array_size)
1076             asterror(ast_ctx(self), "Invalid array of size %lu", (unsigned long)self->expression.count);
1077
1078         v = ir_builder_create_global(ir, self->name, vtype);
1079         if (!v) {
1080             asterror(ast_ctx(self), "ir_builder_create_global failed");
1081             return false;
1082         }
1083         if (vtype == TYPE_FIELD)
1084             v->fieldtype = elemtype->next->expression.vtype;
1085         v->context = ast_ctx(self);
1086
1087         namelen = strlen(self->name);
1088         name    = (char*)mem_a(namelen + 16);
1089         strcpy(name, self->name);
1090
1091         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1092         self->ir_values[0] = v;
1093         for (ai = 1; ai < self->expression.count; ++ai) {
1094             snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1095             self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1096             if (!self->ir_values[ai]) {
1097                 mem_d(name);
1098                 asterror(ast_ctx(self), "ir_builder_create_global failed");
1099                 return false;
1100             }
1101             if (vtype == TYPE_FIELD)
1102                 self->ir_values[ai]->fieldtype = elemtype->next->expression.vtype;
1103             self->ir_values[ai]->context = ast_ctx(self);
1104         }
1105         mem_d(name);
1106     }
1107     else
1108     {
1109         /* Arrays don't do this since there's no "array" value which spans across the
1110          * whole thing.
1111          */
1112         v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1113         if (!v) {
1114             asterror(ast_ctx(self), "ir_builder_create_global failed");
1115             return false;
1116         }
1117         if (self->expression.vtype == TYPE_FIELD)
1118             v->fieldtype = self->expression.next->expression.vtype;
1119         v->context = ast_ctx(self);
1120     }
1121
1122     if (self->isconst) {
1123         switch (self->expression.vtype)
1124         {
1125             case TYPE_FLOAT:
1126                 if (!ir_value_set_float(v, self->constval.vfloat))
1127                     goto error;
1128                 break;
1129             case TYPE_VECTOR:
1130                 if (!ir_value_set_vector(v, self->constval.vvec))
1131                     goto error;
1132                 break;
1133             case TYPE_STRING:
1134                 if (!ir_value_set_string(v, self->constval.vstring))
1135                     goto error;
1136                 break;
1137             case TYPE_ARRAY:
1138                 asterror(ast_ctx(self), "TODO: global constant array");
1139                 break;
1140             case TYPE_FUNCTION:
1141                 asterror(ast_ctx(self), "global of type function not properly generated");
1142                 goto error;
1143                 /* Cannot generate an IR value for a function,
1144                  * need a pointer pointing to a function rather.
1145                  */
1146             default:
1147                 asterror(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1148                 break;
1149         }
1150     }
1151
1152     /* link us to the ir_value */
1153     self->ir_v = v;
1154     return true;
1155
1156 error: /* clean up */
1157     ir_value_delete(v);
1158     return false;
1159 }
1160
1161 bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1162 {
1163     ir_value *v = NULL;
1164     if (self->isconst && self->expression.vtype == TYPE_FUNCTION)
1165     {
1166         /* Do we allow local functions? I think not...
1167          * this is NOT a function pointer atm.
1168          */
1169         return false;
1170     }
1171
1172     if (self->expression.vtype == TYPE_ARRAY) {
1173         size_t ai;
1174         char   *name;
1175         size_t  namelen;
1176
1177         ast_expression_common *elemtype = &self->expression.next->expression;
1178         int vtype = elemtype->vtype;
1179
1180         if (param) {
1181             asterror(ast_ctx(self), "array-parameters are not supported");
1182             return false;
1183         }
1184
1185         /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1186         if (!self->expression.count || self->expression.count > opts_max_array_size) {
1187             asterror(ast_ctx(self), "Invalid array of size %lu", (unsigned long)self->expression.count);
1188         }
1189
1190         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1191         if (!self->ir_values) {
1192             asterror(ast_ctx(self), "failed to allocate array values");
1193             return false;
1194         }
1195
1196         v = ir_function_create_local(func, self->name, vtype, param);
1197         if (!v) {
1198             asterror(ast_ctx(self), "ir_function_create_local failed");
1199             return false;
1200         }
1201         if (vtype == TYPE_FIELD)
1202             v->fieldtype = elemtype->next->expression.vtype;
1203         v->context = ast_ctx(self);
1204
1205         namelen = strlen(self->name);
1206         name    = (char*)mem_a(namelen + 16);
1207         strcpy(name, self->name);
1208
1209         self->ir_values[0] = v;
1210         for (ai = 1; ai < self->expression.count; ++ai) {
1211             snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1212             self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1213             if (!self->ir_values[ai]) {
1214                 asterror(ast_ctx(self), "ir_builder_create_global failed");
1215                 return false;
1216             }
1217             if (vtype == TYPE_FIELD)
1218                 self->ir_values[ai]->fieldtype = elemtype->next->expression.vtype;
1219             self->ir_values[ai]->context = ast_ctx(self);
1220         }
1221     }
1222     else
1223     {
1224         v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1225         if (!v)
1226             return false;
1227         if (self->expression.vtype == TYPE_FIELD)
1228             v->fieldtype = self->expression.next->expression.vtype;
1229         v->context = ast_ctx(self);
1230     }
1231
1232     /* A constant local... hmmm...
1233      * I suppose the IR will have to deal with this
1234      */
1235     if (self->isconst) {
1236         switch (self->expression.vtype)
1237         {
1238             case TYPE_FLOAT:
1239                 if (!ir_value_set_float(v, self->constval.vfloat))
1240                     goto error;
1241                 break;
1242             case TYPE_VECTOR:
1243                 if (!ir_value_set_vector(v, self->constval.vvec))
1244                     goto error;
1245                 break;
1246             case TYPE_STRING:
1247                 if (!ir_value_set_string(v, self->constval.vstring))
1248                     goto error;
1249                 break;
1250             default:
1251                 asterror(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1252                 break;
1253         }
1254     }
1255
1256     /* link us to the ir_value */
1257     self->ir_v = v;
1258
1259     if (self->setter) {
1260         if (!ast_global_codegen(self->setter, func->owner, false) ||
1261             !ast_function_codegen(self->setter->constval.vfunc, func->owner) ||
1262             !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1263             return false;
1264     }
1265     if (self->getter) {
1266         if (!ast_global_codegen(self->getter, func->owner, false) ||
1267             !ast_function_codegen(self->getter->constval.vfunc, func->owner) ||
1268             !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1269             return false;
1270     }
1271     return true;
1272
1273 error: /* clean up */
1274     ir_value_delete(v);
1275     return false;
1276 }
1277
1278 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1279 {
1280     ir_function *irf;
1281     ir_value    *dummy;
1282     ast_expression_common *ec;
1283     size_t    i;
1284
1285     irf = self->ir_func;
1286     if (!irf) {
1287         asterror(ast_ctx(self), "ast_function's related ast_value was not generated yet");
1288         return false;
1289     }
1290
1291     /* fill the parameter list */
1292     ec = &self->vtype->expression;
1293     for (i = 0; i < vec_size(ec->params); ++i)
1294     {
1295         vec_push(irf->params, ec->params[i]->expression.vtype);
1296         if (!self->builtin) {
1297             if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1298                 return false;
1299         }
1300     }
1301
1302     if (self->builtin) {
1303         irf->builtin = self->builtin;
1304         return true;
1305     }
1306
1307     if (!vec_size(self->blocks)) {
1308         asterror(ast_ctx(self), "function `%s` has no body", self->name);
1309         return false;
1310     }
1311
1312     self->curblock = ir_function_create_block(irf, "entry");
1313     if (!self->curblock) {
1314         asterror(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1315         return false;
1316     }
1317
1318     for (i = 0; i < vec_size(self->blocks); ++i) {
1319         ast_expression_codegen *gen = self->blocks[i]->expression.codegen;
1320         if (!(*gen)((ast_expression*)self->blocks[i], self, false, &dummy))
1321             return false;
1322     }
1323
1324     /* TODO: check return types */
1325     if (!self->curblock->is_return)
1326     {
1327         return ir_block_create_return(self->curblock, NULL);
1328         /* From now on the parser has to handle this situation */
1329 #if 0
1330         if (!self->vtype->expression.next ||
1331             self->vtype->expression.next->expression.vtype == TYPE_VOID)
1332         {
1333             return ir_block_create_return(self->curblock, NULL);
1334         }
1335         else
1336         {
1337             /* error("missing return"); */
1338             asterror(ast_ctx(self), "function `%s` missing return value", self->name);
1339             return false;
1340         }
1341 #endif
1342     }
1343     return true;
1344 }
1345
1346 /* Note, you will not see ast_block_codegen generate ir_blocks.
1347  * To the AST and the IR, blocks are 2 different things.
1348  * In the AST it represents a block of code, usually enclosed in
1349  * curly braces {...}.
1350  * While in the IR it represents a block in terms of control-flow.
1351  */
1352 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1353 {
1354     size_t i;
1355
1356     /* We don't use this
1357      * Note: an ast-representation using the comma-operator
1358      * of the form: (a, b, c) = x should not assign to c...
1359      */
1360     if (lvalue) {
1361         asterror(ast_ctx(self), "not an l-value (code-block)");
1362         return false;
1363     }
1364
1365     if (self->expression.outr) {
1366         *out = self->expression.outr;
1367         return true;
1368     }
1369
1370     /* output is NULL at first, we'll have each expression
1371      * assign to out output, thus, a comma-operator represention
1372      * using an ast_block will return the last generated value,
1373      * so: (b, c) + a  executed both b and c, and returns c,
1374      * which is then added to a.
1375      */
1376     *out = NULL;
1377
1378     /* generate locals */
1379     for (i = 0; i < vec_size(self->locals); ++i)
1380     {
1381         if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1382             if (opts_debug)
1383                 asterror(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1384             return false;
1385         }
1386     }
1387
1388     for (i = 0; i < vec_size(self->exprs); ++i)
1389     {
1390         ast_expression_codegen *gen = self->exprs[i]->expression.codegen;
1391         if (func->curblock->final) {
1392             asterror(ast_ctx(self->exprs[i]), "unreachable statement");
1393             return false;
1394         }
1395         if (!(*gen)(self->exprs[i], func, false, out))
1396             return false;
1397     }
1398
1399     self->expression.outr = *out;
1400
1401     return true;
1402 }
1403
1404 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1405 {
1406     ast_expression_codegen *cgen;
1407     ir_value *left, *right;
1408
1409     ast_value       *arr;
1410     ast_value       *idx;
1411     ast_array_index *ai = NULL;
1412
1413     if (lvalue && self->expression.outl) {
1414         *out = self->expression.outl;
1415         return true;
1416     }
1417
1418     if (!lvalue && self->expression.outr) {
1419         *out = self->expression.outr;
1420         return true;
1421     }
1422
1423     if (ast_istype(self->dest, ast_array_index))
1424     {
1425
1426         ai = (ast_array_index*)self->dest;
1427         idx = (ast_value*)ai->index;
1428
1429         if (ast_istype(ai->index, ast_value) && idx->isconst)
1430             ai = NULL;
1431     }
1432
1433     if (ai) {
1434         /* we need to call the setter */
1435         ir_value  *iridx, *funval;
1436         ir_instr  *call;
1437
1438         if (lvalue) {
1439             asterror(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1440             return false;
1441         }
1442
1443         arr = (ast_value*)ai->array;
1444         if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1445             asterror(ast_ctx(self), "value has no setter (%s)", arr->name);
1446             return false;
1447         }
1448
1449         cgen = idx->expression.codegen;
1450         if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1451             return false;
1452
1453         cgen = arr->setter->expression.codegen;
1454         if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
1455             return false;
1456
1457         cgen = self->source->expression.codegen;
1458         if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1459             return false;
1460
1461         call = ir_block_create_call(func->curblock, ast_function_label(func, "store"), funval);
1462         if (!call)
1463             return false;
1464         ir_call_param(call, iridx);
1465         ir_call_param(call, right);
1466         self->expression.outr = right;
1467     }
1468     else
1469     {
1470         /* regular code */
1471
1472         cgen = self->dest->expression.codegen;
1473         /* lvalue! */
1474         if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
1475             return false;
1476         self->expression.outl = left;
1477
1478         cgen = self->source->expression.codegen;
1479         /* rvalue! */
1480         if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1481             return false;
1482
1483         if (!ir_block_create_store_op(func->curblock, self->op, left, right))
1484             return false;
1485         self->expression.outr = right;
1486     }
1487
1488     /* Theoretically, an assinment returns its left side as an
1489      * lvalue, if we don't need an lvalue though, we return
1490      * the right side as an rvalue, otherwise we have to
1491      * somehow know whether or not we need to dereference the pointer
1492      * on the left side - that is: OP_LOAD if it was an address.
1493      * Also: in original QC we cannot OP_LOADP *anyway*.
1494      */
1495     *out = (lvalue ? left : right);
1496
1497     return true;
1498 }
1499
1500 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
1501 {
1502     ast_expression_codegen *cgen;
1503     ir_value *left, *right;
1504
1505     /* A binary operation cannot yield an l-value */
1506     if (lvalue) {
1507         asterror(ast_ctx(self), "not an l-value (binop)");
1508         return false;
1509     }
1510
1511     if (self->expression.outr) {
1512         *out = self->expression.outr;
1513         return true;
1514     }
1515
1516     if (OPTS_FLAG(SHORT_LOGIC) &&
1517         (self->op == INSTR_AND || self->op == INSTR_OR))
1518     {
1519         /* short circuit evaluation */
1520         ir_block *other, *merge;
1521         ir_block *from_left, *from_right;
1522         ir_instr *phi;
1523         size_t    merge_id;
1524         uint16_t  notop;
1525
1526         /* Note about casting to true boolean values:
1527          * We use a single NOT for sub expressions, and an
1528          * overall NOT at the end, and for that purpose swap
1529          * all the jump conditions in order for the NOT to get
1530          * doubled.
1531          * ie: (a && b) usually becomes (!!a ? !!b : !!a)
1532          * but we translate this to (!(!a ? !a : !b))
1533          */
1534
1535         merge_id = vec_size(func->blocks);
1536         merge = ir_function_create_block(func->ir_func, ast_function_label(func, "sce_merge"));
1537
1538         cgen = self->left->expression.codegen;
1539         if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
1540             return false;
1541         if (!OPTS_FLAG(PERL_LOGIC)) {
1542             notop = type_not_instr[left->vtype];
1543             if (notop == AINSTR_END) {
1544                 asterror(ast_ctx(self), "don't know how to cast to bool...");
1545                 return false;
1546             }
1547             left = ir_block_create_unary(func->curblock,
1548                                          ast_function_label(func, "sce_not"),
1549                                          notop,
1550                                          left);
1551         }
1552         from_left = func->curblock;
1553
1554         other = ir_function_create_block(func->ir_func, ast_function_label(func, "sce_other"));
1555         if ( !(self->op == INSTR_OR) != !OPTS_FLAG(PERL_LOGIC) ) {
1556             if (!ir_block_create_if(func->curblock, left, other, merge))
1557                 return false;
1558         } else {
1559             if (!ir_block_create_if(func->curblock, left, merge, other))
1560                 return false;
1561         }
1562         /* use the likely flag */
1563         vec_last(func->curblock->instr)->likely = true;
1564
1565         func->curblock = other;
1566         cgen = self->right->expression.codegen;
1567         if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
1568             return false;
1569         if (!OPTS_FLAG(PERL_LOGIC)) {
1570             notop = type_not_instr[right->vtype];
1571             if (notop == AINSTR_END) {
1572                 asterror(ast_ctx(self), "don't know how to cast to bool...");
1573                 return false;
1574             }
1575             right = ir_block_create_unary(func->curblock,
1576                                           ast_function_label(func, "sce_not"),
1577                                           notop,
1578                                           right);
1579         }
1580         from_right = func->curblock;
1581
1582         if (!ir_block_create_jump(func->curblock, merge))
1583             return false;
1584
1585         vec_remove(func->ir_func->blocks, merge_id, 1);
1586         vec_push(func->ir_func->blocks, merge);
1587
1588         func->curblock = merge;
1589         phi = ir_block_create_phi(func->curblock, ast_function_label(func, "sce_value"), TYPE_FLOAT);
1590         ir_phi_add(phi, from_left, left);
1591         ir_phi_add(phi, from_right, right);
1592         *out = ir_phi_value(phi);
1593         if (!OPTS_FLAG(PERL_LOGIC)) {
1594             notop = type_not_instr[(*out)->vtype];
1595             if (notop == AINSTR_END) {
1596                 asterror(ast_ctx(self), "don't know how to cast to bool...");
1597                 return false;
1598             }
1599             *out = ir_block_create_unary(func->curblock,
1600                                          ast_function_label(func, "sce_final_not"),
1601                                          notop,
1602                                          *out);
1603         }
1604         self->expression.outr = *out;
1605         return true;
1606     }
1607
1608     cgen = self->left->expression.codegen;
1609     if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
1610         return false;
1611
1612     cgen = self->right->expression.codegen;
1613     if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
1614         return false;
1615
1616     *out = ir_block_create_binop(func->curblock, ast_function_label(func, "bin"),
1617                                  self->op, left, right);
1618     if (!*out)
1619         return false;
1620     self->expression.outr = *out;
1621
1622     return true;
1623 }
1624
1625 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
1626 {
1627     ast_expression_codegen *cgen;
1628     ir_value *leftl, *leftr, *right, *bin;
1629
1630     if (lvalue && self->expression.outl) {
1631         *out = self->expression.outl;
1632         return true;
1633     }
1634
1635     if (!lvalue && self->expression.outr) {
1636         *out = self->expression.outr;
1637         return true;
1638     }
1639
1640     /* for a binstore we need both an lvalue and an rvalue for the left side */
1641     /* rvalue of destination! */
1642     cgen = self->dest->expression.codegen;
1643     if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
1644         return false;
1645
1646     /* source as rvalue only */
1647     cgen = self->source->expression.codegen;
1648     if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1649         return false;
1650
1651     /* now the binary */
1652     bin = ir_block_create_binop(func->curblock, ast_function_label(func, "binst"),
1653                                 self->opbin, leftr, right);
1654     self->expression.outr = bin;
1655
1656     /* now store them */
1657     cgen = self->dest->expression.codegen;
1658     /* lvalue of destination */
1659     if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
1660         return false;
1661     self->expression.outl = leftl;
1662
1663     if (!ir_block_create_store_op(func->curblock, self->opstore, leftl, bin))
1664         return false;
1665     self->expression.outr = bin;
1666
1667     /* Theoretically, an assinment returns its left side as an
1668      * lvalue, if we don't need an lvalue though, we return
1669      * the right side as an rvalue, otherwise we have to
1670      * somehow know whether or not we need to dereference the pointer
1671      * on the left side - that is: OP_LOAD if it was an address.
1672      * Also: in original QC we cannot OP_LOADP *anyway*.
1673      */
1674     *out = (lvalue ? leftl : bin);
1675
1676     return true;
1677 }
1678
1679 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
1680 {
1681     ast_expression_codegen *cgen;
1682     ir_value *operand;
1683
1684     /* An unary operation cannot yield an l-value */
1685     if (lvalue) {
1686         asterror(ast_ctx(self), "not an l-value (binop)");
1687         return false;
1688     }
1689
1690     if (self->expression.outr) {
1691         *out = self->expression.outr;
1692         return true;
1693     }
1694
1695     cgen = self->operand->expression.codegen;
1696     /* lvalue! */
1697     if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
1698         return false;
1699
1700     *out = ir_block_create_unary(func->curblock, ast_function_label(func, "unary"),
1701                                  self->op, operand);
1702     if (!*out)
1703         return false;
1704     self->expression.outr = *out;
1705
1706     return true;
1707 }
1708
1709 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
1710 {
1711     ast_expression_codegen *cgen;
1712     ir_value *operand;
1713
1714     /* In the context of a return operation, we don't actually return
1715      * anything...
1716      */
1717     if (lvalue) {
1718         asterror(ast_ctx(self), "return-expression is not an l-value");
1719         return false;
1720     }
1721
1722     if (self->expression.outr) {
1723         asterror(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
1724         return false;
1725     }
1726     self->expression.outr = (ir_value*)1;
1727
1728     if (self->operand) {
1729         cgen = self->operand->expression.codegen;
1730         /* lvalue! */
1731         if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
1732             return false;
1733
1734         if (!ir_block_create_return(func->curblock, operand))
1735             return false;
1736     } else {
1737         if (!ir_block_create_return(func->curblock, NULL))
1738             return false;
1739     }
1740
1741     return true;
1742 }
1743
1744 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
1745 {
1746     ast_expression_codegen *cgen;
1747     ir_value *ent, *field;
1748
1749     /* This function needs to take the 'lvalue' flag into account!
1750      * As lvalue we provide a field-pointer, as rvalue we provide the
1751      * value in a temp.
1752      */
1753
1754     if (lvalue && self->expression.outl) {
1755         *out = self->expression.outl;
1756         return true;
1757     }
1758
1759     if (!lvalue && self->expression.outr) {
1760         *out = self->expression.outr;
1761         return true;
1762     }
1763
1764     cgen = self->entity->expression.codegen;
1765     if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
1766         return false;
1767
1768     cgen = self->field->expression.codegen;
1769     if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
1770         return false;
1771
1772     if (lvalue) {
1773         /* address! */
1774         *out = ir_block_create_fieldaddress(func->curblock, ast_function_label(func, "efa"),
1775                                             ent, field);
1776     } else {
1777         *out = ir_block_create_load_from_ent(func->curblock, ast_function_label(func, "efv"),
1778                                              ent, field, self->expression.vtype);
1779     }
1780     if (!*out) {
1781         asterror(ast_ctx(self), "failed to create %s instruction (output type %s)",
1782                  (lvalue ? "ADDRESS" : "FIELD"),
1783                  type_name[self->expression.vtype]);
1784         return false;
1785     }
1786
1787     if (lvalue)
1788         self->expression.outl = *out;
1789     else
1790         self->expression.outr = *out;
1791
1792     /* Hm that should be it... */
1793     return true;
1794 }
1795
1796 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
1797 {
1798     ast_expression_codegen *cgen;
1799     ir_value *vec;
1800
1801     /* in QC this is always an lvalue */
1802     (void)lvalue;
1803     if (self->expression.outl) {
1804         *out = self->expression.outl;
1805         return true;
1806     }
1807
1808     cgen = self->owner->expression.codegen;
1809     if (!(*cgen)((ast_expression*)(self->owner), func, true, &vec))
1810         return false;
1811
1812     if (vec->vtype != TYPE_VECTOR &&
1813         !(vec->vtype == TYPE_FIELD && self->owner->expression.next->expression.vtype == TYPE_VECTOR))
1814     {
1815         return false;
1816     }
1817
1818     *out = ir_value_vector_member(vec, self->field);
1819     self->expression.outl = *out;
1820
1821     return (*out != NULL);
1822 }
1823
1824 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
1825 {
1826     ast_value *arr;
1827     ast_value *idx;
1828
1829     if (!lvalue && self->expression.outr) {
1830         *out = self->expression.outr;
1831     }
1832     if (lvalue && self->expression.outl) {
1833         *out = self->expression.outl;
1834     }
1835
1836     if (!ast_istype(self->array, ast_value)) {
1837         asterror(ast_ctx(self), "array indexing this way is not supported");
1838         /* note this would actually be pointer indexing because the left side is
1839          * not an actual array but (hopefully) an indexable expression.
1840          * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
1841          * support this path will be filled.
1842          */
1843         return false;
1844     }
1845
1846     arr = (ast_value*)self->array;
1847     idx = (ast_value*)self->index;
1848
1849     if (!ast_istype(self->index, ast_value) || !idx->isconst) {
1850         /* Time to use accessor functions */
1851         ast_expression_codegen *cgen;
1852         ir_value               *iridx, *funval;
1853         ir_instr               *call;
1854
1855         if (lvalue) {
1856             asterror(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
1857             return false;
1858         }
1859
1860         if (!arr->getter) {
1861             asterror(ast_ctx(self), "value has no getter, don't know how to index it");
1862             return false;
1863         }
1864
1865         cgen = self->index->expression.codegen;
1866         if (!(*cgen)((ast_expression*)(self->index), func, true, &iridx))
1867             return false;
1868
1869         cgen = arr->getter->expression.codegen;
1870         if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
1871             return false;
1872
1873         call = ir_block_create_call(func->curblock, ast_function_label(func, "fetch"), funval);
1874         if (!call)
1875             return false;
1876         ir_call_param(call, iridx);
1877
1878         *out = ir_call_value(call);
1879         self->expression.outr = *out;
1880         return true;
1881     }
1882
1883     if (idx->expression.vtype == TYPE_FLOAT)
1884         *out = arr->ir_values[(int)idx->constval.vfloat];
1885     else if (idx->expression.vtype == TYPE_INTEGER)
1886         *out = arr->ir_values[idx->constval.vint];
1887     else {
1888         asterror(ast_ctx(self), "array indexing here needs an integer constant");
1889         return false;
1890     }
1891     return true;
1892 }
1893
1894 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
1895 {
1896     ast_expression_codegen *cgen;
1897
1898     ir_value *condval;
1899     ir_value *dummy;
1900
1901     ir_block *cond = func->curblock;
1902     ir_block *ontrue;
1903     ir_block *onfalse;
1904     ir_block *ontrue_endblock = NULL;
1905     ir_block *onfalse_endblock = NULL;
1906     ir_block *merge;
1907
1908     /* We don't output any value, thus also don't care about r/lvalue */
1909     (void)out;
1910     (void)lvalue;
1911
1912     if (self->expression.outr) {
1913         asterror(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
1914         return false;
1915     }
1916     self->expression.outr = (ir_value*)1;
1917
1918     /* generate the condition */
1919     func->curblock = cond;
1920     cgen = self->cond->expression.codegen;
1921     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
1922         return false;
1923
1924     /* on-true path */
1925
1926     if (self->on_true) {
1927         /* create on-true block */
1928         ontrue = ir_function_create_block(func->ir_func, ast_function_label(func, "ontrue"));
1929         if (!ontrue)
1930             return false;
1931
1932         /* enter the block */
1933         func->curblock = ontrue;
1934
1935         /* generate */
1936         cgen = self->on_true->expression.codegen;
1937         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
1938             return false;
1939
1940         /* we now need to work from the current endpoint */
1941         ontrue_endblock = func->curblock;
1942     } else
1943         ontrue = NULL;
1944
1945     /* on-false path */
1946     if (self->on_false) {
1947         /* create on-false block */
1948         onfalse = ir_function_create_block(func->ir_func, ast_function_label(func, "onfalse"));
1949         if (!onfalse)
1950             return false;
1951
1952         /* enter the block */
1953         func->curblock = onfalse;
1954
1955         /* generate */
1956         cgen = self->on_false->expression.codegen;
1957         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
1958             return false;
1959
1960         /* we now need to work from the current endpoint */
1961         onfalse_endblock = func->curblock;
1962     } else
1963         onfalse = NULL;
1964
1965     /* Merge block were they all merge in to */
1966     merge = ir_function_create_block(func->ir_func, ast_function_label(func, "endif"));
1967     if (!merge)
1968         return false;
1969
1970     /* add jumps ot the merge block */
1971     if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, merge))
1972         return false;
1973     if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, merge))
1974         return false;
1975
1976     /* we create the if here, that way all blocks are ordered :)
1977      */
1978     if (!ir_block_create_if(cond, condval,
1979                             (ontrue  ? ontrue  : merge),
1980                             (onfalse ? onfalse : merge)))
1981     {
1982         return false;
1983     }
1984
1985     /* Now enter the merge block */
1986     func->curblock = merge;
1987
1988     return true;
1989 }
1990
1991 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
1992 {
1993     ast_expression_codegen *cgen;
1994
1995     ir_value *condval;
1996     ir_value *trueval, *falseval;
1997     ir_instr *phi;
1998
1999     ir_block *cond = func->curblock;
2000     ir_block *ontrue;
2001     ir_block *onfalse;
2002     ir_block *merge;
2003
2004     /* Ternary can never create an lvalue... */
2005     if (lvalue)
2006         return false;
2007
2008     /* In theory it shouldn't be possible to pass through a node twice, but
2009      * in case we add any kind of optimization pass for the AST itself, it
2010      * may still happen, thus we remember a created ir_value and simply return one
2011      * if it already exists.
2012      */
2013     if (self->phi_out) {
2014         *out = self->phi_out;
2015         return true;
2016     }
2017
2018     /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2019
2020     /* generate the condition */
2021     func->curblock = cond;
2022     cgen = self->cond->expression.codegen;
2023     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2024         return false;
2025
2026     /* create on-true block */
2027     ontrue = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_T"));
2028     if (!ontrue)
2029         return false;
2030     else
2031     {
2032         /* enter the block */
2033         func->curblock = ontrue;
2034
2035         /* generate */
2036         cgen = self->on_true->expression.codegen;
2037         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2038             return false;
2039     }
2040
2041     /* create on-false block */
2042     onfalse = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_F"));
2043     if (!onfalse)
2044         return false;
2045     else
2046     {
2047         /* enter the block */
2048         func->curblock = onfalse;
2049
2050         /* generate */
2051         cgen = self->on_false->expression.codegen;
2052         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2053             return false;
2054     }
2055
2056     /* create merge block */
2057     merge = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_out"));
2058     if (!merge)
2059         return false;
2060     /* jump to merge block */
2061     if (!ir_block_create_jump(ontrue, merge))
2062         return false;
2063     if (!ir_block_create_jump(onfalse, merge))
2064         return false;
2065
2066     /* create if instruction */
2067     if (!ir_block_create_if(cond, condval, ontrue, onfalse))
2068         return false;
2069
2070     /* Now enter the merge block */
2071     func->curblock = merge;
2072
2073     /* Here, now, we need a PHI node
2074      * but first some sanity checking...
2075      */
2076     if (trueval->vtype != falseval->vtype) {
2077         /* error("ternary with different types on the two sides"); */
2078         return false;
2079     }
2080
2081     /* create PHI */
2082     phi = ir_block_create_phi(merge, ast_function_label(func, "phi"), trueval->vtype);
2083     if (!phi)
2084         return false;
2085     ir_phi_add(phi, ontrue,  trueval);
2086     ir_phi_add(phi, onfalse, falseval);
2087
2088     self->phi_out = ir_phi_value(phi);
2089     *out = self->phi_out;
2090
2091     return true;
2092 }
2093
2094 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2095 {
2096     ast_expression_codegen *cgen;
2097
2098     ir_value *dummy      = NULL;
2099     ir_value *precond    = NULL;
2100     ir_value *postcond   = NULL;
2101
2102     /* Since we insert some jumps "late" so we have blocks
2103      * ordered "nicely", we need to keep track of the actual end-blocks
2104      * of expressions to add the jumps to.
2105      */
2106     ir_block *bbody      = NULL, *end_bbody      = NULL;
2107     ir_block *bprecond   = NULL, *end_bprecond   = NULL;
2108     ir_block *bpostcond  = NULL, *end_bpostcond  = NULL;
2109     ir_block *bincrement = NULL, *end_bincrement = NULL;
2110     ir_block *bout       = NULL, *bin            = NULL;
2111
2112     /* let's at least move the outgoing block to the end */
2113     size_t    bout_id;
2114
2115     /* 'break' and 'continue' need to be able to find the right blocks */
2116     ir_block *bcontinue     = NULL;
2117     ir_block *bbreak        = NULL;
2118
2119     ir_block *old_bcontinue = NULL;
2120     ir_block *old_bbreak    = NULL;
2121
2122     ir_block *tmpblock      = NULL;
2123
2124     (void)lvalue;
2125     (void)out;
2126
2127     if (self->expression.outr) {
2128         asterror(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2129         return false;
2130     }
2131     self->expression.outr = (ir_value*)1;
2132
2133     /* NOTE:
2134      * Should we ever need some kind of block ordering, better make this function
2135      * move blocks around than write a block ordering algorithm later... after all
2136      * the ast and ir should work together, not against each other.
2137      */
2138
2139     /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2140      * anyway if for example it contains a ternary.
2141      */
2142     if (self->initexpr)
2143     {
2144         cgen = self->initexpr->expression.codegen;
2145         if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2146             return false;
2147     }
2148
2149     /* Store the block from which we enter this chaos */
2150     bin = func->curblock;
2151
2152     /* The pre-loop condition needs its own block since we
2153      * need to be able to jump to the start of that expression.
2154      */
2155     if (self->precond)
2156     {
2157         bprecond = ir_function_create_block(func->ir_func, ast_function_label(func, "pre_loop_cond"));
2158         if (!bprecond)
2159             return false;
2160
2161         /* the pre-loop-condition the least important place to 'continue' at */
2162         bcontinue = bprecond;
2163
2164         /* enter */
2165         func->curblock = bprecond;
2166
2167         /* generate */
2168         cgen = self->precond->expression.codegen;
2169         if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2170             return false;
2171
2172         end_bprecond = func->curblock;
2173     } else {
2174         bprecond = end_bprecond = NULL;
2175     }
2176
2177     /* Now the next blocks won't be ordered nicely, but we need to
2178      * generate them this early for 'break' and 'continue'.
2179      */
2180     if (self->increment) {
2181         bincrement = ir_function_create_block(func->ir_func, ast_function_label(func, "loop_increment"));
2182         if (!bincrement)
2183             return false;
2184         bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2185     } else {
2186         bincrement = end_bincrement = NULL;
2187     }
2188
2189     if (self->postcond) {
2190         bpostcond = ir_function_create_block(func->ir_func, ast_function_label(func, "post_loop_cond"));
2191         if (!bpostcond)
2192             return false;
2193         bcontinue = bpostcond; /* postcond comes before the increment */
2194     } else {
2195         bpostcond = end_bpostcond = NULL;
2196     }
2197
2198     bout_id = vec_size(func->ir_func->blocks);
2199     bout = ir_function_create_block(func->ir_func, ast_function_label(func, "after_loop"));
2200     if (!bout)
2201         return false;
2202     bbreak = bout;
2203
2204     /* The loop body... */
2205     if (self->body)
2206     {
2207         bbody = ir_function_create_block(func->ir_func, ast_function_label(func, "loop_body"));
2208         if (!bbody)
2209             return false;
2210
2211         /* enter */
2212         func->curblock = bbody;
2213
2214         old_bbreak          = func->breakblock;
2215         old_bcontinue       = func->continueblock;
2216         func->breakblock    = bbreak;
2217         func->continueblock = bcontinue;
2218
2219         /* generate */
2220         cgen = self->body->expression.codegen;
2221         if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2222             return false;
2223
2224         end_bbody = func->curblock;
2225         func->breakblock    = old_bbreak;
2226         func->continueblock = old_bcontinue;
2227     }
2228
2229     /* post-loop-condition */
2230     if (self->postcond)
2231     {
2232         /* enter */
2233         func->curblock = bpostcond;
2234
2235         /* generate */
2236         cgen = self->postcond->expression.codegen;
2237         if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2238             return false;
2239
2240         end_bpostcond = func->curblock;
2241     }
2242
2243     /* The incrementor */
2244     if (self->increment)
2245     {
2246         /* enter */
2247         func->curblock = bincrement;
2248
2249         /* generate */
2250         cgen = self->increment->expression.codegen;
2251         if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2252             return false;
2253
2254         end_bincrement = func->curblock;
2255     }
2256
2257     /* In any case now, we continue from the outgoing block */
2258     func->curblock = bout;
2259
2260     /* Now all blocks are in place */
2261     /* From 'bin' we jump to whatever comes first */
2262     if      (bprecond)   tmpblock = bprecond;
2263     else if (bbody)      tmpblock = bbody;
2264     else if (bpostcond)  tmpblock = bpostcond;
2265     else                 tmpblock = bout;
2266     if (!ir_block_create_jump(bin, tmpblock))
2267         return false;
2268
2269     /* From precond */
2270     if (bprecond)
2271     {
2272         ir_block *ontrue, *onfalse;
2273         if      (bbody)      ontrue = bbody;
2274         else if (bincrement) ontrue = bincrement;
2275         else if (bpostcond)  ontrue = bpostcond;
2276         else                 ontrue = bprecond;
2277         onfalse = bout;
2278         if (!ir_block_create_if(end_bprecond, precond, ontrue, onfalse))
2279             return false;
2280     }
2281
2282     /* from body */
2283     if (bbody)
2284     {
2285         if      (bincrement) tmpblock = bincrement;
2286         else if (bpostcond)  tmpblock = bpostcond;
2287         else if (bprecond)   tmpblock = bprecond;
2288         else                 tmpblock = bout;
2289         if (!end_bbody->final && !ir_block_create_jump(end_bbody, tmpblock))
2290             return false;
2291     }
2292
2293     /* from increment */
2294     if (bincrement)
2295     {
2296         if      (bpostcond)  tmpblock = bpostcond;
2297         else if (bprecond)   tmpblock = bprecond;
2298         else if (bbody)      tmpblock = bbody;
2299         else                 tmpblock = bout;
2300         if (!ir_block_create_jump(end_bincrement, tmpblock))
2301             return false;
2302     }
2303
2304     /* from postcond */
2305     if (bpostcond)
2306     {
2307         ir_block *ontrue, *onfalse;
2308         if      (bprecond)   ontrue = bprecond;
2309         else if (bbody)      ontrue = bbody;
2310         else if (bincrement) ontrue = bincrement;
2311         else                 ontrue = bpostcond;
2312         onfalse = bout;
2313         if (!ir_block_create_if(end_bpostcond, postcond, ontrue, onfalse))
2314             return false;
2315     }
2316
2317     /* Move 'bout' to the end */
2318     vec_remove(func->ir_func->blocks, bout_id, 1);
2319     vec_push(func->ir_func->blocks, bout);
2320
2321     return true;
2322 }
2323
2324 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
2325 {
2326     ir_block *target;
2327
2328     if (lvalue) {
2329         asterror(ast_ctx(self), "break/continue expression is not an l-value");
2330         return false;
2331     }
2332
2333     if (self->expression.outr) {
2334         asterror(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
2335         return false;
2336     }
2337     self->expression.outr = (ir_value*)1;
2338
2339     if (self->is_continue)
2340         target = func->continueblock;
2341     else
2342         target = func->breakblock;
2343
2344     if (!ir_block_create_jump(func->curblock, target))
2345         return false;
2346     return true;
2347 }
2348
2349 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
2350 {
2351     ast_expression_codegen *cgen;
2352
2353     ast_switch_case *def_case  = NULL;
2354     ir_block        *def_bfall = NULL;
2355
2356     ir_value *dummy     = NULL;
2357     ir_value *irop      = NULL;
2358     ir_block *old_break = NULL;
2359     ir_block *bout      = NULL;
2360     ir_block *bfall     = NULL;
2361     size_t    bout_id;
2362     size_t    c;
2363
2364     char      typestr[1024];
2365     uint16_t  cmpinstr;
2366
2367     if (lvalue) {
2368         asterror(ast_ctx(self), "switch expression is not an l-value");
2369         return false;
2370     }
2371
2372     if (self->expression.outr) {
2373         asterror(ast_ctx(self), "internal error: ast_switch cannot be reused!");
2374         return false;
2375     }
2376     self->expression.outr = (ir_value*)1;
2377
2378     (void)lvalue;
2379     (void)out;
2380
2381     cgen = self->operand->expression.codegen;
2382     if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
2383         return false;
2384
2385     if (!vec_size(self->cases))
2386         return true;
2387
2388     cmpinstr = type_eq_instr[irop->vtype];
2389     if (cmpinstr >= AINSTR_END) {
2390         ast_type_to_string(self->operand, typestr, sizeof(typestr));
2391         asterror(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
2392         return false;
2393     }
2394
2395     bout_id = vec_size(func->ir_func->blocks);
2396     bout = ir_function_create_block(func->ir_func, ast_function_label(func, "after_switch"));
2397     if (!bout)
2398         return false;
2399
2400     /* setup the break block */
2401     old_break        = func->breakblock;
2402     func->breakblock = bout;
2403
2404     /* Now create all cases */
2405     for (c = 0; c < vec_size(self->cases); ++c) {
2406         ir_value *cond, *val;
2407         ir_block *bcase, *bnot;
2408         size_t bnot_id;
2409
2410         ast_switch_case *swcase = &self->cases[c];
2411
2412         if (swcase->value) {
2413             /* A regular case */
2414             /* generate the condition operand */
2415             cgen = swcase->value->expression.codegen;
2416             if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
2417                 return false;
2418             /* generate the condition */
2419             cond = ir_block_create_binop(func->curblock, ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
2420             if (!cond)
2421                 return false;
2422
2423             bcase = ir_function_create_block(func->ir_func, ast_function_label(func, "case"));
2424             bnot_id = vec_size(func->ir_func->blocks);
2425             bnot = ir_function_create_block(func->ir_func, ast_function_label(func, "not_case"));
2426             if (!bcase || !bnot)
2427                 return false;
2428             if (!ir_block_create_if(func->curblock, cond, bcase, bnot))
2429                 return false;
2430
2431             /* Make the previous case-end fall through */
2432             if (bfall && !bfall->final) {
2433                 if (!ir_block_create_jump(bfall, bcase))
2434                     return false;
2435             }
2436
2437             /* enter the case */
2438             func->curblock = bcase;
2439             cgen = swcase->code->expression.codegen;
2440             if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
2441                 return false;
2442
2443             /* remember this block to fall through from */
2444             bfall = func->curblock;
2445
2446             /* enter the else and move it down */
2447             func->curblock = bnot;
2448             vec_remove(func->ir_func->blocks, bnot_id, 1);
2449             vec_push(func->ir_func->blocks, bnot);
2450         } else {
2451             /* The default case */
2452             /* Remember where to fall through from: */
2453             def_bfall = bfall;
2454             bfall     = NULL;
2455             /* remember which case it was */
2456             def_case  = swcase;
2457         }
2458     }
2459
2460     /* Jump from the last bnot to bout */
2461     if (bfall && !bfall->final && !ir_block_create_jump(bfall, bout)) {
2462         /*
2463         astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
2464         */
2465         return false;
2466     }
2467
2468     /* If there was a default case, put it down here */
2469     if (def_case) {
2470         ir_block *bcase;
2471
2472         /* No need to create an extra block */
2473         bcase = func->curblock;
2474
2475         /* Insert the fallthrough jump */
2476         if (def_bfall && !def_bfall->final) {
2477             if (!ir_block_create_jump(def_bfall, bcase))
2478                 return false;
2479         }
2480
2481         /* Now generate the default code */
2482         cgen = def_case->code->expression.codegen;
2483         if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
2484             return false;
2485     }
2486
2487     /* Jump from the last bnot to bout */
2488     if (!func->curblock->final && !ir_block_create_jump(func->curblock, bout))
2489         return false;
2490     /* enter the outgoing block */
2491     func->curblock = bout;
2492
2493     /* restore the break block */
2494     func->breakblock = old_break;
2495
2496     /* Move 'bout' to the end, it's nicer */
2497     vec_remove(func->ir_func->blocks, bout_id, 1);
2498     vec_push(func->ir_func->blocks, bout);
2499
2500     return true;
2501 }
2502
2503 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
2504 {
2505     ast_expression_codegen *cgen;
2506     ir_value              **params;
2507     ir_instr               *callinstr;
2508     size_t i;
2509
2510     ir_value *funval = NULL;
2511
2512     /* return values are never lvalues */
2513     if (lvalue) {
2514         asterror(ast_ctx(self), "not an l-value (function call)");
2515         return false;
2516     }
2517
2518     if (self->expression.outr) {
2519         *out = self->expression.outr;
2520         return true;
2521     }
2522
2523     cgen = self->func->expression.codegen;
2524     if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
2525         return false;
2526     if (!funval)
2527         return false;
2528
2529     params = NULL;
2530
2531     /* parameters */
2532     for (i = 0; i < vec_size(self->params); ++i)
2533     {
2534         ir_value *param;
2535         ast_expression *expr = self->params[i];
2536
2537         cgen = expr->expression.codegen;
2538         if (!(*cgen)(expr, func, false, &param))
2539             goto error;
2540         if (!param)
2541             goto error;
2542         vec_push(params, param);
2543     }
2544
2545     callinstr = ir_block_create_call(func->curblock, ast_function_label(func, "call"), funval);
2546     if (!callinstr)
2547         goto error;
2548
2549     for (i = 0; i < vec_size(params); ++i) {
2550         ir_call_param(callinstr, params[i]);
2551     }
2552
2553     *out = ir_call_value(callinstr);
2554     self->expression.outr = *out;
2555
2556     vec_free(params);
2557     return true;
2558 error:
2559     vec_free(params);
2560     return false;
2561 }