2 * Copyright (C) 2012, 2013
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:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
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
31 #define ast_instantiate(T, ctx, destroyfn) \
32 T* self = (T*)mem_a(sizeof(T)); \
36 ast_node_init((ast_node*)self, ctx, TYPE_##T); \
37 ( (ast_node*)self )->destroy = (ast_node_delete*)destroyfn
40 * forward declarations, these need not be in ast.h for obvious
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**);
79 /* It must not be possible to get here. */
80 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
83 con_err("ast node missing destroy()\n");
87 /* Initialize main ast node aprts */
88 static void ast_node_init(ast_node *self, lex_ctx_t ctx, int nodetype)
91 self->destroy = &_ast_node_destroy;
93 self->nodetype = nodetype;
94 self->side_effects = false;
97 /* weight and side effects */
98 static void _ast_propagate_effects(ast_node *self, ast_node *other)
100 if (ast_side_effects(other))
101 ast_side_effects(self) = true;
103 #define ast_propagate_effects(s,o) _ast_propagate_effects(((ast_node*)(s)), ((ast_node*)(o)))
105 /* General expression initialization */
106 static void ast_expression_init(ast_expression *self,
107 ast_expression_codegen *codegen)
109 self->codegen = codegen;
110 self->vtype = TYPE_VOID;
117 self->varparam = NULL;
120 static void ast_expression_delete(ast_expression *self)
124 ast_delete(self->next);
125 for (i = 0; i < vec_size(self->params); ++i) {
126 ast_delete(self->params[i]);
128 vec_free(self->params);
130 ast_delete(self->varparam);
133 static void ast_expression_delete_full(ast_expression *self)
135 ast_expression_delete(self);
139 ast_value* ast_value_copy(const ast_value *self)
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);
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);
159 void ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
162 const ast_expression *fromex;
163 ast_expression *selfex;
164 self->vtype = other->vtype;
166 self->next = (ast_expression*)ast_type_copy(ast_ctx(self), other->next);
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);
178 static ast_expression* ast_shallow_type(lex_ctx_t ctx, int vtype)
180 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
181 ast_expression_init(self, NULL);
182 self->codegen = NULL;
188 ast_expression* ast_type_copy(lex_ctx_t ctx, const ast_expression *ex)
191 const ast_expression *fromex;
192 ast_expression *selfex;
198 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
199 ast_expression_init(self, NULL);
204 /* This may never be codegen()d */
205 selfex->codegen = NULL;
207 selfex->vtype = fromex->vtype;
209 selfex->next = ast_type_copy(ctx, fromex->next);
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);
224 bool ast_compare_type(ast_expression *a, ast_expression *b)
226 if (a->vtype == TYPE_NIL ||
227 b->vtype == TYPE_NIL)
229 if (a->vtype != b->vtype)
231 if (!a->next != !b->next)
233 if (vec_size(a->params) != vec_size(b->params))
235 if ((a->flags & AST_FLAG_TYPE_MASK) !=
236 (b->flags & AST_FLAG_TYPE_MASK) )
240 if (vec_size(a->params)) {
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]))
249 return ast_compare_type(a->next, b->next);
253 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
260 if (pos + 6 >= bufsize)
262 util_strncpy(buf + pos, "(null)", 6);
266 if (pos + 1 >= bufsize)
271 util_strncpy(buf + pos, "(variant)", 9);
276 return ast_type_to_string_impl(e->next, buf, bufsize, pos);
279 if (pos + 3 >= bufsize)
283 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
284 if (pos + 1 >= bufsize)
290 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
291 if (pos + 2 >= bufsize)
293 if (!vec_size(e->params)) {
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)
305 pos = ast_type_to_string_impl((ast_expression*)(e->params[i]), buf, bufsize, pos);
307 if (pos + 1 >= bufsize)
313 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
314 if (pos + 1 >= bufsize)
317 pos += util_snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->count);
318 if (pos + 1 >= bufsize)
324 typestr = type_name[e->vtype];
325 typelen = strlen(typestr);
326 if (pos + typelen >= bufsize)
328 util_strncpy(buf + pos, typestr, typelen);
329 return pos + typelen;
333 buf[bufsize-3] = '.';
334 buf[bufsize-2] = '.';
335 buf[bufsize-1] = '.';
339 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
341 size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
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)
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 */
353 self->name = name ? util_strdup(name) : NULL;
354 self->expression.vtype = t;
355 self->expression.next = NULL;
356 self->isfield = false;
358 self->hasvalue = false;
361 memset(&self->constval, 0, sizeof(self->constval));
362 self->initlist = NULL;
365 self->ir_values = NULL;
366 self->ir_value_count = 0;
372 self->argcounter = NULL;
373 self->intrinsic = false;
378 void ast_value_delete(ast_value* self)
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)
388 mem_d((void*)self->constval.vstring);
391 /* unlink us from the function node */
392 self->constval.vfunc->vtype = NULL;
394 /* NOTE: delete function? currently collected in
395 * the parser structure
402 mem_d(self->ir_values);
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);
418 vec_free(self->initlist);
421 ast_expression_delete((ast_expression*)self);
425 void ast_value_params_add(ast_value *self, ast_value *p)
427 vec_push(self->expression.params, p);
430 bool ast_value_set_name(ast_value *self, const char *name)
433 mem_d((void*)self->name);
434 self->name = util_strdup(name);
438 ast_binary* ast_binary_new(lex_ctx_t ctx, int op,
439 ast_expression* left, ast_expression* right)
441 ast_instantiate(ast_binary, ctx, ast_binary_delete);
442 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
447 self->right_first = false;
449 ast_propagate_effects(self, left);
450 ast_propagate_effects(self, right);
452 if (op >= INSTR_EQ_F && op <= INSTR_GT)
453 self->expression.vtype = TYPE_FLOAT;
454 else if (op == INSTR_AND || op == INSTR_OR) {
455 if (OPTS_FLAG(PERL_LOGIC))
456 ast_type_adopt(self, right);
458 self->expression.vtype = TYPE_FLOAT;
460 else if (op == INSTR_BITAND || op == INSTR_BITOR)
461 self->expression.vtype = TYPE_FLOAT;
462 else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
463 self->expression.vtype = TYPE_VECTOR;
464 else if (op == INSTR_MUL_V)
465 self->expression.vtype = TYPE_FLOAT;
467 self->expression.vtype = left->vtype;
470 self->refs = AST_REF_ALL;
475 void ast_binary_delete(ast_binary *self)
477 if (self->refs & AST_REF_LEFT) ast_unref(self->left);
478 if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
480 ast_expression_delete((ast_expression*)self);
484 ast_binstore* ast_binstore_new(lex_ctx_t ctx, int storop, int op,
485 ast_expression* left, ast_expression* right)
487 ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
488 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
490 ast_side_effects(self) = true;
492 self->opstore = storop;
495 self->source = right;
497 self->keep_dest = false;
499 ast_type_adopt(self, left);
503 void ast_binstore_delete(ast_binstore *self)
505 if (!self->keep_dest)
506 ast_unref(self->dest);
507 ast_unref(self->source);
508 ast_expression_delete((ast_expression*)self);
512 ast_unary* ast_unary_new(lex_ctx_t ctx, int op,
513 ast_expression *expr)
515 ast_instantiate(ast_unary, ctx, ast_unary_delete);
516 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
519 self->operand = expr;
522 if (ast_istype(expr, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
523 ast_unary *prev = (ast_unary*)((ast_unary*)expr)->operand;
524 ast_unary *cur = (ast_unary*)expr;
526 /* Handle for double negation */
527 if (cur->op == op && (op >= VINSTR_NEG_F && op <= VINSTR_NEG_V))
530 if (ast_istype(prev, ast_unary)) {
531 ast_expression_delete((ast_expression*)self);
533 ++opts_optimizationcount[OPTIM_PEEPHOLE];
538 ast_propagate_effects(self, expr);
540 if (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) {
541 self->expression.vtype = TYPE_FLOAT;
542 } else if (op >= VINSTR_NEG_F && op <= VINSTR_NEG_V) {
543 self->expression.vtype = TYPE_FLOAT;
545 compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
551 void ast_unary_delete(ast_unary *self)
553 if (self->operand) ast_unref(self->operand);
554 ast_expression_delete((ast_expression*)self);
558 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
560 ast_instantiate(ast_return, ctx, ast_return_delete);
561 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
563 self->operand = expr;
566 ast_propagate_effects(self, expr);
571 void ast_return_delete(ast_return *self)
574 ast_unref(self->operand);
575 ast_expression_delete((ast_expression*)self);
579 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
581 if (field->vtype != TYPE_FIELD) {
582 compile_error(ctx, "ast_entfield_new with expression not of type field");
585 return ast_entfield_new_force(ctx, entity, field, field->next);
588 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
590 ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
594 /* Error: field has no type... */
598 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
600 self->entity = entity;
602 ast_propagate_effects(self, entity);
603 ast_propagate_effects(self, field);
605 ast_type_adopt(self, outtype);
609 void ast_entfield_delete(ast_entfield *self)
611 ast_unref(self->entity);
612 ast_unref(self->field);
613 ast_expression_delete((ast_expression*)self);
617 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
619 ast_instantiate(ast_member, ctx, ast_member_delete);
625 if (owner->vtype != TYPE_VECTOR &&
626 owner->vtype != TYPE_FIELD) {
627 compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
632 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
633 self->expression.node.keep = true; /* keep */
635 if (owner->vtype == TYPE_VECTOR) {
636 self->expression.vtype = TYPE_FLOAT;
637 self->expression.next = NULL;
639 self->expression.vtype = TYPE_FIELD;
640 self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
643 self->rvalue = false;
645 ast_propagate_effects(self, owner);
649 self->name = util_strdup(name);
656 void ast_member_delete(ast_member *self)
658 /* The owner is always an ast_value, which has .keep=true,
659 * also: ast_members are usually deleted after the owner, thus
660 * this will cause invalid access
661 ast_unref(self->owner);
662 * once we allow (expression).x to access a vector-member, we need
663 * to change this: preferably by creating an alternate ast node for this
664 * purpose that is not garbage-collected.
666 ast_expression_delete((ast_expression*)self);
671 bool ast_member_set_name(ast_member *self, const char *name)
674 mem_d((void*)self->name);
675 self->name = util_strdup(name);
679 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
681 ast_expression *outtype;
682 ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
684 outtype = array->next;
687 /* Error: field has no type... */
691 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
695 ast_propagate_effects(self, array);
696 ast_propagate_effects(self, index);
698 ast_type_adopt(self, outtype);
699 if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
700 if (self->expression.vtype != TYPE_ARRAY) {
701 compile_error(ast_ctx(self), "array_index node on type");
702 ast_array_index_delete(self);
705 self->array = outtype;
706 self->expression.vtype = TYPE_FIELD;
712 void ast_array_index_delete(ast_array_index *self)
715 ast_unref(self->array);
717 ast_unref(self->index);
718 ast_expression_delete((ast_expression*)self);
722 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
724 ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete);
725 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
727 self->expression.vtype = TYPE_NOEXPR;
731 void ast_argpipe_delete(ast_argpipe *self)
734 ast_unref(self->index);
735 ast_expression_delete((ast_expression*)self);
739 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
741 ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
742 if (!ontrue && !onfalse) {
743 /* because it is invalid */
747 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
750 self->on_true = ontrue;
751 self->on_false = onfalse;
752 ast_propagate_effects(self, cond);
754 ast_propagate_effects(self, ontrue);
756 ast_propagate_effects(self, onfalse);
761 void ast_ifthen_delete(ast_ifthen *self)
763 ast_unref(self->cond);
765 ast_unref(self->on_true);
767 ast_unref(self->on_false);
768 ast_expression_delete((ast_expression*)self);
772 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
774 ast_expression *exprtype = ontrue;
775 ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
776 /* This time NEITHER must be NULL */
777 if (!ontrue || !onfalse) {
781 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
784 self->on_true = ontrue;
785 self->on_false = onfalse;
786 ast_propagate_effects(self, cond);
787 ast_propagate_effects(self, ontrue);
788 ast_propagate_effects(self, onfalse);
790 if (ontrue->vtype == TYPE_NIL)
792 ast_type_adopt(self, exprtype);
797 void ast_ternary_delete(ast_ternary *self)
799 /* the if()s are only there because computed-gotos can set them
802 if (self->cond) ast_unref(self->cond);
803 if (self->on_true) ast_unref(self->on_true);
804 if (self->on_false) ast_unref(self->on_false);
805 ast_expression_delete((ast_expression*)self);
809 ast_loop* ast_loop_new(lex_ctx_t ctx,
810 ast_expression *initexpr,
811 ast_expression *precond, bool pre_not,
812 ast_expression *postcond, bool post_not,
813 ast_expression *increment,
814 ast_expression *body)
816 ast_instantiate(ast_loop, ctx, ast_loop_delete);
817 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
819 self->initexpr = initexpr;
820 self->precond = precond;
821 self->postcond = postcond;
822 self->increment = increment;
825 self->pre_not = pre_not;
826 self->post_not = post_not;
829 ast_propagate_effects(self, initexpr);
831 ast_propagate_effects(self, precond);
833 ast_propagate_effects(self, postcond);
835 ast_propagate_effects(self, increment);
837 ast_propagate_effects(self, body);
842 void ast_loop_delete(ast_loop *self)
845 ast_unref(self->initexpr);
847 ast_unref(self->precond);
849 ast_unref(self->postcond);
851 ast_unref(self->increment);
853 ast_unref(self->body);
854 ast_expression_delete((ast_expression*)self);
858 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
860 ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
861 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
863 self->is_continue = iscont;
864 self->levels = levels;
869 void ast_breakcont_delete(ast_breakcont *self)
871 ast_expression_delete((ast_expression*)self);
875 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
877 ast_instantiate(ast_switch, ctx, ast_switch_delete);
878 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
883 ast_propagate_effects(self, op);
888 void ast_switch_delete(ast_switch *self)
891 ast_unref(self->operand);
893 for (i = 0; i < vec_size(self->cases); ++i) {
894 if (self->cases[i].value)
895 ast_unref(self->cases[i].value);
896 ast_unref(self->cases[i].code);
898 vec_free(self->cases);
900 ast_expression_delete((ast_expression*)self);
904 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
906 ast_instantiate(ast_label, ctx, ast_label_delete);
907 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
909 self->expression.vtype = TYPE_NOEXPR;
911 self->name = util_strdup(name);
912 self->irblock = NULL;
914 self->undefined = undefined;
919 void ast_label_delete(ast_label *self)
921 mem_d((void*)self->name);
922 vec_free(self->gotos);
923 ast_expression_delete((ast_expression*)self);
927 static void ast_label_register_goto(ast_label *self, ast_goto *g)
929 vec_push(self->gotos, g);
932 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
934 ast_instantiate(ast_goto, ctx, ast_goto_delete);
935 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
937 self->name = util_strdup(name);
939 self->irblock_from = NULL;
944 void ast_goto_delete(ast_goto *self)
946 mem_d((void*)self->name);
947 ast_expression_delete((ast_expression*)self);
951 void ast_goto_set_label(ast_goto *self, ast_label *label)
953 self->target = label;
956 ast_call* ast_call_new(lex_ctx_t ctx,
957 ast_expression *funcexpr)
959 ast_instantiate(ast_call, ctx, ast_call_delete);
960 if (!funcexpr->next) {
961 compile_error(ctx, "not a function");
965 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
967 ast_side_effects(self) = true;
970 self->func = funcexpr;
971 self->va_count = NULL;
973 ast_type_adopt(self, funcexpr->next);
978 void ast_call_delete(ast_call *self)
981 for (i = 0; i < vec_size(self->params); ++i)
982 ast_unref(self->params[i]);
983 vec_free(self->params);
986 ast_unref(self->func);
989 ast_unref(self->va_count);
991 ast_expression_delete((ast_expression*)self);
995 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
1001 if (!va_type || !ast_compare_type(va_type, exp_type))
1003 if (va_type && exp_type)
1005 ast_type_to_string(va_type, tgot, sizeof(tgot));
1006 ast_type_to_string(exp_type, texp, sizeof(texp));
1007 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1008 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1009 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1013 compile_error(ast_ctx(self),
1014 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1021 ast_type_to_string(exp_type, texp, sizeof(texp));
1022 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1023 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1024 "piped variadic argument may differ in type: expected type %s",
1028 compile_error(ast_ctx(self),
1029 "piped variadic argument may differ in type: expected type %s",
1038 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1044 const ast_expression *func = self->func;
1045 size_t count = vec_size(self->params);
1046 if (count > vec_size(func->params))
1047 count = vec_size(func->params);
1049 for (i = 0; i < count; ++i) {
1050 if (ast_istype(self->params[i], ast_argpipe)) {
1051 /* warn about type safety instead */
1053 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1056 if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->params[i]))
1059 else if (!ast_compare_type(self->params[i], (ast_expression*)(func->params[i])))
1061 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1062 ast_type_to_string((ast_expression*)func->params[i], texp, sizeof(texp));
1063 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1064 (unsigned int)(i+1), texp, tgot);
1065 /* we don't immediately return */
1069 count = vec_size(self->params);
1070 if (count > vec_size(func->params) && func->varparam) {
1071 for (; i < count; ++i) {
1072 if (ast_istype(self->params[i], ast_argpipe)) {
1073 /* warn about type safety instead */
1075 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1078 if (!ast_call_check_vararg(self, va_type, func->varparam))
1081 else if (!ast_compare_type(self->params[i], func->varparam))
1083 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1084 ast_type_to_string(func->varparam, texp, sizeof(texp));
1085 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1086 (unsigned int)(i+1), texp, tgot);
1087 /* we don't immediately return */
1095 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1096 ast_expression *dest, ast_expression *source)
1098 ast_instantiate(ast_store, ctx, ast_store_delete);
1099 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1101 ast_side_effects(self) = true;
1105 self->source = source;
1107 ast_type_adopt(self, dest);
1112 void ast_store_delete(ast_store *self)
1114 ast_unref(self->dest);
1115 ast_unref(self->source);
1116 ast_expression_delete((ast_expression*)self);
1120 ast_block* ast_block_new(lex_ctx_t ctx)
1122 ast_instantiate(ast_block, ctx, ast_block_delete);
1123 ast_expression_init((ast_expression*)self,
1124 (ast_expression_codegen*)&ast_block_codegen);
1126 self->locals = NULL;
1128 self->collect = NULL;
1133 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1135 ast_propagate_effects(self, e);
1136 vec_push(self->exprs, e);
1137 if (self->expression.next) {
1138 ast_delete(self->expression.next);
1139 self->expression.next = NULL;
1141 ast_type_adopt(self, e);
1145 void ast_block_collect(ast_block *self, ast_expression *expr)
1147 vec_push(self->collect, expr);
1148 expr->node.keep = true;
1151 void ast_block_delete(ast_block *self)
1154 for (i = 0; i < vec_size(self->exprs); ++i)
1155 ast_unref(self->exprs[i]);
1156 vec_free(self->exprs);
1157 for (i = 0; i < vec_size(self->locals); ++i)
1158 ast_delete(self->locals[i]);
1159 vec_free(self->locals);
1160 for (i = 0; i < vec_size(self->collect); ++i)
1161 ast_delete(self->collect[i]);
1162 vec_free(self->collect);
1163 ast_expression_delete((ast_expression*)self);
1167 void ast_block_set_type(ast_block *self, ast_expression *from)
1169 if (self->expression.next)
1170 ast_delete(self->expression.next);
1171 ast_type_adopt(self, from);
1174 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1176 ast_instantiate(ast_function, ctx, ast_function_delete);
1179 compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1181 } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1182 compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1184 (int)vtype->hasvalue,
1185 vtype->expression.vtype);
1189 self->vtype = vtype;
1190 self->name = name ? util_strdup(name) : NULL;
1191 self->blocks = NULL;
1193 self->labelcount = 0;
1196 self->ir_func = NULL;
1197 self->curblock = NULL;
1199 self->breakblocks = NULL;
1200 self->continueblocks = NULL;
1202 vtype->hasvalue = true;
1203 vtype->constval.vfunc = self;
1205 self->varargs = NULL;
1207 self->fixedparams = NULL;
1208 self->return_value = NULL;
1217 void ast_function_delete(ast_function *self)
1221 mem_d((void*)self->name);
1223 /* ast_value_delete(self->vtype); */
1224 self->vtype->hasvalue = false;
1225 self->vtype->constval.vfunc = NULL;
1226 /* We use unref - if it was stored in a global table it is supposed
1227 * to be deleted from *there*
1229 ast_unref(self->vtype);
1231 for (i = 0; i < vec_size(self->blocks); ++i)
1232 ast_delete(self->blocks[i]);
1233 vec_free(self->blocks);
1234 vec_free(self->breakblocks);
1235 vec_free(self->continueblocks);
1237 ast_delete(self->varargs);
1239 ast_delete(self->argc);
1240 if (self->fixedparams)
1241 ast_unref(self->fixedparams);
1242 if (self->return_value)
1243 ast_unref(self->return_value);
1247 const char* ast_function_label(ast_function *self, const char *prefix)
1253 if (!OPTS_OPTION_BOOL(OPTION_DUMP) &&
1254 !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1255 !OPTS_OPTION_BOOL(OPTION_DEBUG))
1260 id = (self->labelcount++);
1261 len = strlen(prefix);
1263 from = self->labelbuf + sizeof(self->labelbuf)-1;
1266 *from-- = (id%10) + '0';
1270 memcpy(from - len, prefix, len);
1274 /*********************************************************************/
1276 * by convention you must never pass NULL to the 'ir_value **out'
1277 * parameter. If you really don't care about the output, pass a dummy.
1278 * But I can't imagine a pituation where the output is truly unnecessary.
1281 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1283 if (out->vtype == TYPE_FIELD)
1284 out->fieldtype = self->next->vtype;
1285 if (out->vtype == TYPE_FUNCTION)
1286 out->outtype = self->next->vtype;
1289 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1291 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1295 if (self->expression.vtype == TYPE_NIL) {
1296 *out = func->ir_func->owner->nil;
1299 /* NOTE: This is the codegen for a variable used in an expression.
1300 * It is not the codegen to generate the value. For this purpose,
1301 * ast_local_codegen and ast_global_codegen are to be used before this
1302 * is executed. ast_function_codegen should take care of its locals,
1303 * and the ast-user should take care of ast_global_codegen to be used
1304 * on all the globals.
1307 char tname[1024]; /* typename is reserved in C++ */
1308 ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1309 compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1316 static bool ast_global_array_set(ast_value *self)
1318 size_t count = vec_size(self->initlist);
1321 if (count > self->expression.count) {
1322 compile_error(ast_ctx(self), "too many elements in initializer");
1323 count = self->expression.count;
1325 else if (count < self->expression.count) {
1327 compile_warning(ast_ctx(self), "not all elements are initialized");
1331 for (i = 0; i != count; ++i) {
1332 switch (self->expression.next->vtype) {
1334 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1338 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1342 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1346 /* we don't support them in any other place yet either */
1347 compile_error(ast_ctx(self), "TODO: nested arrays");
1350 /* this requiers a bit more work - similar to the fields I suppose */
1351 compile_error(ast_ctx(self), "global of type function not properly generated");
1354 if (!self->initlist[i].vfield) {
1355 compile_error(ast_ctx(self), "field constant without vfield set");
1358 if (!self->initlist[i].vfield->ir_v) {
1359 compile_error(ast_ctx(self), "field constant generated before its field");
1362 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1366 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1373 static bool check_array(ast_value *self, ast_value *array)
1375 if (array->expression.flags & AST_FLAG_ARRAY_INIT && !array->initlist) {
1376 compile_error(ast_ctx(self), "array without size: %s", self->name);
1379 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1380 if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1381 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1387 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1391 if (self->expression.vtype == TYPE_NIL) {
1392 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1396 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1398 ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1401 func->context = ast_ctx(self);
1402 func->value->context = ast_ctx(self);
1404 self->constval.vfunc->ir_func = func;
1405 self->ir_v = func->value;
1406 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1407 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1408 if (self->expression.flags & AST_FLAG_ERASEABLE)
1409 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1410 /* The function is filled later on ast_function_codegen... */
1414 if (isfield && self->expression.vtype == TYPE_FIELD) {
1415 ast_expression *fieldtype = self->expression.next;
1417 if (self->hasvalue) {
1418 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1422 if (fieldtype->vtype == TYPE_ARRAY) {
1427 ast_expression *elemtype;
1429 ast_value *array = (ast_value*)fieldtype;
1431 if (!ast_istype(fieldtype, ast_value)) {
1432 compile_error(ast_ctx(self), "internal error: ast_value required");
1436 if (!check_array(self, array))
1439 elemtype = array->expression.next;
1440 vtype = elemtype->vtype;
1442 v = ir_builder_create_field(ir, self->name, vtype);
1444 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1447 v->context = ast_ctx(self);
1448 v->unique_life = true;
1450 array->ir_v = self->ir_v = v;
1452 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1453 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1454 if (self->expression.flags & AST_FLAG_ERASEABLE)
1455 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1457 namelen = strlen(self->name);
1458 name = (char*)mem_a(namelen + 16);
1459 util_strncpy(name, self->name, namelen);
1461 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1462 array->ir_values[0] = v;
1463 for (ai = 1; ai < array->expression.count; ++ai) {
1464 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1465 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1466 if (!array->ir_values[ai]) {
1468 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1471 array->ir_values[ai]->context = ast_ctx(self);
1472 array->ir_values[ai]->unique_life = true;
1473 array->ir_values[ai]->locked = true;
1474 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1475 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1481 v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1484 v->context = ast_ctx(self);
1486 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1487 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1489 if (self->expression.flags & AST_FLAG_ERASEABLE)
1490 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1495 if (self->expression.vtype == TYPE_ARRAY) {
1500 ast_expression *elemtype = self->expression.next;
1501 int vtype = elemtype->vtype;
1503 if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1504 compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1508 /* same as with field arrays */
1509 if (!check_array(self, self))
1512 v = ir_builder_create_global(ir, self->name, vtype);
1514 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1517 v->context = ast_ctx(self);
1518 v->unique_life = true;
1521 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1522 v->flags |= IR_FLAG_INCLUDE_DEF;
1523 if (self->expression.flags & AST_FLAG_ERASEABLE)
1524 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1526 namelen = strlen(self->name);
1527 name = (char*)mem_a(namelen + 16);
1528 util_strncpy(name, self->name, namelen);
1530 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1531 self->ir_values[0] = v;
1532 for (ai = 1; ai < self->expression.count; ++ai) {
1533 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1534 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1535 if (!self->ir_values[ai]) {
1537 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1540 self->ir_values[ai]->context = ast_ctx(self);
1541 self->ir_values[ai]->unique_life = true;
1542 self->ir_values[ai]->locked = true;
1543 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1544 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1550 /* Arrays don't do this since there's no "array" value which spans across the
1553 v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1555 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1558 codegen_output_type(self, v);
1559 v->context = ast_ctx(self);
1562 /* link us to the ir_value */
1566 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1567 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1568 if (self->expression.flags & AST_FLAG_ERASEABLE)
1569 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1572 if (self->hasvalue) {
1573 switch (self->expression.vtype)
1576 if (!ir_value_set_float(v, self->constval.vfloat))
1580 if (!ir_value_set_vector(v, self->constval.vvec))
1584 if (!ir_value_set_string(v, self->constval.vstring))
1588 ast_global_array_set(self);
1591 compile_error(ast_ctx(self), "global of type function not properly generated");
1593 /* Cannot generate an IR value for a function,
1594 * need a pointer pointing to a function rather.
1597 if (!self->constval.vfield) {
1598 compile_error(ast_ctx(self), "field constant without vfield set");
1601 if (!self->constval.vfield->ir_v) {
1602 compile_error(ast_ctx(self), "field constant generated before its field");
1605 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1609 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1615 error: /* clean up */
1616 if(v) ir_value_delete(v);
1620 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1624 if (self->expression.vtype == TYPE_NIL) {
1625 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1629 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1631 /* Do we allow local functions? I think not...
1632 * this is NOT a function pointer atm.
1637 if (self->expression.vtype == TYPE_ARRAY) {
1642 ast_expression *elemtype = self->expression.next;
1643 int vtype = elemtype->vtype;
1645 func->flags |= IR_FLAG_HAS_ARRAYS;
1647 if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1648 compile_error(ast_ctx(self), "array-parameters are not supported");
1652 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1653 if (!check_array(self, self))
1656 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1657 if (!self->ir_values) {
1658 compile_error(ast_ctx(self), "failed to allocate array values");
1662 v = ir_function_create_local(func, self->name, vtype, param);
1664 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1667 v->context = ast_ctx(self);
1668 v->unique_life = true;
1671 namelen = strlen(self->name);
1672 name = (char*)mem_a(namelen + 16);
1673 util_strncpy(name, self->name, namelen);
1675 self->ir_values[0] = v;
1676 for (ai = 1; ai < self->expression.count; ++ai) {
1677 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1678 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1679 if (!self->ir_values[ai]) {
1680 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1683 self->ir_values[ai]->context = ast_ctx(self);
1684 self->ir_values[ai]->unique_life = true;
1685 self->ir_values[ai]->locked = true;
1691 v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1694 codegen_output_type(self, v);
1695 v->context = ast_ctx(self);
1698 /* A constant local... hmmm...
1699 * I suppose the IR will have to deal with this
1701 if (self->hasvalue) {
1702 switch (self->expression.vtype)
1705 if (!ir_value_set_float(v, self->constval.vfloat))
1709 if (!ir_value_set_vector(v, self->constval.vvec))
1713 if (!ir_value_set_string(v, self->constval.vstring))
1717 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1722 /* link us to the ir_value */
1726 if (!ast_generate_accessors(self, func->owner))
1730 error: /* clean up */
1735 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1738 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1739 if (!self->setter || !self->getter)
1741 for (i = 0; i < self->expression.count; ++i) {
1742 if (!self->ir_values) {
1743 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1746 if (!self->ir_values[i]) {
1747 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1750 if (self->ir_values[i]->life) {
1751 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1756 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1758 if (!ast_global_codegen (self->setter, ir, false) ||
1759 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1760 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1762 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1763 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1768 if (!ast_global_codegen (self->getter, ir, false) ||
1769 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1770 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1772 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1773 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1777 for (i = 0; i < self->expression.count; ++i) {
1778 vec_free(self->ir_values[i]->life);
1780 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1784 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1789 ast_expression_codegen *cgen;
1794 irf = self->ir_func;
1796 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1800 /* fill the parameter list */
1801 ec = &self->vtype->expression;
1802 for (i = 0; i < vec_size(ec->params); ++i)
1804 if (ec->params[i]->expression.vtype == TYPE_FIELD)
1805 vec_push(irf->params, ec->params[i]->expression.next->vtype);
1807 vec_push(irf->params, ec->params[i]->expression.vtype);
1808 if (!self->builtin) {
1809 if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1814 if (self->varargs) {
1815 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1817 irf->max_varargs = self->varargs->expression.count;
1820 if (self->builtin) {
1821 irf->builtin = self->builtin;
1825 /* have a local return value variable? */
1826 if (self->return_value) {
1827 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1831 if (!vec_size(self->blocks)) {
1832 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1836 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1837 if (!self->curblock) {
1838 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1846 if (!ast_local_codegen(self->argc, self->ir_func, true))
1848 cgen = self->argc->expression.codegen;
1849 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1851 cgen = self->fixedparams->expression.codegen;
1852 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1854 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1855 ast_function_label(self, "va_count"), INSTR_SUB_F,
1856 ir_builder_get_va_count(ir), fixed);
1859 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1866 for (i = 0; i < vec_size(self->blocks); ++i) {
1867 cgen = self->blocks[i]->expression.codegen;
1868 if (!(*cgen)((ast_expression*)self->blocks[i], self, false, &dummy))
1872 /* TODO: check return types */
1873 if (!self->curblock->final)
1875 if (!self->vtype->expression.next ||
1876 self->vtype->expression.next->vtype == TYPE_VOID)
1878 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1880 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1882 if (self->return_value) {
1883 cgen = self->return_value->expression.codegen;
1884 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1886 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1888 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1889 "control reaches end of non-void function (`%s`) via %s",
1890 self->name, self->curblock->label))
1894 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1900 static bool starts_a_label(ast_expression *ex)
1902 while (ex && ast_istype(ex, ast_block)) {
1903 ast_block *b = (ast_block*)ex;
1908 return ast_istype(ex, ast_label);
1911 /* Note, you will not see ast_block_codegen generate ir_blocks.
1912 * To the AST and the IR, blocks are 2 different things.
1913 * In the AST it represents a block of code, usually enclosed in
1914 * curly braces {...}.
1915 * While in the IR it represents a block in terms of control-flow.
1917 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1921 /* We don't use this
1922 * Note: an ast-representation using the comma-operator
1923 * of the form: (a, b, c) = x should not assign to c...
1926 compile_error(ast_ctx(self), "not an l-value (code-block)");
1930 if (self->expression.outr) {
1931 *out = self->expression.outr;
1935 /* output is NULL at first, we'll have each expression
1936 * assign to out output, thus, a comma-operator represention
1937 * using an ast_block will return the last generated value,
1938 * so: (b, c) + a executed both b and c, and returns c,
1939 * which is then added to a.
1943 /* generate locals */
1944 for (i = 0; i < vec_size(self->locals); ++i)
1946 if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1947 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1948 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1953 for (i = 0; i < vec_size(self->exprs); ++i)
1955 ast_expression_codegen *gen;
1956 if (func->curblock->final && !starts_a_label(self->exprs[i])) {
1957 if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
1961 gen = self->exprs[i]->codegen;
1962 if (!(*gen)(self->exprs[i], func, false, out))
1966 self->expression.outr = *out;
1971 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1973 ast_expression_codegen *cgen;
1974 ir_value *left = NULL;
1975 ir_value *right = NULL;
1979 ast_array_index *ai = NULL;
1981 if (lvalue && self->expression.outl) {
1982 *out = self->expression.outl;
1986 if (!lvalue && self->expression.outr) {
1987 *out = self->expression.outr;
1991 if (ast_istype(self->dest, ast_array_index))
1994 ai = (ast_array_index*)self->dest;
1995 idx = (ast_value*)ai->index;
1997 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2002 /* we need to call the setter */
2003 ir_value *iridx, *funval;
2007 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2011 arr = (ast_value*)ai->array;
2012 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2013 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2017 cgen = idx->expression.codegen;
2018 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2021 cgen = arr->setter->expression.codegen;
2022 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2025 cgen = self->source->codegen;
2026 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2029 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2032 ir_call_param(call, iridx);
2033 ir_call_param(call, right);
2034 self->expression.outr = right;
2040 cgen = self->dest->codegen;
2042 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
2044 self->expression.outl = left;
2046 cgen = self->source->codegen;
2048 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2051 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2053 self->expression.outr = right;
2056 /* Theoretically, an assinment returns its left side as an
2057 * lvalue, if we don't need an lvalue though, we return
2058 * the right side as an rvalue, otherwise we have to
2059 * somehow know whether or not we need to dereference the pointer
2060 * on the left side - that is: OP_LOAD if it was an address.
2061 * Also: in original QC we cannot OP_LOADP *anyway*.
2063 *out = (lvalue ? left : right);
2068 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2070 ast_expression_codegen *cgen;
2071 ir_value *left, *right;
2073 /* A binary operation cannot yield an l-value */
2075 compile_error(ast_ctx(self), "not an l-value (binop)");
2079 if (self->expression.outr) {
2080 *out = self->expression.outr;
2084 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2085 (self->op == INSTR_AND || self->op == INSTR_OR))
2087 /* NOTE: The short-logic path will ignore right_first */
2089 /* short circuit evaluation */
2090 ir_block *other, *merge;
2091 ir_block *from_left, *from_right;
2095 /* prepare end-block */
2096 merge_id = vec_size(func->ir_func->blocks);
2097 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2099 /* generate the left expression */
2100 cgen = self->left->codegen;
2101 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2103 /* remember the block */
2104 from_left = func->curblock;
2106 /* create a new block for the right expression */
2107 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2108 if (self->op == INSTR_AND) {
2109 /* on AND: left==true -> other */
2110 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2113 /* on OR: left==false -> other */
2114 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2117 /* use the likely flag */
2118 vec_last(func->curblock->instr)->likely = true;
2120 /* enter the right-expression's block */
2121 func->curblock = other;
2123 cgen = self->right->codegen;
2124 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2126 /* remember block */
2127 from_right = func->curblock;
2129 /* jump to the merge block */
2130 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2133 vec_remove(func->ir_func->blocks, merge_id, 1);
2134 vec_push(func->ir_func->blocks, merge);
2136 func->curblock = merge;
2137 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2138 ast_function_label(func, "sce_value"),
2139 self->expression.vtype);
2140 ir_phi_add(phi, from_left, left);
2141 ir_phi_add(phi, from_right, right);
2142 *out = ir_phi_value(phi);
2146 if (!OPTS_FLAG(PERL_LOGIC)) {
2148 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2149 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2150 ast_function_label(func, "sce_bool_v"),
2154 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2155 ast_function_label(func, "sce_bool"),
2160 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2161 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2162 ast_function_label(func, "sce_bool_s"),
2166 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2167 ast_function_label(func, "sce_bool"),
2173 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2174 ast_function_label(func, "sce_bool"),
2175 INSTR_AND, *out, *out);
2181 self->expression.outr = *out;
2182 codegen_output_type(self, *out);
2186 if (self->right_first) {
2187 cgen = self->right->codegen;
2188 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2190 cgen = self->left->codegen;
2191 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2194 cgen = self->left->codegen;
2195 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2197 cgen = self->right->codegen;
2198 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2202 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2203 self->op, left, right);
2206 self->expression.outr = *out;
2207 codegen_output_type(self, *out);
2212 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2214 ast_expression_codegen *cgen;
2215 ir_value *leftl = NULL, *leftr, *right, *bin;
2219 ast_array_index *ai = NULL;
2220 ir_value *iridx = NULL;
2222 if (lvalue && self->expression.outl) {
2223 *out = self->expression.outl;
2227 if (!lvalue && self->expression.outr) {
2228 *out = self->expression.outr;
2232 if (ast_istype(self->dest, ast_array_index))
2235 ai = (ast_array_index*)self->dest;
2236 idx = (ast_value*)ai->index;
2238 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2242 /* for a binstore we need both an lvalue and an rvalue for the left side */
2243 /* rvalue of destination! */
2245 cgen = idx->expression.codegen;
2246 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2249 cgen = self->dest->codegen;
2250 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2253 /* source as rvalue only */
2254 cgen = self->source->codegen;
2255 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2258 /* now the binary */
2259 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2260 self->opbin, leftr, right);
2261 self->expression.outr = bin;
2265 /* we need to call the setter */
2270 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2274 arr = (ast_value*)ai->array;
2275 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2276 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2280 cgen = arr->setter->expression.codegen;
2281 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2284 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2287 ir_call_param(call, iridx);
2288 ir_call_param(call, bin);
2289 self->expression.outr = bin;
2291 /* now store them */
2292 cgen = self->dest->codegen;
2293 /* lvalue of destination */
2294 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2296 self->expression.outl = leftl;
2298 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2300 self->expression.outr = bin;
2303 /* Theoretically, an assinment returns its left side as an
2304 * lvalue, if we don't need an lvalue though, we return
2305 * the right side as an rvalue, otherwise we have to
2306 * somehow know whether or not we need to dereference the pointer
2307 * on the left side - that is: OP_LOAD if it was an address.
2308 * Also: in original QC we cannot OP_LOADP *anyway*.
2310 *out = (lvalue ? leftl : bin);
2315 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2317 ast_expression_codegen *cgen;
2320 /* An unary operation cannot yield an l-value */
2322 compile_error(ast_ctx(self), "not an l-value (binop)");
2326 if (self->expression.outr) {
2327 *out = self->expression.outr;
2331 cgen = self->operand->codegen;
2333 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2336 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2340 self->expression.outr = *out;
2345 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2347 ast_expression_codegen *cgen;
2352 /* In the context of a return operation, we don't actually return
2356 compile_error(ast_ctx(self), "return-expression is not an l-value");
2360 if (self->expression.outr) {
2361 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2364 self->expression.outr = (ir_value*)1;
2366 if (self->operand) {
2367 cgen = self->operand->codegen;
2369 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2372 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2375 if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2382 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2384 ast_expression_codegen *cgen;
2385 ir_value *ent, *field;
2387 /* This function needs to take the 'lvalue' flag into account!
2388 * As lvalue we provide a field-pointer, as rvalue we provide the
2392 if (lvalue && self->expression.outl) {
2393 *out = self->expression.outl;
2397 if (!lvalue && self->expression.outr) {
2398 *out = self->expression.outr;
2402 cgen = self->entity->codegen;
2403 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2406 cgen = self->field->codegen;
2407 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2412 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2415 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2416 ent, field, self->expression.vtype);
2417 /* Done AFTER error checking:
2418 codegen_output_type(self, *out);
2422 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2423 (lvalue ? "ADDRESS" : "FIELD"),
2424 type_name[self->expression.vtype]);
2428 codegen_output_type(self, *out);
2431 self->expression.outl = *out;
2433 self->expression.outr = *out;
2435 /* Hm that should be it... */
2439 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2441 ast_expression_codegen *cgen;
2444 /* in QC this is always an lvalue */
2445 if (lvalue && self->rvalue) {
2446 compile_error(ast_ctx(self), "not an l-value (member access)");
2449 if (self->expression.outl) {
2450 *out = self->expression.outl;
2454 cgen = self->owner->codegen;
2455 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2458 if (vec->vtype != TYPE_VECTOR &&
2459 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2464 *out = ir_value_vector_member(vec, self->field);
2465 self->expression.outl = *out;
2467 return (*out != NULL);
2470 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2475 if (!lvalue && self->expression.outr) {
2476 *out = self->expression.outr;
2479 if (lvalue && self->expression.outl) {
2480 *out = self->expression.outl;
2484 if (!ast_istype(self->array, ast_value)) {
2485 compile_error(ast_ctx(self), "array indexing this way is not supported");
2486 /* note this would actually be pointer indexing because the left side is
2487 * not an actual array but (hopefully) an indexable expression.
2488 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2489 * support this path will be filled.
2494 arr = (ast_value*)self->array;
2495 idx = (ast_value*)self->index;
2497 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2498 /* Time to use accessor functions */
2499 ast_expression_codegen *cgen;
2500 ir_value *iridx, *funval;
2504 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2509 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2513 cgen = self->index->codegen;
2514 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2517 cgen = arr->getter->expression.codegen;
2518 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2521 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2524 ir_call_param(call, iridx);
2526 *out = ir_call_value(call);
2527 self->expression.outr = *out;
2528 (*out)->vtype = self->expression.vtype;
2529 codegen_output_type(self, *out);
2533 if (idx->expression.vtype == TYPE_FLOAT) {
2534 unsigned int arridx = idx->constval.vfloat;
2535 if (arridx >= self->array->count)
2537 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2540 *out = arr->ir_values[arridx];
2542 else if (idx->expression.vtype == TYPE_INTEGER) {
2543 unsigned int arridx = idx->constval.vint;
2544 if (arridx >= self->array->count)
2546 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2549 *out = arr->ir_values[arridx];
2552 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2555 (*out)->vtype = self->expression.vtype;
2556 codegen_output_type(self, *out);
2560 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2564 compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2569 compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2573 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2575 ast_expression_codegen *cgen;
2583 ir_block *ontrue_endblock = NULL;
2584 ir_block *onfalse_endblock = NULL;
2585 ir_block *merge = NULL;
2588 /* We don't output any value, thus also don't care about r/lvalue */
2592 if (self->expression.outr) {
2593 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2596 self->expression.outr = (ir_value*)1;
2598 /* generate the condition */
2599 cgen = self->cond->codegen;
2600 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2602 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2603 cond = func->curblock;
2605 /* try constant folding away the condition */
2606 if ((fold = fold_cond_ifthen(condval, func, self)) != -1)
2609 if (self->on_true) {
2610 /* create on-true block */
2611 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2615 /* enter the block */
2616 func->curblock = ontrue;
2619 cgen = self->on_true->codegen;
2620 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2623 /* we now need to work from the current endpoint */
2624 ontrue_endblock = func->curblock;
2629 if (self->on_false) {
2630 /* create on-false block */
2631 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2635 /* enter the block */
2636 func->curblock = onfalse;
2639 cgen = self->on_false->codegen;
2640 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2643 /* we now need to work from the current endpoint */
2644 onfalse_endblock = func->curblock;
2648 /* Merge block were they all merge in to */
2649 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2651 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2654 /* add jumps ot the merge block */
2655 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2657 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2660 /* Now enter the merge block */
2661 func->curblock = merge;
2664 /* we create the if here, that way all blocks are ordered :)
2666 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2667 (ontrue ? ontrue : merge),
2668 (onfalse ? onfalse : merge)))
2676 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2678 ast_expression_codegen *cgen;
2681 ir_value *trueval, *falseval;
2684 ir_block *cond = func->curblock;
2685 ir_block *cond_out = NULL;
2686 ir_block *ontrue, *ontrue_out = NULL;
2687 ir_block *onfalse, *onfalse_out = NULL;
2691 /* Ternary can never create an lvalue... */
2695 /* In theory it shouldn't be possible to pass through a node twice, but
2696 * in case we add any kind of optimization pass for the AST itself, it
2697 * may still happen, thus we remember a created ir_value and simply return one
2698 * if it already exists.
2700 if (self->expression.outr) {
2701 *out = self->expression.outr;
2705 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2707 /* generate the condition */
2708 func->curblock = cond;
2709 cgen = self->cond->codegen;
2710 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2712 cond_out = func->curblock;
2714 /* try constant folding away the condition */
2715 if ((fold = fold_cond_ternary(condval, func, self)) != -1)
2718 /* create on-true block */
2719 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2724 /* enter the block */
2725 func->curblock = ontrue;
2728 cgen = self->on_true->codegen;
2729 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2732 ontrue_out = func->curblock;
2735 /* create on-false block */
2736 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2741 /* enter the block */
2742 func->curblock = onfalse;
2745 cgen = self->on_false->codegen;
2746 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2749 onfalse_out = func->curblock;
2752 /* create merge block */
2753 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2756 /* jump to merge block */
2757 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2759 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2762 /* create if instruction */
2763 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2766 /* Now enter the merge block */
2767 func->curblock = merge;
2769 /* Here, now, we need a PHI node
2770 * but first some sanity checking...
2772 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2773 /* error("ternary with different types on the two sides"); */
2774 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2779 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2781 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2784 ir_phi_add(phi, ontrue_out, trueval);
2785 ir_phi_add(phi, onfalse_out, falseval);
2787 self->expression.outr = ir_phi_value(phi);
2788 *out = self->expression.outr;
2790 codegen_output_type(self, *out);
2795 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2797 ast_expression_codegen *cgen;
2799 ir_value *dummy = NULL;
2800 ir_value *precond = NULL;
2801 ir_value *postcond = NULL;
2803 /* Since we insert some jumps "late" so we have blocks
2804 * ordered "nicely", we need to keep track of the actual end-blocks
2805 * of expressions to add the jumps to.
2807 ir_block *bbody = NULL, *end_bbody = NULL;
2808 ir_block *bprecond = NULL, *end_bprecond = NULL;
2809 ir_block *bpostcond = NULL, *end_bpostcond = NULL;
2810 ir_block *bincrement = NULL, *end_bincrement = NULL;
2811 ir_block *bout = NULL, *bin = NULL;
2813 /* let's at least move the outgoing block to the end */
2816 /* 'break' and 'continue' need to be able to find the right blocks */
2817 ir_block *bcontinue = NULL;
2818 ir_block *bbreak = NULL;
2820 ir_block *tmpblock = NULL;
2825 if (self->expression.outr) {
2826 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2829 self->expression.outr = (ir_value*)1;
2832 * Should we ever need some kind of block ordering, better make this function
2833 * move blocks around than write a block ordering algorithm later... after all
2834 * the ast and ir should work together, not against each other.
2837 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2838 * anyway if for example it contains a ternary.
2842 cgen = self->initexpr->codegen;
2843 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2847 /* Store the block from which we enter this chaos */
2848 bin = func->curblock;
2850 /* The pre-loop condition needs its own block since we
2851 * need to be able to jump to the start of that expression.
2855 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2859 /* the pre-loop-condition the least important place to 'continue' at */
2860 bcontinue = bprecond;
2863 func->curblock = bprecond;
2866 cgen = self->precond->codegen;
2867 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2870 end_bprecond = func->curblock;
2872 bprecond = end_bprecond = NULL;
2875 /* Now the next blocks won't be ordered nicely, but we need to
2876 * generate them this early for 'break' and 'continue'.
2878 if (self->increment) {
2879 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2882 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2884 bincrement = end_bincrement = NULL;
2887 if (self->postcond) {
2888 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2891 bcontinue = bpostcond; /* postcond comes before the increment */
2893 bpostcond = end_bpostcond = NULL;
2896 bout_id = vec_size(func->ir_func->blocks);
2897 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2902 /* The loop body... */
2903 /* if (self->body) */
2905 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2910 func->curblock = bbody;
2912 vec_push(func->breakblocks, bbreak);
2914 vec_push(func->continueblocks, bcontinue);
2916 vec_push(func->continueblocks, bbody);
2920 cgen = self->body->codegen;
2921 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2925 end_bbody = func->curblock;
2926 vec_pop(func->breakblocks);
2927 vec_pop(func->continueblocks);
2930 /* post-loop-condition */
2934 func->curblock = bpostcond;
2937 cgen = self->postcond->codegen;
2938 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2941 end_bpostcond = func->curblock;
2944 /* The incrementor */
2945 if (self->increment)
2948 func->curblock = bincrement;
2951 cgen = self->increment->codegen;
2952 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2955 end_bincrement = func->curblock;
2958 /* In any case now, we continue from the outgoing block */
2959 func->curblock = bout;
2961 /* Now all blocks are in place */
2962 /* From 'bin' we jump to whatever comes first */
2963 if (bprecond) tmpblock = bprecond;
2964 else tmpblock = bbody; /* can never be null */
2967 else if (bpostcond) tmpblock = bpostcond;
2968 else tmpblock = bout;
2971 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2977 ir_block *ontrue, *onfalse;
2978 ontrue = bbody; /* can never be null */
2980 /* all of this is dead code
2981 else if (bincrement) ontrue = bincrement;
2982 else ontrue = bpostcond;
2986 if (self->pre_not) {
2991 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
2998 if (bincrement) tmpblock = bincrement;
2999 else if (bpostcond) tmpblock = bpostcond;
3000 else if (bprecond) tmpblock = bprecond;
3001 else tmpblock = bbody;
3002 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
3006 /* from increment */
3009 if (bpostcond) tmpblock = bpostcond;
3010 else if (bprecond) tmpblock = bprecond;
3011 else if (bbody) tmpblock = bbody;
3012 else tmpblock = bout;
3013 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
3020 ir_block *ontrue, *onfalse;
3021 if (bprecond) ontrue = bprecond;
3022 else ontrue = bbody; /* can never be null */
3024 /* all of this is dead code
3025 else if (bincrement) ontrue = bincrement;
3026 else ontrue = bpostcond;
3030 if (self->post_not) {
3035 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
3039 /* Move 'bout' to the end */
3040 vec_remove(func->ir_func->blocks, bout_id, 1);
3041 vec_push(func->ir_func->blocks, bout);
3046 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
3053 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3057 if (self->expression.outr) {
3058 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3061 self->expression.outr = (ir_value*)1;
3063 if (self->is_continue)
3064 target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
3066 target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
3069 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3073 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3078 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3080 ast_expression_codegen *cgen;
3082 ast_switch_case *def_case = NULL;
3083 ir_block *def_bfall = NULL;
3084 ir_block *def_bfall_to = NULL;
3085 bool set_def_bfall_to = false;
3087 ir_value *dummy = NULL;
3088 ir_value *irop = NULL;
3089 ir_block *bout = NULL;
3090 ir_block *bfall = NULL;
3098 compile_error(ast_ctx(self), "switch expression is not an l-value");
3102 if (self->expression.outr) {
3103 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3106 self->expression.outr = (ir_value*)1;
3111 cgen = self->operand->codegen;
3112 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3115 if (!vec_size(self->cases))
3118 cmpinstr = type_eq_instr[irop->vtype];
3119 if (cmpinstr >= VINSTR_END) {
3120 ast_type_to_string(self->operand, typestr, sizeof(typestr));
3121 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3125 bout_id = vec_size(func->ir_func->blocks);
3126 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3130 /* setup the break block */
3131 vec_push(func->breakblocks, bout);
3133 /* Now create all cases */
3134 for (c = 0; c < vec_size(self->cases); ++c) {
3135 ir_value *cond, *val;
3136 ir_block *bcase, *bnot;
3139 ast_switch_case *swcase = &self->cases[c];
3141 if (swcase->value) {
3142 /* A regular case */
3143 /* generate the condition operand */
3144 cgen = swcase->value->codegen;
3145 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3147 /* generate the condition */
3148 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3152 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3153 bnot_id = vec_size(func->ir_func->blocks);
3154 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3155 if (!bcase || !bnot)
3157 if (set_def_bfall_to) {
3158 set_def_bfall_to = false;
3159 def_bfall_to = bcase;
3161 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3164 /* Make the previous case-end fall through */
3165 if (bfall && !bfall->final) {
3166 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3170 /* enter the case */
3171 func->curblock = bcase;
3172 cgen = swcase->code->codegen;
3173 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3176 /* remember this block to fall through from */
3177 bfall = func->curblock;
3179 /* enter the else and move it down */
3180 func->curblock = bnot;
3181 vec_remove(func->ir_func->blocks, bnot_id, 1);
3182 vec_push(func->ir_func->blocks, bnot);
3184 /* The default case */
3185 /* Remember where to fall through from: */
3188 /* remember which case it was */
3190 /* And the next case will be remembered */
3191 set_def_bfall_to = true;
3195 /* Jump from the last bnot to bout */
3196 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3198 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3203 /* If there was a default case, put it down here */
3207 /* No need to create an extra block */
3208 bcase = func->curblock;
3210 /* Insert the fallthrough jump */
3211 if (def_bfall && !def_bfall->final) {
3212 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3216 /* Now generate the default code */
3217 cgen = def_case->code->codegen;
3218 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3221 /* see if we need to fall through */
3222 if (def_bfall_to && !func->curblock->final)
3224 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3229 /* Jump from the last bnot to bout */
3230 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3232 /* enter the outgoing block */
3233 func->curblock = bout;
3235 /* restore the break block */
3236 vec_pop(func->breakblocks);
3238 /* Move 'bout' to the end, it's nicer */
3239 vec_remove(func->ir_func->blocks, bout_id, 1);
3240 vec_push(func->ir_func->blocks, bout);
3245 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3250 if (self->undefined) {
3251 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3257 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3261 /* simply create a new block and jump to it */
3262 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3263 if (!self->irblock) {
3264 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3267 if (!func->curblock->final) {
3268 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3272 /* enter the new block */
3273 func->curblock = self->irblock;
3275 /* Generate all the leftover gotos */
3276 for (i = 0; i < vec_size(self->gotos); ++i) {
3277 if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3284 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3288 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3292 if (self->target->irblock) {
3293 if (self->irblock_from) {
3294 /* we already tried once, this is the callback */
3295 self->irblock_from->final = false;
3296 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3297 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3303 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3304 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3311 /* the target has not yet been created...
3312 * close this block in a sneaky way:
3314 func->curblock->final = true;
3315 self->irblock_from = func->curblock;
3316 ast_label_register_goto(self->target, self);
3322 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3324 ast_expression_codegen *cgen;
3326 ir_instr *callinstr;
3329 ir_value *funval = NULL;
3331 /* return values are never lvalues */
3333 compile_error(ast_ctx(self), "not an l-value (function call)");
3337 if (self->expression.outr) {
3338 *out = self->expression.outr;
3342 cgen = self->func->codegen;
3343 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3351 for (i = 0; i < vec_size(self->params); ++i)
3354 ast_expression *expr = self->params[i];
3356 cgen = expr->codegen;
3357 if (!(*cgen)(expr, func, false, ¶m))
3361 vec_push(params, param);
3364 /* varargs counter */
3365 if (self->va_count) {
3367 ir_builder *builder = func->curblock->owner->owner;
3368 cgen = self->va_count->codegen;
3369 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3371 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3372 ir_builder_get_va_count(builder), va_count))
3378 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3379 ast_function_label(func, "call"),
3380 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3384 for (i = 0; i < vec_size(params); ++i) {
3385 ir_call_param(callinstr, params[i]);
3388 *out = ir_call_value(callinstr);
3389 self->expression.outr = *out;
3391 codegen_output_type(self, *out);