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