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