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