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