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)
441 ast_instantiate(ast_binary, ctx, ast_binary_delete);
442 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
447 self->right_first = false;
449 ast_propagate_effects(self, left);
450 ast_propagate_effects(self, right);
452 if (op >= INSTR_EQ_F && op <= INSTR_GT)
453 self->expression.vtype = TYPE_FLOAT;
454 else if (op == INSTR_AND || op == INSTR_OR) {
455 if (OPTS_FLAG(PERL_LOGIC))
456 ast_type_adopt(self, right);
458 self->expression.vtype = TYPE_FLOAT;
460 else if (op == INSTR_BITAND || op == INSTR_BITOR)
461 self->expression.vtype = TYPE_FLOAT;
462 else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
463 self->expression.vtype = TYPE_VECTOR;
464 else if (op == INSTR_MUL_V)
465 self->expression.vtype = TYPE_FLOAT;
467 self->expression.vtype = left->vtype;
470 self->refs = AST_REF_ALL;
475 void ast_binary_delete(ast_binary *self)
477 if (self->refs & AST_REF_LEFT) ast_unref(self->left);
478 if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
480 ast_expression_delete((ast_expression*)self);
484 ast_binstore* ast_binstore_new(lex_ctx_t ctx, int storop, int op,
485 ast_expression* left, ast_expression* right)
487 ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
488 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
490 ast_side_effects(self) = true;
492 self->opstore = storop;
495 self->source = right;
497 self->keep_dest = false;
499 ast_type_adopt(self, left);
503 void ast_binstore_delete(ast_binstore *self)
505 if (!self->keep_dest)
506 ast_unref(self->dest);
507 ast_unref(self->source);
508 ast_expression_delete((ast_expression*)self);
512 ast_unary* ast_unary_new(lex_ctx_t ctx, int op,
513 ast_expression *expr)
515 ast_instantiate(ast_unary, ctx, ast_unary_delete);
516 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
519 self->operand = expr;
521 ast_propagate_effects(self, expr);
523 if (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) {
524 self->expression.vtype = TYPE_FLOAT;
526 compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
531 void ast_unary_delete(ast_unary *self)
533 if (self->operand) ast_unref(self->operand);
534 ast_expression_delete((ast_expression*)self);
538 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
540 ast_instantiate(ast_return, ctx, ast_return_delete);
541 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
543 self->operand = expr;
546 ast_propagate_effects(self, expr);
551 void ast_return_delete(ast_return *self)
554 ast_unref(self->operand);
555 ast_expression_delete((ast_expression*)self);
559 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
561 if (field->vtype != TYPE_FIELD) {
562 compile_error(ctx, "ast_entfield_new with expression not of type field");
565 return ast_entfield_new_force(ctx, entity, field, field->next);
568 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
570 ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
574 /* Error: field has no type... */
578 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
580 self->entity = entity;
582 ast_propagate_effects(self, entity);
583 ast_propagate_effects(self, field);
585 ast_type_adopt(self, outtype);
589 void ast_entfield_delete(ast_entfield *self)
591 ast_unref(self->entity);
592 ast_unref(self->field);
593 ast_expression_delete((ast_expression*)self);
597 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
599 ast_instantiate(ast_member, ctx, ast_member_delete);
605 if (owner->vtype != TYPE_VECTOR &&
606 owner->vtype != TYPE_FIELD) {
607 compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
612 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
613 self->expression.node.keep = true; /* keep */
615 if (owner->vtype == TYPE_VECTOR) {
616 self->expression.vtype = TYPE_FLOAT;
617 self->expression.next = NULL;
619 self->expression.vtype = TYPE_FIELD;
620 self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
623 self->rvalue = false;
625 ast_propagate_effects(self, owner);
629 self->name = util_strdup(name);
636 void ast_member_delete(ast_member *self)
638 /* The owner is always an ast_value, which has .keep=true,
639 * also: ast_members are usually deleted after the owner, thus
640 * this will cause invalid access
641 ast_unref(self->owner);
642 * once we allow (expression).x to access a vector-member, we need
643 * to change this: preferably by creating an alternate ast node for this
644 * purpose that is not garbage-collected.
646 ast_expression_delete((ast_expression*)self);
651 bool ast_member_set_name(ast_member *self, const char *name)
654 mem_d((void*)self->name);
655 self->name = util_strdup(name);
659 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
661 ast_expression *outtype;
662 ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
664 outtype = array->next;
667 /* Error: field has no type... */
671 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
675 ast_propagate_effects(self, array);
676 ast_propagate_effects(self, index);
678 ast_type_adopt(self, outtype);
679 if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
680 if (self->expression.vtype != TYPE_ARRAY) {
681 compile_error(ast_ctx(self), "array_index node on type");
682 ast_array_index_delete(self);
685 self->array = outtype;
686 self->expression.vtype = TYPE_FIELD;
692 void ast_array_index_delete(ast_array_index *self)
695 ast_unref(self->array);
697 ast_unref(self->index);
698 ast_expression_delete((ast_expression*)self);
702 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
704 ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete);
705 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
707 self->expression.vtype = TYPE_NOEXPR;
711 void ast_argpipe_delete(ast_argpipe *self)
714 ast_unref(self->index);
715 ast_expression_delete((ast_expression*)self);
719 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
721 ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
722 if (!ontrue && !onfalse) {
723 /* because it is invalid */
727 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
730 self->on_true = ontrue;
731 self->on_false = onfalse;
732 ast_propagate_effects(self, cond);
734 ast_propagate_effects(self, ontrue);
736 ast_propagate_effects(self, onfalse);
741 void ast_ifthen_delete(ast_ifthen *self)
743 ast_unref(self->cond);
745 ast_unref(self->on_true);
747 ast_unref(self->on_false);
748 ast_expression_delete((ast_expression*)self);
752 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
754 ast_expression *exprtype = ontrue;
755 ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
756 /* This time NEITHER must be NULL */
757 if (!ontrue || !onfalse) {
761 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
764 self->on_true = ontrue;
765 self->on_false = onfalse;
766 ast_propagate_effects(self, cond);
767 ast_propagate_effects(self, ontrue);
768 ast_propagate_effects(self, onfalse);
770 if (ontrue->vtype == TYPE_NIL)
772 ast_type_adopt(self, exprtype);
777 void ast_ternary_delete(ast_ternary *self)
779 /* the if()s are only there because computed-gotos can set them
782 if (self->cond) ast_unref(self->cond);
783 if (self->on_true) ast_unref(self->on_true);
784 if (self->on_false) ast_unref(self->on_false);
785 ast_expression_delete((ast_expression*)self);
789 ast_loop* ast_loop_new(lex_ctx_t ctx,
790 ast_expression *initexpr,
791 ast_expression *precond, bool pre_not,
792 ast_expression *postcond, bool post_not,
793 ast_expression *increment,
794 ast_expression *body)
796 ast_instantiate(ast_loop, ctx, ast_loop_delete);
797 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
799 self->initexpr = initexpr;
800 self->precond = precond;
801 self->postcond = postcond;
802 self->increment = increment;
805 self->pre_not = pre_not;
806 self->post_not = post_not;
809 ast_propagate_effects(self, initexpr);
811 ast_propagate_effects(self, precond);
813 ast_propagate_effects(self, postcond);
815 ast_propagate_effects(self, increment);
817 ast_propagate_effects(self, body);
822 void ast_loop_delete(ast_loop *self)
825 ast_unref(self->initexpr);
827 ast_unref(self->precond);
829 ast_unref(self->postcond);
831 ast_unref(self->increment);
833 ast_unref(self->body);
834 ast_expression_delete((ast_expression*)self);
838 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
840 ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
841 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
843 self->is_continue = iscont;
844 self->levels = levels;
849 void ast_breakcont_delete(ast_breakcont *self)
851 ast_expression_delete((ast_expression*)self);
855 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
857 ast_instantiate(ast_switch, ctx, ast_switch_delete);
858 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
863 ast_propagate_effects(self, op);
868 void ast_switch_delete(ast_switch *self)
871 ast_unref(self->operand);
873 for (i = 0; i < vec_size(self->cases); ++i) {
874 if (self->cases[i].value)
875 ast_unref(self->cases[i].value);
876 ast_unref(self->cases[i].code);
878 vec_free(self->cases);
880 ast_expression_delete((ast_expression*)self);
884 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
886 ast_instantiate(ast_label, ctx, ast_label_delete);
887 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
889 self->expression.vtype = TYPE_NOEXPR;
891 self->name = util_strdup(name);
892 self->irblock = NULL;
894 self->undefined = undefined;
899 void ast_label_delete(ast_label *self)
901 mem_d((void*)self->name);
902 vec_free(self->gotos);
903 ast_expression_delete((ast_expression*)self);
907 static void ast_label_register_goto(ast_label *self, ast_goto *g)
909 vec_push(self->gotos, g);
912 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
914 ast_instantiate(ast_goto, ctx, ast_goto_delete);
915 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
917 self->name = util_strdup(name);
919 self->irblock_from = NULL;
924 void ast_goto_delete(ast_goto *self)
926 mem_d((void*)self->name);
927 ast_expression_delete((ast_expression*)self);
931 void ast_goto_set_label(ast_goto *self, ast_label *label)
933 self->target = label;
936 ast_call* ast_call_new(lex_ctx_t ctx,
937 ast_expression *funcexpr)
939 ast_instantiate(ast_call, ctx, ast_call_delete);
940 if (!funcexpr->next) {
941 compile_error(ctx, "not a function");
945 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
947 ast_side_effects(self) = true;
950 self->func = funcexpr;
951 self->va_count = NULL;
953 ast_type_adopt(self, funcexpr->next);
958 void ast_call_delete(ast_call *self)
961 for (i = 0; i < vec_size(self->params); ++i)
962 ast_unref(self->params[i]);
963 vec_free(self->params);
966 ast_unref(self->func);
969 ast_unref(self->va_count);
971 ast_expression_delete((ast_expression*)self);
975 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
981 if (!va_type || !ast_compare_type(va_type, exp_type))
983 if (va_type && exp_type)
985 ast_type_to_string(va_type, tgot, sizeof(tgot));
986 ast_type_to_string(exp_type, texp, sizeof(texp));
987 if (OPTS_FLAG(UNSAFE_VARARGS)) {
988 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
989 "piped variadic argument differs in type: constrained to type %s, expected type %s",
993 compile_error(ast_ctx(self),
994 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1001 ast_type_to_string(exp_type, texp, sizeof(texp));
1002 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1003 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1004 "piped variadic argument may differ in type: expected type %s",
1008 compile_error(ast_ctx(self),
1009 "piped variadic argument may differ in type: expected type %s",
1018 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1024 const ast_expression *func = self->func;
1025 size_t count = vec_size(self->params);
1026 if (count > vec_size(func->params))
1027 count = vec_size(func->params);
1029 for (i = 0; i < count; ++i) {
1030 if (ast_istype(self->params[i], ast_argpipe)) {
1031 /* warn about type safety instead */
1033 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1036 if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->params[i]))
1039 else if (!ast_compare_type(self->params[i], (ast_expression*)(func->params[i])))
1041 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1042 ast_type_to_string((ast_expression*)func->params[i], texp, sizeof(texp));
1043 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1044 (unsigned int)(i+1), texp, tgot);
1045 /* we don't immediately return */
1049 count = vec_size(self->params);
1050 if (count > vec_size(func->params) && func->varparam) {
1051 for (; i < count; ++i) {
1052 if (ast_istype(self->params[i], ast_argpipe)) {
1053 /* warn about type safety instead */
1055 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1058 if (!ast_call_check_vararg(self, va_type, func->varparam))
1061 else if (!ast_compare_type(self->params[i], func->varparam))
1063 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1064 ast_type_to_string(func->varparam, texp, sizeof(texp));
1065 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1066 (unsigned int)(i+1), texp, tgot);
1067 /* we don't immediately return */
1075 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1076 ast_expression *dest, ast_expression *source)
1078 ast_instantiate(ast_store, ctx, ast_store_delete);
1079 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1081 ast_side_effects(self) = true;
1085 self->source = source;
1087 ast_type_adopt(self, dest);
1092 void ast_store_delete(ast_store *self)
1094 ast_unref(self->dest);
1095 ast_unref(self->source);
1096 ast_expression_delete((ast_expression*)self);
1100 ast_block* ast_block_new(lex_ctx_t ctx)
1102 ast_instantiate(ast_block, ctx, ast_block_delete);
1103 ast_expression_init((ast_expression*)self,
1104 (ast_expression_codegen*)&ast_block_codegen);
1106 self->locals = NULL;
1108 self->collect = NULL;
1113 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1115 ast_propagate_effects(self, e);
1116 vec_push(self->exprs, e);
1117 if (self->expression.next) {
1118 ast_delete(self->expression.next);
1119 self->expression.next = NULL;
1121 ast_type_adopt(self, e);
1125 void ast_block_collect(ast_block *self, ast_expression *expr)
1127 vec_push(self->collect, expr);
1128 expr->node.keep = true;
1131 void ast_block_delete(ast_block *self)
1134 for (i = 0; i < vec_size(self->exprs); ++i)
1135 ast_unref(self->exprs[i]);
1136 vec_free(self->exprs);
1137 for (i = 0; i < vec_size(self->locals); ++i)
1138 ast_delete(self->locals[i]);
1139 vec_free(self->locals);
1140 for (i = 0; i < vec_size(self->collect); ++i)
1141 ast_delete(self->collect[i]);
1142 vec_free(self->collect);
1143 ast_expression_delete((ast_expression*)self);
1147 void ast_block_set_type(ast_block *self, ast_expression *from)
1149 if (self->expression.next)
1150 ast_delete(self->expression.next);
1151 ast_type_adopt(self, from);
1154 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1156 ast_instantiate(ast_function, ctx, ast_function_delete);
1159 compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1161 } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1162 compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1164 (int)vtype->hasvalue,
1165 vtype->expression.vtype);
1169 self->vtype = vtype;
1170 self->name = name ? util_strdup(name) : NULL;
1171 self->blocks = NULL;
1173 self->labelcount = 0;
1176 self->ir_func = NULL;
1177 self->curblock = NULL;
1179 self->breakblocks = NULL;
1180 self->continueblocks = NULL;
1182 vtype->hasvalue = true;
1183 vtype->constval.vfunc = self;
1185 self->varargs = NULL;
1187 self->fixedparams = NULL;
1188 self->return_value = NULL;
1197 void ast_function_delete(ast_function *self)
1201 mem_d((void*)self->name);
1203 /* ast_value_delete(self->vtype); */
1204 self->vtype->hasvalue = false;
1205 self->vtype->constval.vfunc = NULL;
1206 /* We use unref - if it was stored in a global table it is supposed
1207 * to be deleted from *there*
1209 ast_unref(self->vtype);
1211 for (i = 0; i < vec_size(self->blocks); ++i)
1212 ast_delete(self->blocks[i]);
1213 vec_free(self->blocks);
1214 vec_free(self->breakblocks);
1215 vec_free(self->continueblocks);
1217 ast_delete(self->varargs);
1219 ast_delete(self->argc);
1220 if (self->fixedparams)
1221 ast_unref(self->fixedparams);
1222 if (self->return_value)
1223 ast_unref(self->return_value);
1227 const char* ast_function_label(ast_function *self, const char *prefix)
1233 if (!OPTS_OPTION_BOOL(OPTION_DUMP) &&
1234 !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1235 !OPTS_OPTION_BOOL(OPTION_DEBUG))
1240 id = (self->labelcount++);
1241 len = strlen(prefix);
1243 from = self->labelbuf + sizeof(self->labelbuf)-1;
1246 *from-- = (id%10) + '0';
1250 memcpy(from - len, prefix, len);
1254 /*********************************************************************/
1256 * by convention you must never pass NULL to the 'ir_value **out'
1257 * parameter. If you really don't care about the output, pass a dummy.
1258 * But I can't imagine a pituation where the output is truly unnecessary.
1261 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1263 if (out->vtype == TYPE_FIELD)
1264 out->fieldtype = self->next->vtype;
1265 if (out->vtype == TYPE_FUNCTION)
1266 out->outtype = self->next->vtype;
1269 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1271 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1275 if (self->expression.vtype == TYPE_NIL) {
1276 *out = func->ir_func->owner->nil;
1279 /* NOTE: This is the codegen for a variable used in an expression.
1280 * It is not the codegen to generate the value. For this purpose,
1281 * ast_local_codegen and ast_global_codegen are to be used before this
1282 * is executed. ast_function_codegen should take care of its locals,
1283 * and the ast-user should take care of ast_global_codegen to be used
1284 * on all the globals.
1287 char tname[1024]; /* typename is reserved in C++ */
1288 ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1289 compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1296 static bool ast_global_array_set(ast_value *self)
1298 size_t count = vec_size(self->initlist);
1301 if (count > self->expression.count) {
1302 compile_error(ast_ctx(self), "too many elements in initializer");
1303 count = self->expression.count;
1305 else if (count < self->expression.count) {
1307 compile_warning(ast_ctx(self), "not all elements are initialized");
1311 for (i = 0; i != count; ++i) {
1312 switch (self->expression.next->vtype) {
1314 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1318 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1322 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1326 /* we don't support them in any other place yet either */
1327 compile_error(ast_ctx(self), "TODO: nested arrays");
1330 /* this requiers a bit more work - similar to the fields I suppose */
1331 compile_error(ast_ctx(self), "global of type function not properly generated");
1334 if (!self->initlist[i].vfield) {
1335 compile_error(ast_ctx(self), "field constant without vfield set");
1338 if (!self->initlist[i].vfield->ir_v) {
1339 compile_error(ast_ctx(self), "field constant generated before its field");
1342 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1346 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1353 static bool check_array(ast_value *self, ast_value *array)
1355 if (array->expression.flags & AST_FLAG_ARRAY_INIT && !array->initlist) {
1356 compile_error(ast_ctx(self), "array without size: %s", self->name);
1359 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1360 if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1361 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1367 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1371 if (self->expression.vtype == TYPE_NIL) {
1372 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1376 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1378 ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1381 func->context = ast_ctx(self);
1382 func->value->context = ast_ctx(self);
1384 self->constval.vfunc->ir_func = func;
1385 self->ir_v = func->value;
1386 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1387 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1388 /* The function is filled later on ast_function_codegen... */
1392 if (isfield && self->expression.vtype == TYPE_FIELD) {
1393 ast_expression *fieldtype = self->expression.next;
1395 if (self->hasvalue) {
1396 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1400 if (fieldtype->vtype == TYPE_ARRAY) {
1405 ast_expression *elemtype;
1407 ast_value *array = (ast_value*)fieldtype;
1409 if (!ast_istype(fieldtype, ast_value)) {
1410 compile_error(ast_ctx(self), "internal error: ast_value required");
1414 if (!check_array(self, array))
1417 elemtype = array->expression.next;
1418 vtype = elemtype->vtype;
1420 v = ir_builder_create_field(ir, self->name, vtype);
1422 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1425 v->context = ast_ctx(self);
1426 v->unique_life = true;
1428 array->ir_v = self->ir_v = v;
1429 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1430 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1432 namelen = strlen(self->name);
1433 name = (char*)mem_a(namelen + 16);
1434 util_strncpy(name, self->name, namelen);
1436 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1437 array->ir_values[0] = v;
1438 for (ai = 1; ai < array->expression.count; ++ai) {
1439 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1440 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1441 if (!array->ir_values[ai]) {
1443 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1446 array->ir_values[ai]->context = ast_ctx(self);
1447 array->ir_values[ai]->unique_life = true;
1448 array->ir_values[ai]->locked = true;
1449 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1450 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1456 v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1459 v->context = ast_ctx(self);
1461 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1462 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1467 if (self->expression.vtype == TYPE_ARRAY) {
1472 ast_expression *elemtype = self->expression.next;
1473 int vtype = elemtype->vtype;
1475 if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1476 compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1480 /* same as with field arrays */
1481 if (!check_array(self, self))
1484 v = ir_builder_create_global(ir, self->name, vtype);
1486 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1489 v->context = ast_ctx(self);
1490 v->unique_life = true;
1492 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1493 v->flags |= IR_FLAG_INCLUDE_DEF;
1495 namelen = strlen(self->name);
1496 name = (char*)mem_a(namelen + 16);
1497 util_strncpy(name, self->name, namelen);
1499 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1500 self->ir_values[0] = v;
1501 for (ai = 1; ai < self->expression.count; ++ai) {
1502 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1503 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1504 if (!self->ir_values[ai]) {
1506 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1509 self->ir_values[ai]->context = ast_ctx(self);
1510 self->ir_values[ai]->unique_life = true;
1511 self->ir_values[ai]->locked = true;
1512 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1513 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1519 /* Arrays don't do this since there's no "array" value which spans across the
1522 v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1524 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1527 codegen_output_type(self, v);
1528 v->context = ast_ctx(self);
1531 /* link us to the ir_value */
1534 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1535 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1538 if (self->hasvalue) {
1539 switch (self->expression.vtype)
1542 if (!ir_value_set_float(v, self->constval.vfloat))
1546 if (!ir_value_set_vector(v, self->constval.vvec))
1550 if (!ir_value_set_string(v, self->constval.vstring))
1554 ast_global_array_set(self);
1557 compile_error(ast_ctx(self), "global of type function not properly generated");
1559 /* Cannot generate an IR value for a function,
1560 * need a pointer pointing to a function rather.
1563 if (!self->constval.vfield) {
1564 compile_error(ast_ctx(self), "field constant without vfield set");
1567 if (!self->constval.vfield->ir_v) {
1568 compile_error(ast_ctx(self), "field constant generated before its field");
1571 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1575 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1581 error: /* clean up */
1582 if(v) ir_value_delete(v);
1586 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1590 if (self->expression.vtype == TYPE_NIL) {
1591 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1595 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1597 /* Do we allow local functions? I think not...
1598 * this is NOT a function pointer atm.
1603 if (self->expression.vtype == TYPE_ARRAY) {
1608 ast_expression *elemtype = self->expression.next;
1609 int vtype = elemtype->vtype;
1611 func->flags |= IR_FLAG_HAS_ARRAYS;
1613 if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1614 compile_error(ast_ctx(self), "array-parameters are not supported");
1618 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1619 if (!check_array(self, self))
1622 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1623 if (!self->ir_values) {
1624 compile_error(ast_ctx(self), "failed to allocate array values");
1628 v = ir_function_create_local(func, self->name, vtype, param);
1630 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1633 v->context = ast_ctx(self);
1634 v->unique_life = true;
1637 namelen = strlen(self->name);
1638 name = (char*)mem_a(namelen + 16);
1639 util_strncpy(name, self->name, namelen);
1641 self->ir_values[0] = v;
1642 for (ai = 1; ai < self->expression.count; ++ai) {
1643 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1644 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1645 if (!self->ir_values[ai]) {
1646 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1649 self->ir_values[ai]->context = ast_ctx(self);
1650 self->ir_values[ai]->unique_life = true;
1651 self->ir_values[ai]->locked = true;
1657 v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1660 codegen_output_type(self, v);
1661 v->context = ast_ctx(self);
1664 /* A constant local... hmmm...
1665 * I suppose the IR will have to deal with this
1667 if (self->hasvalue) {
1668 switch (self->expression.vtype)
1671 if (!ir_value_set_float(v, self->constval.vfloat))
1675 if (!ir_value_set_vector(v, self->constval.vvec))
1679 if (!ir_value_set_string(v, self->constval.vstring))
1683 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1688 /* link us to the ir_value */
1692 if (!ast_generate_accessors(self, func->owner))
1696 error: /* clean up */
1701 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1704 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1705 if (!self->setter || !self->getter)
1707 for (i = 0; i < self->expression.count; ++i) {
1708 if (!self->ir_values) {
1709 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1712 if (!self->ir_values[i]) {
1713 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1716 if (self->ir_values[i]->life) {
1717 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1722 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1724 if (!ast_global_codegen (self->setter, ir, false) ||
1725 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1726 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1728 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1729 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1734 if (!ast_global_codegen (self->getter, ir, false) ||
1735 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1736 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1738 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1739 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1743 for (i = 0; i < self->expression.count; ++i) {
1744 vec_free(self->ir_values[i]->life);
1746 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1750 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1755 ast_expression_codegen *cgen;
1760 irf = self->ir_func;
1762 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1766 /* fill the parameter list */
1767 ec = &self->vtype->expression;
1768 for (i = 0; i < vec_size(ec->params); ++i)
1770 if (ec->params[i]->expression.vtype == TYPE_FIELD)
1771 vec_push(irf->params, ec->params[i]->expression.next->vtype);
1773 vec_push(irf->params, ec->params[i]->expression.vtype);
1774 if (!self->builtin) {
1775 if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1780 if (self->varargs) {
1781 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1783 irf->max_varargs = self->varargs->expression.count;
1786 if (self->builtin) {
1787 irf->builtin = self->builtin;
1791 /* have a local return value variable? */
1792 if (self->return_value) {
1793 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1797 if (!vec_size(self->blocks)) {
1798 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1802 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1803 if (!self->curblock) {
1804 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1812 if (!ast_local_codegen(self->argc, self->ir_func, true))
1814 cgen = self->argc->expression.codegen;
1815 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1817 cgen = self->fixedparams->expression.codegen;
1818 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1820 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1821 ast_function_label(self, "va_count"), INSTR_SUB_F,
1822 ir_builder_get_va_count(ir), fixed);
1825 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1832 for (i = 0; i < vec_size(self->blocks); ++i) {
1833 cgen = self->blocks[i]->expression.codegen;
1834 if (!(*cgen)((ast_expression*)self->blocks[i], self, false, &dummy))
1838 /* TODO: check return types */
1839 if (!self->curblock->final)
1841 if (!self->vtype->expression.next ||
1842 self->vtype->expression.next->vtype == TYPE_VOID)
1844 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1846 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1848 if (self->return_value) {
1849 cgen = self->return_value->expression.codegen;
1850 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1852 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1854 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1855 "control reaches end of non-void function (`%s`) via %s",
1856 self->name, self->curblock->label))
1860 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1866 /* Note, you will not see ast_block_codegen generate ir_blocks.
1867 * To the AST and the IR, blocks are 2 different things.
1868 * In the AST it represents a block of code, usually enclosed in
1869 * curly braces {...}.
1870 * While in the IR it represents a block in terms of control-flow.
1872 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1876 /* We don't use this
1877 * Note: an ast-representation using the comma-operator
1878 * of the form: (a, b, c) = x should not assign to c...
1881 compile_error(ast_ctx(self), "not an l-value (code-block)");
1885 if (self->expression.outr) {
1886 *out = self->expression.outr;
1890 /* output is NULL at first, we'll have each expression
1891 * assign to out output, thus, a comma-operator represention
1892 * using an ast_block will return the last generated value,
1893 * so: (b, c) + a executed both b and c, and returns c,
1894 * which is then added to a.
1898 /* generate locals */
1899 for (i = 0; i < vec_size(self->locals); ++i)
1901 if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1902 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1903 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1908 for (i = 0; i < vec_size(self->exprs); ++i)
1910 ast_expression_codegen *gen;
1911 if (func->curblock->final && !ast_istype(self->exprs[i], ast_label)) {
1912 if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
1916 gen = self->exprs[i]->codegen;
1917 if (!(*gen)(self->exprs[i], func, false, out))
1921 self->expression.outr = *out;
1926 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1928 ast_expression_codegen *cgen;
1929 ir_value *left = NULL;
1930 ir_value *right = NULL;
1934 ast_array_index *ai = NULL;
1936 if (lvalue && self->expression.outl) {
1937 *out = self->expression.outl;
1941 if (!lvalue && self->expression.outr) {
1942 *out = self->expression.outr;
1946 if (ast_istype(self->dest, ast_array_index))
1949 ai = (ast_array_index*)self->dest;
1950 idx = (ast_value*)ai->index;
1952 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
1957 /* we need to call the setter */
1958 ir_value *iridx, *funval;
1962 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1966 arr = (ast_value*)ai->array;
1967 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1968 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
1972 cgen = idx->expression.codegen;
1973 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1976 cgen = arr->setter->expression.codegen;
1977 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
1980 cgen = self->source->codegen;
1981 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1984 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
1987 ir_call_param(call, iridx);
1988 ir_call_param(call, right);
1989 self->expression.outr = right;
1995 cgen = self->dest->codegen;
1997 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
1999 self->expression.outl = left;
2001 cgen = self->source->codegen;
2003 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2006 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2008 self->expression.outr = right;
2011 /* Theoretically, an assinment returns its left side as an
2012 * lvalue, if we don't need an lvalue though, we return
2013 * the right side as an rvalue, otherwise we have to
2014 * somehow know whether or not we need to dereference the pointer
2015 * on the left side - that is: OP_LOAD if it was an address.
2016 * Also: in original QC we cannot OP_LOADP *anyway*.
2018 *out = (lvalue ? left : right);
2023 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2025 ast_expression_codegen *cgen;
2026 ir_value *left, *right;
2028 /* A binary operation cannot yield an l-value */
2030 compile_error(ast_ctx(self), "not an l-value (binop)");
2034 if (self->expression.outr) {
2035 *out = self->expression.outr;
2039 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2040 (self->op == INSTR_AND || self->op == INSTR_OR))
2042 /* NOTE: The short-logic path will ignore right_first */
2044 /* short circuit evaluation */
2045 ir_block *other, *merge;
2046 ir_block *from_left, *from_right;
2050 /* prepare end-block */
2051 merge_id = vec_size(func->ir_func->blocks);
2052 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2054 /* generate the left expression */
2055 cgen = self->left->codegen;
2056 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2058 /* remember the block */
2059 from_left = func->curblock;
2061 /* create a new block for the right expression */
2062 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2063 if (self->op == INSTR_AND) {
2064 /* on AND: left==true -> other */
2065 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2068 /* on OR: left==false -> other */
2069 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2072 /* use the likely flag */
2073 vec_last(func->curblock->instr)->likely = true;
2075 /* enter the right-expression's block */
2076 func->curblock = other;
2078 cgen = self->right->codegen;
2079 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2081 /* remember block */
2082 from_right = func->curblock;
2084 /* jump to the merge block */
2085 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2088 vec_remove(func->ir_func->blocks, merge_id, 1);
2089 vec_push(func->ir_func->blocks, merge);
2091 func->curblock = merge;
2092 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2093 ast_function_label(func, "sce_value"),
2094 self->expression.vtype);
2095 ir_phi_add(phi, from_left, left);
2096 ir_phi_add(phi, from_right, right);
2097 *out = ir_phi_value(phi);
2101 if (!OPTS_FLAG(PERL_LOGIC)) {
2103 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2104 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2105 ast_function_label(func, "sce_bool_v"),
2109 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2110 ast_function_label(func, "sce_bool"),
2115 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2116 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2117 ast_function_label(func, "sce_bool_s"),
2121 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2122 ast_function_label(func, "sce_bool"),
2128 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2129 ast_function_label(func, "sce_bool"),
2130 INSTR_AND, *out, *out);
2136 self->expression.outr = *out;
2137 codegen_output_type(self, *out);
2141 if (self->right_first) {
2142 cgen = self->right->codegen;
2143 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2145 cgen = self->left->codegen;
2146 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2149 cgen = self->left->codegen;
2150 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2152 cgen = self->right->codegen;
2153 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2157 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2158 self->op, left, right);
2161 self->expression.outr = *out;
2162 codegen_output_type(self, *out);
2167 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2169 ast_expression_codegen *cgen;
2170 ir_value *leftl = NULL, *leftr, *right, *bin;
2174 ast_array_index *ai = NULL;
2175 ir_value *iridx = NULL;
2177 if (lvalue && self->expression.outl) {
2178 *out = self->expression.outl;
2182 if (!lvalue && self->expression.outr) {
2183 *out = self->expression.outr;
2187 if (ast_istype(self->dest, ast_array_index))
2190 ai = (ast_array_index*)self->dest;
2191 idx = (ast_value*)ai->index;
2193 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2197 /* for a binstore we need both an lvalue and an rvalue for the left side */
2198 /* rvalue of destination! */
2200 cgen = idx->expression.codegen;
2201 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2204 cgen = self->dest->codegen;
2205 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2208 /* source as rvalue only */
2209 cgen = self->source->codegen;
2210 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2213 /* now the binary */
2214 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2215 self->opbin, leftr, right);
2216 self->expression.outr = bin;
2220 /* we need to call the setter */
2225 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2229 arr = (ast_value*)ai->array;
2230 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2231 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2235 cgen = arr->setter->expression.codegen;
2236 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2239 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2242 ir_call_param(call, iridx);
2243 ir_call_param(call, bin);
2244 self->expression.outr = bin;
2246 /* now store them */
2247 cgen = self->dest->codegen;
2248 /* lvalue of destination */
2249 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2251 self->expression.outl = leftl;
2253 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2255 self->expression.outr = bin;
2258 /* Theoretically, an assinment returns its left side as an
2259 * lvalue, if we don't need an lvalue though, we return
2260 * the right side as an rvalue, otherwise we have to
2261 * somehow know whether or not we need to dereference the pointer
2262 * on the left side - that is: OP_LOAD if it was an address.
2263 * Also: in original QC we cannot OP_LOADP *anyway*.
2265 *out = (lvalue ? leftl : bin);
2270 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2272 ast_expression_codegen *cgen;
2275 /* An unary operation cannot yield an l-value */
2277 compile_error(ast_ctx(self), "not an l-value (binop)");
2281 if (self->expression.outr) {
2282 *out = self->expression.outr;
2286 cgen = self->operand->codegen;
2288 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2291 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2295 self->expression.outr = *out;
2300 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2302 ast_expression_codegen *cgen;
2307 /* In the context of a return operation, we don't actually return
2311 compile_error(ast_ctx(self), "return-expression is not an l-value");
2315 if (self->expression.outr) {
2316 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2319 self->expression.outr = (ir_value*)1;
2321 if (self->operand) {
2322 cgen = self->operand->codegen;
2324 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2327 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2330 if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2337 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2339 ast_expression_codegen *cgen;
2340 ir_value *ent, *field;
2342 /* This function needs to take the 'lvalue' flag into account!
2343 * As lvalue we provide a field-pointer, as rvalue we provide the
2347 if (lvalue && self->expression.outl) {
2348 *out = self->expression.outl;
2352 if (!lvalue && self->expression.outr) {
2353 *out = self->expression.outr;
2357 cgen = self->entity->codegen;
2358 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2361 cgen = self->field->codegen;
2362 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2367 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2370 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2371 ent, field, self->expression.vtype);
2372 /* Done AFTER error checking:
2373 codegen_output_type(self, *out);
2377 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2378 (lvalue ? "ADDRESS" : "FIELD"),
2379 type_name[self->expression.vtype]);
2383 codegen_output_type(self, *out);
2386 self->expression.outl = *out;
2388 self->expression.outr = *out;
2390 /* Hm that should be it... */
2394 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2396 ast_expression_codegen *cgen;
2399 /* in QC this is always an lvalue */
2400 if (lvalue && self->rvalue) {
2401 compile_error(ast_ctx(self), "not an l-value (member access)");
2404 if (self->expression.outl) {
2405 *out = self->expression.outl;
2409 cgen = self->owner->codegen;
2410 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2413 if (vec->vtype != TYPE_VECTOR &&
2414 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2419 *out = ir_value_vector_member(vec, self->field);
2420 self->expression.outl = *out;
2422 return (*out != NULL);
2425 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2430 if (!lvalue && self->expression.outr) {
2431 *out = self->expression.outr;
2434 if (lvalue && self->expression.outl) {
2435 *out = self->expression.outl;
2439 if (!ast_istype(self->array, ast_value)) {
2440 compile_error(ast_ctx(self), "array indexing this way is not supported");
2441 /* note this would actually be pointer indexing because the left side is
2442 * not an actual array but (hopefully) an indexable expression.
2443 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2444 * support this path will be filled.
2449 arr = (ast_value*)self->array;
2450 idx = (ast_value*)self->index;
2452 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2453 /* Time to use accessor functions */
2454 ast_expression_codegen *cgen;
2455 ir_value *iridx, *funval;
2459 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2464 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2468 cgen = self->index->codegen;
2469 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2472 cgen = arr->getter->expression.codegen;
2473 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2476 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2479 ir_call_param(call, iridx);
2481 *out = ir_call_value(call);
2482 self->expression.outr = *out;
2483 (*out)->vtype = self->expression.vtype;
2484 codegen_output_type(self, *out);
2488 if (idx->expression.vtype == TYPE_FLOAT) {
2489 unsigned int arridx = idx->constval.vfloat;
2490 if (arridx >= self->array->count)
2492 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2495 *out = arr->ir_values[arridx];
2497 else if (idx->expression.vtype == TYPE_INTEGER) {
2498 unsigned int arridx = idx->constval.vint;
2499 if (arridx >= self->array->count)
2501 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2504 *out = arr->ir_values[arridx];
2507 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2510 (*out)->vtype = self->expression.vtype;
2511 codegen_output_type(self, *out);
2515 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2519 compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2524 compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2528 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2530 ast_expression_codegen *cgen;
2538 ir_block *ontrue_endblock = NULL;
2539 ir_block *onfalse_endblock = NULL;
2540 ir_block *merge = NULL;
2543 /* We don't output any value, thus also don't care about r/lvalue */
2547 if (self->expression.outr) {
2548 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2551 self->expression.outr = (ir_value*)1;
2553 /* generate the condition */
2554 cgen = self->cond->codegen;
2555 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2557 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2558 cond = func->curblock;
2560 /* try constant folding away the if */
2561 if ((fold = fold_cond(condval, func, self)) != -1)
2564 if (self->on_true) {
2565 /* create on-true block */
2566 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2570 /* enter the block */
2571 func->curblock = ontrue;
2574 cgen = self->on_true->codegen;
2575 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2578 /* we now need to work from the current endpoint */
2579 ontrue_endblock = func->curblock;
2584 if (self->on_false) {
2585 /* create on-false block */
2586 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2590 /* enter the block */
2591 func->curblock = onfalse;
2594 cgen = self->on_false->codegen;
2595 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2598 /* we now need to work from the current endpoint */
2599 onfalse_endblock = func->curblock;
2603 /* Merge block were they all merge in to */
2604 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2606 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2609 /* add jumps ot the merge block */
2610 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2612 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2615 /* Now enter the merge block */
2616 func->curblock = merge;
2619 /* we create the if here, that way all blocks are ordered :)
2621 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2622 (ontrue ? ontrue : merge),
2623 (onfalse ? onfalse : merge)))
2631 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2633 ast_expression_codegen *cgen;
2636 ir_value *trueval, *falseval;
2639 ir_block *cond = func->curblock;
2640 ir_block *cond_out = NULL;
2641 ir_block *ontrue, *ontrue_out = NULL;
2642 ir_block *onfalse, *onfalse_out = NULL;
2645 /* Ternary can never create an lvalue... */
2649 /* In theory it shouldn't be possible to pass through a node twice, but
2650 * in case we add any kind of optimization pass for the AST itself, it
2651 * may still happen, thus we remember a created ir_value and simply return one
2652 * if it already exists.
2654 if (self->expression.outr) {
2655 *out = self->expression.outr;
2659 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2661 /* generate the condition */
2662 func->curblock = cond;
2663 cgen = self->cond->codegen;
2664 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2666 cond_out = func->curblock;
2668 /* create on-true block */
2669 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2674 /* enter the block */
2675 func->curblock = ontrue;
2678 cgen = self->on_true->codegen;
2679 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2682 ontrue_out = func->curblock;
2685 /* create on-false block */
2686 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2691 /* enter the block */
2692 func->curblock = onfalse;
2695 cgen = self->on_false->codegen;
2696 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2699 onfalse_out = func->curblock;
2702 /* create merge block */
2703 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2706 /* jump to merge block */
2707 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2709 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2712 /* create if instruction */
2713 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2716 /* Now enter the merge block */
2717 func->curblock = merge;
2719 /* Here, now, we need a PHI node
2720 * but first some sanity checking...
2722 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2723 /* error("ternary with different types on the two sides"); */
2724 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2729 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2731 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2734 ir_phi_add(phi, ontrue_out, trueval);
2735 ir_phi_add(phi, onfalse_out, falseval);
2737 self->expression.outr = ir_phi_value(phi);
2738 *out = self->expression.outr;
2740 codegen_output_type(self, *out);
2745 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2747 ast_expression_codegen *cgen;
2749 ir_value *dummy = NULL;
2750 ir_value *precond = NULL;
2751 ir_value *postcond = NULL;
2753 /* Since we insert some jumps "late" so we have blocks
2754 * ordered "nicely", we need to keep track of the actual end-blocks
2755 * of expressions to add the jumps to.
2757 ir_block *bbody = NULL, *end_bbody = NULL;
2758 ir_block *bprecond = NULL, *end_bprecond = NULL;
2759 ir_block *bpostcond = NULL, *end_bpostcond = NULL;
2760 ir_block *bincrement = NULL, *end_bincrement = NULL;
2761 ir_block *bout = NULL, *bin = NULL;
2763 /* let's at least move the outgoing block to the end */
2766 /* 'break' and 'continue' need to be able to find the right blocks */
2767 ir_block *bcontinue = NULL;
2768 ir_block *bbreak = NULL;
2770 ir_block *tmpblock = NULL;
2775 if (self->expression.outr) {
2776 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2779 self->expression.outr = (ir_value*)1;
2782 * Should we ever need some kind of block ordering, better make this function
2783 * move blocks around than write a block ordering algorithm later... after all
2784 * the ast and ir should work together, not against each other.
2787 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2788 * anyway if for example it contains a ternary.
2792 cgen = self->initexpr->codegen;
2793 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2797 /* Store the block from which we enter this chaos */
2798 bin = func->curblock;
2800 /* The pre-loop condition needs its own block since we
2801 * need to be able to jump to the start of that expression.
2805 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2809 /* the pre-loop-condition the least important place to 'continue' at */
2810 bcontinue = bprecond;
2813 func->curblock = bprecond;
2816 cgen = self->precond->codegen;
2817 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2820 end_bprecond = func->curblock;
2822 bprecond = end_bprecond = NULL;
2825 /* Now the next blocks won't be ordered nicely, but we need to
2826 * generate them this early for 'break' and 'continue'.
2828 if (self->increment) {
2829 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2832 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2834 bincrement = end_bincrement = NULL;
2837 if (self->postcond) {
2838 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2841 bcontinue = bpostcond; /* postcond comes before the increment */
2843 bpostcond = end_bpostcond = NULL;
2846 bout_id = vec_size(func->ir_func->blocks);
2847 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2852 /* The loop body... */
2853 /* if (self->body) */
2855 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2860 func->curblock = bbody;
2862 vec_push(func->breakblocks, bbreak);
2864 vec_push(func->continueblocks, bcontinue);
2866 vec_push(func->continueblocks, bbody);
2870 cgen = self->body->codegen;
2871 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2875 end_bbody = func->curblock;
2876 vec_pop(func->breakblocks);
2877 vec_pop(func->continueblocks);
2880 /* post-loop-condition */
2884 func->curblock = bpostcond;
2887 cgen = self->postcond->codegen;
2888 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2891 end_bpostcond = func->curblock;
2894 /* The incrementor */
2895 if (self->increment)
2898 func->curblock = bincrement;
2901 cgen = self->increment->codegen;
2902 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2905 end_bincrement = func->curblock;
2908 /* In any case now, we continue from the outgoing block */
2909 func->curblock = bout;
2911 /* Now all blocks are in place */
2912 /* From 'bin' we jump to whatever comes first */
2913 if (bprecond) tmpblock = bprecond;
2914 else tmpblock = bbody; /* can never be null */
2917 else if (bpostcond) tmpblock = bpostcond;
2918 else tmpblock = bout;
2921 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2927 ir_block *ontrue, *onfalse;
2928 ontrue = bbody; /* can never be null */
2930 /* all of this is dead code
2931 else if (bincrement) ontrue = bincrement;
2932 else ontrue = bpostcond;
2936 if (self->pre_not) {
2941 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
2948 if (bincrement) tmpblock = bincrement;
2949 else if (bpostcond) tmpblock = bpostcond;
2950 else if (bprecond) tmpblock = bprecond;
2951 else tmpblock = bbody;
2952 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
2956 /* from increment */
2959 if (bpostcond) tmpblock = bpostcond;
2960 else if (bprecond) tmpblock = bprecond;
2961 else if (bbody) tmpblock = bbody;
2962 else tmpblock = bout;
2963 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
2970 ir_block *ontrue, *onfalse;
2971 if (bprecond) ontrue = bprecond;
2972 else ontrue = bbody; /* can never be null */
2974 /* all of this is dead code
2975 else if (bincrement) ontrue = bincrement;
2976 else ontrue = bpostcond;
2980 if (self->post_not) {
2985 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
2989 /* Move 'bout' to the end */
2990 vec_remove(func->ir_func->blocks, bout_id, 1);
2991 vec_push(func->ir_func->blocks, bout);
2996 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
3003 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3007 if (self->expression.outr) {
3008 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3011 self->expression.outr = (ir_value*)1;
3013 if (self->is_continue)
3014 target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
3016 target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
3019 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3023 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3028 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3030 ast_expression_codegen *cgen;
3032 ast_switch_case *def_case = NULL;
3033 ir_block *def_bfall = NULL;
3034 ir_block *def_bfall_to = NULL;
3035 bool set_def_bfall_to = false;
3037 ir_value *dummy = NULL;
3038 ir_value *irop = NULL;
3039 ir_block *bout = NULL;
3040 ir_block *bfall = NULL;
3048 compile_error(ast_ctx(self), "switch expression is not an l-value");
3052 if (self->expression.outr) {
3053 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3056 self->expression.outr = (ir_value*)1;
3061 cgen = self->operand->codegen;
3062 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3065 if (!vec_size(self->cases))
3068 cmpinstr = type_eq_instr[irop->vtype];
3069 if (cmpinstr >= VINSTR_END) {
3070 ast_type_to_string(self->operand, typestr, sizeof(typestr));
3071 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3075 bout_id = vec_size(func->ir_func->blocks);
3076 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3080 /* setup the break block */
3081 vec_push(func->breakblocks, bout);
3083 /* Now create all cases */
3084 for (c = 0; c < vec_size(self->cases); ++c) {
3085 ir_value *cond, *val;
3086 ir_block *bcase, *bnot;
3089 ast_switch_case *swcase = &self->cases[c];
3091 if (swcase->value) {
3092 /* A regular case */
3093 /* generate the condition operand */
3094 cgen = swcase->value->codegen;
3095 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3097 /* generate the condition */
3098 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3102 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3103 bnot_id = vec_size(func->ir_func->blocks);
3104 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3105 if (!bcase || !bnot)
3107 if (set_def_bfall_to) {
3108 set_def_bfall_to = false;
3109 def_bfall_to = bcase;
3111 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3114 /* Make the previous case-end fall through */
3115 if (bfall && !bfall->final) {
3116 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3120 /* enter the case */
3121 func->curblock = bcase;
3122 cgen = swcase->code->codegen;
3123 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3126 /* remember this block to fall through from */
3127 bfall = func->curblock;
3129 /* enter the else and move it down */
3130 func->curblock = bnot;
3131 vec_remove(func->ir_func->blocks, bnot_id, 1);
3132 vec_push(func->ir_func->blocks, bnot);
3134 /* The default case */
3135 /* Remember where to fall through from: */
3138 /* remember which case it was */
3140 /* And the next case will be remembered */
3141 set_def_bfall_to = true;
3145 /* Jump from the last bnot to bout */
3146 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3148 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3153 /* If there was a default case, put it down here */
3157 /* No need to create an extra block */
3158 bcase = func->curblock;
3160 /* Insert the fallthrough jump */
3161 if (def_bfall && !def_bfall->final) {
3162 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3166 /* Now generate the default code */
3167 cgen = def_case->code->codegen;
3168 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3171 /* see if we need to fall through */
3172 if (def_bfall_to && !func->curblock->final)
3174 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3179 /* Jump from the last bnot to bout */
3180 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3182 /* enter the outgoing block */
3183 func->curblock = bout;
3185 /* restore the break block */
3186 vec_pop(func->breakblocks);
3188 /* Move 'bout' to the end, it's nicer */
3189 vec_remove(func->ir_func->blocks, bout_id, 1);
3190 vec_push(func->ir_func->blocks, bout);
3195 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3200 if (self->undefined) {
3201 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3207 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3211 /* simply create a new block and jump to it */
3212 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3213 if (!self->irblock) {
3214 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3217 if (!func->curblock->final) {
3218 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3222 /* enter the new block */
3223 func->curblock = self->irblock;
3225 /* Generate all the leftover gotos */
3226 for (i = 0; i < vec_size(self->gotos); ++i) {
3227 if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3234 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3238 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3242 if (self->target->irblock) {
3243 if (self->irblock_from) {
3244 /* we already tried once, this is the callback */
3245 self->irblock_from->final = false;
3246 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3247 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3253 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3254 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3261 /* the target has not yet been created...
3262 * close this block in a sneaky way:
3264 func->curblock->final = true;
3265 self->irblock_from = func->curblock;
3266 ast_label_register_goto(self->target, self);
3272 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3274 ast_expression_codegen *cgen;
3276 ir_instr *callinstr;
3279 ir_value *funval = NULL;
3281 /* return values are never lvalues */
3283 compile_error(ast_ctx(self), "not an l-value (function call)");
3287 if (self->expression.outr) {
3288 *out = self->expression.outr;
3292 cgen = self->func->codegen;
3293 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3301 for (i = 0; i < vec_size(self->params); ++i)
3304 ast_expression *expr = self->params[i];
3306 cgen = expr->codegen;
3307 if (!(*cgen)(expr, func, false, ¶m))
3311 vec_push(params, param);
3314 /* varargs counter */
3315 if (self->va_count) {
3317 ir_builder *builder = func->curblock->owner->owner;
3318 cgen = self->va_count->codegen;
3319 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3321 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3322 ir_builder_get_va_count(builder), va_count))
3328 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3329 ast_function_label(func, "call"),
3330 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3334 for (i = 0; i < vec_size(params); ++i) {
3335 ir_call_param(callinstr, params[i]);
3338 *out = ir_call_value(callinstr);
3339 self->expression.outr = *out;
3341 codegen_output_type(self, *out);