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