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