2 * Copyright (C) 2012, 2013
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of
7 * this software and associated documentation files (the "Software"), to deal in
8 * the Software without restriction, including without limitation the rights to
9 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 * of the Software, and to permit persons to whom the Software is furnished to do
11 * so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31 #define ast_instantiate(T, ctx, destroyfn) \
32 T* self = (T*)mem_a(sizeof(T)); \
36 ast_node_init((ast_node*)self, ctx, TYPE_##T); \
37 ( (ast_node*)self )->destroy = (ast_node_delete*)destroyfn
40 * forward declarations, these need not be in ast.h for obvious
43 static bool ast_member_codegen(ast_member*, ast_function*, bool lvalue, ir_value**);
44 static void ast_array_index_delete(ast_array_index*);
45 static bool ast_array_index_codegen(ast_array_index*, ast_function*, bool lvalue, ir_value**);
46 static void ast_argpipe_delete(ast_argpipe*);
47 static bool ast_argpipe_codegen(ast_argpipe*, ast_function*, bool lvalue, ir_value**);
48 static void ast_store_delete(ast_store*);
49 static bool ast_store_codegen(ast_store*, ast_function*, bool lvalue, ir_value**);
50 static void ast_ifthen_delete(ast_ifthen*);
51 static bool ast_ifthen_codegen(ast_ifthen*, ast_function*, bool lvalue, ir_value**);
52 static void ast_ternary_delete(ast_ternary*);
53 static bool ast_ternary_codegen(ast_ternary*, ast_function*, bool lvalue, ir_value**);
54 static void ast_loop_delete(ast_loop*);
55 static bool ast_loop_codegen(ast_loop*, ast_function*, bool lvalue, ir_value**);
56 static void ast_breakcont_delete(ast_breakcont*);
57 static bool ast_breakcont_codegen(ast_breakcont*, ast_function*, bool lvalue, ir_value**);
58 static void ast_switch_delete(ast_switch*);
59 static bool ast_switch_codegen(ast_switch*, ast_function*, bool lvalue, ir_value**);
60 static void ast_label_delete(ast_label*);
61 static void ast_label_register_goto(ast_label*, ast_goto*);
62 static bool ast_label_codegen(ast_label*, ast_function*, bool lvalue, ir_value**);
63 static bool ast_goto_codegen(ast_goto*, ast_function*, bool lvalue, ir_value**);
64 static void ast_goto_delete(ast_goto*);
65 static void ast_call_delete(ast_call*);
66 static bool ast_call_codegen(ast_call*, ast_function*, bool lvalue, ir_value**);
67 static bool ast_block_codegen(ast_block*, ast_function*, bool lvalue, ir_value**);
68 static void ast_unary_delete(ast_unary*);
69 static bool ast_unary_codegen(ast_unary*, ast_function*, bool lvalue, ir_value**);
70 static void ast_entfield_delete(ast_entfield*);
71 static bool ast_entfield_codegen(ast_entfield*, ast_function*, bool lvalue, ir_value**);
72 static void ast_return_delete(ast_return*);
73 static bool ast_return_codegen(ast_return*, ast_function*, bool lvalue, ir_value**);
74 static void ast_binstore_delete(ast_binstore*);
75 static bool ast_binstore_codegen(ast_binstore*, ast_function*, bool lvalue, ir_value**);
76 static void ast_binary_delete(ast_binary*);
77 static bool ast_binary_codegen(ast_binary*, ast_function*, bool lvalue, ir_value**);
79 /* It must not be possible to get here. */
80 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
83 con_err("ast node missing destroy()\n");
87 /* Initialize main ast node aprts */
88 static void ast_node_init(ast_node *self, lex_ctx_t ctx, int nodetype)
91 self->destroy = &_ast_node_destroy;
93 self->nodetype = nodetype;
94 self->side_effects = false;
97 /* weight and side effects */
98 static void _ast_propagate_effects(ast_node *self, ast_node *other)
100 if (ast_side_effects(other))
101 ast_side_effects(self) = true;
103 #define ast_propagate_effects(s,o) _ast_propagate_effects(((ast_node*)(s)), ((ast_node*)(o)))
105 /* General expression initialization */
106 static void ast_expression_init(ast_expression *self,
107 ast_expression_codegen *codegen)
109 self->codegen = codegen;
110 self->vtype = TYPE_VOID;
117 self->varparam = NULL;
120 static void ast_expression_delete(ast_expression *self)
124 ast_delete(self->next);
125 for (i = 0; i < vec_size(self->params); ++i) {
126 ast_delete(self->params[i]);
128 vec_free(self->params);
130 ast_delete(self->varparam);
133 static void ast_expression_delete_full(ast_expression *self)
135 ast_expression_delete(self);
139 ast_value* ast_value_copy(const ast_value *self)
142 const ast_expression *fromex;
143 ast_expression *selfex;
144 ast_value *cp = ast_value_new(self->expression.node.context, self->name, self->expression.vtype);
145 if (self->expression.next) {
146 cp->expression.next = ast_type_copy(self->expression.node.context, self->expression.next);
148 fromex = &self->expression;
149 selfex = &cp->expression;
150 selfex->count = fromex->count;
151 selfex->flags = fromex->flags;
152 for (i = 0; i < vec_size(fromex->params); ++i) {
153 ast_value *v = ast_value_copy(fromex->params[i]);
154 vec_push(selfex->params, v);
159 void ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
162 const ast_expression *fromex;
163 ast_expression *selfex;
164 self->vtype = other->vtype;
166 self->next = (ast_expression*)ast_type_copy(ast_ctx(self), other->next);
170 selfex->count = fromex->count;
171 selfex->flags = fromex->flags;
172 for (i = 0; i < vec_size(fromex->params); ++i) {
173 ast_value *v = ast_value_copy(fromex->params[i]);
174 vec_push(selfex->params, v);
178 static ast_expression* ast_shallow_type(lex_ctx_t ctx, int vtype)
180 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
181 ast_expression_init(self, NULL);
182 self->codegen = NULL;
188 ast_expression* ast_type_copy(lex_ctx_t ctx, const ast_expression *ex)
191 const ast_expression *fromex;
192 ast_expression *selfex;
198 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
199 ast_expression_init(self, NULL);
204 /* This may never be codegen()d */
205 selfex->codegen = NULL;
207 selfex->vtype = fromex->vtype;
209 selfex->next = ast_type_copy(ctx, fromex->next);
213 selfex->count = fromex->count;
214 selfex->flags = fromex->flags;
215 for (i = 0; i < vec_size(fromex->params); ++i) {
216 ast_value *v = ast_value_copy(fromex->params[i]);
217 vec_push(selfex->params, v);
224 bool ast_compare_type(ast_expression *a, ast_expression *b)
226 if (a->vtype == TYPE_NIL ||
227 b->vtype == TYPE_NIL)
229 if (a->vtype != b->vtype)
231 if (!a->next != !b->next)
233 if (vec_size(a->params) != vec_size(b->params))
235 if ((a->flags & AST_FLAG_TYPE_MASK) !=
236 (b->flags & AST_FLAG_TYPE_MASK) )
240 if (vec_size(a->params)) {
242 for (i = 0; i < vec_size(a->params); ++i) {
243 if (!ast_compare_type((ast_expression*)a->params[i],
244 (ast_expression*)b->params[i]))
249 return ast_compare_type(a->next, b->next);
253 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
260 if (pos + 6 >= bufsize)
262 util_strncpy(buf + pos, "(null)", 6);
266 if (pos + 1 >= bufsize)
271 util_strncpy(buf + pos, "(variant)", 9);
276 return ast_type_to_string_impl(e->next, buf, bufsize, pos);
279 if (pos + 3 >= bufsize)
283 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
284 if (pos + 1 >= bufsize)
290 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
291 if (pos + 2 >= bufsize)
293 if (!vec_size(e->params)) {
299 pos = ast_type_to_string_impl((ast_expression*)(e->params[0]), buf, bufsize, pos);
300 for (i = 1; i < vec_size(e->params); ++i) {
301 if (pos + 2 >= bufsize)
305 pos = ast_type_to_string_impl((ast_expression*)(e->params[i]), buf, bufsize, pos);
307 if (pos + 1 >= bufsize)
313 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
314 if (pos + 1 >= bufsize)
317 pos += util_snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->count);
318 if (pos + 1 >= bufsize)
324 typestr = type_name[e->vtype];
325 typelen = strlen(typestr);
326 if (pos + typelen >= bufsize)
328 util_strncpy(buf + pos, typestr, typelen);
329 return pos + typelen;
333 buf[bufsize-3] = '.';
334 buf[bufsize-2] = '.';
335 buf[bufsize-1] = '.';
339 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
341 size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
345 static bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out);
346 ast_value* ast_value_new(lex_ctx_t ctx, const char *name, int t)
348 ast_instantiate(ast_value, ctx, ast_value_delete);
349 ast_expression_init((ast_expression*)self,
350 (ast_expression_codegen*)&ast_value_codegen);
351 self->expression.node.keep = true; /* keep */
353 self->name = name ? util_strdup(name) : NULL;
354 self->expression.vtype = t;
355 self->expression.next = NULL;
356 self->isfield = false;
358 self->hasvalue = false;
361 memset(&self->constval, 0, sizeof(self->constval));
362 self->initlist = NULL;
365 self->ir_values = NULL;
366 self->ir_value_count = 0;
372 self->argcounter = NULL;
377 void ast_value_delete(ast_value* self)
380 mem_d((void*)self->name);
381 if (self->argcounter)
382 mem_d((void*)self->argcounter);
383 if (self->hasvalue) {
384 switch (self->expression.vtype)
387 mem_d((void*)self->constval.vstring);
390 /* unlink us from the function node */
391 self->constval.vfunc->vtype = NULL;
393 /* NOTE: delete function? currently collected in
394 * the parser structure
401 mem_d(self->ir_values);
406 if (self->initlist) {
407 if (self->expression.next->vtype == TYPE_STRING) {
408 /* strings are allocated, free them */
409 size_t i, len = vec_size(self->initlist);
410 /* in theory, len should be expression.count
411 * but let's not take any chances */
412 for (i = 0; i < len; ++i) {
413 if (self->initlist[i].vstring)
414 mem_d(self->initlist[i].vstring);
417 vec_free(self->initlist);
420 ast_expression_delete((ast_expression*)self);
424 void ast_value_params_add(ast_value *self, ast_value *p)
426 vec_push(self->expression.params, p);
429 bool ast_value_set_name(ast_value *self, const char *name)
432 mem_d((void*)self->name);
433 self->name = util_strdup(name);
437 ast_binary* ast_binary_new(lex_ctx_t ctx, int op,
438 ast_expression* left, ast_expression* right)
440 ast_instantiate(ast_binary, ctx, ast_binary_delete);
441 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
446 self->right_first = false;
448 ast_propagate_effects(self, left);
449 ast_propagate_effects(self, right);
451 if (op >= INSTR_EQ_F && op <= INSTR_GT)
452 self->expression.vtype = TYPE_FLOAT;
453 else if (op == INSTR_AND || op == INSTR_OR) {
454 if (OPTS_FLAG(PERL_LOGIC))
455 ast_type_adopt(self, right);
457 self->expression.vtype = TYPE_FLOAT;
459 else if (op == INSTR_BITAND || op == INSTR_BITOR)
460 self->expression.vtype = TYPE_FLOAT;
461 else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
462 self->expression.vtype = TYPE_VECTOR;
463 else if (op == INSTR_MUL_V)
464 self->expression.vtype = TYPE_FLOAT;
466 self->expression.vtype = left->vtype;
469 self->refs = AST_REF_ALL;
474 void ast_binary_delete(ast_binary *self)
476 if (self->refs & AST_REF_LEFT) ast_unref(self->left);
477 if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
479 ast_expression_delete((ast_expression*)self);
483 ast_binstore* ast_binstore_new(lex_ctx_t ctx, int storop, int op,
484 ast_expression* left, ast_expression* right)
486 ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
487 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
489 ast_side_effects(self) = true;
491 self->opstore = storop;
494 self->source = right;
496 self->keep_dest = false;
498 ast_type_adopt(self, left);
502 void ast_binstore_delete(ast_binstore *self)
504 if (!self->keep_dest)
505 ast_unref(self->dest);
506 ast_unref(self->source);
507 ast_expression_delete((ast_expression*)self);
511 ast_unary* ast_unary_new(lex_ctx_t ctx, int op,
512 ast_expression *expr)
514 ast_instantiate(ast_unary, ctx, ast_unary_delete);
515 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
518 self->operand = expr;
520 ast_propagate_effects(self, expr);
522 if (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) {
523 self->expression.vtype = TYPE_FLOAT;
525 compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
530 void ast_unary_delete(ast_unary *self)
532 if (self->operand) ast_unref(self->operand);
533 ast_expression_delete((ast_expression*)self);
537 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
539 ast_instantiate(ast_return, ctx, ast_return_delete);
540 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
542 self->operand = expr;
545 ast_propagate_effects(self, expr);
550 void ast_return_delete(ast_return *self)
553 ast_unref(self->operand);
554 ast_expression_delete((ast_expression*)self);
558 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
560 if (field->vtype != TYPE_FIELD) {
561 compile_error(ctx, "ast_entfield_new with expression not of type field");
564 return ast_entfield_new_force(ctx, entity, field, field->next);
567 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
569 ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
573 /* Error: field has no type... */
577 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
579 self->entity = entity;
581 ast_propagate_effects(self, entity);
582 ast_propagate_effects(self, field);
584 ast_type_adopt(self, outtype);
588 void ast_entfield_delete(ast_entfield *self)
590 ast_unref(self->entity);
591 ast_unref(self->field);
592 ast_expression_delete((ast_expression*)self);
596 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
598 ast_instantiate(ast_member, ctx, ast_member_delete);
604 if (owner->vtype != TYPE_VECTOR &&
605 owner->vtype != TYPE_FIELD) {
606 compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
611 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
612 self->expression.node.keep = true; /* keep */
614 if (owner->vtype == TYPE_VECTOR) {
615 self->expression.vtype = TYPE_FLOAT;
616 self->expression.next = NULL;
618 self->expression.vtype = TYPE_FIELD;
619 self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
622 self->rvalue = false;
624 ast_propagate_effects(self, owner);
628 self->name = util_strdup(name);
635 void ast_member_delete(ast_member *self)
637 /* The owner is always an ast_value, which has .keep=true,
638 * also: ast_members are usually deleted after the owner, thus
639 * this will cause invalid access
640 ast_unref(self->owner);
641 * once we allow (expression).x to access a vector-member, we need
642 * to change this: preferably by creating an alternate ast node for this
643 * purpose that is not garbage-collected.
645 ast_expression_delete((ast_expression*)self);
650 bool ast_member_set_name(ast_member *self, const char *name)
653 mem_d((void*)self->name);
654 self->name = util_strdup(name);
658 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
660 ast_expression *outtype;
661 ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
663 outtype = array->next;
666 /* Error: field has no type... */
670 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
674 ast_propagate_effects(self, array);
675 ast_propagate_effects(self, index);
677 ast_type_adopt(self, outtype);
678 if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
679 if (self->expression.vtype != TYPE_ARRAY) {
680 compile_error(ast_ctx(self), "array_index node on type");
681 ast_array_index_delete(self);
684 self->array = outtype;
685 self->expression.vtype = TYPE_FIELD;
691 void ast_array_index_delete(ast_array_index *self)
694 ast_unref(self->array);
696 ast_unref(self->index);
697 ast_expression_delete((ast_expression*)self);
701 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
703 ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete);
704 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
706 self->expression.vtype = TYPE_NOEXPR;
710 void ast_argpipe_delete(ast_argpipe *self)
713 ast_unref(self->index);
714 ast_expression_delete((ast_expression*)self);
718 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
720 ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
721 if (!ontrue && !onfalse) {
722 /* because it is invalid */
726 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
729 self->on_true = ontrue;
730 self->on_false = onfalse;
731 ast_propagate_effects(self, cond);
733 ast_propagate_effects(self, ontrue);
735 ast_propagate_effects(self, onfalse);
740 void ast_ifthen_delete(ast_ifthen *self)
742 ast_unref(self->cond);
744 ast_unref(self->on_true);
746 ast_unref(self->on_false);
747 ast_expression_delete((ast_expression*)self);
751 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
753 ast_expression *exprtype = ontrue;
754 ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
755 /* This time NEITHER must be NULL */
756 if (!ontrue || !onfalse) {
760 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
763 self->on_true = ontrue;
764 self->on_false = onfalse;
765 ast_propagate_effects(self, cond);
766 ast_propagate_effects(self, ontrue);
767 ast_propagate_effects(self, onfalse);
769 if (ontrue->vtype == TYPE_NIL)
771 ast_type_adopt(self, exprtype);
776 void ast_ternary_delete(ast_ternary *self)
778 /* the if()s are only there because computed-gotos can set them
781 if (self->cond) ast_unref(self->cond);
782 if (self->on_true) ast_unref(self->on_true);
783 if (self->on_false) ast_unref(self->on_false);
784 ast_expression_delete((ast_expression*)self);
788 ast_loop* ast_loop_new(lex_ctx_t ctx,
789 ast_expression *initexpr,
790 ast_expression *precond, bool pre_not,
791 ast_expression *postcond, bool post_not,
792 ast_expression *increment,
793 ast_expression *body)
795 ast_instantiate(ast_loop, ctx, ast_loop_delete);
796 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
798 self->initexpr = initexpr;
799 self->precond = precond;
800 self->postcond = postcond;
801 self->increment = increment;
804 self->pre_not = pre_not;
805 self->post_not = post_not;
808 ast_propagate_effects(self, initexpr);
810 ast_propagate_effects(self, precond);
812 ast_propagate_effects(self, postcond);
814 ast_propagate_effects(self, increment);
816 ast_propagate_effects(self, body);
821 void ast_loop_delete(ast_loop *self)
824 ast_unref(self->initexpr);
826 ast_unref(self->precond);
828 ast_unref(self->postcond);
830 ast_unref(self->increment);
832 ast_unref(self->body);
833 ast_expression_delete((ast_expression*)self);
837 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
839 ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
840 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
842 self->is_continue = iscont;
843 self->levels = levels;
848 void ast_breakcont_delete(ast_breakcont *self)
850 ast_expression_delete((ast_expression*)self);
854 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
856 ast_instantiate(ast_switch, ctx, ast_switch_delete);
857 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
862 ast_propagate_effects(self, op);
867 void ast_switch_delete(ast_switch *self)
870 ast_unref(self->operand);
872 for (i = 0; i < vec_size(self->cases); ++i) {
873 if (self->cases[i].value)
874 ast_unref(self->cases[i].value);
875 ast_unref(self->cases[i].code);
877 vec_free(self->cases);
879 ast_expression_delete((ast_expression*)self);
883 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
885 ast_instantiate(ast_label, ctx, ast_label_delete);
886 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
888 self->expression.vtype = TYPE_NOEXPR;
890 self->name = util_strdup(name);
891 self->irblock = NULL;
893 self->undefined = undefined;
898 void ast_label_delete(ast_label *self)
900 mem_d((void*)self->name);
901 vec_free(self->gotos);
902 ast_expression_delete((ast_expression*)self);
906 static void ast_label_register_goto(ast_label *self, ast_goto *g)
908 vec_push(self->gotos, g);
911 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
913 ast_instantiate(ast_goto, ctx, ast_goto_delete);
914 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
916 self->name = util_strdup(name);
918 self->irblock_from = NULL;
923 void ast_goto_delete(ast_goto *self)
925 mem_d((void*)self->name);
926 ast_expression_delete((ast_expression*)self);
930 void ast_goto_set_label(ast_goto *self, ast_label *label)
932 self->target = label;
935 ast_call* ast_call_new(lex_ctx_t ctx,
936 ast_expression *funcexpr)
938 ast_instantiate(ast_call, ctx, ast_call_delete);
939 if (!funcexpr->next) {
940 compile_error(ctx, "not a function");
944 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
946 ast_side_effects(self) = true;
949 self->func = funcexpr;
950 self->va_count = NULL;
952 ast_type_adopt(self, funcexpr->next);
957 void ast_call_delete(ast_call *self)
960 for (i = 0; i < vec_size(self->params); ++i)
961 ast_unref(self->params[i]);
962 vec_free(self->params);
965 ast_unref(self->func);
968 ast_unref(self->va_count);
970 ast_expression_delete((ast_expression*)self);
974 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
980 if (!va_type || !ast_compare_type(va_type, exp_type))
982 if (va_type && exp_type)
984 ast_type_to_string(va_type, tgot, sizeof(tgot));
985 ast_type_to_string(exp_type, texp, sizeof(texp));
986 if (OPTS_FLAG(UNSAFE_VARARGS)) {
987 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
988 "piped variadic argument differs in type: constrained to type %s, expected type %s",
992 compile_error(ast_ctx(self),
993 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1000 ast_type_to_string(exp_type, texp, sizeof(texp));
1001 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1002 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1003 "piped variadic argument may differ in type: expected type %s",
1007 compile_error(ast_ctx(self),
1008 "piped variadic argument may differ in type: expected type %s",
1017 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1023 const ast_expression *func = self->func;
1024 size_t count = vec_size(self->params);
1025 if (count > vec_size(func->params))
1026 count = vec_size(func->params);
1028 for (i = 0; i < count; ++i) {
1029 if (ast_istype(self->params[i], ast_argpipe)) {
1030 /* warn about type safety instead */
1032 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1035 if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->params[i]))
1038 else if (!ast_compare_type(self->params[i], (ast_expression*)(func->params[i])))
1040 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1041 ast_type_to_string((ast_expression*)func->params[i], texp, sizeof(texp));
1042 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1043 (unsigned int)(i+1), texp, tgot);
1044 /* we don't immediately return */
1048 count = vec_size(self->params);
1049 if (count > vec_size(func->params) && func->varparam) {
1050 for (; i < count; ++i) {
1051 if (ast_istype(self->params[i], ast_argpipe)) {
1052 /* warn about type safety instead */
1054 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1057 if (!ast_call_check_vararg(self, va_type, func->varparam))
1060 else if (!ast_compare_type(self->params[i], func->varparam))
1062 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1063 ast_type_to_string(func->varparam, texp, sizeof(texp));
1064 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1065 (unsigned int)(i+1), texp, tgot);
1066 /* we don't immediately return */
1074 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1075 ast_expression *dest, ast_expression *source)
1077 ast_instantiate(ast_store, ctx, ast_store_delete);
1078 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1080 ast_side_effects(self) = true;
1084 self->source = source;
1086 ast_type_adopt(self, dest);
1091 void ast_store_delete(ast_store *self)
1093 ast_unref(self->dest);
1094 ast_unref(self->source);
1095 ast_expression_delete((ast_expression*)self);
1099 ast_block* ast_block_new(lex_ctx_t ctx)
1101 ast_instantiate(ast_block, ctx, ast_block_delete);
1102 ast_expression_init((ast_expression*)self,
1103 (ast_expression_codegen*)&ast_block_codegen);
1105 self->locals = NULL;
1107 self->collect = NULL;
1112 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1114 ast_propagate_effects(self, e);
1115 vec_push(self->exprs, e);
1116 if (self->expression.next) {
1117 ast_delete(self->expression.next);
1118 self->expression.next = NULL;
1120 ast_type_adopt(self, e);
1124 void ast_block_collect(ast_block *self, ast_expression *expr)
1126 vec_push(self->collect, expr);
1127 expr->node.keep = true;
1130 void ast_block_delete(ast_block *self)
1133 for (i = 0; i < vec_size(self->exprs); ++i)
1134 ast_unref(self->exprs[i]);
1135 vec_free(self->exprs);
1136 for (i = 0; i < vec_size(self->locals); ++i)
1137 ast_delete(self->locals[i]);
1138 vec_free(self->locals);
1139 for (i = 0; i < vec_size(self->collect); ++i)
1140 ast_delete(self->collect[i]);
1141 vec_free(self->collect);
1142 ast_expression_delete((ast_expression*)self);
1146 void ast_block_set_type(ast_block *self, ast_expression *from)
1148 if (self->expression.next)
1149 ast_delete(self->expression.next);
1150 ast_type_adopt(self, from);
1153 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1155 ast_instantiate(ast_function, ctx, ast_function_delete);
1158 compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1160 } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1161 compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1163 (int)vtype->hasvalue,
1164 vtype->expression.vtype);
1168 self->vtype = vtype;
1169 self->name = name ? util_strdup(name) : NULL;
1170 self->blocks = NULL;
1172 self->labelcount = 0;
1175 self->ir_func = NULL;
1176 self->curblock = NULL;
1178 self->breakblocks = NULL;
1179 self->continueblocks = NULL;
1181 vtype->hasvalue = true;
1182 vtype->constval.vfunc = self;
1184 self->varargs = NULL;
1186 self->fixedparams = NULL;
1187 self->return_value = NULL;
1196 void ast_function_delete(ast_function *self)
1200 mem_d((void*)self->name);
1202 /* ast_value_delete(self->vtype); */
1203 self->vtype->hasvalue = false;
1204 self->vtype->constval.vfunc = NULL;
1205 /* We use unref - if it was stored in a global table it is supposed
1206 * to be deleted from *there*
1208 ast_unref(self->vtype);
1210 for (i = 0; i < vec_size(self->blocks); ++i)
1211 ast_delete(self->blocks[i]);
1212 vec_free(self->blocks);
1213 vec_free(self->breakblocks);
1214 vec_free(self->continueblocks);
1216 ast_delete(self->varargs);
1218 ast_delete(self->argc);
1219 if (self->fixedparams)
1220 ast_unref(self->fixedparams);
1221 if (self->return_value)
1222 ast_unref(self->return_value);
1226 const char* ast_function_label(ast_function *self, const char *prefix)
1232 if (!OPTS_OPTION_BOOL(OPTION_DUMP) &&
1233 !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1234 !OPTS_OPTION_BOOL(OPTION_DEBUG))
1239 id = (self->labelcount++);
1240 len = strlen(prefix);
1242 from = self->labelbuf + sizeof(self->labelbuf)-1;
1245 *from-- = (id%10) + '0';
1249 memcpy(from - len, prefix, len);
1253 /*********************************************************************/
1255 * by convention you must never pass NULL to the 'ir_value **out'
1256 * parameter. If you really don't care about the output, pass a dummy.
1257 * But I can't imagine a pituation where the output is truly unnecessary.
1260 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1262 if (out->vtype == TYPE_FIELD)
1263 out->fieldtype = self->next->vtype;
1264 if (out->vtype == TYPE_FUNCTION)
1265 out->outtype = self->next->vtype;
1268 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1270 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1274 if (self->expression.vtype == TYPE_NIL) {
1275 *out = func->ir_func->owner->nil;
1278 /* NOTE: This is the codegen for a variable used in an expression.
1279 * It is not the codegen to generate the value. For this purpose,
1280 * ast_local_codegen and ast_global_codegen are to be used before this
1281 * is executed. ast_function_codegen should take care of its locals,
1282 * and the ast-user should take care of ast_global_codegen to be used
1283 * on all the globals.
1286 char tname[1024]; /* typename is reserved in C++ */
1287 ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1288 compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1295 static bool ast_global_array_set(ast_value *self)
1297 size_t count = vec_size(self->initlist);
1300 if (count > self->expression.count) {
1301 compile_error(ast_ctx(self), "too many elements in initializer");
1302 count = self->expression.count;
1304 else if (count < self->expression.count) {
1306 compile_warning(ast_ctx(self), "not all elements are initialized");
1310 for (i = 0; i != count; ++i) {
1311 switch (self->expression.next->vtype) {
1313 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1317 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1321 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1325 /* we don't support them in any other place yet either */
1326 compile_error(ast_ctx(self), "TODO: nested arrays");
1329 /* this requiers a bit more work - similar to the fields I suppose */
1330 compile_error(ast_ctx(self), "global of type function not properly generated");
1333 if (!self->initlist[i].vfield) {
1334 compile_error(ast_ctx(self), "field constant without vfield set");
1337 if (!self->initlist[i].vfield->ir_v) {
1338 compile_error(ast_ctx(self), "field constant generated before its field");
1341 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1345 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1352 static bool check_array(ast_value *self, ast_value *array)
1354 if (array->expression.flags & AST_FLAG_ARRAY_INIT && !array->initlist) {
1355 compile_error(ast_ctx(self), "array without size: %s", self->name);
1358 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1359 if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1360 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1366 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1370 if (self->expression.vtype == TYPE_NIL) {
1371 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1375 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1377 ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1380 func->context = ast_ctx(self);
1381 func->value->context = ast_ctx(self);
1383 self->constval.vfunc->ir_func = func;
1384 self->ir_v = func->value;
1385 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1386 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1387 /* The function is filled later on ast_function_codegen... */
1391 if (isfield && self->expression.vtype == TYPE_FIELD) {
1392 ast_expression *fieldtype = self->expression.next;
1394 if (self->hasvalue) {
1395 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1399 if (fieldtype->vtype == TYPE_ARRAY) {
1404 ast_expression *elemtype;
1406 ast_value *array = (ast_value*)fieldtype;
1408 if (!ast_istype(fieldtype, ast_value)) {
1409 compile_error(ast_ctx(self), "internal error: ast_value required");
1413 if (!check_array(self, array))
1416 elemtype = array->expression.next;
1417 vtype = elemtype->vtype;
1419 v = ir_builder_create_field(ir, self->name, vtype);
1421 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1424 v->context = ast_ctx(self);
1425 v->unique_life = true;
1427 array->ir_v = self->ir_v = v;
1428 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1429 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1431 namelen = strlen(self->name);
1432 name = (char*)mem_a(namelen + 16);
1433 util_strncpy(name, self->name, namelen);
1435 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1436 array->ir_values[0] = v;
1437 for (ai = 1; ai < array->expression.count; ++ai) {
1438 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1439 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1440 if (!array->ir_values[ai]) {
1442 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1445 array->ir_values[ai]->context = ast_ctx(self);
1446 array->ir_values[ai]->unique_life = true;
1447 array->ir_values[ai]->locked = true;
1448 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1449 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1455 v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1458 v->context = ast_ctx(self);
1460 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1461 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1466 if (self->expression.vtype == TYPE_ARRAY) {
1471 ast_expression *elemtype = self->expression.next;
1472 int vtype = elemtype->vtype;
1474 if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1475 compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1479 /* same as with field arrays */
1480 if (!check_array(self, self))
1483 v = ir_builder_create_global(ir, self->name, vtype);
1485 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1488 v->context = ast_ctx(self);
1489 v->unique_life = true;
1491 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1492 v->flags |= IR_FLAG_INCLUDE_DEF;
1494 namelen = strlen(self->name);
1495 name = (char*)mem_a(namelen + 16);
1496 util_strncpy(name, self->name, namelen);
1498 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1499 self->ir_values[0] = v;
1500 for (ai = 1; ai < self->expression.count; ++ai) {
1501 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1502 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1503 if (!self->ir_values[ai]) {
1505 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1508 self->ir_values[ai]->context = ast_ctx(self);
1509 self->ir_values[ai]->unique_life = true;
1510 self->ir_values[ai]->locked = true;
1511 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1512 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1518 /* Arrays don't do this since there's no "array" value which spans across the
1521 v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1523 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1526 codegen_output_type(self, v);
1527 v->context = ast_ctx(self);
1530 /* link us to the ir_value */
1533 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1534 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1537 if (self->hasvalue) {
1538 switch (self->expression.vtype)
1541 if (!ir_value_set_float(v, self->constval.vfloat))
1545 if (!ir_value_set_vector(v, self->constval.vvec))
1549 if (!ir_value_set_string(v, self->constval.vstring))
1553 ast_global_array_set(self);
1556 compile_error(ast_ctx(self), "global of type function not properly generated");
1558 /* Cannot generate an IR value for a function,
1559 * need a pointer pointing to a function rather.
1562 if (!self->constval.vfield) {
1563 compile_error(ast_ctx(self), "field constant without vfield set");
1566 if (!self->constval.vfield->ir_v) {
1567 compile_error(ast_ctx(self), "field constant generated before its field");
1570 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1574 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1580 error: /* clean up */
1581 if(v) ir_value_delete(v);
1585 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1589 if (self->expression.vtype == TYPE_NIL) {
1590 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1594 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1596 /* Do we allow local functions? I think not...
1597 * this is NOT a function pointer atm.
1602 if (self->expression.vtype == TYPE_ARRAY) {
1607 ast_expression *elemtype = self->expression.next;
1608 int vtype = elemtype->vtype;
1610 func->flags |= IR_FLAG_HAS_ARRAYS;
1612 if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1613 compile_error(ast_ctx(self), "array-parameters are not supported");
1617 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1618 if (!check_array(self, self))
1621 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1622 if (!self->ir_values) {
1623 compile_error(ast_ctx(self), "failed to allocate array values");
1627 v = ir_function_create_local(func, self->name, vtype, param);
1629 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1632 v->context = ast_ctx(self);
1633 v->unique_life = true;
1636 namelen = strlen(self->name);
1637 name = (char*)mem_a(namelen + 16);
1638 util_strncpy(name, self->name, namelen);
1640 self->ir_values[0] = v;
1641 for (ai = 1; ai < self->expression.count; ++ai) {
1642 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1643 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1644 if (!self->ir_values[ai]) {
1645 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1648 self->ir_values[ai]->context = ast_ctx(self);
1649 self->ir_values[ai]->unique_life = true;
1650 self->ir_values[ai]->locked = true;
1656 v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1659 codegen_output_type(self, v);
1660 v->context = ast_ctx(self);
1663 /* A constant local... hmmm...
1664 * I suppose the IR will have to deal with this
1666 if (self->hasvalue) {
1667 switch (self->expression.vtype)
1670 if (!ir_value_set_float(v, self->constval.vfloat))
1674 if (!ir_value_set_vector(v, self->constval.vvec))
1678 if (!ir_value_set_string(v, self->constval.vstring))
1682 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1687 /* link us to the ir_value */
1691 if (!ast_generate_accessors(self, func->owner))
1695 error: /* clean up */
1700 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1703 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1704 if (!self->setter || !self->getter)
1706 for (i = 0; i < self->expression.count; ++i) {
1707 if (!self->ir_values) {
1708 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1711 if (!self->ir_values[i]) {
1712 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1715 if (self->ir_values[i]->life) {
1716 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1721 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1723 if (!ast_global_codegen (self->setter, ir, false) ||
1724 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1725 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1727 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1728 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1733 if (!ast_global_codegen (self->getter, ir, false) ||
1734 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1735 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1737 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1738 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1742 for (i = 0; i < self->expression.count; ++i) {
1743 vec_free(self->ir_values[i]->life);
1745 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1749 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1754 ast_expression_codegen *cgen;
1759 irf = self->ir_func;
1761 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1765 /* fill the parameter list */
1766 ec = &self->vtype->expression;
1767 for (i = 0; i < vec_size(ec->params); ++i)
1769 if (ec->params[i]->expression.vtype == TYPE_FIELD)
1770 vec_push(irf->params, ec->params[i]->expression.next->vtype);
1772 vec_push(irf->params, ec->params[i]->expression.vtype);
1773 if (!self->builtin) {
1774 if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1779 if (self->varargs) {
1780 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1782 irf->max_varargs = self->varargs->expression.count;
1785 if (self->builtin) {
1786 irf->builtin = self->builtin;
1790 /* have a local return value variable? */
1791 if (self->return_value) {
1792 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1796 if (!vec_size(self->blocks)) {
1797 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1801 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1802 if (!self->curblock) {
1803 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1811 if (!ast_local_codegen(self->argc, self->ir_func, true))
1813 cgen = self->argc->expression.codegen;
1814 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1816 cgen = self->fixedparams->expression.codegen;
1817 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1819 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1820 ast_function_label(self, "va_count"), INSTR_SUB_F,
1821 ir_builder_get_va_count(ir), fixed);
1824 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1831 for (i = 0; i < vec_size(self->blocks); ++i) {
1832 cgen = self->blocks[i]->expression.codegen;
1833 if (!(*cgen)((ast_expression*)self->blocks[i], self, false, &dummy))
1837 /* TODO: check return types */
1838 if (!self->curblock->final)
1840 if (!self->vtype->expression.next ||
1841 self->vtype->expression.next->vtype == TYPE_VOID)
1843 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1845 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1847 if (self->return_value) {
1848 cgen = self->return_value->expression.codegen;
1849 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1851 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1853 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1854 "control reaches end of non-void function (`%s`) via %s",
1855 self->name, self->curblock->label))
1859 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1865 /* Note, you will not see ast_block_codegen generate ir_blocks.
1866 * To the AST and the IR, blocks are 2 different things.
1867 * In the AST it represents a block of code, usually enclosed in
1868 * curly braces {...}.
1869 * While in the IR it represents a block in terms of control-flow.
1871 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1875 /* We don't use this
1876 * Note: an ast-representation using the comma-operator
1877 * of the form: (a, b, c) = x should not assign to c...
1880 compile_error(ast_ctx(self), "not an l-value (code-block)");
1884 if (self->expression.outr) {
1885 *out = self->expression.outr;
1889 /* output is NULL at first, we'll have each expression
1890 * assign to out output, thus, a comma-operator represention
1891 * using an ast_block will return the last generated value,
1892 * so: (b, c) + a executed both b and c, and returns c,
1893 * which is then added to a.
1897 /* generate locals */
1898 for (i = 0; i < vec_size(self->locals); ++i)
1900 if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1901 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1902 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1907 for (i = 0; i < vec_size(self->exprs); ++i)
1909 ast_expression_codegen *gen;
1910 if (func->curblock->final && !ast_istype(self->exprs[i], ast_label)) {
1911 if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
1915 gen = self->exprs[i]->codegen;
1916 if (!(*gen)(self->exprs[i], func, false, out))
1920 self->expression.outr = *out;
1925 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1927 ast_expression_codegen *cgen;
1928 ir_value *left = NULL;
1929 ir_value *right = NULL;
1933 ast_array_index *ai = NULL;
1935 if (lvalue && self->expression.outl) {
1936 *out = self->expression.outl;
1940 if (!lvalue && self->expression.outr) {
1941 *out = self->expression.outr;
1945 if (ast_istype(self->dest, ast_array_index))
1948 ai = (ast_array_index*)self->dest;
1949 idx = (ast_value*)ai->index;
1951 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
1956 /* we need to call the setter */
1957 ir_value *iridx, *funval;
1961 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1965 arr = (ast_value*)ai->array;
1966 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1967 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
1971 cgen = idx->expression.codegen;
1972 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1975 cgen = arr->setter->expression.codegen;
1976 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
1979 cgen = self->source->codegen;
1980 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
1983 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
1986 ir_call_param(call, iridx);
1987 ir_call_param(call, right);
1988 self->expression.outr = right;
1994 cgen = self->dest->codegen;
1996 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
1998 self->expression.outl = left;
2000 cgen = self->source->codegen;
2002 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2005 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2007 self->expression.outr = right;
2010 /* Theoretically, an assinment returns its left side as an
2011 * lvalue, if we don't need an lvalue though, we return
2012 * the right side as an rvalue, otherwise we have to
2013 * somehow know whether or not we need to dereference the pointer
2014 * on the left side - that is: OP_LOAD if it was an address.
2015 * Also: in original QC we cannot OP_LOADP *anyway*.
2017 *out = (lvalue ? left : right);
2022 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2024 ast_expression_codegen *cgen;
2025 ir_value *left, *right;
2027 /* A binary operation cannot yield an l-value */
2029 compile_error(ast_ctx(self), "not an l-value (binop)");
2033 if (self->expression.outr) {
2034 *out = self->expression.outr;
2038 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2039 (self->op == INSTR_AND || self->op == INSTR_OR))
2041 /* NOTE: The short-logic path will ignore right_first */
2043 /* short circuit evaluation */
2044 ir_block *other, *merge;
2045 ir_block *from_left, *from_right;
2049 /* prepare end-block */
2050 merge_id = vec_size(func->ir_func->blocks);
2051 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2053 /* generate the left expression */
2054 cgen = self->left->codegen;
2055 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2057 /* remember the block */
2058 from_left = func->curblock;
2060 /* create a new block for the right expression */
2061 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2062 if (self->op == INSTR_AND) {
2063 /* on AND: left==true -> other */
2064 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2067 /* on OR: left==false -> other */
2068 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2071 /* use the likely flag */
2072 vec_last(func->curblock->instr)->likely = true;
2074 /* enter the right-expression's block */
2075 func->curblock = other;
2077 cgen = self->right->codegen;
2078 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2080 /* remember block */
2081 from_right = func->curblock;
2083 /* jump to the merge block */
2084 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2087 vec_remove(func->ir_func->blocks, merge_id, 1);
2088 vec_push(func->ir_func->blocks, merge);
2090 func->curblock = merge;
2091 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2092 ast_function_label(func, "sce_value"),
2093 self->expression.vtype);
2094 ir_phi_add(phi, from_left, left);
2095 ir_phi_add(phi, from_right, right);
2096 *out = ir_phi_value(phi);
2100 if (!OPTS_FLAG(PERL_LOGIC)) {
2102 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2103 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2104 ast_function_label(func, "sce_bool_v"),
2108 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2109 ast_function_label(func, "sce_bool"),
2114 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2115 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2116 ast_function_label(func, "sce_bool_s"),
2120 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2121 ast_function_label(func, "sce_bool"),
2127 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2128 ast_function_label(func, "sce_bool"),
2129 INSTR_AND, *out, *out);
2135 self->expression.outr = *out;
2136 codegen_output_type(self, *out);
2140 if (self->right_first) {
2141 cgen = self->right->codegen;
2142 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2144 cgen = self->left->codegen;
2145 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2148 cgen = self->left->codegen;
2149 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2151 cgen = self->right->codegen;
2152 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2156 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2157 self->op, left, right);
2160 self->expression.outr = *out;
2161 codegen_output_type(self, *out);
2166 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2168 ast_expression_codegen *cgen;
2169 ir_value *leftl = NULL, *leftr, *right, *bin;
2173 ast_array_index *ai = NULL;
2174 ir_value *iridx = NULL;
2176 if (lvalue && self->expression.outl) {
2177 *out = self->expression.outl;
2181 if (!lvalue && self->expression.outr) {
2182 *out = self->expression.outr;
2186 if (ast_istype(self->dest, ast_array_index))
2189 ai = (ast_array_index*)self->dest;
2190 idx = (ast_value*)ai->index;
2192 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2196 /* for a binstore we need both an lvalue and an rvalue for the left side */
2197 /* rvalue of destination! */
2199 cgen = idx->expression.codegen;
2200 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2203 cgen = self->dest->codegen;
2204 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2207 /* source as rvalue only */
2208 cgen = self->source->codegen;
2209 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2212 /* now the binary */
2213 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2214 self->opbin, leftr, right);
2215 self->expression.outr = bin;
2219 /* we need to call the setter */
2224 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2228 arr = (ast_value*)ai->array;
2229 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2230 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2234 cgen = arr->setter->expression.codegen;
2235 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2238 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2241 ir_call_param(call, iridx);
2242 ir_call_param(call, bin);
2243 self->expression.outr = bin;
2245 /* now store them */
2246 cgen = self->dest->codegen;
2247 /* lvalue of destination */
2248 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2250 self->expression.outl = leftl;
2252 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2254 self->expression.outr = bin;
2257 /* Theoretically, an assinment returns its left side as an
2258 * lvalue, if we don't need an lvalue though, we return
2259 * the right side as an rvalue, otherwise we have to
2260 * somehow know whether or not we need to dereference the pointer
2261 * on the left side - that is: OP_LOAD if it was an address.
2262 * Also: in original QC we cannot OP_LOADP *anyway*.
2264 *out = (lvalue ? leftl : bin);
2269 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2271 ast_expression_codegen *cgen;
2274 /* An unary operation cannot yield an l-value */
2276 compile_error(ast_ctx(self), "not an l-value (binop)");
2280 if (self->expression.outr) {
2281 *out = self->expression.outr;
2285 cgen = self->operand->codegen;
2287 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2290 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2294 self->expression.outr = *out;
2299 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2301 ast_expression_codegen *cgen;
2306 /* In the context of a return operation, we don't actually return
2310 compile_error(ast_ctx(self), "return-expression is not an l-value");
2314 if (self->expression.outr) {
2315 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2318 self->expression.outr = (ir_value*)1;
2320 if (self->operand) {
2321 cgen = self->operand->codegen;
2323 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2326 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2329 if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2336 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2338 ast_expression_codegen *cgen;
2339 ir_value *ent, *field;
2341 /* This function needs to take the 'lvalue' flag into account!
2342 * As lvalue we provide a field-pointer, as rvalue we provide the
2346 if (lvalue && self->expression.outl) {
2347 *out = self->expression.outl;
2351 if (!lvalue && self->expression.outr) {
2352 *out = self->expression.outr;
2356 cgen = self->entity->codegen;
2357 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2360 cgen = self->field->codegen;
2361 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2366 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2369 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2370 ent, field, self->expression.vtype);
2371 /* Done AFTER error checking:
2372 codegen_output_type(self, *out);
2376 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2377 (lvalue ? "ADDRESS" : "FIELD"),
2378 type_name[self->expression.vtype]);
2382 codegen_output_type(self, *out);
2385 self->expression.outl = *out;
2387 self->expression.outr = *out;
2389 /* Hm that should be it... */
2393 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2395 ast_expression_codegen *cgen;
2398 /* in QC this is always an lvalue */
2399 if (lvalue && self->rvalue) {
2400 compile_error(ast_ctx(self), "not an l-value (member access)");
2403 if (self->expression.outl) {
2404 *out = self->expression.outl;
2408 cgen = self->owner->codegen;
2409 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2412 if (vec->vtype != TYPE_VECTOR &&
2413 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2418 *out = ir_value_vector_member(vec, self->field);
2419 self->expression.outl = *out;
2421 return (*out != NULL);
2424 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2429 if (!lvalue && self->expression.outr) {
2430 *out = self->expression.outr;
2433 if (lvalue && self->expression.outl) {
2434 *out = self->expression.outl;
2438 if (!ast_istype(self->array, ast_value)) {
2439 compile_error(ast_ctx(self), "array indexing this way is not supported");
2440 /* note this would actually be pointer indexing because the left side is
2441 * not an actual array but (hopefully) an indexable expression.
2442 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2443 * support this path will be filled.
2448 arr = (ast_value*)self->array;
2449 idx = (ast_value*)self->index;
2451 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2452 /* Time to use accessor functions */
2453 ast_expression_codegen *cgen;
2454 ir_value *iridx, *funval;
2458 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2463 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2467 cgen = self->index->codegen;
2468 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2471 cgen = arr->getter->expression.codegen;
2472 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2475 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2478 ir_call_param(call, iridx);
2480 *out = ir_call_value(call);
2481 self->expression.outr = *out;
2482 (*out)->vtype = self->expression.vtype;
2483 codegen_output_type(self, *out);
2487 if (idx->expression.vtype == TYPE_FLOAT) {
2488 unsigned int arridx = idx->constval.vfloat;
2489 if (arridx >= self->array->count)
2491 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2494 *out = arr->ir_values[arridx];
2496 else if (idx->expression.vtype == TYPE_INTEGER) {
2497 unsigned int arridx = idx->constval.vint;
2498 if (arridx >= self->array->count)
2500 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2503 *out = arr->ir_values[arridx];
2506 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2509 (*out)->vtype = self->expression.vtype;
2510 codegen_output_type(self, *out);
2514 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2518 compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2523 compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2527 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2529 ast_expression_codegen *cgen;
2537 ir_block *ontrue_endblock = NULL;
2538 ir_block *onfalse_endblock = NULL;
2539 ir_block *merge = NULL;
2542 /* We don't output any value, thus also don't care about r/lvalue */
2546 if (self->expression.outr) {
2547 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2550 self->expression.outr = (ir_value*)1;
2552 /* generate the condition */
2553 cgen = self->cond->codegen;
2554 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2556 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2557 cond = func->curblock;
2559 /* try constant folding away the if */
2560 if ((fold = fold_cond(condval, func, self)) != -1)
2563 if (self->on_true) {
2564 /* create on-true block */
2565 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2569 /* enter the block */
2570 func->curblock = ontrue;
2573 cgen = self->on_true->codegen;
2574 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2577 /* we now need to work from the current endpoint */
2578 ontrue_endblock = func->curblock;
2583 if (self->on_false) {
2584 /* create on-false block */
2585 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2589 /* enter the block */
2590 func->curblock = onfalse;
2593 cgen = self->on_false->codegen;
2594 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2597 /* we now need to work from the current endpoint */
2598 onfalse_endblock = func->curblock;
2602 /* Merge block were they all merge in to */
2603 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2605 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2608 /* add jumps ot the merge block */
2609 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2611 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2614 /* Now enter the merge block */
2615 func->curblock = merge;
2618 /* we create the if here, that way all blocks are ordered :)
2620 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2621 (ontrue ? ontrue : merge),
2622 (onfalse ? onfalse : merge)))
2630 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2632 ast_expression_codegen *cgen;
2635 ir_value *trueval, *falseval;
2638 ir_block *cond = func->curblock;
2639 ir_block *cond_out = NULL;
2640 ir_block *ontrue, *ontrue_out = NULL;
2641 ir_block *onfalse, *onfalse_out = NULL;
2644 /* Ternary can never create an lvalue... */
2648 /* In theory it shouldn't be possible to pass through a node twice, but
2649 * in case we add any kind of optimization pass for the AST itself, it
2650 * may still happen, thus we remember a created ir_value and simply return one
2651 * if it already exists.
2653 if (self->expression.outr) {
2654 *out = self->expression.outr;
2658 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2660 /* generate the condition */
2661 func->curblock = cond;
2662 cgen = self->cond->codegen;
2663 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2665 cond_out = func->curblock;
2667 /* create on-true block */
2668 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2673 /* enter the block */
2674 func->curblock = ontrue;
2677 cgen = self->on_true->codegen;
2678 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2681 ontrue_out = func->curblock;
2684 /* create on-false block */
2685 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2690 /* enter the block */
2691 func->curblock = onfalse;
2694 cgen = self->on_false->codegen;
2695 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2698 onfalse_out = func->curblock;
2701 /* create merge block */
2702 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2705 /* jump to merge block */
2706 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2708 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2711 /* create if instruction */
2712 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2715 /* Now enter the merge block */
2716 func->curblock = merge;
2718 /* Here, now, we need a PHI node
2719 * but first some sanity checking...
2721 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2722 /* error("ternary with different types on the two sides"); */
2723 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2728 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2730 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2733 ir_phi_add(phi, ontrue_out, trueval);
2734 ir_phi_add(phi, onfalse_out, falseval);
2736 self->expression.outr = ir_phi_value(phi);
2737 *out = self->expression.outr;
2739 codegen_output_type(self, *out);
2744 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2746 ast_expression_codegen *cgen;
2748 ir_value *dummy = NULL;
2749 ir_value *precond = NULL;
2750 ir_value *postcond = NULL;
2752 /* Since we insert some jumps "late" so we have blocks
2753 * ordered "nicely", we need to keep track of the actual end-blocks
2754 * of expressions to add the jumps to.
2756 ir_block *bbody = NULL, *end_bbody = NULL;
2757 ir_block *bprecond = NULL, *end_bprecond = NULL;
2758 ir_block *bpostcond = NULL, *end_bpostcond = NULL;
2759 ir_block *bincrement = NULL, *end_bincrement = NULL;
2760 ir_block *bout = NULL, *bin = NULL;
2762 /* let's at least move the outgoing block to the end */
2765 /* 'break' and 'continue' need to be able to find the right blocks */
2766 ir_block *bcontinue = NULL;
2767 ir_block *bbreak = NULL;
2769 ir_block *tmpblock = NULL;
2774 if (self->expression.outr) {
2775 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2778 self->expression.outr = (ir_value*)1;
2781 * Should we ever need some kind of block ordering, better make this function
2782 * move blocks around than write a block ordering algorithm later... after all
2783 * the ast and ir should work together, not against each other.
2786 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2787 * anyway if for example it contains a ternary.
2791 cgen = self->initexpr->codegen;
2792 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2796 /* Store the block from which we enter this chaos */
2797 bin = func->curblock;
2799 /* The pre-loop condition needs its own block since we
2800 * need to be able to jump to the start of that expression.
2804 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2808 /* the pre-loop-condition the least important place to 'continue' at */
2809 bcontinue = bprecond;
2812 func->curblock = bprecond;
2815 cgen = self->precond->codegen;
2816 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2819 end_bprecond = func->curblock;
2821 bprecond = end_bprecond = NULL;
2824 /* Now the next blocks won't be ordered nicely, but we need to
2825 * generate them this early for 'break' and 'continue'.
2827 if (self->increment) {
2828 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2831 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2833 bincrement = end_bincrement = NULL;
2836 if (self->postcond) {
2837 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2840 bcontinue = bpostcond; /* postcond comes before the increment */
2842 bpostcond = end_bpostcond = NULL;
2845 bout_id = vec_size(func->ir_func->blocks);
2846 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2851 /* The loop body... */
2852 /* if (self->body) */
2854 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2859 func->curblock = bbody;
2861 vec_push(func->breakblocks, bbreak);
2863 vec_push(func->continueblocks, bcontinue);
2865 vec_push(func->continueblocks, bbody);
2869 cgen = self->body->codegen;
2870 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2874 end_bbody = func->curblock;
2875 vec_pop(func->breakblocks);
2876 vec_pop(func->continueblocks);
2879 /* post-loop-condition */
2883 func->curblock = bpostcond;
2886 cgen = self->postcond->codegen;
2887 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2890 end_bpostcond = func->curblock;
2893 /* The incrementor */
2894 if (self->increment)
2897 func->curblock = bincrement;
2900 cgen = self->increment->codegen;
2901 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2904 end_bincrement = func->curblock;
2907 /* In any case now, we continue from the outgoing block */
2908 func->curblock = bout;
2910 /* Now all blocks are in place */
2911 /* From 'bin' we jump to whatever comes first */
2912 if (bprecond) tmpblock = bprecond;
2913 else tmpblock = bbody; /* can never be null */
2916 else if (bpostcond) tmpblock = bpostcond;
2917 else tmpblock = bout;
2920 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2926 ir_block *ontrue, *onfalse;
2927 ontrue = bbody; /* can never be null */
2929 /* all of this is dead code
2930 else if (bincrement) ontrue = bincrement;
2931 else ontrue = bpostcond;
2935 if (self->pre_not) {
2940 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
2947 if (bincrement) tmpblock = bincrement;
2948 else if (bpostcond) tmpblock = bpostcond;
2949 else if (bprecond) tmpblock = bprecond;
2950 else tmpblock = bbody;
2951 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
2955 /* from increment */
2958 if (bpostcond) tmpblock = bpostcond;
2959 else if (bprecond) tmpblock = bprecond;
2960 else if (bbody) tmpblock = bbody;
2961 else tmpblock = bout;
2962 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
2969 ir_block *ontrue, *onfalse;
2970 if (bprecond) ontrue = bprecond;
2971 else ontrue = bbody; /* can never be null */
2973 /* all of this is dead code
2974 else if (bincrement) ontrue = bincrement;
2975 else ontrue = bpostcond;
2979 if (self->post_not) {
2984 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
2988 /* Move 'bout' to the end */
2989 vec_remove(func->ir_func->blocks, bout_id, 1);
2990 vec_push(func->ir_func->blocks, bout);
2995 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
3002 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3006 if (self->expression.outr) {
3007 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3010 self->expression.outr = (ir_value*)1;
3012 if (self->is_continue)
3013 target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
3015 target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
3018 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3022 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3027 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3029 ast_expression_codegen *cgen;
3031 ast_switch_case *def_case = NULL;
3032 ir_block *def_bfall = NULL;
3033 ir_block *def_bfall_to = NULL;
3034 bool set_def_bfall_to = false;
3036 ir_value *dummy = NULL;
3037 ir_value *irop = NULL;
3038 ir_block *bout = NULL;
3039 ir_block *bfall = NULL;
3047 compile_error(ast_ctx(self), "switch expression is not an l-value");
3051 if (self->expression.outr) {
3052 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3055 self->expression.outr = (ir_value*)1;
3060 cgen = self->operand->codegen;
3061 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3064 if (!vec_size(self->cases))
3067 cmpinstr = type_eq_instr[irop->vtype];
3068 if (cmpinstr >= VINSTR_END) {
3069 ast_type_to_string(self->operand, typestr, sizeof(typestr));
3070 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3074 bout_id = vec_size(func->ir_func->blocks);
3075 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3079 /* setup the break block */
3080 vec_push(func->breakblocks, bout);
3082 /* Now create all cases */
3083 for (c = 0; c < vec_size(self->cases); ++c) {
3084 ir_value *cond, *val;
3085 ir_block *bcase, *bnot;
3088 ast_switch_case *swcase = &self->cases[c];
3090 if (swcase->value) {
3091 /* A regular case */
3092 /* generate the condition operand */
3093 cgen = swcase->value->codegen;
3094 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3096 /* generate the condition */
3097 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3101 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3102 bnot_id = vec_size(func->ir_func->blocks);
3103 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3104 if (!bcase || !bnot)
3106 if (set_def_bfall_to) {
3107 set_def_bfall_to = false;
3108 def_bfall_to = bcase;
3110 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3113 /* Make the previous case-end fall through */
3114 if (bfall && !bfall->final) {
3115 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3119 /* enter the case */
3120 func->curblock = bcase;
3121 cgen = swcase->code->codegen;
3122 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3125 /* remember this block to fall through from */
3126 bfall = func->curblock;
3128 /* enter the else and move it down */
3129 func->curblock = bnot;
3130 vec_remove(func->ir_func->blocks, bnot_id, 1);
3131 vec_push(func->ir_func->blocks, bnot);
3133 /* The default case */
3134 /* Remember where to fall through from: */
3137 /* remember which case it was */
3139 /* And the next case will be remembered */
3140 set_def_bfall_to = true;
3144 /* Jump from the last bnot to bout */
3145 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3147 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3152 /* If there was a default case, put it down here */
3156 /* No need to create an extra block */
3157 bcase = func->curblock;
3159 /* Insert the fallthrough jump */
3160 if (def_bfall && !def_bfall->final) {
3161 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3165 /* Now generate the default code */
3166 cgen = def_case->code->codegen;
3167 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3170 /* see if we need to fall through */
3171 if (def_bfall_to && !func->curblock->final)
3173 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3178 /* Jump from the last bnot to bout */
3179 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3181 /* enter the outgoing block */
3182 func->curblock = bout;
3184 /* restore the break block */
3185 vec_pop(func->breakblocks);
3187 /* Move 'bout' to the end, it's nicer */
3188 vec_remove(func->ir_func->blocks, bout_id, 1);
3189 vec_push(func->ir_func->blocks, bout);
3194 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3199 if (self->undefined) {
3200 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3206 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3210 /* simply create a new block and jump to it */
3211 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3212 if (!self->irblock) {
3213 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3216 if (!func->curblock->final) {
3217 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3221 /* enter the new block */
3222 func->curblock = self->irblock;
3224 /* Generate all the leftover gotos */
3225 for (i = 0; i < vec_size(self->gotos); ++i) {
3226 if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3233 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3237 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3241 if (self->target->irblock) {
3242 if (self->irblock_from) {
3243 /* we already tried once, this is the callback */
3244 self->irblock_from->final = false;
3245 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3246 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3252 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3253 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3260 /* the target has not yet been created...
3261 * close this block in a sneaky way:
3263 func->curblock->final = true;
3264 self->irblock_from = func->curblock;
3265 ast_label_register_goto(self->target, self);
3271 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3273 ast_expression_codegen *cgen;
3275 ir_instr *callinstr;
3278 ir_value *funval = NULL;
3280 /* return values are never lvalues */
3282 compile_error(ast_ctx(self), "not an l-value (function call)");
3286 if (self->expression.outr) {
3287 *out = self->expression.outr;
3291 cgen = self->func->codegen;
3292 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3300 for (i = 0; i < vec_size(self->params); ++i)
3303 ast_expression *expr = self->params[i];
3305 cgen = expr->codegen;
3306 if (!(*cgen)(expr, func, false, ¶m))
3310 vec_push(params, param);
3313 /* varargs counter */
3314 if (self->va_count) {
3316 ir_builder *builder = func->curblock->owner->owner;
3317 cgen = self->va_count->codegen;
3318 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3320 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3321 ir_builder_get_va_count(builder), va_count))
3327 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3328 ast_function_label(func, "call"),
3329 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3333 for (i = 0; i < vec_size(params); ++i) {
3334 ir_call_param(callinstr, params[i]);
3337 *out = ir_call_value(callinstr);
3338 self->expression.outr = *out;
3340 codegen_output_type(self, *out);