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