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