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