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
30 #define ast_instantiate(T, ctx, destroyfn) \
31 T* self = (T*)mem_a(sizeof(T)); \
35 ast_node_init((ast_node*)self, ctx, TYPE_##T); \
36 ( (ast_node*)self )->destroy = (ast_node_delete*)destroyfn
39 * forward declarations, these need not be in ast.h for obvious
42 static bool ast_member_codegen(ast_member*, ast_function*, bool lvalue, ir_value**);
43 static void ast_array_index_delete(ast_array_index*);
44 static bool ast_array_index_codegen(ast_array_index*, ast_function*, bool lvalue, ir_value**);
45 static void ast_argpipe_delete(ast_argpipe*);
46 static bool ast_argpipe_codegen(ast_argpipe*, ast_function*, bool lvalue, ir_value**);
47 static void ast_store_delete(ast_store*);
48 static bool ast_store_codegen(ast_store*, ast_function*, bool lvalue, ir_value**);
49 static void ast_ifthen_delete(ast_ifthen*);
50 static bool ast_ifthen_codegen(ast_ifthen*, ast_function*, bool lvalue, ir_value**);
51 static void ast_ternary_delete(ast_ternary*);
52 static bool ast_ternary_codegen(ast_ternary*, ast_function*, bool lvalue, ir_value**);
53 static void ast_loop_delete(ast_loop*);
54 static bool ast_loop_codegen(ast_loop*, ast_function*, bool lvalue, ir_value**);
55 static void ast_breakcont_delete(ast_breakcont*);
56 static bool ast_breakcont_codegen(ast_breakcont*, ast_function*, bool lvalue, ir_value**);
57 static void ast_switch_delete(ast_switch*);
58 static bool ast_switch_codegen(ast_switch*, ast_function*, bool lvalue, ir_value**);
59 static void ast_label_delete(ast_label*);
60 static void ast_label_register_goto(ast_label*, ast_goto*);
61 static bool ast_label_codegen(ast_label*, ast_function*, bool lvalue, ir_value**);
62 static bool ast_goto_codegen(ast_goto*, ast_function*, bool lvalue, ir_value**);
63 static void ast_goto_delete(ast_goto*);
64 static void ast_call_delete(ast_call*);
65 static bool ast_call_codegen(ast_call*, ast_function*, bool lvalue, ir_value**);
66 static bool ast_block_codegen(ast_block*, ast_function*, bool lvalue, ir_value**);
67 static void ast_unary_delete(ast_unary*);
68 static bool ast_unary_codegen(ast_unary*, ast_function*, bool lvalue, ir_value**);
69 static void ast_entfield_delete(ast_entfield*);
70 static bool ast_entfield_codegen(ast_entfield*, ast_function*, bool lvalue, ir_value**);
71 static void ast_return_delete(ast_return*);
72 static bool ast_return_codegen(ast_return*, ast_function*, bool lvalue, ir_value**);
73 static void ast_binstore_delete(ast_binstore*);
74 static bool ast_binstore_codegen(ast_binstore*, ast_function*, bool lvalue, ir_value**);
75 static void ast_binary_delete(ast_binary*);
76 static bool ast_binary_codegen(ast_binary*, ast_function*, bool lvalue, ir_value**);
78 /* It must not be possible to get here. */
79 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
82 con_err("ast node missing destroy()\n");
86 /* Initialize main ast node aprts */
87 static void ast_node_init(ast_node *self, lex_ctx_t ctx, int nodetype)
90 self->destroy = &_ast_node_destroy;
92 self->nodetype = nodetype;
93 self->side_effects = false;
96 /* weight and side effects */
97 static void _ast_propagate_effects(ast_node *self, ast_node *other)
99 if (ast_side_effects(other))
100 ast_side_effects(self) = true;
102 #define ast_propagate_effects(s,o) _ast_propagate_effects(((ast_node*)(s)), ((ast_node*)(o)))
104 /* General expression initialization */
105 static void ast_expression_init(ast_expression *self,
106 ast_expression_codegen *codegen)
108 self->codegen = codegen;
109 self->vtype = TYPE_VOID;
116 self->varparam = NULL;
119 static void ast_expression_delete(ast_expression *self)
123 ast_delete(self->next);
124 for (i = 0; i < vec_size(self->params); ++i) {
125 ast_delete(self->params[i]);
127 vec_free(self->params);
129 ast_delete(self->varparam);
132 static void ast_expression_delete_full(ast_expression *self)
134 ast_expression_delete(self);
138 ast_value* ast_value_copy(const ast_value *self)
141 const ast_expression *fromex;
142 ast_expression *selfex;
143 ast_value *cp = ast_value_new(self->expression.node.context, self->name, self->expression.vtype);
144 if (self->expression.next) {
145 cp->expression.next = ast_type_copy(self->expression.node.context, self->expression.next);
147 fromex = &self->expression;
148 selfex = &cp->expression;
149 selfex->count = fromex->count;
150 selfex->flags = fromex->flags;
151 for (i = 0; i < vec_size(fromex->params); ++i) {
152 ast_value *v = ast_value_copy(fromex->params[i]);
153 vec_push(selfex->params, v);
158 void ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
161 const ast_expression *fromex;
162 ast_expression *selfex;
163 self->vtype = other->vtype;
165 self->next = (ast_expression*)ast_type_copy(ast_ctx(self), other->next);
169 selfex->count = fromex->count;
170 selfex->flags = fromex->flags;
171 for (i = 0; i < vec_size(fromex->params); ++i) {
172 ast_value *v = ast_value_copy(fromex->params[i]);
173 vec_push(selfex->params, v);
177 static ast_expression* ast_shallow_type(lex_ctx_t ctx, int vtype)
179 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
180 ast_expression_init(self, NULL);
181 self->codegen = NULL;
187 ast_expression* ast_type_copy(lex_ctx_t ctx, const ast_expression *ex)
190 const ast_expression *fromex;
191 ast_expression *selfex;
197 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
198 ast_expression_init(self, NULL);
203 /* This may never be codegen()d */
204 selfex->codegen = NULL;
206 selfex->vtype = fromex->vtype;
208 selfex->next = ast_type_copy(ctx, fromex->next);
212 selfex->count = fromex->count;
213 selfex->flags = fromex->flags;
214 for (i = 0; i < vec_size(fromex->params); ++i) {
215 ast_value *v = ast_value_copy(fromex->params[i]);
216 vec_push(selfex->params, v);
223 bool ast_compare_type(ast_expression *a, ast_expression *b)
225 if (a->vtype == TYPE_NIL ||
226 b->vtype == TYPE_NIL)
228 if (a->vtype != b->vtype)
230 if (!a->next != !b->next)
232 if (vec_size(a->params) != vec_size(b->params))
234 if ((a->flags & AST_FLAG_TYPE_MASK) !=
235 (b->flags & AST_FLAG_TYPE_MASK) )
239 if (vec_size(a->params)) {
241 for (i = 0; i < vec_size(a->params); ++i) {
242 if (!ast_compare_type((ast_expression*)a->params[i],
243 (ast_expression*)b->params[i]))
248 return ast_compare_type(a->next, b->next);
252 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
259 if (pos + 6 >= bufsize)
261 util_strncpy(buf + pos, "(null)", 6);
265 if (pos + 1 >= bufsize)
270 util_strncpy(buf + pos, "(variant)", 9);
275 return ast_type_to_string_impl(e->next, buf, bufsize, pos);
278 if (pos + 3 >= bufsize)
282 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
283 if (pos + 1 >= bufsize)
289 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
290 if (pos + 2 >= bufsize)
292 if (!vec_size(e->params)) {
298 pos = ast_type_to_string_impl((ast_expression*)(e->params[0]), buf, bufsize, pos);
299 for (i = 1; i < vec_size(e->params); ++i) {
300 if (pos + 2 >= bufsize)
304 pos = ast_type_to_string_impl((ast_expression*)(e->params[i]), buf, bufsize, pos);
306 if (pos + 1 >= bufsize)
312 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
313 if (pos + 1 >= bufsize)
316 pos += util_snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->count);
317 if (pos + 1 >= bufsize)
323 typestr = type_name[e->vtype];
324 typelen = strlen(typestr);
325 if (pos + typelen >= bufsize)
327 util_strncpy(buf + pos, typestr, typelen);
328 return pos + typelen;
332 buf[bufsize-3] = '.';
333 buf[bufsize-2] = '.';
334 buf[bufsize-1] = '.';
338 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
340 size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
344 static bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out);
345 ast_value* ast_value_new(lex_ctx_t ctx, const char *name, int t)
347 ast_instantiate(ast_value, ctx, ast_value_delete);
348 ast_expression_init((ast_expression*)self,
349 (ast_expression_codegen*)&ast_value_codegen);
350 self->expression.node.keep = true; /* keep */
352 self->name = name ? util_strdup(name) : NULL;
353 self->expression.vtype = t;
354 self->expression.next = NULL;
355 self->isfield = false;
357 self->hasvalue = false;
360 memset(&self->constval, 0, sizeof(self->constval));
361 self->initlist = NULL;
364 self->ir_values = NULL;
365 self->ir_value_count = 0;
371 self->argcounter = NULL;
376 void ast_value_delete(ast_value* self)
379 mem_d((void*)self->name);
380 if (self->argcounter)
381 mem_d((void*)self->argcounter);
382 if (self->hasvalue) {
383 switch (self->expression.vtype)
386 mem_d((void*)self->constval.vstring);
389 /* unlink us from the function node */
390 self->constval.vfunc->vtype = NULL;
392 /* NOTE: delete function? currently collected in
393 * the parser structure
400 mem_d(self->ir_values);
405 if (self->initlist) {
406 if (self->expression.next->vtype == TYPE_STRING) {
407 /* strings are allocated, free them */
408 size_t i, len = vec_size(self->initlist);
409 /* in theory, len should be expression.count
410 * but let's not take any chances */
411 for (i = 0; i < len; ++i) {
412 if (self->initlist[i].vstring)
413 mem_d(self->initlist[i].vstring);
416 vec_free(self->initlist);
419 ast_expression_delete((ast_expression*)self);
423 void ast_value_params_add(ast_value *self, ast_value *p)
425 vec_push(self->expression.params, p);
428 bool ast_value_set_name(ast_value *self, const char *name)
431 mem_d((void*)self->name);
432 self->name = util_strdup(name);
436 ast_binary* ast_binary_new(lex_ctx_t ctx, int op,
437 ast_expression* left, ast_expression* right)
439 ast_instantiate(ast_binary, ctx, ast_binary_delete);
440 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
446 ast_propagate_effects(self, left);
447 ast_propagate_effects(self, right);
449 if (op >= INSTR_EQ_F && op <= INSTR_GT)
450 self->expression.vtype = TYPE_FLOAT;
451 else if (op == INSTR_AND || op == INSTR_OR) {
452 if (OPTS_FLAG(PERL_LOGIC))
453 ast_type_adopt(self, right);
455 self->expression.vtype = TYPE_FLOAT;
457 else if (op == INSTR_BITAND || op == INSTR_BITOR)
458 self->expression.vtype = TYPE_FLOAT;
459 else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
460 self->expression.vtype = TYPE_VECTOR;
461 else if (op == INSTR_MUL_V)
462 self->expression.vtype = TYPE_FLOAT;
464 self->expression.vtype = left->vtype;
467 self->refs = AST_REF_ALL;
472 void ast_binary_delete(ast_binary *self)
474 if (self->refs & AST_REF_LEFT) ast_unref(self->left);
475 if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
477 ast_expression_delete((ast_expression*)self);
481 ast_binstore* ast_binstore_new(lex_ctx_t ctx, int storop, int op,
482 ast_expression* left, ast_expression* right)
484 ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
485 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
487 ast_side_effects(self) = true;
489 self->opstore = storop;
492 self->source = right;
494 self->keep_dest = false;
496 ast_type_adopt(self, left);
500 void ast_binstore_delete(ast_binstore *self)
502 if (!self->keep_dest)
503 ast_unref(self->dest);
504 ast_unref(self->source);
505 ast_expression_delete((ast_expression*)self);
509 ast_unary* ast_unary_new(lex_ctx_t ctx, int op,
510 ast_expression *expr)
512 ast_instantiate(ast_unary, ctx, ast_unary_delete);
513 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
516 self->operand = expr;
518 ast_propagate_effects(self, expr);
520 if (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) {
521 self->expression.vtype = TYPE_FLOAT;
523 compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
528 void ast_unary_delete(ast_unary *self)
530 if (self->operand) ast_unref(self->operand);
531 ast_expression_delete((ast_expression*)self);
535 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
537 ast_instantiate(ast_return, ctx, ast_return_delete);
538 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
540 self->operand = expr;
543 ast_propagate_effects(self, expr);
548 void ast_return_delete(ast_return *self)
551 ast_unref(self->operand);
552 ast_expression_delete((ast_expression*)self);
556 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
558 if (field->vtype != TYPE_FIELD) {
559 compile_error(ctx, "ast_entfield_new with expression not of type field");
562 return ast_entfield_new_force(ctx, entity, field, field->next);
565 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
567 ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
571 /* Error: field has no type... */
575 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
577 self->entity = entity;
579 ast_propagate_effects(self, entity);
580 ast_propagate_effects(self, field);
582 ast_type_adopt(self, outtype);
586 void ast_entfield_delete(ast_entfield *self)
588 ast_unref(self->entity);
589 ast_unref(self->field);
590 ast_expression_delete((ast_expression*)self);
594 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
596 ast_instantiate(ast_member, ctx, ast_member_delete);
602 if (owner->vtype != TYPE_VECTOR &&
603 owner->vtype != TYPE_FIELD) {
604 compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
609 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
610 self->expression.node.keep = true; /* keep */
612 if (owner->vtype == TYPE_VECTOR) {
613 self->expression.vtype = TYPE_FLOAT;
614 self->expression.next = NULL;
616 self->expression.vtype = TYPE_FIELD;
617 self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
620 self->rvalue = false;
622 ast_propagate_effects(self, owner);
626 self->name = util_strdup(name);
633 void ast_member_delete(ast_member *self)
635 /* The owner is always an ast_value, which has .keep=true,
636 * also: ast_members are usually deleted after the owner, thus
637 * this will cause invalid access
638 ast_unref(self->owner);
639 * once we allow (expression).x to access a vector-member, we need
640 * to change this: preferably by creating an alternate ast node for this
641 * purpose that is not garbage-collected.
643 ast_expression_delete((ast_expression*)self);
648 bool ast_member_set_name(ast_member *self, const char *name)
651 mem_d((void*)self->name);
652 self->name = util_strdup(name);
656 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
658 ast_expression *outtype;
659 ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
661 outtype = array->next;
664 /* Error: field has no type... */
668 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
672 ast_propagate_effects(self, array);
673 ast_propagate_effects(self, index);
675 ast_type_adopt(self, outtype);
676 if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
677 if (self->expression.vtype != TYPE_ARRAY) {
678 compile_error(ast_ctx(self), "array_index node on type");
679 ast_array_index_delete(self);
682 self->array = outtype;
683 self->expression.vtype = TYPE_FIELD;
689 void ast_array_index_delete(ast_array_index *self)
692 ast_unref(self->array);
694 ast_unref(self->index);
695 ast_expression_delete((ast_expression*)self);
699 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
701 ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete);
702 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
704 self->expression.vtype = TYPE_NOEXPR;
708 void ast_argpipe_delete(ast_argpipe *self)
711 ast_unref(self->index);
712 ast_expression_delete((ast_expression*)self);
716 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
718 ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
719 if (!ontrue && !onfalse) {
720 /* because it is invalid */
724 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
727 self->on_true = ontrue;
728 self->on_false = onfalse;
729 ast_propagate_effects(self, cond);
731 ast_propagate_effects(self, ontrue);
733 ast_propagate_effects(self, onfalse);
738 void ast_ifthen_delete(ast_ifthen *self)
740 ast_unref(self->cond);
742 ast_unref(self->on_true);
744 ast_unref(self->on_false);
745 ast_expression_delete((ast_expression*)self);
749 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
751 ast_expression *exprtype = ontrue;
752 ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
753 /* This time NEITHER must be NULL */
754 if (!ontrue || !onfalse) {
758 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
761 self->on_true = ontrue;
762 self->on_false = onfalse;
763 ast_propagate_effects(self, cond);
764 ast_propagate_effects(self, ontrue);
765 ast_propagate_effects(self, onfalse);
767 if (ontrue->vtype == TYPE_NIL)
769 ast_type_adopt(self, exprtype);
774 void ast_ternary_delete(ast_ternary *self)
776 /* the if()s are only there because computed-gotos can set them
779 if (self->cond) ast_unref(self->cond);
780 if (self->on_true) ast_unref(self->on_true);
781 if (self->on_false) ast_unref(self->on_false);
782 ast_expression_delete((ast_expression*)self);
786 ast_loop* ast_loop_new(lex_ctx_t ctx,
787 ast_expression *initexpr,
788 ast_expression *precond, bool pre_not,
789 ast_expression *postcond, bool post_not,
790 ast_expression *increment,
791 ast_expression *body)
793 ast_instantiate(ast_loop, ctx, ast_loop_delete);
794 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
796 self->initexpr = initexpr;
797 self->precond = precond;
798 self->postcond = postcond;
799 self->increment = increment;
802 self->pre_not = pre_not;
803 self->post_not = post_not;
806 ast_propagate_effects(self, initexpr);
808 ast_propagate_effects(self, precond);
810 ast_propagate_effects(self, postcond);
812 ast_propagate_effects(self, increment);
814 ast_propagate_effects(self, body);
819 void ast_loop_delete(ast_loop *self)
822 ast_unref(self->initexpr);
824 ast_unref(self->precond);
826 ast_unref(self->postcond);
828 ast_unref(self->increment);
830 ast_unref(self->body);
831 ast_expression_delete((ast_expression*)self);
835 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
837 ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
838 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
840 self->is_continue = iscont;
841 self->levels = levels;
846 void ast_breakcont_delete(ast_breakcont *self)
848 ast_expression_delete((ast_expression*)self);
852 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
854 ast_instantiate(ast_switch, ctx, ast_switch_delete);
855 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
860 ast_propagate_effects(self, op);
865 void ast_switch_delete(ast_switch *self)
868 ast_unref(self->operand);
870 for (i = 0; i < vec_size(self->cases); ++i) {
871 if (self->cases[i].value)
872 ast_unref(self->cases[i].value);
873 ast_unref(self->cases[i].code);
875 vec_free(self->cases);
877 ast_expression_delete((ast_expression*)self);
881 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
883 ast_instantiate(ast_label, ctx, ast_label_delete);
884 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
886 self->expression.vtype = TYPE_NOEXPR;
888 self->name = util_strdup(name);
889 self->irblock = NULL;
891 self->undefined = undefined;
896 void ast_label_delete(ast_label *self)
898 mem_d((void*)self->name);
899 vec_free(self->gotos);
900 ast_expression_delete((ast_expression*)self);
904 static void ast_label_register_goto(ast_label *self, ast_goto *g)
906 vec_push(self->gotos, g);
909 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
911 ast_instantiate(ast_goto, ctx, ast_goto_delete);
912 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
914 self->name = util_strdup(name);
916 self->irblock_from = NULL;
921 void ast_goto_delete(ast_goto *self)
923 mem_d((void*)self->name);
924 ast_expression_delete((ast_expression*)self);
928 void ast_goto_set_label(ast_goto *self, ast_label *label)
930 self->target = label;
933 ast_call* ast_call_new(lex_ctx_t ctx,
934 ast_expression *funcexpr)
936 ast_instantiate(ast_call, ctx, ast_call_delete);
937 if (!funcexpr->next) {
938 compile_error(ctx, "not a function");
942 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
944 ast_side_effects(self) = true;
947 self->func = funcexpr;
948 self->va_count = NULL;
950 ast_type_adopt(self, funcexpr->next);
955 void ast_call_delete(ast_call *self)
958 for (i = 0; i < vec_size(self->params); ++i)
959 ast_unref(self->params[i]);
960 vec_free(self->params);
963 ast_unref(self->func);
966 ast_unref(self->va_count);
968 ast_expression_delete((ast_expression*)self);
972 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
978 if (!va_type || !ast_compare_type(va_type, exp_type))
980 if (va_type && exp_type)
982 ast_type_to_string(va_type, tgot, sizeof(tgot));
983 ast_type_to_string(exp_type, texp, sizeof(texp));
984 if (OPTS_FLAG(UNSAFE_VARARGS)) {
985 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
986 "piped variadic argument differs in type: constrained to type %s, expected type %s",
990 compile_error(ast_ctx(self),
991 "piped variadic argument differs in type: constrained to type %s, expected type %s",
998 ast_type_to_string(exp_type, texp, sizeof(texp));
999 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1000 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1001 "piped variadic argument may differ in type: expected type %s",
1005 compile_error(ast_ctx(self),
1006 "piped variadic argument may differ in type: expected type %s",
1015 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1021 const ast_expression *func = self->func;
1022 size_t count = vec_size(self->params);
1023 if (count > vec_size(func->params))
1024 count = vec_size(func->params);
1026 for (i = 0; i < count; ++i) {
1027 if (ast_istype(self->params[i], ast_argpipe)) {
1028 /* warn about type safety instead */
1030 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1033 if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->params[i]))
1036 else if (!ast_compare_type(self->params[i], (ast_expression*)(func->params[i])))
1038 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1039 ast_type_to_string((ast_expression*)func->params[i], texp, sizeof(texp));
1040 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1041 (unsigned int)(i+1), texp, tgot);
1042 /* we don't immediately return */
1046 count = vec_size(self->params);
1047 if (count > vec_size(func->params) && func->varparam) {
1048 for (; i < count; ++i) {
1049 if (ast_istype(self->params[i], ast_argpipe)) {
1050 /* warn about type safety instead */
1052 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1055 if (!ast_call_check_vararg(self, va_type, func->varparam))
1058 else if (!ast_compare_type(self->params[i], func->varparam))
1060 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1061 ast_type_to_string(func->varparam, texp, sizeof(texp));
1062 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1063 (unsigned int)(i+1), texp, tgot);
1064 /* we don't immediately return */
1072 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1073 ast_expression *dest, ast_expression *source)
1075 ast_instantiate(ast_store, ctx, ast_store_delete);
1076 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1078 ast_side_effects(self) = true;
1082 self->source = source;
1084 ast_type_adopt(self, dest);
1089 void ast_store_delete(ast_store *self)
1091 ast_unref(self->dest);
1092 ast_unref(self->source);
1093 ast_expression_delete((ast_expression*)self);
1097 ast_block* ast_block_new(lex_ctx_t ctx)
1099 ast_instantiate(ast_block, ctx, ast_block_delete);
1100 ast_expression_init((ast_expression*)self,
1101 (ast_expression_codegen*)&ast_block_codegen);
1103 self->locals = NULL;
1105 self->collect = NULL;
1110 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1112 ast_propagate_effects(self, e);
1113 vec_push(self->exprs, e);
1114 if (self->expression.next) {
1115 ast_delete(self->expression.next);
1116 self->expression.next = NULL;
1118 ast_type_adopt(self, e);
1122 void ast_block_collect(ast_block *self, ast_expression *expr)
1124 vec_push(self->collect, expr);
1125 expr->node.keep = true;
1128 void ast_block_delete(ast_block *self)
1131 for (i = 0; i < vec_size(self->exprs); ++i)
1132 ast_unref(self->exprs[i]);
1133 vec_free(self->exprs);
1134 for (i = 0; i < vec_size(self->locals); ++i)
1135 ast_delete(self->locals[i]);
1136 vec_free(self->locals);
1137 for (i = 0; i < vec_size(self->collect); ++i)
1138 ast_delete(self->collect[i]);
1139 vec_free(self->collect);
1140 ast_expression_delete((ast_expression*)self);
1144 void ast_block_set_type(ast_block *self, ast_expression *from)
1146 if (self->expression.next)
1147 ast_delete(self->expression.next);
1148 ast_type_adopt(self, from);
1151 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1153 ast_instantiate(ast_function, ctx, ast_function_delete);
1156 compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1158 } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1159 compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1161 (int)vtype->hasvalue,
1162 vtype->expression.vtype);
1166 self->vtype = vtype;
1167 self->name = name ? util_strdup(name) : NULL;
1168 self->blocks = NULL;
1170 self->labelcount = 0;
1173 self->ir_func = NULL;
1174 self->curblock = NULL;
1176 self->breakblocks = NULL;
1177 self->continueblocks = NULL;
1179 vtype->hasvalue = true;
1180 vtype->constval.vfunc = self;
1182 self->varargs = NULL;
1184 self->fixedparams = NULL;
1185 self->return_value = NULL;
1194 void ast_function_delete(ast_function *self)
1198 mem_d((void*)self->name);
1200 /* ast_value_delete(self->vtype); */
1201 self->vtype->hasvalue = false;
1202 self->vtype->constval.vfunc = NULL;
1203 /* We use unref - if it was stored in a global table it is supposed
1204 * to be deleted from *there*
1206 ast_unref(self->vtype);
1208 for (i = 0; i < vec_size(self->blocks); ++i)
1209 ast_delete(self->blocks[i]);
1210 vec_free(self->blocks);
1211 vec_free(self->breakblocks);
1212 vec_free(self->continueblocks);
1214 ast_delete(self->varargs);
1216 ast_delete(self->argc);
1217 if (self->fixedparams)
1218 ast_unref(self->fixedparams);
1219 if (self->return_value)
1220 ast_unref(self->return_value);
1224 static const char* ast_function_label(ast_function *self, const char *prefix)
1230 if (!OPTS_OPTION_BOOL(OPTION_DUMP) &&
1231 !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1232 !OPTS_OPTION_BOOL(OPTION_DEBUG))
1237 id = (self->labelcount++);
1238 len = strlen(prefix);
1240 from = self->labelbuf + sizeof(self->labelbuf)-1;
1243 *from-- = (id%10) + '0';
1247 memcpy(from - len, prefix, len);
1251 /*********************************************************************/
1253 * by convention you must never pass NULL to the 'ir_value **out'
1254 * parameter. If you really don't care about the output, pass a dummy.
1255 * But I can't imagine a pituation where the output is truly unnecessary.
1258 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1260 if (out->vtype == TYPE_FIELD)
1261 out->fieldtype = self->next->vtype;
1262 if (out->vtype == TYPE_FUNCTION)
1263 out->outtype = self->next->vtype;
1266 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1268 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1272 if (self->expression.vtype == TYPE_NIL) {
1273 *out = func->ir_func->owner->nil;
1276 /* NOTE: This is the codegen for a variable used in an expression.
1277 * It is not the codegen to generate the value. For this purpose,
1278 * ast_local_codegen and ast_global_codegen are to be used before this
1279 * is executed. ast_function_codegen should take care of its locals,
1280 * and the ast-user should take care of ast_global_codegen to be used
1281 * on all the globals.
1284 char tname[1024]; /* typename is reserved in C++ */
1285 ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1286 compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1293 static bool ast_global_array_set(ast_value *self)
1295 size_t count = vec_size(self->initlist);
1298 if (count > self->expression.count) {
1299 compile_error(ast_ctx(self), "too many elements in initializer");
1300 count = self->expression.count;
1302 else if (count < self->expression.count) {
1304 compile_warning(ast_ctx(self), "not all elements are initialized");
1308 for (i = 0; i != count; ++i) {
1309 switch (self->expression.next->vtype) {
1311 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1315 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1319 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1323 /* we don't support them in any other place yet either */
1324 compile_error(ast_ctx(self), "TODO: nested arrays");
1327 /* this requiers a bit more work - similar to the fields I suppose */
1328 compile_error(ast_ctx(self), "global of type function not properly generated");
1331 if (!self->initlist[i].vfield) {
1332 compile_error(ast_ctx(self), "field constant without vfield set");
1335 if (!self->initlist[i].vfield->ir_v) {
1336 compile_error(ast_ctx(self), "field constant generated before its field");
1339 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1343 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1350 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1354 if (self->expression.vtype == TYPE_NIL) {
1355 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1359 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1361 ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1364 func->context = ast_ctx(self);
1365 func->value->context = ast_ctx(self);
1367 self->constval.vfunc->ir_func = func;
1368 self->ir_v = func->value;
1369 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1370 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1371 /* The function is filled later on ast_function_codegen... */
1375 if (isfield && self->expression.vtype == TYPE_FIELD) {
1376 ast_expression *fieldtype = self->expression.next;
1378 if (self->hasvalue) {
1379 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1383 if (fieldtype->vtype == TYPE_ARRAY) {
1388 ast_expression *elemtype;
1390 ast_value *array = (ast_value*)fieldtype;
1392 if (!ast_istype(fieldtype, ast_value)) {
1393 compile_error(ast_ctx(self), "internal error: ast_value required");
1397 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1398 if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE))
1399 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1401 elemtype = array->expression.next;
1402 vtype = elemtype->vtype;
1404 v = ir_builder_create_field(ir, self->name, vtype);
1406 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1409 v->context = ast_ctx(self);
1410 v->unique_life = true;
1412 array->ir_v = self->ir_v = v;
1413 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1414 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1416 namelen = strlen(self->name);
1417 name = (char*)mem_a(namelen + 16);
1418 util_strncpy(name, self->name, namelen);
1420 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1421 array->ir_values[0] = v;
1422 for (ai = 1; ai < array->expression.count; ++ai) {
1423 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1424 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1425 if (!array->ir_values[ai]) {
1427 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1430 array->ir_values[ai]->context = ast_ctx(self);
1431 array->ir_values[ai]->unique_life = true;
1432 array->ir_values[ai]->locked = true;
1433 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1434 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1440 v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1443 v->context = ast_ctx(self);
1445 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1446 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1451 if (self->expression.vtype == TYPE_ARRAY) {
1456 ast_expression *elemtype = self->expression.next;
1457 int vtype = elemtype->vtype;
1459 if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1460 compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1464 /* same as with field arrays */
1465 if (!self->expression.count || self->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE))
1466 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)self->expression.count);
1468 v = ir_builder_create_global(ir, self->name, vtype);
1470 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1473 v->context = ast_ctx(self);
1474 v->unique_life = true;
1476 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1477 v->flags |= IR_FLAG_INCLUDE_DEF;
1479 namelen = strlen(self->name);
1480 name = (char*)mem_a(namelen + 16);
1481 util_strncpy(name, self->name, namelen);
1483 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1484 self->ir_values[0] = v;
1485 for (ai = 1; ai < self->expression.count; ++ai) {
1486 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1487 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1488 if (!self->ir_values[ai]) {
1490 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1493 self->ir_values[ai]->context = ast_ctx(self);
1494 self->ir_values[ai]->unique_life = true;
1495 self->ir_values[ai]->locked = true;
1496 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1497 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1503 /* Arrays don't do this since there's no "array" value which spans across the
1506 v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1508 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1511 codegen_output_type(self, v);
1512 v->context = ast_ctx(self);
1515 /* link us to the ir_value */
1518 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1519 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1522 if (self->hasvalue) {
1523 switch (self->expression.vtype)
1526 if (!ir_value_set_float(v, self->constval.vfloat))
1530 if (!ir_value_set_vector(v, self->constval.vvec))
1534 if (!ir_value_set_string(v, self->constval.vstring))
1538 ast_global_array_set(self);
1541 compile_error(ast_ctx(self), "global of type function not properly generated");
1543 /* Cannot generate an IR value for a function,
1544 * need a pointer pointing to a function rather.
1547 if (!self->constval.vfield) {
1548 compile_error(ast_ctx(self), "field constant without vfield set");
1551 if (!self->constval.vfield->ir_v) {
1552 compile_error(ast_ctx(self), "field constant generated before its field");
1555 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1559 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1565 error: /* clean up */
1566 if(v) ir_value_delete(v);
1570 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1574 if (self->expression.vtype == TYPE_NIL) {
1575 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1579 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1581 /* Do we allow local functions? I think not...
1582 * this is NOT a function pointer atm.
1587 if (self->expression.vtype == TYPE_ARRAY) {
1592 ast_expression *elemtype = self->expression.next;
1593 int vtype = elemtype->vtype;
1595 func->flags |= IR_FLAG_HAS_ARRAYS;
1597 if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1598 compile_error(ast_ctx(self), "array-parameters are not supported");
1602 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1603 if (!self->expression.count || self->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1604 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)self->expression.count);
1607 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1608 if (!self->ir_values) {
1609 compile_error(ast_ctx(self), "failed to allocate array values");
1613 v = ir_function_create_local(func, self->name, vtype, param);
1615 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1618 v->context = ast_ctx(self);
1619 v->unique_life = true;
1622 namelen = strlen(self->name);
1623 name = (char*)mem_a(namelen + 16);
1624 util_strncpy(name, self->name, namelen);
1626 self->ir_values[0] = v;
1627 for (ai = 1; ai < self->expression.count; ++ai) {
1628 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1629 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1630 if (!self->ir_values[ai]) {
1631 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1634 self->ir_values[ai]->context = ast_ctx(self);
1635 self->ir_values[ai]->unique_life = true;
1636 self->ir_values[ai]->locked = true;
1642 v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1645 codegen_output_type(self, v);
1646 v->context = ast_ctx(self);
1649 /* A constant local... hmmm...
1650 * I suppose the IR will have to deal with this
1652 if (self->hasvalue) {
1653 switch (self->expression.vtype)
1656 if (!ir_value_set_float(v, self->constval.vfloat))
1660 if (!ir_value_set_vector(v, self->constval.vvec))
1664 if (!ir_value_set_string(v, self->constval.vstring))
1668 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1673 /* link us to the ir_value */
1677 if (!ast_generate_accessors(self, func->owner))
1681 error: /* clean up */
1686 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1689 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1690 if (!self->setter || !self->getter)
1692 for (i = 0; i < self->expression.count; ++i) {
1693 if (!self->ir_values) {
1694 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1697 if (!self->ir_values[i]) {
1698 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1701 if (self->ir_values[i]->life) {
1702 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1707 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1709 if (!ast_global_codegen (self->setter, ir, false) ||
1710 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1711 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1713 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1714 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1719 if (!ast_global_codegen (self->getter, ir, false) ||
1720 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1721 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1723 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1724 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1728 for (i = 0; i < self->expression.count; ++i) {
1729 vec_free(self->ir_values[i]->life);
1731 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1735 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1740 ast_expression_codegen *cgen;
1745 irf = self->ir_func;
1747 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1751 /* fill the parameter list */
1752 ec = &self->vtype->expression;
1753 for (i = 0; i < vec_size(ec->params); ++i)
1755 if (ec->params[i]->expression.vtype == TYPE_FIELD)
1756 vec_push(irf->params, ec->params[i]->expression.next->vtype);
1758 vec_push(irf->params, ec->params[i]->expression.vtype);
1759 if (!self->builtin) {
1760 if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1765 if (self->varargs) {
1766 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1768 irf->max_varargs = self->varargs->expression.count;
1771 if (self->builtin) {
1772 irf->builtin = self->builtin;
1776 /* have a local return value variable? */
1777 if (self->return_value) {
1778 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1782 if (!vec_size(self->blocks)) {
1783 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1787 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1788 if (!self->curblock) {
1789 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1797 if (!ast_local_codegen(self->argc, self->ir_func, true))
1799 cgen = self->argc->expression.codegen;
1800 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1802 cgen = self->fixedparams->expression.codegen;
1803 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1805 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1806 ast_function_label(self, "va_count"), INSTR_SUB_F,
1807 ir_builder_get_va_count(ir), fixed);
1810 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1817 for (i = 0; i < vec_size(self->blocks); ++i) {
1818 cgen = self->blocks[i]->expression.codegen;
1819 if (!(*cgen)((ast_expression*)self->blocks[i], self, false, &dummy))
1823 /* TODO: check return types */
1824 if (!self->curblock->final)
1826 if (!self->vtype->expression.next ||
1827 self->vtype->expression.next->vtype == TYPE_VOID)
1829 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1831 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1833 if (self->return_value) {
1834 cgen = self->return_value->expression.codegen;
1835 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1837 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1839 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1840 "control reaches end of non-void function (`%s`) via %s",
1841 self->name, self->curblock->label))
1845 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1851 /* Note, you will not see ast_block_codegen generate ir_blocks.
1852 * To the AST and the IR, blocks are 2 different things.
1853 * In the AST it represents a block of code, usually enclosed in
1854 * curly braces {...}.
1855 * While in the IR it represents a block in terms of control-flow.
1857 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1861 /* We don't use this
1862 * Note: an ast-representation using the comma-operator
1863 * of the form: (a, b, c) = x should not assign to c...
1866 compile_error(ast_ctx(self), "not an l-value (code-block)");
1870 if (self->expression.outr) {
1871 *out = self->expression.outr;
1875 /* output is NULL at first, we'll have each expression
1876 * assign to out output, thus, a comma-operator represention
1877 * using an ast_block will return the last generated value,
1878 * so: (b, c) + a executed both b and c, and returns c,
1879 * which is then added to a.
1883 /* generate locals */
1884 for (i = 0; i < vec_size(self->locals); ++i)
1886 if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1887 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1888 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1893 for (i = 0; i < vec_size(self->exprs); ++i)
1895 ast_expression_codegen *gen;
1896 if (func->curblock->final && !ast_istype(self->exprs[i], ast_label)) {
1897 if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
1901 gen = self->exprs[i]->codegen;
1902 if (!(*gen)(self->exprs[i], func, false, out))
1906 self->expression.outr = *out;
1911 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1913 ast_expression_codegen *cgen;
1914 ir_value *left = NULL;
1915 ir_value *right = NULL;
1919 ast_array_index *ai = NULL;
1921 if (lvalue && self->expression.outl) {
1922 *out = self->expression.outl;
1926 if (!lvalue && self->expression.outr) {
1927 *out = self->expression.outr;
1931 if (ast_istype(self->dest, ast_array_index))
1934 ai = (ast_array_index*)self->dest;
1935 idx = (ast_value*)ai->index;
1937 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
1942 /* we need to call the setter */
1943 ir_value *iridx, *funval;
1947 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1951 arr = (ast_value*)ai->array;
1952 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1953 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
1957 cgen = idx->expression.codegen;
1958 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1961 cgen = arr->setter->expression.codegen;
1962 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
1965 cgen = self->source->codegen;
1966 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1969 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
1972 ir_call_param(call, iridx);
1973 ir_call_param(call, right);
1974 self->expression.outr = right;
1980 cgen = self->dest->codegen;
1982 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
1984 self->expression.outl = left;
1986 cgen = self->source->codegen;
1988 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1991 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
1993 self->expression.outr = right;
1996 /* Theoretically, an assinment returns its left side as an
1997 * lvalue, if we don't need an lvalue though, we return
1998 * the right side as an rvalue, otherwise we have to
1999 * somehow know whether or not we need to dereference the pointer
2000 * on the left side - that is: OP_LOAD if it was an address.
2001 * Also: in original QC we cannot OP_LOADP *anyway*.
2003 *out = (lvalue ? left : right);
2008 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2010 ast_expression_codegen *cgen;
2011 ir_value *left, *right;
2013 /* A binary operation cannot yield an l-value */
2015 compile_error(ast_ctx(self), "not an l-value (binop)");
2019 if (self->expression.outr) {
2020 *out = self->expression.outr;
2024 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2025 (self->op == INSTR_AND || self->op == INSTR_OR))
2027 /* short circuit evaluation */
2028 ir_block *other, *merge;
2029 ir_block *from_left, *from_right;
2033 /* prepare end-block */
2034 merge_id = vec_size(func->ir_func->blocks);
2035 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2037 /* generate the left expression */
2038 cgen = self->left->codegen;
2039 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2041 /* remember the block */
2042 from_left = func->curblock;
2044 /* create a new block for the right expression */
2045 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2046 if (self->op == INSTR_AND) {
2047 /* on AND: left==true -> other */
2048 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2051 /* on OR: left==false -> other */
2052 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2055 /* use the likely flag */
2056 vec_last(func->curblock->instr)->likely = true;
2058 /* enter the right-expression's block */
2059 func->curblock = other;
2061 cgen = self->right->codegen;
2062 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2064 /* remember block */
2065 from_right = func->curblock;
2067 /* jump to the merge block */
2068 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2071 vec_remove(func->ir_func->blocks, merge_id, 1);
2072 vec_push(func->ir_func->blocks, merge);
2074 func->curblock = merge;
2075 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2076 ast_function_label(func, "sce_value"),
2077 self->expression.vtype);
2078 ir_phi_add(phi, from_left, left);
2079 ir_phi_add(phi, from_right, right);
2080 *out = ir_phi_value(phi);
2084 if (!OPTS_FLAG(PERL_LOGIC)) {
2086 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2087 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2088 ast_function_label(func, "sce_bool_v"),
2092 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2093 ast_function_label(func, "sce_bool"),
2098 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2099 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2100 ast_function_label(func, "sce_bool_s"),
2104 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2105 ast_function_label(func, "sce_bool"),
2111 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2112 ast_function_label(func, "sce_bool"),
2113 INSTR_AND, *out, *out);
2119 self->expression.outr = *out;
2120 codegen_output_type(self, *out);
2124 cgen = self->left->codegen;
2125 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2128 cgen = self->right->codegen;
2129 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2132 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2133 self->op, left, right);
2136 self->expression.outr = *out;
2137 codegen_output_type(self, *out);
2142 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2144 ast_expression_codegen *cgen;
2145 ir_value *leftl = NULL, *leftr, *right, *bin;
2149 ast_array_index *ai = NULL;
2150 ir_value *iridx = NULL;
2152 if (lvalue && self->expression.outl) {
2153 *out = self->expression.outl;
2157 if (!lvalue && self->expression.outr) {
2158 *out = self->expression.outr;
2162 if (ast_istype(self->dest, ast_array_index))
2165 ai = (ast_array_index*)self->dest;
2166 idx = (ast_value*)ai->index;
2168 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2172 /* for a binstore we need both an lvalue and an rvalue for the left side */
2173 /* rvalue of destination! */
2175 cgen = idx->expression.codegen;
2176 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2179 cgen = self->dest->codegen;
2180 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2183 /* source as rvalue only */
2184 cgen = self->source->codegen;
2185 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2188 /* now the binary */
2189 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2190 self->opbin, leftr, right);
2191 self->expression.outr = bin;
2195 /* we need to call the setter */
2200 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2204 arr = (ast_value*)ai->array;
2205 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2206 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2210 cgen = arr->setter->expression.codegen;
2211 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2214 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2217 ir_call_param(call, iridx);
2218 ir_call_param(call, bin);
2219 self->expression.outr = bin;
2221 /* now store them */
2222 cgen = self->dest->codegen;
2223 /* lvalue of destination */
2224 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2226 self->expression.outl = leftl;
2228 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2230 self->expression.outr = bin;
2233 /* Theoretically, an assinment returns its left side as an
2234 * lvalue, if we don't need an lvalue though, we return
2235 * the right side as an rvalue, otherwise we have to
2236 * somehow know whether or not we need to dereference the pointer
2237 * on the left side - that is: OP_LOAD if it was an address.
2238 * Also: in original QC we cannot OP_LOADP *anyway*.
2240 *out = (lvalue ? leftl : bin);
2245 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2247 ast_expression_codegen *cgen;
2250 /* An unary operation cannot yield an l-value */
2252 compile_error(ast_ctx(self), "not an l-value (binop)");
2256 if (self->expression.outr) {
2257 *out = self->expression.outr;
2261 cgen = self->operand->codegen;
2263 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2266 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2270 self->expression.outr = *out;
2275 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2277 ast_expression_codegen *cgen;
2282 /* In the context of a return operation, we don't actually return
2286 compile_error(ast_ctx(self), "return-expression is not an l-value");
2290 if (self->expression.outr) {
2291 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2294 self->expression.outr = (ir_value*)1;
2296 if (self->operand) {
2297 cgen = self->operand->codegen;
2299 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2302 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2305 if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2312 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2314 ast_expression_codegen *cgen;
2315 ir_value *ent, *field;
2317 /* This function needs to take the 'lvalue' flag into account!
2318 * As lvalue we provide a field-pointer, as rvalue we provide the
2322 if (lvalue && self->expression.outl) {
2323 *out = self->expression.outl;
2327 if (!lvalue && self->expression.outr) {
2328 *out = self->expression.outr;
2332 cgen = self->entity->codegen;
2333 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2336 cgen = self->field->codegen;
2337 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2342 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2345 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2346 ent, field, self->expression.vtype);
2347 /* Done AFTER error checking:
2348 codegen_output_type(self, *out);
2352 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2353 (lvalue ? "ADDRESS" : "FIELD"),
2354 type_name[self->expression.vtype]);
2358 codegen_output_type(self, *out);
2361 self->expression.outl = *out;
2363 self->expression.outr = *out;
2365 /* Hm that should be it... */
2369 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2371 ast_expression_codegen *cgen;
2374 /* in QC this is always an lvalue */
2375 if (lvalue && self->rvalue) {
2376 compile_error(ast_ctx(self), "not an l-value (member access)");
2379 if (self->expression.outl) {
2380 *out = self->expression.outl;
2384 cgen = self->owner->codegen;
2385 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2388 if (vec->vtype != TYPE_VECTOR &&
2389 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2394 *out = ir_value_vector_member(vec, self->field);
2395 self->expression.outl = *out;
2397 return (*out != NULL);
2400 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2405 if (!lvalue && self->expression.outr) {
2406 *out = self->expression.outr;
2409 if (lvalue && self->expression.outl) {
2410 *out = self->expression.outl;
2414 if (!ast_istype(self->array, ast_value)) {
2415 compile_error(ast_ctx(self), "array indexing this way is not supported");
2416 /* note this would actually be pointer indexing because the left side is
2417 * not an actual array but (hopefully) an indexable expression.
2418 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2419 * support this path will be filled.
2424 arr = (ast_value*)self->array;
2425 idx = (ast_value*)self->index;
2427 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2428 /* Time to use accessor functions */
2429 ast_expression_codegen *cgen;
2430 ir_value *iridx, *funval;
2434 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2439 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2443 cgen = self->index->codegen;
2444 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2447 cgen = arr->getter->expression.codegen;
2448 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2451 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2454 ir_call_param(call, iridx);
2456 *out = ir_call_value(call);
2457 self->expression.outr = *out;
2458 (*out)->vtype = self->expression.vtype;
2459 codegen_output_type(self, *out);
2463 if (idx->expression.vtype == TYPE_FLOAT) {
2464 unsigned int arridx = idx->constval.vfloat;
2465 if (arridx >= self->array->count)
2467 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2470 *out = arr->ir_values[arridx];
2472 else if (idx->expression.vtype == TYPE_INTEGER) {
2473 unsigned int arridx = idx->constval.vint;
2474 if (arridx >= self->array->count)
2476 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2479 *out = arr->ir_values[arridx];
2482 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2485 (*out)->vtype = self->expression.vtype;
2486 codegen_output_type(self, *out);
2490 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2494 compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2499 compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2503 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2505 ast_expression_codegen *cgen;
2513 ir_block *ontrue_endblock = NULL;
2514 ir_block *onfalse_endblock = NULL;
2515 ir_block *merge = NULL;
2517 /* We don't output any value, thus also don't care about r/lvalue */
2521 if (self->expression.outr) {
2522 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2525 self->expression.outr = (ir_value*)1;
2527 /* generate the condition */
2528 cgen = self->cond->codegen;
2529 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2531 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2532 cond = func->curblock;
2534 /* eliminate branches if value is constant */
2535 if (condval->vtype == TYPE_FLOAT && condval->hasvalue && condval->cvq == CV_CONST) {
2536 /* don't generate if statements */
2537 if (condval->constval.vfloat == 1.0f && self->on_true) {
2538 if (!(ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"))))
2541 if (!(*(cgen = self->on_true->codegen))((ast_expression*)(self->on_true), func, false, &dummy))
2543 if (!ir_block_create_jump(func->curblock, ast_ctx(self), ontrue))
2545 func->curblock = ontrue;
2547 } else if (condval->constval.vfloat == 0.0f && self->on_false) {
2548 if (!(onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"))))
2551 if (!(*(cgen = self->on_false->codegen))((ast_expression*)(self->on_false), func, false, &dummy))
2553 if (!ir_block_create_jump(func->curblock, ast_ctx(self), onfalse))
2555 func->curblock = onfalse;
2561 if (self->on_true) {
2562 /* create on-true block */
2563 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2567 /* enter the block */
2568 func->curblock = ontrue;
2571 cgen = self->on_true->codegen;
2572 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2575 /* we now need to work from the current endpoint */
2576 ontrue_endblock = func->curblock;
2581 if (self->on_false) {
2582 /* create on-false block */
2583 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2587 /* enter the block */
2588 func->curblock = onfalse;
2591 cgen = self->on_false->codegen;
2592 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2595 /* we now need to work from the current endpoint */
2596 onfalse_endblock = func->curblock;
2600 /* Merge block were they all merge in to */
2601 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2603 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2606 /* add jumps ot the merge block */
2607 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2609 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2612 /* Now enter the merge block */
2613 func->curblock = merge;
2616 /* we create the if here, that way all blocks are ordered :)
2618 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2619 (ontrue ? ontrue : merge),
2620 (onfalse ? onfalse : merge)))
2628 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2630 ast_expression_codegen *cgen;
2633 ir_value *trueval, *falseval;
2636 ir_block *cond = func->curblock;
2637 ir_block *cond_out = NULL;
2638 ir_block *ontrue, *ontrue_out = NULL;
2639 ir_block *onfalse, *onfalse_out = NULL;
2642 /* Ternary can never create an lvalue... */
2646 /* In theory it shouldn't be possible to pass through a node twice, but
2647 * in case we add any kind of optimization pass for the AST itself, it
2648 * may still happen, thus we remember a created ir_value and simply return one
2649 * if it already exists.
2651 if (self->expression.outr) {
2652 *out = self->expression.outr;
2656 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2658 /* generate the condition */
2659 func->curblock = cond;
2660 cgen = self->cond->codegen;
2661 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2663 cond_out = func->curblock;
2665 /* create on-true block */
2666 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2671 /* enter the block */
2672 func->curblock = ontrue;
2675 cgen = self->on_true->codegen;
2676 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2679 ontrue_out = func->curblock;
2682 /* create on-false block */
2683 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2688 /* enter the block */
2689 func->curblock = onfalse;
2692 cgen = self->on_false->codegen;
2693 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2696 onfalse_out = func->curblock;
2699 /* create merge block */
2700 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2703 /* jump to merge block */
2704 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2706 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2709 /* create if instruction */
2710 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2713 /* Now enter the merge block */
2714 func->curblock = merge;
2716 /* Here, now, we need a PHI node
2717 * but first some sanity checking...
2719 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2720 /* error("ternary with different types on the two sides"); */
2721 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2726 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2728 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2731 ir_phi_add(phi, ontrue_out, trueval);
2732 ir_phi_add(phi, onfalse_out, falseval);
2734 self->expression.outr = ir_phi_value(phi);
2735 *out = self->expression.outr;
2737 codegen_output_type(self, *out);
2742 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2744 ast_expression_codegen *cgen;
2746 ir_value *dummy = NULL;
2747 ir_value *precond = NULL;
2748 ir_value *postcond = NULL;
2750 /* Since we insert some jumps "late" so we have blocks
2751 * ordered "nicely", we need to keep track of the actual end-blocks
2752 * of expressions to add the jumps to.
2754 ir_block *bbody = NULL, *end_bbody = NULL;
2755 ir_block *bprecond = NULL, *end_bprecond = NULL;
2756 ir_block *bpostcond = NULL, *end_bpostcond = NULL;
2757 ir_block *bincrement = NULL, *end_bincrement = NULL;
2758 ir_block *bout = NULL, *bin = NULL;
2760 /* let's at least move the outgoing block to the end */
2763 /* 'break' and 'continue' need to be able to find the right blocks */
2764 ir_block *bcontinue = NULL;
2765 ir_block *bbreak = NULL;
2767 ir_block *tmpblock = NULL;
2772 if (self->expression.outr) {
2773 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2776 self->expression.outr = (ir_value*)1;
2779 * Should we ever need some kind of block ordering, better make this function
2780 * move blocks around than write a block ordering algorithm later... after all
2781 * the ast and ir should work together, not against each other.
2784 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2785 * anyway if for example it contains a ternary.
2789 cgen = self->initexpr->codegen;
2790 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2794 /* Store the block from which we enter this chaos */
2795 bin = func->curblock;
2797 /* The pre-loop condition needs its own block since we
2798 * need to be able to jump to the start of that expression.
2802 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2806 /* the pre-loop-condition the least important place to 'continue' at */
2807 bcontinue = bprecond;
2810 func->curblock = bprecond;
2813 cgen = self->precond->codegen;
2814 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2817 end_bprecond = func->curblock;
2819 bprecond = end_bprecond = NULL;
2822 /* Now the next blocks won't be ordered nicely, but we need to
2823 * generate them this early for 'break' and 'continue'.
2825 if (self->increment) {
2826 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2829 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2831 bincrement = end_bincrement = NULL;
2834 if (self->postcond) {
2835 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2838 bcontinue = bpostcond; /* postcond comes before the increment */
2840 bpostcond = end_bpostcond = NULL;
2843 bout_id = vec_size(func->ir_func->blocks);
2844 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2849 /* The loop body... */
2850 /* if (self->body) */
2852 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2857 func->curblock = bbody;
2859 vec_push(func->breakblocks, bbreak);
2861 vec_push(func->continueblocks, bcontinue);
2863 vec_push(func->continueblocks, bbody);
2867 cgen = self->body->codegen;
2868 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2872 end_bbody = func->curblock;
2873 vec_pop(func->breakblocks);
2874 vec_pop(func->continueblocks);
2877 /* post-loop-condition */
2881 func->curblock = bpostcond;
2884 cgen = self->postcond->codegen;
2885 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2888 end_bpostcond = func->curblock;
2891 /* The incrementor */
2892 if (self->increment)
2895 func->curblock = bincrement;
2898 cgen = self->increment->codegen;
2899 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2902 end_bincrement = func->curblock;
2905 /* In any case now, we continue from the outgoing block */
2906 func->curblock = bout;
2908 /* Now all blocks are in place */
2909 /* From 'bin' we jump to whatever comes first */
2910 if (bprecond) tmpblock = bprecond;
2911 else tmpblock = bbody; /* can never be null */
2914 else if (bpostcond) tmpblock = bpostcond;
2915 else tmpblock = bout;
2918 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2924 ir_block *ontrue, *onfalse;
2925 ontrue = bbody; /* can never be null */
2927 /* all of this is dead code
2928 else if (bincrement) ontrue = bincrement;
2929 else ontrue = bpostcond;
2933 if (self->pre_not) {
2938 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
2945 if (bincrement) tmpblock = bincrement;
2946 else if (bpostcond) tmpblock = bpostcond;
2947 else if (bprecond) tmpblock = bprecond;
2948 else tmpblock = bbody;
2949 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
2953 /* from increment */
2956 if (bpostcond) tmpblock = bpostcond;
2957 else if (bprecond) tmpblock = bprecond;
2958 else if (bbody) tmpblock = bbody;
2959 else tmpblock = bout;
2960 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
2967 ir_block *ontrue, *onfalse;
2968 if (bprecond) ontrue = bprecond;
2969 else ontrue = bbody; /* can never be null */
2971 /* all of this is dead code
2972 else if (bincrement) ontrue = bincrement;
2973 else ontrue = bpostcond;
2977 if (self->post_not) {
2982 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
2986 /* Move 'bout' to the end */
2987 vec_remove(func->ir_func->blocks, bout_id, 1);
2988 vec_push(func->ir_func->blocks, bout);
2993 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
3000 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3004 if (self->expression.outr) {
3005 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3008 self->expression.outr = (ir_value*)1;
3010 if (self->is_continue)
3011 target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
3013 target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
3016 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3020 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3025 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3027 ast_expression_codegen *cgen;
3029 ast_switch_case *def_case = NULL;
3030 ir_block *def_bfall = NULL;
3031 ir_block *def_bfall_to = NULL;
3032 bool set_def_bfall_to = false;
3034 ir_value *dummy = NULL;
3035 ir_value *irop = NULL;
3036 ir_block *bout = NULL;
3037 ir_block *bfall = NULL;
3045 compile_error(ast_ctx(self), "switch expression is not an l-value");
3049 if (self->expression.outr) {
3050 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3053 self->expression.outr = (ir_value*)1;
3058 cgen = self->operand->codegen;
3059 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3062 if (!vec_size(self->cases))
3065 cmpinstr = type_eq_instr[irop->vtype];
3066 if (cmpinstr >= VINSTR_END) {
3067 ast_type_to_string(self->operand, typestr, sizeof(typestr));
3068 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3072 bout_id = vec_size(func->ir_func->blocks);
3073 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3077 /* setup the break block */
3078 vec_push(func->breakblocks, bout);
3080 /* Now create all cases */
3081 for (c = 0; c < vec_size(self->cases); ++c) {
3082 ir_value *cond, *val;
3083 ir_block *bcase, *bnot;
3086 ast_switch_case *swcase = &self->cases[c];
3088 if (swcase->value) {
3089 /* A regular case */
3090 /* generate the condition operand */
3091 cgen = swcase->value->codegen;
3092 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3094 /* generate the condition */
3095 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3099 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3100 bnot_id = vec_size(func->ir_func->blocks);
3101 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3102 if (!bcase || !bnot)
3104 if (set_def_bfall_to) {
3105 set_def_bfall_to = false;
3106 def_bfall_to = bcase;
3108 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3111 /* Make the previous case-end fall through */
3112 if (bfall && !bfall->final) {
3113 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3117 /* enter the case */
3118 func->curblock = bcase;
3119 cgen = swcase->code->codegen;
3120 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3123 /* remember this block to fall through from */
3124 bfall = func->curblock;
3126 /* enter the else and move it down */
3127 func->curblock = bnot;
3128 vec_remove(func->ir_func->blocks, bnot_id, 1);
3129 vec_push(func->ir_func->blocks, bnot);
3131 /* The default case */
3132 /* Remember where to fall through from: */
3135 /* remember which case it was */
3137 /* And the next case will be remembered */
3138 set_def_bfall_to = true;
3142 /* Jump from the last bnot to bout */
3143 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3145 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3150 /* If there was a default case, put it down here */
3154 /* No need to create an extra block */
3155 bcase = func->curblock;
3157 /* Insert the fallthrough jump */
3158 if (def_bfall && !def_bfall->final) {
3159 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3163 /* Now generate the default code */
3164 cgen = def_case->code->codegen;
3165 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3168 /* see if we need to fall through */
3169 if (def_bfall_to && !func->curblock->final)
3171 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3176 /* Jump from the last bnot to bout */
3177 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3179 /* enter the outgoing block */
3180 func->curblock = bout;
3182 /* restore the break block */
3183 vec_pop(func->breakblocks);
3185 /* Move 'bout' to the end, it's nicer */
3186 vec_remove(func->ir_func->blocks, bout_id, 1);
3187 vec_push(func->ir_func->blocks, bout);
3192 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3197 if (self->undefined) {
3198 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3204 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3208 /* simply create a new block and jump to it */
3209 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3210 if (!self->irblock) {
3211 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3214 if (!func->curblock->final) {
3215 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3219 /* enter the new block */
3220 func->curblock = self->irblock;
3222 /* Generate all the leftover gotos */
3223 for (i = 0; i < vec_size(self->gotos); ++i) {
3224 if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3231 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3235 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3239 if (self->target->irblock) {
3240 if (self->irblock_from) {
3241 /* we already tried once, this is the callback */
3242 self->irblock_from->final = false;
3243 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3244 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3250 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3251 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3258 /* the target has not yet been created...
3259 * close this block in a sneaky way:
3261 func->curblock->final = true;
3262 self->irblock_from = func->curblock;
3263 ast_label_register_goto(self->target, self);
3269 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3271 ast_expression_codegen *cgen;
3273 ir_instr *callinstr;
3276 ir_value *funval = NULL;
3278 /* return values are never lvalues */
3280 compile_error(ast_ctx(self), "not an l-value (function call)");
3284 if (self->expression.outr) {
3285 *out = self->expression.outr;
3289 cgen = self->func->codegen;
3290 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3298 for (i = 0; i < vec_size(self->params); ++i)
3301 ast_expression *expr = self->params[i];
3303 cgen = expr->codegen;
3304 if (!(*cgen)(expr, func, false, ¶m))
3308 vec_push(params, param);
3311 /* varargs counter */
3312 if (self->va_count) {
3314 ir_builder *builder = func->curblock->owner->owner;
3315 cgen = self->va_count->codegen;
3316 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3318 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3319 ir_builder_get_va_count(builder), va_count))
3325 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3326 ast_function_label(func, "call"),
3327 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3331 for (i = 0; i < vec_size(params); ++i) {
3332 ir_call_param(callinstr, params[i]);
3335 *out = ir_call_value(callinstr);
3336 self->expression.outr = *out;
3338 codegen_output_type(self, *out);