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
32 #define ast_instantiate(T, ctx, destroyfn) \
33 T* self = (T*)mem_a(sizeof(T)); \
37 ast_node_init((ast_node*)self, ctx, TYPE_##T); \
38 ( (ast_node*)self )->destroy = (ast_node_delete*)destroyfn
41 * forward declarations, these need not be in ast.h for obvious
44 static bool ast_member_codegen(ast_member*, ast_function*, bool lvalue, ir_value**);
45 static void ast_array_index_delete(ast_array_index*);
46 static bool ast_array_index_codegen(ast_array_index*, ast_function*, bool lvalue, ir_value**);
47 static void ast_argpipe_delete(ast_argpipe*);
48 static bool ast_argpipe_codegen(ast_argpipe*, ast_function*, bool lvalue, ir_value**);
49 static void ast_store_delete(ast_store*);
50 static bool ast_store_codegen(ast_store*, ast_function*, bool lvalue, ir_value**);
51 static void ast_ifthen_delete(ast_ifthen*);
52 static bool ast_ifthen_codegen(ast_ifthen*, ast_function*, bool lvalue, ir_value**);
53 static void ast_ternary_delete(ast_ternary*);
54 static bool ast_ternary_codegen(ast_ternary*, ast_function*, bool lvalue, ir_value**);
55 static void ast_loop_delete(ast_loop*);
56 static bool ast_loop_codegen(ast_loop*, ast_function*, bool lvalue, ir_value**);
57 static void ast_breakcont_delete(ast_breakcont*);
58 static bool ast_breakcont_codegen(ast_breakcont*, ast_function*, bool lvalue, ir_value**);
59 static void ast_switch_delete(ast_switch*);
60 static bool ast_switch_codegen(ast_switch*, ast_function*, bool lvalue, ir_value**);
61 static void ast_label_delete(ast_label*);
62 static void ast_label_register_goto(ast_label*, ast_goto*);
63 static bool ast_label_codegen(ast_label*, ast_function*, bool lvalue, ir_value**);
64 static bool ast_goto_codegen(ast_goto*, ast_function*, bool lvalue, ir_value**);
65 static void ast_goto_delete(ast_goto*);
66 static void ast_call_delete(ast_call*);
67 static bool ast_call_codegen(ast_call*, ast_function*, bool lvalue, ir_value**);
68 static bool ast_block_codegen(ast_block*, ast_function*, bool lvalue, ir_value**);
69 static void ast_unary_delete(ast_unary*);
70 static bool ast_unary_codegen(ast_unary*, ast_function*, bool lvalue, ir_value**);
71 static void ast_entfield_delete(ast_entfield*);
72 static bool ast_entfield_codegen(ast_entfield*, ast_function*, bool lvalue, ir_value**);
73 static void ast_return_delete(ast_return*);
74 static bool ast_return_codegen(ast_return*, ast_function*, bool lvalue, ir_value**);
75 static void ast_binstore_delete(ast_binstore*);
76 static bool ast_binstore_codegen(ast_binstore*, ast_function*, bool lvalue, ir_value**);
77 static void ast_binary_delete(ast_binary*);
78 static bool ast_binary_codegen(ast_binary*, ast_function*, bool lvalue, ir_value**);
80 /* It must not be possible to get here. */
81 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
84 con_err("ast node missing destroy()\n");
88 /* Initialize main ast node aprts */
89 static void ast_node_init(ast_node *self, lex_ctx_t ctx, int nodetype)
92 self->destroy = &_ast_node_destroy;
94 self->nodetype = nodetype;
95 self->side_effects = false;
98 /* weight and side effects */
99 static void _ast_propagate_effects(ast_node *self, ast_node *other)
101 if (ast_side_effects(other))
102 ast_side_effects(self) = true;
104 #define ast_propagate_effects(s,o) _ast_propagate_effects(((ast_node*)(s)), ((ast_node*)(o)))
106 /* General expression initialization */
107 static void ast_expression_init(ast_expression *self,
108 ast_expression_codegen *codegen)
110 self->codegen = codegen;
111 self->vtype = TYPE_VOID;
118 self->varparam = NULL;
121 static void ast_expression_delete(ast_expression *self)
125 ast_delete(self->next);
126 for (i = 0; i < vec_size(self->params); ++i) {
127 ast_delete(self->params[i]);
129 vec_free(self->params);
131 ast_delete(self->varparam);
134 static void ast_expression_delete_full(ast_expression *self)
136 ast_expression_delete(self);
140 ast_value* ast_value_copy(const ast_value *self)
143 const ast_expression *fromex;
144 ast_expression *selfex;
145 ast_value *cp = ast_value_new(self->expression.node.context, self->name, self->expression.vtype);
146 if (self->expression.next) {
147 cp->expression.next = ast_type_copy(self->expression.node.context, self->expression.next);
149 fromex = &self->expression;
150 selfex = &cp->expression;
151 selfex->count = fromex->count;
152 selfex->flags = fromex->flags;
153 for (i = 0; i < vec_size(fromex->params); ++i) {
154 ast_value *v = ast_value_copy(fromex->params[i]);
155 vec_push(selfex->params, v);
160 void ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
163 const ast_expression *fromex;
164 ast_expression *selfex;
165 self->vtype = other->vtype;
167 self->next = (ast_expression*)ast_type_copy(ast_ctx(self), other->next);
171 selfex->count = fromex->count;
172 selfex->flags = fromex->flags;
173 for (i = 0; i < vec_size(fromex->params); ++i) {
174 ast_value *v = ast_value_copy(fromex->params[i]);
175 vec_push(selfex->params, v);
179 static ast_expression* ast_shallow_type(lex_ctx_t ctx, int vtype)
181 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
182 ast_expression_init(self, NULL);
183 self->codegen = NULL;
189 ast_expression* ast_type_copy(lex_ctx_t ctx, const ast_expression *ex)
192 const ast_expression *fromex;
193 ast_expression *selfex;
199 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
200 ast_expression_init(self, NULL);
205 /* This may never be codegen()d */
206 selfex->codegen = NULL;
208 selfex->vtype = fromex->vtype;
210 selfex->next = ast_type_copy(ctx, fromex->next);
214 selfex->count = fromex->count;
215 selfex->flags = fromex->flags;
216 for (i = 0; i < vec_size(fromex->params); ++i) {
217 ast_value *v = ast_value_copy(fromex->params[i]);
218 vec_push(selfex->params, v);
225 bool ast_compare_type(ast_expression *a, ast_expression *b)
227 if (a->vtype == TYPE_NIL ||
228 b->vtype == TYPE_NIL)
230 if (a->vtype != b->vtype)
232 if (!a->next != !b->next)
234 if (vec_size(a->params) != vec_size(b->params))
236 if ((a->flags & AST_FLAG_TYPE_MASK) !=
237 (b->flags & AST_FLAG_TYPE_MASK) )
241 if (vec_size(a->params)) {
243 for (i = 0; i < vec_size(a->params); ++i) {
244 if (!ast_compare_type((ast_expression*)a->params[i],
245 (ast_expression*)b->params[i]))
250 return ast_compare_type(a->next, b->next);
254 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
261 if (pos + 6 >= bufsize)
263 platform_strncpy(buf + pos, "(null)", 6);
267 if (pos + 1 >= bufsize)
272 platform_strncpy(buf + pos, "(variant)", 9);
277 return ast_type_to_string_impl(e->next, buf, bufsize, pos);
280 if (pos + 3 >= bufsize)
284 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
285 if (pos + 1 >= bufsize)
291 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
292 if (pos + 2 >= bufsize)
294 if (!vec_size(e->params)) {
300 pos = ast_type_to_string_impl((ast_expression*)(e->params[0]), buf, bufsize, pos);
301 for (i = 1; i < vec_size(e->params); ++i) {
302 if (pos + 2 >= bufsize)
306 pos = ast_type_to_string_impl((ast_expression*)(e->params[i]), buf, bufsize, pos);
308 if (pos + 1 >= bufsize)
314 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
315 if (pos + 1 >= bufsize)
318 pos += platform_snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->count);
319 if (pos + 1 >= bufsize)
325 typestr = type_name[e->vtype];
326 typelen = strlen(typestr);
327 if (pos + typelen >= bufsize)
329 platform_strncpy(buf + pos, typestr, typelen);
330 return pos + typelen;
334 buf[bufsize-3] = '.';
335 buf[bufsize-2] = '.';
336 buf[bufsize-1] = '.';
340 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
342 size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
346 static bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out);
347 ast_value* ast_value_new(lex_ctx_t ctx, const char *name, int t)
349 ast_instantiate(ast_value, ctx, ast_value_delete);
350 ast_expression_init((ast_expression*)self,
351 (ast_expression_codegen*)&ast_value_codegen);
352 self->expression.node.keep = true; /* keep */
354 self->name = name ? util_strdup(name) : NULL;
355 self->expression.vtype = t;
356 self->expression.next = NULL;
357 self->isfield = false;
359 self->hasvalue = false;
362 memset(&self->constval, 0, sizeof(self->constval));
363 self->initlist = NULL;
366 self->ir_values = NULL;
367 self->ir_value_count = 0;
373 self->argcounter = NULL;
374 self->intrinsic = false;
379 void ast_value_delete(ast_value* self)
382 mem_d((void*)self->name);
383 if (self->argcounter)
384 mem_d((void*)self->argcounter);
385 if (self->hasvalue) {
386 switch (self->expression.vtype)
389 mem_d((void*)self->constval.vstring);
392 /* unlink us from the function node */
393 self->constval.vfunc->vtype = NULL;
395 /* NOTE: delete function? currently collected in
396 * the parser structure
403 mem_d(self->ir_values);
408 if (self->initlist) {
409 if (self->expression.next->vtype == TYPE_STRING) {
410 /* strings are allocated, free them */
411 size_t i, len = vec_size(self->initlist);
412 /* in theory, len should be expression.count
413 * but let's not take any chances */
414 for (i = 0; i < len; ++i) {
415 if (self->initlist[i].vstring)
416 mem_d(self->initlist[i].vstring);
419 vec_free(self->initlist);
422 ast_expression_delete((ast_expression*)self);
426 void ast_value_params_add(ast_value *self, ast_value *p)
428 vec_push(self->expression.params, p);
431 bool ast_value_set_name(ast_value *self, const char *name)
434 mem_d((void*)self->name);
435 self->name = util_strdup(name);
439 ast_binary* ast_binary_new(lex_ctx_t ctx, int op,
440 ast_expression* left, ast_expression* right)
443 ast_instantiate(ast_binary, ctx, ast_binary_delete);
444 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
449 self->right_first = false;
451 ast_propagate_effects(self, left);
452 ast_propagate_effects(self, right);
454 if (OPTS_OPTIMIZATION(OPTIM_PEEPHOLE) && (fold = (ast_binary*)fold_superfluous(left, right, op))) {
455 ast_binary_delete(self);
459 if (op >= INSTR_EQ_F && op <= INSTR_GT)
460 self->expression.vtype = TYPE_FLOAT;
461 else if (op == INSTR_AND || op == INSTR_OR) {
462 if (OPTS_FLAG(PERL_LOGIC))
463 ast_type_adopt(self, right);
465 self->expression.vtype = TYPE_FLOAT;
467 else if (op == INSTR_BITAND || op == INSTR_BITOR)
468 self->expression.vtype = TYPE_FLOAT;
469 else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
470 self->expression.vtype = TYPE_VECTOR;
471 else if (op == INSTR_MUL_V)
472 self->expression.vtype = TYPE_FLOAT;
474 self->expression.vtype = left->vtype;
477 self->refs = AST_REF_ALL;
482 void ast_binary_delete(ast_binary *self)
484 if (self->refs & AST_REF_LEFT) ast_unref(self->left);
485 if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
487 ast_expression_delete((ast_expression*)self);
491 ast_binstore* ast_binstore_new(lex_ctx_t ctx, int storop, int op,
492 ast_expression* left, ast_expression* right)
494 ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
495 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
497 ast_side_effects(self) = true;
499 self->opstore = storop;
502 self->source = right;
504 self->keep_dest = false;
506 ast_type_adopt(self, left);
510 void ast_binstore_delete(ast_binstore *self)
512 if (!self->keep_dest)
513 ast_unref(self->dest);
514 ast_unref(self->source);
515 ast_expression_delete((ast_expression*)self);
519 ast_unary* ast_unary_new(lex_ctx_t ctx, int op,
520 ast_expression *expr)
522 ast_instantiate(ast_unary, ctx, ast_unary_delete);
523 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
526 self->operand = expr;
529 if (ast_istype(expr, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
530 ast_unary *prev = (ast_unary*)((ast_unary*)expr)->operand;
532 /* Handle for double negation */
533 if ((((ast_unary*)expr)->op == VINSTR_NEG_V && op == VINSTR_NEG_V) ||
534 (((ast_unary*)expr)->op == VINSTR_NEG_F && op == VINSTR_NEG_F)) {
535 prev = (ast_unary*)((ast_unary*)expr)->operand;
538 if (ast_istype(prev, ast_unary)) {
539 ast_expression_delete((ast_expression*)self);
541 ++opts_optimizationcount[OPTIM_PEEPHOLE];
546 ast_propagate_effects(self, expr);
548 if ((op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) || op == VINSTR_NEG_F) {
549 self->expression.vtype = TYPE_FLOAT;
550 } else if (op == VINSTR_NEG_V) {
551 self->expression.vtype = TYPE_VECTOR;
553 compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
559 void ast_unary_delete(ast_unary *self)
561 if (self->operand) ast_unref(self->operand);
562 ast_expression_delete((ast_expression*)self);
566 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
568 ast_instantiate(ast_return, ctx, ast_return_delete);
569 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
571 self->operand = expr;
574 ast_propagate_effects(self, expr);
579 void ast_return_delete(ast_return *self)
582 ast_unref(self->operand);
583 ast_expression_delete((ast_expression*)self);
587 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
589 if (field->vtype != TYPE_FIELD) {
590 compile_error(ctx, "ast_entfield_new with expression not of type field");
593 return ast_entfield_new_force(ctx, entity, field, field->next);
596 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
598 ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
602 /* Error: field has no type... */
606 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
608 self->entity = entity;
610 ast_propagate_effects(self, entity);
611 ast_propagate_effects(self, field);
613 ast_type_adopt(self, outtype);
617 void ast_entfield_delete(ast_entfield *self)
619 ast_unref(self->entity);
620 ast_unref(self->field);
621 ast_expression_delete((ast_expression*)self);
625 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
627 ast_instantiate(ast_member, ctx, ast_member_delete);
633 if (owner->vtype != TYPE_VECTOR &&
634 owner->vtype != TYPE_FIELD) {
635 compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
640 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
641 self->expression.node.keep = true; /* keep */
643 if (owner->vtype == TYPE_VECTOR) {
644 self->expression.vtype = TYPE_FLOAT;
645 self->expression.next = NULL;
647 self->expression.vtype = TYPE_FIELD;
648 self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
651 self->rvalue = false;
653 ast_propagate_effects(self, owner);
657 self->name = util_strdup(name);
664 void ast_member_delete(ast_member *self)
666 /* The owner is always an ast_value, which has .keep=true,
667 * also: ast_members are usually deleted after the owner, thus
668 * this will cause invalid access
669 ast_unref(self->owner);
670 * once we allow (expression).x to access a vector-member, we need
671 * to change this: preferably by creating an alternate ast node for this
672 * purpose that is not garbage-collected.
674 ast_expression_delete((ast_expression*)self);
679 bool ast_member_set_name(ast_member *self, const char *name)
682 mem_d((void*)self->name);
683 self->name = util_strdup(name);
687 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
689 ast_expression *outtype;
690 ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
692 outtype = array->next;
695 /* Error: field has no type... */
699 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
703 ast_propagate_effects(self, array);
704 ast_propagate_effects(self, index);
706 ast_type_adopt(self, outtype);
707 if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
708 if (self->expression.vtype != TYPE_ARRAY) {
709 compile_error(ast_ctx(self), "array_index node on type");
710 ast_array_index_delete(self);
713 self->array = outtype;
714 self->expression.vtype = TYPE_FIELD;
720 void ast_array_index_delete(ast_array_index *self)
723 ast_unref(self->array);
725 ast_unref(self->index);
726 ast_expression_delete((ast_expression*)self);
730 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
732 ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete);
733 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
735 self->expression.vtype = TYPE_NOEXPR;
739 void ast_argpipe_delete(ast_argpipe *self)
742 ast_unref(self->index);
743 ast_expression_delete((ast_expression*)self);
747 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
749 ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
750 if (!ontrue && !onfalse) {
751 /* because it is invalid */
755 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
758 self->on_true = ontrue;
759 self->on_false = onfalse;
760 ast_propagate_effects(self, cond);
762 ast_propagate_effects(self, ontrue);
764 ast_propagate_effects(self, onfalse);
769 void ast_ifthen_delete(ast_ifthen *self)
771 ast_unref(self->cond);
773 ast_unref(self->on_true);
775 ast_unref(self->on_false);
776 ast_expression_delete((ast_expression*)self);
780 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
782 ast_expression *exprtype = ontrue;
783 ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
784 /* This time NEITHER must be NULL */
785 if (!ontrue || !onfalse) {
789 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
792 self->on_true = ontrue;
793 self->on_false = onfalse;
794 ast_propagate_effects(self, cond);
795 ast_propagate_effects(self, ontrue);
796 ast_propagate_effects(self, onfalse);
798 if (ontrue->vtype == TYPE_NIL)
800 ast_type_adopt(self, exprtype);
805 void ast_ternary_delete(ast_ternary *self)
807 /* the if()s are only there because computed-gotos can set them
810 if (self->cond) ast_unref(self->cond);
811 if (self->on_true) ast_unref(self->on_true);
812 if (self->on_false) ast_unref(self->on_false);
813 ast_expression_delete((ast_expression*)self);
817 ast_loop* ast_loop_new(lex_ctx_t ctx,
818 ast_expression *initexpr,
819 ast_expression *precond, bool pre_not,
820 ast_expression *postcond, bool post_not,
821 ast_expression *increment,
822 ast_expression *body)
824 ast_instantiate(ast_loop, ctx, ast_loop_delete);
825 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
827 self->initexpr = initexpr;
828 self->precond = precond;
829 self->postcond = postcond;
830 self->increment = increment;
833 self->pre_not = pre_not;
834 self->post_not = post_not;
837 ast_propagate_effects(self, initexpr);
839 ast_propagate_effects(self, precond);
841 ast_propagate_effects(self, postcond);
843 ast_propagate_effects(self, increment);
845 ast_propagate_effects(self, body);
850 void ast_loop_delete(ast_loop *self)
853 ast_unref(self->initexpr);
855 ast_unref(self->precond);
857 ast_unref(self->postcond);
859 ast_unref(self->increment);
861 ast_unref(self->body);
862 ast_expression_delete((ast_expression*)self);
866 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
868 ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
869 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
871 self->is_continue = iscont;
872 self->levels = levels;
877 void ast_breakcont_delete(ast_breakcont *self)
879 ast_expression_delete((ast_expression*)self);
883 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
885 ast_instantiate(ast_switch, ctx, ast_switch_delete);
886 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
891 ast_propagate_effects(self, op);
896 void ast_switch_delete(ast_switch *self)
899 ast_unref(self->operand);
901 for (i = 0; i < vec_size(self->cases); ++i) {
902 if (self->cases[i].value)
903 ast_unref(self->cases[i].value);
904 ast_unref(self->cases[i].code);
906 vec_free(self->cases);
908 ast_expression_delete((ast_expression*)self);
912 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
914 ast_instantiate(ast_label, ctx, ast_label_delete);
915 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
917 self->expression.vtype = TYPE_NOEXPR;
919 self->name = util_strdup(name);
920 self->irblock = NULL;
922 self->undefined = undefined;
927 void ast_label_delete(ast_label *self)
929 mem_d((void*)self->name);
930 vec_free(self->gotos);
931 ast_expression_delete((ast_expression*)self);
935 static void ast_label_register_goto(ast_label *self, ast_goto *g)
937 vec_push(self->gotos, g);
940 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
942 ast_instantiate(ast_goto, ctx, ast_goto_delete);
943 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
945 self->name = util_strdup(name);
947 self->irblock_from = NULL;
952 void ast_goto_delete(ast_goto *self)
954 mem_d((void*)self->name);
955 ast_expression_delete((ast_expression*)self);
959 void ast_goto_set_label(ast_goto *self, ast_label *label)
961 self->target = label;
964 ast_call* ast_call_new(lex_ctx_t ctx,
965 ast_expression *funcexpr)
967 ast_instantiate(ast_call, ctx, ast_call_delete);
968 if (!funcexpr->next) {
969 compile_error(ctx, "not a function");
973 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
975 ast_side_effects(self) = true;
978 self->func = funcexpr;
979 self->va_count = NULL;
981 ast_type_adopt(self, funcexpr->next);
986 void ast_call_delete(ast_call *self)
989 for (i = 0; i < vec_size(self->params); ++i)
990 ast_unref(self->params[i]);
991 vec_free(self->params);
994 ast_unref(self->func);
997 ast_unref(self->va_count);
999 ast_expression_delete((ast_expression*)self);
1003 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
1009 if (!va_type || !ast_compare_type(va_type, exp_type))
1011 if (va_type && exp_type)
1013 ast_type_to_string(va_type, tgot, sizeof(tgot));
1014 ast_type_to_string(exp_type, texp, sizeof(texp));
1015 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1016 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1017 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1021 compile_error(ast_ctx(self),
1022 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1029 ast_type_to_string(exp_type, texp, sizeof(texp));
1030 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1031 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1032 "piped variadic argument may differ in type: expected type %s",
1036 compile_error(ast_ctx(self),
1037 "piped variadic argument may differ in type: expected type %s",
1046 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1052 const ast_expression *func = self->func;
1053 size_t count = vec_size(self->params);
1054 if (count > vec_size(func->params))
1055 count = vec_size(func->params);
1057 for (i = 0; i < count; ++i) {
1058 if (ast_istype(self->params[i], ast_argpipe)) {
1059 /* warn about type safety instead */
1061 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1064 if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->params[i]))
1067 else if (!ast_compare_type(self->params[i], (ast_expression*)(func->params[i])))
1069 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1070 ast_type_to_string((ast_expression*)func->params[i], texp, sizeof(texp));
1071 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1072 (unsigned int)(i+1), texp, tgot);
1073 /* we don't immediately return */
1077 count = vec_size(self->params);
1078 if (count > vec_size(func->params) && func->varparam) {
1079 for (; i < count; ++i) {
1080 if (ast_istype(self->params[i], ast_argpipe)) {
1081 /* warn about type safety instead */
1083 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1086 if (!ast_call_check_vararg(self, va_type, func->varparam))
1089 else if (!ast_compare_type(self->params[i], func->varparam))
1091 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1092 ast_type_to_string(func->varparam, texp, sizeof(texp));
1093 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1094 (unsigned int)(i+1), texp, tgot);
1095 /* we don't immediately return */
1103 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1104 ast_expression *dest, ast_expression *source)
1106 ast_instantiate(ast_store, ctx, ast_store_delete);
1107 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1109 ast_side_effects(self) = true;
1113 self->source = source;
1115 ast_type_adopt(self, dest);
1120 void ast_store_delete(ast_store *self)
1122 ast_unref(self->dest);
1123 ast_unref(self->source);
1124 ast_expression_delete((ast_expression*)self);
1128 ast_block* ast_block_new(lex_ctx_t ctx)
1130 ast_instantiate(ast_block, ctx, ast_block_delete);
1131 ast_expression_init((ast_expression*)self,
1132 (ast_expression_codegen*)&ast_block_codegen);
1134 self->locals = NULL;
1136 self->collect = NULL;
1141 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1143 ast_propagate_effects(self, e);
1144 vec_push(self->exprs, e);
1145 if (self->expression.next) {
1146 ast_delete(self->expression.next);
1147 self->expression.next = NULL;
1149 ast_type_adopt(self, e);
1153 void ast_block_collect(ast_block *self, ast_expression *expr)
1155 vec_push(self->collect, expr);
1156 expr->node.keep = true;
1159 void ast_block_delete(ast_block *self)
1162 for (i = 0; i < vec_size(self->exprs); ++i)
1163 ast_unref(self->exprs[i]);
1164 vec_free(self->exprs);
1165 for (i = 0; i < vec_size(self->locals); ++i)
1166 ast_delete(self->locals[i]);
1167 vec_free(self->locals);
1168 for (i = 0; i < vec_size(self->collect); ++i)
1169 ast_delete(self->collect[i]);
1170 vec_free(self->collect);
1171 ast_expression_delete((ast_expression*)self);
1175 void ast_block_set_type(ast_block *self, ast_expression *from)
1177 if (self->expression.next)
1178 ast_delete(self->expression.next);
1179 ast_type_adopt(self, from);
1182 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1184 ast_instantiate(ast_function, ctx, ast_function_delete);
1187 compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1189 } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1190 compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1192 (int)vtype->hasvalue,
1193 vtype->expression.vtype);
1197 self->vtype = vtype;
1198 self->name = name ? util_strdup(name) : NULL;
1199 self->blocks = NULL;
1201 self->labelcount = 0;
1204 self->ir_func = NULL;
1205 self->curblock = NULL;
1207 self->breakblocks = NULL;
1208 self->continueblocks = NULL;
1210 vtype->hasvalue = true;
1211 vtype->constval.vfunc = self;
1213 self->varargs = NULL;
1215 self->fixedparams = NULL;
1216 self->return_value = NULL;
1225 void ast_function_delete(ast_function *self)
1229 mem_d((void*)self->name);
1231 /* ast_value_delete(self->vtype); */
1232 self->vtype->hasvalue = false;
1233 self->vtype->constval.vfunc = NULL;
1234 /* We use unref - if it was stored in a global table it is supposed
1235 * to be deleted from *there*
1237 ast_unref(self->vtype);
1239 for (i = 0; i < vec_size(self->blocks); ++i)
1240 ast_delete(self->blocks[i]);
1241 vec_free(self->blocks);
1242 vec_free(self->breakblocks);
1243 vec_free(self->continueblocks);
1245 ast_delete(self->varargs);
1247 ast_delete(self->argc);
1248 if (self->fixedparams)
1249 ast_unref(self->fixedparams);
1250 if (self->return_value)
1251 ast_unref(self->return_value);
1255 const char* ast_function_label(ast_function *self, const char *prefix)
1261 if (!OPTS_OPTION_BOOL(OPTION_DUMP) &&
1262 !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1263 !OPTS_OPTION_BOOL(OPTION_DEBUG))
1268 id = (self->labelcount++);
1269 len = strlen(prefix);
1271 from = self->labelbuf + sizeof(self->labelbuf)-1;
1274 *from-- = (id%10) + '0';
1278 memcpy(from - len, prefix, len);
1282 /*********************************************************************/
1284 * by convention you must never pass NULL to the 'ir_value **out'
1285 * parameter. If you really don't care about the output, pass a dummy.
1286 * But I can't imagine a pituation where the output is truly unnecessary.
1289 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1291 if (out->vtype == TYPE_FIELD)
1292 out->fieldtype = self->next->vtype;
1293 if (out->vtype == TYPE_FUNCTION)
1294 out->outtype = self->next->vtype;
1297 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1299 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1303 if (self->expression.vtype == TYPE_NIL) {
1304 *out = func->ir_func->owner->nil;
1307 /* NOTE: This is the codegen for a variable used in an expression.
1308 * It is not the codegen to generate the value. For this purpose,
1309 * ast_local_codegen and ast_global_codegen are to be used before this
1310 * is executed. ast_function_codegen should take care of its locals,
1311 * and the ast-user should take care of ast_global_codegen to be used
1312 * on all the globals.
1315 char tname[1024]; /* typename is reserved in C++ */
1316 ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1317 compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1324 static bool ast_global_array_set(ast_value *self)
1326 size_t count = vec_size(self->initlist);
1329 if (count > self->expression.count) {
1330 compile_error(ast_ctx(self), "too many elements in initializer");
1331 count = self->expression.count;
1333 else if (count < self->expression.count) {
1335 compile_warning(ast_ctx(self), "not all elements are initialized");
1339 for (i = 0; i != count; ++i) {
1340 switch (self->expression.next->vtype) {
1342 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1346 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1350 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1354 /* we don't support them in any other place yet either */
1355 compile_error(ast_ctx(self), "TODO: nested arrays");
1358 /* this requiers a bit more work - similar to the fields I suppose */
1359 compile_error(ast_ctx(self), "global of type function not properly generated");
1362 if (!self->initlist[i].vfield) {
1363 compile_error(ast_ctx(self), "field constant without vfield set");
1366 if (!self->initlist[i].vfield->ir_v) {
1367 compile_error(ast_ctx(self), "field constant generated before its field");
1370 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1374 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1381 static bool check_array(ast_value *self, ast_value *array)
1383 if (array->expression.flags & AST_FLAG_ARRAY_INIT && !array->initlist) {
1384 compile_error(ast_ctx(self), "array without size: %s", self->name);
1387 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1388 if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1389 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1395 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1399 if (self->expression.vtype == TYPE_NIL) {
1400 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1404 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1406 ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1409 func->context = ast_ctx(self);
1410 func->value->context = ast_ctx(self);
1412 self->constval.vfunc->ir_func = func;
1413 self->ir_v = func->value;
1414 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1415 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1416 if (self->expression.flags & AST_FLAG_ERASEABLE)
1417 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1418 /* The function is filled later on ast_function_codegen... */
1422 if (isfield && self->expression.vtype == TYPE_FIELD) {
1423 ast_expression *fieldtype = self->expression.next;
1425 if (self->hasvalue) {
1426 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1430 if (fieldtype->vtype == TYPE_ARRAY) {
1435 ast_expression *elemtype;
1437 ast_value *array = (ast_value*)fieldtype;
1439 if (!ast_istype(fieldtype, ast_value)) {
1440 compile_error(ast_ctx(self), "internal error: ast_value required");
1444 if (!check_array(self, array))
1447 elemtype = array->expression.next;
1448 vtype = elemtype->vtype;
1450 v = ir_builder_create_field(ir, self->name, vtype);
1452 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1455 v->context = ast_ctx(self);
1456 v->unique_life = true;
1458 array->ir_v = self->ir_v = v;
1460 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1461 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1462 if (self->expression.flags & AST_FLAG_ERASEABLE)
1463 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1465 namelen = strlen(self->name);
1466 name = (char*)mem_a(namelen + 16);
1467 platform_strncpy(name, self->name, namelen);
1469 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1470 array->ir_values[0] = v;
1471 for (ai = 1; ai < array->expression.count; ++ai) {
1472 platform_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1473 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1474 if (!array->ir_values[ai]) {
1476 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1479 array->ir_values[ai]->context = ast_ctx(self);
1480 array->ir_values[ai]->unique_life = true;
1481 array->ir_values[ai]->locked = true;
1482 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1483 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1489 v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1492 v->context = ast_ctx(self);
1494 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1495 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1497 if (self->expression.flags & AST_FLAG_ERASEABLE)
1498 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1503 if (self->expression.vtype == TYPE_ARRAY) {
1508 ast_expression *elemtype = self->expression.next;
1509 int vtype = elemtype->vtype;
1511 if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1512 compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1516 /* same as with field arrays */
1517 if (!check_array(self, self))
1520 v = ir_builder_create_global(ir, self->name, vtype);
1522 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1525 v->context = ast_ctx(self);
1526 v->unique_life = true;
1529 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1530 v->flags |= IR_FLAG_INCLUDE_DEF;
1531 if (self->expression.flags & AST_FLAG_ERASEABLE)
1532 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1534 namelen = strlen(self->name);
1535 name = (char*)mem_a(namelen + 16);
1536 platform_strncpy(name, self->name, namelen);
1538 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1539 self->ir_values[0] = v;
1540 for (ai = 1; ai < self->expression.count; ++ai) {
1541 platform_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1542 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1543 if (!self->ir_values[ai]) {
1545 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1548 self->ir_values[ai]->context = ast_ctx(self);
1549 self->ir_values[ai]->unique_life = true;
1550 self->ir_values[ai]->locked = true;
1551 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1552 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1558 /* Arrays don't do this since there's no "array" value which spans across the
1561 v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1563 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1566 codegen_output_type(self, v);
1567 v->context = ast_ctx(self);
1570 /* link us to the ir_value */
1574 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1575 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1576 if (self->expression.flags & AST_FLAG_ERASEABLE)
1577 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1580 if (self->hasvalue) {
1581 switch (self->expression.vtype)
1584 if (!ir_value_set_float(v, self->constval.vfloat))
1588 if (!ir_value_set_vector(v, self->constval.vvec))
1592 if (!ir_value_set_string(v, self->constval.vstring))
1596 ast_global_array_set(self);
1599 compile_error(ast_ctx(self), "global of type function not properly generated");
1601 /* Cannot generate an IR value for a function,
1602 * need a pointer pointing to a function rather.
1605 if (!self->constval.vfield) {
1606 compile_error(ast_ctx(self), "field constant without vfield set");
1609 if (!self->constval.vfield->ir_v) {
1610 compile_error(ast_ctx(self), "field constant generated before its field");
1613 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1617 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1623 error: /* clean up */
1624 if(v) ir_value_delete(v);
1628 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1632 if (self->expression.vtype == TYPE_NIL) {
1633 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1637 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1639 /* Do we allow local functions? I think not...
1640 * this is NOT a function pointer atm.
1645 if (self->expression.vtype == TYPE_ARRAY) {
1650 ast_expression *elemtype = self->expression.next;
1651 int vtype = elemtype->vtype;
1653 func->flags |= IR_FLAG_HAS_ARRAYS;
1655 if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1656 compile_error(ast_ctx(self), "array-parameters are not supported");
1660 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1661 if (!check_array(self, self))
1664 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1665 if (!self->ir_values) {
1666 compile_error(ast_ctx(self), "failed to allocate array values");
1670 v = ir_function_create_local(func, self->name, vtype, param);
1672 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1675 v->context = ast_ctx(self);
1676 v->unique_life = true;
1679 namelen = strlen(self->name);
1680 name = (char*)mem_a(namelen + 16);
1681 platform_strncpy(name, self->name, namelen);
1683 self->ir_values[0] = v;
1684 for (ai = 1; ai < self->expression.count; ++ai) {
1685 platform_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1686 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1687 if (!self->ir_values[ai]) {
1688 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1691 self->ir_values[ai]->context = ast_ctx(self);
1692 self->ir_values[ai]->unique_life = true;
1693 self->ir_values[ai]->locked = true;
1699 v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1702 codegen_output_type(self, v);
1703 v->context = ast_ctx(self);
1706 /* A constant local... hmmm...
1707 * I suppose the IR will have to deal with this
1709 if (self->hasvalue) {
1710 switch (self->expression.vtype)
1713 if (!ir_value_set_float(v, self->constval.vfloat))
1717 if (!ir_value_set_vector(v, self->constval.vvec))
1721 if (!ir_value_set_string(v, self->constval.vstring))
1725 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1730 /* link us to the ir_value */
1734 if (!ast_generate_accessors(self, func->owner))
1738 error: /* clean up */
1743 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1746 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1747 if (!self->setter || !self->getter)
1749 for (i = 0; i < self->expression.count; ++i) {
1750 if (!self->ir_values) {
1751 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1754 if (!self->ir_values[i]) {
1755 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1758 if (self->ir_values[i]->life) {
1759 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1764 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1766 if (!ast_global_codegen (self->setter, ir, false) ||
1767 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1768 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1770 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1771 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1776 if (!ast_global_codegen (self->getter, ir, false) ||
1777 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1778 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1780 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1781 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1785 for (i = 0; i < self->expression.count; ++i) {
1786 vec_free(self->ir_values[i]->life);
1788 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1792 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1797 ast_expression_codegen *cgen;
1802 irf = self->ir_func;
1804 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1808 /* fill the parameter list */
1809 ec = &self->vtype->expression;
1810 for (i = 0; i < vec_size(ec->params); ++i)
1812 if (ec->params[i]->expression.vtype == TYPE_FIELD)
1813 vec_push(irf->params, ec->params[i]->expression.next->vtype);
1815 vec_push(irf->params, ec->params[i]->expression.vtype);
1816 if (!self->builtin) {
1817 if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1822 if (self->varargs) {
1823 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1825 irf->max_varargs = self->varargs->expression.count;
1828 if (self->builtin) {
1829 irf->builtin = self->builtin;
1833 /* have a local return value variable? */
1834 if (self->return_value) {
1835 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1839 if (!vec_size(self->blocks)) {
1840 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1844 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1845 if (!self->curblock) {
1846 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1854 if (!ast_local_codegen(self->argc, self->ir_func, true))
1856 cgen = self->argc->expression.codegen;
1857 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1859 cgen = self->fixedparams->expression.codegen;
1860 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1862 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1863 ast_function_label(self, "va_count"), INSTR_SUB_F,
1864 ir_builder_get_va_count(ir), fixed);
1867 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1874 for (i = 0; i < vec_size(self->blocks); ++i) {
1875 cgen = self->blocks[i]->expression.codegen;
1876 if (!(*cgen)((ast_expression*)self->blocks[i], self, false, &dummy))
1880 /* TODO: check return types */
1881 if (!self->curblock->final)
1883 if (!self->vtype->expression.next ||
1884 self->vtype->expression.next->vtype == TYPE_VOID)
1886 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1888 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1890 if (self->return_value) {
1891 cgen = self->return_value->expression.codegen;
1892 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1894 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1896 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1897 "control reaches end of non-void function (`%s`) via %s",
1898 self->name, self->curblock->label))
1902 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1908 static bool starts_a_label(ast_expression *ex)
1910 while (ex && ast_istype(ex, ast_block)) {
1911 ast_block *b = (ast_block*)ex;
1916 return ast_istype(ex, ast_label);
1919 /* Note, you will not see ast_block_codegen generate ir_blocks.
1920 * To the AST and the IR, blocks are 2 different things.
1921 * In the AST it represents a block of code, usually enclosed in
1922 * curly braces {...}.
1923 * While in the IR it represents a block in terms of control-flow.
1925 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1929 /* We don't use this
1930 * Note: an ast-representation using the comma-operator
1931 * of the form: (a, b, c) = x should not assign to c...
1934 compile_error(ast_ctx(self), "not an l-value (code-block)");
1938 if (self->expression.outr) {
1939 *out = self->expression.outr;
1943 /* output is NULL at first, we'll have each expression
1944 * assign to out output, thus, a comma-operator represention
1945 * using an ast_block will return the last generated value,
1946 * so: (b, c) + a executed both b and c, and returns c,
1947 * which is then added to a.
1951 /* generate locals */
1952 for (i = 0; i < vec_size(self->locals); ++i)
1954 if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1955 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1956 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1961 for (i = 0; i < vec_size(self->exprs); ++i)
1963 ast_expression_codegen *gen;
1964 if (func->curblock->final && !starts_a_label(self->exprs[i])) {
1965 if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
1969 gen = self->exprs[i]->codegen;
1970 if (!(*gen)(self->exprs[i], func, false, out))
1974 self->expression.outr = *out;
1979 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1981 ast_expression_codegen *cgen;
1982 ir_value *left = NULL;
1983 ir_value *right = NULL;
1987 ast_array_index *ai = NULL;
1989 if (lvalue && self->expression.outl) {
1990 *out = self->expression.outl;
1994 if (!lvalue && self->expression.outr) {
1995 *out = self->expression.outr;
1999 if (ast_istype(self->dest, ast_array_index))
2002 ai = (ast_array_index*)self->dest;
2003 idx = (ast_value*)ai->index;
2005 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2010 /* we need to call the setter */
2011 ir_value *iridx, *funval;
2015 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2019 arr = (ast_value*)ai->array;
2020 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2021 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2025 cgen = idx->expression.codegen;
2026 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2029 cgen = arr->setter->expression.codegen;
2030 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2033 cgen = self->source->codegen;
2034 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2037 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2040 ir_call_param(call, iridx);
2041 ir_call_param(call, right);
2042 self->expression.outr = right;
2048 cgen = self->dest->codegen;
2050 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
2052 self->expression.outl = left;
2054 cgen = self->source->codegen;
2056 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2059 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2061 self->expression.outr = right;
2064 /* Theoretically, an assinment returns its left side as an
2065 * lvalue, if we don't need an lvalue though, we return
2066 * the right side as an rvalue, otherwise we have to
2067 * somehow know whether or not we need to dereference the pointer
2068 * on the left side - that is: OP_LOAD if it was an address.
2069 * Also: in original QC we cannot OP_LOADP *anyway*.
2071 *out = (lvalue ? left : right);
2076 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2078 ast_expression_codegen *cgen;
2079 ir_value *left, *right;
2081 /* A binary operation cannot yield an l-value */
2083 compile_error(ast_ctx(self), "not an l-value (binop)");
2087 if (self->expression.outr) {
2088 *out = self->expression.outr;
2092 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2093 (self->op == INSTR_AND || self->op == INSTR_OR))
2095 /* NOTE: The short-logic path will ignore right_first */
2097 /* short circuit evaluation */
2098 ir_block *other, *merge;
2099 ir_block *from_left, *from_right;
2103 /* prepare end-block */
2104 merge_id = vec_size(func->ir_func->blocks);
2105 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2107 /* generate the left expression */
2108 cgen = self->left->codegen;
2109 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2111 /* remember the block */
2112 from_left = func->curblock;
2114 /* create a new block for the right expression */
2115 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2116 if (self->op == INSTR_AND) {
2117 /* on AND: left==true -> other */
2118 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2121 /* on OR: left==false -> other */
2122 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2125 /* use the likely flag */
2126 vec_last(func->curblock->instr)->likely = true;
2128 /* enter the right-expression's block */
2129 func->curblock = other;
2131 cgen = self->right->codegen;
2132 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2134 /* remember block */
2135 from_right = func->curblock;
2137 /* jump to the merge block */
2138 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2141 vec_remove(func->ir_func->blocks, merge_id, 1);
2142 vec_push(func->ir_func->blocks, merge);
2144 func->curblock = merge;
2145 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2146 ast_function_label(func, "sce_value"),
2147 self->expression.vtype);
2148 ir_phi_add(phi, from_left, left);
2149 ir_phi_add(phi, from_right, right);
2150 *out = ir_phi_value(phi);
2154 if (!OPTS_FLAG(PERL_LOGIC)) {
2156 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2157 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2158 ast_function_label(func, "sce_bool_v"),
2162 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2163 ast_function_label(func, "sce_bool"),
2168 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2169 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2170 ast_function_label(func, "sce_bool_s"),
2174 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2175 ast_function_label(func, "sce_bool"),
2181 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2182 ast_function_label(func, "sce_bool"),
2183 INSTR_AND, *out, *out);
2189 self->expression.outr = *out;
2190 codegen_output_type(self, *out);
2194 if (self->right_first) {
2195 cgen = self->right->codegen;
2196 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2198 cgen = self->left->codegen;
2199 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2202 cgen = self->left->codegen;
2203 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2205 cgen = self->right->codegen;
2206 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2210 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2211 self->op, left, right);
2214 self->expression.outr = *out;
2215 codegen_output_type(self, *out);
2220 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2222 ast_expression_codegen *cgen;
2223 ir_value *leftl = NULL, *leftr, *right, *bin;
2227 ast_array_index *ai = NULL;
2228 ir_value *iridx = NULL;
2230 if (lvalue && self->expression.outl) {
2231 *out = self->expression.outl;
2235 if (!lvalue && self->expression.outr) {
2236 *out = self->expression.outr;
2240 if (ast_istype(self->dest, ast_array_index))
2243 ai = (ast_array_index*)self->dest;
2244 idx = (ast_value*)ai->index;
2246 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2250 /* for a binstore we need both an lvalue and an rvalue for the left side */
2251 /* rvalue of destination! */
2253 cgen = idx->expression.codegen;
2254 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2257 cgen = self->dest->codegen;
2258 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2261 /* source as rvalue only */
2262 cgen = self->source->codegen;
2263 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2266 /* now the binary */
2267 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2268 self->opbin, leftr, right);
2269 self->expression.outr = bin;
2273 /* we need to call the setter */
2278 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2282 arr = (ast_value*)ai->array;
2283 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2284 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2288 cgen = arr->setter->expression.codegen;
2289 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2292 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2295 ir_call_param(call, iridx);
2296 ir_call_param(call, bin);
2297 self->expression.outr = bin;
2299 /* now store them */
2300 cgen = self->dest->codegen;
2301 /* lvalue of destination */
2302 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2304 self->expression.outl = leftl;
2306 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2308 self->expression.outr = bin;
2311 /* Theoretically, an assinment returns its left side as an
2312 * lvalue, if we don't need an lvalue though, we return
2313 * the right side as an rvalue, otherwise we have to
2314 * somehow know whether or not we need to dereference the pointer
2315 * on the left side - that is: OP_LOAD if it was an address.
2316 * Also: in original QC we cannot OP_LOADP *anyway*.
2318 *out = (lvalue ? leftl : bin);
2323 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2325 ast_expression_codegen *cgen;
2328 /* An unary operation cannot yield an l-value */
2330 compile_error(ast_ctx(self), "not an l-value (binop)");
2334 if (self->expression.outr) {
2335 *out = self->expression.outr;
2339 cgen = self->operand->codegen;
2341 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2344 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2348 self->expression.outr = *out;
2353 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2355 ast_expression_codegen *cgen;
2360 /* In the context of a return operation, we don't actually return
2364 compile_error(ast_ctx(self), "return-expression is not an l-value");
2368 if (self->expression.outr) {
2369 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2372 self->expression.outr = (ir_value*)1;
2374 if (self->operand) {
2375 cgen = self->operand->codegen;
2377 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2380 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2383 if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2390 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2392 ast_expression_codegen *cgen;
2393 ir_value *ent, *field;
2395 /* This function needs to take the 'lvalue' flag into account!
2396 * As lvalue we provide a field-pointer, as rvalue we provide the
2400 if (lvalue && self->expression.outl) {
2401 *out = self->expression.outl;
2405 if (!lvalue && self->expression.outr) {
2406 *out = self->expression.outr;
2410 cgen = self->entity->codegen;
2411 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2414 cgen = self->field->codegen;
2415 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2420 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2423 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2424 ent, field, self->expression.vtype);
2425 /* Done AFTER error checking:
2426 codegen_output_type(self, *out);
2430 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2431 (lvalue ? "ADDRESS" : "FIELD"),
2432 type_name[self->expression.vtype]);
2436 codegen_output_type(self, *out);
2439 self->expression.outl = *out;
2441 self->expression.outr = *out;
2443 /* Hm that should be it... */
2447 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2449 ast_expression_codegen *cgen;
2452 /* in QC this is always an lvalue */
2453 if (lvalue && self->rvalue) {
2454 compile_error(ast_ctx(self), "not an l-value (member access)");
2457 if (self->expression.outl) {
2458 *out = self->expression.outl;
2462 cgen = self->owner->codegen;
2463 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2466 if (vec->vtype != TYPE_VECTOR &&
2467 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2472 *out = ir_value_vector_member(vec, self->field);
2473 self->expression.outl = *out;
2475 return (*out != NULL);
2478 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2483 if (!lvalue && self->expression.outr) {
2484 *out = self->expression.outr;
2487 if (lvalue && self->expression.outl) {
2488 *out = self->expression.outl;
2492 if (!ast_istype(self->array, ast_value)) {
2493 compile_error(ast_ctx(self), "array indexing this way is not supported");
2494 /* note this would actually be pointer indexing because the left side is
2495 * not an actual array but (hopefully) an indexable expression.
2496 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2497 * support this path will be filled.
2502 arr = (ast_value*)self->array;
2503 idx = (ast_value*)self->index;
2505 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2506 /* Time to use accessor functions */
2507 ast_expression_codegen *cgen;
2508 ir_value *iridx, *funval;
2512 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2517 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2521 cgen = self->index->codegen;
2522 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2525 cgen = arr->getter->expression.codegen;
2526 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2529 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2532 ir_call_param(call, iridx);
2534 *out = ir_call_value(call);
2535 self->expression.outr = *out;
2536 (*out)->vtype = self->expression.vtype;
2537 codegen_output_type(self, *out);
2541 if (idx->expression.vtype == TYPE_FLOAT) {
2542 unsigned int arridx = idx->constval.vfloat;
2543 if (arridx >= self->array->count)
2545 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2548 *out = arr->ir_values[arridx];
2550 else if (idx->expression.vtype == TYPE_INTEGER) {
2551 unsigned int arridx = idx->constval.vint;
2552 if (arridx >= self->array->count)
2554 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2557 *out = arr->ir_values[arridx];
2560 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2563 (*out)->vtype = self->expression.vtype;
2564 codegen_output_type(self, *out);
2568 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2572 compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2577 compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2581 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2583 ast_expression_codegen *cgen;
2591 ir_block *ontrue_endblock = NULL;
2592 ir_block *onfalse_endblock = NULL;
2593 ir_block *merge = NULL;
2596 /* We don't output any value, thus also don't care about r/lvalue */
2600 if (self->expression.outr) {
2601 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2604 self->expression.outr = (ir_value*)1;
2606 /* generate the condition */
2607 cgen = self->cond->codegen;
2608 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2610 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2611 cond = func->curblock;
2613 /* try constant folding away the condition */
2614 if ((fold = fold_cond_ifthen(condval, func, self)) != -1)
2617 if (self->on_true) {
2618 /* create on-true block */
2619 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2623 /* enter the block */
2624 func->curblock = ontrue;
2627 cgen = self->on_true->codegen;
2628 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2631 /* we now need to work from the current endpoint */
2632 ontrue_endblock = func->curblock;
2637 if (self->on_false) {
2638 /* create on-false block */
2639 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2643 /* enter the block */
2644 func->curblock = onfalse;
2647 cgen = self->on_false->codegen;
2648 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2651 /* we now need to work from the current endpoint */
2652 onfalse_endblock = func->curblock;
2656 /* Merge block were they all merge in to */
2657 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2659 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2662 /* add jumps ot the merge block */
2663 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2665 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2668 /* Now enter the merge block */
2669 func->curblock = merge;
2672 /* we create the if here, that way all blocks are ordered :)
2674 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2675 (ontrue ? ontrue : merge),
2676 (onfalse ? onfalse : merge)))
2684 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2686 ast_expression_codegen *cgen;
2689 ir_value *trueval, *falseval;
2692 ir_block *cond = func->curblock;
2693 ir_block *cond_out = NULL;
2694 ir_block *ontrue, *ontrue_out = NULL;
2695 ir_block *onfalse, *onfalse_out = NULL;
2699 /* Ternary can never create an lvalue... */
2703 /* In theory it shouldn't be possible to pass through a node twice, but
2704 * in case we add any kind of optimization pass for the AST itself, it
2705 * may still happen, thus we remember a created ir_value and simply return one
2706 * if it already exists.
2708 if (self->expression.outr) {
2709 *out = self->expression.outr;
2713 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2715 /* generate the condition */
2716 func->curblock = cond;
2717 cgen = self->cond->codegen;
2718 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2720 cond_out = func->curblock;
2722 /* try constant folding away the condition */
2723 if ((fold = fold_cond_ternary(condval, func, self)) != -1)
2726 /* create on-true block */
2727 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2732 /* enter the block */
2733 func->curblock = ontrue;
2736 cgen = self->on_true->codegen;
2737 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2740 ontrue_out = func->curblock;
2743 /* create on-false block */
2744 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2749 /* enter the block */
2750 func->curblock = onfalse;
2753 cgen = self->on_false->codegen;
2754 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2757 onfalse_out = func->curblock;
2760 /* create merge block */
2761 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2764 /* jump to merge block */
2765 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2767 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2770 /* create if instruction */
2771 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2774 /* Now enter the merge block */
2775 func->curblock = merge;
2777 /* Here, now, we need a PHI node
2778 * but first some sanity checking...
2780 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2781 /* error("ternary with different types on the two sides"); */
2782 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2787 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2789 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2792 ir_phi_add(phi, ontrue_out, trueval);
2793 ir_phi_add(phi, onfalse_out, falseval);
2795 self->expression.outr = ir_phi_value(phi);
2796 *out = self->expression.outr;
2798 codegen_output_type(self, *out);
2803 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2805 ast_expression_codegen *cgen;
2807 ir_value *dummy = NULL;
2808 ir_value *precond = NULL;
2809 ir_value *postcond = NULL;
2811 /* Since we insert some jumps "late" so we have blocks
2812 * ordered "nicely", we need to keep track of the actual end-blocks
2813 * of expressions to add the jumps to.
2815 ir_block *bbody = NULL, *end_bbody = NULL;
2816 ir_block *bprecond = NULL, *end_bprecond = NULL;
2817 ir_block *bpostcond = NULL, *end_bpostcond = NULL;
2818 ir_block *bincrement = NULL, *end_bincrement = NULL;
2819 ir_block *bout = NULL, *bin = NULL;
2821 /* let's at least move the outgoing block to the end */
2824 /* 'break' and 'continue' need to be able to find the right blocks */
2825 ir_block *bcontinue = NULL;
2826 ir_block *bbreak = NULL;
2828 ir_block *tmpblock = NULL;
2833 if (self->expression.outr) {
2834 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2837 self->expression.outr = (ir_value*)1;
2840 * Should we ever need some kind of block ordering, better make this function
2841 * move blocks around than write a block ordering algorithm later... after all
2842 * the ast and ir should work together, not against each other.
2845 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2846 * anyway if for example it contains a ternary.
2850 cgen = self->initexpr->codegen;
2851 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2855 /* Store the block from which we enter this chaos */
2856 bin = func->curblock;
2858 /* The pre-loop condition needs its own block since we
2859 * need to be able to jump to the start of that expression.
2863 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2867 /* the pre-loop-condition the least important place to 'continue' at */
2868 bcontinue = bprecond;
2871 func->curblock = bprecond;
2874 cgen = self->precond->codegen;
2875 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2878 end_bprecond = func->curblock;
2880 bprecond = end_bprecond = NULL;
2883 /* Now the next blocks won't be ordered nicely, but we need to
2884 * generate them this early for 'break' and 'continue'.
2886 if (self->increment) {
2887 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2890 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2892 bincrement = end_bincrement = NULL;
2895 if (self->postcond) {
2896 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2899 bcontinue = bpostcond; /* postcond comes before the increment */
2901 bpostcond = end_bpostcond = NULL;
2904 bout_id = vec_size(func->ir_func->blocks);
2905 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2910 /* The loop body... */
2911 /* if (self->body) */
2913 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2918 func->curblock = bbody;
2920 vec_push(func->breakblocks, bbreak);
2922 vec_push(func->continueblocks, bcontinue);
2924 vec_push(func->continueblocks, bbody);
2928 cgen = self->body->codegen;
2929 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2933 end_bbody = func->curblock;
2934 vec_pop(func->breakblocks);
2935 vec_pop(func->continueblocks);
2938 /* post-loop-condition */
2942 func->curblock = bpostcond;
2945 cgen = self->postcond->codegen;
2946 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2949 end_bpostcond = func->curblock;
2952 /* The incrementor */
2953 if (self->increment)
2956 func->curblock = bincrement;
2959 cgen = self->increment->codegen;
2960 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2963 end_bincrement = func->curblock;
2966 /* In any case now, we continue from the outgoing block */
2967 func->curblock = bout;
2969 /* Now all blocks are in place */
2970 /* From 'bin' we jump to whatever comes first */
2971 if (bprecond) tmpblock = bprecond;
2972 else tmpblock = bbody; /* can never be null */
2975 else if (bpostcond) tmpblock = bpostcond;
2976 else tmpblock = bout;
2979 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2985 ir_block *ontrue, *onfalse;
2986 ontrue = bbody; /* can never be null */
2988 /* all of this is dead code
2989 else if (bincrement) ontrue = bincrement;
2990 else ontrue = bpostcond;
2994 if (self->pre_not) {
2999 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
3006 if (bincrement) tmpblock = bincrement;
3007 else if (bpostcond) tmpblock = bpostcond;
3008 else if (bprecond) tmpblock = bprecond;
3009 else tmpblock = bbody;
3010 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
3014 /* from increment */
3017 if (bpostcond) tmpblock = bpostcond;
3018 else if (bprecond) tmpblock = bprecond;
3019 else if (bbody) tmpblock = bbody;
3020 else tmpblock = bout;
3021 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
3028 ir_block *ontrue, *onfalse;
3029 if (bprecond) ontrue = bprecond;
3030 else ontrue = bbody; /* can never be null */
3032 /* all of this is dead code
3033 else if (bincrement) ontrue = bincrement;
3034 else ontrue = bpostcond;
3038 if (self->post_not) {
3043 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
3047 /* Move 'bout' to the end */
3048 vec_remove(func->ir_func->blocks, bout_id, 1);
3049 vec_push(func->ir_func->blocks, bout);
3054 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
3061 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3065 if (self->expression.outr) {
3066 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3069 self->expression.outr = (ir_value*)1;
3071 if (self->is_continue)
3072 target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
3074 target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
3077 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3081 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3086 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3088 ast_expression_codegen *cgen;
3090 ast_switch_case *def_case = NULL;
3091 ir_block *def_bfall = NULL;
3092 ir_block *def_bfall_to = NULL;
3093 bool set_def_bfall_to = false;
3095 ir_value *dummy = NULL;
3096 ir_value *irop = NULL;
3097 ir_block *bout = NULL;
3098 ir_block *bfall = NULL;
3106 compile_error(ast_ctx(self), "switch expression is not an l-value");
3110 if (self->expression.outr) {
3111 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3114 self->expression.outr = (ir_value*)1;
3119 cgen = self->operand->codegen;
3120 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3123 if (!vec_size(self->cases))
3126 cmpinstr = type_eq_instr[irop->vtype];
3127 if (cmpinstr >= VINSTR_END) {
3128 ast_type_to_string(self->operand, typestr, sizeof(typestr));
3129 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3133 bout_id = vec_size(func->ir_func->blocks);
3134 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3138 /* setup the break block */
3139 vec_push(func->breakblocks, bout);
3141 /* Now create all cases */
3142 for (c = 0; c < vec_size(self->cases); ++c) {
3143 ir_value *cond, *val;
3144 ir_block *bcase, *bnot;
3147 ast_switch_case *swcase = &self->cases[c];
3149 if (swcase->value) {
3150 /* A regular case */
3151 /* generate the condition operand */
3152 cgen = swcase->value->codegen;
3153 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3155 /* generate the condition */
3156 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3160 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3161 bnot_id = vec_size(func->ir_func->blocks);
3162 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3163 if (!bcase || !bnot)
3165 if (set_def_bfall_to) {
3166 set_def_bfall_to = false;
3167 def_bfall_to = bcase;
3169 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3172 /* Make the previous case-end fall through */
3173 if (bfall && !bfall->final) {
3174 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3178 /* enter the case */
3179 func->curblock = bcase;
3180 cgen = swcase->code->codegen;
3181 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3184 /* remember this block to fall through from */
3185 bfall = func->curblock;
3187 /* enter the else and move it down */
3188 func->curblock = bnot;
3189 vec_remove(func->ir_func->blocks, bnot_id, 1);
3190 vec_push(func->ir_func->blocks, bnot);
3192 /* The default case */
3193 /* Remember where to fall through from: */
3196 /* remember which case it was */
3198 /* And the next case will be remembered */
3199 set_def_bfall_to = true;
3203 /* Jump from the last bnot to bout */
3204 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3206 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3211 /* If there was a default case, put it down here */
3215 /* No need to create an extra block */
3216 bcase = func->curblock;
3218 /* Insert the fallthrough jump */
3219 if (def_bfall && !def_bfall->final) {
3220 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3224 /* Now generate the default code */
3225 cgen = def_case->code->codegen;
3226 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3229 /* see if we need to fall through */
3230 if (def_bfall_to && !func->curblock->final)
3232 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3237 /* Jump from the last bnot to bout */
3238 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3240 /* enter the outgoing block */
3241 func->curblock = bout;
3243 /* restore the break block */
3244 vec_pop(func->breakblocks);
3246 /* Move 'bout' to the end, it's nicer */
3247 vec_remove(func->ir_func->blocks, bout_id, 1);
3248 vec_push(func->ir_func->blocks, bout);
3253 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3258 if (self->undefined) {
3259 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3265 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3269 /* simply create a new block and jump to it */
3270 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3271 if (!self->irblock) {
3272 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3275 if (!func->curblock->final) {
3276 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3280 /* enter the new block */
3281 func->curblock = self->irblock;
3283 /* Generate all the leftover gotos */
3284 for (i = 0; i < vec_size(self->gotos); ++i) {
3285 if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3292 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3296 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3300 if (self->target->irblock) {
3301 if (self->irblock_from) {
3302 /* we already tried once, this is the callback */
3303 self->irblock_from->final = false;
3304 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3305 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3311 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3312 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3319 /* the target has not yet been created...
3320 * close this block in a sneaky way:
3322 func->curblock->final = true;
3323 self->irblock_from = func->curblock;
3324 ast_label_register_goto(self->target, self);
3330 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3332 ast_expression_codegen *cgen;
3334 ir_instr *callinstr;
3337 ir_value *funval = NULL;
3339 /* return values are never lvalues */
3341 compile_error(ast_ctx(self), "not an l-value (function call)");
3345 if (self->expression.outr) {
3346 *out = self->expression.outr;
3350 cgen = self->func->codegen;
3351 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3359 for (i = 0; i < vec_size(self->params); ++i)
3362 ast_expression *expr = self->params[i];
3364 cgen = expr->codegen;
3365 if (!(*cgen)(expr, func, false, ¶m))
3369 vec_push(params, param);
3372 /* varargs counter */
3373 if (self->va_count) {
3375 ir_builder *builder = func->curblock->owner->owner;
3376 cgen = self->va_count->codegen;
3377 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3379 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3380 ir_builder_get_va_count(builder), va_count))
3386 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3387 ast_function_label(func, "call"),
3388 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3392 for (i = 0; i < vec_size(params); ++i) {
3393 ir_call_param(callinstr, params[i]);
3396 *out = ir_call_value(callinstr);
3397 self->expression.outr = *out;
3399 codegen_output_type(self, *out);