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**);
78 static bool ast_state_codegen(ast_state*, ast_function*, bool lvalue, ir_value**);
80 /* It must not be possible to get here. */
81 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
84 con_err("ast node missing destroy()\n");
88 /* Initialize main ast node aprts */
89 static void ast_node_init(ast_node *self, lex_ctx_t ctx, int nodetype)
92 self->destroy = &_ast_node_destroy;
94 self->nodetype = nodetype;
95 self->side_effects = false;
98 /* weight and side effects */
99 static void _ast_propagate_effects(ast_node *self, ast_node *other)
101 if (ast_side_effects(other))
102 ast_side_effects(self) = true;
104 #define ast_propagate_effects(s,o) _ast_propagate_effects(((ast_node*)(s)), ((ast_node*)(o)))
106 /* General expression initialization */
107 static void ast_expression_init(ast_expression *self,
108 ast_expression_codegen *codegen)
110 self->codegen = codegen;
111 self->vtype = TYPE_VOID;
117 self->varparam = NULL;
119 if (OPTS_OPTION_BOOL(OPTION_COVERAGE))
120 self->flags |= AST_FLAG_BLOCK_COVERAGE;
123 static void ast_expression_delete(ast_expression *self)
127 ast_delete(self->next);
128 for (i = 0; i < vec_size(self->params); ++i) {
129 ast_delete(self->params[i]);
131 vec_free(self->params);
133 ast_delete(self->varparam);
136 static void ast_expression_delete_full(ast_expression *self)
138 ast_expression_delete(self);
142 ast_value* ast_value_copy(const ast_value *self)
145 const ast_expression *fromex;
146 ast_expression *selfex;
147 ast_value *cp = ast_value_new(self->expression.node.context, self->name, self->expression.vtype);
148 if (self->expression.next) {
149 cp->expression.next = ast_type_copy(self->expression.node.context, self->expression.next);
151 fromex = &self->expression;
152 selfex = &cp->expression;
153 selfex->count = fromex->count;
154 selfex->flags = fromex->flags;
155 for (i = 0; i < vec_size(fromex->params); ++i) {
156 ast_value *v = ast_value_copy(fromex->params[i]);
157 vec_push(selfex->params, v);
162 void ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
165 const ast_expression *fromex;
166 ast_expression *selfex;
167 self->vtype = other->vtype;
169 self->next = (ast_expression*)ast_type_copy(ast_ctx(self), other->next);
173 selfex->count = fromex->count;
174 selfex->flags = fromex->flags;
175 for (i = 0; i < vec_size(fromex->params); ++i) {
176 ast_value *v = ast_value_copy(fromex->params[i]);
177 vec_push(selfex->params, v);
181 static ast_expression* ast_shallow_type(lex_ctx_t ctx, int vtype)
183 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
184 ast_expression_init(self, NULL);
185 self->codegen = NULL;
191 ast_expression* ast_type_copy(lex_ctx_t ctx, const ast_expression *ex)
194 const ast_expression *fromex;
195 ast_expression *selfex;
201 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
202 ast_expression_init(self, NULL);
207 /* This may never be codegen()d */
208 selfex->codegen = NULL;
210 selfex->vtype = fromex->vtype;
212 selfex->next = ast_type_copy(ctx, fromex->next);
216 selfex->count = fromex->count;
217 selfex->flags = fromex->flags;
218 for (i = 0; i < vec_size(fromex->params); ++i) {
219 ast_value *v = ast_value_copy(fromex->params[i]);
220 vec_push(selfex->params, v);
227 bool ast_compare_type(ast_expression *a, ast_expression *b)
229 if (a->vtype == TYPE_NIL ||
230 b->vtype == TYPE_NIL)
232 if (a->vtype != b->vtype)
234 if (!a->next != !b->next)
236 if (vec_size(a->params) != vec_size(b->params))
238 if ((a->flags & AST_FLAG_TYPE_MASK) !=
239 (b->flags & AST_FLAG_TYPE_MASK) )
243 if (vec_size(a->params)) {
245 for (i = 0; i < vec_size(a->params); ++i) {
246 if (!ast_compare_type((ast_expression*)a->params[i],
247 (ast_expression*)b->params[i]))
252 return ast_compare_type(a->next, b->next);
256 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
263 if (pos + 6 >= bufsize)
265 util_strncpy(buf + pos, "(null)", 6);
269 if (pos + 1 >= bufsize)
274 util_strncpy(buf + pos, "(variant)", 9);
279 return ast_type_to_string_impl(e->next, buf, bufsize, pos);
282 if (pos + 3 >= bufsize)
286 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
287 if (pos + 1 >= bufsize)
293 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
294 if (pos + 2 >= bufsize)
296 if (!vec_size(e->params)) {
302 pos = ast_type_to_string_impl((ast_expression*)(e->params[0]), buf, bufsize, pos);
303 for (i = 1; i < vec_size(e->params); ++i) {
304 if (pos + 2 >= bufsize)
308 pos = ast_type_to_string_impl((ast_expression*)(e->params[i]), buf, bufsize, pos);
310 if (pos + 1 >= bufsize)
316 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
317 if (pos + 1 >= bufsize)
320 pos += util_snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->count);
321 if (pos + 1 >= bufsize)
327 typestr = type_name[e->vtype];
328 typelen = strlen(typestr);
329 if (pos + typelen >= bufsize)
331 util_strncpy(buf + pos, typestr, typelen);
332 return pos + typelen;
336 buf[bufsize-3] = '.';
337 buf[bufsize-2] = '.';
338 buf[bufsize-1] = '.';
342 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
344 size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
348 static bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out);
349 ast_value* ast_value_new(lex_ctx_t ctx, const char *name, int t)
351 ast_instantiate(ast_value, ctx, ast_value_delete);
352 ast_expression_init((ast_expression*)self,
353 (ast_expression_codegen*)&ast_value_codegen);
354 self->expression.node.keep = true; /* keep */
356 self->name = name ? util_strdup(name) : NULL;
357 self->expression.vtype = t;
358 self->expression.next = NULL;
359 self->isfield = false;
361 self->hasvalue = false;
363 self->inexact = false;
365 memset(&self->constval, 0, sizeof(self->constval));
366 self->initlist = NULL;
369 self->ir_values = NULL;
370 self->ir_value_count = 0;
376 self->argcounter = NULL;
377 self->intrinsic = false;
382 void ast_value_delete(ast_value* self)
385 mem_d((void*)self->name);
386 if (self->argcounter)
387 mem_d((void*)self->argcounter);
388 if (self->hasvalue) {
389 switch (self->expression.vtype)
392 mem_d((void*)self->constval.vstring);
395 /* unlink us from the function node */
396 self->constval.vfunc->vtype = NULL;
398 /* NOTE: delete function? currently collected in
399 * the parser structure
406 mem_d(self->ir_values);
411 if (self->initlist) {
412 if (self->expression.next->vtype == TYPE_STRING) {
413 /* strings are allocated, free them */
414 size_t i, len = vec_size(self->initlist);
415 /* in theory, len should be expression.count
416 * but let's not take any chances */
417 for (i = 0; i < len; ++i) {
418 if (self->initlist[i].vstring)
419 mem_d(self->initlist[i].vstring);
422 vec_free(self->initlist);
425 ast_expression_delete((ast_expression*)self);
429 void ast_value_params_add(ast_value *self, ast_value *p)
431 vec_push(self->expression.params, p);
434 bool ast_value_set_name(ast_value *self, const char *name)
437 mem_d((void*)self->name);
438 self->name = util_strdup(name);
442 ast_binary* ast_binary_new(lex_ctx_t ctx, int op,
443 ast_expression* left, ast_expression* right)
445 ast_instantiate(ast_binary, ctx, ast_binary_delete);
446 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
448 if (ast_istype(right, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
449 ast_unary *unary = ((ast_unary*)right);
450 ast_expression *normal = unary->operand;
452 /* make a-(-b) => a + b */
453 if (unary->op == VINSTR_NEG_F || unary->op == VINSTR_NEG_V) {
454 if (op == INSTR_SUB_F) {
457 ++opts_optimizationcount[OPTIM_PEEPHOLE];
458 } else if (op == INSTR_SUB_V) {
461 ++opts_optimizationcount[OPTIM_PEEPHOLE];
469 self->right_first = false;
471 ast_propagate_effects(self, left);
472 ast_propagate_effects(self, right);
474 if (op >= INSTR_EQ_F && op <= INSTR_GT)
475 self->expression.vtype = TYPE_FLOAT;
476 else if (op == INSTR_AND || op == INSTR_OR) {
477 if (OPTS_FLAG(PERL_LOGIC))
478 ast_type_adopt(self, right);
480 self->expression.vtype = TYPE_FLOAT;
482 else if (op == INSTR_BITAND || op == INSTR_BITOR)
483 self->expression.vtype = TYPE_FLOAT;
484 else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
485 self->expression.vtype = TYPE_VECTOR;
486 else if (op == INSTR_MUL_V)
487 self->expression.vtype = TYPE_FLOAT;
489 self->expression.vtype = left->vtype;
492 self->refs = AST_REF_ALL;
497 void ast_binary_delete(ast_binary *self)
499 if (self->refs & AST_REF_LEFT) ast_unref(self->left);
500 if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
502 ast_expression_delete((ast_expression*)self);
506 ast_binstore* ast_binstore_new(lex_ctx_t ctx, int storop, int op,
507 ast_expression* left, ast_expression* right)
509 ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
510 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
512 ast_side_effects(self) = true;
514 self->opstore = storop;
517 self->source = right;
519 self->keep_dest = false;
521 ast_type_adopt(self, left);
525 void ast_binstore_delete(ast_binstore *self)
527 if (!self->keep_dest)
528 ast_unref(self->dest);
529 ast_unref(self->source);
530 ast_expression_delete((ast_expression*)self);
534 ast_unary* ast_unary_new(lex_ctx_t ctx, int op,
535 ast_expression *expr)
537 ast_instantiate(ast_unary, ctx, ast_unary_delete);
538 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
541 self->operand = expr;
544 if (ast_istype(expr, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
545 ast_unary *prev = (ast_unary*)((ast_unary*)expr)->operand;
547 /* Handle for double negation */
548 if (((ast_unary*)expr)->op == op)
549 prev = (ast_unary*)((ast_unary*)expr)->operand;
551 if (ast_istype(prev, ast_unary)) {
552 ast_expression_delete((ast_expression*)self);
554 ++opts_optimizationcount[OPTIM_PEEPHOLE];
559 ast_propagate_effects(self, expr);
561 if ((op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) || op == VINSTR_NEG_F) {
562 self->expression.vtype = TYPE_FLOAT;
563 } else if (op == VINSTR_NEG_V) {
564 self->expression.vtype = TYPE_VECTOR;
566 compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
572 void ast_unary_delete(ast_unary *self)
574 if (self->operand) ast_unref(self->operand);
575 ast_expression_delete((ast_expression*)self);
579 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
581 ast_instantiate(ast_return, ctx, ast_return_delete);
582 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
584 self->operand = expr;
587 ast_propagate_effects(self, expr);
592 void ast_return_delete(ast_return *self)
595 ast_unref(self->operand);
596 ast_expression_delete((ast_expression*)self);
600 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
602 if (field->vtype != TYPE_FIELD) {
603 compile_error(ctx, "ast_entfield_new with expression not of type field");
606 return ast_entfield_new_force(ctx, entity, field, field->next);
609 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
611 ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
615 /* Error: field has no type... */
619 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
621 self->entity = entity;
623 ast_propagate_effects(self, entity);
624 ast_propagate_effects(self, field);
626 ast_type_adopt(self, outtype);
630 void ast_entfield_delete(ast_entfield *self)
632 ast_unref(self->entity);
633 ast_unref(self->field);
634 ast_expression_delete((ast_expression*)self);
638 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
640 ast_instantiate(ast_member, ctx, ast_member_delete);
646 if (owner->vtype != TYPE_VECTOR &&
647 owner->vtype != TYPE_FIELD) {
648 compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
653 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
654 self->expression.node.keep = true; /* keep */
656 if (owner->vtype == TYPE_VECTOR) {
657 self->expression.vtype = TYPE_FLOAT;
658 self->expression.next = NULL;
660 self->expression.vtype = TYPE_FIELD;
661 self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
664 self->rvalue = false;
666 ast_propagate_effects(self, owner);
670 self->name = util_strdup(name);
677 void ast_member_delete(ast_member *self)
679 /* The owner is always an ast_value, which has .keep=true,
680 * also: ast_members are usually deleted after the owner, thus
681 * this will cause invalid access
682 ast_unref(self->owner);
683 * once we allow (expression).x to access a vector-member, we need
684 * to change this: preferably by creating an alternate ast node for this
685 * purpose that is not garbage-collected.
687 ast_expression_delete((ast_expression*)self);
692 bool ast_member_set_name(ast_member *self, const char *name)
695 mem_d((void*)self->name);
696 self->name = util_strdup(name);
700 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
702 ast_expression *outtype;
703 ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
705 outtype = array->next;
708 /* Error: field has no type... */
712 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
716 ast_propagate_effects(self, array);
717 ast_propagate_effects(self, index);
719 ast_type_adopt(self, outtype);
720 if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
721 if (self->expression.vtype != TYPE_ARRAY) {
722 compile_error(ast_ctx(self), "array_index node on type");
723 ast_array_index_delete(self);
726 self->array = outtype;
727 self->expression.vtype = TYPE_FIELD;
733 void ast_array_index_delete(ast_array_index *self)
736 ast_unref(self->array);
738 ast_unref(self->index);
739 ast_expression_delete((ast_expression*)self);
743 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
745 ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete);
746 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
748 self->expression.vtype = TYPE_NOEXPR;
752 void ast_argpipe_delete(ast_argpipe *self)
755 ast_unref(self->index);
756 ast_expression_delete((ast_expression*)self);
760 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
762 ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
763 if (!ontrue && !onfalse) {
764 /* because it is invalid */
768 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
771 self->on_true = ontrue;
772 self->on_false = onfalse;
773 ast_propagate_effects(self, cond);
775 ast_propagate_effects(self, ontrue);
777 ast_propagate_effects(self, onfalse);
782 void ast_ifthen_delete(ast_ifthen *self)
784 ast_unref(self->cond);
786 ast_unref(self->on_true);
788 ast_unref(self->on_false);
789 ast_expression_delete((ast_expression*)self);
793 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
795 ast_expression *exprtype = ontrue;
796 ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
797 /* This time NEITHER must be NULL */
798 if (!ontrue || !onfalse) {
802 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
805 self->on_true = ontrue;
806 self->on_false = onfalse;
807 ast_propagate_effects(self, cond);
808 ast_propagate_effects(self, ontrue);
809 ast_propagate_effects(self, onfalse);
811 if (ontrue->vtype == TYPE_NIL)
813 ast_type_adopt(self, exprtype);
818 void ast_ternary_delete(ast_ternary *self)
820 /* the if()s are only there because computed-gotos can set them
823 if (self->cond) ast_unref(self->cond);
824 if (self->on_true) ast_unref(self->on_true);
825 if (self->on_false) ast_unref(self->on_false);
826 ast_expression_delete((ast_expression*)self);
830 ast_loop* ast_loop_new(lex_ctx_t ctx,
831 ast_expression *initexpr,
832 ast_expression *precond, bool pre_not,
833 ast_expression *postcond, bool post_not,
834 ast_expression *increment,
835 ast_expression *body)
837 ast_instantiate(ast_loop, ctx, ast_loop_delete);
838 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
840 self->initexpr = initexpr;
841 self->precond = precond;
842 self->postcond = postcond;
843 self->increment = increment;
846 self->pre_not = pre_not;
847 self->post_not = post_not;
850 ast_propagate_effects(self, initexpr);
852 ast_propagate_effects(self, precond);
854 ast_propagate_effects(self, postcond);
856 ast_propagate_effects(self, increment);
858 ast_propagate_effects(self, body);
863 void ast_loop_delete(ast_loop *self)
866 ast_unref(self->initexpr);
868 ast_unref(self->precond);
870 ast_unref(self->postcond);
872 ast_unref(self->increment);
874 ast_unref(self->body);
875 ast_expression_delete((ast_expression*)self);
879 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
881 ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
882 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
884 self->is_continue = iscont;
885 self->levels = levels;
890 void ast_breakcont_delete(ast_breakcont *self)
892 ast_expression_delete((ast_expression*)self);
896 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
898 ast_instantiate(ast_switch, ctx, ast_switch_delete);
899 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
904 ast_propagate_effects(self, op);
909 void ast_switch_delete(ast_switch *self)
912 ast_unref(self->operand);
914 for (i = 0; i < vec_size(self->cases); ++i) {
915 if (self->cases[i].value)
916 ast_unref(self->cases[i].value);
917 ast_unref(self->cases[i].code);
919 vec_free(self->cases);
921 ast_expression_delete((ast_expression*)self);
925 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
927 ast_instantiate(ast_label, ctx, ast_label_delete);
928 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
930 self->expression.vtype = TYPE_NOEXPR;
932 self->name = util_strdup(name);
933 self->irblock = NULL;
935 self->undefined = undefined;
940 void ast_label_delete(ast_label *self)
942 mem_d((void*)self->name);
943 vec_free(self->gotos);
944 ast_expression_delete((ast_expression*)self);
948 static void ast_label_register_goto(ast_label *self, ast_goto *g)
950 vec_push(self->gotos, g);
953 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
955 ast_instantiate(ast_goto, ctx, ast_goto_delete);
956 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
958 self->name = util_strdup(name);
960 self->irblock_from = NULL;
965 void ast_goto_delete(ast_goto *self)
967 mem_d((void*)self->name);
968 ast_expression_delete((ast_expression*)self);
972 void ast_goto_set_label(ast_goto *self, ast_label *label)
974 self->target = label;
977 ast_state* ast_state_new(lex_ctx_t ctx, ast_expression *frame, ast_expression *think)
979 ast_instantiate(ast_state, ctx, ast_state_delete);
980 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_state_codegen);
981 self->framenum = frame;
982 self->nextthink = think;
986 void ast_state_delete(ast_state *self)
989 ast_unref(self->framenum);
991 ast_unref(self->nextthink);
993 ast_expression_delete((ast_expression*)self);
997 ast_call* ast_call_new(lex_ctx_t ctx,
998 ast_expression *funcexpr)
1000 ast_instantiate(ast_call, ctx, ast_call_delete);
1001 if (!funcexpr->next) {
1002 compile_error(ctx, "not a function");
1006 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
1008 ast_side_effects(self) = true;
1010 self->params = NULL;
1011 self->func = funcexpr;
1012 self->va_count = NULL;
1014 ast_type_adopt(self, funcexpr->next);
1019 void ast_call_delete(ast_call *self)
1022 for (i = 0; i < vec_size(self->params); ++i)
1023 ast_unref(self->params[i]);
1024 vec_free(self->params);
1027 ast_unref(self->func);
1030 ast_unref(self->va_count);
1032 ast_expression_delete((ast_expression*)self);
1036 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
1042 if (!va_type || !ast_compare_type(va_type, exp_type))
1044 if (va_type && exp_type)
1046 ast_type_to_string(va_type, tgot, sizeof(tgot));
1047 ast_type_to_string(exp_type, texp, sizeof(texp));
1048 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1049 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1050 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1054 compile_error(ast_ctx(self),
1055 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1062 ast_type_to_string(exp_type, texp, sizeof(texp));
1063 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1064 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1065 "piped variadic argument may differ in type: expected type %s",
1069 compile_error(ast_ctx(self),
1070 "piped variadic argument may differ in type: expected type %s",
1079 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1085 const ast_expression *func = self->func;
1086 size_t count = vec_size(self->params);
1087 if (count > vec_size(func->params))
1088 count = vec_size(func->params);
1090 for (i = 0; i < count; ++i) {
1091 if (ast_istype(self->params[i], ast_argpipe)) {
1092 /* warn about type safety instead */
1094 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1097 if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->params[i]))
1100 else if (!ast_compare_type(self->params[i], (ast_expression*)(func->params[i])))
1102 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1103 ast_type_to_string((ast_expression*)func->params[i], texp, sizeof(texp));
1104 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1105 (unsigned int)(i+1), texp, tgot);
1106 /* we don't immediately return */
1110 count = vec_size(self->params);
1111 if (count > vec_size(func->params) && func->varparam) {
1112 for (; i < count; ++i) {
1113 if (ast_istype(self->params[i], ast_argpipe)) {
1114 /* warn about type safety instead */
1116 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1119 if (!ast_call_check_vararg(self, va_type, func->varparam))
1122 else if (!ast_compare_type(self->params[i], func->varparam))
1124 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1125 ast_type_to_string(func->varparam, texp, sizeof(texp));
1126 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1127 (unsigned int)(i+1), texp, tgot);
1128 /* we don't immediately return */
1136 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1137 ast_expression *dest, ast_expression *source)
1139 ast_instantiate(ast_store, ctx, ast_store_delete);
1140 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1142 ast_side_effects(self) = true;
1146 self->source = source;
1148 ast_type_adopt(self, dest);
1153 void ast_store_delete(ast_store *self)
1155 ast_unref(self->dest);
1156 ast_unref(self->source);
1157 ast_expression_delete((ast_expression*)self);
1161 ast_block* ast_block_new(lex_ctx_t ctx)
1163 ast_instantiate(ast_block, ctx, ast_block_delete);
1164 ast_expression_init((ast_expression*)self,
1165 (ast_expression_codegen*)&ast_block_codegen);
1167 self->locals = NULL;
1169 self->collect = NULL;
1174 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1176 ast_propagate_effects(self, e);
1177 vec_push(self->exprs, e);
1178 if (self->expression.next) {
1179 ast_delete(self->expression.next);
1180 self->expression.next = NULL;
1182 ast_type_adopt(self, e);
1186 void ast_block_collect(ast_block *self, ast_expression *expr)
1188 vec_push(self->collect, expr);
1189 expr->node.keep = true;
1192 void ast_block_delete(ast_block *self)
1195 for (i = 0; i < vec_size(self->exprs); ++i)
1196 ast_unref(self->exprs[i]);
1197 vec_free(self->exprs);
1198 for (i = 0; i < vec_size(self->locals); ++i)
1199 ast_delete(self->locals[i]);
1200 vec_free(self->locals);
1201 for (i = 0; i < vec_size(self->collect); ++i)
1202 ast_delete(self->collect[i]);
1203 vec_free(self->collect);
1204 ast_expression_delete((ast_expression*)self);
1208 void ast_block_set_type(ast_block *self, ast_expression *from)
1210 if (self->expression.next)
1211 ast_delete(self->expression.next);
1212 ast_type_adopt(self, from);
1215 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1217 ast_instantiate(ast_function, ctx, ast_function_delete);
1220 compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1222 } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1223 compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1225 (int)vtype->hasvalue,
1226 vtype->expression.vtype);
1230 self->vtype = vtype;
1231 self->name = name ? util_strdup(name) : NULL;
1232 self->blocks = NULL;
1234 self->labelcount = 0;
1237 self->ir_func = NULL;
1238 self->curblock = NULL;
1240 self->breakblocks = NULL;
1241 self->continueblocks = NULL;
1243 vtype->hasvalue = true;
1244 vtype->constval.vfunc = self;
1246 self->varargs = NULL;
1248 self->fixedparams = NULL;
1249 self->return_value = NULL;
1251 self->static_names = NULL;
1252 self->static_count = 0;
1261 void ast_function_delete(ast_function *self)
1265 mem_d((void*)self->name);
1267 /* ast_value_delete(self->vtype); */
1268 self->vtype->hasvalue = false;
1269 self->vtype->constval.vfunc = NULL;
1270 /* We use unref - if it was stored in a global table it is supposed
1271 * to be deleted from *there*
1273 ast_unref(self->vtype);
1275 for (i = 0; i < vec_size(self->static_names); ++i)
1276 mem_d(self->static_names[i]);
1277 vec_free(self->static_names);
1278 for (i = 0; i < vec_size(self->blocks); ++i)
1279 ast_delete(self->blocks[i]);
1280 vec_free(self->blocks);
1281 vec_free(self->breakblocks);
1282 vec_free(self->continueblocks);
1284 ast_delete(self->varargs);
1286 ast_delete(self->argc);
1287 if (self->fixedparams)
1288 ast_unref(self->fixedparams);
1289 if (self->return_value)
1290 ast_unref(self->return_value);
1294 const char* ast_function_label(ast_function *self, const char *prefix)
1300 if (!OPTS_OPTION_BOOL(OPTION_DUMP) &&
1301 !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1302 !OPTS_OPTION_BOOL(OPTION_DEBUG))
1307 id = (self->labelcount++);
1308 len = strlen(prefix);
1310 from = self->labelbuf + sizeof(self->labelbuf)-1;
1313 *from-- = (id%10) + '0';
1317 memcpy(from - len, prefix, len);
1321 /*********************************************************************/
1323 * by convention you must never pass NULL to the 'ir_value **out'
1324 * parameter. If you really don't care about the output, pass a dummy.
1325 * But I can't imagine a pituation where the output is truly unnecessary.
1328 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1330 if (out->vtype == TYPE_FIELD)
1331 out->fieldtype = self->next->vtype;
1332 if (out->vtype == TYPE_FUNCTION)
1333 out->outtype = self->next->vtype;
1336 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1338 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1342 if (self->expression.vtype == TYPE_NIL) {
1343 *out = func->ir_func->owner->nil;
1346 /* NOTE: This is the codegen for a variable used in an expression.
1347 * It is not the codegen to generate the value. For this purpose,
1348 * ast_local_codegen and ast_global_codegen are to be used before this
1349 * is executed. ast_function_codegen should take care of its locals,
1350 * and the ast-user should take care of ast_global_codegen to be used
1351 * on all the globals.
1354 char tname[1024]; /* typename is reserved in C++ */
1355 ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1356 compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1363 static bool ast_global_array_set(ast_value *self)
1365 size_t count = vec_size(self->initlist);
1368 if (count > self->expression.count) {
1369 compile_error(ast_ctx(self), "too many elements in initializer");
1370 count = self->expression.count;
1372 else if (count < self->expression.count) {
1374 compile_warning(ast_ctx(self), "not all elements are initialized");
1378 for (i = 0; i != count; ++i) {
1379 switch (self->expression.next->vtype) {
1381 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1385 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1389 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1393 /* we don't support them in any other place yet either */
1394 compile_error(ast_ctx(self), "TODO: nested arrays");
1397 /* this requiers a bit more work - similar to the fields I suppose */
1398 compile_error(ast_ctx(self), "global of type function not properly generated");
1401 if (!self->initlist[i].vfield) {
1402 compile_error(ast_ctx(self), "field constant without vfield set");
1405 if (!self->initlist[i].vfield->ir_v) {
1406 compile_error(ast_ctx(self), "field constant generated before its field");
1409 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1413 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1420 static bool check_array(ast_value *self, ast_value *array)
1422 if (array->expression.flags & AST_FLAG_ARRAY_INIT && !array->initlist) {
1423 compile_error(ast_ctx(self), "array without size: %s", self->name);
1426 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1427 if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1428 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1434 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1438 if (self->expression.vtype == TYPE_NIL) {
1439 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1443 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1445 ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1448 func->context = ast_ctx(self);
1449 func->value->context = ast_ctx(self);
1451 self->constval.vfunc->ir_func = func;
1452 self->ir_v = func->value;
1453 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1454 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1455 if (self->expression.flags & AST_FLAG_ERASEABLE)
1456 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1457 if (self->expression.flags & AST_FLAG_BLOCK_COVERAGE)
1458 func->flags |= IR_FLAG_BLOCK_COVERAGE;
1459 /* The function is filled later on ast_function_codegen... */
1463 if (isfield && self->expression.vtype == TYPE_FIELD) {
1464 ast_expression *fieldtype = self->expression.next;
1466 if (self->hasvalue) {
1467 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1471 if (fieldtype->vtype == TYPE_ARRAY) {
1476 ast_expression *elemtype;
1478 ast_value *array = (ast_value*)fieldtype;
1480 if (!ast_istype(fieldtype, ast_value)) {
1481 compile_error(ast_ctx(self), "internal error: ast_value required");
1485 if (!check_array(self, array))
1488 elemtype = array->expression.next;
1489 vtype = elemtype->vtype;
1491 v = ir_builder_create_field(ir, self->name, vtype);
1493 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1496 v->context = ast_ctx(self);
1497 v->unique_life = true;
1499 array->ir_v = self->ir_v = v;
1501 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1502 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1503 if (self->expression.flags & AST_FLAG_ERASEABLE)
1504 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1506 namelen = strlen(self->name);
1507 name = (char*)mem_a(namelen + 16);
1508 util_strncpy(name, self->name, namelen);
1510 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1511 array->ir_values[0] = v;
1512 for (ai = 1; ai < array->expression.count; ++ai) {
1513 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1514 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1515 if (!array->ir_values[ai]) {
1517 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1520 array->ir_values[ai]->context = ast_ctx(self);
1521 array->ir_values[ai]->unique_life = true;
1522 array->ir_values[ai]->locked = true;
1523 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1524 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1530 v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1533 v->context = ast_ctx(self);
1535 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1536 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1538 if (self->expression.flags & AST_FLAG_ERASEABLE)
1539 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1544 if (self->expression.vtype == TYPE_ARRAY) {
1549 ast_expression *elemtype = self->expression.next;
1550 int vtype = elemtype->vtype;
1552 if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1553 compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1557 /* same as with field arrays */
1558 if (!check_array(self, self))
1561 v = ir_builder_create_global(ir, self->name, vtype);
1563 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1566 v->context = ast_ctx(self);
1567 v->unique_life = true;
1570 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1571 v->flags |= IR_FLAG_INCLUDE_DEF;
1572 if (self->expression.flags & AST_FLAG_ERASEABLE)
1573 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1575 namelen = strlen(self->name);
1576 name = (char*)mem_a(namelen + 16);
1577 util_strncpy(name, self->name, namelen);
1579 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1580 self->ir_values[0] = v;
1581 for (ai = 1; ai < self->expression.count; ++ai) {
1582 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1583 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1584 if (!self->ir_values[ai]) {
1586 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1589 self->ir_values[ai]->context = ast_ctx(self);
1590 self->ir_values[ai]->unique_life = true;
1591 self->ir_values[ai]->locked = true;
1592 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1593 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1599 /* Arrays don't do this since there's no "array" value which spans across the
1602 v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1604 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1607 codegen_output_type(self, v);
1608 v->context = ast_ctx(self);
1611 /* link us to the ir_value */
1615 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1616 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1617 if (self->expression.flags & AST_FLAG_ERASEABLE)
1618 self->ir_v->flags |= IR_FLAG_ERASEABLE;
1621 if (self->hasvalue) {
1622 switch (self->expression.vtype)
1625 if (!ir_value_set_float(v, self->constval.vfloat))
1629 if (!ir_value_set_vector(v, self->constval.vvec))
1633 if (!ir_value_set_string(v, self->constval.vstring))
1637 ast_global_array_set(self);
1640 compile_error(ast_ctx(self), "global of type function not properly generated");
1642 /* Cannot generate an IR value for a function,
1643 * need a pointer pointing to a function rather.
1646 if (!self->constval.vfield) {
1647 compile_error(ast_ctx(self), "field constant without vfield set");
1650 if (!self->constval.vfield->ir_v) {
1651 compile_error(ast_ctx(self), "field constant generated before its field");
1654 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1658 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1664 error: /* clean up */
1665 if(v) ir_value_delete(v);
1669 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1673 if (self->expression.vtype == TYPE_NIL) {
1674 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1678 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1680 /* Do we allow local functions? I think not...
1681 * this is NOT a function pointer atm.
1686 if (self->expression.vtype == TYPE_ARRAY) {
1691 ast_expression *elemtype = self->expression.next;
1692 int vtype = elemtype->vtype;
1694 func->flags |= IR_FLAG_HAS_ARRAYS;
1696 if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1697 compile_error(ast_ctx(self), "array-parameters are not supported");
1701 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1702 if (!check_array(self, self))
1705 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1706 if (!self->ir_values) {
1707 compile_error(ast_ctx(self), "failed to allocate array values");
1711 v = ir_function_create_local(func, self->name, vtype, param);
1713 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1716 v->context = ast_ctx(self);
1717 v->unique_life = true;
1720 namelen = strlen(self->name);
1721 name = (char*)mem_a(namelen + 16);
1722 util_strncpy(name, self->name, namelen);
1724 self->ir_values[0] = v;
1725 for (ai = 1; ai < self->expression.count; ++ai) {
1726 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1727 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1728 if (!self->ir_values[ai]) {
1729 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1732 self->ir_values[ai]->context = ast_ctx(self);
1733 self->ir_values[ai]->unique_life = true;
1734 self->ir_values[ai]->locked = true;
1740 v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1743 codegen_output_type(self, v);
1744 v->context = ast_ctx(self);
1747 /* A constant local... hmmm...
1748 * I suppose the IR will have to deal with this
1750 if (self->hasvalue) {
1751 switch (self->expression.vtype)
1754 if (!ir_value_set_float(v, self->constval.vfloat))
1758 if (!ir_value_set_vector(v, self->constval.vvec))
1762 if (!ir_value_set_string(v, self->constval.vstring))
1766 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1771 /* link us to the ir_value */
1775 if (!ast_generate_accessors(self, func->owner))
1779 error: /* clean up */
1784 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1787 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1788 if (!self->setter || !self->getter)
1790 for (i = 0; i < self->expression.count; ++i) {
1791 if (!self->ir_values) {
1792 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1795 if (!self->ir_values[i]) {
1796 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1799 if (self->ir_values[i]->life) {
1800 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1805 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1807 if (!ast_global_codegen (self->setter, ir, false) ||
1808 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1809 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1811 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1812 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1817 if (!ast_global_codegen (self->getter, ir, false) ||
1818 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1819 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1821 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1822 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1826 for (i = 0; i < self->expression.count; ++i) {
1827 vec_free(self->ir_values[i]->life);
1829 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1833 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1838 ast_expression_codegen *cgen;
1844 irf = self->ir_func;
1846 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1850 /* fill the parameter list */
1851 ec = &self->vtype->expression;
1852 for (i = 0; i < vec_size(ec->params); ++i)
1854 if (ec->params[i]->expression.vtype == TYPE_FIELD)
1855 vec_push(irf->params, ec->params[i]->expression.next->vtype);
1857 vec_push(irf->params, ec->params[i]->expression.vtype);
1858 if (!self->builtin) {
1859 if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1864 if (self->varargs) {
1865 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1867 irf->max_varargs = self->varargs->expression.count;
1870 if (self->builtin) {
1871 irf->builtin = self->builtin;
1875 /* have a local return value variable? */
1876 if (self->return_value) {
1877 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1881 if (!vec_size(self->blocks)) {
1882 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1886 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1887 if (!self->curblock) {
1888 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1896 if (!ast_local_codegen(self->argc, self->ir_func, true))
1898 cgen = self->argc->expression.codegen;
1899 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1901 cgen = self->fixedparams->expression.codegen;
1902 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1904 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1905 ast_function_label(self, "va_count"), INSTR_SUB_F,
1906 ir_builder_get_va_count(ir), fixed);
1909 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1916 for (i = 0; i < vec_size(self->blocks); ++i) {
1917 cgen = self->blocks[i]->expression.codegen;
1918 if (!(*cgen)((ast_expression*)self->blocks[i], self, false, &dummy))
1922 /* TODO: check return types */
1923 if (!self->curblock->final)
1925 if (!self->vtype->expression.next ||
1926 self->vtype->expression.next->vtype == TYPE_VOID)
1928 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1930 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1932 if (self->return_value) {
1933 cgen = self->return_value->expression.codegen;
1934 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1936 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1938 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1939 "control reaches end of non-void function (`%s`) via %s",
1940 self->name, self->curblock->label))
1944 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1950 static bool starts_a_label(ast_expression *ex)
1952 while (ex && ast_istype(ex, ast_block)) {
1953 ast_block *b = (ast_block*)ex;
1958 return ast_istype(ex, ast_label);
1961 /* Note, you will not see ast_block_codegen generate ir_blocks.
1962 * To the AST and the IR, blocks are 2 different things.
1963 * In the AST it represents a block of code, usually enclosed in
1964 * curly braces {...}.
1965 * While in the IR it represents a block in terms of control-flow.
1967 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1971 /* We don't use this
1972 * Note: an ast-representation using the comma-operator
1973 * of the form: (a, b, c) = x should not assign to c...
1976 compile_error(ast_ctx(self), "not an l-value (code-block)");
1980 if (self->expression.outr) {
1981 *out = self->expression.outr;
1985 /* output is NULL at first, we'll have each expression
1986 * assign to out output, thus, a comma-operator represention
1987 * using an ast_block will return the last generated value,
1988 * so: (b, c) + a executed both b and c, and returns c,
1989 * which is then added to a.
1993 /* generate locals */
1994 for (i = 0; i < vec_size(self->locals); ++i)
1996 if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1997 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1998 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
2003 for (i = 0; i < vec_size(self->exprs); ++i)
2005 ast_expression_codegen *gen;
2006 if (func->curblock->final && !starts_a_label(self->exprs[i])) {
2007 if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
2011 gen = self->exprs[i]->codegen;
2012 if (!(*gen)(self->exprs[i], func, false, out))
2016 self->expression.outr = *out;
2021 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
2023 ast_expression_codegen *cgen;
2024 ir_value *left = NULL;
2025 ir_value *right = NULL;
2029 ast_array_index *ai = NULL;
2031 if (lvalue && self->expression.outl) {
2032 *out = self->expression.outl;
2036 if (!lvalue && self->expression.outr) {
2037 *out = self->expression.outr;
2041 if (ast_istype(self->dest, ast_array_index))
2044 ai = (ast_array_index*)self->dest;
2045 idx = (ast_value*)ai->index;
2047 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2052 /* we need to call the setter */
2053 ir_value *iridx, *funval;
2057 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2061 arr = (ast_value*)ai->array;
2062 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2063 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2067 cgen = idx->expression.codegen;
2068 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2071 cgen = arr->setter->expression.codegen;
2072 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2075 cgen = self->source->codegen;
2076 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2079 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2082 ir_call_param(call, iridx);
2083 ir_call_param(call, right);
2084 self->expression.outr = right;
2090 cgen = self->dest->codegen;
2092 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
2094 self->expression.outl = left;
2096 cgen = self->source->codegen;
2098 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2101 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2103 self->expression.outr = right;
2106 /* Theoretically, an assinment returns its left side as an
2107 * lvalue, if we don't need an lvalue though, we return
2108 * the right side as an rvalue, otherwise we have to
2109 * somehow know whether or not we need to dereference the pointer
2110 * on the left side - that is: OP_LOAD if it was an address.
2111 * Also: in original QC we cannot OP_LOADP *anyway*.
2113 *out = (lvalue ? left : right);
2118 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2120 ast_expression_codegen *cgen;
2121 ir_value *left, *right;
2123 /* A binary operation cannot yield an l-value */
2125 compile_error(ast_ctx(self), "not an l-value (binop)");
2129 if (self->expression.outr) {
2130 *out = self->expression.outr;
2134 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2135 (self->op == INSTR_AND || self->op == INSTR_OR))
2137 /* NOTE: The short-logic path will ignore right_first */
2139 /* short circuit evaluation */
2140 ir_block *other, *merge;
2141 ir_block *from_left, *from_right;
2145 /* prepare end-block */
2146 merge_id = vec_size(func->ir_func->blocks);
2147 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2149 /* generate the left expression */
2150 cgen = self->left->codegen;
2151 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2153 /* remember the block */
2154 from_left = func->curblock;
2156 /* create a new block for the right expression */
2157 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2158 if (self->op == INSTR_AND) {
2159 /* on AND: left==true -> other */
2160 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2163 /* on OR: left==false -> other */
2164 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2167 /* use the likely flag */
2168 vec_last(func->curblock->instr)->likely = true;
2170 /* enter the right-expression's block */
2171 func->curblock = other;
2173 cgen = self->right->codegen;
2174 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2176 /* remember block */
2177 from_right = func->curblock;
2179 /* jump to the merge block */
2180 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2183 vec_remove(func->ir_func->blocks, merge_id, 1);
2184 vec_push(func->ir_func->blocks, merge);
2186 func->curblock = merge;
2187 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2188 ast_function_label(func, "sce_value"),
2189 self->expression.vtype);
2190 ir_phi_add(phi, from_left, left);
2191 ir_phi_add(phi, from_right, right);
2192 *out = ir_phi_value(phi);
2196 if (!OPTS_FLAG(PERL_LOGIC)) {
2198 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2199 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2200 ast_function_label(func, "sce_bool_v"),
2204 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2205 ast_function_label(func, "sce_bool"),
2210 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2211 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2212 ast_function_label(func, "sce_bool_s"),
2216 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2217 ast_function_label(func, "sce_bool"),
2223 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2224 ast_function_label(func, "sce_bool"),
2225 INSTR_AND, *out, *out);
2231 self->expression.outr = *out;
2232 codegen_output_type(self, *out);
2236 if (self->right_first) {
2237 cgen = self->right->codegen;
2238 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2240 cgen = self->left->codegen;
2241 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2244 cgen = self->left->codegen;
2245 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2247 cgen = self->right->codegen;
2248 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2252 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2253 self->op, left, right);
2256 self->expression.outr = *out;
2257 codegen_output_type(self, *out);
2262 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2264 ast_expression_codegen *cgen;
2265 ir_value *leftl = NULL, *leftr, *right, *bin;
2269 ast_array_index *ai = NULL;
2270 ir_value *iridx = NULL;
2272 if (lvalue && self->expression.outl) {
2273 *out = self->expression.outl;
2277 if (!lvalue && self->expression.outr) {
2278 *out = self->expression.outr;
2282 if (ast_istype(self->dest, ast_array_index))
2285 ai = (ast_array_index*)self->dest;
2286 idx = (ast_value*)ai->index;
2288 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2292 /* for a binstore we need both an lvalue and an rvalue for the left side */
2293 /* rvalue of destination! */
2295 cgen = idx->expression.codegen;
2296 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2299 cgen = self->dest->codegen;
2300 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2303 /* source as rvalue only */
2304 cgen = self->source->codegen;
2305 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2308 /* now the binary */
2309 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2310 self->opbin, leftr, right);
2311 self->expression.outr = bin;
2315 /* we need to call the setter */
2320 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2324 arr = (ast_value*)ai->array;
2325 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2326 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2330 cgen = arr->setter->expression.codegen;
2331 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2334 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2337 ir_call_param(call, iridx);
2338 ir_call_param(call, bin);
2339 self->expression.outr = bin;
2341 /* now store them */
2342 cgen = self->dest->codegen;
2343 /* lvalue of destination */
2344 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2346 self->expression.outl = leftl;
2348 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2350 self->expression.outr = bin;
2353 /* Theoretically, an assinment returns its left side as an
2354 * lvalue, if we don't need an lvalue though, we return
2355 * the right side as an rvalue, otherwise we have to
2356 * somehow know whether or not we need to dereference the pointer
2357 * on the left side - that is: OP_LOAD if it was an address.
2358 * Also: in original QC we cannot OP_LOADP *anyway*.
2360 *out = (lvalue ? leftl : bin);
2365 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2367 ast_expression_codegen *cgen;
2370 /* An unary operation cannot yield an l-value */
2372 compile_error(ast_ctx(self), "not an l-value (binop)");
2376 if (self->expression.outr) {
2377 *out = self->expression.outr;
2381 cgen = self->operand->codegen;
2383 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2386 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2390 self->expression.outr = *out;
2395 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2397 ast_expression_codegen *cgen;
2402 /* In the context of a return operation, we don't actually return
2406 compile_error(ast_ctx(self), "return-expression is not an l-value");
2410 if (self->expression.outr) {
2411 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2414 self->expression.outr = (ir_value*)1;
2416 if (self->operand) {
2417 cgen = self->operand->codegen;
2419 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2422 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2425 if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2432 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2434 ast_expression_codegen *cgen;
2435 ir_value *ent, *field;
2437 /* This function needs to take the 'lvalue' flag into account!
2438 * As lvalue we provide a field-pointer, as rvalue we provide the
2442 if (lvalue && self->expression.outl) {
2443 *out = self->expression.outl;
2447 if (!lvalue && self->expression.outr) {
2448 *out = self->expression.outr;
2452 cgen = self->entity->codegen;
2453 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2456 cgen = self->field->codegen;
2457 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2462 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2465 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2466 ent, field, self->expression.vtype);
2467 /* Done AFTER error checking:
2468 codegen_output_type(self, *out);
2472 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2473 (lvalue ? "ADDRESS" : "FIELD"),
2474 type_name[self->expression.vtype]);
2478 codegen_output_type(self, *out);
2481 self->expression.outl = *out;
2483 self->expression.outr = *out;
2485 /* Hm that should be it... */
2489 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2491 ast_expression_codegen *cgen;
2494 /* in QC this is always an lvalue */
2495 if (lvalue && self->rvalue) {
2496 compile_error(ast_ctx(self), "not an l-value (member access)");
2499 if (self->expression.outl) {
2500 *out = self->expression.outl;
2504 cgen = self->owner->codegen;
2505 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2508 if (vec->vtype != TYPE_VECTOR &&
2509 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2514 *out = ir_value_vector_member(vec, self->field);
2515 self->expression.outl = *out;
2517 return (*out != NULL);
2520 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2525 if (!lvalue && self->expression.outr) {
2526 *out = self->expression.outr;
2529 if (lvalue && self->expression.outl) {
2530 *out = self->expression.outl;
2534 if (!ast_istype(self->array, ast_value)) {
2535 compile_error(ast_ctx(self), "array indexing this way is not supported");
2536 /* note this would actually be pointer indexing because the left side is
2537 * not an actual array but (hopefully) an indexable expression.
2538 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2539 * support this path will be filled.
2544 arr = (ast_value*)self->array;
2545 idx = (ast_value*)self->index;
2547 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2548 /* Time to use accessor functions */
2549 ast_expression_codegen *cgen;
2550 ir_value *iridx, *funval;
2554 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2559 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2563 cgen = self->index->codegen;
2564 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2567 cgen = arr->getter->expression.codegen;
2568 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2571 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2574 ir_call_param(call, iridx);
2576 *out = ir_call_value(call);
2577 self->expression.outr = *out;
2578 (*out)->vtype = self->expression.vtype;
2579 codegen_output_type(self, *out);
2583 if (idx->expression.vtype == TYPE_FLOAT) {
2584 unsigned int arridx = idx->constval.vfloat;
2585 if (arridx >= self->array->count)
2587 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2590 *out = arr->ir_values[arridx];
2592 else if (idx->expression.vtype == TYPE_INTEGER) {
2593 unsigned int arridx = idx->constval.vint;
2594 if (arridx >= self->array->count)
2596 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2599 *out = arr->ir_values[arridx];
2602 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2605 (*out)->vtype = self->expression.vtype;
2606 codegen_output_type(self, *out);
2610 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2614 compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2619 compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2623 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2625 ast_expression_codegen *cgen;
2633 ir_block *ontrue_endblock = NULL;
2634 ir_block *onfalse_endblock = NULL;
2635 ir_block *merge = NULL;
2638 /* We don't output any value, thus also don't care about r/lvalue */
2642 if (self->expression.outr) {
2643 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2646 self->expression.outr = (ir_value*)1;
2648 /* generate the condition */
2649 cgen = self->cond->codegen;
2650 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2652 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2653 cond = func->curblock;
2655 /* try constant folding away the condition */
2656 if ((fold = fold_cond_ifthen(condval, func, self)) != -1)
2659 if (self->on_true) {
2660 /* create on-true block */
2661 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2665 /* enter the block */
2666 func->curblock = ontrue;
2669 cgen = self->on_true->codegen;
2670 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2673 /* we now need to work from the current endpoint */
2674 ontrue_endblock = func->curblock;
2679 if (self->on_false) {
2680 /* create on-false block */
2681 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2685 /* enter the block */
2686 func->curblock = onfalse;
2689 cgen = self->on_false->codegen;
2690 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2693 /* we now need to work from the current endpoint */
2694 onfalse_endblock = func->curblock;
2698 /* Merge block were they all merge in to */
2699 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2701 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2704 /* add jumps ot the merge block */
2705 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2707 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2710 /* Now enter the merge block */
2711 func->curblock = merge;
2714 /* we create the if here, that way all blocks are ordered :)
2716 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2717 (ontrue ? ontrue : merge),
2718 (onfalse ? onfalse : merge)))
2726 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2728 ast_expression_codegen *cgen;
2731 ir_value *trueval, *falseval;
2734 ir_block *cond = func->curblock;
2735 ir_block *cond_out = NULL;
2736 ir_block *ontrue, *ontrue_out = NULL;
2737 ir_block *onfalse, *onfalse_out = NULL;
2741 /* Ternary can never create an lvalue... */
2745 /* In theory it shouldn't be possible to pass through a node twice, but
2746 * in case we add any kind of optimization pass for the AST itself, it
2747 * may still happen, thus we remember a created ir_value and simply return one
2748 * if it already exists.
2750 if (self->expression.outr) {
2751 *out = self->expression.outr;
2755 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2757 /* generate the condition */
2758 func->curblock = cond;
2759 cgen = self->cond->codegen;
2760 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2762 cond_out = func->curblock;
2764 /* try constant folding away the condition */
2765 if ((fold = fold_cond_ternary(condval, func, self)) != -1)
2768 /* create on-true block */
2769 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2774 /* enter the block */
2775 func->curblock = ontrue;
2778 cgen = self->on_true->codegen;
2779 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2782 ontrue_out = func->curblock;
2785 /* create on-false block */
2786 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2791 /* enter the block */
2792 func->curblock = onfalse;
2795 cgen = self->on_false->codegen;
2796 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2799 onfalse_out = func->curblock;
2802 /* create merge block */
2803 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2806 /* jump to merge block */
2807 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2809 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2812 /* create if instruction */
2813 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2816 /* Now enter the merge block */
2817 func->curblock = merge;
2819 /* Here, now, we need a PHI node
2820 * but first some sanity checking...
2822 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2823 /* error("ternary with different types on the two sides"); */
2824 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2829 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2831 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2834 ir_phi_add(phi, ontrue_out, trueval);
2835 ir_phi_add(phi, onfalse_out, falseval);
2837 self->expression.outr = ir_phi_value(phi);
2838 *out = self->expression.outr;
2840 codegen_output_type(self, *out);
2845 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2847 ast_expression_codegen *cgen;
2849 ir_value *dummy = NULL;
2850 ir_value *precond = NULL;
2851 ir_value *postcond = NULL;
2853 /* Since we insert some jumps "late" so we have blocks
2854 * ordered "nicely", we need to keep track of the actual end-blocks
2855 * of expressions to add the jumps to.
2857 ir_block *bbody = NULL, *end_bbody = NULL;
2858 ir_block *bprecond = NULL, *end_bprecond = NULL;
2859 ir_block *bpostcond = NULL, *end_bpostcond = NULL;
2860 ir_block *bincrement = NULL, *end_bincrement = NULL;
2861 ir_block *bout = NULL, *bin = NULL;
2863 /* let's at least move the outgoing block to the end */
2866 /* 'break' and 'continue' need to be able to find the right blocks */
2867 ir_block *bcontinue = NULL;
2868 ir_block *bbreak = NULL;
2870 ir_block *tmpblock = NULL;
2875 if (self->expression.outr) {
2876 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2879 self->expression.outr = (ir_value*)1;
2882 * Should we ever need some kind of block ordering, better make this function
2883 * move blocks around than write a block ordering algorithm later... after all
2884 * the ast and ir should work together, not against each other.
2887 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2888 * anyway if for example it contains a ternary.
2892 cgen = self->initexpr->codegen;
2893 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2897 /* Store the block from which we enter this chaos */
2898 bin = func->curblock;
2900 /* The pre-loop condition needs its own block since we
2901 * need to be able to jump to the start of that expression.
2905 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2909 /* the pre-loop-condition the least important place to 'continue' at */
2910 bcontinue = bprecond;
2913 func->curblock = bprecond;
2916 cgen = self->precond->codegen;
2917 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2920 end_bprecond = func->curblock;
2922 bprecond = end_bprecond = NULL;
2925 /* Now the next blocks won't be ordered nicely, but we need to
2926 * generate them this early for 'break' and 'continue'.
2928 if (self->increment) {
2929 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2932 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2934 bincrement = end_bincrement = NULL;
2937 if (self->postcond) {
2938 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2941 bcontinue = bpostcond; /* postcond comes before the increment */
2943 bpostcond = end_bpostcond = NULL;
2946 bout_id = vec_size(func->ir_func->blocks);
2947 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2952 /* The loop body... */
2953 /* if (self->body) */
2955 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2960 func->curblock = bbody;
2962 vec_push(func->breakblocks, bbreak);
2964 vec_push(func->continueblocks, bcontinue);
2966 vec_push(func->continueblocks, bbody);
2970 cgen = self->body->codegen;
2971 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2975 end_bbody = func->curblock;
2976 vec_pop(func->breakblocks);
2977 vec_pop(func->continueblocks);
2980 /* post-loop-condition */
2984 func->curblock = bpostcond;
2987 cgen = self->postcond->codegen;
2988 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2991 end_bpostcond = func->curblock;
2994 /* The incrementor */
2995 if (self->increment)
2998 func->curblock = bincrement;
3001 cgen = self->increment->codegen;
3002 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
3005 end_bincrement = func->curblock;
3008 /* In any case now, we continue from the outgoing block */
3009 func->curblock = bout;
3011 /* Now all blocks are in place */
3012 /* From 'bin' we jump to whatever comes first */
3013 if (bprecond) tmpblock = bprecond;
3014 else tmpblock = bbody; /* can never be null */
3017 else if (bpostcond) tmpblock = bpostcond;
3018 else tmpblock = bout;
3021 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
3027 ir_block *ontrue, *onfalse;
3028 ontrue = bbody; /* can never be null */
3030 /* all of this is dead code
3031 else if (bincrement) ontrue = bincrement;
3032 else ontrue = bpostcond;
3036 if (self->pre_not) {
3041 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
3048 if (bincrement) tmpblock = bincrement;
3049 else if (bpostcond) tmpblock = bpostcond;
3050 else if (bprecond) tmpblock = bprecond;
3051 else tmpblock = bbody;
3052 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
3056 /* from increment */
3059 if (bpostcond) tmpblock = bpostcond;
3060 else if (bprecond) tmpblock = bprecond;
3061 else if (bbody) tmpblock = bbody;
3062 else tmpblock = bout;
3063 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
3070 ir_block *ontrue, *onfalse;
3071 if (bprecond) ontrue = bprecond;
3072 else ontrue = bbody; /* can never be null */
3074 /* all of this is dead code
3075 else if (bincrement) ontrue = bincrement;
3076 else ontrue = bpostcond;
3080 if (self->post_not) {
3085 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
3089 /* Move 'bout' to the end */
3090 vec_remove(func->ir_func->blocks, bout_id, 1);
3091 vec_push(func->ir_func->blocks, bout);
3096 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
3103 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3107 if (self->expression.outr) {
3108 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3111 self->expression.outr = (ir_value*)1;
3113 if (self->is_continue)
3114 target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
3116 target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
3119 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3123 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3128 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3130 ast_expression_codegen *cgen;
3132 ast_switch_case *def_case = NULL;
3133 ir_block *def_bfall = NULL;
3134 ir_block *def_bfall_to = NULL;
3135 bool set_def_bfall_to = false;
3137 ir_value *dummy = NULL;
3138 ir_value *irop = NULL;
3139 ir_block *bout = NULL;
3140 ir_block *bfall = NULL;
3148 compile_error(ast_ctx(self), "switch expression is not an l-value");
3152 if (self->expression.outr) {
3153 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3156 self->expression.outr = (ir_value*)1;
3161 cgen = self->operand->codegen;
3162 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3165 if (!vec_size(self->cases))
3168 cmpinstr = type_eq_instr[irop->vtype];
3169 if (cmpinstr >= VINSTR_END) {
3170 ast_type_to_string(self->operand, typestr, sizeof(typestr));
3171 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3175 bout_id = vec_size(func->ir_func->blocks);
3176 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3180 /* setup the break block */
3181 vec_push(func->breakblocks, bout);
3183 /* Now create all cases */
3184 for (c = 0; c < vec_size(self->cases); ++c) {
3185 ir_value *cond, *val;
3186 ir_block *bcase, *bnot;
3189 ast_switch_case *swcase = &self->cases[c];
3191 if (swcase->value) {
3192 /* A regular case */
3193 /* generate the condition operand */
3194 cgen = swcase->value->codegen;
3195 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3197 /* generate the condition */
3198 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3202 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3203 bnot_id = vec_size(func->ir_func->blocks);
3204 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3205 if (!bcase || !bnot)
3207 if (set_def_bfall_to) {
3208 set_def_bfall_to = false;
3209 def_bfall_to = bcase;
3211 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3214 /* Make the previous case-end fall through */
3215 if (bfall && !bfall->final) {
3216 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3220 /* enter the case */
3221 func->curblock = bcase;
3222 cgen = swcase->code->codegen;
3223 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3226 /* remember this block to fall through from */
3227 bfall = func->curblock;
3229 /* enter the else and move it down */
3230 func->curblock = bnot;
3231 vec_remove(func->ir_func->blocks, bnot_id, 1);
3232 vec_push(func->ir_func->blocks, bnot);
3234 /* The default case */
3235 /* Remember where to fall through from: */
3238 /* remember which case it was */
3240 /* And the next case will be remembered */
3241 set_def_bfall_to = true;
3245 /* Jump from the last bnot to bout */
3246 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3248 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3253 /* If there was a default case, put it down here */
3257 /* No need to create an extra block */
3258 bcase = func->curblock;
3260 /* Insert the fallthrough jump */
3261 if (def_bfall && !def_bfall->final) {
3262 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3266 /* Now generate the default code */
3267 cgen = def_case->code->codegen;
3268 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3271 /* see if we need to fall through */
3272 if (def_bfall_to && !func->curblock->final)
3274 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3279 /* Jump from the last bnot to bout */
3280 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3282 /* enter the outgoing block */
3283 func->curblock = bout;
3285 /* restore the break block */
3286 vec_pop(func->breakblocks);
3288 /* Move 'bout' to the end, it's nicer */
3289 vec_remove(func->ir_func->blocks, bout_id, 1);
3290 vec_push(func->ir_func->blocks, bout);
3295 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3300 if (self->undefined) {
3301 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3307 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3311 /* simply create a new block and jump to it */
3312 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3313 if (!self->irblock) {
3314 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3317 if (!func->curblock->final) {
3318 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3322 /* enter the new block */
3323 func->curblock = self->irblock;
3325 /* Generate all the leftover gotos */
3326 for (i = 0; i < vec_size(self->gotos); ++i) {
3327 if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3334 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3338 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3342 if (self->target->irblock) {
3343 if (self->irblock_from) {
3344 /* we already tried once, this is the callback */
3345 self->irblock_from->final = false;
3346 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3347 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3353 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3354 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3361 /* the target has not yet been created...
3362 * close this block in a sneaky way:
3364 func->curblock->final = true;
3365 self->irblock_from = func->curblock;
3366 ast_label_register_goto(self->target, self);
3373 bool ast_state_codegen(ast_state *self, ast_function *func, bool lvalue, ir_value **out)
3375 ast_expression_codegen *cgen;
3377 ir_value *frameval, *thinkval;
3380 compile_error(ast_ctx(self), "not an l-value (state operation)");
3383 if (self->expression.outr) {
3384 compile_error(ast_ctx(self), "internal error: ast_state cannot be reused!");
3389 cgen = self->framenum->codegen;
3390 if (!(*cgen)((ast_expression*)(self->framenum), func, false, &frameval))
3395 cgen = self->nextthink->codegen;
3396 if (!(*cgen)((ast_expression*)(self->nextthink), func, false, &thinkval))
3401 if (!ir_block_create_state_op(func->curblock, ast_ctx(self), frameval, thinkval)) {
3402 compile_error(ast_ctx(self), "failed to create STATE instruction");
3406 self->expression.outr = (ir_value*)1;
3410 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3412 ast_expression_codegen *cgen;
3414 ir_instr *callinstr;
3417 ir_value *funval = NULL;
3419 /* return values are never lvalues */
3421 compile_error(ast_ctx(self), "not an l-value (function call)");
3425 if (self->expression.outr) {
3426 *out = self->expression.outr;
3430 cgen = self->func->codegen;
3431 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3439 for (i = 0; i < vec_size(self->params); ++i)
3442 ast_expression *expr = self->params[i];
3444 cgen = expr->codegen;
3445 if (!(*cgen)(expr, func, false, ¶m))
3449 vec_push(params, param);
3452 /* varargs counter */
3453 if (self->va_count) {
3455 ir_builder *builder = func->curblock->owner->owner;
3456 cgen = self->va_count->codegen;
3457 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3459 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3460 ir_builder_get_va_count(builder), va_count))
3466 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3467 ast_function_label(func, "call"),
3468 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3472 for (i = 0; i < vec_size(params); ++i) {
3473 ir_call_param(callinstr, params[i]);
3476 *out = ir_call_value(callinstr);
3477 self->expression.outr = *out;
3479 codegen_output_type(self, *out);