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