2 * Copyright (C) 2012, 2013
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of
7 * this software and associated documentation files (the "Software"), to deal in
8 * the Software without restriction, including without limitation the rights to
9 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 * of the Software, and to permit persons to whom the Software is furnished to do
11 * so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31 #define ast_instantiate(T, ctx, destroyfn) \
32 T* self = (T*)mem_a(sizeof(T)); \
36 ast_node_init((ast_node*)self, ctx, TYPE_##T); \
37 ( (ast_node*)self )->destroy = (ast_node_delete*)destroyfn
40 * forward declarations, these need not be in ast.h for obvious
43 static bool ast_member_codegen(ast_member*, ast_function*, bool lvalue, ir_value**);
44 static void ast_array_index_delete(ast_array_index*);
45 static bool ast_array_index_codegen(ast_array_index*, ast_function*, bool lvalue, ir_value**);
46 static void ast_argpipe_delete(ast_argpipe*);
47 static bool ast_argpipe_codegen(ast_argpipe*, ast_function*, bool lvalue, ir_value**);
48 static void ast_store_delete(ast_store*);
49 static bool ast_store_codegen(ast_store*, ast_function*, bool lvalue, ir_value**);
50 static void ast_ifthen_delete(ast_ifthen*);
51 static bool ast_ifthen_codegen(ast_ifthen*, ast_function*, bool lvalue, ir_value**);
52 static void ast_ternary_delete(ast_ternary*);
53 static bool ast_ternary_codegen(ast_ternary*, ast_function*, bool lvalue, ir_value**);
54 static void ast_loop_delete(ast_loop*);
55 static bool ast_loop_codegen(ast_loop*, ast_function*, bool lvalue, ir_value**);
56 static void ast_breakcont_delete(ast_breakcont*);
57 static bool ast_breakcont_codegen(ast_breakcont*, ast_function*, bool lvalue, ir_value**);
58 static void ast_switch_delete(ast_switch*);
59 static bool ast_switch_codegen(ast_switch*, ast_function*, bool lvalue, ir_value**);
60 static void ast_label_delete(ast_label*);
61 static void ast_label_register_goto(ast_label*, ast_goto*);
62 static bool ast_label_codegen(ast_label*, ast_function*, bool lvalue, ir_value**);
63 static bool ast_goto_codegen(ast_goto*, ast_function*, bool lvalue, ir_value**);
64 static void ast_goto_delete(ast_goto*);
65 static void ast_call_delete(ast_call*);
66 static bool ast_call_codegen(ast_call*, ast_function*, bool lvalue, ir_value**);
67 static bool ast_block_codegen(ast_block*, ast_function*, bool lvalue, ir_value**);
68 static void ast_unary_delete(ast_unary*);
69 static bool ast_unary_codegen(ast_unary*, ast_function*, bool lvalue, ir_value**);
70 static void ast_entfield_delete(ast_entfield*);
71 static bool ast_entfield_codegen(ast_entfield*, ast_function*, bool lvalue, ir_value**);
72 static void ast_return_delete(ast_return*);
73 static bool ast_return_codegen(ast_return*, ast_function*, bool lvalue, ir_value**);
74 static void ast_binstore_delete(ast_binstore*);
75 static bool ast_binstore_codegen(ast_binstore*, ast_function*, bool lvalue, ir_value**);
76 static void ast_binary_delete(ast_binary*);
77 static bool ast_binary_codegen(ast_binary*, ast_function*, bool lvalue, ir_value**);
79 /* It must not be possible to get here. */
80 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
83 con_err("ast node missing destroy()\n");
87 /* Initialize main ast node aprts */
88 static void ast_node_init(ast_node *self, lex_ctx_t ctx, int nodetype)
91 self->destroy = &_ast_node_destroy;
93 self->nodetype = nodetype;
94 self->side_effects = false;
97 /* weight and side effects */
98 static void _ast_propagate_effects(ast_node *self, ast_node *other)
100 if (ast_side_effects(other))
101 ast_side_effects(self) = true;
103 #define ast_propagate_effects(s,o) _ast_propagate_effects(((ast_node*)(s)), ((ast_node*)(o)))
105 /* General expression initialization */
106 static void ast_expression_init(ast_expression *self,
107 ast_expression_codegen *codegen)
109 self->codegen = codegen;
110 self->vtype = TYPE_VOID;
117 self->varparam = NULL;
120 static void ast_expression_delete(ast_expression *self)
124 ast_delete(self->next);
125 for (i = 0; i < vec_size(self->params); ++i) {
126 ast_delete(self->params[i]);
128 vec_free(self->params);
130 ast_delete(self->varparam);
133 static void ast_expression_delete_full(ast_expression *self)
135 ast_expression_delete(self);
139 ast_value* ast_value_copy(const ast_value *self)
142 const ast_expression *fromex;
143 ast_expression *selfex;
144 ast_value *cp = ast_value_new(self->expression.node.context, self->name, self->expression.vtype);
145 if (self->expression.next) {
146 cp->expression.next = ast_type_copy(self->expression.node.context, self->expression.next);
148 fromex = &self->expression;
149 selfex = &cp->expression;
150 selfex->count = fromex->count;
151 selfex->flags = fromex->flags;
152 for (i = 0; i < vec_size(fromex->params); ++i) {
153 ast_value *v = ast_value_copy(fromex->params[i]);
154 vec_push(selfex->params, v);
159 void ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
162 const ast_expression *fromex;
163 ast_expression *selfex;
164 self->vtype = other->vtype;
166 self->next = (ast_expression*)ast_type_copy(ast_ctx(self), other->next);
170 selfex->count = fromex->count;
171 selfex->flags = fromex->flags;
172 for (i = 0; i < vec_size(fromex->params); ++i) {
173 ast_value *v = ast_value_copy(fromex->params[i]);
174 vec_push(selfex->params, v);
178 static ast_expression* ast_shallow_type(lex_ctx_t ctx, int vtype)
180 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
181 ast_expression_init(self, NULL);
182 self->codegen = NULL;
188 ast_expression* ast_type_copy(lex_ctx_t ctx, const ast_expression *ex)
191 const ast_expression *fromex;
192 ast_expression *selfex;
198 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
199 ast_expression_init(self, NULL);
204 /* This may never be codegen()d */
205 selfex->codegen = NULL;
207 selfex->vtype = fromex->vtype;
209 selfex->next = ast_type_copy(ctx, fromex->next);
213 selfex->count = fromex->count;
214 selfex->flags = fromex->flags;
215 for (i = 0; i < vec_size(fromex->params); ++i) {
216 ast_value *v = ast_value_copy(fromex->params[i]);
217 vec_push(selfex->params, v);
224 bool ast_compare_type(ast_expression *a, ast_expression *b)
226 if (a->vtype == TYPE_NIL ||
227 b->vtype == TYPE_NIL)
229 if (a->vtype != b->vtype)
231 if (!a->next != !b->next)
233 if (vec_size(a->params) != vec_size(b->params))
235 if ((a->flags & AST_FLAG_TYPE_MASK) !=
236 (b->flags & AST_FLAG_TYPE_MASK) )
240 if (vec_size(a->params)) {
242 for (i = 0; i < vec_size(a->params); ++i) {
243 if (!ast_compare_type((ast_expression*)a->params[i],
244 (ast_expression*)b->params[i]))
249 return ast_compare_type(a->next, b->next);
253 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
260 if (pos + 6 >= bufsize)
262 util_strncpy(buf + pos, "(null)", 6);
266 if (pos + 1 >= bufsize)
271 util_strncpy(buf + pos, "(variant)", 9);
276 return ast_type_to_string_impl(e->next, buf, bufsize, pos);
279 if (pos + 3 >= bufsize)
283 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
284 if (pos + 1 >= bufsize)
290 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
291 if (pos + 2 >= bufsize)
293 if (!vec_size(e->params)) {
299 pos = ast_type_to_string_impl((ast_expression*)(e->params[0]), buf, bufsize, pos);
300 for (i = 1; i < vec_size(e->params); ++i) {
301 if (pos + 2 >= bufsize)
305 pos = ast_type_to_string_impl((ast_expression*)(e->params[i]), buf, bufsize, pos);
307 if (pos + 1 >= bufsize)
313 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
314 if (pos + 1 >= bufsize)
317 pos += util_snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->count);
318 if (pos + 1 >= bufsize)
324 typestr = type_name[e->vtype];
325 typelen = strlen(typestr);
326 if (pos + typelen >= bufsize)
328 util_strncpy(buf + pos, typestr, typelen);
329 return pos + typelen;
333 buf[bufsize-3] = '.';
334 buf[bufsize-2] = '.';
335 buf[bufsize-1] = '.';
339 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
341 size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
345 static bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out);
346 ast_value* ast_value_new(lex_ctx_t ctx, const char *name, int t)
348 ast_instantiate(ast_value, ctx, ast_value_delete);
349 ast_expression_init((ast_expression*)self,
350 (ast_expression_codegen*)&ast_value_codegen);
351 self->expression.node.keep = true; /* keep */
353 self->name = name ? util_strdup(name) : NULL;
354 self->expression.vtype = t;
355 self->expression.next = NULL;
356 self->isfield = false;
358 self->hasvalue = false;
361 memset(&self->constval, 0, sizeof(self->constval));
362 self->initlist = NULL;
365 self->ir_values = NULL;
366 self->ir_value_count = 0;
372 self->argcounter = NULL;
373 self->intrinsic = false;
378 void ast_value_delete(ast_value* self)
381 mem_d((void*)self->name);
382 if (self->argcounter)
383 mem_d((void*)self->argcounter);
384 if (self->hasvalue) {
385 switch (self->expression.vtype)
388 mem_d((void*)self->constval.vstring);
391 /* unlink us from the function node */
392 self->constval.vfunc->vtype = NULL;
394 /* NOTE: delete function? currently collected in
395 * the parser structure
402 mem_d(self->ir_values);
407 if (self->initlist) {
408 if (self->expression.next->vtype == TYPE_STRING) {
409 /* strings are allocated, free them */
410 size_t i, len = vec_size(self->initlist);
411 /* in theory, len should be expression.count
412 * but let's not take any chances */
413 for (i = 0; i < len; ++i) {
414 if (self->initlist[i].vstring)
415 mem_d(self->initlist[i].vstring);
418 vec_free(self->initlist);
421 ast_expression_delete((ast_expression*)self);
425 void ast_value_params_add(ast_value *self, ast_value *p)
427 vec_push(self->expression.params, p);
430 bool ast_value_set_name(ast_value *self, const char *name)
433 mem_d((void*)self->name);
434 self->name = util_strdup(name);
438 ast_binary* ast_binary_new(lex_ctx_t ctx, int op,
439 ast_expression* left, ast_expression* right)
442 ast_instantiate(ast_binary, ctx, ast_binary_delete);
443 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
448 self->right_first = false;
450 ast_propagate_effects(self, left);
451 ast_propagate_effects(self, right);
454 * Try to fold away superfluous binary operations, such as:
457 if (OPTS_OPTIMIZATION(OPTIM_PEEPHOLE) && (fold = (ast_binary*)fold_superfluous(left, right, op))) {
458 ast_binary_delete(self);
462 if (op >= INSTR_EQ_F && op <= INSTR_GT)
463 self->expression.vtype = TYPE_FLOAT;
464 else if (op == INSTR_AND || op == INSTR_OR) {
465 if (OPTS_FLAG(PERL_LOGIC))
466 ast_type_adopt(self, right);
468 self->expression.vtype = TYPE_FLOAT;
470 else if (op == INSTR_BITAND || op == INSTR_BITOR || op == INSTR_MUL_F)
471 self->expression.vtype = TYPE_FLOAT;
472 else if (op >= INSTR_MUL_V && op <= INSTR_MUL_VF)
473 self->expression.vtype = TYPE_VECTOR;
475 self->expression.vtype = left->vtype;
478 self->refs = AST_REF_ALL;
483 void ast_binary_delete(ast_binary *self)
485 if (self->refs & AST_REF_LEFT) ast_unref(self->left);
486 if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
488 ast_expression_delete((ast_expression*)self);
492 ast_binstore* ast_binstore_new(lex_ctx_t ctx, int storop, int op,
493 ast_expression* left, ast_expression* right)
495 ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
496 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
498 ast_side_effects(self) = true;
500 self->opstore = storop;
503 self->source = right;
505 self->keep_dest = false;
507 ast_type_adopt(self, left);
511 void ast_binstore_delete(ast_binstore *self)
513 if (!self->keep_dest)
514 ast_unref(self->dest);
515 ast_unref(self->source);
516 ast_expression_delete((ast_expression*)self);
520 ast_unary* ast_unary_new(lex_ctx_t ctx, int op,
521 ast_expression *expr)
523 ast_instantiate(ast_unary, ctx, ast_unary_delete);
524 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
527 self->operand = expr;
530 if (ast_istype(expr, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
531 ast_unary *prev = (ast_unary*)((ast_unary*)expr)->operand;
533 /* Handle for double negation */
534 if ((((ast_unary*)expr)->op == VINSTR_NEG_V && op == VINSTR_NEG_V) ||
535 (((ast_unary*)expr)->op == VINSTR_NEG_F && op == VINSTR_NEG_F)) {
536 prev = (ast_unary*)((ast_unary*)expr)->operand;
539 if (ast_istype(prev, ast_unary)) {
540 ast_expression_delete((ast_expression*)self);
542 ++opts_optimizationcount[OPTIM_PEEPHOLE];
547 ast_propagate_effects(self, expr);
549 if ((op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) || op == VINSTR_NEG_F) {
550 self->expression.vtype = TYPE_FLOAT;
551 } else if (op == VINSTR_NEG_V) {
552 self->expression.vtype = TYPE_VECTOR;
554 compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
560 void ast_unary_delete(ast_unary *self)
562 if (self->operand) ast_unref(self->operand);
563 ast_expression_delete((ast_expression*)self);
567 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
569 ast_instantiate(ast_return, ctx, ast_return_delete);
570 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
572 self->operand = expr;
575 ast_propagate_effects(self, expr);
580 void ast_return_delete(ast_return *self)
583 ast_unref(self->operand);
584 ast_expression_delete((ast_expression*)self);
588 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
590 if (field->vtype != TYPE_FIELD) {
591 compile_error(ctx, "ast_entfield_new with expression not of type field");
594 return ast_entfield_new_force(ctx, entity, field, field->next);
597 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
599 ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
603 /* Error: field has no type... */
607 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
609 self->entity = entity;
611 ast_propagate_effects(self, entity);
612 ast_propagate_effects(self, field);
614 ast_type_adopt(self, outtype);
618 void ast_entfield_delete(ast_entfield *self)
620 ast_unref(self->entity);
621 ast_unref(self->field);
622 ast_expression_delete((ast_expression*)self);
626 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
628 ast_instantiate(ast_member, ctx, ast_member_delete);
634 if (owner->vtype != TYPE_VECTOR &&
635 owner->vtype != TYPE_FIELD) {
636 compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
641 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
642 self->expression.node.keep = true; /* keep */
644 if (owner->vtype == TYPE_VECTOR) {
645 self->expression.vtype = TYPE_FLOAT;
646 self->expression.next = NULL;
648 self->expression.vtype = TYPE_FIELD;
649 self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
652 self->rvalue = false;
654 ast_propagate_effects(self, owner);
658 self->name = util_strdup(name);
665 void ast_member_delete(ast_member *self)
667 /* The owner is always an ast_value, which has .keep=true,
668 * also: ast_members are usually deleted after the owner, thus
669 * this will cause invalid access
670 ast_unref(self->owner);
671 * once we allow (expression).x to access a vector-member, we need
672 * to change this: preferably by creating an alternate ast node for this
673 * purpose that is not garbage-collected.
675 ast_expression_delete((ast_expression*)self);
680 bool ast_member_set_name(ast_member *self, const char *name)
683 mem_d((void*)self->name);
684 self->name = util_strdup(name);
688 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
690 ast_expression *outtype;
691 ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
693 outtype = array->next;
696 /* Error: field has no type... */
700 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
704 ast_propagate_effects(self, array);
705 ast_propagate_effects(self, index);
707 ast_type_adopt(self, outtype);
708 if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
709 if (self->expression.vtype != TYPE_ARRAY) {
710 compile_error(ast_ctx(self), "array_index node on type");
711 ast_array_index_delete(self);
714 self->array = outtype;
715 self->expression.vtype = TYPE_FIELD;
721 void ast_array_index_delete(ast_array_index *self)
724 ast_unref(self->array);
726 ast_unref(self->index);
727 ast_expression_delete((ast_expression*)self);
731 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
733 ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete);
734 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
736 self->expression.vtype = TYPE_NOEXPR;
740 void ast_argpipe_delete(ast_argpipe *self)
743 ast_unref(self->index);
744 ast_expression_delete((ast_expression*)self);
748 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
750 ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
751 if (!ontrue && !onfalse) {
752 /* because it is invalid */
756 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
759 self->on_true = ontrue;
760 self->on_false = onfalse;
761 ast_propagate_effects(self, cond);
763 ast_propagate_effects(self, ontrue);
765 ast_propagate_effects(self, onfalse);
770 void ast_ifthen_delete(ast_ifthen *self)
772 ast_unref(self->cond);
774 ast_unref(self->on_true);
776 ast_unref(self->on_false);
777 ast_expression_delete((ast_expression*)self);
781 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
783 ast_expression *exprtype = ontrue;
784 ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
785 /* This time NEITHER must be NULL */
786 if (!ontrue || !onfalse) {
790 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
793 self->on_true = ontrue;
794 self->on_false = onfalse;
795 ast_propagate_effects(self, cond);
796 ast_propagate_effects(self, ontrue);
797 ast_propagate_effects(self, onfalse);
799 if (ontrue->vtype == TYPE_NIL)
801 ast_type_adopt(self, exprtype);
806 void ast_ternary_delete(ast_ternary *self)
808 /* the if()s are only there because computed-gotos can set them
811 if (self->cond) ast_unref(self->cond);
812 if (self->on_true) ast_unref(self->on_true);
813 if (self->on_false) ast_unref(self->on_false);
814 ast_expression_delete((ast_expression*)self);
818 ast_loop* ast_loop_new(lex_ctx_t ctx,
819 ast_expression *initexpr,
820 ast_expression *precond, bool pre_not,
821 ast_expression *postcond, bool post_not,
822 ast_expression *increment,
823 ast_expression *body)
825 ast_instantiate(ast_loop, ctx, ast_loop_delete);
826 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
828 self->initexpr = initexpr;
829 self->precond = precond;
830 self->postcond = postcond;
831 self->increment = increment;
834 self->pre_not = pre_not;
835 self->post_not = post_not;
838 ast_propagate_effects(self, initexpr);
840 ast_propagate_effects(self, precond);
842 ast_propagate_effects(self, postcond);
844 ast_propagate_effects(self, increment);
846 ast_propagate_effects(self, body);
851 void ast_loop_delete(ast_loop *self)
854 ast_unref(self->initexpr);
856 ast_unref(self->precond);
858 ast_unref(self->postcond);
860 ast_unref(self->increment);
862 ast_unref(self->body);
863 ast_expression_delete((ast_expression*)self);
867 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
869 ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
870 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
872 self->is_continue = iscont;
873 self->levels = levels;
878 void ast_breakcont_delete(ast_breakcont *self)
880 ast_expression_delete((ast_expression*)self);
884 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
886 ast_instantiate(ast_switch, ctx, ast_switch_delete);
887 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
892 ast_propagate_effects(self, op);
897 void ast_switch_delete(ast_switch *self)
900 ast_unref(self->operand);
902 for (i = 0; i < vec_size(self->cases); ++i) {
903 if (self->cases[i].value)
904 ast_unref(self->cases[i].value);
905 ast_unref(self->cases[i].code);
907 vec_free(self->cases);
909 ast_expression_delete((ast_expression*)self);
913 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
915 ast_instantiate(ast_label, ctx, ast_label_delete);
916 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
918 self->expression.vtype = TYPE_NOEXPR;
920 self->name = util_strdup(name);
921 self->irblock = NULL;
923 self->undefined = undefined;
928 void ast_label_delete(ast_label *self)
930 mem_d((void*)self->name);
931 vec_free(self->gotos);
932 ast_expression_delete((ast_expression*)self);
936 static void ast_label_register_goto(ast_label *self, ast_goto *g)
938 vec_push(self->gotos, g);
941 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
943 ast_instantiate(ast_goto, ctx, ast_goto_delete);
944 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
946 self->name = util_strdup(name);
948 self->irblock_from = NULL;
953 void ast_goto_delete(ast_goto *self)
955 mem_d((void*)self->name);
956 ast_expression_delete((ast_expression*)self);
960 void ast_goto_set_label(ast_goto *self, ast_label *label)
962 self->target = label;
965 ast_call* ast_call_new(lex_ctx_t ctx,
966 ast_expression *funcexpr)
968 ast_instantiate(ast_call, ctx, ast_call_delete);
969 if (!funcexpr->next) {
970 compile_error(ctx, "not a function");
974 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
976 ast_side_effects(self) = true;
979 self->func = funcexpr;
980 self->va_count = NULL;
982 ast_type_adopt(self, funcexpr->next);
987 void ast_call_delete(ast_call *self)
990 for (i = 0; i < vec_size(self->params); ++i)
991 ast_unref(self->params[i]);
992 vec_free(self->params);
995 ast_unref(self->func);
998 ast_unref(self->va_count);
1000 ast_expression_delete((ast_expression*)self);
1004 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
1010 if (!va_type || !ast_compare_type(va_type, exp_type))
1012 if (va_type && exp_type)
1014 ast_type_to_string(va_type, tgot, sizeof(tgot));
1015 ast_type_to_string(exp_type, texp, sizeof(texp));
1016 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1017 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1018 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1022 compile_error(ast_ctx(self),
1023 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1030 ast_type_to_string(exp_type, texp, sizeof(texp));
1031 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1032 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1033 "piped variadic argument may differ in type: expected type %s",
1037 compile_error(ast_ctx(self),
1038 "piped variadic argument may differ in type: expected type %s",
1047 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1053 const ast_expression *func = self->func;
1054 size_t count = vec_size(self->params);
1055 if (count > vec_size(func->params))
1056 count = vec_size(func->params);
1058 for (i = 0; i < count; ++i) {
1059 if (ast_istype(self->params[i], ast_argpipe)) {
1060 /* warn about type safety instead */
1062 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1065 if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->params[i]))
1068 else if (!ast_compare_type(self->params[i], (ast_expression*)(func->params[i])))
1070 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1071 ast_type_to_string((ast_expression*)func->params[i], texp, sizeof(texp));
1072 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1073 (unsigned int)(i+1), texp, tgot);
1074 /* we don't immediately return */
1078 count = vec_size(self->params);
1079 if (count > vec_size(func->params) && func->varparam) {
1080 for (; i < count; ++i) {
1081 if (ast_istype(self->params[i], ast_argpipe)) {
1082 /* warn about type safety instead */
1084 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1087 if (!ast_call_check_vararg(self, va_type, func->varparam))
1090 else if (!ast_compare_type(self->params[i], func->varparam))
1092 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1093 ast_type_to_string(func->varparam, texp, sizeof(texp));
1094 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1095 (unsigned int)(i+1), texp, tgot);
1096 /* we don't immediately return */
1104 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1105 ast_expression *dest, ast_expression *source)
1107 ast_instantiate(ast_store, ctx, ast_store_delete);
1108 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1110 ast_side_effects(self) = true;
1114 self->source = source;
1116 ast_type_adopt(self, dest);
1121 void ast_store_delete(ast_store *self)
1123 ast_unref(self->dest);
1124 ast_unref(self->source);
1125 ast_expression_delete((ast_expression*)self);
1129 ast_block* ast_block_new(lex_ctx_t ctx)
1131 ast_instantiate(ast_block, ctx, ast_block_delete);
1132 ast_expression_init((ast_expression*)self,
1133 (ast_expression_codegen*)&ast_block_codegen);
1135 self->locals = NULL;
1137 self->collect = NULL;
1142 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1144 ast_propagate_effects(self, e);
1145 vec_push(self->exprs, e);
1146 if (self->expression.next) {
1147 ast_delete(self->expression.next);
1148 self->expression.next = NULL;
1150 ast_type_adopt(self, e);
1154 void ast_block_collect(ast_block *self, ast_expression *expr)
1156 vec_push(self->collect, expr);
1157 expr->node.keep = true;
1160 void ast_block_delete(ast_block *self)
1163 for (i = 0; i < vec_size(self->exprs); ++i)
1164 ast_unref(self->exprs[i]);
1165 vec_free(self->exprs);
1166 for (i = 0; i < vec_size(self->locals); ++i)
1167 ast_delete(self->locals[i]);
1168 vec_free(self->locals);
1169 for (i = 0; i < vec_size(self->collect); ++i)
1170 ast_delete(self->collect[i]);
1171 vec_free(self->collect);
1172 ast_expression_delete((ast_expression*)self);
1176 void ast_block_set_type(ast_block *self, ast_expression *from)
1178 if (self->expression.next)
1179 ast_delete(self->expression.next);
1180 ast_type_adopt(self, from);
1183 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1185 ast_instantiate(ast_function, ctx, ast_function_delete);
1188 compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1190 } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1191 compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1193 (int)vtype->hasvalue,
1194 vtype->expression.vtype);
1198 self->vtype = vtype;
1199 self->name = name ? util_strdup(name) : NULL;
1200 self->blocks = NULL;
1202 self->labelcount = 0;
1205 self->ir_func = NULL;
1206 self->curblock = NULL;
1208 self->breakblocks = NULL;
1209 self->continueblocks = NULL;
1211 vtype->hasvalue = true;
1212 vtype->constval.vfunc = self;
1214 self->varargs = NULL;
1216 self->fixedparams = NULL;
1217 self->return_value = NULL;
1226 void ast_function_delete(ast_function *self)
1230 mem_d((void*)self->name);
1232 /* ast_value_delete(self->vtype); */
1233 self->vtype->hasvalue = false;
1234 self->vtype->constval.vfunc = NULL;
1235 /* We use unref - if it was stored in a global table it is supposed
1236 * to be deleted from *there*
1238 ast_unref(self->vtype);
1240 for (i = 0; i < vec_size(self->blocks); ++i)
1241 ast_delete(self->blocks[i]);
1242 vec_free(self->blocks);
1243 vec_free(self->breakblocks);
1244 vec_free(self->continueblocks);
1246 ast_delete(self->varargs);
1248 ast_delete(self->argc);
1249 if (self->fixedparams)
1250 ast_unref(self->fixedparams);
1251 if (self->return_value)
1252 ast_unref(self->return_value);
1256 const char* ast_function_label(ast_function *self, const char *prefix)
1262 if (!OPTS_OPTION_BOOL(OPTION_DUMP) &&
1263 !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1264 !OPTS_OPTION_BOOL(OPTION_DEBUG))
1269 id = (self->labelcount++);
1270 len = strlen(prefix);
1272 from = self->labelbuf + sizeof(self->labelbuf)-1;
1275 *from-- = (id%10) + '0';
1279 memcpy(from - len, prefix, len);
1283 /*********************************************************************/
1285 * by convention you must never pass NULL to the 'ir_value **out'
1286 * parameter. If you really don't care about the output, pass a dummy.
1287 * But I can't imagine a pituation where the output is truly unnecessary.
1290 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1292 if (out->vtype == TYPE_FIELD)
1293 out->fieldtype = self->next->vtype;
1294 if (out->vtype == TYPE_FUNCTION)
1295 out->outtype = self->next->vtype;
1298 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1300 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1304 if (self->expression.vtype == TYPE_NIL) {
1305 *out = func->ir_func->owner->nil;
1308 /* NOTE: This is the codegen for a variable used in an expression.
1309 * It is not the codegen to generate the value. For this purpose,
1310 * ast_local_codegen and ast_global_codegen are to be used before this
1311 * is executed. ast_function_codegen should take care of its locals,
1312 * and the ast-user should take care of ast_global_codegen to be used
1313 * on all the globals.
1316 char tname[1024]; /* typename is reserved in C++ */
1317 ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1318 compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1325 static bool ast_global_array_set(ast_value *self)
1327 size_t count = vec_size(self->initlist);
1330 if (count > self->expression.count) {
1331 compile_error(ast_ctx(self), "too many elements in initializer");
1332 count = self->expression.count;
1334 else if (count < self->expression.count) {
1336 compile_warning(ast_ctx(self), "not all elements are initialized");
1340 for (i = 0; i != count; ++i) {
1341 switch (self->expression.next->vtype) {
1343 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1347 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1351 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1355 /* we don't support them in any other place yet either */
1356 compile_error(ast_ctx(self), "TODO: nested arrays");
1359 /* this requiers a bit more work - similar to the fields I suppose */
1360 compile_error(ast_ctx(self), "global of type function not properly generated");
1363 if (!self->initlist[i].vfield) {
1364 compile_error(ast_ctx(self), "field constant without vfield set");
1367 if (!self->initlist[i].vfield->ir_v) {
1368 compile_error(ast_ctx(self), "field constant generated before its field");
1371 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1375 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1382 static bool check_array(ast_value *self, ast_value *array)
1384 if (array->expression.flags & AST_FLAG_ARRAY_INIT && !array->initlist) {
1385 compile_error(ast_ctx(self), "array without size: %s", self->name);
1388 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1389 if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1390 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1396 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1400 if (self->expression.vtype == TYPE_NIL) {
1401 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1405 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1407 ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1410 func->context = ast_ctx(self);
1411 func->value->context = ast_ctx(self);
1413 self->constval.vfunc->ir_func = func;
1414 self->ir_v = func->value;
1415 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1416 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1417 if (self->expression.flags & AST_FLAG_ERASEABLE)
1418 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1419 /* The function is filled later on ast_function_codegen... */
1423 if (isfield && self->expression.vtype == TYPE_FIELD) {
1424 ast_expression *fieldtype = self->expression.next;
1426 if (self->hasvalue) {
1427 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1431 if (fieldtype->vtype == TYPE_ARRAY) {
1436 ast_expression *elemtype;
1438 ast_value *array = (ast_value*)fieldtype;
1440 if (!ast_istype(fieldtype, ast_value)) {
1441 compile_error(ast_ctx(self), "internal error: ast_value required");
1445 if (!check_array(self, array))
1448 elemtype = array->expression.next;
1449 vtype = elemtype->vtype;
1451 v = ir_builder_create_field(ir, self->name, vtype);
1453 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1456 v->context = ast_ctx(self);
1457 v->unique_life = true;
1459 array->ir_v = self->ir_v = v;
1461 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1462 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1463 if (self->expression.flags & AST_FLAG_ERASEABLE)
1464 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1466 namelen = strlen(self->name);
1467 name = (char*)mem_a(namelen + 16);
1468 util_strncpy(name, self->name, namelen);
1470 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1471 array->ir_values[0] = v;
1472 for (ai = 1; ai < array->expression.count; ++ai) {
1473 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1474 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1475 if (!array->ir_values[ai]) {
1477 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1480 array->ir_values[ai]->context = ast_ctx(self);
1481 array->ir_values[ai]->unique_life = true;
1482 array->ir_values[ai]->locked = true;
1483 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1484 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1490 v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1493 v->context = ast_ctx(self);
1495 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1496 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1498 if (self->expression.flags & AST_FLAG_ERASEABLE)
1499 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1504 if (self->expression.vtype == TYPE_ARRAY) {
1509 ast_expression *elemtype = self->expression.next;
1510 int vtype = elemtype->vtype;
1512 if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1513 compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1517 /* same as with field arrays */
1518 if (!check_array(self, self))
1521 v = ir_builder_create_global(ir, self->name, vtype);
1523 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1526 v->context = ast_ctx(self);
1527 v->unique_life = true;
1530 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1531 v->flags |= IR_FLAG_INCLUDE_DEF;
1532 if (self->expression.flags & AST_FLAG_ERASEABLE)
1533 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1535 namelen = strlen(self->name);
1536 name = (char*)mem_a(namelen + 16);
1537 util_strncpy(name, self->name, namelen);
1539 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1540 self->ir_values[0] = v;
1541 for (ai = 1; ai < self->expression.count; ++ai) {
1542 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1543 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1544 if (!self->ir_values[ai]) {
1546 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1549 self->ir_values[ai]->context = ast_ctx(self);
1550 self->ir_values[ai]->unique_life = true;
1551 self->ir_values[ai]->locked = true;
1552 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1553 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1559 /* Arrays don't do this since there's no "array" value which spans across the
1562 v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1564 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1567 codegen_output_type(self, v);
1568 v->context = ast_ctx(self);
1571 /* link us to the ir_value */
1575 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1576 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1577 if (self->expression.flags & AST_FLAG_ERASEABLE)
1578 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1581 if (self->hasvalue) {
1582 switch (self->expression.vtype)
1585 if (!ir_value_set_float(v, self->constval.vfloat))
1589 if (!ir_value_set_vector(v, self->constval.vvec))
1593 if (!ir_value_set_string(v, self->constval.vstring))
1597 ast_global_array_set(self);
1600 compile_error(ast_ctx(self), "global of type function not properly generated");
1602 /* Cannot generate an IR value for a function,
1603 * need a pointer pointing to a function rather.
1606 if (!self->constval.vfield) {
1607 compile_error(ast_ctx(self), "field constant without vfield set");
1610 if (!self->constval.vfield->ir_v) {
1611 compile_error(ast_ctx(self), "field constant generated before its field");
1614 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1618 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1624 error: /* clean up */
1625 if(v) ir_value_delete(v);
1629 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1633 if (self->expression.vtype == TYPE_NIL) {
1634 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1638 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1640 /* Do we allow local functions? I think not...
1641 * this is NOT a function pointer atm.
1646 if (self->expression.vtype == TYPE_ARRAY) {
1651 ast_expression *elemtype = self->expression.next;
1652 int vtype = elemtype->vtype;
1654 func->flags |= IR_FLAG_HAS_ARRAYS;
1656 if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1657 compile_error(ast_ctx(self), "array-parameters are not supported");
1661 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1662 if (!check_array(self, self))
1665 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1666 if (!self->ir_values) {
1667 compile_error(ast_ctx(self), "failed to allocate array values");
1671 v = ir_function_create_local(func, self->name, vtype, param);
1673 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1676 v->context = ast_ctx(self);
1677 v->unique_life = true;
1680 namelen = strlen(self->name);
1681 name = (char*)mem_a(namelen + 16);
1682 util_strncpy(name, self->name, namelen);
1684 self->ir_values[0] = v;
1685 for (ai = 1; ai < self->expression.count; ++ai) {
1686 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1687 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1688 if (!self->ir_values[ai]) {
1689 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1692 self->ir_values[ai]->context = ast_ctx(self);
1693 self->ir_values[ai]->unique_life = true;
1694 self->ir_values[ai]->locked = true;
1700 v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1703 codegen_output_type(self, v);
1704 v->context = ast_ctx(self);
1707 /* A constant local... hmmm...
1708 * I suppose the IR will have to deal with this
1710 if (self->hasvalue) {
1711 switch (self->expression.vtype)
1714 if (!ir_value_set_float(v, self->constval.vfloat))
1718 if (!ir_value_set_vector(v, self->constval.vvec))
1722 if (!ir_value_set_string(v, self->constval.vstring))
1726 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1731 /* link us to the ir_value */
1735 if (!ast_generate_accessors(self, func->owner))
1739 error: /* clean up */
1744 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1747 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1748 if (!self->setter || !self->getter)
1750 for (i = 0; i < self->expression.count; ++i) {
1751 if (!self->ir_values) {
1752 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1755 if (!self->ir_values[i]) {
1756 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1759 if (self->ir_values[i]->life) {
1760 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1765 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1767 if (!ast_global_codegen (self->setter, ir, false) ||
1768 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1769 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1771 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1772 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1777 if (!ast_global_codegen (self->getter, ir, false) ||
1778 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1779 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1781 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1782 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1786 for (i = 0; i < self->expression.count; ++i) {
1787 vec_free(self->ir_values[i]->life);
1789 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1793 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1798 ast_expression_codegen *cgen;
1803 irf = self->ir_func;
1805 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1809 /* fill the parameter list */
1810 ec = &self->vtype->expression;
1811 for (i = 0; i < vec_size(ec->params); ++i)
1813 if (ec->params[i]->expression.vtype == TYPE_FIELD)
1814 vec_push(irf->params, ec->params[i]->expression.next->vtype);
1816 vec_push(irf->params, ec->params[i]->expression.vtype);
1817 if (!self->builtin) {
1818 if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1823 if (self->varargs) {
1824 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1826 irf->max_varargs = self->varargs->expression.count;
1829 if (self->builtin) {
1830 irf->builtin = self->builtin;
1834 /* have a local return value variable? */
1835 if (self->return_value) {
1836 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1840 if (!vec_size(self->blocks)) {
1841 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1845 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1846 if (!self->curblock) {
1847 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1855 if (!ast_local_codegen(self->argc, self->ir_func, true))
1857 cgen = self->argc->expression.codegen;
1858 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1860 cgen = self->fixedparams->expression.codegen;
1861 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1863 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1864 ast_function_label(self, "va_count"), INSTR_SUB_F,
1865 ir_builder_get_va_count(ir), fixed);
1868 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1875 for (i = 0; i < vec_size(self->blocks); ++i) {
1876 cgen = self->blocks[i]->expression.codegen;
1877 if (!(*cgen)((ast_expression*)self->blocks[i], self, false, &dummy))
1881 /* TODO: check return types */
1882 if (!self->curblock->final)
1884 if (!self->vtype->expression.next ||
1885 self->vtype->expression.next->vtype == TYPE_VOID)
1887 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1889 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1891 if (self->return_value) {
1892 cgen = self->return_value->expression.codegen;
1893 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1895 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1897 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1898 "control reaches end of non-void function (`%s`) via %s",
1899 self->name, self->curblock->label))
1903 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1909 static bool starts_a_label(ast_expression *ex)
1911 while (ex && ast_istype(ex, ast_block)) {
1912 ast_block *b = (ast_block*)ex;
1917 return ast_istype(ex, ast_label);
1920 /* Note, you will not see ast_block_codegen generate ir_blocks.
1921 * To the AST and the IR, blocks are 2 different things.
1922 * In the AST it represents a block of code, usually enclosed in
1923 * curly braces {...}.
1924 * While in the IR it represents a block in terms of control-flow.
1926 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1930 /* We don't use this
1931 * Note: an ast-representation using the comma-operator
1932 * of the form: (a, b, c) = x should not assign to c...
1935 compile_error(ast_ctx(self), "not an l-value (code-block)");
1939 if (self->expression.outr) {
1940 *out = self->expression.outr;
1944 /* output is NULL at first, we'll have each expression
1945 * assign to out output, thus, a comma-operator represention
1946 * using an ast_block will return the last generated value,
1947 * so: (b, c) + a executed both b and c, and returns c,
1948 * which is then added to a.
1952 /* generate locals */
1953 for (i = 0; i < vec_size(self->locals); ++i)
1955 if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1956 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1957 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1962 for (i = 0; i < vec_size(self->exprs); ++i)
1964 ast_expression_codegen *gen;
1965 if (func->curblock->final && !starts_a_label(self->exprs[i])) {
1966 if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
1970 gen = self->exprs[i]->codegen;
1971 if (!(*gen)(self->exprs[i], func, false, out))
1975 self->expression.outr = *out;
1980 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1982 ast_expression_codegen *cgen;
1983 ir_value *left = NULL;
1984 ir_value *right = NULL;
1988 ast_array_index *ai = NULL;
1990 if (lvalue && self->expression.outl) {
1991 *out = self->expression.outl;
1995 if (!lvalue && self->expression.outr) {
1996 *out = self->expression.outr;
2000 if (ast_istype(self->dest, ast_array_index))
2003 ai = (ast_array_index*)self->dest;
2004 idx = (ast_value*)ai->index;
2006 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2011 /* we need to call the setter */
2012 ir_value *iridx, *funval;
2016 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2020 arr = (ast_value*)ai->array;
2021 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2022 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2026 cgen = idx->expression.codegen;
2027 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2030 cgen = arr->setter->expression.codegen;
2031 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2034 cgen = self->source->codegen;
2035 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2038 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2041 ir_call_param(call, iridx);
2042 ir_call_param(call, right);
2043 self->expression.outr = right;
2049 cgen = self->dest->codegen;
2051 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
2053 self->expression.outl = left;
2055 cgen = self->source->codegen;
2057 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2060 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2062 self->expression.outr = right;
2065 /* Theoretically, an assinment returns its left side as an
2066 * lvalue, if we don't need an lvalue though, we return
2067 * the right side as an rvalue, otherwise we have to
2068 * somehow know whether or not we need to dereference the pointer
2069 * on the left side - that is: OP_LOAD if it was an address.
2070 * Also: in original QC we cannot OP_LOADP *anyway*.
2072 *out = (lvalue ? left : right);
2077 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2079 ast_expression_codegen *cgen;
2080 ir_value *left, *right;
2082 /* A binary operation cannot yield an l-value */
2084 compile_error(ast_ctx(self), "not an l-value (binop)");
2088 if (self->expression.outr) {
2089 *out = self->expression.outr;
2093 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2094 (self->op == INSTR_AND || self->op == INSTR_OR))
2096 /* NOTE: The short-logic path will ignore right_first */
2098 /* short circuit evaluation */
2099 ir_block *other, *merge;
2100 ir_block *from_left, *from_right;
2104 /* prepare end-block */
2105 merge_id = vec_size(func->ir_func->blocks);
2106 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2108 /* generate the left expression */
2109 cgen = self->left->codegen;
2110 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2112 /* remember the block */
2113 from_left = func->curblock;
2115 /* create a new block for the right expression */
2116 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2117 if (self->op == INSTR_AND) {
2118 /* on AND: left==true -> other */
2119 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2122 /* on OR: left==false -> other */
2123 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2126 /* use the likely flag */
2127 vec_last(func->curblock->instr)->likely = true;
2129 /* enter the right-expression's block */
2130 func->curblock = other;
2132 cgen = self->right->codegen;
2133 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2135 /* remember block */
2136 from_right = func->curblock;
2138 /* jump to the merge block */
2139 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2142 vec_remove(func->ir_func->blocks, merge_id, 1);
2143 vec_push(func->ir_func->blocks, merge);
2145 func->curblock = merge;
2146 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2147 ast_function_label(func, "sce_value"),
2148 self->expression.vtype);
2149 ir_phi_add(phi, from_left, left);
2150 ir_phi_add(phi, from_right, right);
2151 *out = ir_phi_value(phi);
2155 if (!OPTS_FLAG(PERL_LOGIC)) {
2157 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2158 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2159 ast_function_label(func, "sce_bool_v"),
2163 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2164 ast_function_label(func, "sce_bool"),
2169 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2170 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2171 ast_function_label(func, "sce_bool_s"),
2175 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2176 ast_function_label(func, "sce_bool"),
2182 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2183 ast_function_label(func, "sce_bool"),
2184 INSTR_AND, *out, *out);
2190 self->expression.outr = *out;
2191 codegen_output_type(self, *out);
2195 if (self->right_first) {
2196 cgen = self->right->codegen;
2197 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2199 cgen = self->left->codegen;
2200 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2203 cgen = self->left->codegen;
2204 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2206 cgen = self->right->codegen;
2207 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2211 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2212 self->op, left, right);
2215 self->expression.outr = *out;
2216 codegen_output_type(self, *out);
2221 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2223 ast_expression_codegen *cgen;
2224 ir_value *leftl = NULL, *leftr, *right, *bin;
2228 ast_array_index *ai = NULL;
2229 ir_value *iridx = NULL;
2231 if (lvalue && self->expression.outl) {
2232 *out = self->expression.outl;
2236 if (!lvalue && self->expression.outr) {
2237 *out = self->expression.outr;
2241 if (ast_istype(self->dest, ast_array_index))
2244 ai = (ast_array_index*)self->dest;
2245 idx = (ast_value*)ai->index;
2247 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2251 /* for a binstore we need both an lvalue and an rvalue for the left side */
2252 /* rvalue of destination! */
2254 cgen = idx->expression.codegen;
2255 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2258 cgen = self->dest->codegen;
2259 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2262 /* source as rvalue only */
2263 cgen = self->source->codegen;
2264 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2267 /* now the binary */
2268 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2269 self->opbin, leftr, right);
2270 self->expression.outr = bin;
2274 /* we need to call the setter */
2279 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2283 arr = (ast_value*)ai->array;
2284 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2285 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2289 cgen = arr->setter->expression.codegen;
2290 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2293 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2296 ir_call_param(call, iridx);
2297 ir_call_param(call, bin);
2298 self->expression.outr = bin;
2300 /* now store them */
2301 cgen = self->dest->codegen;
2302 /* lvalue of destination */
2303 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2305 self->expression.outl = leftl;
2307 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2309 self->expression.outr = bin;
2312 /* Theoretically, an assinment returns its left side as an
2313 * lvalue, if we don't need an lvalue though, we return
2314 * the right side as an rvalue, otherwise we have to
2315 * somehow know whether or not we need to dereference the pointer
2316 * on the left side - that is: OP_LOAD if it was an address.
2317 * Also: in original QC we cannot OP_LOADP *anyway*.
2319 *out = (lvalue ? leftl : bin);
2324 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2326 ast_expression_codegen *cgen;
2329 /* An unary operation cannot yield an l-value */
2331 compile_error(ast_ctx(self), "not an l-value (binop)");
2335 if (self->expression.outr) {
2336 *out = self->expression.outr;
2340 cgen = self->operand->codegen;
2342 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2345 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2349 self->expression.outr = *out;
2354 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2356 ast_expression_codegen *cgen;
2361 /* In the context of a return operation, we don't actually return
2365 compile_error(ast_ctx(self), "return-expression is not an l-value");
2369 if (self->expression.outr) {
2370 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2373 self->expression.outr = (ir_value*)1;
2375 if (self->operand) {
2376 cgen = self->operand->codegen;
2378 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2381 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2384 if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2391 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2393 ast_expression_codegen *cgen;
2394 ir_value *ent, *field;
2396 /* This function needs to take the 'lvalue' flag into account!
2397 * As lvalue we provide a field-pointer, as rvalue we provide the
2401 if (lvalue && self->expression.outl) {
2402 *out = self->expression.outl;
2406 if (!lvalue && self->expression.outr) {
2407 *out = self->expression.outr;
2411 cgen = self->entity->codegen;
2412 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2415 cgen = self->field->codegen;
2416 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2421 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2424 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2425 ent, field, self->expression.vtype);
2426 /* Done AFTER error checking:
2427 codegen_output_type(self, *out);
2431 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2432 (lvalue ? "ADDRESS" : "FIELD"),
2433 type_name[self->expression.vtype]);
2437 codegen_output_type(self, *out);
2440 self->expression.outl = *out;
2442 self->expression.outr = *out;
2444 /* Hm that should be it... */
2448 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2450 ast_expression_codegen *cgen;
2453 /* in QC this is always an lvalue */
2454 if (lvalue && self->rvalue) {
2455 compile_error(ast_ctx(self), "not an l-value (member access)");
2458 if (self->expression.outl) {
2459 *out = self->expression.outl;
2463 cgen = self->owner->codegen;
2464 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2467 if (vec->vtype != TYPE_VECTOR &&
2468 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2473 *out = ir_value_vector_member(vec, self->field);
2474 self->expression.outl = *out;
2476 return (*out != NULL);
2479 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2484 if (!lvalue && self->expression.outr) {
2485 *out = self->expression.outr;
2488 if (lvalue && self->expression.outl) {
2489 *out = self->expression.outl;
2493 if (!ast_istype(self->array, ast_value)) {
2494 compile_error(ast_ctx(self), "array indexing this way is not supported");
2495 /* note this would actually be pointer indexing because the left side is
2496 * not an actual array but (hopefully) an indexable expression.
2497 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2498 * support this path will be filled.
2503 arr = (ast_value*)self->array;
2504 idx = (ast_value*)self->index;
2506 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2507 /* Time to use accessor functions */
2508 ast_expression_codegen *cgen;
2509 ir_value *iridx, *funval;
2513 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2518 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2522 cgen = self->index->codegen;
2523 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2526 cgen = arr->getter->expression.codegen;
2527 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2530 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2533 ir_call_param(call, iridx);
2535 *out = ir_call_value(call);
2536 self->expression.outr = *out;
2537 (*out)->vtype = self->expression.vtype;
2538 codegen_output_type(self, *out);
2542 if (idx->expression.vtype == TYPE_FLOAT) {
2543 unsigned int arridx = idx->constval.vfloat;
2544 if (arridx >= self->array->count)
2546 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2549 *out = arr->ir_values[arridx];
2551 else if (idx->expression.vtype == TYPE_INTEGER) {
2552 unsigned int arridx = idx->constval.vint;
2553 if (arridx >= self->array->count)
2555 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2558 *out = arr->ir_values[arridx];
2561 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2564 (*out)->vtype = self->expression.vtype;
2565 codegen_output_type(self, *out);
2569 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2573 compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2578 compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2582 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2584 ast_expression_codegen *cgen;
2592 ir_block *ontrue_endblock = NULL;
2593 ir_block *onfalse_endblock = NULL;
2594 ir_block *merge = NULL;
2597 /* We don't output any value, thus also don't care about r/lvalue */
2601 if (self->expression.outr) {
2602 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2605 self->expression.outr = (ir_value*)1;
2607 /* generate the condition */
2608 cgen = self->cond->codegen;
2609 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2611 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2612 cond = func->curblock;
2614 /* try constant folding away the condition */
2615 if ((fold = fold_cond_ifthen(condval, func, self)) != -1)
2618 if (self->on_true) {
2619 /* create on-true block */
2620 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2624 /* enter the block */
2625 func->curblock = ontrue;
2628 cgen = self->on_true->codegen;
2629 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2632 /* we now need to work from the current endpoint */
2633 ontrue_endblock = func->curblock;
2638 if (self->on_false) {
2639 /* create on-false block */
2640 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2644 /* enter the block */
2645 func->curblock = onfalse;
2648 cgen = self->on_false->codegen;
2649 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2652 /* we now need to work from the current endpoint */
2653 onfalse_endblock = func->curblock;
2657 /* Merge block were they all merge in to */
2658 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2660 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2663 /* add jumps ot the merge block */
2664 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2666 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2669 /* Now enter the merge block */
2670 func->curblock = merge;
2673 /* we create the if here, that way all blocks are ordered :)
2675 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2676 (ontrue ? ontrue : merge),
2677 (onfalse ? onfalse : merge)))
2685 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2687 ast_expression_codegen *cgen;
2690 ir_value *trueval, *falseval;
2693 ir_block *cond = func->curblock;
2694 ir_block *cond_out = NULL;
2695 ir_block *ontrue, *ontrue_out = NULL;
2696 ir_block *onfalse, *onfalse_out = NULL;
2700 /* Ternary can never create an lvalue... */
2704 /* In theory it shouldn't be possible to pass through a node twice, but
2705 * in case we add any kind of optimization pass for the AST itself, it
2706 * may still happen, thus we remember a created ir_value and simply return one
2707 * if it already exists.
2709 if (self->expression.outr) {
2710 *out = self->expression.outr;
2714 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2716 /* generate the condition */
2717 func->curblock = cond;
2718 cgen = self->cond->codegen;
2719 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2721 cond_out = func->curblock;
2723 /* try constant folding away the condition */
2724 if ((fold = fold_cond_ternary(condval, func, self)) != -1)
2727 /* create on-true block */
2728 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2733 /* enter the block */
2734 func->curblock = ontrue;
2737 cgen = self->on_true->codegen;
2738 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2741 ontrue_out = func->curblock;
2744 /* create on-false block */
2745 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2750 /* enter the block */
2751 func->curblock = onfalse;
2754 cgen = self->on_false->codegen;
2755 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2758 onfalse_out = func->curblock;
2761 /* create merge block */
2762 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2765 /* jump to merge block */
2766 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2768 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2771 /* create if instruction */
2772 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2775 /* Now enter the merge block */
2776 func->curblock = merge;
2778 /* Here, now, we need a PHI node
2779 * but first some sanity checking...
2781 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2782 /* error("ternary with different types on the two sides"); */
2783 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2788 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2790 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2793 ir_phi_add(phi, ontrue_out, trueval);
2794 ir_phi_add(phi, onfalse_out, falseval);
2796 self->expression.outr = ir_phi_value(phi);
2797 *out = self->expression.outr;
2799 codegen_output_type(self, *out);
2804 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2806 ast_expression_codegen *cgen;
2808 ir_value *dummy = NULL;
2809 ir_value *precond = NULL;
2810 ir_value *postcond = NULL;
2812 /* Since we insert some jumps "late" so we have blocks
2813 * ordered "nicely", we need to keep track of the actual end-blocks
2814 * of expressions to add the jumps to.
2816 ir_block *bbody = NULL, *end_bbody = NULL;
2817 ir_block *bprecond = NULL, *end_bprecond = NULL;
2818 ir_block *bpostcond = NULL, *end_bpostcond = NULL;
2819 ir_block *bincrement = NULL, *end_bincrement = NULL;
2820 ir_block *bout = NULL, *bin = NULL;
2822 /* let's at least move the outgoing block to the end */
2825 /* 'break' and 'continue' need to be able to find the right blocks */
2826 ir_block *bcontinue = NULL;
2827 ir_block *bbreak = NULL;
2829 ir_block *tmpblock = NULL;
2834 if (self->expression.outr) {
2835 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2838 self->expression.outr = (ir_value*)1;
2841 * Should we ever need some kind of block ordering, better make this function
2842 * move blocks around than write a block ordering algorithm later... after all
2843 * the ast and ir should work together, not against each other.
2846 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2847 * anyway if for example it contains a ternary.
2851 cgen = self->initexpr->codegen;
2852 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2856 /* Store the block from which we enter this chaos */
2857 bin = func->curblock;
2859 /* The pre-loop condition needs its own block since we
2860 * need to be able to jump to the start of that expression.
2864 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2868 /* the pre-loop-condition the least important place to 'continue' at */
2869 bcontinue = bprecond;
2872 func->curblock = bprecond;
2875 cgen = self->precond->codegen;
2876 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2879 end_bprecond = func->curblock;
2881 bprecond = end_bprecond = NULL;
2884 /* Now the next blocks won't be ordered nicely, but we need to
2885 * generate them this early for 'break' and 'continue'.
2887 if (self->increment) {
2888 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2891 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2893 bincrement = end_bincrement = NULL;
2896 if (self->postcond) {
2897 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2900 bcontinue = bpostcond; /* postcond comes before the increment */
2902 bpostcond = end_bpostcond = NULL;
2905 bout_id = vec_size(func->ir_func->blocks);
2906 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2911 /* The loop body... */
2912 /* if (self->body) */
2914 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2919 func->curblock = bbody;
2921 vec_push(func->breakblocks, bbreak);
2923 vec_push(func->continueblocks, bcontinue);
2925 vec_push(func->continueblocks, bbody);
2929 cgen = self->body->codegen;
2930 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2934 end_bbody = func->curblock;
2935 vec_pop(func->breakblocks);
2936 vec_pop(func->continueblocks);
2939 /* post-loop-condition */
2943 func->curblock = bpostcond;
2946 cgen = self->postcond->codegen;
2947 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2950 end_bpostcond = func->curblock;
2953 /* The incrementor */
2954 if (self->increment)
2957 func->curblock = bincrement;
2960 cgen = self->increment->codegen;
2961 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2964 end_bincrement = func->curblock;
2967 /* In any case now, we continue from the outgoing block */
2968 func->curblock = bout;
2970 /* Now all blocks are in place */
2971 /* From 'bin' we jump to whatever comes first */
2972 if (bprecond) tmpblock = bprecond;
2973 else tmpblock = bbody; /* can never be null */
2976 else if (bpostcond) tmpblock = bpostcond;
2977 else tmpblock = bout;
2980 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2986 ir_block *ontrue, *onfalse;
2987 ontrue = bbody; /* can never be null */
2989 /* all of this is dead code
2990 else if (bincrement) ontrue = bincrement;
2991 else ontrue = bpostcond;
2995 if (self->pre_not) {
3000 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
3007 if (bincrement) tmpblock = bincrement;
3008 else if (bpostcond) tmpblock = bpostcond;
3009 else if (bprecond) tmpblock = bprecond;
3010 else tmpblock = bbody;
3011 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
3015 /* from increment */
3018 if (bpostcond) tmpblock = bpostcond;
3019 else if (bprecond) tmpblock = bprecond;
3020 else if (bbody) tmpblock = bbody;
3021 else tmpblock = bout;
3022 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
3029 ir_block *ontrue, *onfalse;
3030 if (bprecond) ontrue = bprecond;
3031 else ontrue = bbody; /* can never be null */
3033 /* all of this is dead code
3034 else if (bincrement) ontrue = bincrement;
3035 else ontrue = bpostcond;
3039 if (self->post_not) {
3044 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
3048 /* Move 'bout' to the end */
3049 vec_remove(func->ir_func->blocks, bout_id, 1);
3050 vec_push(func->ir_func->blocks, bout);
3055 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
3062 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3066 if (self->expression.outr) {
3067 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3070 self->expression.outr = (ir_value*)1;
3072 if (self->is_continue)
3073 target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
3075 target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
3078 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3082 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3087 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3089 ast_expression_codegen *cgen;
3091 ast_switch_case *def_case = NULL;
3092 ir_block *def_bfall = NULL;
3093 ir_block *def_bfall_to = NULL;
3094 bool set_def_bfall_to = false;
3096 ir_value *dummy = NULL;
3097 ir_value *irop = NULL;
3098 ir_block *bout = NULL;
3099 ir_block *bfall = NULL;
3107 compile_error(ast_ctx(self), "switch expression is not an l-value");
3111 if (self->expression.outr) {
3112 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3115 self->expression.outr = (ir_value*)1;
3120 cgen = self->operand->codegen;
3121 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3124 if (!vec_size(self->cases))
3127 cmpinstr = type_eq_instr[irop->vtype];
3128 if (cmpinstr >= VINSTR_END) {
3129 ast_type_to_string(self->operand, typestr, sizeof(typestr));
3130 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3134 bout_id = vec_size(func->ir_func->blocks);
3135 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3139 /* setup the break block */
3140 vec_push(func->breakblocks, bout);
3142 /* Now create all cases */
3143 for (c = 0; c < vec_size(self->cases); ++c) {
3144 ir_value *cond, *val;
3145 ir_block *bcase, *bnot;
3148 ast_switch_case *swcase = &self->cases[c];
3150 if (swcase->value) {
3151 /* A regular case */
3152 /* generate the condition operand */
3153 cgen = swcase->value->codegen;
3154 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3156 /* generate the condition */
3157 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3161 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3162 bnot_id = vec_size(func->ir_func->blocks);
3163 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3164 if (!bcase || !bnot)
3166 if (set_def_bfall_to) {
3167 set_def_bfall_to = false;
3168 def_bfall_to = bcase;
3170 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3173 /* Make the previous case-end fall through */
3174 if (bfall && !bfall->final) {
3175 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3179 /* enter the case */
3180 func->curblock = bcase;
3181 cgen = swcase->code->codegen;
3182 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3185 /* remember this block to fall through from */
3186 bfall = func->curblock;
3188 /* enter the else and move it down */
3189 func->curblock = bnot;
3190 vec_remove(func->ir_func->blocks, bnot_id, 1);
3191 vec_push(func->ir_func->blocks, bnot);
3193 /* The default case */
3194 /* Remember where to fall through from: */
3197 /* remember which case it was */
3199 /* And the next case will be remembered */
3200 set_def_bfall_to = true;
3204 /* Jump from the last bnot to bout */
3205 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3207 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3212 /* If there was a default case, put it down here */
3216 /* No need to create an extra block */
3217 bcase = func->curblock;
3219 /* Insert the fallthrough jump */
3220 if (def_bfall && !def_bfall->final) {
3221 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3225 /* Now generate the default code */
3226 cgen = def_case->code->codegen;
3227 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3230 /* see if we need to fall through */
3231 if (def_bfall_to && !func->curblock->final)
3233 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3238 /* Jump from the last bnot to bout */
3239 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3241 /* enter the outgoing block */
3242 func->curblock = bout;
3244 /* restore the break block */
3245 vec_pop(func->breakblocks);
3247 /* Move 'bout' to the end, it's nicer */
3248 vec_remove(func->ir_func->blocks, bout_id, 1);
3249 vec_push(func->ir_func->blocks, bout);
3254 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3259 if (self->undefined) {
3260 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3266 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3270 /* simply create a new block and jump to it */
3271 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3272 if (!self->irblock) {
3273 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3276 if (!func->curblock->final) {
3277 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3281 /* enter the new block */
3282 func->curblock = self->irblock;
3284 /* Generate all the leftover gotos */
3285 for (i = 0; i < vec_size(self->gotos); ++i) {
3286 if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3293 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3297 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3301 if (self->target->irblock) {
3302 if (self->irblock_from) {
3303 /* we already tried once, this is the callback */
3304 self->irblock_from->final = false;
3305 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3306 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3312 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3313 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3320 /* the target has not yet been created...
3321 * close this block in a sneaky way:
3323 func->curblock->final = true;
3324 self->irblock_from = func->curblock;
3325 ast_label_register_goto(self->target, self);
3331 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3333 ast_expression_codegen *cgen;
3335 ir_instr *callinstr;
3338 ir_value *funval = NULL;
3340 /* return values are never lvalues */
3342 compile_error(ast_ctx(self), "not an l-value (function call)");
3346 if (self->expression.outr) {
3347 *out = self->expression.outr;
3351 cgen = self->func->codegen;
3352 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3360 for (i = 0; i < vec_size(self->params); ++i)
3363 ast_expression *expr = self->params[i];
3365 cgen = expr->codegen;
3366 if (!(*cgen)(expr, func, false, ¶m))
3370 vec_push(params, param);
3373 /* varargs counter */
3374 if (self->va_count) {
3376 ir_builder *builder = func->curblock->owner->owner;
3377 cgen = self->va_count->codegen;
3378 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3380 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3381 ir_builder_get_va_count(builder), va_count))
3387 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3388 ast_function_label(func, "call"),
3389 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3393 for (i = 0; i < vec_size(params); ++i) {
3394 ir_call_param(callinstr, params[i]);
3397 *out = ir_call_value(callinstr);
3398 self->expression.outr = *out;
3400 codegen_output_type(self, *out);