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