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