]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ast.c
Updated readme
[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);                            \
36     ( (ast_node*)self )->node.destroy = (ast_node_delete*)destroyfn
37
38 /* It must not be possible to get here. */
39 static 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)
47 {
48     self->node.context = ctx;
49     self->node.destroy = &_ast_node_destroy;
50     self->node.keep    = false;
51 }
52
53 /* General expression initialization */
54 static void ast_expression_init(ast_expression *self,
55                                 ast_expression_codegen *codegen)
56 {
57     self->expression.codegen = codegen;
58     self->expression.vtype   = TYPE_VOID;
59     self->expression.next    = NULL;
60 }
61
62 static void ast_expression_delete(ast_expression *self)
63 {
64     if (self->expression.next)
65         ast_delete(self->expression.next);
66 }
67
68 static void ast_expression_delete_full(ast_expression *self)
69 {
70     ast_expression_delete(self);
71     mem_d(self);
72 }
73
74 static ast_expression* ast_type_copy(lex_ctx ctx, const ast_expression *ex)
75 {
76     const ast_expression_common *cpex;
77     ast_expression_common *selfex;
78
79     if (!ex)
80         return NULL;
81     else
82     {
83         ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
84
85         cpex   = &ex->expression;
86         selfex = &self->expression;
87
88         selfex->vtype = cpex->vtype;
89         if (cpex->next)
90         {
91             selfex->next = ast_type_copy(ctx, cpex->next);
92             if (!selfex->next) {
93                 mem_d(self);
94                 return NULL;
95             }
96         }
97         else
98             selfex->next = NULL;
99
100         /* This may never be codegen()d */
101         selfex->codegen = NULL;
102         return self;
103     }
104 }
105
106 ast_value* ast_value_new(lex_ctx ctx, const char *name, int t)
107 {
108     ast_instantiate(ast_value, ctx, ast_value_delete);
109     ast_expression_init((ast_expression*)self,
110                         (ast_expression_codegen*)&ast_value_codegen);
111     self->expression.node.keep = true; /* keep */
112
113     self->name = name ? util_strdup(name) : NULL;
114     self->expression.vtype = t;
115     self->expression.next  = NULL;
116     MEM_VECTOR_INIT(self, params);
117     self->isconst = false;
118     memset(&self->constval, 0, sizeof(self->constval));
119
120     self->ir_v    = NULL;
121
122     return self;
123 }
124 MEM_VEC_FUNCTIONS(ast_value, ast_value*, params)
125
126 void ast_value_delete(ast_value* self)
127 {
128     size_t i;
129     if (self->name)
130         mem_d((void*)self->name);
131     for (i = 0; i < self->params_count; ++i)
132         ast_value_delete(self->params[i]); /* delete, the ast_function is expected to die first */
133     MEM_VECTOR_CLEAR(self, params);
134     if (self->isconst) {
135         switch (self->expression.vtype)
136         {
137         case TYPE_STRING:
138             mem_d((void*)self->constval.vstring);
139             break;
140         case TYPE_FUNCTION:
141             /* unlink us from the function node */
142             self->constval.vfunc->vtype = NULL;
143             break;
144         /* NOTE: delete function? currently collected in
145          * the parser structure
146          */
147         default:
148             break;
149         }
150     }
151     ast_expression_delete((ast_expression*)self);
152     mem_d(self);
153 }
154
155 bool ast_value_set_name(ast_value *self, const char *name)
156 {
157     if (self->name)
158         mem_d((void*)self->name);
159     self->name = util_strdup(name);
160     return !!self->name;
161 }
162
163 ast_binary* ast_binary_new(lex_ctx ctx, int op,
164                            ast_expression* left, ast_expression* right)
165 {
166     ast_instantiate(ast_binary, ctx, ast_binary_delete);
167     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
168
169     self->op = op;
170     self->left = left;
171     self->right = right;
172
173     return self;
174 }
175
176 void ast_binary_delete(ast_binary *self)
177 {
178     ast_unref(self->left);
179     ast_unref(self->right);
180     ast_expression_delete((ast_expression*)self);
181     mem_d(self);
182 }
183
184 ast_entfield* ast_entfield_new(lex_ctx ctx, ast_expression *entity, ast_expression *field)
185 {
186     const ast_expression *outtype;
187
188     ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
189
190     if (field->expression.vtype != TYPE_FIELD) {
191         mem_d(self);
192         return NULL;
193     }
194
195     outtype = field->expression.next;
196     if (!outtype) {
197         mem_d(self);
198         /* Error: field has no type... */
199         return NULL;
200     }
201
202     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
203
204     self->expression.vtype = outtype->expression.vtype;
205     self->expression.next  = ast_type_copy(ctx, outtype->expression.next);
206
207     self->entity = entity;
208     self->field  = field;
209
210     return self;
211 }
212
213 void ast_entfield_delete(ast_entfield *self)
214 {
215     ast_unref(self->entity);
216     ast_unref(self->field);
217     ast_expression_delete((ast_expression*)self);
218     mem_d(self);
219 }
220
221 ast_ifthen* ast_ifthen_new(lex_ctx ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
222 {
223     ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
224     if (!ontrue && !onfalse) {
225         /* because it is invalid */
226         mem_d(self);
227         return NULL;
228     }
229     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
230
231     self->cond     = cond;
232     self->on_true  = ontrue;
233     self->on_false = onfalse;
234
235     return self;
236 }
237
238 void ast_ifthen_delete(ast_ifthen *self)
239 {
240     ast_unref(self->cond);
241     if (self->on_true)
242         ast_unref(self->on_true);
243     if (self->on_false)
244         ast_unref(self->on_false);
245     ast_expression_delete((ast_expression*)self);
246     mem_d(self);
247 }
248
249 ast_ternary* ast_ternary_new(lex_ctx ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
250 {
251     ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
252     /* This time NEITHER must be NULL */
253     if (!ontrue || !onfalse) {
254         mem_d(self);
255         return NULL;
256     }
257     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
258
259     self->cond     = cond;
260     self->on_true  = ontrue;
261     self->on_false = onfalse;
262     self->phi_out  = NULL;
263
264     return self;
265 }
266
267 void ast_ternary_delete(ast_ternary *self)
268 {
269     ast_unref(self->cond);
270     ast_unref(self->on_true);
271     ast_unref(self->on_false);
272     ast_expression_delete((ast_expression*)self);
273     mem_d(self);
274 }
275
276 ast_loop* ast_loop_new(lex_ctx ctx,
277                        ast_expression *initexpr,
278                        ast_expression *precond,
279                        ast_expression *postcond,
280                        ast_expression *increment,
281                        ast_expression *body)
282 {
283     ast_instantiate(ast_loop, ctx, ast_loop_delete);
284     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
285
286     self->initexpr  = initexpr;
287     self->precond   = precond;
288     self->postcond  = postcond;
289     self->increment = increment;
290     self->body      = body;
291
292     return self;
293 }
294
295 void ast_loop_delete(ast_loop *self)
296 {
297     if (self->initexpr)
298         ast_unref(self->initexpr);
299     if (self->precond)
300         ast_unref(self->precond);
301     if (self->postcond)
302         ast_unref(self->postcond);
303     if (self->increment)
304         ast_unref(self->increment);
305     if (self->body)
306         ast_unref(self->body);
307     ast_expression_delete((ast_expression*)self);
308     mem_d(self);
309 }
310
311 ast_store* ast_store_new(lex_ctx ctx, int op,
312                          ast_value *dest, ast_expression *source)
313 {
314     ast_instantiate(ast_store, ctx, ast_store_delete);
315     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
316
317     self->op = op;
318     self->dest = dest;
319     self->source = source;
320
321     return self;
322 }
323
324 void ast_store_delete(ast_store *self)
325 {
326     ast_unref(self->dest);
327     ast_unref(self->source);
328     ast_expression_delete((ast_expression*)self);
329     mem_d(self);
330 }
331
332 ast_block* ast_block_new(lex_ctx ctx)
333 {
334     ast_instantiate(ast_block, ctx, ast_block_delete);
335     ast_expression_init((ast_expression*)self,
336                         (ast_expression_codegen*)&ast_block_codegen);
337
338     MEM_VECTOR_INIT(self, locals);
339     MEM_VECTOR_INIT(self, exprs);
340
341     return self;
342 }
343 MEM_VEC_FUNCTIONS(ast_block, ast_value*, locals)
344 MEM_VEC_FUNCTIONS(ast_block, ast_expression*, exprs)
345
346 void ast_block_delete(ast_block *self)
347 {
348     size_t i;
349     for (i = 0; i < self->exprs_count; ++i)
350         ast_unref(self->exprs[i]);
351     MEM_VECTOR_CLEAR(self, exprs);
352     for (i = 0; i < self->locals_count; ++i)
353         ast_delete(self->locals[i]);
354     MEM_VECTOR_CLEAR(self, locals);
355     ast_expression_delete((ast_expression*)self);
356     mem_d(self);
357 }
358
359 ast_function* ast_function_new(lex_ctx ctx, const char *name, ast_value *vtype)
360 {
361     ast_instantiate(ast_function, ctx, ast_function_delete);
362
363     if (!vtype ||
364         vtype->isconst ||
365         vtype->expression.vtype != TYPE_FUNCTION)
366     {
367         mem_d(self);
368         return NULL;
369     }
370
371     self->vtype = vtype;
372     self->name = name ? util_strdup(name) : NULL;
373     MEM_VECTOR_INIT(self, blocks);
374
375     self->labelcount = 0;
376
377     self->ir_func = NULL;
378     self->curblock = NULL;
379
380     self->breakblock    = NULL;
381     self->continueblock = NULL;
382
383     vtype->isconst = true;
384     vtype->constval.vfunc = self;
385
386     return self;
387 }
388
389 MEM_VEC_FUNCTIONS(ast_function, ast_block*, blocks)
390
391 void ast_function_delete(ast_function *self)
392 {
393     size_t i;
394     if (self->name)
395         mem_d((void*)self->name);
396     if (self->vtype) {
397         /* ast_value_delete(self->vtype); */
398         self->vtype->isconst = false;
399         self->vtype->constval.vfunc = NULL;
400         /* We use unref - if it was stored in a global table it is supposed
401          * to be deleted from *there*
402          */
403         ast_unref(self->vtype);
404     }
405     for (i = 0; i < self->blocks_count; ++i)
406         ast_delete(self->blocks[i]);
407     MEM_VECTOR_CLEAR(self, blocks);
408     mem_d(self);
409 }
410
411 static void ast_util_hexitoa(char *buf, size_t size, unsigned int num)
412 {
413     unsigned int base = 10;
414 #define checknul() do { if (size == 1) { *buf = 0; return; } } while (0)
415 #define addch(x) do { *buf++ = (x); --size; checknul(); } while (0)
416     if (size < 1)
417         return;
418     checknul();
419     if (!num)
420         addch('0');
421     else {
422         while (num)
423         {
424             int digit = num % base;
425             num /= base;
426             addch('0' + digit);
427         }
428     }
429
430     *buf = 0;
431 #undef addch
432 #undef checknul
433 }
434
435 const char* ast_function_label(ast_function *self, const char *prefix)
436 {
437     size_t id = (self->labelcount++);
438     size_t len = strlen(prefix);
439     strncpy(self->labelbuf, prefix, sizeof(self->labelbuf));
440     ast_util_hexitoa(self->labelbuf + len, sizeof(self->labelbuf)-len, id);
441     return self->labelbuf;
442 }
443
444 /*********************************************************************/
445 /* AST codegen part
446  * by convention you must never pass NULL to the 'ir_value **out'
447  * parameter. If you really don't care about the output, pass a dummy.
448  * But I can't imagine a pituation where the output is truly unnecessary.
449  */
450
451 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
452 {
453     /* NOTE: This is the codegen for a variable used in an expression.
454      * It is not the codegen to generate the value. For this purpose,
455      * ast_local_codegen and ast_global_codegen are to be used before this
456      * is executed. ast_function_codegen should take care of its locals,
457      * and the ast-user should take care of ast_global_codegen to be used
458      * on all the globals.
459      */
460     if (!self->ir_v)
461         return false;
462     *out = self->ir_v;
463     return true;
464 }
465
466 bool ast_global_codegen(ast_value *self, ir_builder *ir)
467 {
468     ir_value *v = NULL;
469     if (self->isconst && self->expression.vtype == TYPE_FUNCTION)
470     {
471         ir_function *func = ir_builder_create_function(ir, self->name);
472         if (!func)
473             return false;
474
475         self->constval.vfunc->ir_func = func;
476         /* The function is filled later on ast_function_codegen... */
477         return true;
478     }
479
480     v = ir_builder_create_global(ir, self->name, self->expression.vtype);
481     if (!v)
482         return false;
483
484     if (self->isconst) {
485         switch (self->expression.vtype)
486         {
487             case TYPE_FLOAT:
488                 if (!ir_value_set_float(v, self->constval.vfloat))
489                     goto error;
490                 break;
491             case TYPE_VECTOR:
492                 if (!ir_value_set_vector(v, self->constval.vvec))
493                     goto error;
494                 break;
495             case TYPE_STRING:
496                 if (!ir_value_set_string(v, self->constval.vstring))
497                     goto error;
498                 break;
499             case TYPE_FUNCTION:
500                 /* Cannot generate an IR value for a function,
501                  * need a pointer pointing to a function rather.
502                  */
503                 goto error;
504             default:
505                 printf("TODO: global constant type %i\n", self->expression.vtype);
506                 break;
507         }
508     }
509
510     /* link us to the ir_value */
511     self->ir_v = v;
512     return true;
513
514 error: /* clean up */
515     ir_value_delete(v);
516     return false;
517 }
518
519 bool ast_local_codegen(ast_value *self, ir_function *func)
520 {
521     ir_value *v = NULL;
522     if (self->isconst && self->expression.vtype == TYPE_FUNCTION)
523     {
524         /* Do we allow local functions? I think not...
525          * this is NOT a function pointer atm.
526          */
527         return false;
528     }
529
530     v = ir_function_create_local(func, self->name, self->expression.vtype);
531     if (!v)
532         return false;
533
534     /* A constant local... hmmm...
535      * I suppose the IR will have to deal with this
536      */
537     if (self->isconst) {
538         switch (self->expression.vtype)
539         {
540             case TYPE_FLOAT:
541                 if (!ir_value_set_float(v, self->constval.vfloat))
542                     goto error;
543                 break;
544             case TYPE_VECTOR:
545                 if (!ir_value_set_vector(v, self->constval.vvec))
546                     goto error;
547                 break;
548             case TYPE_STRING:
549                 if (!ir_value_set_string(v, self->constval.vstring))
550                     goto error;
551                 break;
552             default:
553                 printf("TODO: global constant type %i\n", self->expression.vtype);
554                 break;
555         }
556     }
557
558     /* link us to the ir_value */
559     self->ir_v = v;
560     return true;
561
562 error: /* clean up */
563     ir_value_delete(v);
564     return false;
565 }
566
567 bool ast_function_codegen(ast_function *self, ir_builder *ir)
568 {
569     ir_function *irf;
570     ir_value    *dummy;
571     size_t    i;
572
573     irf = self->ir_func;
574     if (!irf) {
575         printf("ast_function's related ast_value was not generated yet\n");
576         return false;
577     }
578
579     self->curblock = ir_function_create_block(irf, "entry");
580     if (!self->curblock)
581         return false;
582
583     for (i = 0; i < self->blocks_count; ++i) {
584         ast_expression_codegen *gen = self->blocks[i]->expression.codegen;
585         if (!(*gen)((ast_expression*)self->blocks[i], self, false, &dummy))
586             return false;
587     }
588
589     /* TODO: check return types */
590     if (!self->curblock->is_return)
591     {
592         if (!self->vtype->expression.next ||
593             self->vtype->expression.next->expression.vtype == TYPE_VOID)
594             return ir_block_create_return(self->curblock, NULL);
595         else
596         {
597             /* error("missing return"); */
598             return false;
599         }
600     }
601     return true;
602 }
603
604 /* Note, you will not see ast_block_codegen generate ir_blocks.
605  * To the AST and the IR, blocks are 2 different things.
606  * In the AST it represents a block of code, usually enclosed in
607  * curly braces {...}.
608  * While in the IR it represents a block in terms of control-flow.
609  */
610 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
611 {
612     size_t i;
613
614     /* We don't use this
615      * Note: an ast-representation using the comma-operator
616      * of the form: (a, b, c) = x should not assign to c...
617      */
618     (void)lvalue;
619
620     /* output is NULL at first, we'll have each expression
621      * assign to out output, thus, a comma-operator represention
622      * using an ast_block will return the last generated value,
623      * so: (b, c) + a  executed both b and c, and returns c,
624      * which is then added to a.
625      */
626     *out = NULL;
627
628     /* generate locals */
629     for (i = 0; i < self->locals_count; ++i)
630     {
631         if (!ast_local_codegen(self->locals[i], func->ir_func))
632             return false;
633     }
634
635     for (i = 0; i < self->exprs_count; ++i)
636     {
637         ast_expression_codegen *gen = self->exprs[i]->expression.codegen;
638         if (!(*gen)(self->exprs[i], func, false, out))
639             return false;
640     }
641
642     return true;
643 }
644
645 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
646 {
647     ast_expression_codegen *cgen;
648     ir_value *left, *right;
649
650     cgen = self->dest->expression.codegen;
651     /* lvalue! */
652     if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
653         return false;
654
655     cgen = self->source->expression.codegen;
656     /* rvalue! */
657     if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
658         return false;
659
660     if (!ir_block_create_store_op(func->curblock, self->op, left, right))
661         return false;
662
663     /* Theoretically, an assinment returns its left side as an
664      * lvalue, if we don't need an lvalue though, we return
665      * the right side as an rvalue, otherwise we have to
666      * somehow know whether or not we need to dereference the pointer
667      * on the left side - that is: OP_LOAD if it was an address.
668      * Also: in original QC we cannot OP_LOADP *anyway*.
669      */
670     *out = (lvalue ? left : right);
671
672     return true;
673 }
674
675 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
676 {
677     ast_expression_codegen *cgen;
678     ir_value *left, *right;
679
680     /* In the context of a binary operation, we can disregard
681      * the lvalue flag.
682      */
683      (void)lvalue;
684
685     cgen = self->left->expression.codegen;
686     /* lvalue! */
687     if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
688         return false;
689
690     cgen = self->right->expression.codegen;
691     /* rvalue! */
692     if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
693         return false;
694
695     *out = ir_block_create_binop(func->curblock, ast_function_label(func, "bin"),
696                                  self->op, left, right);
697     if (!*out)
698         return false;
699
700     return true;
701 }
702
703 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
704 {
705     ast_expression_codegen *cgen;
706     ir_value *ent, *field;
707
708     /* This function needs to take the 'lvalue' flag into account!
709      * As lvalue we provide a field-pointer, as rvalue we provide the
710      * value in a temp.
711      */
712
713     cgen = self->entity->expression.codegen;
714     if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
715         return false;
716
717     cgen = self->field->expression.codegen;
718     if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
719         return false;
720
721     if (lvalue) {
722         /* address! */
723         *out = ir_block_create_fieldaddress(func->curblock, ast_function_label(func, "efa"),
724                                             ent, field);
725     } else {
726         *out = ir_block_create_load_from_ent(func->curblock, ast_function_label(func, "efv"),
727                                              ent, field, self->expression.vtype);
728     }
729     if (!*out)
730         return false;
731
732     /* Hm that should be it... */
733     return true;
734 }
735
736 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
737 {
738     ast_expression_codegen *cgen;
739
740     ir_value *condval;
741     ir_value *dummy;
742
743     ir_block *cond = func->curblock;
744     ir_block *ontrue;
745     ir_block *onfalse;
746     ir_block *merge;
747
748     /* We don't output any value, thus also don't care about r/lvalue */
749     (void)out;
750     (void)lvalue;
751
752     /* generate the condition */
753     func->curblock = cond;
754     cgen = self->cond->expression.codegen;
755     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
756         return false;
757
758     /* on-true path */
759
760     if (self->on_true) {
761         /* create on-true block */
762         ontrue = ir_function_create_block(func->ir_func, ast_function_label(func, "ontrue"));
763         if (!ontrue)
764             return false;
765
766         /* enter the block */
767         func->curblock = ontrue;
768
769         /* generate */
770         cgen = self->on_true->expression.codegen;
771         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
772             return false;
773     } else
774         ontrue = NULL;
775     
776     /* on-false path */
777     if (self->on_false) {
778         /* create on-false block */
779         onfalse = ir_function_create_block(func->ir_func, ast_function_label(func, "onfalse"));
780         if (!onfalse)
781             return false;
782
783         /* enter the block */
784         func->curblock = onfalse;
785
786         /* generate */
787         cgen = self->on_false->expression.codegen;
788         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
789             return false;
790     } else
791         onfalse = NULL;
792
793     /* Merge block were they all merge in to */
794     merge = ir_function_create_block(func->ir_func, ast_function_label(func, "endif"));
795     if (!merge)
796         return NULL;
797
798     /* add jumps ot the merge block */
799     if (ontrue && !ir_block_create_jump(ontrue, merge))
800         return false;
801     if (onfalse && !ir_block_create_jump(onfalse, merge))
802         return false;
803
804     /* we create the if here, that way all blocks are ordered :)
805      */
806     if (!ir_block_create_if(cond, condval,
807                             (ontrue  ? ontrue  : merge),
808                             (onfalse ? onfalse : merge)))
809     {
810         return false;
811     }
812
813     /* Now enter the merge block */
814     func->curblock = merge;
815
816     return true;
817 }
818
819 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
820 {
821     ast_expression_codegen *cgen;
822
823     ir_value *condval;
824     ir_value *trueval, *falseval;
825     ir_instr *phi;
826
827     ir_block *cond = func->curblock;
828     ir_block *ontrue;
829     ir_block *onfalse;
830     ir_block *merge;
831
832     /* In theory it shouldn't be possible to pass through a node twice, but
833      * in case we add any kind of optimization pass for the AST itself, it
834      * may still happen, thus we remember a created ir_value and simply return one
835      * if it already exists.
836      */
837     if (self->phi_out) {
838         *out = self->phi_out;
839         return true;
840     }
841
842     /* Ternary can never create an lvalue... */
843     if (lvalue)
844         return false;
845
846     /* In the following, contraty to ast_ifthen, we assume both paths exist. */
847     
848     /* generate the condition */
849     func->curblock = cond;
850     cgen = self->cond->expression.codegen;
851     if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
852         return false;
853
854     /* create on-true block */
855     ontrue = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_T"));
856     if (!ontrue)
857         return false;
858     else
859     {
860         /* enter the block */
861         func->curblock = ontrue;
862
863         /* generate */
864         cgen = self->on_true->expression.codegen;
865         if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
866             return false;
867     }
868     
869     /* create on-false block */
870     onfalse = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_F"));
871     if (!onfalse)
872         return false;
873     else
874     {
875         /* enter the block */
876         func->curblock = onfalse;
877
878         /* generate */
879         cgen = self->on_false->expression.codegen;
880         if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
881             return false;
882     }
883
884     /* create merge block */
885     merge = ir_function_create_block(func->ir_func, ast_function_label(func, "tern_out"));
886     if (!merge)
887         return NULL;
888     /* jump to merge block */
889     if (!ir_block_create_jump(ontrue, merge))
890         return false;
891     if (!ir_block_create_jump(onfalse, merge))
892         return false;
893
894     /* create if instruction */
895     if (!ir_block_create_if(cond, condval, ontrue, onfalse))
896         return false;
897
898     /* Now enter the merge block */
899     func->curblock = merge;
900
901     /* Here, now, we need a PHI node
902      * but first some sanity checking...
903      */
904     if (trueval->vtype != falseval->vtype) {
905         /* error("ternary with different types on the two sides"); */
906         return false;
907     }
908
909     /* create PHI */
910     phi = ir_block_create_phi(merge, ast_function_label(func, "phi"), trueval->vtype);
911     if (!phi ||
912         !ir_phi_add(phi, ontrue,  trueval) ||
913         !ir_phi_add(phi, onfalse, falseval))
914     {
915         return false;
916     }
917
918     self->phi_out = ir_phi_value(phi);
919     *out = self->phi_out;
920
921     return true;
922 }
923
924 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
925 {
926     ast_expression_codegen *cgen;
927
928     ir_value *dummy;
929     ir_value *precond;
930     ir_value *postcond;
931
932     /* Since we insert some jumps "late" so we have blocks
933      * ordered "nicely", we need to keep track of the actual end-blocks
934      * of expressions to add the jumps to.
935      */
936     ir_block *bbody,      *end_bbody;
937     ir_block *bprecond,   *end_bprecond;
938     ir_block *bpostcond,  *end_bpostcond;
939     ir_block *bincrement, *end_bincrement;
940     ir_block *bout, *bin;
941
942     /* let's at least move the outgoing block to the end */
943     size_t    bout_id;
944
945     /* 'break' and 'continue' need to be able to find the right blocks */
946     ir_block *bcontinue = NULL;
947     ir_block *bbreak    = NULL;
948
949     ir_block *old_bcontinue;
950     ir_block *old_bbreak;
951
952     ir_block *tmpblock;
953
954     (void)lvalue;
955     (void)out;
956
957     /* NOTE:
958      * Should we ever need some kind of block ordering, better make this function
959      * move blocks around than write a block ordering algorithm later... after all
960      * the ast and ir should work together, not against each other.
961      */
962
963     /* initexpr doesn't get its own block, it's pointless, it could create more blocks
964      * anyway if for example it contains a ternary.
965      */
966     if (self->initexpr)
967     {
968         cgen = self->initexpr->expression.codegen;
969         if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
970             return false;
971     }
972
973     /* Store the block from which we enter this chaos */
974     bin = func->curblock;
975
976     /* The pre-loop condition needs its own block since we
977      * need to be able to jump to the start of that expression.
978      */
979     if (self->precond)
980     {
981         bprecond = ir_function_create_block(func->ir_func, ast_function_label(func, "pre_loop_cond"));
982         if (!bprecond)
983             return false;
984
985         /* the pre-loop-condition the least important place to 'continue' at */
986         bcontinue = bprecond;
987
988         /* enter */
989         func->curblock = bprecond;
990
991         /* generate */
992         cgen = self->precond->expression.codegen;
993         if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
994             return false;
995
996         end_bprecond = func->curblock;
997     } else {
998         bprecond = end_bprecond = NULL;
999     }
1000
1001     /* Now the next blocks won't be ordered nicely, but we need to
1002      * generate them this early for 'break' and 'continue'.
1003      */
1004     if (self->increment) {
1005         bincrement = ir_function_create_block(func->ir_func, ast_function_label(func, "loop_increment"));
1006         if (!bincrement)
1007             return false;
1008         bcontinue = bincrement; /* increment comes before the pre-loop-condition */
1009     } else {
1010         bincrement = end_bincrement = NULL;
1011     }
1012
1013     if (self->postcond) {
1014         bpostcond = ir_function_create_block(func->ir_func, ast_function_label(func, "post_loop_cond"));
1015         if (!bpostcond)
1016             return false;
1017         bcontinue = bpostcond; /* postcond comes before the increment */
1018     } else {
1019         bpostcond = end_bpostcond = NULL;
1020     }
1021
1022     bout_id = func->ir_func->blocks_count;
1023     bout = ir_function_create_block(func->ir_func, ast_function_label(func, "after_loop"));
1024     if (!bout)
1025         return false;
1026     bbreak = bout;
1027
1028     /* The loop body... */
1029     if (self->body)
1030     {
1031         bbody = ir_function_create_block(func->ir_func, ast_function_label(func, "loop_body"));
1032         if (!bbody)
1033             return false;
1034
1035         /* enter */
1036         func->curblock = bbody;
1037
1038         old_bbreak          = func->breakblock;
1039         old_bcontinue       = func->continueblock;
1040         func->breakblock    = bbreak;
1041         func->continueblock = bcontinue;
1042
1043         /* generate */
1044         cgen = self->body->expression.codegen;
1045         if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
1046             return false;
1047
1048         end_bbody = func->curblock;
1049         func->breakblock    = old_bbreak;
1050         func->continueblock = old_bcontinue;
1051     }
1052
1053     /* post-loop-condition */
1054     if (self->postcond)
1055     {
1056         /* enter */
1057         func->curblock = bpostcond;
1058
1059         /* generate */
1060         cgen = self->postcond->expression.codegen;
1061         if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
1062             return false;
1063
1064         end_bpostcond = func->curblock;
1065     }
1066
1067     /* The incrementor */
1068     if (self->increment)
1069     {
1070         /* enter */
1071         func->curblock = bincrement;
1072
1073         /* generate */
1074         cgen = self->increment->expression.codegen;
1075         if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
1076             return false;
1077
1078         end_bincrement = func->curblock;
1079     }
1080
1081     /* In any case now, we continue from the outgoing block */
1082     func->curblock = bout;
1083
1084     /* Now all blocks are in place */
1085     /* From 'bin' we jump to whatever comes first */
1086     if      (bprecond)   tmpblock = bprecond;
1087     else if (bbody)      tmpblock = bbody;
1088     else if (bpostcond)  tmpblock = bpostcond;
1089     else                 tmpblock = bout;
1090     if (!ir_block_create_jump(bin, tmpblock))
1091         return false;
1092
1093     /* From precond */
1094     if (bprecond)
1095     {
1096         ir_block *ontrue, *onfalse;
1097         if      (bbody)      ontrue = bbody;
1098         else if (bincrement) ontrue = bincrement;
1099         else if (bpostcond)  ontrue = bpostcond;
1100         else                 ontrue = bprecond;
1101         onfalse = bout;
1102         if (!ir_block_create_if(end_bprecond, precond, ontrue, onfalse))
1103             return false;
1104     }
1105
1106     /* from body */
1107     if (bbody)
1108     {
1109         if      (bincrement) tmpblock = bincrement;
1110         else if (bpostcond)  tmpblock = bpostcond;
1111         else if (bprecond)   tmpblock = bprecond;
1112         else                 tmpblock = bout;
1113         if (!ir_block_create_jump(end_bbody, tmpblock))
1114             return false;
1115     }
1116
1117     /* from increment */
1118     if (bincrement)
1119     {
1120         if      (bpostcond)  tmpblock = bpostcond;
1121         else if (bprecond)   tmpblock = bprecond;
1122         else if (bbody)      tmpblock = bbody;
1123         else                 tmpblock = bout;
1124         if (!ir_block_create_jump(end_bincrement, tmpblock))
1125             return false;
1126     }
1127
1128     /* from postcond */
1129     if (bpostcond)
1130     {
1131         ir_block *ontrue, *onfalse;
1132         if      (bprecond)   ontrue = bprecond;
1133         else if (bbody)      ontrue = bbody;
1134         else if (bincrement) ontrue = bincrement;
1135         else                 ontrue = bpostcond;
1136         onfalse = bout;
1137         if (!ir_block_create_if(end_bpostcond, postcond, ontrue, onfalse))
1138             return false;
1139     }
1140
1141     /* Move 'bout' to the end */
1142     if (!ir_function_blocks_remove(func->ir_func, bout_id) ||
1143         !ir_function_blocks_add(func->ir_func, bout))
1144     {
1145         ir_block_delete(bout);
1146         return false;
1147     }
1148
1149     return true;
1150 }