2 * Copyright (C) 2012, 2013
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of
7 * this software and associated documentation files (the "Software"), to deal in
8 * the Software without restriction, including without limitation the rights to
9 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 * of the Software, and to permit persons to whom the Software is furnished to do
11 * so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31 #define ast_instantiate(T, ctx, destroyfn) \
32 T* self = (T*)mem_a(sizeof(T)); \
36 ast_node_init((ast_node*)self, ctx, TYPE_##T); \
37 ( (ast_node*)self )->destroy = (ast_node_delete*)destroyfn
40 * forward declarations, these need not be in ast.h for obvious
43 static bool ast_member_codegen(ast_member*, ast_function*, bool lvalue, ir_value**);
44 static void ast_array_index_delete(ast_array_index*);
45 static bool ast_array_index_codegen(ast_array_index*, ast_function*, bool lvalue, ir_value**);
46 static void ast_argpipe_delete(ast_argpipe*);
47 static bool ast_argpipe_codegen(ast_argpipe*, ast_function*, bool lvalue, ir_value**);
48 static void ast_store_delete(ast_store*);
49 static bool ast_store_codegen(ast_store*, ast_function*, bool lvalue, ir_value**);
50 static void ast_ifthen_delete(ast_ifthen*);
51 static bool ast_ifthen_codegen(ast_ifthen*, ast_function*, bool lvalue, ir_value**);
52 static void ast_ternary_delete(ast_ternary*);
53 static bool ast_ternary_codegen(ast_ternary*, ast_function*, bool lvalue, ir_value**);
54 static void ast_loop_delete(ast_loop*);
55 static bool ast_loop_codegen(ast_loop*, ast_function*, bool lvalue, ir_value**);
56 static void ast_breakcont_delete(ast_breakcont*);
57 static bool ast_breakcont_codegen(ast_breakcont*, ast_function*, bool lvalue, ir_value**);
58 static void ast_switch_delete(ast_switch*);
59 static bool ast_switch_codegen(ast_switch*, ast_function*, bool lvalue, ir_value**);
60 static void ast_label_delete(ast_label*);
61 static void ast_label_register_goto(ast_label*, ast_goto*);
62 static bool ast_label_codegen(ast_label*, ast_function*, bool lvalue, ir_value**);
63 static bool ast_goto_codegen(ast_goto*, ast_function*, bool lvalue, ir_value**);
64 static void ast_goto_delete(ast_goto*);
65 static void ast_call_delete(ast_call*);
66 static bool ast_call_codegen(ast_call*, ast_function*, bool lvalue, ir_value**);
67 static bool ast_block_codegen(ast_block*, ast_function*, bool lvalue, ir_value**);
68 static void ast_unary_delete(ast_unary*);
69 static bool ast_unary_codegen(ast_unary*, ast_function*, bool lvalue, ir_value**);
70 static void ast_entfield_delete(ast_entfield*);
71 static bool ast_entfield_codegen(ast_entfield*, ast_function*, bool lvalue, ir_value**);
72 static void ast_return_delete(ast_return*);
73 static bool ast_return_codegen(ast_return*, ast_function*, bool lvalue, ir_value**);
74 static void ast_binstore_delete(ast_binstore*);
75 static bool ast_binstore_codegen(ast_binstore*, ast_function*, bool lvalue, ir_value**);
76 static void ast_binary_delete(ast_binary*);
77 static bool ast_binary_codegen(ast_binary*, ast_function*, bool lvalue, ir_value**);
79 /* It must not be possible to get here. */
80 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
83 con_err("ast node missing destroy()\n");
87 /* Initialize main ast node aprts */
88 static void ast_node_init(ast_node *self, lex_ctx_t ctx, int nodetype)
91 self->destroy = &_ast_node_destroy;
93 self->nodetype = nodetype;
94 self->side_effects = false;
97 /* weight and side effects */
98 static void _ast_propagate_effects(ast_node *self, ast_node *other)
100 if (ast_side_effects(other))
101 ast_side_effects(self) = true;
103 #define ast_propagate_effects(s,o) _ast_propagate_effects(((ast_node*)(s)), ((ast_node*)(o)))
105 /* General expression initialization */
106 static void ast_expression_init(ast_expression *self,
107 ast_expression_codegen *codegen)
109 self->codegen = codegen;
110 self->vtype = TYPE_VOID;
117 self->varparam = NULL;
120 static void ast_expression_delete(ast_expression *self)
124 ast_delete(self->next);
125 for (i = 0; i < vec_size(self->params); ++i) {
126 ast_delete(self->params[i]);
128 vec_free(self->params);
130 ast_delete(self->varparam);
133 static void ast_expression_delete_full(ast_expression *self)
135 ast_expression_delete(self);
139 ast_value* ast_value_copy(const ast_value *self)
142 const ast_expression *fromex;
143 ast_expression *selfex;
144 ast_value *cp = ast_value_new(self->expression.node.context, self->name, self->expression.vtype);
145 if (self->expression.next) {
146 cp->expression.next = ast_type_copy(self->expression.node.context, self->expression.next);
148 fromex = &self->expression;
149 selfex = &cp->expression;
150 selfex->count = fromex->count;
151 selfex->flags = fromex->flags;
152 for (i = 0; i < vec_size(fromex->params); ++i) {
153 ast_value *v = ast_value_copy(fromex->params[i]);
154 vec_push(selfex->params, v);
159 void ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
162 const ast_expression *fromex;
163 ast_expression *selfex;
164 self->vtype = other->vtype;
166 self->next = (ast_expression*)ast_type_copy(ast_ctx(self), other->next);
170 selfex->count = fromex->count;
171 selfex->flags = fromex->flags;
172 for (i = 0; i < vec_size(fromex->params); ++i) {
173 ast_value *v = ast_value_copy(fromex->params[i]);
174 vec_push(selfex->params, v);
178 static ast_expression* ast_shallow_type(lex_ctx_t ctx, int vtype)
180 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
181 ast_expression_init(self, NULL);
182 self->codegen = NULL;
188 ast_expression* ast_type_copy(lex_ctx_t ctx, const ast_expression *ex)
191 const ast_expression *fromex;
192 ast_expression *selfex;
198 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
199 ast_expression_init(self, NULL);
204 /* This may never be codegen()d */
205 selfex->codegen = NULL;
207 selfex->vtype = fromex->vtype;
209 selfex->next = ast_type_copy(ctx, fromex->next);
213 selfex->count = fromex->count;
214 selfex->flags = fromex->flags;
215 for (i = 0; i < vec_size(fromex->params); ++i) {
216 ast_value *v = ast_value_copy(fromex->params[i]);
217 vec_push(selfex->params, v);
224 bool ast_compare_type(ast_expression *a, ast_expression *b)
226 if (a->vtype == TYPE_NIL ||
227 b->vtype == TYPE_NIL)
229 if (a->vtype != b->vtype)
231 if (!a->next != !b->next)
233 if (vec_size(a->params) != vec_size(b->params))
235 if ((a->flags & AST_FLAG_TYPE_MASK) !=
236 (b->flags & AST_FLAG_TYPE_MASK) )
240 if (vec_size(a->params)) {
242 for (i = 0; i < vec_size(a->params); ++i) {
243 if (!ast_compare_type((ast_expression*)a->params[i],
244 (ast_expression*)b->params[i]))
249 return ast_compare_type(a->next, b->next);
253 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
260 if (pos + 6 >= bufsize)
262 util_strncpy(buf + pos, "(null)", 6);
266 if (pos + 1 >= bufsize)
271 util_strncpy(buf + pos, "(variant)", 9);
276 return ast_type_to_string_impl(e->next, buf, bufsize, pos);
279 if (pos + 3 >= bufsize)
283 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
284 if (pos + 1 >= bufsize)
290 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
291 if (pos + 2 >= bufsize)
293 if (!vec_size(e->params)) {
299 pos = ast_type_to_string_impl((ast_expression*)(e->params[0]), buf, bufsize, pos);
300 for (i = 1; i < vec_size(e->params); ++i) {
301 if (pos + 2 >= bufsize)
305 pos = ast_type_to_string_impl((ast_expression*)(e->params[i]), buf, bufsize, pos);
307 if (pos + 1 >= bufsize)
313 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
314 if (pos + 1 >= bufsize)
317 pos += util_snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->count);
318 if (pos + 1 >= bufsize)
324 typestr = type_name[e->vtype];
325 typelen = strlen(typestr);
326 if (pos + typelen >= bufsize)
328 util_strncpy(buf + pos, typestr, typelen);
329 return pos + typelen;
333 buf[bufsize-3] = '.';
334 buf[bufsize-2] = '.';
335 buf[bufsize-1] = '.';
339 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
341 size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
345 static bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out);
346 ast_value* ast_value_new(lex_ctx_t ctx, const char *name, int t)
348 ast_instantiate(ast_value, ctx, ast_value_delete);
349 ast_expression_init((ast_expression*)self,
350 (ast_expression_codegen*)&ast_value_codegen);
351 self->expression.node.keep = true; /* keep */
353 self->name = name ? util_strdup(name) : NULL;
354 self->expression.vtype = t;
355 self->expression.next = NULL;
356 self->isfield = false;
358 self->hasvalue = false;
361 memset(&self->constval, 0, sizeof(self->constval));
362 self->initlist = NULL;
365 self->ir_values = NULL;
366 self->ir_value_count = 0;
372 self->argcounter = NULL;
373 self->intrinsic = false;
378 void ast_value_delete(ast_value* self)
381 mem_d((void*)self->name);
382 if (self->argcounter)
383 mem_d((void*)self->argcounter);
384 if (self->hasvalue) {
385 switch (self->expression.vtype)
388 mem_d((void*)self->constval.vstring);
391 /* unlink us from the function node */
392 self->constval.vfunc->vtype = NULL;
394 /* NOTE: delete function? currently collected in
395 * the parser structure
402 mem_d(self->ir_values);
407 if (self->initlist) {
408 if (self->expression.next->vtype == TYPE_STRING) {
409 /* strings are allocated, free them */
410 size_t i, len = vec_size(self->initlist);
411 /* in theory, len should be expression.count
412 * but let's not take any chances */
413 for (i = 0; i < len; ++i) {
414 if (self->initlist[i].vstring)
415 mem_d(self->initlist[i].vstring);
418 vec_free(self->initlist);
421 ast_expression_delete((ast_expression*)self);
425 void ast_value_params_add(ast_value *self, ast_value *p)
427 vec_push(self->expression.params, p);
430 bool ast_value_set_name(ast_value *self, const char *name)
433 mem_d((void*)self->name);
434 self->name = util_strdup(name);
438 ast_binary* ast_binary_new(lex_ctx_t ctx, int op,
439 ast_expression* left, ast_expression* right)
442 ast_instantiate(ast_binary, ctx, ast_binary_delete);
443 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
448 self->right_first = false;
450 ast_propagate_effects(self, left);
451 ast_propagate_effects(self, right);
453 if (OPTS_OPTIMIZATION(OPTIM_PEEPHOLE) && (fold = (ast_binary*)fold_superfluous(left, right, op))) {
454 ast_binary_delete(self);
458 if (op >= INSTR_EQ_F && op <= INSTR_GT)
459 self->expression.vtype = TYPE_FLOAT;
460 else if (op == INSTR_AND || op == INSTR_OR) {
461 if (OPTS_FLAG(PERL_LOGIC))
462 ast_type_adopt(self, right);
464 self->expression.vtype = TYPE_FLOAT;
466 else if (op == INSTR_BITAND || op == INSTR_BITOR)
467 self->expression.vtype = TYPE_FLOAT;
468 else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
469 self->expression.vtype = TYPE_VECTOR;
470 else if (op == INSTR_MUL_V)
471 self->expression.vtype = TYPE_FLOAT;
473 self->expression.vtype = left->vtype;
476 self->refs = AST_REF_ALL;
481 void ast_binary_delete(ast_binary *self)
483 if (self->refs & AST_REF_LEFT) ast_unref(self->left);
484 if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
486 ast_expression_delete((ast_expression*)self);
490 ast_binstore* ast_binstore_new(lex_ctx_t ctx, int storop, int op,
491 ast_expression* left, ast_expression* right)
493 ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
494 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
496 ast_side_effects(self) = true;
498 self->opstore = storop;
501 self->source = right;
503 self->keep_dest = false;
505 ast_type_adopt(self, left);
509 void ast_binstore_delete(ast_binstore *self)
511 if (!self->keep_dest)
512 ast_unref(self->dest);
513 ast_unref(self->source);
514 ast_expression_delete((ast_expression*)self);
518 ast_unary* ast_unary_new(lex_ctx_t ctx, int op,
519 ast_expression *expr)
521 ast_instantiate(ast_unary, ctx, ast_unary_delete);
522 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
525 self->operand = expr;
528 if (ast_istype(expr, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
529 ast_unary *prev = (ast_unary*)((ast_unary*)expr)->operand;
531 /* Handle for double negation */
532 if (((ast_unary*)expr)->op == op)
533 prev = (ast_unary*)((ast_unary*)expr)->operand;
535 if (ast_istype(prev, ast_unary)) {
536 ast_expression_delete((ast_expression*)self);
538 ++opts_optimizationcount[OPTIM_PEEPHOLE];
543 ast_propagate_effects(self, expr);
545 if ((op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) || op == VINSTR_NEG_F) {
546 self->expression.vtype = TYPE_FLOAT;
547 } else if (op == VINSTR_NEG_V) {
548 self->expression.vtype = TYPE_VECTOR;
550 compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
556 void ast_unary_delete(ast_unary *self)
558 if (self->operand) ast_unref(self->operand);
559 ast_expression_delete((ast_expression*)self);
563 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
565 ast_instantiate(ast_return, ctx, ast_return_delete);
566 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
568 self->operand = expr;
571 ast_propagate_effects(self, expr);
576 void ast_return_delete(ast_return *self)
579 ast_unref(self->operand);
580 ast_expression_delete((ast_expression*)self);
584 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
586 if (field->vtype != TYPE_FIELD) {
587 compile_error(ctx, "ast_entfield_new with expression not of type field");
590 return ast_entfield_new_force(ctx, entity, field, field->next);
593 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
595 ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
599 /* Error: field has no type... */
603 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
605 self->entity = entity;
607 ast_propagate_effects(self, entity);
608 ast_propagate_effects(self, field);
610 ast_type_adopt(self, outtype);
614 void ast_entfield_delete(ast_entfield *self)
616 ast_unref(self->entity);
617 ast_unref(self->field);
618 ast_expression_delete((ast_expression*)self);
622 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
624 ast_instantiate(ast_member, ctx, ast_member_delete);
630 if (owner->vtype != TYPE_VECTOR &&
631 owner->vtype != TYPE_FIELD) {
632 compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
637 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
638 self->expression.node.keep = true; /* keep */
640 if (owner->vtype == TYPE_VECTOR) {
641 self->expression.vtype = TYPE_FLOAT;
642 self->expression.next = NULL;
644 self->expression.vtype = TYPE_FIELD;
645 self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
648 self->rvalue = false;
650 ast_propagate_effects(self, owner);
654 self->name = util_strdup(name);
661 void ast_member_delete(ast_member *self)
663 /* The owner is always an ast_value, which has .keep=true,
664 * also: ast_members are usually deleted after the owner, thus
665 * this will cause invalid access
666 ast_unref(self->owner);
667 * once we allow (expression).x to access a vector-member, we need
668 * to change this: preferably by creating an alternate ast node for this
669 * purpose that is not garbage-collected.
671 ast_expression_delete((ast_expression*)self);
676 bool ast_member_set_name(ast_member *self, const char *name)
679 mem_d((void*)self->name);
680 self->name = util_strdup(name);
684 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
686 ast_expression *outtype;
687 ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
689 outtype = array->next;
692 /* Error: field has no type... */
696 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
700 ast_propagate_effects(self, array);
701 ast_propagate_effects(self, index);
703 ast_type_adopt(self, outtype);
704 if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
705 if (self->expression.vtype != TYPE_ARRAY) {
706 compile_error(ast_ctx(self), "array_index node on type");
707 ast_array_index_delete(self);
710 self->array = outtype;
711 self->expression.vtype = TYPE_FIELD;
717 void ast_array_index_delete(ast_array_index *self)
720 ast_unref(self->array);
722 ast_unref(self->index);
723 ast_expression_delete((ast_expression*)self);
727 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
729 ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete);
730 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
732 self->expression.vtype = TYPE_NOEXPR;
736 void ast_argpipe_delete(ast_argpipe *self)
739 ast_unref(self->index);
740 ast_expression_delete((ast_expression*)self);
744 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
746 ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
747 if (!ontrue && !onfalse) {
748 /* because it is invalid */
752 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
755 self->on_true = ontrue;
756 self->on_false = onfalse;
757 ast_propagate_effects(self, cond);
759 ast_propagate_effects(self, ontrue);
761 ast_propagate_effects(self, onfalse);
766 void ast_ifthen_delete(ast_ifthen *self)
768 ast_unref(self->cond);
770 ast_unref(self->on_true);
772 ast_unref(self->on_false);
773 ast_expression_delete((ast_expression*)self);
777 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
779 ast_expression *exprtype = ontrue;
780 ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
781 /* This time NEITHER must be NULL */
782 if (!ontrue || !onfalse) {
786 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
789 self->on_true = ontrue;
790 self->on_false = onfalse;
791 ast_propagate_effects(self, cond);
792 ast_propagate_effects(self, ontrue);
793 ast_propagate_effects(self, onfalse);
795 if (ontrue->vtype == TYPE_NIL)
797 ast_type_adopt(self, exprtype);
802 void ast_ternary_delete(ast_ternary *self)
804 /* the if()s are only there because computed-gotos can set them
807 if (self->cond) ast_unref(self->cond);
808 if (self->on_true) ast_unref(self->on_true);
809 if (self->on_false) ast_unref(self->on_false);
810 ast_expression_delete((ast_expression*)self);
814 ast_loop* ast_loop_new(lex_ctx_t ctx,
815 ast_expression *initexpr,
816 ast_expression *precond, bool pre_not,
817 ast_expression *postcond, bool post_not,
818 ast_expression *increment,
819 ast_expression *body)
821 ast_instantiate(ast_loop, ctx, ast_loop_delete);
822 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
824 self->initexpr = initexpr;
825 self->precond = precond;
826 self->postcond = postcond;
827 self->increment = increment;
830 self->pre_not = pre_not;
831 self->post_not = post_not;
834 ast_propagate_effects(self, initexpr);
836 ast_propagate_effects(self, precond);
838 ast_propagate_effects(self, postcond);
840 ast_propagate_effects(self, increment);
842 ast_propagate_effects(self, body);
847 void ast_loop_delete(ast_loop *self)
850 ast_unref(self->initexpr);
852 ast_unref(self->precond);
854 ast_unref(self->postcond);
856 ast_unref(self->increment);
858 ast_unref(self->body);
859 ast_expression_delete((ast_expression*)self);
863 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
865 ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
866 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
868 self->is_continue = iscont;
869 self->levels = levels;
874 void ast_breakcont_delete(ast_breakcont *self)
876 ast_expression_delete((ast_expression*)self);
880 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
882 ast_instantiate(ast_switch, ctx, ast_switch_delete);
883 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
888 ast_propagate_effects(self, op);
893 void ast_switch_delete(ast_switch *self)
896 ast_unref(self->operand);
898 for (i = 0; i < vec_size(self->cases); ++i) {
899 if (self->cases[i].value)
900 ast_unref(self->cases[i].value);
901 ast_unref(self->cases[i].code);
903 vec_free(self->cases);
905 ast_expression_delete((ast_expression*)self);
909 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
911 ast_instantiate(ast_label, ctx, ast_label_delete);
912 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
914 self->expression.vtype = TYPE_NOEXPR;
916 self->name = util_strdup(name);
917 self->irblock = NULL;
919 self->undefined = undefined;
924 void ast_label_delete(ast_label *self)
926 mem_d((void*)self->name);
927 vec_free(self->gotos);
928 ast_expression_delete((ast_expression*)self);
932 static void ast_label_register_goto(ast_label *self, ast_goto *g)
934 vec_push(self->gotos, g);
937 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
939 ast_instantiate(ast_goto, ctx, ast_goto_delete);
940 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
942 self->name = util_strdup(name);
944 self->irblock_from = NULL;
949 void ast_goto_delete(ast_goto *self)
951 mem_d((void*)self->name);
952 ast_expression_delete((ast_expression*)self);
956 void ast_goto_set_label(ast_goto *self, ast_label *label)
958 self->target = label;
961 ast_call* ast_call_new(lex_ctx_t ctx,
962 ast_expression *funcexpr)
964 ast_instantiate(ast_call, ctx, ast_call_delete);
965 if (!funcexpr->next) {
966 compile_error(ctx, "not a function");
970 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
972 ast_side_effects(self) = true;
975 self->func = funcexpr;
976 self->va_count = NULL;
978 ast_type_adopt(self, funcexpr->next);
983 void ast_call_delete(ast_call *self)
986 for (i = 0; i < vec_size(self->params); ++i)
987 ast_unref(self->params[i]);
988 vec_free(self->params);
991 ast_unref(self->func);
994 ast_unref(self->va_count);
996 ast_expression_delete((ast_expression*)self);
1000 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
1006 if (!va_type || !ast_compare_type(va_type, exp_type))
1008 if (va_type && exp_type)
1010 ast_type_to_string(va_type, tgot, sizeof(tgot));
1011 ast_type_to_string(exp_type, texp, sizeof(texp));
1012 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1013 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1014 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1018 compile_error(ast_ctx(self),
1019 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1026 ast_type_to_string(exp_type, texp, sizeof(texp));
1027 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1028 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1029 "piped variadic argument may differ in type: expected type %s",
1033 compile_error(ast_ctx(self),
1034 "piped variadic argument may differ in type: expected type %s",
1043 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1049 const ast_expression *func = self->func;
1050 size_t count = vec_size(self->params);
1051 if (count > vec_size(func->params))
1052 count = vec_size(func->params);
1054 for (i = 0; i < count; ++i) {
1055 if (ast_istype(self->params[i], ast_argpipe)) {
1056 /* warn about type safety instead */
1058 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1061 if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->params[i]))
1064 else if (!ast_compare_type(self->params[i], (ast_expression*)(func->params[i])))
1066 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1067 ast_type_to_string((ast_expression*)func->params[i], texp, sizeof(texp));
1068 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1069 (unsigned int)(i+1), texp, tgot);
1070 /* we don't immediately return */
1074 count = vec_size(self->params);
1075 if (count > vec_size(func->params) && func->varparam) {
1076 for (; i < count; ++i) {
1077 if (ast_istype(self->params[i], ast_argpipe)) {
1078 /* warn about type safety instead */
1080 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1083 if (!ast_call_check_vararg(self, va_type, func->varparam))
1086 else if (!ast_compare_type(self->params[i], func->varparam))
1088 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1089 ast_type_to_string(func->varparam, texp, sizeof(texp));
1090 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1091 (unsigned int)(i+1), texp, tgot);
1092 /* we don't immediately return */
1100 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1101 ast_expression *dest, ast_expression *source)
1103 ast_instantiate(ast_store, ctx, ast_store_delete);
1104 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1106 ast_side_effects(self) = true;
1110 self->source = source;
1112 ast_type_adopt(self, dest);
1117 void ast_store_delete(ast_store *self)
1119 ast_unref(self->dest);
1120 ast_unref(self->source);
1121 ast_expression_delete((ast_expression*)self);
1125 ast_block* ast_block_new(lex_ctx_t ctx)
1127 ast_instantiate(ast_block, ctx, ast_block_delete);
1128 ast_expression_init((ast_expression*)self,
1129 (ast_expression_codegen*)&ast_block_codegen);
1131 self->locals = NULL;
1133 self->collect = NULL;
1138 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1140 ast_propagate_effects(self, e);
1141 vec_push(self->exprs, e);
1142 if (self->expression.next) {
1143 ast_delete(self->expression.next);
1144 self->expression.next = NULL;
1146 ast_type_adopt(self, e);
1150 void ast_block_collect(ast_block *self, ast_expression *expr)
1152 vec_push(self->collect, expr);
1153 expr->node.keep = true;
1156 void ast_block_delete(ast_block *self)
1159 for (i = 0; i < vec_size(self->exprs); ++i)
1160 ast_unref(self->exprs[i]);
1161 vec_free(self->exprs);
1162 for (i = 0; i < vec_size(self->locals); ++i)
1163 ast_delete(self->locals[i]);
1164 vec_free(self->locals);
1165 for (i = 0; i < vec_size(self->collect); ++i)
1166 ast_delete(self->collect[i]);
1167 vec_free(self->collect);
1168 ast_expression_delete((ast_expression*)self);
1172 void ast_block_set_type(ast_block *self, ast_expression *from)
1174 if (self->expression.next)
1175 ast_delete(self->expression.next);
1176 ast_type_adopt(self, from);
1179 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1181 ast_instantiate(ast_function, ctx, ast_function_delete);
1184 compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1186 } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1187 } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1188 compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1190 (int)vtype->hasvalue,
1191 vtype->expression.vtype);
1195 self->vtype = vtype;
1196 self->name = name ? util_strdup(name) : NULL;
1197 self->blocks = NULL;
1199 self->labelcount = 0;
1202 self->ir_func = NULL;
1203 self->curblock = NULL;
1205 self->breakblocks = NULL;
1206 self->continueblocks = NULL;
1208 vtype->hasvalue = true;
1209 vtype->constval.vfunc = self;
1211 self->varargs = NULL;
1213 self->fixedparams = NULL;
1214 self->return_value = NULL;
1216 self->accumulate = NULL;
1217 self->accumulation = 0;
1226 void ast_function_delete(ast_function *self)
1230 mem_d((void*)self->name);
1232 /* ast_value_delete(self->vtype); */
1233 self->vtype->hasvalue = false;
1234 self->vtype->constval.vfunc = NULL;
1235 /* We use unref - if it was stored in a global table it is supposed
1236 * to be deleted from *there*
1238 ast_unref(self->vtype);
1240 for (i = 0; i < vec_size(self->blocks); ++i)
1241 ast_delete(self->blocks[i]);
1242 vec_free(self->blocks);
1243 vec_free(self->breakblocks);
1244 vec_free(self->continueblocks);
1246 ast_delete(self->varargs);
1248 ast_delete(self->argc);
1249 if (self->fixedparams)
1250 ast_unref(self->fixedparams);
1251 if (self->return_value)
1252 ast_unref(self->return_value);
1256 const char* ast_function_label(ast_function *self, const char *prefix)
1262 if (!OPTS_OPTION_BOOL(OPTION_DUMP) &&
1263 !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1264 !OPTS_OPTION_BOOL(OPTION_DEBUG))
1269 id = (self->labelcount++);
1270 len = strlen(prefix);
1272 from = self->labelbuf + sizeof(self->labelbuf)-1;
1275 *from-- = (id%10) + '0';
1279 memcpy(from - len, prefix, len);
1283 /*********************************************************************/
1285 * by convention you must never pass NULL to the 'ir_value **out'
1286 * parameter. If you really don't care about the output, pass a dummy.
1287 * But I can't imagine a pituation where the output is truly unnecessary.
1290 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1292 if (out->vtype == TYPE_FIELD)
1293 out->fieldtype = self->next->vtype;
1294 if (out->vtype == TYPE_FUNCTION)
1295 out->outtype = self->next->vtype;
1298 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1300 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1304 if (self->expression.vtype == TYPE_NIL) {
1305 *out = func->ir_func->owner->nil;
1308 /* NOTE: This is the codegen for a variable used in an expression.
1309 * It is not the codegen to generate the value. For this purpose,
1310 * ast_local_codegen and ast_global_codegen are to be used before this
1311 * is executed. ast_function_codegen should take care of its locals,
1312 * and the ast-user should take care of ast_global_codegen to be used
1313 * on all the globals.
1316 char tname[1024]; /* typename is reserved in C++ */
1317 ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1318 compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1325 static bool ast_global_array_set(ast_value *self)
1327 size_t count = vec_size(self->initlist);
1330 if (count > self->expression.count) {
1331 compile_error(ast_ctx(self), "too many elements in initializer");
1332 count = self->expression.count;
1334 else if (count < self->expression.count) {
1336 compile_warning(ast_ctx(self), "not all elements are initialized");
1340 for (i = 0; i != count; ++i) {
1341 switch (self->expression.next->vtype) {
1343 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1347 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1351 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1355 /* we don't support them in any other place yet either */
1356 compile_error(ast_ctx(self), "TODO: nested arrays");
1359 /* this requiers a bit more work - similar to the fields I suppose */
1360 compile_error(ast_ctx(self), "global of type function not properly generated");
1363 if (!self->initlist[i].vfield) {
1364 compile_error(ast_ctx(self), "field constant without vfield set");
1367 if (!self->initlist[i].vfield->ir_v) {
1368 compile_error(ast_ctx(self), "field constant generated before its field");
1371 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1375 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1382 static bool check_array(ast_value *self, ast_value *array)
1384 if (array->expression.flags & AST_FLAG_ARRAY_INIT && !array->initlist) {
1385 compile_error(ast_ctx(self), "array without size: %s", self->name);
1388 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1389 if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1390 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1396 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1400 if (self->expression.vtype == TYPE_NIL) {
1401 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1405 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1407 ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1410 func->context = ast_ctx(self);
1411 func->value->context = ast_ctx(self);
1413 self->constval.vfunc->ir_func = func;
1414 self->ir_v = func->value;
1415 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1416 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1417 if (self->expression.flags & AST_FLAG_ERASEABLE)
1418 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1419 /* The function is filled later on ast_function_codegen... */
1423 if (isfield && self->expression.vtype == TYPE_FIELD) {
1424 ast_expression *fieldtype = self->expression.next;
1426 if (self->hasvalue) {
1427 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1431 if (fieldtype->vtype == TYPE_ARRAY) {
1436 ast_expression *elemtype;
1438 ast_value *array = (ast_value*)fieldtype;
1440 if (!ast_istype(fieldtype, ast_value)) {
1441 compile_error(ast_ctx(self), "internal error: ast_value required");
1445 if (!check_array(self, array))
1448 elemtype = array->expression.next;
1449 vtype = elemtype->vtype;
1451 v = ir_builder_create_field(ir, self->name, vtype);
1453 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1456 v->context = ast_ctx(self);
1457 v->unique_life = true;
1459 array->ir_v = self->ir_v = v;
1461 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1462 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1463 if (self->expression.flags & AST_FLAG_ERASEABLE)
1464 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1466 namelen = strlen(self->name);
1467 name = (char*)mem_a(namelen + 16);
1468 util_strncpy(name, self->name, namelen);
1470 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1471 array->ir_values[0] = v;
1472 for (ai = 1; ai < array->expression.count; ++ai) {
1473 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1474 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1475 if (!array->ir_values[ai]) {
1477 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1480 array->ir_values[ai]->context = ast_ctx(self);
1481 array->ir_values[ai]->unique_life = true;
1482 array->ir_values[ai]->locked = true;
1483 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1484 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1490 v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1493 v->context = ast_ctx(self);
1495 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1496 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1498 if (self->expression.flags & AST_FLAG_ERASEABLE)
1499 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1504 if (self->expression.vtype == TYPE_ARRAY) {
1509 ast_expression *elemtype = self->expression.next;
1510 int vtype = elemtype->vtype;
1512 if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1513 compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1517 /* same as with field arrays */
1518 if (!check_array(self, self))
1521 v = ir_builder_create_global(ir, self->name, vtype);
1523 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1526 v->context = ast_ctx(self);
1527 v->unique_life = true;
1530 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1531 v->flags |= IR_FLAG_INCLUDE_DEF;
1532 if (self->expression.flags & AST_FLAG_ERASEABLE)
1533 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1535 namelen = strlen(self->name);
1536 name = (char*)mem_a(namelen + 16);
1537 util_strncpy(name, self->name, namelen);
1539 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1540 self->ir_values[0] = v;
1541 for (ai = 1; ai < self->expression.count; ++ai) {
1542 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1543 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1544 if (!self->ir_values[ai]) {
1546 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1549 self->ir_values[ai]->context = ast_ctx(self);
1550 self->ir_values[ai]->unique_life = true;
1551 self->ir_values[ai]->locked = true;
1552 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1553 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1559 /* Arrays don't do this since there's no "array" value which spans across the
1562 v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1564 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1567 codegen_output_type(self, v);
1568 v->context = ast_ctx(self);
1571 /* link us to the ir_value */
1575 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1576 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1577 if (self->expression.flags & AST_FLAG_ERASEABLE)
1578 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1581 if (self->hasvalue) {
1582 switch (self->expression.vtype)
1585 if (!ir_value_set_float(v, self->constval.vfloat))
1589 if (!ir_value_set_vector(v, self->constval.vvec))
1593 if (!ir_value_set_string(v, self->constval.vstring))
1597 ast_global_array_set(self);
1600 compile_error(ast_ctx(self), "global of type function not properly generated");
1602 /* Cannot generate an IR value for a function,
1603 * need a pointer pointing to a function rather.
1606 if (!self->constval.vfield) {
1607 compile_error(ast_ctx(self), "field constant without vfield set");
1610 if (!self->constval.vfield->ir_v) {
1611 compile_error(ast_ctx(self), "field constant generated before its field");
1614 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1618 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1624 error: /* clean up */
1625 if(v) ir_value_delete(v);
1629 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1633 if (self->expression.vtype == TYPE_NIL) {
1634 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1638 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1640 /* Do we allow local functions? I think not...
1641 * this is NOT a function pointer atm.
1646 if (self->expression.vtype == TYPE_ARRAY) {
1651 ast_expression *elemtype = self->expression.next;
1652 int vtype = elemtype->vtype;
1654 func->flags |= IR_FLAG_HAS_ARRAYS;
1656 if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1657 compile_error(ast_ctx(self), "array-parameters are not supported");
1661 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1662 if (!check_array(self, self))
1665 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1666 if (!self->ir_values) {
1667 compile_error(ast_ctx(self), "failed to allocate array values");
1671 v = ir_function_create_local(func, self->name, vtype, param);
1673 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1676 v->context = ast_ctx(self);
1677 v->unique_life = true;
1680 namelen = strlen(self->name);
1681 name = (char*)mem_a(namelen + 16);
1682 util_strncpy(name, self->name, namelen);
1684 self->ir_values[0] = v;
1685 for (ai = 1; ai < self->expression.count; ++ai) {
1686 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1687 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1688 if (!self->ir_values[ai]) {
1689 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1692 self->ir_values[ai]->context = ast_ctx(self);
1693 self->ir_values[ai]->unique_life = true;
1694 self->ir_values[ai]->locked = true;
1700 v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1703 codegen_output_type(self, v);
1704 v->context = ast_ctx(self);
1707 /* A constant local... hmmm...
1708 * I suppose the IR will have to deal with this
1710 if (self->hasvalue) {
1711 switch (self->expression.vtype)
1714 if (!ir_value_set_float(v, self->constval.vfloat))
1718 if (!ir_value_set_vector(v, self->constval.vvec))
1722 if (!ir_value_set_string(v, self->constval.vstring))
1726 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1731 /* link us to the ir_value */
1735 if (!ast_generate_accessors(self, func->owner))
1739 error: /* clean up */
1744 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1747 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1748 if (!self->setter || !self->getter)
1750 for (i = 0; i < self->expression.count; ++i) {
1751 if (!self->ir_values) {
1752 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1755 if (!self->ir_values[i]) {
1756 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1759 if (self->ir_values[i]->life) {
1760 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1765 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1767 if (!ast_global_codegen (self->setter, ir, false) ||
1768 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1769 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1771 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1772 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1777 if (!ast_global_codegen (self->getter, ir, false) ||
1778 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1779 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1781 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1782 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1786 for (i = 0; i < self->expression.count; ++i) {
1787 vec_free(self->ir_values[i]->life);
1789 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1793 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1798 ast_expression_codegen *cgen;
1804 irf = self->ir_func;
1806 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1810 /* fill the parameter list */
1811 ec = &self->vtype->expression;
1812 for (i = 0; i < vec_size(ec->params); ++i)
1814 if (ec->params[i]->expression.vtype == TYPE_FIELD)
1815 vec_push(irf->params, ec->params[i]->expression.next->vtype);
1817 vec_push(irf->params, ec->params[i]->expression.vtype);
1818 if (!self->builtin) {
1819 if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1824 if (self->varargs) {
1825 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1827 irf->max_varargs = self->varargs->expression.count;
1830 if (self->builtin) {
1831 irf->builtin = self->builtin;
1835 /* have a local return value variable? */
1836 if (self->return_value) {
1837 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1841 if (!vec_size(self->blocks)) {
1842 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1846 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1847 if (!self->curblock) {
1848 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1856 if (!ast_local_codegen(self->argc, self->ir_func, true))
1858 cgen = self->argc->expression.codegen;
1859 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1861 cgen = self->fixedparams->expression.codegen;
1862 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1864 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1865 ast_function_label(self, "va_count"), INSTR_SUB_F,
1866 ir_builder_get_va_count(ir), fixed);
1869 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1876 /* generate the call for any accumulation */
1877 if (self->accumulate) {
1878 ast_call *call = ast_call_new(ast_ctx(self), (ast_expression*)self->accumulate->vtype);
1879 for (i = 0; i < vec_size(ec->params); i++)
1880 vec_push(call->params, (ast_expression*)ec->params[i]);
1881 vec_push(vec_last(self->blocks)->exprs, (ast_expression*)call);
1884 for (i = 0; i < vec_size(self->blocks); ++i) {
1885 cgen = self->blocks[i]->expression.codegen;
1886 if (!(*cgen)((ast_expression*)self->blocks[i], self, false, &dummy))
1890 /* TODO: check return types */
1891 if (!self->curblock->final)
1893 if (!self->vtype->expression.next ||
1894 self->vtype->expression.next->vtype == TYPE_VOID)
1896 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1898 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1900 if (self->return_value) {
1901 cgen = self->return_value->expression.codegen;
1902 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1904 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1906 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1907 "control reaches end of non-void function (`%s`) via %s",
1908 self->name, self->curblock->label))
1912 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1918 static bool starts_a_label(ast_expression *ex)
1920 while (ex && ast_istype(ex, ast_block)) {
1921 ast_block *b = (ast_block*)ex;
1926 return ast_istype(ex, ast_label);
1929 /* Note, you will not see ast_block_codegen generate ir_blocks.
1930 * To the AST and the IR, blocks are 2 different things.
1931 * In the AST it represents a block of code, usually enclosed in
1932 * curly braces {...}.
1933 * While in the IR it represents a block in terms of control-flow.
1935 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1939 /* We don't use this
1940 * Note: an ast-representation using the comma-operator
1941 * of the form: (a, b, c) = x should not assign to c...
1944 compile_error(ast_ctx(self), "not an l-value (code-block)");
1948 if (self->expression.outr) {
1949 *out = self->expression.outr;
1953 /* output is NULL at first, we'll have each expression
1954 * assign to out output, thus, a comma-operator represention
1955 * using an ast_block will return the last generated value,
1956 * so: (b, c) + a executed both b and c, and returns c,
1957 * which is then added to a.
1961 /* generate locals */
1962 for (i = 0; i < vec_size(self->locals); ++i)
1964 if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1965 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1966 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1971 for (i = 0; i < vec_size(self->exprs); ++i)
1973 ast_expression_codegen *gen;
1974 if (func->curblock->final && !starts_a_label(self->exprs[i])) {
1975 if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
1979 gen = self->exprs[i]->codegen;
1980 if (!(*gen)(self->exprs[i], func, false, out))
1984 self->expression.outr = *out;
1989 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1991 ast_expression_codegen *cgen;
1992 ir_value *left = NULL;
1993 ir_value *right = NULL;
1997 ast_array_index *ai = NULL;
1999 if (lvalue && self->expression.outl) {
2000 *out = self->expression.outl;
2004 if (!lvalue && self->expression.outr) {
2005 *out = self->expression.outr;
2009 if (ast_istype(self->dest, ast_array_index))
2012 ai = (ast_array_index*)self->dest;
2013 idx = (ast_value*)ai->index;
2015 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2020 /* we need to call the setter */
2021 ir_value *iridx, *funval;
2025 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2029 arr = (ast_value*)ai->array;
2030 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2031 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2035 cgen = idx->expression.codegen;
2036 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2039 cgen = arr->setter->expression.codegen;
2040 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2043 cgen = self->source->codegen;
2044 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2047 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2050 ir_call_param(call, iridx);
2051 ir_call_param(call, right);
2052 self->expression.outr = right;
2058 cgen = self->dest->codegen;
2060 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
2062 self->expression.outl = left;
2064 cgen = self->source->codegen;
2066 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2069 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2071 self->expression.outr = right;
2074 /* Theoretically, an assinment returns its left side as an
2075 * lvalue, if we don't need an lvalue though, we return
2076 * the right side as an rvalue, otherwise we have to
2077 * somehow know whether or not we need to dereference the pointer
2078 * on the left side - that is: OP_LOAD if it was an address.
2079 * Also: in original QC we cannot OP_LOADP *anyway*.
2081 *out = (lvalue ? left : right);
2086 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2088 ast_expression_codegen *cgen;
2089 ir_value *left, *right;
2091 /* A binary operation cannot yield an l-value */
2093 compile_error(ast_ctx(self), "not an l-value (binop)");
2097 if (self->expression.outr) {
2098 *out = self->expression.outr;
2102 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2103 (self->op == INSTR_AND || self->op == INSTR_OR))
2105 /* NOTE: The short-logic path will ignore right_first */
2107 /* short circuit evaluation */
2108 ir_block *other, *merge;
2109 ir_block *from_left, *from_right;
2113 /* prepare end-block */
2114 merge_id = vec_size(func->ir_func->blocks);
2115 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2117 /* generate the left expression */
2118 cgen = self->left->codegen;
2119 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2121 /* remember the block */
2122 from_left = func->curblock;
2124 /* create a new block for the right expression */
2125 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2126 if (self->op == INSTR_AND) {
2127 /* on AND: left==true -> other */
2128 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2131 /* on OR: left==false -> other */
2132 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2135 /* use the likely flag */
2136 vec_last(func->curblock->instr)->likely = true;
2138 /* enter the right-expression's block */
2139 func->curblock = other;
2141 cgen = self->right->codegen;
2142 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2144 /* remember block */
2145 from_right = func->curblock;
2147 /* jump to the merge block */
2148 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2151 vec_remove(func->ir_func->blocks, merge_id, 1);
2152 vec_push(func->ir_func->blocks, merge);
2154 func->curblock = merge;
2155 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2156 ast_function_label(func, "sce_value"),
2157 self->expression.vtype);
2158 ir_phi_add(phi, from_left, left);
2159 ir_phi_add(phi, from_right, right);
2160 *out = ir_phi_value(phi);
2164 if (!OPTS_FLAG(PERL_LOGIC)) {
2166 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2167 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2168 ast_function_label(func, "sce_bool_v"),
2172 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2173 ast_function_label(func, "sce_bool"),
2178 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2179 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2180 ast_function_label(func, "sce_bool_s"),
2184 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2185 ast_function_label(func, "sce_bool"),
2191 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2192 ast_function_label(func, "sce_bool"),
2193 INSTR_AND, *out, *out);
2199 self->expression.outr = *out;
2200 codegen_output_type(self, *out);
2204 if (self->right_first) {
2205 cgen = self->right->codegen;
2206 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2208 cgen = self->left->codegen;
2209 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2212 cgen = self->left->codegen;
2213 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2215 cgen = self->right->codegen;
2216 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2220 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2221 self->op, left, right);
2224 self->expression.outr = *out;
2225 codegen_output_type(self, *out);
2230 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2232 ast_expression_codegen *cgen;
2233 ir_value *leftl = NULL, *leftr, *right, *bin;
2237 ast_array_index *ai = NULL;
2238 ir_value *iridx = NULL;
2240 if (lvalue && self->expression.outl) {
2241 *out = self->expression.outl;
2245 if (!lvalue && self->expression.outr) {
2246 *out = self->expression.outr;
2250 if (ast_istype(self->dest, ast_array_index))
2253 ai = (ast_array_index*)self->dest;
2254 idx = (ast_value*)ai->index;
2256 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2260 /* for a binstore we need both an lvalue and an rvalue for the left side */
2261 /* rvalue of destination! */
2263 cgen = idx->expression.codegen;
2264 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2267 cgen = self->dest->codegen;
2268 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2271 /* source as rvalue only */
2272 cgen = self->source->codegen;
2273 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2276 /* now the binary */
2277 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2278 self->opbin, leftr, right);
2279 self->expression.outr = bin;
2283 /* we need to call the setter */
2288 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2292 arr = (ast_value*)ai->array;
2293 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2294 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2298 cgen = arr->setter->expression.codegen;
2299 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2302 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2305 ir_call_param(call, iridx);
2306 ir_call_param(call, bin);
2307 self->expression.outr = bin;
2309 /* now store them */
2310 cgen = self->dest->codegen;
2311 /* lvalue of destination */
2312 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2314 self->expression.outl = leftl;
2316 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2318 self->expression.outr = bin;
2321 /* Theoretically, an assinment returns its left side as an
2322 * lvalue, if we don't need an lvalue though, we return
2323 * the right side as an rvalue, otherwise we have to
2324 * somehow know whether or not we need to dereference the pointer
2325 * on the left side - that is: OP_LOAD if it was an address.
2326 * Also: in original QC we cannot OP_LOADP *anyway*.
2328 *out = (lvalue ? leftl : bin);
2333 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2335 ast_expression_codegen *cgen;
2338 /* An unary operation cannot yield an l-value */
2340 compile_error(ast_ctx(self), "not an l-value (binop)");
2344 if (self->expression.outr) {
2345 *out = self->expression.outr;
2349 cgen = self->operand->codegen;
2351 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2354 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2358 self->expression.outr = *out;
2363 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2365 ast_expression_codegen *cgen;
2370 /* In the context of a return operation, we don't actually return
2374 compile_error(ast_ctx(self), "return-expression is not an l-value");
2378 if (self->expression.outr) {
2379 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2382 self->expression.outr = (ir_value*)1;
2384 if (self->operand) {
2385 cgen = self->operand->codegen;
2387 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2390 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2393 if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2400 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2402 ast_expression_codegen *cgen;
2403 ir_value *ent, *field;
2405 /* This function needs to take the 'lvalue' flag into account!
2406 * As lvalue we provide a field-pointer, as rvalue we provide the
2410 if (lvalue && self->expression.outl) {
2411 *out = self->expression.outl;
2415 if (!lvalue && self->expression.outr) {
2416 *out = self->expression.outr;
2420 cgen = self->entity->codegen;
2421 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2424 cgen = self->field->codegen;
2425 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2430 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2433 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2434 ent, field, self->expression.vtype);
2435 /* Done AFTER error checking:
2436 codegen_output_type(self, *out);
2440 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2441 (lvalue ? "ADDRESS" : "FIELD"),
2442 type_name[self->expression.vtype]);
2446 codegen_output_type(self, *out);
2449 self->expression.outl = *out;
2451 self->expression.outr = *out;
2453 /* Hm that should be it... */
2457 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2459 ast_expression_codegen *cgen;
2462 /* in QC this is always an lvalue */
2463 if (lvalue && self->rvalue) {
2464 compile_error(ast_ctx(self), "not an l-value (member access)");
2467 if (self->expression.outl) {
2468 *out = self->expression.outl;
2472 cgen = self->owner->codegen;
2473 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2476 if (vec->vtype != TYPE_VECTOR &&
2477 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2482 *out = ir_value_vector_member(vec, self->field);
2483 self->expression.outl = *out;
2485 return (*out != NULL);
2488 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2493 if (!lvalue && self->expression.outr) {
2494 *out = self->expression.outr;
2497 if (lvalue && self->expression.outl) {
2498 *out = self->expression.outl;
2502 if (!ast_istype(self->array, ast_value)) {
2503 compile_error(ast_ctx(self), "array indexing this way is not supported");
2504 /* note this would actually be pointer indexing because the left side is
2505 * not an actual array but (hopefully) an indexable expression.
2506 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2507 * support this path will be filled.
2512 arr = (ast_value*)self->array;
2513 idx = (ast_value*)self->index;
2515 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2516 /* Time to use accessor functions */
2517 ast_expression_codegen *cgen;
2518 ir_value *iridx, *funval;
2522 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2527 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2531 cgen = self->index->codegen;
2532 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2535 cgen = arr->getter->expression.codegen;
2536 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2539 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2542 ir_call_param(call, iridx);
2544 *out = ir_call_value(call);
2545 self->expression.outr = *out;
2546 (*out)->vtype = self->expression.vtype;
2547 codegen_output_type(self, *out);
2551 if (idx->expression.vtype == TYPE_FLOAT) {
2552 unsigned int arridx = idx->constval.vfloat;
2553 if (arridx >= self->array->count)
2555 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2558 *out = arr->ir_values[arridx];
2560 else if (idx->expression.vtype == TYPE_INTEGER) {
2561 unsigned int arridx = idx->constval.vint;
2562 if (arridx >= self->array->count)
2564 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2567 *out = arr->ir_values[arridx];
2570 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2573 (*out)->vtype = self->expression.vtype;
2574 codegen_output_type(self, *out);
2578 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2582 compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2587 compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2591 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2593 ast_expression_codegen *cgen;
2601 ir_block *ontrue_endblock = NULL;
2602 ir_block *onfalse_endblock = NULL;
2603 ir_block *merge = NULL;
2606 /* We don't output any value, thus also don't care about r/lvalue */
2610 if (self->expression.outr) {
2611 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2614 self->expression.outr = (ir_value*)1;
2616 /* generate the condition */
2617 cgen = self->cond->codegen;
2618 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2620 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2621 cond = func->curblock;
2623 /* try constant folding away the condition */
2624 if ((fold = fold_cond_ifthen(condval, func, self)) != -1)
2627 if (self->on_true) {
2628 /* create on-true block */
2629 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2633 /* enter the block */
2634 func->curblock = ontrue;
2637 cgen = self->on_true->codegen;
2638 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2641 /* we now need to work from the current endpoint */
2642 ontrue_endblock = func->curblock;
2647 if (self->on_false) {
2648 /* create on-false block */
2649 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2653 /* enter the block */
2654 func->curblock = onfalse;
2657 cgen = self->on_false->codegen;
2658 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2661 /* we now need to work from the current endpoint */
2662 onfalse_endblock = func->curblock;
2666 /* Merge block were they all merge in to */
2667 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2669 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2672 /* add jumps ot the merge block */
2673 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2675 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2678 /* Now enter the merge block */
2679 func->curblock = merge;
2682 /* we create the if here, that way all blocks are ordered :)
2684 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2685 (ontrue ? ontrue : merge),
2686 (onfalse ? onfalse : merge)))
2694 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2696 ast_expression_codegen *cgen;
2699 ir_value *trueval, *falseval;
2702 ir_block *cond = func->curblock;
2703 ir_block *cond_out = NULL;
2704 ir_block *ontrue, *ontrue_out = NULL;
2705 ir_block *onfalse, *onfalse_out = NULL;
2709 /* Ternary can never create an lvalue... */
2713 /* In theory it shouldn't be possible to pass through a node twice, but
2714 * in case we add any kind of optimization pass for the AST itself, it
2715 * may still happen, thus we remember a created ir_value and simply return one
2716 * if it already exists.
2718 if (self->expression.outr) {
2719 *out = self->expression.outr;
2723 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2725 /* generate the condition */
2726 func->curblock = cond;
2727 cgen = self->cond->codegen;
2728 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2730 cond_out = func->curblock;
2732 /* try constant folding away the condition */
2733 if ((fold = fold_cond_ternary(condval, func, self)) != -1)
2736 /* create on-true block */
2737 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2742 /* enter the block */
2743 func->curblock = ontrue;
2746 cgen = self->on_true->codegen;
2747 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2750 ontrue_out = func->curblock;
2753 /* create on-false block */
2754 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2759 /* enter the block */
2760 func->curblock = onfalse;
2763 cgen = self->on_false->codegen;
2764 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2767 onfalse_out = func->curblock;
2770 /* create merge block */
2771 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2774 /* jump to merge block */
2775 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2777 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2780 /* create if instruction */
2781 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2784 /* Now enter the merge block */
2785 func->curblock = merge;
2787 /* Here, now, we need a PHI node
2788 * but first some sanity checking...
2790 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2791 /* error("ternary with different types on the two sides"); */
2792 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2797 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2799 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2802 ir_phi_add(phi, ontrue_out, trueval);
2803 ir_phi_add(phi, onfalse_out, falseval);
2805 self->expression.outr = ir_phi_value(phi);
2806 *out = self->expression.outr;
2808 codegen_output_type(self, *out);
2813 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2815 ast_expression_codegen *cgen;
2817 ir_value *dummy = NULL;
2818 ir_value *precond = NULL;
2819 ir_value *postcond = NULL;
2821 /* Since we insert some jumps "late" so we have blocks
2822 * ordered "nicely", we need to keep track of the actual end-blocks
2823 * of expressions to add the jumps to.
2825 ir_block *bbody = NULL, *end_bbody = NULL;
2826 ir_block *bprecond = NULL, *end_bprecond = NULL;
2827 ir_block *bpostcond = NULL, *end_bpostcond = NULL;
2828 ir_block *bincrement = NULL, *end_bincrement = NULL;
2829 ir_block *bout = NULL, *bin = NULL;
2831 /* let's at least move the outgoing block to the end */
2834 /* 'break' and 'continue' need to be able to find the right blocks */
2835 ir_block *bcontinue = NULL;
2836 ir_block *bbreak = NULL;
2838 ir_block *tmpblock = NULL;
2843 if (self->expression.outr) {
2844 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2847 self->expression.outr = (ir_value*)1;
2850 * Should we ever need some kind of block ordering, better make this function
2851 * move blocks around than write a block ordering algorithm later... after all
2852 * the ast and ir should work together, not against each other.
2855 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2856 * anyway if for example it contains a ternary.
2860 cgen = self->initexpr->codegen;
2861 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2865 /* Store the block from which we enter this chaos */
2866 bin = func->curblock;
2868 /* The pre-loop condition needs its own block since we
2869 * need to be able to jump to the start of that expression.
2873 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2877 /* the pre-loop-condition the least important place to 'continue' at */
2878 bcontinue = bprecond;
2881 func->curblock = bprecond;
2884 cgen = self->precond->codegen;
2885 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2888 end_bprecond = func->curblock;
2890 bprecond = end_bprecond = NULL;
2893 /* Now the next blocks won't be ordered nicely, but we need to
2894 * generate them this early for 'break' and 'continue'.
2896 if (self->increment) {
2897 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2900 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2902 bincrement = end_bincrement = NULL;
2905 if (self->postcond) {
2906 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2909 bcontinue = bpostcond; /* postcond comes before the increment */
2911 bpostcond = end_bpostcond = NULL;
2914 bout_id = vec_size(func->ir_func->blocks);
2915 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2920 /* The loop body... */
2921 /* if (self->body) */
2923 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2928 func->curblock = bbody;
2930 vec_push(func->breakblocks, bbreak);
2932 vec_push(func->continueblocks, bcontinue);
2934 vec_push(func->continueblocks, bbody);
2938 cgen = self->body->codegen;
2939 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2943 end_bbody = func->curblock;
2944 vec_pop(func->breakblocks);
2945 vec_pop(func->continueblocks);
2948 /* post-loop-condition */
2952 func->curblock = bpostcond;
2955 cgen = self->postcond->codegen;
2956 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2959 end_bpostcond = func->curblock;
2962 /* The incrementor */
2963 if (self->increment)
2966 func->curblock = bincrement;
2969 cgen = self->increment->codegen;
2970 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2973 end_bincrement = func->curblock;
2976 /* In any case now, we continue from the outgoing block */
2977 func->curblock = bout;
2979 /* Now all blocks are in place */
2980 /* From 'bin' we jump to whatever comes first */
2981 if (bprecond) tmpblock = bprecond;
2982 else tmpblock = bbody; /* can never be null */
2985 else if (bpostcond) tmpblock = bpostcond;
2986 else tmpblock = bout;
2989 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2995 ir_block *ontrue, *onfalse;
2996 ontrue = bbody; /* can never be null */
2998 /* all of this is dead code
2999 else if (bincrement) ontrue = bincrement;
3000 else ontrue = bpostcond;
3004 if (self->pre_not) {
3009 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
3016 if (bincrement) tmpblock = bincrement;
3017 else if (bpostcond) tmpblock = bpostcond;
3018 else if (bprecond) tmpblock = bprecond;
3019 else tmpblock = bbody;
3020 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
3024 /* from increment */
3027 if (bpostcond) tmpblock = bpostcond;
3028 else if (bprecond) tmpblock = bprecond;
3029 else if (bbody) tmpblock = bbody;
3030 else tmpblock = bout;
3031 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
3038 ir_block *ontrue, *onfalse;
3039 if (bprecond) ontrue = bprecond;
3040 else ontrue = bbody; /* can never be null */
3042 /* all of this is dead code
3043 else if (bincrement) ontrue = bincrement;
3044 else ontrue = bpostcond;
3048 if (self->post_not) {
3053 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
3057 /* Move 'bout' to the end */
3058 vec_remove(func->ir_func->blocks, bout_id, 1);
3059 vec_push(func->ir_func->blocks, bout);
3064 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
3071 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3075 if (self->expression.outr) {
3076 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3079 self->expression.outr = (ir_value*)1;
3081 if (self->is_continue)
3082 target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
3084 target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
3087 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3091 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3096 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3098 ast_expression_codegen *cgen;
3100 ast_switch_case *def_case = NULL;
3101 ir_block *def_bfall = NULL;
3102 ir_block *def_bfall_to = NULL;
3103 bool set_def_bfall_to = false;
3105 ir_value *dummy = NULL;
3106 ir_value *irop = NULL;
3107 ir_block *bout = NULL;
3108 ir_block *bfall = NULL;
3116 compile_error(ast_ctx(self), "switch expression is not an l-value");
3120 if (self->expression.outr) {
3121 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3124 self->expression.outr = (ir_value*)1;
3129 cgen = self->operand->codegen;
3130 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3133 if (!vec_size(self->cases))
3136 cmpinstr = type_eq_instr[irop->vtype];
3137 if (cmpinstr >= VINSTR_END) {
3138 ast_type_to_string(self->operand, typestr, sizeof(typestr));
3139 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3143 bout_id = vec_size(func->ir_func->blocks);
3144 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3148 /* setup the break block */
3149 vec_push(func->breakblocks, bout);
3151 /* Now create all cases */
3152 for (c = 0; c < vec_size(self->cases); ++c) {
3153 ir_value *cond, *val;
3154 ir_block *bcase, *bnot;
3157 ast_switch_case *swcase = &self->cases[c];
3159 if (swcase->value) {
3160 /* A regular case */
3161 /* generate the condition operand */
3162 cgen = swcase->value->codegen;
3163 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3165 /* generate the condition */
3166 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3170 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3171 bnot_id = vec_size(func->ir_func->blocks);
3172 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3173 if (!bcase || !bnot)
3175 if (set_def_bfall_to) {
3176 set_def_bfall_to = false;
3177 def_bfall_to = bcase;
3179 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3182 /* Make the previous case-end fall through */
3183 if (bfall && !bfall->final) {
3184 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3188 /* enter the case */
3189 func->curblock = bcase;
3190 cgen = swcase->code->codegen;
3191 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3194 /* remember this block to fall through from */
3195 bfall = func->curblock;
3197 /* enter the else and move it down */
3198 func->curblock = bnot;
3199 vec_remove(func->ir_func->blocks, bnot_id, 1);
3200 vec_push(func->ir_func->blocks, bnot);
3202 /* The default case */
3203 /* Remember where to fall through from: */
3206 /* remember which case it was */
3208 /* And the next case will be remembered */
3209 set_def_bfall_to = true;
3213 /* Jump from the last bnot to bout */
3214 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3216 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3221 /* If there was a default case, put it down here */
3225 /* No need to create an extra block */
3226 bcase = func->curblock;
3228 /* Insert the fallthrough jump */
3229 if (def_bfall && !def_bfall->final) {
3230 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3234 /* Now generate the default code */
3235 cgen = def_case->code->codegen;
3236 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3239 /* see if we need to fall through */
3240 if (def_bfall_to && !func->curblock->final)
3242 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3247 /* Jump from the last bnot to bout */
3248 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3250 /* enter the outgoing block */
3251 func->curblock = bout;
3253 /* restore the break block */
3254 vec_pop(func->breakblocks);
3256 /* Move 'bout' to the end, it's nicer */
3257 vec_remove(func->ir_func->blocks, bout_id, 1);
3258 vec_push(func->ir_func->blocks, bout);
3263 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3268 if (self->undefined) {
3269 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3275 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3279 /* simply create a new block and jump to it */
3280 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3281 if (!self->irblock) {
3282 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3285 if (!func->curblock->final) {
3286 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3290 /* enter the new block */
3291 func->curblock = self->irblock;
3293 /* Generate all the leftover gotos */
3294 for (i = 0; i < vec_size(self->gotos); ++i) {
3295 if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3302 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3306 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3310 if (self->target->irblock) {
3311 if (self->irblock_from) {
3312 /* we already tried once, this is the callback */
3313 self->irblock_from->final = false;
3314 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3315 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3321 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3322 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3329 /* the target has not yet been created...
3330 * close this block in a sneaky way:
3332 func->curblock->final = true;
3333 self->irblock_from = func->curblock;
3334 ast_label_register_goto(self->target, self);
3340 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3342 ast_expression_codegen *cgen;
3344 ir_instr *callinstr;
3347 ir_value *funval = NULL;
3349 /* return values are never lvalues */
3351 compile_error(ast_ctx(self), "not an l-value (function call)");
3355 if (self->expression.outr) {
3356 *out = self->expression.outr;
3360 cgen = self->func->codegen;
3361 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3369 for (i = 0; i < vec_size(self->params); ++i)
3372 ast_expression *expr = self->params[i];
3374 cgen = expr->codegen;
3375 if (!(*cgen)(expr, func, false, ¶m))
3379 vec_push(params, param);
3382 /* varargs counter */
3383 if (self->va_count) {
3385 ir_builder *builder = func->curblock->owner->owner;
3386 cgen = self->va_count->codegen;
3387 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3389 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3390 ir_builder_get_va_count(builder), va_count))
3396 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3397 ast_function_label(func, "call"),
3398 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3402 for (i = 0; i < vec_size(params); ++i) {
3403 ir_call_param(callinstr, params[i]);
3406 *out = ir_call_value(callinstr);
3407 self->expression.outr = *out;
3409 codegen_output_type(self, *out);