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