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