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 static bool check_array(ast_value *self, ast_value *array)
1353 if (array->expression.flags & AST_FLAG_ARRAY_INIT && !array->initlist) {
1354 compile_error(ast_ctx(self), "array without size: %s", self->name);
1357 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1358 if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1359 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1365 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1369 if (self->expression.vtype == TYPE_NIL) {
1370 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1374 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1376 ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1379 func->context = ast_ctx(self);
1380 func->value->context = ast_ctx(self);
1382 self->constval.vfunc->ir_func = func;
1383 self->ir_v = func->value;
1384 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1385 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1386 /* The function is filled later on ast_function_codegen... */
1390 if (isfield && self->expression.vtype == TYPE_FIELD) {
1391 ast_expression *fieldtype = self->expression.next;
1393 if (self->hasvalue) {
1394 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1398 if (fieldtype->vtype == TYPE_ARRAY) {
1403 ast_expression *elemtype;
1405 ast_value *array = (ast_value*)fieldtype;
1407 if (!ast_istype(fieldtype, ast_value)) {
1408 compile_error(ast_ctx(self), "internal error: ast_value required");
1412 if (!check_array(self, array))
1415 elemtype = array->expression.next;
1416 vtype = elemtype->vtype;
1418 v = ir_builder_create_field(ir, self->name, vtype);
1420 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1423 v->context = ast_ctx(self);
1424 v->unique_life = true;
1426 array->ir_v = self->ir_v = v;
1427 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1428 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1430 namelen = strlen(self->name);
1431 name = (char*)mem_a(namelen + 16);
1432 util_strncpy(name, self->name, namelen);
1434 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1435 array->ir_values[0] = v;
1436 for (ai = 1; ai < array->expression.count; ++ai) {
1437 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1438 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1439 if (!array->ir_values[ai]) {
1441 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1444 array->ir_values[ai]->context = ast_ctx(self);
1445 array->ir_values[ai]->unique_life = true;
1446 array->ir_values[ai]->locked = true;
1447 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1448 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1454 v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1457 v->context = ast_ctx(self);
1459 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1460 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1465 if (self->expression.vtype == TYPE_ARRAY) {
1470 ast_expression *elemtype = self->expression.next;
1471 int vtype = elemtype->vtype;
1473 if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1474 compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1478 /* same as with field arrays */
1479 if (!check_array(self, self))
1482 v = ir_builder_create_global(ir, self->name, vtype);
1484 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1487 v->context = ast_ctx(self);
1488 v->unique_life = true;
1490 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1491 v->flags |= IR_FLAG_INCLUDE_DEF;
1493 namelen = strlen(self->name);
1494 name = (char*)mem_a(namelen + 16);
1495 util_strncpy(name, self->name, namelen);
1497 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1498 self->ir_values[0] = v;
1499 for (ai = 1; ai < self->expression.count; ++ai) {
1500 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1501 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1502 if (!self->ir_values[ai]) {
1504 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1507 self->ir_values[ai]->context = ast_ctx(self);
1508 self->ir_values[ai]->unique_life = true;
1509 self->ir_values[ai]->locked = true;
1510 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1511 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1517 /* Arrays don't do this since there's no "array" value which spans across the
1520 v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1522 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1525 codegen_output_type(self, v);
1526 v->context = ast_ctx(self);
1529 /* link us to the ir_value */
1532 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1533 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1536 if (self->hasvalue) {
1537 switch (self->expression.vtype)
1540 if (!ir_value_set_float(v, self->constval.vfloat))
1544 if (!ir_value_set_vector(v, self->constval.vvec))
1548 if (!ir_value_set_string(v, self->constval.vstring))
1552 ast_global_array_set(self);
1555 compile_error(ast_ctx(self), "global of type function not properly generated");
1557 /* Cannot generate an IR value for a function,
1558 * need a pointer pointing to a function rather.
1561 if (!self->constval.vfield) {
1562 compile_error(ast_ctx(self), "field constant without vfield set");
1565 if (!self->constval.vfield->ir_v) {
1566 compile_error(ast_ctx(self), "field constant generated before its field");
1569 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1573 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1579 error: /* clean up */
1580 if(v) ir_value_delete(v);
1584 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1588 if (self->expression.vtype == TYPE_NIL) {
1589 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1593 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1595 /* Do we allow local functions? I think not...
1596 * this is NOT a function pointer atm.
1601 if (self->expression.vtype == TYPE_ARRAY) {
1606 ast_expression *elemtype = self->expression.next;
1607 int vtype = elemtype->vtype;
1609 func->flags |= IR_FLAG_HAS_ARRAYS;
1611 if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1612 compile_error(ast_ctx(self), "array-parameters are not supported");
1616 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1617 if (!check_array(self, self))
1620 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1621 if (!self->ir_values) {
1622 compile_error(ast_ctx(self), "failed to allocate array values");
1626 v = ir_function_create_local(func, self->name, vtype, param);
1628 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1631 v->context = ast_ctx(self);
1632 v->unique_life = true;
1635 namelen = strlen(self->name);
1636 name = (char*)mem_a(namelen + 16);
1637 util_strncpy(name, self->name, namelen);
1639 self->ir_values[0] = v;
1640 for (ai = 1; ai < self->expression.count; ++ai) {
1641 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1642 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1643 if (!self->ir_values[ai]) {
1644 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1647 self->ir_values[ai]->context = ast_ctx(self);
1648 self->ir_values[ai]->unique_life = true;
1649 self->ir_values[ai]->locked = true;
1655 v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1658 codegen_output_type(self, v);
1659 v->context = ast_ctx(self);
1662 /* A constant local... hmmm...
1663 * I suppose the IR will have to deal with this
1665 if (self->hasvalue) {
1666 switch (self->expression.vtype)
1669 if (!ir_value_set_float(v, self->constval.vfloat))
1673 if (!ir_value_set_vector(v, self->constval.vvec))
1677 if (!ir_value_set_string(v, self->constval.vstring))
1681 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1686 /* link us to the ir_value */
1690 if (!ast_generate_accessors(self, func->owner))
1694 error: /* clean up */
1699 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1702 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1703 if (!self->setter || !self->getter)
1705 for (i = 0; i < self->expression.count; ++i) {
1706 if (!self->ir_values) {
1707 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1710 if (!self->ir_values[i]) {
1711 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1714 if (self->ir_values[i]->life) {
1715 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1720 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1722 if (!ast_global_codegen (self->setter, ir, false) ||
1723 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1724 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1726 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1727 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1732 if (!ast_global_codegen (self->getter, ir, false) ||
1733 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1734 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1736 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1737 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1741 for (i = 0; i < self->expression.count; ++i) {
1742 vec_free(self->ir_values[i]->life);
1744 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1748 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1753 ast_expression_codegen *cgen;
1758 irf = self->ir_func;
1760 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1764 /* fill the parameter list */
1765 ec = &self->vtype->expression;
1766 for (i = 0; i < vec_size(ec->params); ++i)
1768 if (ec->params[i]->expression.vtype == TYPE_FIELD)
1769 vec_push(irf->params, ec->params[i]->expression.next->vtype);
1771 vec_push(irf->params, ec->params[i]->expression.vtype);
1772 if (!self->builtin) {
1773 if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1778 if (self->varargs) {
1779 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1781 irf->max_varargs = self->varargs->expression.count;
1784 if (self->builtin) {
1785 irf->builtin = self->builtin;
1789 /* have a local return value variable? */
1790 if (self->return_value) {
1791 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1795 if (!vec_size(self->blocks)) {
1796 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1800 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1801 if (!self->curblock) {
1802 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1810 if (!ast_local_codegen(self->argc, self->ir_func, true))
1812 cgen = self->argc->expression.codegen;
1813 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1815 cgen = self->fixedparams->expression.codegen;
1816 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1818 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1819 ast_function_label(self, "va_count"), INSTR_SUB_F,
1820 ir_builder_get_va_count(ir), fixed);
1823 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1830 for (i = 0; i < vec_size(self->blocks); ++i) {
1831 cgen = self->blocks[i]->expression.codegen;
1832 if (!(*cgen)((ast_expression*)self->blocks[i], self, false, &dummy))
1836 /* TODO: check return types */
1837 if (!self->curblock->final)
1839 if (!self->vtype->expression.next ||
1840 self->vtype->expression.next->vtype == TYPE_VOID)
1842 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1844 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1846 if (self->return_value) {
1847 cgen = self->return_value->expression.codegen;
1848 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1850 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1852 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1853 "control reaches end of non-void function (`%s`) via %s",
1854 self->name, self->curblock->label))
1858 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1864 /* Note, you will not see ast_block_codegen generate ir_blocks.
1865 * To the AST and the IR, blocks are 2 different things.
1866 * In the AST it represents a block of code, usually enclosed in
1867 * curly braces {...}.
1868 * While in the IR it represents a block in terms of control-flow.
1870 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1874 /* We don't use this
1875 * Note: an ast-representation using the comma-operator
1876 * of the form: (a, b, c) = x should not assign to c...
1879 compile_error(ast_ctx(self), "not an l-value (code-block)");
1883 if (self->expression.outr) {
1884 *out = self->expression.outr;
1888 /* output is NULL at first, we'll have each expression
1889 * assign to out output, thus, a comma-operator represention
1890 * using an ast_block will return the last generated value,
1891 * so: (b, c) + a executed both b and c, and returns c,
1892 * which is then added to a.
1896 /* generate locals */
1897 for (i = 0; i < vec_size(self->locals); ++i)
1899 if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1900 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1901 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1906 for (i = 0; i < vec_size(self->exprs); ++i)
1908 ast_expression_codegen *gen;
1909 if (func->curblock->final && !ast_istype(self->exprs[i], ast_label)) {
1910 if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
1914 gen = self->exprs[i]->codegen;
1915 if (!(*gen)(self->exprs[i], func, false, out))
1919 self->expression.outr = *out;
1924 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1926 ast_expression_codegen *cgen;
1927 ir_value *left = NULL;
1928 ir_value *right = NULL;
1932 ast_array_index *ai = NULL;
1934 if (lvalue && self->expression.outl) {
1935 *out = self->expression.outl;
1939 if (!lvalue && self->expression.outr) {
1940 *out = self->expression.outr;
1944 if (ast_istype(self->dest, ast_array_index))
1947 ai = (ast_array_index*)self->dest;
1948 idx = (ast_value*)ai->index;
1950 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
1955 /* we need to call the setter */
1956 ir_value *iridx, *funval;
1960 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1964 arr = (ast_value*)ai->array;
1965 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1966 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
1970 cgen = idx->expression.codegen;
1971 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1974 cgen = arr->setter->expression.codegen;
1975 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
1978 cgen = self->source->codegen;
1979 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1982 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
1985 ir_call_param(call, iridx);
1986 ir_call_param(call, right);
1987 self->expression.outr = right;
1993 cgen = self->dest->codegen;
1995 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
1997 self->expression.outl = left;
1999 cgen = self->source->codegen;
2001 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2004 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2006 self->expression.outr = right;
2009 /* Theoretically, an assinment returns its left side as an
2010 * lvalue, if we don't need an lvalue though, we return
2011 * the right side as an rvalue, otherwise we have to
2012 * somehow know whether or not we need to dereference the pointer
2013 * on the left side - that is: OP_LOAD if it was an address.
2014 * Also: in original QC we cannot OP_LOADP *anyway*.
2016 *out = (lvalue ? left : right);
2021 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2023 ast_expression_codegen *cgen;
2024 ir_value *left, *right;
2026 /* A binary operation cannot yield an l-value */
2028 compile_error(ast_ctx(self), "not an l-value (binop)");
2032 if (self->expression.outr) {
2033 *out = self->expression.outr;
2037 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2038 (self->op == INSTR_AND || self->op == INSTR_OR))
2040 /* short circuit evaluation */
2041 ir_block *other, *merge;
2042 ir_block *from_left, *from_right;
2046 /* prepare end-block */
2047 merge_id = vec_size(func->ir_func->blocks);
2048 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2050 /* generate the left expression */
2051 cgen = self->left->codegen;
2052 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2054 /* remember the block */
2055 from_left = func->curblock;
2057 /* create a new block for the right expression */
2058 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2059 if (self->op == INSTR_AND) {
2060 /* on AND: left==true -> other */
2061 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2064 /* on OR: left==false -> other */
2065 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2068 /* use the likely flag */
2069 vec_last(func->curblock->instr)->likely = true;
2071 /* enter the right-expression's block */
2072 func->curblock = other;
2074 cgen = self->right->codegen;
2075 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2077 /* remember block */
2078 from_right = func->curblock;
2080 /* jump to the merge block */
2081 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2084 vec_remove(func->ir_func->blocks, merge_id, 1);
2085 vec_push(func->ir_func->blocks, merge);
2087 func->curblock = merge;
2088 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2089 ast_function_label(func, "sce_value"),
2090 self->expression.vtype);
2091 ir_phi_add(phi, from_left, left);
2092 ir_phi_add(phi, from_right, right);
2093 *out = ir_phi_value(phi);
2097 if (!OPTS_FLAG(PERL_LOGIC)) {
2099 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2100 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2101 ast_function_label(func, "sce_bool_v"),
2105 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2106 ast_function_label(func, "sce_bool"),
2111 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2112 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2113 ast_function_label(func, "sce_bool_s"),
2117 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2118 ast_function_label(func, "sce_bool"),
2124 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2125 ast_function_label(func, "sce_bool"),
2126 INSTR_AND, *out, *out);
2132 self->expression.outr = *out;
2133 codegen_output_type(self, *out);
2137 cgen = self->left->codegen;
2138 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2141 cgen = self->right->codegen;
2142 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2145 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2146 self->op, left, right);
2149 self->expression.outr = *out;
2150 codegen_output_type(self, *out);
2155 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2157 ast_expression_codegen *cgen;
2158 ir_value *leftl = NULL, *leftr, *right, *bin;
2162 ast_array_index *ai = NULL;
2163 ir_value *iridx = NULL;
2165 if (lvalue && self->expression.outl) {
2166 *out = self->expression.outl;
2170 if (!lvalue && self->expression.outr) {
2171 *out = self->expression.outr;
2175 if (ast_istype(self->dest, ast_array_index))
2178 ai = (ast_array_index*)self->dest;
2179 idx = (ast_value*)ai->index;
2181 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2185 /* for a binstore we need both an lvalue and an rvalue for the left side */
2186 /* rvalue of destination! */
2188 cgen = idx->expression.codegen;
2189 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2192 cgen = self->dest->codegen;
2193 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2196 /* source as rvalue only */
2197 cgen = self->source->codegen;
2198 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2201 /* now the binary */
2202 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2203 self->opbin, leftr, right);
2204 self->expression.outr = bin;
2208 /* we need to call the setter */
2213 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2217 arr = (ast_value*)ai->array;
2218 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2219 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2223 cgen = arr->setter->expression.codegen;
2224 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2227 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2230 ir_call_param(call, iridx);
2231 ir_call_param(call, bin);
2232 self->expression.outr = bin;
2234 /* now store them */
2235 cgen = self->dest->codegen;
2236 /* lvalue of destination */
2237 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2239 self->expression.outl = leftl;
2241 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2243 self->expression.outr = bin;
2246 /* Theoretically, an assinment returns its left side as an
2247 * lvalue, if we don't need an lvalue though, we return
2248 * the right side as an rvalue, otherwise we have to
2249 * somehow know whether or not we need to dereference the pointer
2250 * on the left side - that is: OP_LOAD if it was an address.
2251 * Also: in original QC we cannot OP_LOADP *anyway*.
2253 *out = (lvalue ? leftl : bin);
2258 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2260 ast_expression_codegen *cgen;
2263 /* An unary operation cannot yield an l-value */
2265 compile_error(ast_ctx(self), "not an l-value (binop)");
2269 if (self->expression.outr) {
2270 *out = self->expression.outr;
2274 cgen = self->operand->codegen;
2276 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2279 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2283 self->expression.outr = *out;
2288 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2290 ast_expression_codegen *cgen;
2295 /* In the context of a return operation, we don't actually return
2299 compile_error(ast_ctx(self), "return-expression is not an l-value");
2303 if (self->expression.outr) {
2304 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2307 self->expression.outr = (ir_value*)1;
2309 if (self->operand) {
2310 cgen = self->operand->codegen;
2312 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2315 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2318 if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2325 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2327 ast_expression_codegen *cgen;
2328 ir_value *ent, *field;
2330 /* This function needs to take the 'lvalue' flag into account!
2331 * As lvalue we provide a field-pointer, as rvalue we provide the
2335 if (lvalue && self->expression.outl) {
2336 *out = self->expression.outl;
2340 if (!lvalue && self->expression.outr) {
2341 *out = self->expression.outr;
2345 cgen = self->entity->codegen;
2346 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2349 cgen = self->field->codegen;
2350 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2355 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2358 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2359 ent, field, self->expression.vtype);
2360 /* Done AFTER error checking:
2361 codegen_output_type(self, *out);
2365 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2366 (lvalue ? "ADDRESS" : "FIELD"),
2367 type_name[self->expression.vtype]);
2371 codegen_output_type(self, *out);
2374 self->expression.outl = *out;
2376 self->expression.outr = *out;
2378 /* Hm that should be it... */
2382 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2384 ast_expression_codegen *cgen;
2387 /* in QC this is always an lvalue */
2388 if (lvalue && self->rvalue) {
2389 compile_error(ast_ctx(self), "not an l-value (member access)");
2392 if (self->expression.outl) {
2393 *out = self->expression.outl;
2397 cgen = self->owner->codegen;
2398 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2401 if (vec->vtype != TYPE_VECTOR &&
2402 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2407 *out = ir_value_vector_member(vec, self->field);
2408 self->expression.outl = *out;
2410 return (*out != NULL);
2413 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2418 if (!lvalue && self->expression.outr) {
2419 *out = self->expression.outr;
2422 if (lvalue && self->expression.outl) {
2423 *out = self->expression.outl;
2427 if (!ast_istype(self->array, ast_value)) {
2428 compile_error(ast_ctx(self), "array indexing this way is not supported");
2429 /* note this would actually be pointer indexing because the left side is
2430 * not an actual array but (hopefully) an indexable expression.
2431 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2432 * support this path will be filled.
2437 arr = (ast_value*)self->array;
2438 idx = (ast_value*)self->index;
2440 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2441 /* Time to use accessor functions */
2442 ast_expression_codegen *cgen;
2443 ir_value *iridx, *funval;
2447 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2452 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2456 cgen = self->index->codegen;
2457 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2460 cgen = arr->getter->expression.codegen;
2461 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2464 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2467 ir_call_param(call, iridx);
2469 *out = ir_call_value(call);
2470 self->expression.outr = *out;
2471 (*out)->vtype = self->expression.vtype;
2472 codegen_output_type(self, *out);
2476 if (idx->expression.vtype == TYPE_FLOAT) {
2477 unsigned int arridx = idx->constval.vfloat;
2478 if (arridx >= self->array->count)
2480 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2483 *out = arr->ir_values[arridx];
2485 else if (idx->expression.vtype == TYPE_INTEGER) {
2486 unsigned int arridx = idx->constval.vint;
2487 if (arridx >= self->array->count)
2489 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2492 *out = arr->ir_values[arridx];
2495 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2498 (*out)->vtype = self->expression.vtype;
2499 codegen_output_type(self, *out);
2503 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2507 compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2512 compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2516 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2518 ast_expression_codegen *cgen;
2526 ir_block *ontrue_endblock = NULL;
2527 ir_block *onfalse_endblock = NULL;
2528 ir_block *merge = NULL;
2531 /* We don't output any value, thus also don't care about r/lvalue */
2535 if (self->expression.outr) {
2536 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2539 self->expression.outr = (ir_value*)1;
2541 /* generate the condition */
2542 cgen = self->cond->codegen;
2543 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2545 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2546 cond = func->curblock;
2548 /* try constant folding away the if */
2549 if ((fold = fold_cond(condval, func, self)) != -1)
2552 if (self->on_true) {
2553 /* create on-true block */
2554 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2558 /* enter the block */
2559 func->curblock = ontrue;
2562 cgen = self->on_true->codegen;
2563 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2566 /* we now need to work from the current endpoint */
2567 ontrue_endblock = func->curblock;
2572 if (self->on_false) {
2573 /* create on-false block */
2574 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2578 /* enter the block */
2579 func->curblock = onfalse;
2582 cgen = self->on_false->codegen;
2583 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2586 /* we now need to work from the current endpoint */
2587 onfalse_endblock = func->curblock;
2591 /* Merge block were they all merge in to */
2592 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2594 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2597 /* add jumps ot the merge block */
2598 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2600 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2603 /* Now enter the merge block */
2604 func->curblock = merge;
2607 /* we create the if here, that way all blocks are ordered :)
2609 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2610 (ontrue ? ontrue : merge),
2611 (onfalse ? onfalse : merge)))
2619 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2621 ast_expression_codegen *cgen;
2624 ir_value *trueval, *falseval;
2627 ir_block *cond = func->curblock;
2628 ir_block *cond_out = NULL;
2629 ir_block *ontrue, *ontrue_out = NULL;
2630 ir_block *onfalse, *onfalse_out = NULL;
2633 /* Ternary can never create an lvalue... */
2637 /* In theory it shouldn't be possible to pass through a node twice, but
2638 * in case we add any kind of optimization pass for the AST itself, it
2639 * may still happen, thus we remember a created ir_value and simply return one
2640 * if it already exists.
2642 if (self->expression.outr) {
2643 *out = self->expression.outr;
2647 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2649 /* generate the condition */
2650 func->curblock = cond;
2651 cgen = self->cond->codegen;
2652 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2654 cond_out = func->curblock;
2656 /* create on-true block */
2657 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2662 /* enter the block */
2663 func->curblock = ontrue;
2666 cgen = self->on_true->codegen;
2667 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2670 ontrue_out = func->curblock;
2673 /* create on-false block */
2674 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2679 /* enter the block */
2680 func->curblock = onfalse;
2683 cgen = self->on_false->codegen;
2684 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2687 onfalse_out = func->curblock;
2690 /* create merge block */
2691 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2694 /* jump to merge block */
2695 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2697 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2700 /* create if instruction */
2701 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2704 /* Now enter the merge block */
2705 func->curblock = merge;
2707 /* Here, now, we need a PHI node
2708 * but first some sanity checking...
2710 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2711 /* error("ternary with different types on the two sides"); */
2712 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2717 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2719 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2722 ir_phi_add(phi, ontrue_out, trueval);
2723 ir_phi_add(phi, onfalse_out, falseval);
2725 self->expression.outr = ir_phi_value(phi);
2726 *out = self->expression.outr;
2728 codegen_output_type(self, *out);
2733 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2735 ast_expression_codegen *cgen;
2737 ir_value *dummy = NULL;
2738 ir_value *precond = NULL;
2739 ir_value *postcond = NULL;
2741 /* Since we insert some jumps "late" so we have blocks
2742 * ordered "nicely", we need to keep track of the actual end-blocks
2743 * of expressions to add the jumps to.
2745 ir_block *bbody = NULL, *end_bbody = NULL;
2746 ir_block *bprecond = NULL, *end_bprecond = NULL;
2747 ir_block *bpostcond = NULL, *end_bpostcond = NULL;
2748 ir_block *bincrement = NULL, *end_bincrement = NULL;
2749 ir_block *bout = NULL, *bin = NULL;
2751 /* let's at least move the outgoing block to the end */
2754 /* 'break' and 'continue' need to be able to find the right blocks */
2755 ir_block *bcontinue = NULL;
2756 ir_block *bbreak = NULL;
2758 ir_block *tmpblock = NULL;
2763 if (self->expression.outr) {
2764 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2767 self->expression.outr = (ir_value*)1;
2770 * Should we ever need some kind of block ordering, better make this function
2771 * move blocks around than write a block ordering algorithm later... after all
2772 * the ast and ir should work together, not against each other.
2775 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2776 * anyway if for example it contains a ternary.
2780 cgen = self->initexpr->codegen;
2781 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2785 /* Store the block from which we enter this chaos */
2786 bin = func->curblock;
2788 /* The pre-loop condition needs its own block since we
2789 * need to be able to jump to the start of that expression.
2793 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2797 /* the pre-loop-condition the least important place to 'continue' at */
2798 bcontinue = bprecond;
2801 func->curblock = bprecond;
2804 cgen = self->precond->codegen;
2805 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2808 end_bprecond = func->curblock;
2810 bprecond = end_bprecond = NULL;
2813 /* Now the next blocks won't be ordered nicely, but we need to
2814 * generate them this early for 'break' and 'continue'.
2816 if (self->increment) {
2817 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2820 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2822 bincrement = end_bincrement = NULL;
2825 if (self->postcond) {
2826 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2829 bcontinue = bpostcond; /* postcond comes before the increment */
2831 bpostcond = end_bpostcond = NULL;
2834 bout_id = vec_size(func->ir_func->blocks);
2835 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2840 /* The loop body... */
2841 /* if (self->body) */
2843 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2848 func->curblock = bbody;
2850 vec_push(func->breakblocks, bbreak);
2852 vec_push(func->continueblocks, bcontinue);
2854 vec_push(func->continueblocks, bbody);
2858 cgen = self->body->codegen;
2859 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2863 end_bbody = func->curblock;
2864 vec_pop(func->breakblocks);
2865 vec_pop(func->continueblocks);
2868 /* post-loop-condition */
2872 func->curblock = bpostcond;
2875 cgen = self->postcond->codegen;
2876 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2879 end_bpostcond = func->curblock;
2882 /* The incrementor */
2883 if (self->increment)
2886 func->curblock = bincrement;
2889 cgen = self->increment->codegen;
2890 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2893 end_bincrement = func->curblock;
2896 /* In any case now, we continue from the outgoing block */
2897 func->curblock = bout;
2899 /* Now all blocks are in place */
2900 /* From 'bin' we jump to whatever comes first */
2901 if (bprecond) tmpblock = bprecond;
2902 else tmpblock = bbody; /* can never be null */
2905 else if (bpostcond) tmpblock = bpostcond;
2906 else tmpblock = bout;
2909 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2915 ir_block *ontrue, *onfalse;
2916 ontrue = bbody; /* can never be null */
2918 /* all of this is dead code
2919 else if (bincrement) ontrue = bincrement;
2920 else ontrue = bpostcond;
2924 if (self->pre_not) {
2929 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
2936 if (bincrement) tmpblock = bincrement;
2937 else if (bpostcond) tmpblock = bpostcond;
2938 else if (bprecond) tmpblock = bprecond;
2939 else tmpblock = bbody;
2940 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
2944 /* from increment */
2947 if (bpostcond) tmpblock = bpostcond;
2948 else if (bprecond) tmpblock = bprecond;
2949 else if (bbody) tmpblock = bbody;
2950 else tmpblock = bout;
2951 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
2958 ir_block *ontrue, *onfalse;
2959 if (bprecond) ontrue = bprecond;
2960 else ontrue = bbody; /* can never be null */
2962 /* all of this is dead code
2963 else if (bincrement) ontrue = bincrement;
2964 else ontrue = bpostcond;
2968 if (self->post_not) {
2973 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
2977 /* Move 'bout' to the end */
2978 vec_remove(func->ir_func->blocks, bout_id, 1);
2979 vec_push(func->ir_func->blocks, bout);
2984 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
2991 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
2995 if (self->expression.outr) {
2996 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
2999 self->expression.outr = (ir_value*)1;
3001 if (self->is_continue)
3002 target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
3004 target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
3007 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3011 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3016 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3018 ast_expression_codegen *cgen;
3020 ast_switch_case *def_case = NULL;
3021 ir_block *def_bfall = NULL;
3022 ir_block *def_bfall_to = NULL;
3023 bool set_def_bfall_to = false;
3025 ir_value *dummy = NULL;
3026 ir_value *irop = NULL;
3027 ir_block *bout = NULL;
3028 ir_block *bfall = NULL;
3036 compile_error(ast_ctx(self), "switch expression is not an l-value");
3040 if (self->expression.outr) {
3041 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3044 self->expression.outr = (ir_value*)1;
3049 cgen = self->operand->codegen;
3050 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3053 if (!vec_size(self->cases))
3056 cmpinstr = type_eq_instr[irop->vtype];
3057 if (cmpinstr >= VINSTR_END) {
3058 ast_type_to_string(self->operand, typestr, sizeof(typestr));
3059 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3063 bout_id = vec_size(func->ir_func->blocks);
3064 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3068 /* setup the break block */
3069 vec_push(func->breakblocks, bout);
3071 /* Now create all cases */
3072 for (c = 0; c < vec_size(self->cases); ++c) {
3073 ir_value *cond, *val;
3074 ir_block *bcase, *bnot;
3077 ast_switch_case *swcase = &self->cases[c];
3079 if (swcase->value) {
3080 /* A regular case */
3081 /* generate the condition operand */
3082 cgen = swcase->value->codegen;
3083 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3085 /* generate the condition */
3086 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3090 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3091 bnot_id = vec_size(func->ir_func->blocks);
3092 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3093 if (!bcase || !bnot)
3095 if (set_def_bfall_to) {
3096 set_def_bfall_to = false;
3097 def_bfall_to = bcase;
3099 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3102 /* Make the previous case-end fall through */
3103 if (bfall && !bfall->final) {
3104 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3108 /* enter the case */
3109 func->curblock = bcase;
3110 cgen = swcase->code->codegen;
3111 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3114 /* remember this block to fall through from */
3115 bfall = func->curblock;
3117 /* enter the else and move it down */
3118 func->curblock = bnot;
3119 vec_remove(func->ir_func->blocks, bnot_id, 1);
3120 vec_push(func->ir_func->blocks, bnot);
3122 /* The default case */
3123 /* Remember where to fall through from: */
3126 /* remember which case it was */
3128 /* And the next case will be remembered */
3129 set_def_bfall_to = true;
3133 /* Jump from the last bnot to bout */
3134 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3136 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3141 /* If there was a default case, put it down here */
3145 /* No need to create an extra block */
3146 bcase = func->curblock;
3148 /* Insert the fallthrough jump */
3149 if (def_bfall && !def_bfall->final) {
3150 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3154 /* Now generate the default code */
3155 cgen = def_case->code->codegen;
3156 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3159 /* see if we need to fall through */
3160 if (def_bfall_to && !func->curblock->final)
3162 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3167 /* Jump from the last bnot to bout */
3168 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3170 /* enter the outgoing block */
3171 func->curblock = bout;
3173 /* restore the break block */
3174 vec_pop(func->breakblocks);
3176 /* Move 'bout' to the end, it's nicer */
3177 vec_remove(func->ir_func->blocks, bout_id, 1);
3178 vec_push(func->ir_func->blocks, bout);
3183 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3188 if (self->undefined) {
3189 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3195 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3199 /* simply create a new block and jump to it */
3200 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3201 if (!self->irblock) {
3202 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3205 if (!func->curblock->final) {
3206 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3210 /* enter the new block */
3211 func->curblock = self->irblock;
3213 /* Generate all the leftover gotos */
3214 for (i = 0; i < vec_size(self->gotos); ++i) {
3215 if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3222 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3226 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3230 if (self->target->irblock) {
3231 if (self->irblock_from) {
3232 /* we already tried once, this is the callback */
3233 self->irblock_from->final = false;
3234 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3235 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3241 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3242 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3249 /* the target has not yet been created...
3250 * close this block in a sneaky way:
3252 func->curblock->final = true;
3253 self->irblock_from = func->curblock;
3254 ast_label_register_goto(self->target, self);
3260 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3262 ast_expression_codegen *cgen;
3264 ir_instr *callinstr;
3267 ir_value *funval = NULL;
3269 /* return values are never lvalues */
3271 compile_error(ast_ctx(self), "not an l-value (function call)");
3275 if (self->expression.outr) {
3276 *out = self->expression.outr;
3280 cgen = self->func->codegen;
3281 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3289 for (i = 0; i < vec_size(self->params); ++i)
3292 ast_expression *expr = self->params[i];
3294 cgen = expr->codegen;
3295 if (!(*cgen)(expr, func, false, ¶m))
3299 vec_push(params, param);
3302 /* varargs counter */
3303 if (self->va_count) {
3305 ir_builder *builder = func->curblock->owner->owner;
3306 cgen = self->va_count->codegen;
3307 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3309 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3310 ir_builder_get_va_count(builder), va_count))
3316 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3317 ast_function_label(func, "call"),
3318 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3322 for (i = 0; i < vec_size(params); ++i) {
3323 ir_call_param(callinstr, params[i]);
3326 *out = ir_call_value(callinstr);
3327 self->expression.outr = *out;
3329 codegen_output_type(self, *out);