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