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;
377 void ast_value_delete(ast_value* self)
380 mem_d((void*)self->name);
381 if (self->argcounter)
382 mem_d((void*)self->argcounter);
383 if (self->hasvalue) {
384 switch (self->expression.vtype)
387 mem_d((void*)self->constval.vstring);
390 /* unlink us from the function node */
391 self->constval.vfunc->vtype = NULL;
393 /* NOTE: delete function? currently collected in
394 * the parser structure
401 mem_d(self->ir_values);
406 if (self->initlist) {
407 if (self->expression.next->vtype == TYPE_STRING) {
408 /* strings are allocated, free them */
409 size_t i, len = vec_size(self->initlist);
410 /* in theory, len should be expression.count
411 * but let's not take any chances */
412 for (i = 0; i < len; ++i) {
413 if (self->initlist[i].vstring)
414 mem_d(self->initlist[i].vstring);
417 vec_free(self->initlist);
420 ast_expression_delete((ast_expression*)self);
424 void ast_value_params_add(ast_value *self, ast_value *p)
426 vec_push(self->expression.params, p);
429 bool ast_value_set_name(ast_value *self, const char *name)
432 mem_d((void*)self->name);
433 self->name = util_strdup(name);
437 ast_binary* ast_binary_new(lex_ctx_t ctx, int op,
438 ast_expression* left, ast_expression* right)
440 ast_instantiate(ast_binary, ctx, ast_binary_delete);
441 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
447 ast_propagate_effects(self, left);
448 ast_propagate_effects(self, right);
450 if (op >= INSTR_EQ_F && op <= INSTR_GT)
451 self->expression.vtype = TYPE_FLOAT;
452 else if (op == INSTR_AND || op == INSTR_OR) {
453 if (OPTS_FLAG(PERL_LOGIC))
454 ast_type_adopt(self, right);
456 self->expression.vtype = TYPE_FLOAT;
458 else if (op == INSTR_BITAND || op == INSTR_BITOR)
459 self->expression.vtype = TYPE_FLOAT;
460 else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
461 self->expression.vtype = TYPE_VECTOR;
462 else if (op == INSTR_MUL_V)
463 self->expression.vtype = TYPE_FLOAT;
465 self->expression.vtype = left->vtype;
468 self->refs = AST_REF_ALL;
473 void ast_binary_delete(ast_binary *self)
475 if (self->refs & AST_REF_LEFT) ast_unref(self->left);
476 if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
478 ast_expression_delete((ast_expression*)self);
482 ast_binstore* ast_binstore_new(lex_ctx_t ctx, int storop, int op,
483 ast_expression* left, ast_expression* right)
485 ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
486 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
488 ast_side_effects(self) = true;
490 self->opstore = storop;
493 self->source = right;
495 self->keep_dest = false;
497 ast_type_adopt(self, left);
501 void ast_binstore_delete(ast_binstore *self)
503 if (!self->keep_dest)
504 ast_unref(self->dest);
505 ast_unref(self->source);
506 ast_expression_delete((ast_expression*)self);
510 ast_unary* ast_unary_new(lex_ctx_t ctx, int op,
511 ast_expression *expr)
513 ast_instantiate(ast_unary, ctx, ast_unary_delete);
514 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
517 self->operand = expr;
519 ast_propagate_effects(self, expr);
521 if (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) {
522 self->expression.vtype = TYPE_FLOAT;
524 compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
529 void ast_unary_delete(ast_unary *self)
531 if (self->operand) ast_unref(self->operand);
532 ast_expression_delete((ast_expression*)self);
536 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
538 ast_instantiate(ast_return, ctx, ast_return_delete);
539 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
541 self->operand = expr;
544 ast_propagate_effects(self, expr);
549 void ast_return_delete(ast_return *self)
552 ast_unref(self->operand);
553 ast_expression_delete((ast_expression*)self);
557 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
559 if (field->vtype != TYPE_FIELD) {
560 compile_error(ctx, "ast_entfield_new with expression not of type field");
563 return ast_entfield_new_force(ctx, entity, field, field->next);
566 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
568 ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
572 /* Error: field has no type... */
576 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
578 self->entity = entity;
580 ast_propagate_effects(self, entity);
581 ast_propagate_effects(self, field);
583 ast_type_adopt(self, outtype);
587 void ast_entfield_delete(ast_entfield *self)
589 ast_unref(self->entity);
590 ast_unref(self->field);
591 ast_expression_delete((ast_expression*)self);
595 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
597 ast_instantiate(ast_member, ctx, ast_member_delete);
603 if (owner->vtype != TYPE_VECTOR &&
604 owner->vtype != TYPE_FIELD) {
605 compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
610 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
611 self->expression.node.keep = true; /* keep */
613 if (owner->vtype == TYPE_VECTOR) {
614 self->expression.vtype = TYPE_FLOAT;
615 self->expression.next = NULL;
617 self->expression.vtype = TYPE_FIELD;
618 self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
621 self->rvalue = false;
623 ast_propagate_effects(self, owner);
627 self->name = util_strdup(name);
634 void ast_member_delete(ast_member *self)
636 /* The owner is always an ast_value, which has .keep=true,
637 * also: ast_members are usually deleted after the owner, thus
638 * this will cause invalid access
639 ast_unref(self->owner);
640 * once we allow (expression).x to access a vector-member, we need
641 * to change this: preferably by creating an alternate ast node for this
642 * purpose that is not garbage-collected.
644 ast_expression_delete((ast_expression*)self);
649 bool ast_member_set_name(ast_member *self, const char *name)
652 mem_d((void*)self->name);
653 self->name = util_strdup(name);
657 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
659 ast_expression *outtype;
660 ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
662 outtype = array->next;
665 /* Error: field has no type... */
669 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
673 ast_propagate_effects(self, array);
674 ast_propagate_effects(self, index);
676 ast_type_adopt(self, outtype);
677 if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
678 if (self->expression.vtype != TYPE_ARRAY) {
679 compile_error(ast_ctx(self), "array_index node on type");
680 ast_array_index_delete(self);
683 self->array = outtype;
684 self->expression.vtype = TYPE_FIELD;
690 void ast_array_index_delete(ast_array_index *self)
693 ast_unref(self->array);
695 ast_unref(self->index);
696 ast_expression_delete((ast_expression*)self);
700 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
702 ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete);
703 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
705 self->expression.vtype = TYPE_NOEXPR;
709 void ast_argpipe_delete(ast_argpipe *self)
712 ast_unref(self->index);
713 ast_expression_delete((ast_expression*)self);
717 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
719 ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
720 if (!ontrue && !onfalse) {
721 /* because it is invalid */
725 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
728 self->on_true = ontrue;
729 self->on_false = onfalse;
730 ast_propagate_effects(self, cond);
732 ast_propagate_effects(self, ontrue);
734 ast_propagate_effects(self, onfalse);
739 void ast_ifthen_delete(ast_ifthen *self)
741 ast_unref(self->cond);
743 ast_unref(self->on_true);
745 ast_unref(self->on_false);
746 ast_expression_delete((ast_expression*)self);
750 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
752 ast_expression *exprtype = ontrue;
753 ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
754 /* This time NEITHER must be NULL */
755 if (!ontrue || !onfalse) {
759 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
762 self->on_true = ontrue;
763 self->on_false = onfalse;
764 ast_propagate_effects(self, cond);
765 ast_propagate_effects(self, ontrue);
766 ast_propagate_effects(self, onfalse);
768 if (ontrue->vtype == TYPE_NIL)
770 ast_type_adopt(self, exprtype);
775 void ast_ternary_delete(ast_ternary *self)
777 /* the if()s are only there because computed-gotos can set them
780 if (self->cond) ast_unref(self->cond);
781 if (self->on_true) ast_unref(self->on_true);
782 if (self->on_false) ast_unref(self->on_false);
783 ast_expression_delete((ast_expression*)self);
787 ast_loop* ast_loop_new(lex_ctx_t ctx,
788 ast_expression *initexpr,
789 ast_expression *precond, bool pre_not,
790 ast_expression *postcond, bool post_not,
791 ast_expression *increment,
792 ast_expression *body)
794 ast_instantiate(ast_loop, ctx, ast_loop_delete);
795 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
797 self->initexpr = initexpr;
798 self->precond = precond;
799 self->postcond = postcond;
800 self->increment = increment;
803 self->pre_not = pre_not;
804 self->post_not = post_not;
807 ast_propagate_effects(self, initexpr);
809 ast_propagate_effects(self, precond);
811 ast_propagate_effects(self, postcond);
813 ast_propagate_effects(self, increment);
815 ast_propagate_effects(self, body);
820 void ast_loop_delete(ast_loop *self)
823 ast_unref(self->initexpr);
825 ast_unref(self->precond);
827 ast_unref(self->postcond);
829 ast_unref(self->increment);
831 ast_unref(self->body);
832 ast_expression_delete((ast_expression*)self);
836 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
838 ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
839 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
841 self->is_continue = iscont;
842 self->levels = levels;
847 void ast_breakcont_delete(ast_breakcont *self)
849 ast_expression_delete((ast_expression*)self);
853 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
855 ast_instantiate(ast_switch, ctx, ast_switch_delete);
856 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
861 ast_propagate_effects(self, op);
866 void ast_switch_delete(ast_switch *self)
869 ast_unref(self->operand);
871 for (i = 0; i < vec_size(self->cases); ++i) {
872 if (self->cases[i].value)
873 ast_unref(self->cases[i].value);
874 ast_unref(self->cases[i].code);
876 vec_free(self->cases);
878 ast_expression_delete((ast_expression*)self);
882 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
884 ast_instantiate(ast_label, ctx, ast_label_delete);
885 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
887 self->expression.vtype = TYPE_NOEXPR;
889 self->name = util_strdup(name);
890 self->irblock = NULL;
892 self->undefined = undefined;
897 void ast_label_delete(ast_label *self)
899 mem_d((void*)self->name);
900 vec_free(self->gotos);
901 ast_expression_delete((ast_expression*)self);
905 static void ast_label_register_goto(ast_label *self, ast_goto *g)
907 vec_push(self->gotos, g);
910 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
912 ast_instantiate(ast_goto, ctx, ast_goto_delete);
913 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
915 self->name = util_strdup(name);
917 self->irblock_from = NULL;
922 void ast_goto_delete(ast_goto *self)
924 mem_d((void*)self->name);
925 ast_expression_delete((ast_expression*)self);
929 void ast_goto_set_label(ast_goto *self, ast_label *label)
931 self->target = label;
934 ast_call* ast_call_new(lex_ctx_t ctx,
935 ast_expression *funcexpr)
937 ast_instantiate(ast_call, ctx, ast_call_delete);
938 if (!funcexpr->next) {
939 compile_error(ctx, "not a function");
943 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
945 ast_side_effects(self) = true;
948 self->func = funcexpr;
949 self->va_count = NULL;
951 ast_type_adopt(self, funcexpr->next);
956 void ast_call_delete(ast_call *self)
959 for (i = 0; i < vec_size(self->params); ++i)
960 ast_unref(self->params[i]);
961 vec_free(self->params);
964 ast_unref(self->func);
967 ast_unref(self->va_count);
969 ast_expression_delete((ast_expression*)self);
973 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
979 if (!va_type || !ast_compare_type(va_type, exp_type))
981 if (va_type && exp_type)
983 ast_type_to_string(va_type, tgot, sizeof(tgot));
984 ast_type_to_string(exp_type, texp, sizeof(texp));
985 if (OPTS_FLAG(UNSAFE_VARARGS)) {
986 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
987 "piped variadic argument differs in type: constrained to type %s, expected type %s",
991 compile_error(ast_ctx(self),
992 "piped variadic argument differs in type: constrained to type %s, expected type %s",
999 ast_type_to_string(exp_type, texp, sizeof(texp));
1000 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1001 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1002 "piped variadic argument may differ in type: expected type %s",
1006 compile_error(ast_ctx(self),
1007 "piped variadic argument may differ in type: expected type %s",
1016 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1022 const ast_expression *func = self->func;
1023 size_t count = vec_size(self->params);
1024 if (count > vec_size(func->params))
1025 count = vec_size(func->params);
1027 for (i = 0; i < count; ++i) {
1028 if (ast_istype(self->params[i], ast_argpipe)) {
1029 /* warn about type safety instead */
1031 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1034 if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->params[i]))
1037 else if (!ast_compare_type(self->params[i], (ast_expression*)(func->params[i])))
1039 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1040 ast_type_to_string((ast_expression*)func->params[i], texp, sizeof(texp));
1041 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1042 (unsigned int)(i+1), texp, tgot);
1043 /* we don't immediately return */
1047 count = vec_size(self->params);
1048 if (count > vec_size(func->params) && func->varparam) {
1049 for (; 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, func->varparam))
1059 else if (!ast_compare_type(self->params[i], func->varparam))
1061 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1062 ast_type_to_string(func->varparam, texp, sizeof(texp));
1063 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1064 (unsigned int)(i+1), texp, tgot);
1065 /* we don't immediately return */
1073 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1074 ast_expression *dest, ast_expression *source)
1076 ast_instantiate(ast_store, ctx, ast_store_delete);
1077 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1079 ast_side_effects(self) = true;
1083 self->source = source;
1085 ast_type_adopt(self, dest);
1090 void ast_store_delete(ast_store *self)
1092 ast_unref(self->dest);
1093 ast_unref(self->source);
1094 ast_expression_delete((ast_expression*)self);
1098 ast_block* ast_block_new(lex_ctx_t ctx)
1100 ast_instantiate(ast_block, ctx, ast_block_delete);
1101 ast_expression_init((ast_expression*)self,
1102 (ast_expression_codegen*)&ast_block_codegen);
1104 self->locals = NULL;
1106 self->collect = NULL;
1111 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1113 ast_propagate_effects(self, e);
1114 vec_push(self->exprs, e);
1115 if (self->expression.next) {
1116 ast_delete(self->expression.next);
1117 self->expression.next = NULL;
1119 ast_type_adopt(self, e);
1123 void ast_block_collect(ast_block *self, ast_expression *expr)
1125 vec_push(self->collect, expr);
1126 expr->node.keep = true;
1129 void ast_block_delete(ast_block *self)
1132 for (i = 0; i < vec_size(self->exprs); ++i)
1133 ast_unref(self->exprs[i]);
1134 vec_free(self->exprs);
1135 for (i = 0; i < vec_size(self->locals); ++i)
1136 ast_delete(self->locals[i]);
1137 vec_free(self->locals);
1138 for (i = 0; i < vec_size(self->collect); ++i)
1139 ast_delete(self->collect[i]);
1140 vec_free(self->collect);
1141 ast_expression_delete((ast_expression*)self);
1145 void ast_block_set_type(ast_block *self, ast_expression *from)
1147 if (self->expression.next)
1148 ast_delete(self->expression.next);
1149 ast_type_adopt(self, from);
1152 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1154 ast_instantiate(ast_function, ctx, ast_function_delete);
1157 compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1159 } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1160 compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1162 (int)vtype->hasvalue,
1163 vtype->expression.vtype);
1167 self->vtype = vtype;
1168 self->name = name ? util_strdup(name) : NULL;
1169 self->blocks = NULL;
1171 self->labelcount = 0;
1174 self->ir_func = NULL;
1175 self->curblock = NULL;
1177 self->breakblocks = NULL;
1178 self->continueblocks = NULL;
1180 vtype->hasvalue = true;
1181 vtype->constval.vfunc = self;
1183 self->varargs = NULL;
1185 self->fixedparams = NULL;
1186 self->return_value = NULL;
1195 void ast_function_delete(ast_function *self)
1199 mem_d((void*)self->name);
1201 /* ast_value_delete(self->vtype); */
1202 self->vtype->hasvalue = false;
1203 self->vtype->constval.vfunc = NULL;
1204 /* We use unref - if it was stored in a global table it is supposed
1205 * to be deleted from *there*
1207 ast_unref(self->vtype);
1209 for (i = 0; i < vec_size(self->blocks); ++i)
1210 ast_delete(self->blocks[i]);
1211 vec_free(self->blocks);
1212 vec_free(self->breakblocks);
1213 vec_free(self->continueblocks);
1215 ast_delete(self->varargs);
1217 ast_delete(self->argc);
1218 if (self->fixedparams)
1219 ast_unref(self->fixedparams);
1220 if (self->return_value)
1221 ast_unref(self->return_value);
1225 const char* ast_function_label(ast_function *self, const char *prefix)
1231 if (!OPTS_OPTION_BOOL(OPTION_DUMP) &&
1232 !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1233 !OPTS_OPTION_BOOL(OPTION_DEBUG))
1238 id = (self->labelcount++);
1239 len = strlen(prefix);
1241 from = self->labelbuf + sizeof(self->labelbuf)-1;
1244 *from-- = (id%10) + '0';
1248 memcpy(from - len, prefix, len);
1252 /*********************************************************************/
1254 * by convention you must never pass NULL to the 'ir_value **out'
1255 * parameter. If you really don't care about the output, pass a dummy.
1256 * But I can't imagine a pituation where the output is truly unnecessary.
1259 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1261 if (out->vtype == TYPE_FIELD)
1262 out->fieldtype = self->next->vtype;
1263 if (out->vtype == TYPE_FUNCTION)
1264 out->outtype = self->next->vtype;
1267 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1269 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1273 if (self->expression.vtype == TYPE_NIL) {
1274 *out = func->ir_func->owner->nil;
1277 /* NOTE: This is the codegen for a variable used in an expression.
1278 * It is not the codegen to generate the value. For this purpose,
1279 * ast_local_codegen and ast_global_codegen are to be used before this
1280 * is executed. ast_function_codegen should take care of its locals,
1281 * and the ast-user should take care of ast_global_codegen to be used
1282 * on all the globals.
1285 char tname[1024]; /* typename is reserved in C++ */
1286 ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1287 compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1294 static bool ast_global_array_set(ast_value *self)
1296 size_t count = vec_size(self->initlist);
1299 if (count > self->expression.count) {
1300 compile_error(ast_ctx(self), "too many elements in initializer");
1301 count = self->expression.count;
1303 else if (count < self->expression.count) {
1305 compile_warning(ast_ctx(self), "not all elements are initialized");
1309 for (i = 0; i != count; ++i) {
1310 switch (self->expression.next->vtype) {
1312 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1316 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1320 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1324 /* we don't support them in any other place yet either */
1325 compile_error(ast_ctx(self), "TODO: nested arrays");
1328 /* this requiers a bit more work - similar to the fields I suppose */
1329 compile_error(ast_ctx(self), "global of type function not properly generated");
1332 if (!self->initlist[i].vfield) {
1333 compile_error(ast_ctx(self), "field constant without vfield set");
1336 if (!self->initlist[i].vfield->ir_v) {
1337 compile_error(ast_ctx(self), "field constant generated before its field");
1340 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1344 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1351 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1355 if (self->expression.vtype == TYPE_NIL) {
1356 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1360 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1362 ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1365 func->context = ast_ctx(self);
1366 func->value->context = ast_ctx(self);
1368 self->constval.vfunc->ir_func = func;
1369 self->ir_v = func->value;
1370 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1371 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1372 /* The function is filled later on ast_function_codegen... */
1376 if (isfield && self->expression.vtype == TYPE_FIELD) {
1377 ast_expression *fieldtype = self->expression.next;
1379 if (self->hasvalue) {
1380 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1384 if (fieldtype->vtype == TYPE_ARRAY) {
1389 ast_expression *elemtype;
1391 ast_value *array = (ast_value*)fieldtype;
1393 if (!ast_istype(fieldtype, ast_value)) {
1394 compile_error(ast_ctx(self), "internal error: ast_value required");
1398 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1399 if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE))
1400 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1402 elemtype = array->expression.next;
1403 vtype = elemtype->vtype;
1405 v = ir_builder_create_field(ir, self->name, vtype);
1407 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1410 v->context = ast_ctx(self);
1411 v->unique_life = true;
1413 array->ir_v = self->ir_v = v;
1414 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1415 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1417 namelen = strlen(self->name);
1418 name = (char*)mem_a(namelen + 16);
1419 util_strncpy(name, self->name, namelen);
1421 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1422 array->ir_values[0] = v;
1423 for (ai = 1; ai < array->expression.count; ++ai) {
1424 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1425 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1426 if (!array->ir_values[ai]) {
1428 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1431 array->ir_values[ai]->context = ast_ctx(self);
1432 array->ir_values[ai]->unique_life = true;
1433 array->ir_values[ai]->locked = true;
1434 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1435 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1441 v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1444 v->context = ast_ctx(self);
1446 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1447 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1452 if (self->expression.vtype == TYPE_ARRAY) {
1457 ast_expression *elemtype = self->expression.next;
1458 int vtype = elemtype->vtype;
1460 if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1461 compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1465 /* same as with field arrays */
1466 if (!self->expression.count || self->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE))
1467 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)self->expression.count);
1469 v = ir_builder_create_global(ir, self->name, vtype);
1471 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1474 v->context = ast_ctx(self);
1475 v->unique_life = true;
1477 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1478 v->flags |= IR_FLAG_INCLUDE_DEF;
1480 namelen = strlen(self->name);
1481 name = (char*)mem_a(namelen + 16);
1482 util_strncpy(name, self->name, namelen);
1484 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1485 self->ir_values[0] = v;
1486 for (ai = 1; ai < self->expression.count; ++ai) {
1487 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1488 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1489 if (!self->ir_values[ai]) {
1491 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1494 self->ir_values[ai]->context = ast_ctx(self);
1495 self->ir_values[ai]->unique_life = true;
1496 self->ir_values[ai]->locked = true;
1497 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1498 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1504 /* Arrays don't do this since there's no "array" value which spans across the
1507 v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1509 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1512 codegen_output_type(self, v);
1513 v->context = ast_ctx(self);
1516 /* link us to the ir_value */
1519 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1520 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1523 if (self->hasvalue) {
1524 switch (self->expression.vtype)
1527 if (!ir_value_set_float(v, self->constval.vfloat))
1531 if (!ir_value_set_vector(v, self->constval.vvec))
1535 if (!ir_value_set_string(v, self->constval.vstring))
1539 ast_global_array_set(self);
1542 compile_error(ast_ctx(self), "global of type function not properly generated");
1544 /* Cannot generate an IR value for a function,
1545 * need a pointer pointing to a function rather.
1548 if (!self->constval.vfield) {
1549 compile_error(ast_ctx(self), "field constant without vfield set");
1552 if (!self->constval.vfield->ir_v) {
1553 compile_error(ast_ctx(self), "field constant generated before its field");
1556 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1560 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1566 error: /* clean up */
1567 if(v) ir_value_delete(v);
1571 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1575 if (self->expression.vtype == TYPE_NIL) {
1576 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1580 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1582 /* Do we allow local functions? I think not...
1583 * this is NOT a function pointer atm.
1588 if (self->expression.vtype == TYPE_ARRAY) {
1593 ast_expression *elemtype = self->expression.next;
1594 int vtype = elemtype->vtype;
1596 func->flags |= IR_FLAG_HAS_ARRAYS;
1598 if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1599 compile_error(ast_ctx(self), "array-parameters are not supported");
1603 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1604 if (!self->expression.count || self->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1605 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)self->expression.count);
1608 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1609 if (!self->ir_values) {
1610 compile_error(ast_ctx(self), "failed to allocate array values");
1614 v = ir_function_create_local(func, self->name, vtype, param);
1616 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1619 v->context = ast_ctx(self);
1620 v->unique_life = true;
1623 namelen = strlen(self->name);
1624 name = (char*)mem_a(namelen + 16);
1625 util_strncpy(name, self->name, namelen);
1627 self->ir_values[0] = v;
1628 for (ai = 1; ai < self->expression.count; ++ai) {
1629 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1630 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1631 if (!self->ir_values[ai]) {
1632 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1635 self->ir_values[ai]->context = ast_ctx(self);
1636 self->ir_values[ai]->unique_life = true;
1637 self->ir_values[ai]->locked = true;
1643 v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1646 codegen_output_type(self, v);
1647 v->context = ast_ctx(self);
1650 /* A constant local... hmmm...
1651 * I suppose the IR will have to deal with this
1653 if (self->hasvalue) {
1654 switch (self->expression.vtype)
1657 if (!ir_value_set_float(v, self->constval.vfloat))
1661 if (!ir_value_set_vector(v, self->constval.vvec))
1665 if (!ir_value_set_string(v, self->constval.vstring))
1669 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1674 /* link us to the ir_value */
1678 if (!ast_generate_accessors(self, func->owner))
1682 error: /* clean up */
1687 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1690 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1691 if (!self->setter || !self->getter)
1693 for (i = 0; i < self->expression.count; ++i) {
1694 if (!self->ir_values) {
1695 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1698 if (!self->ir_values[i]) {
1699 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1702 if (self->ir_values[i]->life) {
1703 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1708 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1710 if (!ast_global_codegen (self->setter, ir, false) ||
1711 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1712 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1714 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1715 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1720 if (!ast_global_codegen (self->getter, ir, false) ||
1721 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1722 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1724 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1725 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1729 for (i = 0; i < self->expression.count; ++i) {
1730 vec_free(self->ir_values[i]->life);
1732 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1736 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1741 ast_expression_codegen *cgen;
1746 irf = self->ir_func;
1748 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1752 /* fill the parameter list */
1753 ec = &self->vtype->expression;
1754 for (i = 0; i < vec_size(ec->params); ++i)
1756 if (ec->params[i]->expression.vtype == TYPE_FIELD)
1757 vec_push(irf->params, ec->params[i]->expression.next->vtype);
1759 vec_push(irf->params, ec->params[i]->expression.vtype);
1760 if (!self->builtin) {
1761 if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1766 if (self->varargs) {
1767 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1769 irf->max_varargs = self->varargs->expression.count;
1772 if (self->builtin) {
1773 irf->builtin = self->builtin;
1777 /* have a local return value variable? */
1778 if (self->return_value) {
1779 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1783 if (!vec_size(self->blocks)) {
1784 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1788 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1789 if (!self->curblock) {
1790 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1798 if (!ast_local_codegen(self->argc, self->ir_func, true))
1800 cgen = self->argc->expression.codegen;
1801 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1803 cgen = self->fixedparams->expression.codegen;
1804 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1806 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1807 ast_function_label(self, "va_count"), INSTR_SUB_F,
1808 ir_builder_get_va_count(ir), fixed);
1811 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1818 for (i = 0; i < vec_size(self->blocks); ++i) {
1819 cgen = self->blocks[i]->expression.codegen;
1820 if (!(*cgen)((ast_expression*)self->blocks[i], self, false, &dummy))
1824 /* TODO: check return types */
1825 if (!self->curblock->final)
1827 if (!self->vtype->expression.next ||
1828 self->vtype->expression.next->vtype == TYPE_VOID)
1830 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1832 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1834 if (self->return_value) {
1835 cgen = self->return_value->expression.codegen;
1836 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1838 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1840 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1841 "control reaches end of non-void function (`%s`) via %s",
1842 self->name, self->curblock->label))
1846 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1852 /* Note, you will not see ast_block_codegen generate ir_blocks.
1853 * To the AST and the IR, blocks are 2 different things.
1854 * In the AST it represents a block of code, usually enclosed in
1855 * curly braces {...}.
1856 * While in the IR it represents a block in terms of control-flow.
1858 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1862 /* We don't use this
1863 * Note: an ast-representation using the comma-operator
1864 * of the form: (a, b, c) = x should not assign to c...
1867 compile_error(ast_ctx(self), "not an l-value (code-block)");
1871 if (self->expression.outr) {
1872 *out = self->expression.outr;
1876 /* output is NULL at first, we'll have each expression
1877 * assign to out output, thus, a comma-operator represention
1878 * using an ast_block will return the last generated value,
1879 * so: (b, c) + a executed both b and c, and returns c,
1880 * which is then added to a.
1884 /* generate locals */
1885 for (i = 0; i < vec_size(self->locals); ++i)
1887 if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1888 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1889 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1894 for (i = 0; i < vec_size(self->exprs); ++i)
1896 ast_expression_codegen *gen;
1897 if (func->curblock->final && !ast_istype(self->exprs[i], ast_label)) {
1898 if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
1902 gen = self->exprs[i]->codegen;
1903 if (!(*gen)(self->exprs[i], func, false, out))
1907 self->expression.outr = *out;
1912 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1914 ast_expression_codegen *cgen;
1915 ir_value *left = NULL;
1916 ir_value *right = NULL;
1920 ast_array_index *ai = NULL;
1922 if (lvalue && self->expression.outl) {
1923 *out = self->expression.outl;
1927 if (!lvalue && self->expression.outr) {
1928 *out = self->expression.outr;
1932 if (ast_istype(self->dest, ast_array_index))
1935 ai = (ast_array_index*)self->dest;
1936 idx = (ast_value*)ai->index;
1938 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
1943 /* we need to call the setter */
1944 ir_value *iridx, *funval;
1948 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1952 arr = (ast_value*)ai->array;
1953 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1954 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
1958 cgen = idx->expression.codegen;
1959 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1962 cgen = arr->setter->expression.codegen;
1963 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
1966 cgen = self->source->codegen;
1967 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1970 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
1973 ir_call_param(call, iridx);
1974 ir_call_param(call, right);
1975 self->expression.outr = right;
1981 cgen = self->dest->codegen;
1983 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
1985 self->expression.outl = left;
1987 cgen = self->source->codegen;
1989 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1992 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
1994 self->expression.outr = right;
1997 /* Theoretically, an assinment returns its left side as an
1998 * lvalue, if we don't need an lvalue though, we return
1999 * the right side as an rvalue, otherwise we have to
2000 * somehow know whether or not we need to dereference the pointer
2001 * on the left side - that is: OP_LOAD if it was an address.
2002 * Also: in original QC we cannot OP_LOADP *anyway*.
2004 *out = (lvalue ? left : right);
2009 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2011 ast_expression_codegen *cgen;
2012 ir_value *left, *right;
2014 /* A binary operation cannot yield an l-value */
2016 compile_error(ast_ctx(self), "not an l-value (binop)");
2020 if (self->expression.outr) {
2021 *out = self->expression.outr;
2025 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2026 (self->op == INSTR_AND || self->op == INSTR_OR))
2028 /* short circuit evaluation */
2029 ir_block *other, *merge;
2030 ir_block *from_left, *from_right;
2034 /* prepare end-block */
2035 merge_id = vec_size(func->ir_func->blocks);
2036 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2038 /* generate the left expression */
2039 cgen = self->left->codegen;
2040 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2042 /* remember the block */
2043 from_left = func->curblock;
2045 /* create a new block for the right expression */
2046 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2047 if (self->op == INSTR_AND) {
2048 /* on AND: left==true -> other */
2049 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2052 /* on OR: left==false -> other */
2053 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2056 /* use the likely flag */
2057 vec_last(func->curblock->instr)->likely = true;
2059 /* enter the right-expression's block */
2060 func->curblock = other;
2062 cgen = self->right->codegen;
2063 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2065 /* remember block */
2066 from_right = func->curblock;
2068 /* jump to the merge block */
2069 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2072 vec_remove(func->ir_func->blocks, merge_id, 1);
2073 vec_push(func->ir_func->blocks, merge);
2075 func->curblock = merge;
2076 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2077 ast_function_label(func, "sce_value"),
2078 self->expression.vtype);
2079 ir_phi_add(phi, from_left, left);
2080 ir_phi_add(phi, from_right, right);
2081 *out = ir_phi_value(phi);
2085 if (!OPTS_FLAG(PERL_LOGIC)) {
2087 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2088 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2089 ast_function_label(func, "sce_bool_v"),
2093 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2094 ast_function_label(func, "sce_bool"),
2099 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2100 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2101 ast_function_label(func, "sce_bool_s"),
2105 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2106 ast_function_label(func, "sce_bool"),
2112 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2113 ast_function_label(func, "sce_bool"),
2114 INSTR_AND, *out, *out);
2120 self->expression.outr = *out;
2121 codegen_output_type(self, *out);
2125 cgen = self->left->codegen;
2126 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2129 cgen = self->right->codegen;
2130 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2133 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2134 self->op, left, right);
2137 self->expression.outr = *out;
2138 codegen_output_type(self, *out);
2143 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2145 ast_expression_codegen *cgen;
2146 ir_value *leftl = NULL, *leftr, *right, *bin;
2150 ast_array_index *ai = NULL;
2151 ir_value *iridx = NULL;
2153 if (lvalue && self->expression.outl) {
2154 *out = self->expression.outl;
2158 if (!lvalue && self->expression.outr) {
2159 *out = self->expression.outr;
2163 if (ast_istype(self->dest, ast_array_index))
2166 ai = (ast_array_index*)self->dest;
2167 idx = (ast_value*)ai->index;
2169 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2173 /* for a binstore we need both an lvalue and an rvalue for the left side */
2174 /* rvalue of destination! */
2176 cgen = idx->expression.codegen;
2177 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2180 cgen = self->dest->codegen;
2181 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2184 /* source as rvalue only */
2185 cgen = self->source->codegen;
2186 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2189 /* now the binary */
2190 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2191 self->opbin, leftr, right);
2192 self->expression.outr = bin;
2196 /* we need to call the setter */
2201 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2205 arr = (ast_value*)ai->array;
2206 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2207 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2211 cgen = arr->setter->expression.codegen;
2212 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2215 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2218 ir_call_param(call, iridx);
2219 ir_call_param(call, bin);
2220 self->expression.outr = bin;
2222 /* now store them */
2223 cgen = self->dest->codegen;
2224 /* lvalue of destination */
2225 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2227 self->expression.outl = leftl;
2229 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2231 self->expression.outr = bin;
2234 /* Theoretically, an assinment returns its left side as an
2235 * lvalue, if we don't need an lvalue though, we return
2236 * the right side as an rvalue, otherwise we have to
2237 * somehow know whether or not we need to dereference the pointer
2238 * on the left side - that is: OP_LOAD if it was an address.
2239 * Also: in original QC we cannot OP_LOADP *anyway*.
2241 *out = (lvalue ? leftl : bin);
2246 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2248 ast_expression_codegen *cgen;
2251 /* An unary operation cannot yield an l-value */
2253 compile_error(ast_ctx(self), "not an l-value (binop)");
2257 if (self->expression.outr) {
2258 *out = self->expression.outr;
2262 cgen = self->operand->codegen;
2264 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2267 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2271 self->expression.outr = *out;
2276 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2278 ast_expression_codegen *cgen;
2283 /* In the context of a return operation, we don't actually return
2287 compile_error(ast_ctx(self), "return-expression is not an l-value");
2291 if (self->expression.outr) {
2292 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2295 self->expression.outr = (ir_value*)1;
2297 if (self->operand) {
2298 cgen = self->operand->codegen;
2300 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2303 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2306 if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2313 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2315 ast_expression_codegen *cgen;
2316 ir_value *ent, *field;
2318 /* This function needs to take the 'lvalue' flag into account!
2319 * As lvalue we provide a field-pointer, as rvalue we provide the
2323 if (lvalue && self->expression.outl) {
2324 *out = self->expression.outl;
2328 if (!lvalue && self->expression.outr) {
2329 *out = self->expression.outr;
2333 cgen = self->entity->codegen;
2334 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2337 cgen = self->field->codegen;
2338 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2343 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2346 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2347 ent, field, self->expression.vtype);
2348 /* Done AFTER error checking:
2349 codegen_output_type(self, *out);
2353 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2354 (lvalue ? "ADDRESS" : "FIELD"),
2355 type_name[self->expression.vtype]);
2359 codegen_output_type(self, *out);
2362 self->expression.outl = *out;
2364 self->expression.outr = *out;
2366 /* Hm that should be it... */
2370 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2372 ast_expression_codegen *cgen;
2375 /* in QC this is always an lvalue */
2376 if (lvalue && self->rvalue) {
2377 compile_error(ast_ctx(self), "not an l-value (member access)");
2380 if (self->expression.outl) {
2381 *out = self->expression.outl;
2385 cgen = self->owner->codegen;
2386 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2389 if (vec->vtype != TYPE_VECTOR &&
2390 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2395 *out = ir_value_vector_member(vec, self->field);
2396 self->expression.outl = *out;
2398 return (*out != NULL);
2401 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2406 if (!lvalue && self->expression.outr) {
2407 *out = self->expression.outr;
2410 if (lvalue && self->expression.outl) {
2411 *out = self->expression.outl;
2415 if (!ast_istype(self->array, ast_value)) {
2416 compile_error(ast_ctx(self), "array indexing this way is not supported");
2417 /* note this would actually be pointer indexing because the left side is
2418 * not an actual array but (hopefully) an indexable expression.
2419 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2420 * support this path will be filled.
2425 arr = (ast_value*)self->array;
2426 idx = (ast_value*)self->index;
2428 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2429 /* Time to use accessor functions */
2430 ast_expression_codegen *cgen;
2431 ir_value *iridx, *funval;
2435 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2440 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2444 cgen = self->index->codegen;
2445 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2448 cgen = arr->getter->expression.codegen;
2449 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2452 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2455 ir_call_param(call, iridx);
2457 *out = ir_call_value(call);
2458 self->expression.outr = *out;
2459 (*out)->vtype = self->expression.vtype;
2460 codegen_output_type(self, *out);
2464 if (idx->expression.vtype == TYPE_FLOAT) {
2465 unsigned int arridx = idx->constval.vfloat;
2466 if (arridx >= self->array->count)
2468 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2471 *out = arr->ir_values[arridx];
2473 else if (idx->expression.vtype == TYPE_INTEGER) {
2474 unsigned int arridx = idx->constval.vint;
2475 if (arridx >= self->array->count)
2477 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2480 *out = arr->ir_values[arridx];
2483 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2486 (*out)->vtype = self->expression.vtype;
2487 codegen_output_type(self, *out);
2491 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2495 compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2500 compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2504 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2506 ast_expression_codegen *cgen;
2514 ir_block *ontrue_endblock = NULL;
2515 ir_block *onfalse_endblock = NULL;
2516 ir_block *merge = NULL;
2519 /* We don't output any value, thus also don't care about r/lvalue */
2523 if (self->expression.outr) {
2524 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2527 self->expression.outr = (ir_value*)1;
2529 /* generate the condition */
2530 cgen = self->cond->codegen;
2531 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2533 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2534 cond = func->curblock;
2536 /* try constant folding away the if */
2537 if ((fold = fold_cond(condval, func, self)) != -1)
2540 if (self->on_true) {
2541 /* create on-true block */
2542 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2546 /* enter the block */
2547 func->curblock = ontrue;
2550 cgen = self->on_true->codegen;
2551 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2554 /* we now need to work from the current endpoint */
2555 ontrue_endblock = func->curblock;
2560 if (self->on_false) {
2561 /* create on-false block */
2562 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2566 /* enter the block */
2567 func->curblock = onfalse;
2570 cgen = self->on_false->codegen;
2571 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2574 /* we now need to work from the current endpoint */
2575 onfalse_endblock = func->curblock;
2579 /* Merge block were they all merge in to */
2580 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2582 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2585 /* add jumps ot the merge block */
2586 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2588 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2591 /* Now enter the merge block */
2592 func->curblock = merge;
2595 /* we create the if here, that way all blocks are ordered :)
2597 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2598 (ontrue ? ontrue : merge),
2599 (onfalse ? onfalse : merge)))
2607 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2609 ast_expression_codegen *cgen;
2612 ir_value *trueval, *falseval;
2615 ir_block *cond = func->curblock;
2616 ir_block *cond_out = NULL;
2617 ir_block *ontrue, *ontrue_out = NULL;
2618 ir_block *onfalse, *onfalse_out = NULL;
2621 /* Ternary can never create an lvalue... */
2625 /* In theory it shouldn't be possible to pass through a node twice, but
2626 * in case we add any kind of optimization pass for the AST itself, it
2627 * may still happen, thus we remember a created ir_value and simply return one
2628 * if it already exists.
2630 if (self->expression.outr) {
2631 *out = self->expression.outr;
2635 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2637 /* generate the condition */
2638 func->curblock = cond;
2639 cgen = self->cond->codegen;
2640 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2642 cond_out = func->curblock;
2644 /* create on-true block */
2645 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2650 /* enter the block */
2651 func->curblock = ontrue;
2654 cgen = self->on_true->codegen;
2655 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2658 ontrue_out = func->curblock;
2661 /* create on-false block */
2662 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2667 /* enter the block */
2668 func->curblock = onfalse;
2671 cgen = self->on_false->codegen;
2672 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2675 onfalse_out = func->curblock;
2678 /* create merge block */
2679 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2682 /* jump to merge block */
2683 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2685 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2688 /* create if instruction */
2689 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2692 /* Now enter the merge block */
2693 func->curblock = merge;
2695 /* Here, now, we need a PHI node
2696 * but first some sanity checking...
2698 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2699 /* error("ternary with different types on the two sides"); */
2700 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2705 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2707 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2710 ir_phi_add(phi, ontrue_out, trueval);
2711 ir_phi_add(phi, onfalse_out, falseval);
2713 self->expression.outr = ir_phi_value(phi);
2714 *out = self->expression.outr;
2716 codegen_output_type(self, *out);
2721 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2723 ast_expression_codegen *cgen;
2725 ir_value *dummy = NULL;
2726 ir_value *precond = NULL;
2727 ir_value *postcond = NULL;
2729 /* Since we insert some jumps "late" so we have blocks
2730 * ordered "nicely", we need to keep track of the actual end-blocks
2731 * of expressions to add the jumps to.
2733 ir_block *bbody = NULL, *end_bbody = NULL;
2734 ir_block *bprecond = NULL, *end_bprecond = NULL;
2735 ir_block *bpostcond = NULL, *end_bpostcond = NULL;
2736 ir_block *bincrement = NULL, *end_bincrement = NULL;
2737 ir_block *bout = NULL, *bin = NULL;
2739 /* let's at least move the outgoing block to the end */
2742 /* 'break' and 'continue' need to be able to find the right blocks */
2743 ir_block *bcontinue = NULL;
2744 ir_block *bbreak = NULL;
2746 ir_block *tmpblock = NULL;
2751 if (self->expression.outr) {
2752 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2755 self->expression.outr = (ir_value*)1;
2758 * Should we ever need some kind of block ordering, better make this function
2759 * move blocks around than write a block ordering algorithm later... after all
2760 * the ast and ir should work together, not against each other.
2763 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2764 * anyway if for example it contains a ternary.
2768 cgen = self->initexpr->codegen;
2769 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2773 /* Store the block from which we enter this chaos */
2774 bin = func->curblock;
2776 /* The pre-loop condition needs its own block since we
2777 * need to be able to jump to the start of that expression.
2781 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2785 /* the pre-loop-condition the least important place to 'continue' at */
2786 bcontinue = bprecond;
2789 func->curblock = bprecond;
2792 cgen = self->precond->codegen;
2793 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2796 end_bprecond = func->curblock;
2798 bprecond = end_bprecond = NULL;
2801 /* Now the next blocks won't be ordered nicely, but we need to
2802 * generate them this early for 'break' and 'continue'.
2804 if (self->increment) {
2805 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2808 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2810 bincrement = end_bincrement = NULL;
2813 if (self->postcond) {
2814 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2817 bcontinue = bpostcond; /* postcond comes before the increment */
2819 bpostcond = end_bpostcond = NULL;
2822 bout_id = vec_size(func->ir_func->blocks);
2823 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2828 /* The loop body... */
2829 /* if (self->body) */
2831 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2836 func->curblock = bbody;
2838 vec_push(func->breakblocks, bbreak);
2840 vec_push(func->continueblocks, bcontinue);
2842 vec_push(func->continueblocks, bbody);
2846 cgen = self->body->codegen;
2847 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2851 end_bbody = func->curblock;
2852 vec_pop(func->breakblocks);
2853 vec_pop(func->continueblocks);
2856 /* post-loop-condition */
2860 func->curblock = bpostcond;
2863 cgen = self->postcond->codegen;
2864 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2867 end_bpostcond = func->curblock;
2870 /* The incrementor */
2871 if (self->increment)
2874 func->curblock = bincrement;
2877 cgen = self->increment->codegen;
2878 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2881 end_bincrement = func->curblock;
2884 /* In any case now, we continue from the outgoing block */
2885 func->curblock = bout;
2887 /* Now all blocks are in place */
2888 /* From 'bin' we jump to whatever comes first */
2889 if (bprecond) tmpblock = bprecond;
2890 else tmpblock = bbody; /* can never be null */
2893 else if (bpostcond) tmpblock = bpostcond;
2894 else tmpblock = bout;
2897 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2903 ir_block *ontrue, *onfalse;
2904 ontrue = bbody; /* can never be null */
2906 /* all of this is dead code
2907 else if (bincrement) ontrue = bincrement;
2908 else ontrue = bpostcond;
2912 if (self->pre_not) {
2917 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
2924 if (bincrement) tmpblock = bincrement;
2925 else if (bpostcond) tmpblock = bpostcond;
2926 else if (bprecond) tmpblock = bprecond;
2927 else tmpblock = bbody;
2928 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
2932 /* from increment */
2935 if (bpostcond) tmpblock = bpostcond;
2936 else if (bprecond) tmpblock = bprecond;
2937 else if (bbody) tmpblock = bbody;
2938 else tmpblock = bout;
2939 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
2946 ir_block *ontrue, *onfalse;
2947 if (bprecond) ontrue = bprecond;
2948 else ontrue = bbody; /* can never be null */
2950 /* all of this is dead code
2951 else if (bincrement) ontrue = bincrement;
2952 else ontrue = bpostcond;
2956 if (self->post_not) {
2961 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
2965 /* Move 'bout' to the end */
2966 vec_remove(func->ir_func->blocks, bout_id, 1);
2967 vec_push(func->ir_func->blocks, bout);
2972 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
2979 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
2983 if (self->expression.outr) {
2984 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
2987 self->expression.outr = (ir_value*)1;
2989 if (self->is_continue)
2990 target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
2992 target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
2995 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
2999 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3004 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3006 ast_expression_codegen *cgen;
3008 ast_switch_case *def_case = NULL;
3009 ir_block *def_bfall = NULL;
3010 ir_block *def_bfall_to = NULL;
3011 bool set_def_bfall_to = false;
3013 ir_value *dummy = NULL;
3014 ir_value *irop = NULL;
3015 ir_block *bout = NULL;
3016 ir_block *bfall = NULL;
3024 compile_error(ast_ctx(self), "switch expression is not an l-value");
3028 if (self->expression.outr) {
3029 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3032 self->expression.outr = (ir_value*)1;
3037 cgen = self->operand->codegen;
3038 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3041 if (!vec_size(self->cases))
3044 cmpinstr = type_eq_instr[irop->vtype];
3045 if (cmpinstr >= VINSTR_END) {
3046 ast_type_to_string(self->operand, typestr, sizeof(typestr));
3047 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3051 bout_id = vec_size(func->ir_func->blocks);
3052 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3056 /* setup the break block */
3057 vec_push(func->breakblocks, bout);
3059 /* Now create all cases */
3060 for (c = 0; c < vec_size(self->cases); ++c) {
3061 ir_value *cond, *val;
3062 ir_block *bcase, *bnot;
3065 ast_switch_case *swcase = &self->cases[c];
3067 if (swcase->value) {
3068 /* A regular case */
3069 /* generate the condition operand */
3070 cgen = swcase->value->codegen;
3071 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3073 /* generate the condition */
3074 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3078 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3079 bnot_id = vec_size(func->ir_func->blocks);
3080 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3081 if (!bcase || !bnot)
3083 if (set_def_bfall_to) {
3084 set_def_bfall_to = false;
3085 def_bfall_to = bcase;
3087 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3090 /* Make the previous case-end fall through */
3091 if (bfall && !bfall->final) {
3092 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3096 /* enter the case */
3097 func->curblock = bcase;
3098 cgen = swcase->code->codegen;
3099 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3102 /* remember this block to fall through from */
3103 bfall = func->curblock;
3105 /* enter the else and move it down */
3106 func->curblock = bnot;
3107 vec_remove(func->ir_func->blocks, bnot_id, 1);
3108 vec_push(func->ir_func->blocks, bnot);
3110 /* The default case */
3111 /* Remember where to fall through from: */
3114 /* remember which case it was */
3116 /* And the next case will be remembered */
3117 set_def_bfall_to = true;
3121 /* Jump from the last bnot to bout */
3122 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3124 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3129 /* If there was a default case, put it down here */
3133 /* No need to create an extra block */
3134 bcase = func->curblock;
3136 /* Insert the fallthrough jump */
3137 if (def_bfall && !def_bfall->final) {
3138 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3142 /* Now generate the default code */
3143 cgen = def_case->code->codegen;
3144 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3147 /* see if we need to fall through */
3148 if (def_bfall_to && !func->curblock->final)
3150 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3155 /* Jump from the last bnot to bout */
3156 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3158 /* enter the outgoing block */
3159 func->curblock = bout;
3161 /* restore the break block */
3162 vec_pop(func->breakblocks);
3164 /* Move 'bout' to the end, it's nicer */
3165 vec_remove(func->ir_func->blocks, bout_id, 1);
3166 vec_push(func->ir_func->blocks, bout);
3171 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3176 if (self->undefined) {
3177 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3183 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3187 /* simply create a new block and jump to it */
3188 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3189 if (!self->irblock) {
3190 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3193 if (!func->curblock->final) {
3194 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3198 /* enter the new block */
3199 func->curblock = self->irblock;
3201 /* Generate all the leftover gotos */
3202 for (i = 0; i < vec_size(self->gotos); ++i) {
3203 if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3210 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3214 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3218 if (self->target->irblock) {
3219 if (self->irblock_from) {
3220 /* we already tried once, this is the callback */
3221 self->irblock_from->final = false;
3222 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3223 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3229 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3230 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3237 /* the target has not yet been created...
3238 * close this block in a sneaky way:
3240 func->curblock->final = true;
3241 self->irblock_from = func->curblock;
3242 ast_label_register_goto(self->target, self);
3248 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3250 ast_expression_codegen *cgen;
3252 ir_instr *callinstr;
3255 ir_value *funval = NULL;
3257 /* return values are never lvalues */
3259 compile_error(ast_ctx(self), "not an l-value (function call)");
3263 if (self->expression.outr) {
3264 *out = self->expression.outr;
3268 cgen = self->func->codegen;
3269 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3277 for (i = 0; i < vec_size(self->params); ++i)
3280 ast_expression *expr = self->params[i];
3282 cgen = expr->codegen;
3283 if (!(*cgen)(expr, func, false, ¶m))
3287 vec_push(params, param);
3290 /* varargs counter */
3291 if (self->va_count) {
3293 ir_builder *builder = func->curblock->owner->owner;
3294 cgen = self->va_count->codegen;
3295 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3297 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3298 ir_builder_get_va_count(builder), va_count))
3304 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3305 ast_function_label(func, "call"),
3306 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3310 for (i = 0; i < vec_size(params); ++i) {
3311 ir_call_param(callinstr, params[i]);
3314 *out = ir_call_value(callinstr);
3315 self->expression.outr = *out;
3317 codegen_output_type(self, *out);