]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ast.c
Working vector-field test
[xonotic/gmqcc.git] / ast.c
1 /*
2  * Copyright (C) 2012
3  *     Wolfgang Bumiller
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of
6  * this software and associated documentation files (the "Software"), to deal in
7  * the Software without restriction, including without limitation the rights to
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9  * of the Software, and to permit persons to whom the Software is furnished to do
10  * so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  */
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include "gmqcc.h"
28 #include "ast.h"
29
30 #define ast_instantiate(T, ctx, destroyfn)                          \
31     T* self = (T*)mem_a(sizeof(T));                                 \
32     if (!self) {                                                    \
33         return NULL;                                                \
34     }                                                               \
35     ast_node_init((ast_node*)self, ctx, TYPE_##T);                  \
36     ( (ast_node*)self )->node.destroy = (ast_node_delete*)destroyfn
37
38 /* It must not be possible to get here. */
39 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
40 {
41     fprintf(stderr, "ast node missing destroy()\n");
42     abort();
43 }
44
45 /* Initialize main ast node aprts */
46 static void ast_node_init(ast_node *self, lex_ctx ctx, int nodetype)
47 {
48     self->node.context = ctx;
49     self->node.destroy = &_ast_node_destroy;
50     self->node.keep    = false;
51     self->node.nodetype = nodetype;
52 }
53
54 /* General expression initialization */
55 static void ast_expression_init(ast_expression *self,
56                                 ast_expression_codegen *codegen)
57 {
58     self->expression.codegen = codegen;
59     self->expression.vtype   = TYPE_VOID;
60     self->expression.next    = NULL;
61     MEM_VECTOR_INIT(&self->expression, params);
62 }
63
64 static void ast_expression_delete(ast_expression *self)
65 {
66     size_t i;
67     if (self->expression.next)
68         ast_delete(self->expression.next);
69     for (i = 0; i < self->expression.params_count; ++i) {
70         ast_delete(self->expression.params[i]);
71     }
72     MEM_VECTOR_CLEAR(&self->expression, params);
73 }
74
75 static void ast_expression_delete_full(ast_expression *self)
76 {
77     ast_expression_delete(self);
78     mem_d(self);
79 }
80
81 MEM_VEC_FUNCTIONS(ast_expression_common, ast_value*, params)
82
83 static ast_expression* ast_type_copy(lex_ctx ctx, const ast_expression *ex);
84 static ast_value* ast_value_copy(const ast_value *self)
85 {
86     ast_value *cp = ast_value_new(self->expression.node.context, self->name, self->expression.vtype);
87     if (self->expression.next) {
88         cp->expression.next = ast_type_copy(self->expression.node.context, self->expression.next);
89         if (!cp->expression.next) {
90             ast_value_delete(cp);
91             return NULL;
92         }
93     }
94     return cp;
95 }
96
97 static ast_expression* ast_shallow_type(lex_ctx ctx, int vtype)
98 {
99     ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
100     self->expression.codegen = NULL;
101     self->expression.next    = NULL;
102     self->expression.vtype   = vtype;
103     return self;
104 }
105
106 static ast_expression* ast_type_copy(lex_ctx ctx, const ast_expression *ex)
107 {
108     size_t i;
109     const ast_expression_common *fromex;
110     ast_expression_common *selfex;
111
112     if (!ex)
113         return NULL;
114     else
115     {
116         ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
117
118         fromex   = &ex->expression;
119         selfex = &self->expression;
120
121         /* This may never be codegen()d */
122         selfex->codegen = NULL;
123
124         selfex->vtype = fromex->vtype;
125         if (fromex->next)
126         {
127             selfex->next = ast_type_copy(ctx, fromex->next);
128             if (!selfex->next) {
129                 ast_expression_delete_full(self);
130                 return NULL;
131             }
132         }
133         else
134             selfex->next = NULL;
135
136         for (i = 0; i < fromex->params_count; ++i) {
137             ast_value *v = ast_value_copy(fromex->params[i]);
138             if (!v || !ast_expression_common_params_add(selfex, v)) {
139                 ast_expression_delete_full(self);
140                 return NULL;
141             }
142         }
143
144         return self;
145     }
146 }
147
148 ast_value* ast_value_new(lex_ctx ctx, const char *name, int t)
149 {
150     ast_instantiate(ast_value, ctx, ast_value_delete);
151     ast_expression_init((ast_expression*)self,
152                         (ast_expression_codegen*)&ast_value_codegen);
153     self->expression.node.keep = true; /* keep */
154
155     self->name = name ? util_strdup(name) : NULL;
156     self->expression.vtype = t;
157     self->expression.next  = NULL;
158     self->isconst = false;
159     memset(&self->constval, 0, sizeof(self->constval));
160
161     self->ir_v    = NULL;
162
163     return self;
164 }
165
166 void ast_value_delete(ast_value* self)
167 {
168     if (self->name)
169         mem_d((void*)self->name);
170     if (self->isconst) {
171         switch (self->expression.vtype)
172         {
173         case TYPE_STRING:
174             mem_d((void*)self->constval.vstring);
175             break;
176         case TYPE_FUNCTION:
177             /* unlink us from the function node */
178             self->constval.vfunc->vtype = NULL;
179             break;
180         /* NOTE: delete function? currently collected in
181          * the parser structure
182          */
183         default:
184             break;
185         }
186     }
187     ast_expression_delete((ast_expression*)self);
188     mem_d(self);
189 }
190
191 bool GMQCC_WARN ast_value_params_add(ast_value *self, ast_value *p)
192 {
193     return ast_expression_common_params_add(&self->expression, p);
194 }
195
196 bool ast_value_set_name(ast_value *self, const char *name)
197 {
198     if (self->name)
199         mem_d((void*)self->name);
200     self->name = util_strdup(name);
201     return !!self->name;
202 }
203
204 ast_binary* ast_binary_new(lex_ctx ctx, int op,
205                            ast_expression* left, ast_expression* right)
206 {
207     ast_instantiate(ast_binary, ctx, ast_binary_delete);
208     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
209
210     self->op = op;
211     self->left = left;
212     self->right = right;
213
214     return self;
215 }
216
217 void ast_binary_delete(ast_binary *self)
218 {
219     ast_unref(self->left);
220     ast_unref(self->right);
221     ast_expression_delete((ast_expression*)self);
222     mem_d(self);
223 }
224
225 ast_unary* ast_unary_new(lex_ctx ctx, int op,
226                          ast_expression *expr)
227 {
228     ast_instantiate(ast_unary, ctx, ast_unary_delete);
229     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
230
231     self->op = op;
232     self->operand = expr;
233
234     return self;
235 }
236
237 void ast_unary_delete(ast_unary *self)
238 {
239     ast_unref(self->operand);
240     ast_expression_delete((ast_expression*)self);
241     mem_d(self);
242 }
243
244 ast_return* ast_return_new(lex_ctx ctx, ast_expression *expr)
245 {
246     ast_instantiate(ast_return, ctx, ast_return_delete);
247     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
248
249     self->operand = expr;
250
251     return self;
252 }
253
254 void ast_return_delete(ast_return *self)
255 {
256     ast_unref(self->operand);
257     ast_expression_delete((ast_expression*)self);
258     mem_d(self);
259 }
260
261 ast_entfield* ast_entfield_new(lex_ctx ctx, ast_expression *entity, ast_expression *field)
262 {
263     const ast_expression *outtype;
264
265     ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
266
267     if (field->expression.vtype != TYPE_FIELD) {
268         mem_d(self);
269         return NULL;
270     }
271
272     outtype = field->expression.next;
273     if (!outtype) {
274         mem_d(self);
275         /* Error: field has no type... */
276         return NULL;
277     }
278
279     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
280
281     self->expression.vtype = outtype->expression.vtype;
282     self->expression.next  = ast_type_copy(ctx, outtype->expression.next);
283
284     self->entity = entity;
285     self->field  = field;
286
287     return self;
288 }
289
290 void ast_entfield_delete(ast_entfield *self)
291 {
292     ast_unref(self->entity);
293     ast_unref(self->field);
294     ast_expression_delete((ast_expression*)self);
295     mem_d(self);
296 }
297
298 ast_member* ast_member_new(lex_ctx ctx, ast_expression *owner, unsigned int field)
299 {
300     ast_instantiate(ast_member, ctx, ast_member_delete);
301     if (field >= 3) {
302         mem_d(self);
303         return NULL;
304     }
305
306     if (owner->expression.vtype != TYPE_FLOAT &&
307         owner->expression.vtype != TYPE_FIELD) {
308         printf("ast_member on an invalid owner of type %i\n", (int)owner->expression.vtype);
309         mem_d(self);
310         return NULL;
311     }
312
313     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
314
315     if (owner->expression.vtype == TYPE_VECTOR) {
316         self->expression.vtype = TYPE_FLOAT;
317         self->expression.next  = NULL;
318     } else {
319         self->expression.vtype = TYPE_FIELD;
320         self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
321     }
322
323     self->owner = owner;
324     self->field = field;
325
326     return self;
327 }
328
329 void ast_member_delete(ast_member *self)
330 {
331     ast_unref(self->owner);
332     ast_expression_delete((ast_expression*)self);
333     mem_d(self);
334 }
335
336 ast_ifthen* ast_ifthen_new(lex_ctx ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
337 {
338     ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
339     if (!ontrue && !onfalse) {
340         /* because it is invalid */
341         mem_d(self);
342         return NULL;
343     }
344     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
345
346     self->cond     = cond;
347     self->on_true  = ontrue;
348     self->on_false = onfalse;
349
350     return self;
351 }
352
353 void ast_ifthen_delete(ast_ifthen *self)
354 {
355     ast_unref(self->cond);
356     if (self->on_true)
357         ast_unref(self->on_true);
358     if (self->on_false)
359         ast_unref(self->on_false);
360     ast_expression_delete((ast_expression*)self);
361     mem_d(self);
362 }
363
364 ast_ternary* ast_ternary_new(lex_ctx ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
365 {
366     ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
367     /* This time NEITHER must be NULL */
368     if (!ontrue || !onfalse) {
369         mem_d(self);
370         return NULL;
371     }
372     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
373
374     self->cond     = cond;
375     self->on_true  = ontrue;
376     self->on_false = onfalse;
377     self->phi_out  = NULL;
378
379     return self;
380 }
381
382 void ast_ternary_delete(ast_ternary *self)
383 {
384     ast_unref(self->cond);
385     ast_unref(self->on_true);
386     ast_unref(self->on_false);
387     ast_expression_delete((ast_expression*)self);
388     mem_d(self);
389 }
390
391 ast_loop* ast_loop_new(lex_ctx ctx,
392                        ast_expression *initexpr,
393                        ast_expression *precond,
394                        ast_expression *postcond,
395                        ast_expression *increment,
396                        ast_expression *body)
397 {
398     ast_instantiate(ast_loop, ctx, ast_loop_delete);
399     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
400
401     self->initexpr  = initexpr;
402     self->precond   = precond;
403     self->postcond  = postcond;
404     self->increment = increment;
405     self->body      = body;
406
407     return self;
408 }
409
410 void ast_loop_delete(ast_loop *self)
411 {
412     if (self->initexpr)
413         ast_unref(self->initexpr);
414     if (self->precond)
415         ast_unref(self->precond);
416     if (self->postcond)
417         ast_unref(self->postcond);
418     if (self->increment)
419         ast_unref(self->increment);
420     if (self->body)
421         ast_unref(self->body);
422     ast_expression_delete((ast_expression*)self);
423     mem_d(self);
424 }
425
426 ast_call* ast_call_new(lex_ctx ctx,
427                        ast_expression *funcexpr)
428 {
429     ast_instantiate(ast_call, ctx, ast_call_delete);
430     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
431
432     MEM_VECTOR_INIT(self, params);
433
434     self->func = funcexpr;
435
436     return self;
437 }
438 MEM_VEC_FUNCTIONS(ast_call, ast_expression*, params)
439
440 void ast_call_delete(ast_call *self)
441 {
442     size_t i;
443     for (i = 0; i < self->params_count; ++i)
444         ast_unref(self->params[i]);
445     MEM_VECTOR_CLEAR(self, params);
446
447     if (self->func)
448         ast_unref(self->func);
449
450     ast_expression_delete((ast_expression*)self);
451     mem_d(self);
452 }
453
454 ast_store* ast_store_new(lex_ctx ctx, int op,
455                          ast_expression *dest, ast_expression *source)
456 {
457     ast_instantiate(ast_store, ctx, ast_store_delete);
458     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
459
460     self->op = op;
461     self->dest = dest;
462     self->source = source;
463
464     return self;
465 }
466
467 void ast_store_delete(ast_store *self)
468 {
469     ast_unref(self->dest);
470     ast_unref(self->source);
471     ast_expression_delete((ast_expression*)self);
472     mem_d(self);
473 }
474
475 ast_block* ast_block_new(lex_ctx ctx)
476 {
477     ast_instantiate(ast_block, ctx, ast_block_delete);
478     ast_expression_init((ast_expression*)self,
479                         (ast_expression_codegen*)&ast_block_codegen);
480
481     MEM_VECTOR_INIT(self, locals);
482     MEM_VECTOR_INIT(self, exprs);
483
484     return self;
485 }
486 MEM_VEC_FUNCTIONS(ast_block, ast_value*, locals)
487 MEM_VEC_FUNCTIONS(ast_block, ast_expression*, exprs)
488
489 void ast_block_delete(ast_block *self)
490 {
491     size_t i;
492     for (i = 0; i < self->exprs_count; ++i)
493         ast_unref(self->exprs[i]);
494     MEM_VECTOR_CLEAR(self, exprs);
495     for (i = 0; i < self->locals_count; ++i)
496         ast_delete(self->locals[i]);
497     MEM_VECTOR_CLEAR(self, locals);
498     ast_expression_delete((ast_expression*)self);
499     mem_d(self);
500 }
501
502 bool ast_block_set_type(ast_block *self, ast_expression *from)
503 {
504     if (self->expression.next)
505         ast_delete(self->expression.next);
506     self->expression.vtype = from->expression.vtype;
507     if (from->expression.next) {
508         self->expression.next = ast_type_copy(self->expression.node.context, from->expression.next);
509         if (!self->expression.next)
510             return false;
511     }
512     return true;
513 }
514
515 ast_function* ast_function_new(lex_ctx ctx, const char *name, ast_value *vtype)
516 {
517     ast_instantiate(ast_function, ctx, ast_function_delete);
518
519     if (!vtype ||
520         vtype->isconst ||
521         vtype->expression.vtype != TYPE_FUNCTION)
522     {
523         mem_d(self);
524         return NULL;
525     }
526
527     self->vtype = vtype;
528     self->name = name ? util_strdup(name) : NULL;
529     MEM_VECTOR_INIT(self, blocks);
530
531     self->labelcount = 0;
532     self->builtin = 0;
533
534     self->ir_func = NULL;
535     self->curblock = NULL;
536
537     self->breakblock    = NULL;
538     self->continueblock = NULL;
539
540     vtype->isconst = true;
541     vtype->constval.vfunc = self;
542
543     return self;
544 }
545
546 MEM_VEC_FUNCTIONS(ast_function, ast_block*, blocks)
547
548 void ast_function_delete(ast_function *self)
549 {
550     size_t i;
551     if (self->name)
552         mem_d((void*)self->name);
553     if (self->vtype) {
554         /* ast_value_delete(self->vtype); */
555         self->vtype->isconst = false;
556         self->vtype->constval.vfunc = NULL;
557         /* We use unref - if it was stored in a global table it is supposed
558          * to be deleted from *there*
559          */
560         ast_unref(self->vtype);
561     }
562     for (i = 0; i < self->blocks_count; ++i)
563         ast_delete(self->blocks[i]);
564     MEM_VECTOR_CLEAR(self, blocks);
565     mem_d(self);
566 }
567
568 static void ast_util_hexitoa(char *buf, size_t size, unsigned int num)
569 {
570     unsigned int base = 10;
571 #define checknul() do { if (size == 1) { *buf = 0; return; } } while (0)
572 #define addch(x) do { *buf++ = (x); --size; checknul(); } while (0)
573     if (size < 1)
574         return;
575     checknul();
576     if (!num)
577         addch('0');
578     else {
579         while (num)
580         {
581             int digit = num % base;
582             num /= base;
583             addch('0' + digit);
584         }
585     }
586
587     *buf = 0;
588 #undef addch
589 #undef checknul
590 }
591
592 const char* ast_function_label(ast_function *self, const char *prefix)
593 {
594     size_t id = (self->labelcount++);
595     size_t len = strlen(prefix);
596     strncpy(self->labelbuf, prefix, sizeof(self->labelbuf));
597     ast_util_hexitoa(self->labelbuf + len, sizeof(self->labelbuf)-len, id);
598     return self->labelbuf;
599 }
600
601 /*********************************************************************/
602 /* AST codegen part
603  * by convention you must never pass NULL to the 'ir_value **out'
604  * parameter. If you really don't care about the output, pass a dummy.
605  * But I can't imagine a pituation where the output is truly unnecessary.
606  */
607
608 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
609 {
610     /* NOTE: This is the codegen for a variable used in an expression.
611      * It is not the codegen to generate the value. For this purpose,
612      * ast_local_codegen and ast_global_codegen are to be used before this
613      * is executed. ast_function_codegen should take care of its locals,
614      * and the ast-user should take care of ast_global_codegen to be used
615      * on all the globals.
616      */
617     if (!self->ir_v) {
618         printf("ast_value used before generated (%s)\n", self->name);
619         return false;
620     }
621     *out = self->ir_v;
622     return true;
623 }
624
625 bool ast_global_codegen(ast_value *self, ir_builder *ir)
626 {
627     ir_value *v = NULL;
628     if (self->isconst && self->expression.vtype == TYPE_FUNCTION)
629     {
630         ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->expression.vtype);
631         if (!func)
632             return false;
633
634         self->constval.vfunc->ir_func = func;
635         self->ir_v = func->value;
636         /* The function is filled later on ast_function_codegen... */
637         return true;
638     }
639
640     if (self->expression.vtype == TYPE_FIELD) {
641         v = ir_builder_create_field(ir, self->name, self->expression.next->expression.vtype);
642         if (!v)
643             return false;
644         if (self->isconst) {
645             printf("TODO: constant field pointers with value\n");
646             goto error;
647         }
648         self->ir_v = v;
649         return true;
650     }
651
652     v = ir_builder_create_global(ir, self->name, self->expression.vtype);
653     if (!v)
654         return false;
655
656     if (self->isconst) {
657         switch (self->expression.vtype)
658         {
659             case TYPE_FLOAT:
660                 if (!ir_value_set_float(v, self->constval.vfloat))
661                     goto error;
662                 break;
663             case TYPE_VECTOR:
664                 if (!ir_value_set_vector(v, self->constval.vvec))
665                     goto error;
666                 break;
667             case TYPE_STRING:
668                 if (!ir_value_set_string(v, self->constval.vstring))
669                     goto error;
670                 break;
671             case TYPE_FUNCTION:
672                 printf("global of type function not properly generated\n");
673                 goto error;
674                 /* Cannot generate an IR value for a function,
675                  * need a pointer pointing to a function rather.
676                  */
677             default:
678                 printf("TODO: global constant type %i\n", self->expression.vtype);
679                 break;
680         }
681     }
682
683     /* link us to the ir_value */
684     self->ir_v = v;
685     return true;
686
687 error: /* clean up */
688     ir_value_delete(v);
689     return false;
690 }
691
692 bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
693 {
694     ir_value *v = NULL;
695     if (self->isconst && self->expression.vtype == TYPE_FUNCTION)
696     {
697         /* Do we allow local functions? I think not...
698          * this is NOT a function pointer atm.
699          */
700         return false;
701     }
702
703     v = ir_function_create_local(func, self->name, self->expression.vtype, param);
704     if (!v)
705         return false;
706
707     /* A constant local... hmmm...
708      * I suppose the IR will have to deal with this
709      */
710     if (self->isconst) {
711         switch (self->expression.vtype)
712         {
713             case TYPE_FLOAT:
714                 if (!ir_value_set_float(v, self->constval.vfloat))
715                     goto error;
716                 break;
717             case TYPE_VECTOR:
718                 if (!ir_value_set_vector(v, self->constval.vvec))
719                     goto error;
720                 break;
721             case TYPE_STRING:
722                 if (!ir_value_set_string(v, self->constval.vstring))
723                     goto error;
724                 break;
725             default:
726                 printf("TODO: global constant type %i\n", self->expression.vtype);
727                 break;
728         }
729     }
730
731     /* link us to the ir_value */
732     self->ir_v = v;
733     return true;
734
735 error: /* clean up */
736     ir_value_delete(v);
737     return false;
738 }
739
740 bool ast_function_codegen(ast_function *self, ir_builder *ir)
741 {
742     ir_function *irf;
743     ir_value    *dummy;
744     ast_expression_common *ec;
745     size_t    i;
746
747     irf = self->ir_func;
748     if (!irf) {
749         printf("ast_function's related ast_value was not generated yet\n");
750         return false;
751     }
752
753     /* fill the parameter list */
754     ec = &self->vtype->expression;
755     for (i = 0; i < ec->params_count; ++i)
756     {
757         if (!ir_function_params_add(irf, ec->params[i]->expression.vtype))
758             return false;
759         if (!self->builtin) {
760             if (!ast_local_codegen(ec->params[i], self->ir_func, true))
761                 return false;
762         }
763     }
764
765     if (self->builtin) {
766         irf->builtin = self->builtin;
767         return true;
768     }
769
770     self->curblock = ir_function_create_block(irf, "entry");
771     if (!self->curblock)
772         return false;
773
774     for (i = 0; i < self->blocks_count; ++i) {
775         ast_expression_codegen *gen = self->blocks[i]->expression.codegen;
776         if (!(*gen)((ast_expression*)self->blocks[i], self, false, &dummy))
777             return false;
778     }
779
780     /* TODO: check return types */
781     if (!self->curblock->is_return)
782     {
783         if (!self->vtype->expression.next ||
784             self->vtype->expression.next->expression.vtype == TYPE_VOID)
785         {
786             return ir_block_create_return(self->curblock, NULL);
787         }
788         else
789         {
790             /* error("missing return"); */
791             return false;
792         }
793     }
794     return true;
795 }
796
797 /* Note, you will not see ast_block_codegen generate ir_blocks.
798  * To the AST and the IR, blocks are 2 different things.
799  * In the AST it represents a block of code, usually enclosed in
800  * curly braces {...}.
801  * While in the IR it represents a block in terms of control-flow.
802  */
803 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
804 {
805     size_t i;
806
807     /* We don't use this
808      * Note: an ast-representation using the comma-operator
809      * of the form: (a, b, c) = x should not assign to c...
810      */
811     (void)lvalue;
812
813     /* output is NULL at first, we'll have each expression
814      * assign to out output, thus, a comma-operator represention
815      * using an ast_block will return the last generated value,
816      * so: (b, c) + a  executed both b and c, and returns c,
817      * which is then added to a.
818      */
819     *out = NULL;
820
821     /* generate locals */
822     for (i = 0; i < self->locals_count; ++i)
823     {
824         if (!ast_local_codegen(self->locals[i], func->ir_func, false))
825             return false;
826     }
827
828     for (i = 0; i < self->exprs_count; ++i)
829     {
830         ast_expression_codegen *gen = self->exprs[i]->expression.codegen;
831         if (!(*gen)(self->exprs[i], func, false, out))
832             return false;
833     }
834
835     return true;
836 }
837
838 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
839 {
840     ast_expression_codegen *cgen;
841     ir_value *left, *right;
842
843     cgen = self->dest->expression.codegen;
844     /* lvalue! */
845     if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
846         return false;
847
848     cgen = self->source->expression.codegen;
849     /* rvalue! */
850     if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
851         return false;
852
853     if (!ir_block_create_store_op(func->curblock, self->op, left, right))
854         return false;
855
856     /* Theoretically, an assinment returns its left side as an
857      * lvalue, if we don't need an lvalue though, we return
858      * the right side as an rvalue, otherwise we have to
859      * somehow know whether or not we need to dereference the pointer
860      * on the left side - that is: OP_LOAD if it was an address.
861      * Also: in original QC we cannot OP_LOADP *anyway*.
862      */
863     *out = (lvalue ? left : right);
864
865     return true;
866 }
867
868 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
869 {
870     ast_expression_codegen *cgen;
871     ir_value *left, *right;
872
873     /* In the context of a binary operation, we can disregard
874      * the lvalue flag.
875      */
876      (void)lvalue;
877
878     cgen = self->left->expression.codegen;
879     /* lvalue! */
880     if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
881         return false;
882
883     cgen = self->right->expression.codegen;
884     /* rvalue! */
885     if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
886         return false;
887
888     *out = ir_block_create_binop(func->curblock, ast_function_label(func, "bin"),
889                                  self->op, left, right);
890     if (!*out)
891         return false;
892
893     return true;
894 }
895
896 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
897 {
898     ast_expression_codegen *cgen;
899     ir_value *operand;
900
901     /* In the context of a unary operation, we can disregard
902      * the lvalue flag.
903      */
904     (void)lvalue;
905
906     cgen = self->operand->expression.codegen;
907     /* lvalue! */
908     if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
909         return false;
910
911     *out = ir_block_create_unary(func->curblock, ast_function_label(func, "unary"),
912                                  self->op, operand);
913     if (!*out)
914         return false;
915
916     return true;
917 }
918
919 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
920 {
921     ast_expression_codegen *cgen;
922     ir_value *operand;
923
924     /* In the context of a return operation, we can disregard
925      * the lvalue flag.
926      */
927     (void)lvalue;
928
929     cgen = self->operand->expression.codegen;
930     /* lvalue! */
931     if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
932         return false;
933
934     if (!ir_block_create_return(func->curblock, operand))
935         return false;
936
937     return true;
938 }
939
940 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
941 {
942     ast_expression_codegen *cgen;
943     ir_value *ent, *field;
944
945     /* This function needs to take the 'lvalue' flag into account!
946      * As lvalue we provide a field-pointer, as rvalue we provide the
947      * value in a temp.
948      */
949
950     cgen = self->entity->expression.codegen;
951     if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
952         return false;
953
954     cgen = self->field->expression.codegen;
955     if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
956         return false;
957
958     if (lvalue) {
959         /* address! */
960         *out = ir_block_create_fieldaddress(func->curblock, ast_function_label(func, "efa"),
961                                             ent, field);
962     } else {
963         *out = ir_block_create_load_from_ent(func->curblock, ast_function_label(func, "efv"),
964                                              ent, field, self->expression.vtype);
965     }
966     if (!*out)
967         return false;
968
969     /* Hm that should be it... */
970     return true;
971 }
972
973 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
974 {
975     ast_expression_codegen *cgen;
976     ir_value *vec;
977
978     cgen = self->owner->expression.codegen;
979     if (!(*cgen)((ast_expression*)(self->owner), func, true, &vec))
980         return false;
981
982     if (vec->vtype != TYPE_VECTOR &&
983         !(vec->vtype == TYPE_FIELD && self->owner->expression.next->expression.vtype == TYPE_VECTOR))
984     {
985         return false;
986     }
987
988     *out = ir_value_vector_member(vec, self->field);
989
990     return (*out != NULL);
991 }
992
993 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
994 {
995     ast_expression_codegen *cgen;
996
997     ir_value *condval;
998     ir_value *dummy;
999
1000     ir_block *cond = func->curblock;
1001     ir_block *ontrue;
1002     ir_block *onfalse;
1003     ir_block *merge;
1004
1005     /* We don't output any value, thus also don't care about r/lvalue */
1006     (void)out;
1007     (void)lvalue;
1008
1009     /* generate the condition */
1010     func->curblock = cond;
1011     cgen = self->cond->expression.codegen;
1012     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
1013         return false;
1014
1015     /* on-true path */
1016
1017     if (self->on_true) {
1018         /* create on-true block */
1019         ontrue = ir_function_create_block(func->ir_func, ast_function_label(func, "ontrue"));
1020         if (!ontrue)
1021             return false;
1022
1023         /* enter the block */
1024         func->curblock = ontrue;
1025
1026         /* generate */
1027         cgen = self->on_true->expression.codegen;
1028         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
1029             return false;
1030     } else
1031         ontrue = NULL;
1032
1033     /* on-false path */
1034     if (self->on_false) {
1035         /* create on-false block */
1036         onfalse = ir_function_create_block(func->ir_func, ast_function_label(func, "onfalse"));
1037         if (!onfalse)
1038             return false;
1039
1040         /* enter the block */
1041         func->curblock = onfalse;
1042
1043         /* generate */
1044         cgen = self->on_false->expression.codegen;
1045         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
1046             return false;
1047     } else
1048         onfalse = NULL;
1049
1050     /* Merge block were they all merge in to */
1051     merge = ir_function_create_block(func->ir_func, ast_function_label(func, "endif"));
1052     if (!merge)
1053         return false;
1054
1055     /* add jumps ot the merge block */
1056     if (ontrue && !ir_block_create_jump(ontrue, merge))
1057         return false;
1058     if (onfalse && !ir_block_create_jump(onfalse, merge))
1059         return false;
1060
1061     /* we create the if here, that way all blocks are ordered :)
1062      */
1063     if (!ir_block_create_if(cond, condval,
1064                             (ontrue  ? ontrue  : merge),
1065                             (onfalse ? onfalse : merge)))
1066     {
1067         return false;
1068     }
1069
1070     /* Now enter the merge block */
1071     func->curblock = merge;
1072
1073     return true;
1074 }
1075
1076 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
1077 {
1078     ast_expression_codegen *cgen;
1079
1080     ir_value *condval;
1081     ir_value *trueval, *falseval;
1082     ir_instr *phi;
1083
1084     ir_block *cond = func->curblock;
1085     ir_block *ontrue;
1086     ir_block *onfalse;
1087     ir_block *merge;
1088
1089     /* In theory it shouldn't be possible to pass through a node twice, but
1090      * in case we add any kind of optimization pass for the AST itself, it
1091      * may still happen, thus we remember a created ir_value and simply return one
1092      * if it already exists.
1093      */
1094     if (self->phi_out) {
1095         *out = self->phi_out;
1096         return true;
1097     }
1098
1099     /* Ternary can never create an lvalue... */
1100     if (lvalue)
1101         return false;
1102
1103     /* In the following, contraty to ast_ifthen, we assume both paths exist. */
1104
1105     /* generate the condition */
1106     func->curblock = cond;
1107     cgen = self->cond->expression.codegen;
1108     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
1109         return false;
1110
1111     /* create on-true block */
1112     ontrue = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_T"));
1113     if (!ontrue)
1114         return false;
1115     else
1116     {
1117         /* enter the block */
1118         func->curblock = ontrue;
1119
1120         /* generate */
1121         cgen = self->on_true->expression.codegen;
1122         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
1123             return false;
1124     }
1125
1126     /* create on-false block */
1127     onfalse = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_F"));
1128     if (!onfalse)
1129         return false;
1130     else
1131     {
1132         /* enter the block */
1133         func->curblock = onfalse;
1134
1135         /* generate */
1136         cgen = self->on_false->expression.codegen;
1137         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
1138             return false;
1139     }
1140
1141     /* create merge block */
1142     merge = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_out"));
1143     if (!merge)
1144         return false;
1145     /* jump to merge block */
1146     if (!ir_block_create_jump(ontrue, merge))
1147         return false;
1148     if (!ir_block_create_jump(onfalse, merge))
1149         return false;
1150
1151     /* create if instruction */
1152     if (!ir_block_create_if(cond, condval, ontrue, onfalse))
1153         return false;
1154
1155     /* Now enter the merge block */
1156     func->curblock = merge;
1157
1158     /* Here, now, we need a PHI node
1159      * but first some sanity checking...
1160      */
1161     if (trueval->vtype != falseval->vtype) {
1162         /* error("ternary with different types on the two sides"); */
1163         return false;
1164     }
1165
1166     /* create PHI */
1167     phi = ir_block_create_phi(merge, ast_function_label(func, "phi"), trueval->vtype);
1168     if (!phi ||
1169         !ir_phi_add(phi, ontrue,  trueval) ||
1170         !ir_phi_add(phi, onfalse, falseval))
1171     {
1172         return false;
1173     }
1174
1175     self->phi_out = ir_phi_value(phi);
1176     *out = self->phi_out;
1177
1178     return true;
1179 }
1180
1181 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
1182 {
1183     ast_expression_codegen *cgen;
1184
1185     ir_value *dummy      = NULL;
1186     ir_value *precond    = NULL;
1187     ir_value *postcond   = NULL;
1188
1189     /* Since we insert some jumps "late" so we have blocks
1190      * ordered "nicely", we need to keep track of the actual end-blocks
1191      * of expressions to add the jumps to.
1192      */
1193     ir_block *bbody      = NULL, *end_bbody      = NULL;
1194     ir_block *bprecond   = NULL, *end_bprecond   = NULL;
1195     ir_block *bpostcond  = NULL, *end_bpostcond  = NULL;
1196     ir_block *bincrement = NULL, *end_bincrement = NULL;
1197     ir_block *bout       = NULL, *bin            = NULL;
1198
1199     /* let's at least move the outgoing block to the end */
1200     size_t    bout_id;
1201
1202     /* 'break' and 'continue' need to be able to find the right blocks */
1203     ir_block *bcontinue     = NULL;
1204     ir_block *bbreak        = NULL;
1205
1206     ir_block *old_bcontinue = NULL;
1207     ir_block *old_bbreak    = NULL;
1208
1209     ir_block *tmpblock      = NULL;
1210
1211     (void)lvalue;
1212     (void)out;
1213
1214     /* NOTE:
1215      * Should we ever need some kind of block ordering, better make this function
1216      * move blocks around than write a block ordering algorithm later... after all
1217      * the ast and ir should work together, not against each other.
1218      */
1219
1220     /* initexpr doesn't get its own block, it's pointless, it could create more blocks
1221      * anyway if for example it contains a ternary.
1222      */
1223     if (self->initexpr)
1224     {
1225         cgen = self->initexpr->expression.codegen;
1226         if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
1227             return false;
1228     }
1229
1230     /* Store the block from which we enter this chaos */
1231     bin = func->curblock;
1232
1233     /* The pre-loop condition needs its own block since we
1234      * need to be able to jump to the start of that expression.
1235      */
1236     if (self->precond)
1237     {
1238         bprecond = ir_function_create_block(func->ir_func, ast_function_label(func, "pre_loop_cond"));
1239         if (!bprecond)
1240             return false;
1241
1242         /* the pre-loop-condition the least important place to 'continue' at */
1243         bcontinue = bprecond;
1244
1245         /* enter */
1246         func->curblock = bprecond;
1247
1248         /* generate */
1249         cgen = self->precond->expression.codegen;
1250         if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
1251             return false;
1252
1253         end_bprecond = func->curblock;
1254     } else {
1255         bprecond = end_bprecond = NULL;
1256     }
1257
1258     /* Now the next blocks won't be ordered nicely, but we need to
1259      * generate them this early for 'break' and 'continue'.
1260      */
1261     if (self->increment) {
1262         bincrement = ir_function_create_block(func->ir_func, ast_function_label(func, "loop_increment"));
1263         if (!bincrement)
1264             return false;
1265         bcontinue = bincrement; /* increment comes before the pre-loop-condition */
1266     } else {
1267         bincrement = end_bincrement = NULL;
1268     }
1269
1270     if (self->postcond) {
1271         bpostcond = ir_function_create_block(func->ir_func, ast_function_label(func, "post_loop_cond"));
1272         if (!bpostcond)
1273             return false;
1274         bcontinue = bpostcond; /* postcond comes before the increment */
1275     } else {
1276         bpostcond = end_bpostcond = NULL;
1277     }
1278
1279     bout_id = func->ir_func->blocks_count;
1280     bout = ir_function_create_block(func->ir_func, ast_function_label(func, "after_loop"));
1281     if (!bout)
1282         return false;
1283     bbreak = bout;
1284
1285     /* The loop body... */
1286     if (self->body)
1287     {
1288         bbody = ir_function_create_block(func->ir_func, ast_function_label(func, "loop_body"));
1289         if (!bbody)
1290             return false;
1291
1292         /* enter */
1293         func->curblock = bbody;
1294
1295         old_bbreak          = func->breakblock;
1296         old_bcontinue       = func->continueblock;
1297         func->breakblock    = bbreak;
1298         func->continueblock = bcontinue;
1299
1300         /* generate */
1301         cgen = self->body->expression.codegen;
1302         if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
1303             return false;
1304
1305         end_bbody = func->curblock;
1306         func->breakblock    = old_bbreak;
1307         func->continueblock = old_bcontinue;
1308     }
1309
1310     /* post-loop-condition */
1311     if (self->postcond)
1312     {
1313         /* enter */
1314         func->curblock = bpostcond;
1315
1316         /* generate */
1317         cgen = self->postcond->expression.codegen;
1318         if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
1319             return false;
1320
1321         end_bpostcond = func->curblock;
1322     }
1323
1324     /* The incrementor */
1325     if (self->increment)
1326     {
1327         /* enter */
1328         func->curblock = bincrement;
1329
1330         /* generate */
1331         cgen = self->increment->expression.codegen;
1332         if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
1333             return false;
1334
1335         end_bincrement = func->curblock;
1336     }
1337
1338     /* In any case now, we continue from the outgoing block */
1339     func->curblock = bout;
1340
1341     /* Now all blocks are in place */
1342     /* From 'bin' we jump to whatever comes first */
1343     if      (bprecond)   tmpblock = bprecond;
1344     else if (bbody)      tmpblock = bbody;
1345     else if (bpostcond)  tmpblock = bpostcond;
1346     else                 tmpblock = bout;
1347     if (!ir_block_create_jump(bin, tmpblock))
1348         return false;
1349
1350     /* From precond */
1351     if (bprecond)
1352     {
1353         ir_block *ontrue, *onfalse;
1354         if      (bbody)      ontrue = bbody;
1355         else if (bincrement) ontrue = bincrement;
1356         else if (bpostcond)  ontrue = bpostcond;
1357         else                 ontrue = bprecond;
1358         onfalse = bout;
1359         if (!ir_block_create_if(end_bprecond, precond, ontrue, onfalse))
1360             return false;
1361     }
1362
1363     /* from body */
1364     if (bbody)
1365     {
1366         if      (bincrement) tmpblock = bincrement;
1367         else if (bpostcond)  tmpblock = bpostcond;
1368         else if (bprecond)   tmpblock = bprecond;
1369         else                 tmpblock = bout;
1370         if (!ir_block_create_jump(end_bbody, tmpblock))
1371             return false;
1372     }
1373
1374     /* from increment */
1375     if (bincrement)
1376     {
1377         if      (bpostcond)  tmpblock = bpostcond;
1378         else if (bprecond)   tmpblock = bprecond;
1379         else if (bbody)      tmpblock = bbody;
1380         else                 tmpblock = bout;
1381         if (!ir_block_create_jump(end_bincrement, tmpblock))
1382             return false;
1383     }
1384
1385     /* from postcond */
1386     if (bpostcond)
1387     {
1388         ir_block *ontrue, *onfalse;
1389         if      (bprecond)   ontrue = bprecond;
1390         else if (bbody)      ontrue = bbody;
1391         else if (bincrement) ontrue = bincrement;
1392         else                 ontrue = bpostcond;
1393         onfalse = bout;
1394         if (!ir_block_create_if(end_bpostcond, postcond, ontrue, onfalse))
1395             return false;
1396     }
1397
1398     /* Move 'bout' to the end */
1399     if (!ir_function_blocks_remove(func->ir_func, bout_id) ||
1400         !ir_function_blocks_add(func->ir_func, bout))
1401     {
1402         ir_block_delete(bout);
1403         return false;
1404     }
1405
1406     return true;
1407 }
1408
1409 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
1410 {
1411     ast_expression_codegen *cgen;
1412     ir_value_vector         params;
1413     ir_instr               *callinstr;
1414     size_t i;
1415
1416     ir_value *funval = NULL;
1417
1418     /* return values are never rvalues */
1419     (void)lvalue;
1420
1421     cgen = self->func->expression.codegen;
1422     if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
1423         return false;
1424     if (!funval)
1425         return false;
1426
1427     MEM_VECTOR_INIT(&params, v);
1428
1429     /* parameters */
1430     for (i = 0; i < self->params_count; ++i)
1431     {
1432         ir_value *param;
1433         ast_expression *expr = self->params[i];
1434
1435         cgen = expr->expression.codegen;
1436         if (!(*cgen)(expr, func, false, &param))
1437             goto error;
1438         if (!param)
1439             goto error;
1440         if (!ir_value_vector_v_add(&params, param))
1441             goto error;
1442     }
1443
1444     callinstr = ir_block_create_call(func->curblock, ast_function_label(func, "call"), funval);
1445     if (!callinstr)
1446         goto error;
1447
1448     for (i = 0; i < params.v_count; ++i) {
1449         if (!ir_call_param(callinstr, params.v[i]))
1450             goto error;
1451     }
1452
1453     *out = ir_call_value(callinstr);
1454
1455     MEM_VECTOR_CLEAR(&params, v);
1456     return true;
1457 error:
1458     MEM_VECTOR_CLEAR(&params, v);
1459     return false;
1460 }