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