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