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