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