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