2 * Copyright (C) 2012, 2013, 2014
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;
116 self->varparam = NULL;
118 if (OPTS_OPTION_BOOL(OPTION_COVERAGE))
119 self->flags |= AST_FLAG_BLOCK_COVERAGE;
122 static void ast_expression_delete(ast_expression *self)
126 ast_delete(self->next);
127 for (i = 0; i < vec_size(self->params); ++i) {
128 ast_delete(self->params[i]);
130 vec_free(self->params);
132 ast_delete(self->varparam);
135 static void ast_expression_delete_full(ast_expression *self)
137 ast_expression_delete(self);
141 ast_value* ast_value_copy(const ast_value *self)
144 const ast_expression *fromex;
145 ast_expression *selfex;
146 ast_value *cp = ast_value_new(self->expression.node.context, self->name, self->expression.vtype);
147 if (self->expression.next) {
148 cp->expression.next = ast_type_copy(self->expression.node.context, self->expression.next);
150 fromex = &self->expression;
151 selfex = &cp->expression;
152 selfex->count = fromex->count;
153 selfex->flags = fromex->flags;
154 for (i = 0; i < vec_size(fromex->params); ++i) {
155 ast_value *v = ast_value_copy(fromex->params[i]);
156 vec_push(selfex->params, v);
161 void ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
164 const ast_expression *fromex;
165 ast_expression *selfex;
166 self->vtype = other->vtype;
168 self->next = (ast_expression*)ast_type_copy(ast_ctx(self), other->next);
172 selfex->count = fromex->count;
173 selfex->flags = fromex->flags;
174 for (i = 0; i < vec_size(fromex->params); ++i) {
175 ast_value *v = ast_value_copy(fromex->params[i]);
176 vec_push(selfex->params, v);
180 static ast_expression* ast_shallow_type(lex_ctx_t ctx, int vtype)
182 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
183 ast_expression_init(self, NULL);
184 self->codegen = NULL;
190 ast_expression* ast_type_copy(lex_ctx_t ctx, const ast_expression *ex)
193 const ast_expression *fromex;
194 ast_expression *selfex;
200 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
201 ast_expression_init(self, NULL);
206 /* This may never be codegen()d */
207 selfex->codegen = NULL;
209 selfex->vtype = fromex->vtype;
211 selfex->next = ast_type_copy(ctx, fromex->next);
215 selfex->count = fromex->count;
216 selfex->flags = fromex->flags;
217 for (i = 0; i < vec_size(fromex->params); ++i) {
218 ast_value *v = ast_value_copy(fromex->params[i]);
219 vec_push(selfex->params, v);
226 bool ast_compare_type(ast_expression *a, ast_expression *b)
228 if (a->vtype == TYPE_NIL ||
229 b->vtype == TYPE_NIL)
231 if (a->vtype != b->vtype)
233 if (!a->next != !b->next)
235 if (vec_size(a->params) != vec_size(b->params))
237 if ((a->flags & AST_FLAG_TYPE_MASK) !=
238 (b->flags & AST_FLAG_TYPE_MASK) )
242 if (vec_size(a->params)) {
244 for (i = 0; i < vec_size(a->params); ++i) {
245 if (!ast_compare_type((ast_expression*)a->params[i],
246 (ast_expression*)b->params[i]))
251 return ast_compare_type(a->next, b->next);
255 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
262 if (pos + 6 >= bufsize)
264 util_strncpy(buf + pos, "(null)", 6);
268 if (pos + 1 >= bufsize)
273 util_strncpy(buf + pos, "(variant)", 9);
278 return ast_type_to_string_impl(e->next, buf, bufsize, pos);
281 if (pos + 3 >= bufsize)
285 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
286 if (pos + 1 >= bufsize)
292 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
293 if (pos + 2 >= bufsize)
295 if (!vec_size(e->params)) {
301 pos = ast_type_to_string_impl((ast_expression*)(e->params[0]), buf, bufsize, pos);
302 for (i = 1; i < vec_size(e->params); ++i) {
303 if (pos + 2 >= bufsize)
307 pos = ast_type_to_string_impl((ast_expression*)(e->params[i]), buf, bufsize, pos);
309 if (pos + 1 >= bufsize)
315 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
316 if (pos + 1 >= bufsize)
319 pos += util_snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->count);
320 if (pos + 1 >= bufsize)
326 typestr = type_name[e->vtype];
327 typelen = strlen(typestr);
328 if (pos + typelen >= bufsize)
330 util_strncpy(buf + pos, typestr, typelen);
331 return pos + typelen;
335 buf[bufsize-3] = '.';
336 buf[bufsize-2] = '.';
337 buf[bufsize-1] = '.';
341 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
343 size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
347 static bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out);
348 ast_value* ast_value_new(lex_ctx_t ctx, const char *name, int t)
350 ast_instantiate(ast_value, ctx, ast_value_delete);
351 ast_expression_init((ast_expression*)self,
352 (ast_expression_codegen*)&ast_value_codegen);
353 self->expression.node.keep = true; /* keep */
355 self->name = name ? util_strdup(name) : NULL;
356 self->expression.vtype = t;
357 self->expression.next = NULL;
358 self->isfield = false;
360 self->hasvalue = false;
362 self->inexact = false;
364 memset(&self->constval, 0, sizeof(self->constval));
365 self->initlist = NULL;
368 self->ir_values = NULL;
369 self->ir_value_count = 0;
375 self->argcounter = NULL;
376 self->intrinsic = false;
381 void ast_value_delete(ast_value* self)
384 mem_d((void*)self->name);
385 if (self->argcounter)
386 mem_d((void*)self->argcounter);
387 if (self->hasvalue) {
388 switch (self->expression.vtype)
391 mem_d((void*)self->constval.vstring);
394 /* unlink us from the function node */
395 self->constval.vfunc->vtype = NULL;
397 /* NOTE: delete function? currently collected in
398 * the parser structure
405 mem_d(self->ir_values);
410 if (self->initlist) {
411 if (self->expression.next->vtype == TYPE_STRING) {
412 /* strings are allocated, free them */
413 size_t i, len = vec_size(self->initlist);
414 /* in theory, len should be expression.count
415 * but let's not take any chances */
416 for (i = 0; i < len; ++i) {
417 if (self->initlist[i].vstring)
418 mem_d(self->initlist[i].vstring);
421 vec_free(self->initlist);
424 ast_expression_delete((ast_expression*)self);
428 void ast_value_params_add(ast_value *self, ast_value *p)
430 vec_push(self->expression.params, p);
433 bool ast_value_set_name(ast_value *self, const char *name)
436 mem_d((void*)self->name);
437 self->name = util_strdup(name);
441 ast_binary* ast_binary_new(lex_ctx_t ctx, int op,
442 ast_expression* left, ast_expression* right)
444 ast_instantiate(ast_binary, ctx, ast_binary_delete);
445 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
447 if (ast_istype(right, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
448 ast_unary *unary = ((ast_unary*)right);
449 ast_expression *normal = unary->operand;
451 /* make a-(-b) => a + b */
452 if (unary->op == VINSTR_NEG_F || unary->op == VINSTR_NEG_V) {
453 if (op == INSTR_SUB_F) {
456 ++opts_optimizationcount[OPTIM_PEEPHOLE];
457 } else if (op == INSTR_SUB_V) {
460 ++opts_optimizationcount[OPTIM_PEEPHOLE];
468 self->right_first = false;
470 ast_propagate_effects(self, left);
471 ast_propagate_effects(self, right);
473 if (op >= INSTR_EQ_F && op <= INSTR_GT)
474 self->expression.vtype = TYPE_FLOAT;
475 else if (op == INSTR_AND || op == INSTR_OR) {
476 if (OPTS_FLAG(PERL_LOGIC))
477 ast_type_adopt(self, right);
479 self->expression.vtype = TYPE_FLOAT;
481 else if (op == INSTR_BITAND || op == INSTR_BITOR)
482 self->expression.vtype = TYPE_FLOAT;
483 else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
484 self->expression.vtype = TYPE_VECTOR;
485 else if (op == INSTR_MUL_V)
486 self->expression.vtype = TYPE_FLOAT;
488 self->expression.vtype = left->vtype;
491 self->refs = AST_REF_ALL;
496 void ast_binary_delete(ast_binary *self)
498 if (self->refs & AST_REF_LEFT) ast_unref(self->left);
499 if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
501 ast_expression_delete((ast_expression*)self);
505 ast_binstore* ast_binstore_new(lex_ctx_t ctx, int storop, int op,
506 ast_expression* left, ast_expression* right)
508 ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
509 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
511 ast_side_effects(self) = true;
513 self->opstore = storop;
516 self->source = right;
518 self->keep_dest = false;
520 ast_type_adopt(self, left);
524 void ast_binstore_delete(ast_binstore *self)
526 if (!self->keep_dest)
527 ast_unref(self->dest);
528 ast_unref(self->source);
529 ast_expression_delete((ast_expression*)self);
533 ast_unary* ast_unary_new(lex_ctx_t ctx, int op,
534 ast_expression *expr)
536 ast_instantiate(ast_unary, ctx, ast_unary_delete);
537 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
540 self->operand = expr;
543 if (ast_istype(expr, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
544 ast_unary *prev = (ast_unary*)((ast_unary*)expr)->operand;
546 /* Handle for double negation */
547 if (((ast_unary*)expr)->op == op)
548 prev = (ast_unary*)((ast_unary*)expr)->operand;
550 if (ast_istype(prev, ast_unary)) {
551 ast_expression_delete((ast_expression*)self);
553 ++opts_optimizationcount[OPTIM_PEEPHOLE];
558 ast_propagate_effects(self, expr);
560 if ((op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) || op == VINSTR_NEG_F) {
561 self->expression.vtype = TYPE_FLOAT;
562 } else if (op == VINSTR_NEG_V) {
563 self->expression.vtype = TYPE_VECTOR;
565 compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
571 void ast_unary_delete(ast_unary *self)
573 if (self->operand) ast_unref(self->operand);
574 ast_expression_delete((ast_expression*)self);
578 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
580 ast_instantiate(ast_return, ctx, ast_return_delete);
581 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
583 self->operand = expr;
586 ast_propagate_effects(self, expr);
591 void ast_return_delete(ast_return *self)
594 ast_unref(self->operand);
595 ast_expression_delete((ast_expression*)self);
599 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
601 if (field->vtype != TYPE_FIELD) {
602 compile_error(ctx, "ast_entfield_new with expression not of type field");
605 return ast_entfield_new_force(ctx, entity, field, field->next);
608 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
610 ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
614 /* Error: field has no type... */
618 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
620 self->entity = entity;
622 ast_propagate_effects(self, entity);
623 ast_propagate_effects(self, field);
625 ast_type_adopt(self, outtype);
629 void ast_entfield_delete(ast_entfield *self)
631 ast_unref(self->entity);
632 ast_unref(self->field);
633 ast_expression_delete((ast_expression*)self);
637 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
639 ast_instantiate(ast_member, ctx, ast_member_delete);
645 if (owner->vtype != TYPE_VECTOR &&
646 owner->vtype != TYPE_FIELD) {
647 compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
652 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
653 self->expression.node.keep = true; /* keep */
655 if (owner->vtype == TYPE_VECTOR) {
656 self->expression.vtype = TYPE_FLOAT;
657 self->expression.next = NULL;
659 self->expression.vtype = TYPE_FIELD;
660 self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
663 self->rvalue = false;
665 ast_propagate_effects(self, owner);
669 self->name = util_strdup(name);
676 void ast_member_delete(ast_member *self)
678 /* The owner is always an ast_value, which has .keep=true,
679 * also: ast_members are usually deleted after the owner, thus
680 * this will cause invalid access
681 ast_unref(self->owner);
682 * once we allow (expression).x to access a vector-member, we need
683 * to change this: preferably by creating an alternate ast node for this
684 * purpose that is not garbage-collected.
686 ast_expression_delete((ast_expression*)self);
691 bool ast_member_set_name(ast_member *self, const char *name)
694 mem_d((void*)self->name);
695 self->name = util_strdup(name);
699 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
701 ast_expression *outtype;
702 ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
704 outtype = array->next;
707 /* Error: field has no type... */
711 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
715 ast_propagate_effects(self, array);
716 ast_propagate_effects(self, index);
718 ast_type_adopt(self, outtype);
719 if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
720 if (self->expression.vtype != TYPE_ARRAY) {
721 compile_error(ast_ctx(self), "array_index node on type");
722 ast_array_index_delete(self);
725 self->array = outtype;
726 self->expression.vtype = TYPE_FIELD;
732 void ast_array_index_delete(ast_array_index *self)
735 ast_unref(self->array);
737 ast_unref(self->index);
738 ast_expression_delete((ast_expression*)self);
742 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
744 ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete);
745 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
747 self->expression.vtype = TYPE_NOEXPR;
751 void ast_argpipe_delete(ast_argpipe *self)
754 ast_unref(self->index);
755 ast_expression_delete((ast_expression*)self);
759 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
761 ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
762 if (!ontrue && !onfalse) {
763 /* because it is invalid */
767 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
770 self->on_true = ontrue;
771 self->on_false = onfalse;
772 ast_propagate_effects(self, cond);
774 ast_propagate_effects(self, ontrue);
776 ast_propagate_effects(self, onfalse);
781 void ast_ifthen_delete(ast_ifthen *self)
783 ast_unref(self->cond);
785 ast_unref(self->on_true);
787 ast_unref(self->on_false);
788 ast_expression_delete((ast_expression*)self);
792 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
794 ast_expression *exprtype = ontrue;
795 ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
796 /* This time NEITHER must be NULL */
797 if (!ontrue || !onfalse) {
801 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
804 self->on_true = ontrue;
805 self->on_false = onfalse;
806 ast_propagate_effects(self, cond);
807 ast_propagate_effects(self, ontrue);
808 ast_propagate_effects(self, onfalse);
810 if (ontrue->vtype == TYPE_NIL)
812 ast_type_adopt(self, exprtype);
817 void ast_ternary_delete(ast_ternary *self)
819 /* the if()s are only there because computed-gotos can set them
822 if (self->cond) ast_unref(self->cond);
823 if (self->on_true) ast_unref(self->on_true);
824 if (self->on_false) ast_unref(self->on_false);
825 ast_expression_delete((ast_expression*)self);
829 ast_loop* ast_loop_new(lex_ctx_t ctx,
830 ast_expression *initexpr,
831 ast_expression *precond, bool pre_not,
832 ast_expression *postcond, bool post_not,
833 ast_expression *increment,
834 ast_expression *body)
836 ast_instantiate(ast_loop, ctx, ast_loop_delete);
837 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
839 self->initexpr = initexpr;
840 self->precond = precond;
841 self->postcond = postcond;
842 self->increment = increment;
845 self->pre_not = pre_not;
846 self->post_not = post_not;
849 ast_propagate_effects(self, initexpr);
851 ast_propagate_effects(self, precond);
853 ast_propagate_effects(self, postcond);
855 ast_propagate_effects(self, increment);
857 ast_propagate_effects(self, body);
862 void ast_loop_delete(ast_loop *self)
865 ast_unref(self->initexpr);
867 ast_unref(self->precond);
869 ast_unref(self->postcond);
871 ast_unref(self->increment);
873 ast_unref(self->body);
874 ast_expression_delete((ast_expression*)self);
878 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
880 ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
881 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
883 self->is_continue = iscont;
884 self->levels = levels;
889 void ast_breakcont_delete(ast_breakcont *self)
891 ast_expression_delete((ast_expression*)self);
895 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
897 ast_instantiate(ast_switch, ctx, ast_switch_delete);
898 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
903 ast_propagate_effects(self, op);
908 void ast_switch_delete(ast_switch *self)
911 ast_unref(self->operand);
913 for (i = 0; i < vec_size(self->cases); ++i) {
914 if (self->cases[i].value)
915 ast_unref(self->cases[i].value);
916 ast_unref(self->cases[i].code);
918 vec_free(self->cases);
920 ast_expression_delete((ast_expression*)self);
924 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
926 ast_instantiate(ast_label, ctx, ast_label_delete);
927 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
929 self->expression.vtype = TYPE_NOEXPR;
931 self->name = util_strdup(name);
932 self->irblock = NULL;
934 self->undefined = undefined;
939 void ast_label_delete(ast_label *self)
941 mem_d((void*)self->name);
942 vec_free(self->gotos);
943 ast_expression_delete((ast_expression*)self);
947 static void ast_label_register_goto(ast_label *self, ast_goto *g)
949 vec_push(self->gotos, g);
952 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
954 ast_instantiate(ast_goto, ctx, ast_goto_delete);
955 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
957 self->name = util_strdup(name);
959 self->irblock_from = NULL;
964 void ast_goto_delete(ast_goto *self)
966 mem_d((void*)self->name);
967 ast_expression_delete((ast_expression*)self);
971 void ast_goto_set_label(ast_goto *self, ast_label *label)
973 self->target = label;
976 ast_call* ast_call_new(lex_ctx_t ctx,
977 ast_expression *funcexpr)
979 ast_instantiate(ast_call, ctx, ast_call_delete);
980 if (!funcexpr->next) {
981 compile_error(ctx, "not a function");
985 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
987 ast_side_effects(self) = true;
990 self->func = funcexpr;
991 self->va_count = NULL;
993 ast_type_adopt(self, funcexpr->next);
998 void ast_call_delete(ast_call *self)
1001 for (i = 0; i < vec_size(self->params); ++i)
1002 ast_unref(self->params[i]);
1003 vec_free(self->params);
1006 ast_unref(self->func);
1009 ast_unref(self->va_count);
1011 ast_expression_delete((ast_expression*)self);
1015 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
1021 if (!va_type || !ast_compare_type(va_type, exp_type))
1023 if (va_type && exp_type)
1025 ast_type_to_string(va_type, tgot, sizeof(tgot));
1026 ast_type_to_string(exp_type, texp, sizeof(texp));
1027 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1028 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1029 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1033 compile_error(ast_ctx(self),
1034 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1041 ast_type_to_string(exp_type, texp, sizeof(texp));
1042 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1043 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1044 "piped variadic argument may differ in type: expected type %s",
1048 compile_error(ast_ctx(self),
1049 "piped variadic argument may differ in type: expected type %s",
1058 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1064 const ast_expression *func = self->func;
1065 size_t count = vec_size(self->params);
1066 if (count > vec_size(func->params))
1067 count = vec_size(func->params);
1069 for (i = 0; i < count; ++i) {
1070 if (ast_istype(self->params[i], ast_argpipe)) {
1071 /* warn about type safety instead */
1073 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1076 if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->params[i]))
1079 else if (!ast_compare_type(self->params[i], (ast_expression*)(func->params[i])))
1081 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1082 ast_type_to_string((ast_expression*)func->params[i], texp, sizeof(texp));
1083 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1084 (unsigned int)(i+1), texp, tgot);
1085 /* we don't immediately return */
1089 count = vec_size(self->params);
1090 if (count > vec_size(func->params) && func->varparam) {
1091 for (; i < count; ++i) {
1092 if (ast_istype(self->params[i], ast_argpipe)) {
1093 /* warn about type safety instead */
1095 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1098 if (!ast_call_check_vararg(self, va_type, func->varparam))
1101 else if (!ast_compare_type(self->params[i], func->varparam))
1103 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1104 ast_type_to_string(func->varparam, texp, sizeof(texp));
1105 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1106 (unsigned int)(i+1), texp, tgot);
1107 /* we don't immediately return */
1115 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1116 ast_expression *dest, ast_expression *source)
1118 ast_instantiate(ast_store, ctx, ast_store_delete);
1119 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1121 ast_side_effects(self) = true;
1125 self->source = source;
1127 ast_type_adopt(self, dest);
1132 void ast_store_delete(ast_store *self)
1134 ast_unref(self->dest);
1135 ast_unref(self->source);
1136 ast_expression_delete((ast_expression*)self);
1140 ast_block* ast_block_new(lex_ctx_t ctx)
1142 ast_instantiate(ast_block, ctx, ast_block_delete);
1143 ast_expression_init((ast_expression*)self,
1144 (ast_expression_codegen*)&ast_block_codegen);
1146 self->locals = NULL;
1148 self->collect = NULL;
1153 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1155 ast_propagate_effects(self, e);
1156 vec_push(self->exprs, e);
1157 if (self->expression.next) {
1158 ast_delete(self->expression.next);
1159 self->expression.next = NULL;
1161 ast_type_adopt(self, e);
1165 void ast_block_collect(ast_block *self, ast_expression *expr)
1167 vec_push(self->collect, expr);
1168 expr->node.keep = true;
1171 void ast_block_delete(ast_block *self)
1174 for (i = 0; i < vec_size(self->exprs); ++i)
1175 ast_unref(self->exprs[i]);
1176 vec_free(self->exprs);
1177 for (i = 0; i < vec_size(self->locals); ++i)
1178 ast_delete(self->locals[i]);
1179 vec_free(self->locals);
1180 for (i = 0; i < vec_size(self->collect); ++i)
1181 ast_delete(self->collect[i]);
1182 vec_free(self->collect);
1183 ast_expression_delete((ast_expression*)self);
1187 void ast_block_set_type(ast_block *self, ast_expression *from)
1189 if (self->expression.next)
1190 ast_delete(self->expression.next);
1191 ast_type_adopt(self, from);
1194 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1196 ast_instantiate(ast_function, ctx, ast_function_delete);
1199 compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1201 } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1202 compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1204 (int)vtype->hasvalue,
1205 vtype->expression.vtype);
1209 self->vtype = vtype;
1210 self->name = name ? util_strdup(name) : NULL;
1211 self->blocks = NULL;
1213 self->labelcount = 0;
1216 self->ir_func = NULL;
1217 self->curblock = NULL;
1219 self->breakblocks = NULL;
1220 self->continueblocks = NULL;
1222 vtype->hasvalue = true;
1223 vtype->constval.vfunc = self;
1225 self->varargs = NULL;
1227 self->fixedparams = NULL;
1228 self->return_value = NULL;
1230 self->static_names = NULL;
1231 self->static_count = 0;
1240 void ast_function_delete(ast_function *self)
1244 mem_d((void*)self->name);
1246 /* ast_value_delete(self->vtype); */
1247 self->vtype->hasvalue = false;
1248 self->vtype->constval.vfunc = NULL;
1249 /* We use unref - if it was stored in a global table it is supposed
1250 * to be deleted from *there*
1252 ast_unref(self->vtype);
1254 for (i = 0; i < vec_size(self->static_names); ++i)
1255 mem_d(self->static_names[i]);
1256 vec_free(self->static_names);
1257 for (i = 0; i < vec_size(self->blocks); ++i)
1258 ast_delete(self->blocks[i]);
1259 vec_free(self->blocks);
1260 vec_free(self->breakblocks);
1261 vec_free(self->continueblocks);
1263 ast_delete(self->varargs);
1265 ast_delete(self->argc);
1266 if (self->fixedparams)
1267 ast_unref(self->fixedparams);
1268 if (self->return_value)
1269 ast_unref(self->return_value);
1273 const char* ast_function_label(ast_function *self, const char *prefix)
1279 if (!OPTS_OPTION_BOOL(OPTION_DUMP) &&
1280 !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1281 !OPTS_OPTION_BOOL(OPTION_DEBUG))
1286 id = (self->labelcount++);
1287 len = strlen(prefix);
1289 from = self->labelbuf + sizeof(self->labelbuf)-1;
1292 *from-- = (id%10) + '0';
1296 memcpy(from - len, prefix, len);
1300 /*********************************************************************/
1302 * by convention you must never pass NULL to the 'ir_value **out'
1303 * parameter. If you really don't care about the output, pass a dummy.
1304 * But I can't imagine a pituation where the output is truly unnecessary.
1307 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1309 if (out->vtype == TYPE_FIELD)
1310 out->fieldtype = self->next->vtype;
1311 if (out->vtype == TYPE_FUNCTION)
1312 out->outtype = self->next->vtype;
1315 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1317 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1321 if (self->expression.vtype == TYPE_NIL) {
1322 *out = func->ir_func->owner->nil;
1325 /* NOTE: This is the codegen for a variable used in an expression.
1326 * It is not the codegen to generate the value. For this purpose,
1327 * ast_local_codegen and ast_global_codegen are to be used before this
1328 * is executed. ast_function_codegen should take care of its locals,
1329 * and the ast-user should take care of ast_global_codegen to be used
1330 * on all the globals.
1333 char tname[1024]; /* typename is reserved in C++ */
1334 ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1335 compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1342 static bool ast_global_array_set(ast_value *self)
1344 size_t count = vec_size(self->initlist);
1347 if (count > self->expression.count) {
1348 compile_error(ast_ctx(self), "too many elements in initializer");
1349 count = self->expression.count;
1351 else if (count < self->expression.count) {
1353 compile_warning(ast_ctx(self), "not all elements are initialized");
1357 for (i = 0; i != count; ++i) {
1358 switch (self->expression.next->vtype) {
1360 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1364 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1368 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1372 /* we don't support them in any other place yet either */
1373 compile_error(ast_ctx(self), "TODO: nested arrays");
1376 /* this requiers a bit more work - similar to the fields I suppose */
1377 compile_error(ast_ctx(self), "global of type function not properly generated");
1380 if (!self->initlist[i].vfield) {
1381 compile_error(ast_ctx(self), "field constant without vfield set");
1384 if (!self->initlist[i].vfield->ir_v) {
1385 compile_error(ast_ctx(self), "field constant generated before its field");
1388 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1392 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1399 static bool check_array(ast_value *self, ast_value *array)
1401 if (array->expression.flags & AST_FLAG_ARRAY_INIT && !array->initlist) {
1402 compile_error(ast_ctx(self), "array without size: %s", self->name);
1405 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1406 if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1407 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1413 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1417 if (self->expression.vtype == TYPE_NIL) {
1418 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1422 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1424 ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1427 func->context = ast_ctx(self);
1428 func->value->context = ast_ctx(self);
1430 self->constval.vfunc->ir_func = func;
1431 self->ir_v = func->value;
1432 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1433 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1434 if (self->expression.flags & AST_FLAG_ERASEABLE)
1435 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1436 if (self->expression.flags & AST_FLAG_BLOCK_COVERAGE)
1437 func->flags |= IR_FLAG_BLOCK_COVERAGE;
1438 /* The function is filled later on ast_function_codegen... */
1442 if (isfield && self->expression.vtype == TYPE_FIELD) {
1443 ast_expression *fieldtype = self->expression.next;
1445 if (self->hasvalue) {
1446 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1450 if (fieldtype->vtype == TYPE_ARRAY) {
1455 ast_expression *elemtype;
1457 ast_value *array = (ast_value*)fieldtype;
1459 if (!ast_istype(fieldtype, ast_value)) {
1460 compile_error(ast_ctx(self), "internal error: ast_value required");
1464 if (!check_array(self, array))
1467 elemtype = array->expression.next;
1468 vtype = elemtype->vtype;
1470 v = ir_builder_create_field(ir, self->name, vtype);
1472 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1475 v->context = ast_ctx(self);
1476 v->unique_life = true;
1478 array->ir_v = self->ir_v = v;
1480 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1481 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1482 if (self->expression.flags & AST_FLAG_ERASEABLE)
1483 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1485 namelen = strlen(self->name);
1486 name = (char*)mem_a(namelen + 16);
1487 util_strncpy(name, self->name, namelen);
1489 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1490 array->ir_values[0] = v;
1491 for (ai = 1; ai < array->expression.count; ++ai) {
1492 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1493 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1494 if (!array->ir_values[ai]) {
1496 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1499 array->ir_values[ai]->context = ast_ctx(self);
1500 array->ir_values[ai]->unique_life = true;
1501 array->ir_values[ai]->locked = true;
1502 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1503 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1509 v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1512 v->context = ast_ctx(self);
1514 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1515 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1517 if (self->expression.flags & AST_FLAG_ERASEABLE)
1518 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1523 if (self->expression.vtype == TYPE_ARRAY) {
1528 ast_expression *elemtype = self->expression.next;
1529 int vtype = elemtype->vtype;
1531 if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1532 compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1536 /* same as with field arrays */
1537 if (!check_array(self, self))
1540 v = ir_builder_create_global(ir, self->name, vtype);
1542 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1545 v->context = ast_ctx(self);
1546 v->unique_life = true;
1549 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1550 v->flags |= IR_FLAG_INCLUDE_DEF;
1551 if (self->expression.flags & AST_FLAG_ERASEABLE)
1552 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1554 namelen = strlen(self->name);
1555 name = (char*)mem_a(namelen + 16);
1556 util_strncpy(name, self->name, namelen);
1558 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1559 self->ir_values[0] = v;
1560 for (ai = 1; ai < self->expression.count; ++ai) {
1561 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1562 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1563 if (!self->ir_values[ai]) {
1565 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1568 self->ir_values[ai]->context = ast_ctx(self);
1569 self->ir_values[ai]->unique_life = true;
1570 self->ir_values[ai]->locked = true;
1571 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1572 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1578 /* Arrays don't do this since there's no "array" value which spans across the
1581 v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1583 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1586 codegen_output_type(self, v);
1587 v->context = ast_ctx(self);
1590 /* link us to the ir_value */
1594 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1595 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1596 if (self->expression.flags & AST_FLAG_ERASEABLE)
1597 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1600 if (self->hasvalue) {
1601 switch (self->expression.vtype)
1604 if (!ir_value_set_float(v, self->constval.vfloat))
1608 if (!ir_value_set_vector(v, self->constval.vvec))
1612 if (!ir_value_set_string(v, self->constval.vstring))
1616 ast_global_array_set(self);
1619 compile_error(ast_ctx(self), "global of type function not properly generated");
1621 /* Cannot generate an IR value for a function,
1622 * need a pointer pointing to a function rather.
1625 if (!self->constval.vfield) {
1626 compile_error(ast_ctx(self), "field constant without vfield set");
1629 if (!self->constval.vfield->ir_v) {
1630 compile_error(ast_ctx(self), "field constant generated before its field");
1633 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1637 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1643 error: /* clean up */
1644 if(v) ir_value_delete(v);
1648 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1652 if (self->expression.vtype == TYPE_NIL) {
1653 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1657 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1659 /* Do we allow local functions? I think not...
1660 * this is NOT a function pointer atm.
1665 if (self->expression.vtype == TYPE_ARRAY) {
1670 ast_expression *elemtype = self->expression.next;
1671 int vtype = elemtype->vtype;
1673 func->flags |= IR_FLAG_HAS_ARRAYS;
1675 if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1676 compile_error(ast_ctx(self), "array-parameters are not supported");
1680 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1681 if (!check_array(self, self))
1684 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1685 if (!self->ir_values) {
1686 compile_error(ast_ctx(self), "failed to allocate array values");
1690 v = ir_function_create_local(func, self->name, vtype, param);
1692 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1695 v->context = ast_ctx(self);
1696 v->unique_life = true;
1699 namelen = strlen(self->name);
1700 name = (char*)mem_a(namelen + 16);
1701 util_strncpy(name, self->name, namelen);
1703 self->ir_values[0] = v;
1704 for (ai = 1; ai < self->expression.count; ++ai) {
1705 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1706 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1707 if (!self->ir_values[ai]) {
1708 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1711 self->ir_values[ai]->context = ast_ctx(self);
1712 self->ir_values[ai]->unique_life = true;
1713 self->ir_values[ai]->locked = true;
1719 v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1722 codegen_output_type(self, v);
1723 v->context = ast_ctx(self);
1726 /* A constant local... hmmm...
1727 * I suppose the IR will have to deal with this
1729 if (self->hasvalue) {
1730 switch (self->expression.vtype)
1733 if (!ir_value_set_float(v, self->constval.vfloat))
1737 if (!ir_value_set_vector(v, self->constval.vvec))
1741 if (!ir_value_set_string(v, self->constval.vstring))
1745 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1750 /* link us to the ir_value */
1754 if (!ast_generate_accessors(self, func->owner))
1758 error: /* clean up */
1763 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1766 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1767 if (!self->setter || !self->getter)
1769 for (i = 0; i < self->expression.count; ++i) {
1770 if (!self->ir_values) {
1771 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1774 if (!self->ir_values[i]) {
1775 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1778 if (self->ir_values[i]->life) {
1779 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1784 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1786 if (!ast_global_codegen (self->setter, ir, false) ||
1787 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1788 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1790 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1791 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1796 if (!ast_global_codegen (self->getter, ir, false) ||
1797 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1798 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1800 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1801 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1805 for (i = 0; i < self->expression.count; ++i) {
1806 vec_free(self->ir_values[i]->life);
1808 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1812 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1817 ast_expression_codegen *cgen;
1823 irf = self->ir_func;
1825 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1829 /* fill the parameter list */
1830 ec = &self->vtype->expression;
1831 for (i = 0; i < vec_size(ec->params); ++i)
1833 if (ec->params[i]->expression.vtype == TYPE_FIELD)
1834 vec_push(irf->params, ec->params[i]->expression.next->vtype);
1836 vec_push(irf->params, ec->params[i]->expression.vtype);
1837 if (!self->builtin) {
1838 if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1843 if (self->varargs) {
1844 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1846 irf->max_varargs = self->varargs->expression.count;
1849 if (self->builtin) {
1850 irf->builtin = self->builtin;
1854 /* have a local return value variable? */
1855 if (self->return_value) {
1856 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1860 if (!vec_size(self->blocks)) {
1861 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1865 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1866 if (!self->curblock) {
1867 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1875 if (!ast_local_codegen(self->argc, self->ir_func, true))
1877 cgen = self->argc->expression.codegen;
1878 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1880 cgen = self->fixedparams->expression.codegen;
1881 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1883 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1884 ast_function_label(self, "va_count"), INSTR_SUB_F,
1885 ir_builder_get_va_count(ir), fixed);
1888 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1895 for (i = 0; i < vec_size(self->blocks); ++i) {
1896 cgen = self->blocks[i]->expression.codegen;
1897 if (!(*cgen)((ast_expression*)self->blocks[i], self, false, &dummy))
1901 /* TODO: check return types */
1902 if (!self->curblock->final)
1904 if (!self->vtype->expression.next ||
1905 self->vtype->expression.next->vtype == TYPE_VOID)
1907 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1909 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1911 if (self->return_value) {
1912 cgen = self->return_value->expression.codegen;
1913 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1915 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1917 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1918 "control reaches end of non-void function (`%s`) via %s",
1919 self->name, self->curblock->label))
1923 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1929 static bool starts_a_label(ast_expression *ex)
1931 while (ex && ast_istype(ex, ast_block)) {
1932 ast_block *b = (ast_block*)ex;
1937 return ast_istype(ex, ast_label);
1940 /* Note, you will not see ast_block_codegen generate ir_blocks.
1941 * To the AST and the IR, blocks are 2 different things.
1942 * In the AST it represents a block of code, usually enclosed in
1943 * curly braces {...}.
1944 * While in the IR it represents a block in terms of control-flow.
1946 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1950 /* We don't use this
1951 * Note: an ast-representation using the comma-operator
1952 * of the form: (a, b, c) = x should not assign to c...
1955 compile_error(ast_ctx(self), "not an l-value (code-block)");
1959 if (self->expression.outr) {
1960 *out = self->expression.outr;
1964 /* output is NULL at first, we'll have each expression
1965 * assign to out output, thus, a comma-operator represention
1966 * using an ast_block will return the last generated value,
1967 * so: (b, c) + a executed both b and c, and returns c,
1968 * which is then added to a.
1972 /* generate locals */
1973 for (i = 0; i < vec_size(self->locals); ++i)
1975 if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1976 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1977 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1982 for (i = 0; i < vec_size(self->exprs); ++i)
1984 ast_expression_codegen *gen;
1985 if (func->curblock->final && !starts_a_label(self->exprs[i])) {
1986 if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
1990 gen = self->exprs[i]->codegen;
1991 if (!(*gen)(self->exprs[i], func, false, out))
1995 self->expression.outr = *out;
2000 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
2002 ast_expression_codegen *cgen;
2003 ir_value *left = NULL;
2004 ir_value *right = NULL;
2008 ast_array_index *ai = NULL;
2010 if (lvalue && self->expression.outl) {
2011 *out = self->expression.outl;
2015 if (!lvalue && self->expression.outr) {
2016 *out = self->expression.outr;
2020 if (ast_istype(self->dest, ast_array_index))
2023 ai = (ast_array_index*)self->dest;
2024 idx = (ast_value*)ai->index;
2026 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2031 /* we need to call the setter */
2032 ir_value *iridx, *funval;
2036 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2040 arr = (ast_value*)ai->array;
2041 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2042 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2046 cgen = idx->expression.codegen;
2047 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2050 cgen = arr->setter->expression.codegen;
2051 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2054 cgen = self->source->codegen;
2055 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2058 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2061 ir_call_param(call, iridx);
2062 ir_call_param(call, right);
2063 self->expression.outr = right;
2069 cgen = self->dest->codegen;
2071 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
2073 self->expression.outl = left;
2075 cgen = self->source->codegen;
2077 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2080 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2082 self->expression.outr = right;
2085 /* Theoretically, an assinment returns its left side as an
2086 * lvalue, if we don't need an lvalue though, we return
2087 * the right side as an rvalue, otherwise we have to
2088 * somehow know whether or not we need to dereference the pointer
2089 * on the left side - that is: OP_LOAD if it was an address.
2090 * Also: in original QC we cannot OP_LOADP *anyway*.
2092 *out = (lvalue ? left : right);
2097 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2099 ast_expression_codegen *cgen;
2100 ir_value *left, *right;
2102 /* A binary operation cannot yield an l-value */
2104 compile_error(ast_ctx(self), "not an l-value (binop)");
2108 if (self->expression.outr) {
2109 *out = self->expression.outr;
2113 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2114 (self->op == INSTR_AND || self->op == INSTR_OR))
2116 /* NOTE: The short-logic path will ignore right_first */
2118 /* short circuit evaluation */
2119 ir_block *other, *merge;
2120 ir_block *from_left, *from_right;
2124 /* prepare end-block */
2125 merge_id = vec_size(func->ir_func->blocks);
2126 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2128 /* generate the left expression */
2129 cgen = self->left->codegen;
2130 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2132 /* remember the block */
2133 from_left = func->curblock;
2135 /* create a new block for the right expression */
2136 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2137 if (self->op == INSTR_AND) {
2138 /* on AND: left==true -> other */
2139 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2142 /* on OR: left==false -> other */
2143 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2146 /* use the likely flag */
2147 vec_last(func->curblock->instr)->likely = true;
2149 /* enter the right-expression's block */
2150 func->curblock = other;
2152 cgen = self->right->codegen;
2153 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2155 /* remember block */
2156 from_right = func->curblock;
2158 /* jump to the merge block */
2159 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2162 vec_remove(func->ir_func->blocks, merge_id, 1);
2163 vec_push(func->ir_func->blocks, merge);
2165 func->curblock = merge;
2166 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2167 ast_function_label(func, "sce_value"),
2168 self->expression.vtype);
2169 ir_phi_add(phi, from_left, left);
2170 ir_phi_add(phi, from_right, right);
2171 *out = ir_phi_value(phi);
2175 if (!OPTS_FLAG(PERL_LOGIC)) {
2177 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2178 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2179 ast_function_label(func, "sce_bool_v"),
2183 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2184 ast_function_label(func, "sce_bool"),
2189 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2190 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2191 ast_function_label(func, "sce_bool_s"),
2195 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2196 ast_function_label(func, "sce_bool"),
2202 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2203 ast_function_label(func, "sce_bool"),
2204 INSTR_AND, *out, *out);
2210 self->expression.outr = *out;
2211 codegen_output_type(self, *out);
2215 if (self->right_first) {
2216 cgen = self->right->codegen;
2217 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2219 cgen = self->left->codegen;
2220 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2223 cgen = self->left->codegen;
2224 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2226 cgen = self->right->codegen;
2227 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2231 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2232 self->op, left, right);
2235 self->expression.outr = *out;
2236 codegen_output_type(self, *out);
2241 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2243 ast_expression_codegen *cgen;
2244 ir_value *leftl = NULL, *leftr, *right, *bin;
2248 ast_array_index *ai = NULL;
2249 ir_value *iridx = NULL;
2251 if (lvalue && self->expression.outl) {
2252 *out = self->expression.outl;
2256 if (!lvalue && self->expression.outr) {
2257 *out = self->expression.outr;
2261 if (ast_istype(self->dest, ast_array_index))
2264 ai = (ast_array_index*)self->dest;
2265 idx = (ast_value*)ai->index;
2267 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2271 /* for a binstore we need both an lvalue and an rvalue for the left side */
2272 /* rvalue of destination! */
2274 cgen = idx->expression.codegen;
2275 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2278 cgen = self->dest->codegen;
2279 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2282 /* source as rvalue only */
2283 cgen = self->source->codegen;
2284 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2287 /* now the binary */
2288 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2289 self->opbin, leftr, right);
2290 self->expression.outr = bin;
2294 /* we need to call the setter */
2299 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2303 arr = (ast_value*)ai->array;
2304 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2305 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2309 cgen = arr->setter->expression.codegen;
2310 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2313 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2316 ir_call_param(call, iridx);
2317 ir_call_param(call, bin);
2318 self->expression.outr = bin;
2320 /* now store them */
2321 cgen = self->dest->codegen;
2322 /* lvalue of destination */
2323 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2325 self->expression.outl = leftl;
2327 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2329 self->expression.outr = bin;
2332 /* Theoretically, an assinment returns its left side as an
2333 * lvalue, if we don't need an lvalue though, we return
2334 * the right side as an rvalue, otherwise we have to
2335 * somehow know whether or not we need to dereference the pointer
2336 * on the left side - that is: OP_LOAD if it was an address.
2337 * Also: in original QC we cannot OP_LOADP *anyway*.
2339 *out = (lvalue ? leftl : bin);
2344 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2346 ast_expression_codegen *cgen;
2349 /* An unary operation cannot yield an l-value */
2351 compile_error(ast_ctx(self), "not an l-value (binop)");
2355 if (self->expression.outr) {
2356 *out = self->expression.outr;
2360 cgen = self->operand->codegen;
2362 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2365 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2369 self->expression.outr = *out;
2374 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2376 ast_expression_codegen *cgen;
2381 /* In the context of a return operation, we don't actually return
2385 compile_error(ast_ctx(self), "return-expression is not an l-value");
2389 if (self->expression.outr) {
2390 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2393 self->expression.outr = (ir_value*)1;
2395 if (self->operand) {
2396 cgen = self->operand->codegen;
2398 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2401 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2404 if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2411 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2413 ast_expression_codegen *cgen;
2414 ir_value *ent, *field;
2416 /* This function needs to take the 'lvalue' flag into account!
2417 * As lvalue we provide a field-pointer, as rvalue we provide the
2421 if (lvalue && self->expression.outl) {
2422 *out = self->expression.outl;
2426 if (!lvalue && self->expression.outr) {
2427 *out = self->expression.outr;
2431 cgen = self->entity->codegen;
2432 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2435 cgen = self->field->codegen;
2436 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2441 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2444 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2445 ent, field, self->expression.vtype);
2446 /* Done AFTER error checking:
2447 codegen_output_type(self, *out);
2451 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2452 (lvalue ? "ADDRESS" : "FIELD"),
2453 type_name[self->expression.vtype]);
2457 codegen_output_type(self, *out);
2460 self->expression.outl = *out;
2462 self->expression.outr = *out;
2464 /* Hm that should be it... */
2468 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2470 ast_expression_codegen *cgen;
2473 /* in QC this is always an lvalue */
2474 if (lvalue && self->rvalue) {
2475 compile_error(ast_ctx(self), "not an l-value (member access)");
2478 if (self->expression.outl) {
2479 *out = self->expression.outl;
2483 cgen = self->owner->codegen;
2484 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2487 if (vec->vtype != TYPE_VECTOR &&
2488 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2493 *out = ir_value_vector_member(vec, self->field);
2494 self->expression.outl = *out;
2496 return (*out != NULL);
2499 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2504 if (!lvalue && self->expression.outr) {
2505 *out = self->expression.outr;
2508 if (lvalue && self->expression.outl) {
2509 *out = self->expression.outl;
2513 if (!ast_istype(self->array, ast_value)) {
2514 compile_error(ast_ctx(self), "array indexing this way is not supported");
2515 /* note this would actually be pointer indexing because the left side is
2516 * not an actual array but (hopefully) an indexable expression.
2517 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2518 * support this path will be filled.
2523 arr = (ast_value*)self->array;
2524 idx = (ast_value*)self->index;
2526 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2527 /* Time to use accessor functions */
2528 ast_expression_codegen *cgen;
2529 ir_value *iridx, *funval;
2533 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2538 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2542 cgen = self->index->codegen;
2543 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2546 cgen = arr->getter->expression.codegen;
2547 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2550 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2553 ir_call_param(call, iridx);
2555 *out = ir_call_value(call);
2556 self->expression.outr = *out;
2557 (*out)->vtype = self->expression.vtype;
2558 codegen_output_type(self, *out);
2562 if (idx->expression.vtype == TYPE_FLOAT) {
2563 unsigned int arridx = idx->constval.vfloat;
2564 if (arridx >= self->array->count)
2566 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2569 *out = arr->ir_values[arridx];
2571 else if (idx->expression.vtype == TYPE_INTEGER) {
2572 unsigned int arridx = idx->constval.vint;
2573 if (arridx >= self->array->count)
2575 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2578 *out = arr->ir_values[arridx];
2581 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2584 (*out)->vtype = self->expression.vtype;
2585 codegen_output_type(self, *out);
2589 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2593 compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2598 compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2602 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2604 ast_expression_codegen *cgen;
2612 ir_block *ontrue_endblock = NULL;
2613 ir_block *onfalse_endblock = NULL;
2614 ir_block *merge = NULL;
2617 /* We don't output any value, thus also don't care about r/lvalue */
2621 if (self->expression.outr) {
2622 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2625 self->expression.outr = (ir_value*)1;
2627 /* generate the condition */
2628 cgen = self->cond->codegen;
2629 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2631 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2632 cond = func->curblock;
2634 /* try constant folding away the condition */
2635 if ((fold = fold_cond_ifthen(condval, func, self)) != -1)
2638 if (self->on_true) {
2639 /* create on-true block */
2640 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2644 /* enter the block */
2645 func->curblock = ontrue;
2648 cgen = self->on_true->codegen;
2649 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2652 /* we now need to work from the current endpoint */
2653 ontrue_endblock = func->curblock;
2658 if (self->on_false) {
2659 /* create on-false block */
2660 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2664 /* enter the block */
2665 func->curblock = onfalse;
2668 cgen = self->on_false->codegen;
2669 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2672 /* we now need to work from the current endpoint */
2673 onfalse_endblock = func->curblock;
2677 /* Merge block were they all merge in to */
2678 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2680 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2683 /* add jumps ot the merge block */
2684 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2686 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2689 /* Now enter the merge block */
2690 func->curblock = merge;
2693 /* we create the if here, that way all blocks are ordered :)
2695 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2696 (ontrue ? ontrue : merge),
2697 (onfalse ? onfalse : merge)))
2705 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2707 ast_expression_codegen *cgen;
2710 ir_value *trueval, *falseval;
2713 ir_block *cond = func->curblock;
2714 ir_block *cond_out = NULL;
2715 ir_block *ontrue, *ontrue_out = NULL;
2716 ir_block *onfalse, *onfalse_out = NULL;
2720 /* Ternary can never create an lvalue... */
2724 /* In theory it shouldn't be possible to pass through a node twice, but
2725 * in case we add any kind of optimization pass for the AST itself, it
2726 * may still happen, thus we remember a created ir_value and simply return one
2727 * if it already exists.
2729 if (self->expression.outr) {
2730 *out = self->expression.outr;
2734 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2736 /* generate the condition */
2737 func->curblock = cond;
2738 cgen = self->cond->codegen;
2739 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2741 cond_out = func->curblock;
2743 /* try constant folding away the condition */
2744 if ((fold = fold_cond_ternary(condval, func, self)) != -1)
2747 /* create on-true block */
2748 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2753 /* enter the block */
2754 func->curblock = ontrue;
2757 cgen = self->on_true->codegen;
2758 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2761 ontrue_out = func->curblock;
2764 /* create on-false block */
2765 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2770 /* enter the block */
2771 func->curblock = onfalse;
2774 cgen = self->on_false->codegen;
2775 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2778 onfalse_out = func->curblock;
2781 /* create merge block */
2782 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2785 /* jump to merge block */
2786 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2788 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2791 /* create if instruction */
2792 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2795 /* Now enter the merge block */
2796 func->curblock = merge;
2798 /* Here, now, we need a PHI node
2799 * but first some sanity checking...
2801 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2802 /* error("ternary with different types on the two sides"); */
2803 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2808 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2810 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2813 ir_phi_add(phi, ontrue_out, trueval);
2814 ir_phi_add(phi, onfalse_out, falseval);
2816 self->expression.outr = ir_phi_value(phi);
2817 *out = self->expression.outr;
2819 codegen_output_type(self, *out);
2824 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2826 ast_expression_codegen *cgen;
2828 ir_value *dummy = NULL;
2829 ir_value *precond = NULL;
2830 ir_value *postcond = NULL;
2832 /* Since we insert some jumps "late" so we have blocks
2833 * ordered "nicely", we need to keep track of the actual end-blocks
2834 * of expressions to add the jumps to.
2836 ir_block *bbody = NULL, *end_bbody = NULL;
2837 ir_block *bprecond = NULL, *end_bprecond = NULL;
2838 ir_block *bpostcond = NULL, *end_bpostcond = NULL;
2839 ir_block *bincrement = NULL, *end_bincrement = NULL;
2840 ir_block *bout = NULL, *bin = NULL;
2842 /* let's at least move the outgoing block to the end */
2845 /* 'break' and 'continue' need to be able to find the right blocks */
2846 ir_block *bcontinue = NULL;
2847 ir_block *bbreak = NULL;
2849 ir_block *tmpblock = NULL;
2854 if (self->expression.outr) {
2855 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2858 self->expression.outr = (ir_value*)1;
2861 * Should we ever need some kind of block ordering, better make this function
2862 * move blocks around than write a block ordering algorithm later... after all
2863 * the ast and ir should work together, not against each other.
2866 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2867 * anyway if for example it contains a ternary.
2871 cgen = self->initexpr->codegen;
2872 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2876 /* Store the block from which we enter this chaos */
2877 bin = func->curblock;
2879 /* The pre-loop condition needs its own block since we
2880 * need to be able to jump to the start of that expression.
2884 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2888 /* the pre-loop-condition the least important place to 'continue' at */
2889 bcontinue = bprecond;
2892 func->curblock = bprecond;
2895 cgen = self->precond->codegen;
2896 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2899 end_bprecond = func->curblock;
2901 bprecond = end_bprecond = NULL;
2904 /* Now the next blocks won't be ordered nicely, but we need to
2905 * generate them this early for 'break' and 'continue'.
2907 if (self->increment) {
2908 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2911 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2913 bincrement = end_bincrement = NULL;
2916 if (self->postcond) {
2917 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2920 bcontinue = bpostcond; /* postcond comes before the increment */
2922 bpostcond = end_bpostcond = NULL;
2925 bout_id = vec_size(func->ir_func->blocks);
2926 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2931 /* The loop body... */
2932 /* if (self->body) */
2934 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2939 func->curblock = bbody;
2941 vec_push(func->breakblocks, bbreak);
2943 vec_push(func->continueblocks, bcontinue);
2945 vec_push(func->continueblocks, bbody);
2949 cgen = self->body->codegen;
2950 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2954 end_bbody = func->curblock;
2955 vec_pop(func->breakblocks);
2956 vec_pop(func->continueblocks);
2959 /* post-loop-condition */
2963 func->curblock = bpostcond;
2966 cgen = self->postcond->codegen;
2967 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2970 end_bpostcond = func->curblock;
2973 /* The incrementor */
2974 if (self->increment)
2977 func->curblock = bincrement;
2980 cgen = self->increment->codegen;
2981 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2984 end_bincrement = func->curblock;
2987 /* In any case now, we continue from the outgoing block */
2988 func->curblock = bout;
2990 /* Now all blocks are in place */
2991 /* From 'bin' we jump to whatever comes first */
2992 if (bprecond) tmpblock = bprecond;
2993 else tmpblock = bbody; /* can never be null */
2996 else if (bpostcond) tmpblock = bpostcond;
2997 else tmpblock = bout;
3000 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
3006 ir_block *ontrue, *onfalse;
3007 ontrue = bbody; /* can never be null */
3009 /* all of this is dead code
3010 else if (bincrement) ontrue = bincrement;
3011 else ontrue = bpostcond;
3015 if (self->pre_not) {
3020 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
3027 if (bincrement) tmpblock = bincrement;
3028 else if (bpostcond) tmpblock = bpostcond;
3029 else if (bprecond) tmpblock = bprecond;
3030 else tmpblock = bbody;
3031 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
3035 /* from increment */
3038 if (bpostcond) tmpblock = bpostcond;
3039 else if (bprecond) tmpblock = bprecond;
3040 else if (bbody) tmpblock = bbody;
3041 else tmpblock = bout;
3042 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
3049 ir_block *ontrue, *onfalse;
3050 if (bprecond) ontrue = bprecond;
3051 else ontrue = bbody; /* can never be null */
3053 /* all of this is dead code
3054 else if (bincrement) ontrue = bincrement;
3055 else ontrue = bpostcond;
3059 if (self->post_not) {
3064 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
3068 /* Move 'bout' to the end */
3069 vec_remove(func->ir_func->blocks, bout_id, 1);
3070 vec_push(func->ir_func->blocks, bout);
3075 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
3082 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3086 if (self->expression.outr) {
3087 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3090 self->expression.outr = (ir_value*)1;
3092 if (self->is_continue)
3093 target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
3095 target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
3098 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3102 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3107 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3109 ast_expression_codegen *cgen;
3111 ast_switch_case *def_case = NULL;
3112 ir_block *def_bfall = NULL;
3113 ir_block *def_bfall_to = NULL;
3114 bool set_def_bfall_to = false;
3116 ir_value *dummy = NULL;
3117 ir_value *irop = NULL;
3118 ir_block *bout = NULL;
3119 ir_block *bfall = NULL;
3127 compile_error(ast_ctx(self), "switch expression is not an l-value");
3131 if (self->expression.outr) {
3132 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3135 self->expression.outr = (ir_value*)1;
3140 cgen = self->operand->codegen;
3141 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3144 if (!vec_size(self->cases))
3147 cmpinstr = type_eq_instr[irop->vtype];
3148 if (cmpinstr >= VINSTR_END) {
3149 ast_type_to_string(self->operand, typestr, sizeof(typestr));
3150 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3154 bout_id = vec_size(func->ir_func->blocks);
3155 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3159 /* setup the break block */
3160 vec_push(func->breakblocks, bout);
3162 /* Now create all cases */
3163 for (c = 0; c < vec_size(self->cases); ++c) {
3164 ir_value *cond, *val;
3165 ir_block *bcase, *bnot;
3168 ast_switch_case *swcase = &self->cases[c];
3170 if (swcase->value) {
3171 /* A regular case */
3172 /* generate the condition operand */
3173 cgen = swcase->value->codegen;
3174 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3176 /* generate the condition */
3177 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3181 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3182 bnot_id = vec_size(func->ir_func->blocks);
3183 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3184 if (!bcase || !bnot)
3186 if (set_def_bfall_to) {
3187 set_def_bfall_to = false;
3188 def_bfall_to = bcase;
3190 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3193 /* Make the previous case-end fall through */
3194 if (bfall && !bfall->final) {
3195 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3199 /* enter the case */
3200 func->curblock = bcase;
3201 cgen = swcase->code->codegen;
3202 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3205 /* remember this block to fall through from */
3206 bfall = func->curblock;
3208 /* enter the else and move it down */
3209 func->curblock = bnot;
3210 vec_remove(func->ir_func->blocks, bnot_id, 1);
3211 vec_push(func->ir_func->blocks, bnot);
3213 /* The default case */
3214 /* Remember where to fall through from: */
3217 /* remember which case it was */
3219 /* And the next case will be remembered */
3220 set_def_bfall_to = true;
3224 /* Jump from the last bnot to bout */
3225 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3227 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3232 /* If there was a default case, put it down here */
3236 /* No need to create an extra block */
3237 bcase = func->curblock;
3239 /* Insert the fallthrough jump */
3240 if (def_bfall && !def_bfall->final) {
3241 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3245 /* Now generate the default code */
3246 cgen = def_case->code->codegen;
3247 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3250 /* see if we need to fall through */
3251 if (def_bfall_to && !func->curblock->final)
3253 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3258 /* Jump from the last bnot to bout */
3259 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3261 /* enter the outgoing block */
3262 func->curblock = bout;
3264 /* restore the break block */
3265 vec_pop(func->breakblocks);
3267 /* Move 'bout' to the end, it's nicer */
3268 vec_remove(func->ir_func->blocks, bout_id, 1);
3269 vec_push(func->ir_func->blocks, bout);
3274 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3279 if (self->undefined) {
3280 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3286 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3290 /* simply create a new block and jump to it */
3291 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3292 if (!self->irblock) {
3293 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3296 if (!func->curblock->final) {
3297 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3301 /* enter the new block */
3302 func->curblock = self->irblock;
3304 /* Generate all the leftover gotos */
3305 for (i = 0; i < vec_size(self->gotos); ++i) {
3306 if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3313 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3317 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3321 if (self->target->irblock) {
3322 if (self->irblock_from) {
3323 /* we already tried once, this is the callback */
3324 self->irblock_from->final = false;
3325 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3326 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3332 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3333 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3340 /* the target has not yet been created...
3341 * close this block in a sneaky way:
3343 func->curblock->final = true;
3344 self->irblock_from = func->curblock;
3345 ast_label_register_goto(self->target, self);
3351 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3353 ast_expression_codegen *cgen;
3355 ir_instr *callinstr;
3358 ir_value *funval = NULL;
3360 /* return values are never lvalues */
3362 compile_error(ast_ctx(self), "not an l-value (function call)");
3366 if (self->expression.outr) {
3367 *out = self->expression.outr;
3371 cgen = self->func->codegen;
3372 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3380 for (i = 0; i < vec_size(self->params); ++i)
3383 ast_expression *expr = self->params[i];
3385 cgen = expr->codegen;
3386 if (!(*cgen)(expr, func, false, ¶m))
3390 vec_push(params, param);
3393 /* varargs counter */
3394 if (self->va_count) {
3396 ir_builder *builder = func->curblock->owner->owner;
3397 cgen = self->va_count->codegen;
3398 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3400 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3401 ir_builder_get_va_count(builder), va_count))
3407 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3408 ast_function_label(func, "call"),
3409 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3413 for (i = 0; i < vec_size(params); ++i) {
3414 ir_call_param(callinstr, params[i]);
3417 *out = ir_call_value(callinstr);
3418 self->expression.outr = *out;
3420 codegen_output_type(self, *out);