]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ast.c
Constant fold intrinsics if their arguments are constant. TODO: reference count intri...
[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         /* The function is filled later on ast_function_codegen... */
1389         return true;
1390     }
1391
1392     if (isfield && self->expression.vtype == TYPE_FIELD) {
1393         ast_expression *fieldtype = self->expression.next;
1394
1395         if (self->hasvalue) {
1396             compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1397             goto error;
1398         }
1399
1400         if (fieldtype->vtype == TYPE_ARRAY) {
1401             size_t ai;
1402             char   *name;
1403             size_t  namelen;
1404
1405             ast_expression *elemtype;
1406             int             vtype;
1407             ast_value      *array = (ast_value*)fieldtype;
1408
1409             if (!ast_istype(fieldtype, ast_value)) {
1410                 compile_error(ast_ctx(self), "internal error: ast_value required");
1411                 return false;
1412             }
1413
1414             if (!check_array(self, array))
1415                 return false;
1416
1417             elemtype = array->expression.next;
1418             vtype = elemtype->vtype;
1419
1420             v = ir_builder_create_field(ir, self->name, vtype);
1421             if (!v) {
1422                 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1423                 return false;
1424             }
1425             v->context = ast_ctx(self);
1426             v->unique_life = true;
1427             v->locked      = true;
1428             array->ir_v = self->ir_v = v;
1429             if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1430                 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1431
1432             namelen = strlen(self->name);
1433             name    = (char*)mem_a(namelen + 16);
1434             util_strncpy(name, self->name, namelen);
1435
1436             array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1437             array->ir_values[0] = v;
1438             for (ai = 1; ai < array->expression.count; ++ai) {
1439                 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1440                 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1441                 if (!array->ir_values[ai]) {
1442                     mem_d(name);
1443                     compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1444                     return false;
1445                 }
1446                 array->ir_values[ai]->context = ast_ctx(self);
1447                 array->ir_values[ai]->unique_life = true;
1448                 array->ir_values[ai]->locked      = true;
1449                 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1450                     self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1451             }
1452             mem_d(name);
1453         }
1454         else
1455         {
1456             v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1457             if (!v)
1458                 return false;
1459             v->context = ast_ctx(self);
1460             self->ir_v = v;
1461             if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1462                 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1463         }
1464         return true;
1465     }
1466
1467     if (self->expression.vtype == TYPE_ARRAY) {
1468         size_t ai;
1469         char   *name;
1470         size_t  namelen;
1471
1472         ast_expression *elemtype = self->expression.next;
1473         int vtype = elemtype->vtype;
1474
1475         if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1476             compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1477             return false;
1478         }
1479
1480         /* same as with field arrays */
1481         if (!check_array(self, self))
1482             return false;
1483
1484         v = ir_builder_create_global(ir, self->name, vtype);
1485         if (!v) {
1486             compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1487             return false;
1488         }
1489         v->context = ast_ctx(self);
1490         v->unique_life = true;
1491         v->locked      = true;
1492         if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1493             v->flags |= IR_FLAG_INCLUDE_DEF;
1494
1495         namelen = strlen(self->name);
1496         name    = (char*)mem_a(namelen + 16);
1497         util_strncpy(name, self->name, namelen);
1498
1499         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1500         self->ir_values[0] = v;
1501         for (ai = 1; ai < self->expression.count; ++ai) {
1502             util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1503             self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1504             if (!self->ir_values[ai]) {
1505                 mem_d(name);
1506                 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1507                 return false;
1508             }
1509             self->ir_values[ai]->context = ast_ctx(self);
1510             self->ir_values[ai]->unique_life = true;
1511             self->ir_values[ai]->locked      = true;
1512             if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1513                 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1514         }
1515         mem_d(name);
1516     }
1517     else
1518     {
1519         /* Arrays don't do this since there's no "array" value which spans across the
1520          * whole thing.
1521          */
1522         v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1523         if (!v) {
1524             compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1525             return false;
1526         }
1527         codegen_output_type(self, v);
1528         v->context = ast_ctx(self);
1529     }
1530
1531     /* link us to the ir_value */
1532     v->cvq = self->cvq;
1533     self->ir_v = v;
1534     if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1535         self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1536
1537     /* initialize */
1538     if (self->hasvalue) {
1539         switch (self->expression.vtype)
1540         {
1541             case TYPE_FLOAT:
1542                 if (!ir_value_set_float(v, self->constval.vfloat))
1543                     goto error;
1544                 break;
1545             case TYPE_VECTOR:
1546                 if (!ir_value_set_vector(v, self->constval.vvec))
1547                     goto error;
1548                 break;
1549             case TYPE_STRING:
1550                 if (!ir_value_set_string(v, self->constval.vstring))
1551                     goto error;
1552                 break;
1553             case TYPE_ARRAY:
1554                 ast_global_array_set(self);
1555                 break;
1556             case TYPE_FUNCTION:
1557                 compile_error(ast_ctx(self), "global of type function not properly generated");
1558                 goto error;
1559                 /* Cannot generate an IR value for a function,
1560                  * need a pointer pointing to a function rather.
1561                  */
1562             case TYPE_FIELD:
1563                 if (!self->constval.vfield) {
1564                     compile_error(ast_ctx(self), "field constant without vfield set");
1565                     goto error;
1566                 }
1567                 if (!self->constval.vfield->ir_v) {
1568                     compile_error(ast_ctx(self), "field constant generated before its field");
1569                     goto error;
1570                 }
1571                 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1572                     goto error;
1573                 break;
1574             default:
1575                 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1576                 break;
1577         }
1578     }
1579     return true;
1580
1581 error: /* clean up */
1582     if(v) ir_value_delete(v);
1583     return false;
1584 }
1585
1586 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1587 {
1588     ir_value *v = NULL;
1589
1590     if (self->expression.vtype == TYPE_NIL) {
1591         compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1592         return false;
1593     }
1594
1595     if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1596     {
1597         /* Do we allow local functions? I think not...
1598          * this is NOT a function pointer atm.
1599          */
1600         return false;
1601     }
1602
1603     if (self->expression.vtype == TYPE_ARRAY) {
1604         size_t ai;
1605         char   *name;
1606         size_t  namelen;
1607
1608         ast_expression *elemtype = self->expression.next;
1609         int vtype = elemtype->vtype;
1610
1611         func->flags |= IR_FLAG_HAS_ARRAYS;
1612
1613         if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1614             compile_error(ast_ctx(self), "array-parameters are not supported");
1615             return false;
1616         }
1617
1618         /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1619         if (!check_array(self, self))
1620             return false;
1621
1622         self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1623         if (!self->ir_values) {
1624             compile_error(ast_ctx(self), "failed to allocate array values");
1625             return false;
1626         }
1627
1628         v = ir_function_create_local(func, self->name, vtype, param);
1629         if (!v) {
1630             compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1631             return false;
1632         }
1633         v->context = ast_ctx(self);
1634         v->unique_life = true;
1635         v->locked      = true;
1636
1637         namelen = strlen(self->name);
1638         name    = (char*)mem_a(namelen + 16);
1639         util_strncpy(name, self->name, namelen);
1640
1641         self->ir_values[0] = v;
1642         for (ai = 1; ai < self->expression.count; ++ai) {
1643             util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1644             self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1645             if (!self->ir_values[ai]) {
1646                 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1647                 return false;
1648             }
1649             self->ir_values[ai]->context = ast_ctx(self);
1650             self->ir_values[ai]->unique_life = true;
1651             self->ir_values[ai]->locked      = true;
1652         }
1653         mem_d(name);
1654     }
1655     else
1656     {
1657         v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1658         if (!v)
1659             return false;
1660         codegen_output_type(self, v);
1661         v->context = ast_ctx(self);
1662     }
1663
1664     /* A constant local... hmmm...
1665      * I suppose the IR will have to deal with this
1666      */
1667     if (self->hasvalue) {
1668         switch (self->expression.vtype)
1669         {
1670             case TYPE_FLOAT:
1671                 if (!ir_value_set_float(v, self->constval.vfloat))
1672                     goto error;
1673                 break;
1674             case TYPE_VECTOR:
1675                 if (!ir_value_set_vector(v, self->constval.vvec))
1676                     goto error;
1677                 break;
1678             case TYPE_STRING:
1679                 if (!ir_value_set_string(v, self->constval.vstring))
1680                     goto error;
1681                 break;
1682             default:
1683                 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1684                 break;
1685         }
1686     }
1687
1688     /* link us to the ir_value */
1689     v->cvq = self->cvq;
1690     self->ir_v = v;
1691
1692     if (!ast_generate_accessors(self, func->owner))
1693         return false;
1694     return true;
1695
1696 error: /* clean up */
1697     ir_value_delete(v);
1698     return false;
1699 }
1700
1701 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1702 {
1703     size_t i;
1704     bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1705     if (!self->setter || !self->getter)
1706         return true;
1707     for (i = 0; i < self->expression.count; ++i) {
1708         if (!self->ir_values) {
1709             compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1710             return false;
1711         }
1712         if (!self->ir_values[i]) {
1713             compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1714             return false;
1715         }
1716         if (self->ir_values[i]->life) {
1717             compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1718             return false;
1719         }
1720     }
1721
1722     opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1723     if (self->setter) {
1724         if (!ast_global_codegen  (self->setter, ir, false) ||
1725             !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1726             !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1727         {
1728             compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1729             opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1730             return false;
1731         }
1732     }
1733     if (self->getter) {
1734         if (!ast_global_codegen  (self->getter, ir, false) ||
1735             !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1736             !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1737         {
1738             compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1739             opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1740             return false;
1741         }
1742     }
1743     for (i = 0; i < self->expression.count; ++i) {
1744         vec_free(self->ir_values[i]->life);
1745     }
1746     opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1747     return true;
1748 }
1749
1750 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1751 {
1752     ir_function *irf;
1753     ir_value    *dummy;
1754     ast_expression         *ec;
1755     ast_expression_codegen *cgen;
1756     size_t    i;
1757
1758     (void)ir;
1759
1760     irf = self->ir_func;
1761     if (!irf) {
1762         compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1763         return false;
1764     }
1765
1766     /* fill the parameter list */
1767     ec = &self->vtype->expression;
1768     for (i = 0; i < vec_size(ec->params); ++i)
1769     {
1770         if (ec->params[i]->expression.vtype == TYPE_FIELD)
1771             vec_push(irf->params, ec->params[i]->expression.next->vtype);
1772         else
1773             vec_push(irf->params, ec->params[i]->expression.vtype);
1774         if (!self->builtin) {
1775             if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1776                 return false;
1777         }
1778     }
1779
1780     if (self->varargs) {
1781         if (!ast_local_codegen(self->varargs, self->ir_func, true))
1782             return false;
1783         irf->max_varargs = self->varargs->expression.count;
1784     }
1785
1786     if (self->builtin) {
1787         irf->builtin = self->builtin;
1788         return true;
1789     }
1790
1791     /* have a local return value variable? */
1792     if (self->return_value) {
1793         if (!ast_local_codegen(self->return_value, self->ir_func, false))
1794             return false;
1795     }
1796
1797     if (!vec_size(self->blocks)) {
1798         compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1799         return false;
1800     }
1801
1802     irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1803     if (!self->curblock) {
1804         compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1805         return false;
1806     }
1807
1808     if (self->argc) {
1809         ir_value *va_count;
1810         ir_value *fixed;
1811         ir_value *sub;
1812         if (!ast_local_codegen(self->argc, self->ir_func, true))
1813             return false;
1814         cgen = self->argc->expression.codegen;
1815         if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1816             return false;
1817         cgen = self->fixedparams->expression.codegen;
1818         if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1819             return false;
1820         sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1821                                     ast_function_label(self, "va_count"), INSTR_SUB_F,
1822                                     ir_builder_get_va_count(ir), fixed);
1823         if (!sub)
1824             return false;
1825         if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1826                                       va_count, sub))
1827         {
1828             return false;
1829         }
1830     }
1831
1832     for (i = 0; i < vec_size(self->blocks); ++i) {
1833         cgen = self->blocks[i]->expression.codegen;
1834         if (!(*cgen)((ast_expression*)self->blocks[i], self, false, &dummy))
1835             return false;
1836     }
1837
1838     /* TODO: check return types */
1839     if (!self->curblock->final)
1840     {
1841         if (!self->vtype->expression.next ||
1842             self->vtype->expression.next->vtype == TYPE_VOID)
1843         {
1844             return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1845         }
1846         else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1847         {
1848             if (self->return_value) {
1849                 cgen = self->return_value->expression.codegen;
1850                 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1851                     return false;
1852                 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1853             }
1854             else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1855                                 "control reaches end of non-void function (`%s`) via %s",
1856                                 self->name, self->curblock->label))
1857             {
1858                 return false;
1859             }
1860             return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1861         }
1862     }
1863     return true;
1864 }
1865
1866 /* Note, you will not see ast_block_codegen generate ir_blocks.
1867  * To the AST and the IR, blocks are 2 different things.
1868  * In the AST it represents a block of code, usually enclosed in
1869  * curly braces {...}.
1870  * While in the IR it represents a block in terms of control-flow.
1871  */
1872 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1873 {
1874     size_t i;
1875
1876     /* We don't use this
1877      * Note: an ast-representation using the comma-operator
1878      * of the form: (a, b, c) = x should not assign to c...
1879      */
1880     if (lvalue) {
1881         compile_error(ast_ctx(self), "not an l-value (code-block)");
1882         return false;
1883     }
1884
1885     if (self->expression.outr) {
1886         *out = self->expression.outr;
1887         return true;
1888     }
1889
1890     /* output is NULL at first, we'll have each expression
1891      * assign to out output, thus, a comma-operator represention
1892      * using an ast_block will return the last generated value,
1893      * so: (b, c) + a  executed both b and c, and returns c,
1894      * which is then added to a.
1895      */
1896     *out = NULL;
1897
1898     /* generate locals */
1899     for (i = 0; i < vec_size(self->locals); ++i)
1900     {
1901         if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1902             if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1903                 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1904             return false;
1905         }
1906     }
1907
1908     for (i = 0; i < vec_size(self->exprs); ++i)
1909     {
1910         ast_expression_codegen *gen;
1911         if (func->curblock->final && !ast_istype(self->exprs[i], ast_label)) {
1912             if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
1913                 return false;
1914             continue;
1915         }
1916         gen = self->exprs[i]->codegen;
1917         if (!(*gen)(self->exprs[i], func, false, out))
1918             return false;
1919     }
1920
1921     self->expression.outr = *out;
1922
1923     return true;
1924 }
1925
1926 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1927 {
1928     ast_expression_codegen *cgen;
1929     ir_value *left  = NULL;
1930     ir_value *right = NULL;
1931
1932     ast_value       *arr;
1933     ast_value       *idx = 0;
1934     ast_array_index *ai = NULL;
1935
1936     if (lvalue && self->expression.outl) {
1937         *out = self->expression.outl;
1938         return true;
1939     }
1940
1941     if (!lvalue && self->expression.outr) {
1942         *out = self->expression.outr;
1943         return true;
1944     }
1945
1946     if (ast_istype(self->dest, ast_array_index))
1947     {
1948
1949         ai = (ast_array_index*)self->dest;
1950         idx = (ast_value*)ai->index;
1951
1952         if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
1953             ai = NULL;
1954     }
1955
1956     if (ai) {
1957         /* we need to call the setter */
1958         ir_value  *iridx, *funval;
1959         ir_instr  *call;
1960
1961         if (lvalue) {
1962             compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1963             return false;
1964         }
1965
1966         arr = (ast_value*)ai->array;
1967         if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1968             compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
1969             return false;
1970         }
1971
1972         cgen = idx->expression.codegen;
1973         if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1974             return false;
1975
1976         cgen = arr->setter->expression.codegen;
1977         if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
1978             return false;
1979
1980         cgen = self->source->codegen;
1981         if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1982             return false;
1983
1984         call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
1985         if (!call)
1986             return false;
1987         ir_call_param(call, iridx);
1988         ir_call_param(call, right);
1989         self->expression.outr = right;
1990     }
1991     else
1992     {
1993         /* regular code */
1994
1995         cgen = self->dest->codegen;
1996         /* lvalue! */
1997         if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
1998             return false;
1999         self->expression.outl = left;
2000
2001         cgen = self->source->codegen;
2002         /* rvalue! */
2003         if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2004             return false;
2005
2006         if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2007             return false;
2008         self->expression.outr = right;
2009     }
2010
2011     /* Theoretically, an assinment returns its left side as an
2012      * lvalue, if we don't need an lvalue though, we return
2013      * the right side as an rvalue, otherwise we have to
2014      * somehow know whether or not we need to dereference the pointer
2015      * on the left side - that is: OP_LOAD if it was an address.
2016      * Also: in original QC we cannot OP_LOADP *anyway*.
2017      */
2018     *out = (lvalue ? left : right);
2019
2020     return true;
2021 }
2022
2023 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2024 {
2025     ast_expression_codegen *cgen;
2026     ir_value *left, *right;
2027
2028     /* A binary operation cannot yield an l-value */
2029     if (lvalue) {
2030         compile_error(ast_ctx(self), "not an l-value (binop)");
2031         return false;
2032     }
2033
2034     if (self->expression.outr) {
2035         *out = self->expression.outr;
2036         return true;
2037     }
2038
2039     if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2040         (self->op == INSTR_AND || self->op == INSTR_OR))
2041     {
2042         /* NOTE: The short-logic path will ignore right_first */
2043
2044         /* short circuit evaluation */
2045         ir_block *other, *merge;
2046         ir_block *from_left, *from_right;
2047         ir_instr *phi;
2048         size_t    merge_id;
2049
2050         /* prepare end-block */
2051         merge_id = vec_size(func->ir_func->blocks);
2052         merge    = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2053
2054         /* generate the left expression */
2055         cgen = self->left->codegen;
2056         if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2057             return false;
2058         /* remember the block */
2059         from_left = func->curblock;
2060
2061         /* create a new block for the right expression */
2062         other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2063         if (self->op == INSTR_AND) {
2064             /* on AND: left==true -> other */
2065             if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2066                 return false;
2067         } else {
2068             /* on OR: left==false -> other */
2069             if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2070                 return false;
2071         }
2072         /* use the likely flag */
2073         vec_last(func->curblock->instr)->likely = true;
2074
2075         /* enter the right-expression's block */
2076         func->curblock = other;
2077         /* generate */
2078         cgen = self->right->codegen;
2079         if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2080             return false;
2081         /* remember block */
2082         from_right = func->curblock;
2083
2084         /* jump to the merge block */
2085         if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2086             return false;
2087
2088         vec_remove(func->ir_func->blocks, merge_id, 1);
2089         vec_push(func->ir_func->blocks, merge);
2090
2091         func->curblock = merge;
2092         phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2093                                   ast_function_label(func, "sce_value"),
2094                                   self->expression.vtype);
2095         ir_phi_add(phi, from_left, left);
2096         ir_phi_add(phi, from_right, right);
2097         *out = ir_phi_value(phi);
2098         if (!*out)
2099             return false;
2100
2101         if (!OPTS_FLAG(PERL_LOGIC)) {
2102             /* cast-to-bool */
2103             if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2104                 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2105                                              ast_function_label(func, "sce_bool_v"),
2106                                              INSTR_NOT_V, *out);
2107                 if (!*out)
2108                     return false;
2109                 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2110                                              ast_function_label(func, "sce_bool"),
2111                                              INSTR_NOT_F, *out);
2112                 if (!*out)
2113                     return false;
2114             }
2115             else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2116                 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2117                                              ast_function_label(func, "sce_bool_s"),
2118                                              INSTR_NOT_S, *out);
2119                 if (!*out)
2120                     return false;
2121                 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2122                                              ast_function_label(func, "sce_bool"),
2123                                              INSTR_NOT_F, *out);
2124                 if (!*out)
2125                     return false;
2126             }
2127             else {
2128                 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2129                                              ast_function_label(func, "sce_bool"),
2130                                              INSTR_AND, *out, *out);
2131                 if (!*out)
2132                     return false;
2133             }
2134         }
2135
2136         self->expression.outr = *out;
2137         codegen_output_type(self, *out);
2138         return true;
2139     }
2140
2141     if (self->right_first) {
2142         cgen = self->right->codegen;
2143         if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2144             return false;
2145         cgen = self->left->codegen;
2146         if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2147             return false;
2148     } else {
2149         cgen = self->left->codegen;
2150         if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2151             return false;
2152         cgen = self->right->codegen;
2153         if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2154             return false;
2155     }
2156
2157     *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2158                                  self->op, left, right);
2159     if (!*out)
2160         return false;
2161     self->expression.outr = *out;
2162     codegen_output_type(self, *out);
2163
2164     return true;
2165 }
2166
2167 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2168 {
2169     ast_expression_codegen *cgen;
2170     ir_value *leftl = NULL, *leftr, *right, *bin;
2171
2172     ast_value       *arr;
2173     ast_value       *idx = 0;
2174     ast_array_index *ai = NULL;
2175     ir_value        *iridx = NULL;
2176
2177     if (lvalue && self->expression.outl) {
2178         *out = self->expression.outl;
2179         return true;
2180     }
2181
2182     if (!lvalue && self->expression.outr) {
2183         *out = self->expression.outr;
2184         return true;
2185     }
2186
2187     if (ast_istype(self->dest, ast_array_index))
2188     {
2189
2190         ai = (ast_array_index*)self->dest;
2191         idx = (ast_value*)ai->index;
2192
2193         if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2194             ai = NULL;
2195     }
2196
2197     /* for a binstore we need both an lvalue and an rvalue for the left side */
2198     /* rvalue of destination! */
2199     if (ai) {
2200         cgen = idx->expression.codegen;
2201         if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2202             return false;
2203     }
2204     cgen = self->dest->codegen;
2205     if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2206         return false;
2207
2208     /* source as rvalue only */
2209     cgen = self->source->codegen;
2210     if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2211         return false;
2212
2213     /* now the binary */
2214     bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2215                                 self->opbin, leftr, right);
2216     self->expression.outr = bin;
2217
2218
2219     if (ai) {
2220         /* we need to call the setter */
2221         ir_value  *funval;
2222         ir_instr  *call;
2223
2224         if (lvalue) {
2225             compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2226             return false;
2227         }
2228
2229         arr = (ast_value*)ai->array;
2230         if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2231             compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2232             return false;
2233         }
2234
2235         cgen = arr->setter->expression.codegen;
2236         if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2237             return false;
2238
2239         call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2240         if (!call)
2241             return false;
2242         ir_call_param(call, iridx);
2243         ir_call_param(call, bin);
2244         self->expression.outr = bin;
2245     } else {
2246         /* now store them */
2247         cgen = self->dest->codegen;
2248         /* lvalue of destination */
2249         if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2250             return false;
2251         self->expression.outl = leftl;
2252
2253         if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2254             return false;
2255         self->expression.outr = bin;
2256     }
2257
2258     /* Theoretically, an assinment returns its left side as an
2259      * lvalue, if we don't need an lvalue though, we return
2260      * the right side as an rvalue, otherwise we have to
2261      * somehow know whether or not we need to dereference the pointer
2262      * on the left side - that is: OP_LOAD if it was an address.
2263      * Also: in original QC we cannot OP_LOADP *anyway*.
2264      */
2265     *out = (lvalue ? leftl : bin);
2266
2267     return true;
2268 }
2269
2270 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2271 {
2272     ast_expression_codegen *cgen;
2273     ir_value *operand;
2274
2275     /* An unary operation cannot yield an l-value */
2276     if (lvalue) {
2277         compile_error(ast_ctx(self), "not an l-value (binop)");
2278         return false;
2279     }
2280
2281     if (self->expression.outr) {
2282         *out = self->expression.outr;
2283         return true;
2284     }
2285
2286     cgen = self->operand->codegen;
2287     /* lvalue! */
2288     if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2289         return false;
2290
2291     *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2292                                  self->op, operand);
2293     if (!*out)
2294         return false;
2295     self->expression.outr = *out;
2296
2297     return true;
2298 }
2299
2300 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2301 {
2302     ast_expression_codegen *cgen;
2303     ir_value *operand;
2304
2305     *out = NULL;
2306
2307     /* In the context of a return operation, we don't actually return
2308      * anything...
2309      */
2310     if (lvalue) {
2311         compile_error(ast_ctx(self), "return-expression is not an l-value");
2312         return false;
2313     }
2314
2315     if (self->expression.outr) {
2316         compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2317         return false;
2318     }
2319     self->expression.outr = (ir_value*)1;
2320
2321     if (self->operand) {
2322         cgen = self->operand->codegen;
2323         /* lvalue! */
2324         if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2325             return false;
2326
2327         if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2328             return false;
2329     } else {
2330         if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2331             return false;
2332     }
2333
2334     return true;
2335 }
2336
2337 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2338 {
2339     ast_expression_codegen *cgen;
2340     ir_value *ent, *field;
2341
2342     /* This function needs to take the 'lvalue' flag into account!
2343      * As lvalue we provide a field-pointer, as rvalue we provide the
2344      * value in a temp.
2345      */
2346
2347     if (lvalue && self->expression.outl) {
2348         *out = self->expression.outl;
2349         return true;
2350     }
2351
2352     if (!lvalue && self->expression.outr) {
2353         *out = self->expression.outr;
2354         return true;
2355     }
2356
2357     cgen = self->entity->codegen;
2358     if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2359         return false;
2360
2361     cgen = self->field->codegen;
2362     if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2363         return false;
2364
2365     if (lvalue) {
2366         /* address! */
2367         *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2368                                             ent, field);
2369     } else {
2370         *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2371                                              ent, field, self->expression.vtype);
2372         /* Done AFTER error checking:
2373         codegen_output_type(self, *out);
2374         */
2375     }
2376     if (!*out) {
2377         compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2378                  (lvalue ? "ADDRESS" : "FIELD"),
2379                  type_name[self->expression.vtype]);
2380         return false;
2381     }
2382     if (!lvalue)
2383         codegen_output_type(self, *out);
2384
2385     if (lvalue)
2386         self->expression.outl = *out;
2387     else
2388         self->expression.outr = *out;
2389
2390     /* Hm that should be it... */
2391     return true;
2392 }
2393
2394 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2395 {
2396     ast_expression_codegen *cgen;
2397     ir_value *vec;
2398
2399     /* in QC this is always an lvalue */
2400     if (lvalue && self->rvalue) {
2401         compile_error(ast_ctx(self), "not an l-value (member access)");
2402         return false;
2403     }
2404     if (self->expression.outl) {
2405         *out = self->expression.outl;
2406         return true;
2407     }
2408
2409     cgen = self->owner->codegen;
2410     if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2411         return false;
2412
2413     if (vec->vtype != TYPE_VECTOR &&
2414         !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2415     {
2416         return false;
2417     }
2418
2419     *out = ir_value_vector_member(vec, self->field);
2420     self->expression.outl = *out;
2421
2422     return (*out != NULL);
2423 }
2424
2425 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2426 {
2427     ast_value *arr;
2428     ast_value *idx;
2429
2430     if (!lvalue && self->expression.outr) {
2431         *out = self->expression.outr;
2432         return true;
2433     }
2434     if (lvalue && self->expression.outl) {
2435         *out = self->expression.outl;
2436         return true;
2437     }
2438
2439     if (!ast_istype(self->array, ast_value)) {
2440         compile_error(ast_ctx(self), "array indexing this way is not supported");
2441         /* note this would actually be pointer indexing because the left side is
2442          * not an actual array but (hopefully) an indexable expression.
2443          * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2444          * support this path will be filled.
2445          */
2446         return false;
2447     }
2448
2449     arr = (ast_value*)self->array;
2450     idx = (ast_value*)self->index;
2451
2452     if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2453         /* Time to use accessor functions */
2454         ast_expression_codegen *cgen;
2455         ir_value               *iridx, *funval;
2456         ir_instr               *call;
2457
2458         if (lvalue) {
2459             compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2460             return false;
2461         }
2462
2463         if (!arr->getter) {
2464             compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2465             return false;
2466         }
2467
2468         cgen = self->index->codegen;
2469         if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2470             return false;
2471
2472         cgen = arr->getter->expression.codegen;
2473         if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2474             return false;
2475
2476         call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2477         if (!call)
2478             return false;
2479         ir_call_param(call, iridx);
2480
2481         *out = ir_call_value(call);
2482         self->expression.outr = *out;
2483         (*out)->vtype = self->expression.vtype;
2484         codegen_output_type(self, *out);
2485         return true;
2486     }
2487
2488     if (idx->expression.vtype == TYPE_FLOAT) {
2489         unsigned int arridx = idx->constval.vfloat;
2490         if (arridx >= self->array->count)
2491         {
2492             compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2493             return false;
2494         }
2495         *out = arr->ir_values[arridx];
2496     }
2497     else if (idx->expression.vtype == TYPE_INTEGER) {
2498         unsigned int arridx = idx->constval.vint;
2499         if (arridx >= self->array->count)
2500         {
2501             compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2502             return false;
2503         }
2504         *out = arr->ir_values[arridx];
2505     }
2506     else {
2507         compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2508         return false;
2509     }
2510     (*out)->vtype = self->expression.vtype;
2511     codegen_output_type(self, *out);
2512     return true;
2513 }
2514
2515 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2516 {
2517     *out = NULL;
2518     if (lvalue) {
2519         compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2520         return false;
2521     }
2522     (void)func;
2523     (void)out;
2524     compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2525     return false;
2526 }
2527
2528 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2529 {
2530     ast_expression_codegen *cgen;
2531
2532     ir_value *condval;
2533     ir_value *dummy;
2534
2535     ir_block *cond;
2536     ir_block *ontrue;
2537     ir_block *onfalse;
2538     ir_block *ontrue_endblock = NULL;
2539     ir_block *onfalse_endblock = NULL;
2540     ir_block *merge = NULL;
2541     int       fold  = 0;
2542
2543     /* We don't output any value, thus also don't care about r/lvalue */
2544     (void)out;
2545     (void)lvalue;
2546
2547     if (self->expression.outr) {
2548         compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2549         return false;
2550     }
2551     self->expression.outr = (ir_value*)1;
2552
2553     /* generate the condition */
2554     cgen = self->cond->codegen;
2555     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2556         return false;
2557     /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2558     cond = func->curblock;
2559
2560     /* try constant folding away the if */
2561     if ((fold = fold_cond(condval, func, self)) != -1)
2562         return fold;
2563
2564     if (self->on_true) {
2565         /* create on-true block */
2566         ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2567         if (!ontrue)
2568             return false;
2569
2570         /* enter the block */
2571         func->curblock = ontrue;
2572
2573         /* generate */
2574         cgen = self->on_true->codegen;
2575         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2576             return false;
2577
2578         /* we now need to work from the current endpoint */
2579         ontrue_endblock = func->curblock;
2580     } else
2581         ontrue = NULL;
2582
2583     /* on-false path */
2584     if (self->on_false) {
2585         /* create on-false block */
2586         onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2587         if (!onfalse)
2588             return false;
2589
2590         /* enter the block */
2591         func->curblock = onfalse;
2592
2593         /* generate */
2594         cgen = self->on_false->codegen;
2595         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2596             return false;
2597
2598         /* we now need to work from the current endpoint */
2599         onfalse_endblock = func->curblock;
2600     } else
2601         onfalse = NULL;
2602
2603     /* Merge block were they all merge in to */
2604     if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2605     {
2606         merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2607         if (!merge)
2608             return false;
2609         /* add jumps ot the merge block */
2610         if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2611             return false;
2612         if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2613             return false;
2614
2615         /* Now enter the merge block */
2616         func->curblock = merge;
2617     }
2618
2619     /* we create the if here, that way all blocks are ordered :)
2620      */
2621     if (!ir_block_create_if(cond, ast_ctx(self), condval,
2622                             (ontrue  ? ontrue  : merge),
2623                             (onfalse ? onfalse : merge)))
2624     {
2625         return false;
2626     }
2627
2628     return true;
2629 }
2630
2631 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2632 {
2633     ast_expression_codegen *cgen;
2634
2635     ir_value *condval;
2636     ir_value *trueval, *falseval;
2637     ir_instr *phi;
2638
2639     ir_block *cond = func->curblock;
2640     ir_block *cond_out = NULL;
2641     ir_block *ontrue, *ontrue_out = NULL;
2642     ir_block *onfalse, *onfalse_out = NULL;
2643     ir_block *merge;
2644
2645     /* Ternary can never create an lvalue... */
2646     if (lvalue)
2647         return false;
2648
2649     /* In theory it shouldn't be possible to pass through a node twice, but
2650      * in case we add any kind of optimization pass for the AST itself, it
2651      * may still happen, thus we remember a created ir_value and simply return one
2652      * if it already exists.
2653      */
2654     if (self->expression.outr) {
2655         *out = self->expression.outr;
2656         return true;
2657     }
2658
2659     /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2660
2661     /* generate the condition */
2662     func->curblock = cond;
2663     cgen = self->cond->codegen;
2664     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2665         return false;
2666     cond_out = func->curblock;
2667
2668     /* create on-true block */
2669     ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2670     if (!ontrue)
2671         return false;
2672     else
2673     {
2674         /* enter the block */
2675         func->curblock = ontrue;
2676
2677         /* generate */
2678         cgen = self->on_true->codegen;
2679         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2680             return false;
2681
2682         ontrue_out = func->curblock;
2683     }
2684
2685     /* create on-false block */
2686     onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2687     if (!onfalse)
2688         return false;
2689     else
2690     {
2691         /* enter the block */
2692         func->curblock = onfalse;
2693
2694         /* generate */
2695         cgen = self->on_false->codegen;
2696         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2697             return false;
2698
2699         onfalse_out = func->curblock;
2700     }
2701
2702     /* create merge block */
2703     merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2704     if (!merge)
2705         return false;
2706     /* jump to merge block */
2707     if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2708         return false;
2709     if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2710         return false;
2711
2712     /* create if instruction */
2713     if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2714         return false;
2715
2716     /* Now enter the merge block */
2717     func->curblock = merge;
2718
2719     /* Here, now, we need a PHI node
2720      * but first some sanity checking...
2721      */
2722     if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2723         /* error("ternary with different types on the two sides"); */
2724         compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2725         return false;
2726     }
2727
2728     /* create PHI */
2729     phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2730     if (!phi) {
2731         compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2732         return false;
2733     }
2734     ir_phi_add(phi, ontrue_out,  trueval);
2735     ir_phi_add(phi, onfalse_out, falseval);
2736
2737     self->expression.outr = ir_phi_value(phi);
2738     *out = self->expression.outr;
2739
2740     codegen_output_type(self, *out);
2741
2742     return true;
2743 }
2744
2745 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2746 {
2747     ast_expression_codegen *cgen;
2748
2749     ir_value *dummy      = NULL;
2750     ir_value *precond    = NULL;
2751     ir_value *postcond   = NULL;
2752
2753     /* Since we insert some jumps "late" so we have blocks
2754      * ordered "nicely", we need to keep track of the actual end-blocks
2755      * of expressions to add the jumps to.
2756      */
2757     ir_block *bbody      = NULL, *end_bbody      = NULL;
2758     ir_block *bprecond   = NULL, *end_bprecond   = NULL;
2759     ir_block *bpostcond  = NULL, *end_bpostcond  = NULL;
2760     ir_block *bincrement = NULL, *end_bincrement = NULL;
2761     ir_block *bout       = NULL, *bin            = NULL;
2762
2763     /* let's at least move the outgoing block to the end */
2764     size_t    bout_id;
2765
2766     /* 'break' and 'continue' need to be able to find the right blocks */
2767     ir_block *bcontinue     = NULL;
2768     ir_block *bbreak        = NULL;
2769
2770     ir_block *tmpblock      = NULL;
2771
2772     (void)lvalue;
2773     (void)out;
2774
2775     if (self->expression.outr) {
2776         compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2777         return false;
2778     }
2779     self->expression.outr = (ir_value*)1;
2780
2781     /* NOTE:
2782      * Should we ever need some kind of block ordering, better make this function
2783      * move blocks around than write a block ordering algorithm later... after all
2784      * the ast and ir should work together, not against each other.
2785      */
2786
2787     /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2788      * anyway if for example it contains a ternary.
2789      */
2790     if (self->initexpr)
2791     {
2792         cgen = self->initexpr->codegen;
2793         if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2794             return false;
2795     }
2796
2797     /* Store the block from which we enter this chaos */
2798     bin = func->curblock;
2799
2800     /* The pre-loop condition needs its own block since we
2801      * need to be able to jump to the start of that expression.
2802      */
2803     if (self->precond)
2804     {
2805         bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2806         if (!bprecond)
2807             return false;
2808
2809         /* the pre-loop-condition the least important place to 'continue' at */
2810         bcontinue = bprecond;
2811
2812         /* enter */
2813         func->curblock = bprecond;
2814
2815         /* generate */
2816         cgen = self->precond->codegen;
2817         if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2818             return false;
2819
2820         end_bprecond = func->curblock;
2821     } else {
2822         bprecond = end_bprecond = NULL;
2823     }
2824
2825     /* Now the next blocks won't be ordered nicely, but we need to
2826      * generate them this early for 'break' and 'continue'.
2827      */
2828     if (self->increment) {
2829         bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2830         if (!bincrement)
2831             return false;
2832         bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2833     } else {
2834         bincrement = end_bincrement = NULL;
2835     }
2836
2837     if (self->postcond) {
2838         bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2839         if (!bpostcond)
2840             return false;
2841         bcontinue = bpostcond; /* postcond comes before the increment */
2842     } else {
2843         bpostcond = end_bpostcond = NULL;
2844     }
2845
2846     bout_id = vec_size(func->ir_func->blocks);
2847     bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2848     if (!bout)
2849         return false;
2850     bbreak = bout;
2851
2852     /* The loop body... */
2853     /* if (self->body) */
2854     {
2855         bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2856         if (!bbody)
2857             return false;
2858
2859         /* enter */
2860         func->curblock = bbody;
2861
2862         vec_push(func->breakblocks,    bbreak);
2863         if (bcontinue)
2864             vec_push(func->continueblocks, bcontinue);
2865         else
2866             vec_push(func->continueblocks, bbody);
2867
2868         /* generate */
2869         if (self->body) {
2870             cgen = self->body->codegen;
2871             if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2872                 return false;
2873         }
2874
2875         end_bbody = func->curblock;
2876         vec_pop(func->breakblocks);
2877         vec_pop(func->continueblocks);
2878     }
2879
2880     /* post-loop-condition */
2881     if (self->postcond)
2882     {
2883         /* enter */
2884         func->curblock = bpostcond;
2885
2886         /* generate */
2887         cgen = self->postcond->codegen;
2888         if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2889             return false;
2890
2891         end_bpostcond = func->curblock;
2892     }
2893
2894     /* The incrementor */
2895     if (self->increment)
2896     {
2897         /* enter */
2898         func->curblock = bincrement;
2899
2900         /* generate */
2901         cgen = self->increment->codegen;
2902         if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2903             return false;
2904
2905         end_bincrement = func->curblock;
2906     }
2907
2908     /* In any case now, we continue from the outgoing block */
2909     func->curblock = bout;
2910
2911     /* Now all blocks are in place */
2912     /* From 'bin' we jump to whatever comes first */
2913     if      (bprecond)   tmpblock = bprecond;
2914     else                 tmpblock = bbody;    /* can never be null */
2915
2916     /* DEAD CODE
2917     else if (bpostcond)  tmpblock = bpostcond;
2918     else                 tmpblock = bout;
2919     */
2920
2921     if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2922         return false;
2923
2924     /* From precond */
2925     if (bprecond)
2926     {
2927         ir_block *ontrue, *onfalse;
2928         ontrue = bbody; /* can never be null */
2929
2930         /* all of this is dead code
2931         else if (bincrement) ontrue = bincrement;
2932         else                 ontrue = bpostcond;
2933         */
2934
2935         onfalse = bout;
2936         if (self->pre_not) {
2937             tmpblock = ontrue;
2938             ontrue   = onfalse;
2939             onfalse  = tmpblock;
2940         }
2941         if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
2942             return false;
2943     }
2944
2945     /* from body */
2946     if (bbody)
2947     {
2948         if      (bincrement) tmpblock = bincrement;
2949         else if (bpostcond)  tmpblock = bpostcond;
2950         else if (bprecond)   tmpblock = bprecond;
2951         else                 tmpblock = bbody;
2952         if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
2953             return false;
2954     }
2955
2956     /* from increment */
2957     if (bincrement)
2958     {
2959         if      (bpostcond)  tmpblock = bpostcond;
2960         else if (bprecond)   tmpblock = bprecond;
2961         else if (bbody)      tmpblock = bbody;
2962         else                 tmpblock = bout;
2963         if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
2964             return false;
2965     }
2966
2967     /* from postcond */
2968     if (bpostcond)
2969     {
2970         ir_block *ontrue, *onfalse;
2971         if      (bprecond)   ontrue = bprecond;
2972         else                 ontrue = bbody; /* can never be null */
2973
2974         /* all of this is dead code
2975         else if (bincrement) ontrue = bincrement;
2976         else                 ontrue = bpostcond;
2977         */
2978
2979         onfalse = bout;
2980         if (self->post_not) {
2981             tmpblock = ontrue;
2982             ontrue   = onfalse;
2983             onfalse  = tmpblock;
2984         }
2985         if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
2986             return false;
2987     }
2988
2989     /* Move 'bout' to the end */
2990     vec_remove(func->ir_func->blocks, bout_id, 1);
2991     vec_push(func->ir_func->blocks, bout);
2992
2993     return true;
2994 }
2995
2996 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
2997 {
2998     ir_block *target;
2999
3000     *out = NULL;
3001
3002     if (lvalue) {
3003         compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3004         return false;
3005     }
3006
3007     if (self->expression.outr) {
3008         compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3009         return false;
3010     }
3011     self->expression.outr = (ir_value*)1;
3012
3013     if (self->is_continue)
3014         target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
3015     else
3016         target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
3017
3018     if (!target) {
3019         compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3020         return false;
3021     }
3022
3023     if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3024         return false;
3025     return true;
3026 }
3027
3028 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3029 {
3030     ast_expression_codegen *cgen;
3031
3032     ast_switch_case *def_case     = NULL;
3033     ir_block        *def_bfall    = NULL;
3034     ir_block        *def_bfall_to = NULL;
3035     bool set_def_bfall_to = false;
3036
3037     ir_value *dummy     = NULL;
3038     ir_value *irop      = NULL;
3039     ir_block *bout      = NULL;
3040     ir_block *bfall     = NULL;
3041     size_t    bout_id;
3042     size_t    c;
3043
3044     char      typestr[1024];
3045     uint16_t  cmpinstr;
3046
3047     if (lvalue) {
3048         compile_error(ast_ctx(self), "switch expression is not an l-value");
3049         return false;
3050     }
3051
3052     if (self->expression.outr) {
3053         compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3054         return false;
3055     }
3056     self->expression.outr = (ir_value*)1;
3057
3058     (void)lvalue;
3059     (void)out;
3060
3061     cgen = self->operand->codegen;
3062     if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3063         return false;
3064
3065     if (!vec_size(self->cases))
3066         return true;
3067
3068     cmpinstr = type_eq_instr[irop->vtype];
3069     if (cmpinstr >= VINSTR_END) {
3070         ast_type_to_string(self->operand, typestr, sizeof(typestr));
3071         compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3072         return false;
3073     }
3074
3075     bout_id = vec_size(func->ir_func->blocks);
3076     bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3077     if (!bout)
3078         return false;
3079
3080     /* setup the break block */
3081     vec_push(func->breakblocks, bout);
3082
3083     /* Now create all cases */
3084     for (c = 0; c < vec_size(self->cases); ++c) {
3085         ir_value *cond, *val;
3086         ir_block *bcase, *bnot;
3087         size_t bnot_id;
3088
3089         ast_switch_case *swcase = &self->cases[c];
3090
3091         if (swcase->value) {
3092             /* A regular case */
3093             /* generate the condition operand */
3094             cgen = swcase->value->codegen;
3095             if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3096                 return false;
3097             /* generate the condition */
3098             cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3099             if (!cond)
3100                 return false;
3101
3102             bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3103             bnot_id = vec_size(func->ir_func->blocks);
3104             bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3105             if (!bcase || !bnot)
3106                 return false;
3107             if (set_def_bfall_to) {
3108                 set_def_bfall_to = false;
3109                 def_bfall_to = bcase;
3110             }
3111             if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3112                 return false;
3113
3114             /* Make the previous case-end fall through */
3115             if (bfall && !bfall->final) {
3116                 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3117                     return false;
3118             }
3119
3120             /* enter the case */
3121             func->curblock = bcase;
3122             cgen = swcase->code->codegen;
3123             if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3124                 return false;
3125
3126             /* remember this block to fall through from */
3127             bfall = func->curblock;
3128
3129             /* enter the else and move it down */
3130             func->curblock = bnot;
3131             vec_remove(func->ir_func->blocks, bnot_id, 1);
3132             vec_push(func->ir_func->blocks, bnot);
3133         } else {
3134             /* The default case */
3135             /* Remember where to fall through from: */
3136             def_bfall = bfall;
3137             bfall     = NULL;
3138             /* remember which case it was */
3139             def_case  = swcase;
3140             /* And the next case will be remembered */
3141             set_def_bfall_to = true;
3142         }
3143     }
3144
3145     /* Jump from the last bnot to bout */
3146     if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3147         /*
3148         astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3149         */
3150         return false;
3151     }
3152
3153     /* If there was a default case, put it down here */
3154     if (def_case) {
3155         ir_block *bcase;
3156
3157         /* No need to create an extra block */
3158         bcase = func->curblock;
3159
3160         /* Insert the fallthrough jump */
3161         if (def_bfall && !def_bfall->final) {
3162             if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3163                 return false;
3164         }
3165
3166         /* Now generate the default code */
3167         cgen = def_case->code->codegen;
3168         if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3169             return false;
3170
3171         /* see if we need to fall through */
3172         if (def_bfall_to && !func->curblock->final)
3173         {
3174             if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3175                 return false;
3176         }
3177     }
3178
3179     /* Jump from the last bnot to bout */
3180     if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3181         return false;
3182     /* enter the outgoing block */
3183     func->curblock = bout;
3184
3185     /* restore the break block */
3186     vec_pop(func->breakblocks);
3187
3188     /* Move 'bout' to the end, it's nicer */
3189     vec_remove(func->ir_func->blocks, bout_id, 1);
3190     vec_push(func->ir_func->blocks, bout);
3191
3192     return true;
3193 }
3194
3195 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3196 {
3197     size_t i;
3198     ir_value *dummy;
3199
3200     if (self->undefined) {
3201         compile_error(ast_ctx(self), "internal error: ast_label never defined");
3202         return false;
3203     }
3204
3205     *out = NULL;
3206     if (lvalue) {
3207         compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3208         return false;
3209     }
3210
3211     /* simply create a new block and jump to it */
3212     self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3213     if (!self->irblock) {
3214         compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3215         return false;
3216     }
3217     if (!func->curblock->final) {
3218         if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3219             return false;
3220     }
3221
3222     /* enter the new block */
3223     func->curblock = self->irblock;
3224
3225     /* Generate all the leftover gotos */
3226     for (i = 0; i < vec_size(self->gotos); ++i) {
3227         if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3228             return false;
3229     }
3230
3231     return true;
3232 }
3233
3234 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3235 {
3236     *out = NULL;
3237     if (lvalue) {
3238         compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3239         return false;
3240     }
3241
3242     if (self->target->irblock) {
3243         if (self->irblock_from) {
3244             /* we already tried once, this is the callback */
3245             self->irblock_from->final = false;
3246             if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3247                 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3248                 return false;
3249             }
3250         }
3251         else
3252         {
3253             if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3254                 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3255                 return false;
3256             }
3257         }
3258     }
3259     else
3260     {
3261         /* the target has not yet been created...
3262          * close this block in a sneaky way:
3263          */
3264         func->curblock->final = true;
3265         self->irblock_from = func->curblock;
3266         ast_label_register_goto(self->target, self);
3267     }
3268
3269     return true;
3270 }
3271
3272 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3273 {
3274     ast_expression_codegen *cgen;
3275     ir_value              **params;
3276     ir_instr               *callinstr;
3277     size_t i;
3278
3279     ir_value *funval = NULL;
3280
3281     /* return values are never lvalues */
3282     if (lvalue) {
3283         compile_error(ast_ctx(self), "not an l-value (function call)");
3284         return false;
3285     }
3286
3287     if (self->expression.outr) {
3288         *out = self->expression.outr;
3289         return true;
3290     }
3291
3292     cgen = self->func->codegen;
3293     if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3294         return false;
3295     if (!funval)
3296         return false;
3297
3298     params = NULL;
3299
3300     /* parameters */
3301     for (i = 0; i < vec_size(self->params); ++i)
3302     {
3303         ir_value *param;
3304         ast_expression *expr = self->params[i];
3305
3306         cgen = expr->codegen;
3307         if (!(*cgen)(expr, func, false, &param))
3308             goto error;
3309         if (!param)
3310             goto error;
3311         vec_push(params, param);
3312     }
3313
3314     /* varargs counter */
3315     if (self->va_count) {
3316         ir_value   *va_count;
3317         ir_builder *builder = func->curblock->owner->owner;
3318         cgen = self->va_count->codegen;
3319         if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3320             return false;
3321         if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3322                                       ir_builder_get_va_count(builder), va_count))
3323         {
3324             return false;
3325         }
3326     }
3327
3328     callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3329                                      ast_function_label(func, "call"),
3330                                      funval, !!(self->func->flags & AST_FLAG_NORETURN));
3331     if (!callinstr)
3332         goto error;
3333
3334     for (i = 0; i < vec_size(params); ++i) {
3335         ir_call_param(callinstr, params[i]);
3336     }
3337
3338     *out = ir_call_value(callinstr);
3339     self->expression.outr = *out;
3340
3341     codegen_output_type(self, *out);
3342
3343     vec_free(params);
3344     return true;
3345 error:
3346     vec_free(params);
3347     return false;
3348 }