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