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