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