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