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