11 #define ast_instantiate(T, ctx, destroyfn) \
12 T* self = (T*)mem_a(sizeof(T)); \
17 ast_node_init((ast_node*)self, ctx, TYPE_##T); \
18 ( (ast_node*)self )->destroy = (ast_node_delete*)destroyfn
21 * forward declarations, these need not be in ast.h for obvious
24 static bool ast_member_codegen(ast_member*, ast_function*, bool lvalue, ir_value**);
25 static void ast_array_index_delete(ast_array_index*);
26 static bool ast_array_index_codegen(ast_array_index*, ast_function*, bool lvalue, ir_value**);
27 static void ast_argpipe_delete(ast_argpipe*);
28 static bool ast_argpipe_codegen(ast_argpipe*, ast_function*, bool lvalue, ir_value**);
29 static void ast_store_delete(ast_store*);
30 static bool ast_store_codegen(ast_store*, ast_function*, bool lvalue, ir_value**);
31 static void ast_ifthen_delete(ast_ifthen*);
32 static bool ast_ifthen_codegen(ast_ifthen*, ast_function*, bool lvalue, ir_value**);
33 static void ast_ternary_delete(ast_ternary*);
34 static bool ast_ternary_codegen(ast_ternary*, ast_function*, bool lvalue, ir_value**);
35 static void ast_loop_delete(ast_loop*);
36 static bool ast_loop_codegen(ast_loop*, ast_function*, bool lvalue, ir_value**);
37 static void ast_breakcont_delete(ast_breakcont*);
38 static bool ast_breakcont_codegen(ast_breakcont*, ast_function*, bool lvalue, ir_value**);
39 static void ast_switch_delete(ast_switch*);
40 static bool ast_switch_codegen(ast_switch*, ast_function*, bool lvalue, ir_value**);
41 static void ast_label_delete(ast_label*);
42 static void ast_label_register_goto(ast_label*, ast_goto*);
43 static bool ast_label_codegen(ast_label*, ast_function*, bool lvalue, ir_value**);
44 static bool ast_goto_codegen(ast_goto*, ast_function*, bool lvalue, ir_value**);
45 static void ast_goto_delete(ast_goto*);
46 static void ast_call_delete(ast_call*);
47 static bool ast_call_codegen(ast_call*, ast_function*, bool lvalue, ir_value**);
48 static bool ast_block_codegen(ast_block*, ast_function*, bool lvalue, ir_value**);
49 static void ast_unary_delete(ast_unary*);
50 static bool ast_unary_codegen(ast_unary*, ast_function*, bool lvalue, ir_value**);
51 static void ast_entfield_delete(ast_entfield*);
52 static bool ast_entfield_codegen(ast_entfield*, ast_function*, bool lvalue, ir_value**);
53 static void ast_return_delete(ast_return*);
54 static bool ast_return_codegen(ast_return*, ast_function*, bool lvalue, ir_value**);
55 static void ast_binstore_delete(ast_binstore*);
56 static bool ast_binstore_codegen(ast_binstore*, ast_function*, bool lvalue, ir_value**);
57 static void ast_binary_delete(ast_binary*);
58 static bool ast_binary_codegen(ast_binary*, ast_function*, bool lvalue, ir_value**);
59 static bool ast_state_codegen(ast_state*, ast_function*, bool lvalue, ir_value**);
61 /* It must not be possible to get here. */
62 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
65 con_err("ast node missing destroy()\n");
69 /* Initialize main ast node aprts */
70 static void ast_node_init(ast_node *self, lex_ctx_t ctx, int node_type)
73 self->destroy = &_ast_node_destroy;
74 self->keep_node = false;
75 self->node_type = node_type;
76 self->side_effects = false;
79 /* weight and side effects */
80 static void _ast_propagate_effects(ast_node *self, ast_node *other)
82 if (ast_side_effects(other))
83 ast_side_effects(self) = true;
85 #define ast_propagate_effects(s,o) _ast_propagate_effects(((ast_node*)(s)), ((ast_node*)(o)))
87 /* General expression initialization */
88 static void ast_expression_init(ast_expression *self,
89 ast_expression_codegen *codegen)
91 self->codegen = codegen;
92 self->vtype = TYPE_VOID;
97 self->varparam = nullptr;
99 if (OPTS_OPTION_BOOL(OPTION_COVERAGE))
100 self->flags |= AST_FLAG_BLOCK_COVERAGE;
103 static void ast_expression_delete(ast_expression *self)
106 ast_delete(self->next);
107 for (auto &it : self->type_params)
110 ast_delete(self->varparam);
113 static void ast_expression_delete_full(ast_expression *self)
115 ast_expression_delete(self);
119 ast_value* ast_value_copy(const ast_value *self)
121 ast_value *cp = ast_value_new(self->context, self->name, self->vtype);
123 cp->next = ast_type_copy(self->context, self->next);
125 const ast_expression *fromex = self;
126 ast_expression *selfex = cp;
127 selfex->count = fromex->count;
128 selfex->flags = fromex->flags;
129 for (auto &it : fromex->type_params) {
130 ast_value *v = ast_value_copy(it);
131 selfex->type_params.push_back(v);
136 void ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
138 const ast_expression *fromex;
139 ast_expression *selfex;
140 self->vtype = other->vtype;
142 self->next = (ast_expression*)ast_type_copy(ast_ctx(self), other->next);
146 selfex->count = fromex->count;
147 selfex->flags = fromex->flags;
148 for (auto &it : fromex->type_params) {
149 ast_value *v = ast_value_copy(it);
150 selfex->type_params.push_back(v);
154 static ast_expression* ast_shallow_type(lex_ctx_t ctx, qc_type vtype)
156 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
157 ast_expression_init(self, nullptr);
158 self->codegen = nullptr;
159 self->next = nullptr;
164 ast_expression* ast_type_copy(lex_ctx_t ctx, const ast_expression *ex)
166 const ast_expression *fromex;
167 ast_expression *selfex;
173 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
174 ast_expression_init(self, nullptr);
179 /* This may never be codegen()d */
180 selfex->codegen = nullptr;
182 selfex->vtype = fromex->vtype;
184 selfex->next = ast_type_copy(ctx, fromex->next);
186 selfex->next = nullptr;
188 selfex->count = fromex->count;
189 selfex->flags = fromex->flags;
190 for (auto &it : fromex->type_params) {
191 ast_value *v = ast_value_copy(it);
192 selfex->type_params.push_back(v);
199 bool ast_compare_type(ast_expression *a, ast_expression *b)
201 if (a->vtype == TYPE_NIL ||
202 b->vtype == TYPE_NIL)
204 if (a->vtype != b->vtype)
206 if (!a->next != !b->next)
208 if (a->type_params.size() != b->type_params.size())
210 if ((a->flags & AST_FLAG_TYPE_MASK) !=
211 (b->flags & AST_FLAG_TYPE_MASK) )
215 if (a->type_params.size()) {
217 for (i = 0; i < a->type_params.size(); ++i) {
218 if (!ast_compare_type((ast_expression*)a->type_params[i],
219 (ast_expression*)b->type_params[i]))
224 return ast_compare_type(a->next, b->next);
228 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
235 if (pos + 6 >= bufsize)
237 util_strncpy(buf + pos, "(null)", 6);
241 if (pos + 1 >= bufsize)
246 util_strncpy(buf + pos, "(variant)", 9);
251 return ast_type_to_string_impl(e->next, buf, bufsize, pos);
254 if (pos + 3 >= bufsize)
258 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
259 if (pos + 1 >= bufsize)
265 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
266 if (pos + 2 >= bufsize)
268 if (e->type_params.empty()) {
274 pos = ast_type_to_string_impl((ast_expression*)(e->type_params[0]), buf, bufsize, pos);
275 for (i = 1; i < e->type_params.size(); ++i) {
276 if (pos + 2 >= bufsize)
280 pos = ast_type_to_string_impl((ast_expression*)(e->type_params[i]), buf, bufsize, pos);
282 if (pos + 1 >= bufsize)
288 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
289 if (pos + 1 >= bufsize)
292 pos += util_snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->count);
293 if (pos + 1 >= bufsize)
299 typestr = type_name[e->vtype];
300 typelen = strlen(typestr);
301 if (pos + typelen >= bufsize)
303 util_strncpy(buf + pos, typestr, typelen);
304 return pos + typelen;
308 buf[bufsize-3] = '.';
309 buf[bufsize-2] = '.';
310 buf[bufsize-1] = '.';
314 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
316 size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
320 static bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out);
321 ast_value* ast_value_new(lex_ctx_t ctx, const char *name, qc_type t)
323 ast_instantiate(ast_value, ctx, ast_value_delete);
324 ast_expression_init((ast_expression*)self,
325 (ast_expression_codegen*)&ast_value_codegen);
326 self->keep_node = true; /* keep */
328 self->name = name ? util_strdup(name) : nullptr;
330 self->next = nullptr;
331 self->isfield = false;
333 self->hasvalue = false;
335 self->inexact = false;
337 memset(&self->constval, 0, sizeof(self->constval));
339 self->ir_v = nullptr;
340 self->ir_values = nullptr;
341 self->ir_value_count = 0;
343 self->setter = nullptr;
344 self->getter = nullptr;
345 self->desc = nullptr;
347 self->argcounter = nullptr;
348 self->intrinsic = false;
353 void ast_value_delete(ast_value* self)
356 mem_d((void*)self->name);
357 if (self->argcounter)
358 mem_d((void*)self->argcounter);
359 if (self->hasvalue) {
363 mem_d((void*)self->constval.vstring);
366 /* unlink us from the function node */
367 self->constval.vfunc->function_type = nullptr;
369 /* NOTE: delete function? currently collected in
370 * the parser structure
377 mem_d(self->ir_values);
382 // initlist imples an array which implies .next in the expression exists.
383 if (self->initlist.size() && self->next->vtype == TYPE_STRING) {
384 for (auto &it : self->initlist)
389 ast_expression_delete((ast_expression*)self);
393 void ast_value_params_add(ast_value *self, ast_value *p)
395 self->type_params.push_back(p);
398 bool ast_value_set_name(ast_value *self, const char *name)
401 mem_d((void*)self->name);
402 self->name = util_strdup(name);
406 ast_binary* ast_binary_new(lex_ctx_t ctx, int op,
407 ast_expression* left, ast_expression* right)
409 ast_instantiate(ast_binary, ctx, ast_binary_delete);
410 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
412 if (ast_istype(right, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
413 ast_unary *unary = ((ast_unary*)right);
414 ast_expression *normal = unary->operand;
416 /* make a-(-b) => a + b */
417 if (unary->op == VINSTR_NEG_F || unary->op == VINSTR_NEG_V) {
418 if (op == INSTR_SUB_F) {
421 ++opts_optimizationcount[OPTIM_PEEPHOLE];
422 } else if (op == INSTR_SUB_V) {
425 ++opts_optimizationcount[OPTIM_PEEPHOLE];
433 self->right_first = false;
435 ast_propagate_effects(self, left);
436 ast_propagate_effects(self, right);
438 if (op >= INSTR_EQ_F && op <= INSTR_GT)
439 self->vtype = TYPE_FLOAT;
440 else if (op == INSTR_AND || op == INSTR_OR) {
441 if (OPTS_FLAG(PERL_LOGIC))
442 ast_type_adopt(self, right);
444 self->vtype = TYPE_FLOAT;
446 else if (op == INSTR_BITAND || op == INSTR_BITOR)
447 self->vtype = TYPE_FLOAT;
448 else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
449 self->vtype = TYPE_VECTOR;
450 else if (op == INSTR_MUL_V)
451 self->vtype = TYPE_FLOAT;
453 self->vtype = left->vtype;
456 self->refs = AST_REF_ALL;
461 void ast_binary_delete(ast_binary *self)
463 if (self->refs & AST_REF_LEFT) ast_unref(self->left);
464 if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
466 ast_expression_delete((ast_expression*)self);
470 ast_binstore* ast_binstore_new(lex_ctx_t ctx, int storop, int op,
471 ast_expression* left, ast_expression* right)
473 ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
474 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
476 ast_side_effects(self) = true;
478 self->opstore = storop;
481 self->source = right;
483 self->keep_dest = false;
485 ast_type_adopt(self, left);
489 void ast_binstore_delete(ast_binstore *self)
491 if (!self->keep_dest)
492 ast_unref(self->dest);
493 ast_unref(self->source);
494 ast_expression_delete((ast_expression*)self);
498 ast_unary* ast_unary_new(lex_ctx_t ctx, int op,
499 ast_expression *expr)
501 ast_instantiate(ast_unary, ctx, ast_unary_delete);
502 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
505 self->operand = expr;
508 if (ast_istype(expr, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
509 ast_unary *prev = (ast_unary*)((ast_unary*)expr)->operand;
511 /* Handle for double negation */
512 if (((ast_unary*)expr)->op == op)
513 prev = (ast_unary*)((ast_unary*)expr)->operand;
515 if (ast_istype(prev, ast_unary)) {
516 ast_expression_delete((ast_expression*)self);
518 ++opts_optimizationcount[OPTIM_PEEPHOLE];
523 ast_propagate_effects(self, expr);
525 if ((op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) || op == VINSTR_NEG_F) {
526 self->vtype = TYPE_FLOAT;
527 } else if (op == VINSTR_NEG_V) {
528 self->vtype = TYPE_VECTOR;
530 compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
536 void ast_unary_delete(ast_unary *self)
538 if (self->operand) ast_unref(self->operand);
539 ast_expression_delete((ast_expression*)self);
543 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
545 ast_instantiate(ast_return, ctx, ast_return_delete);
546 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
548 self->operand = expr;
551 ast_propagate_effects(self, expr);
556 void ast_return_delete(ast_return *self)
559 ast_unref(self->operand);
560 ast_expression_delete((ast_expression*)self);
564 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
566 if (field->vtype != TYPE_FIELD) {
567 compile_error(ctx, "ast_entfield_new with expression not of type field");
570 return ast_entfield_new_force(ctx, entity, field, field->next);
573 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
575 ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
579 /* Error: field has no type... */
583 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
585 self->entity = entity;
587 ast_propagate_effects(self, entity);
588 ast_propagate_effects(self, field);
590 ast_type_adopt(self, outtype);
594 void ast_entfield_delete(ast_entfield *self)
596 ast_unref(self->entity);
597 ast_unref(self->field);
598 ast_expression_delete((ast_expression*)self);
602 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
604 ast_instantiate(ast_member, ctx, ast_member_delete);
610 if (owner->vtype != TYPE_VECTOR &&
611 owner->vtype != TYPE_FIELD) {
612 compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
617 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
618 self->keep_node = true; /* keep */
620 if (owner->vtype == TYPE_VECTOR) {
621 self->vtype = TYPE_FLOAT;
622 self->next = nullptr;
624 self->vtype = TYPE_FIELD;
625 self->next = ast_shallow_type(ctx, TYPE_FLOAT);
628 self->rvalue = false;
630 ast_propagate_effects(self, owner);
634 self->name = util_strdup(name);
636 self->name = nullptr;
641 void ast_member_delete(ast_member *self)
643 /* The owner is always an ast_value, which has .keep_node=true,
644 * also: ast_members are usually deleted after the owner, thus
645 * this will cause invalid access
646 ast_unref(self->owner);
647 * once we allow (expression).x to access a vector-member, we need
648 * to change this: preferably by creating an alternate ast node for this
649 * purpose that is not garbage-collected.
651 ast_expression_delete((ast_expression*)self);
656 bool ast_member_set_name(ast_member *self, const char *name)
659 mem_d((void*)self->name);
660 self->name = util_strdup(name);
664 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
666 ast_expression *outtype;
667 ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
669 outtype = array->next;
672 /* Error: field has no type... */
676 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
680 ast_propagate_effects(self, array);
681 ast_propagate_effects(self, index);
683 ast_type_adopt(self, outtype);
684 if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
685 if (self->vtype != TYPE_ARRAY) {
686 compile_error(ast_ctx(self), "array_index node on type");
687 ast_array_index_delete(self);
690 self->array = outtype;
691 self->vtype = TYPE_FIELD;
697 void ast_array_index_delete(ast_array_index *self)
700 ast_unref(self->array);
702 ast_unref(self->index);
703 ast_expression_delete((ast_expression*)self);
707 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
709 ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete);
710 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
712 self->vtype = TYPE_NOEXPR;
716 void ast_argpipe_delete(ast_argpipe *self)
719 ast_unref(self->index);
720 ast_expression_delete((ast_expression*)self);
724 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
726 ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
727 if (!ontrue && !onfalse) {
728 /* because it is invalid */
732 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
735 self->on_true = ontrue;
736 self->on_false = onfalse;
737 ast_propagate_effects(self, cond);
739 ast_propagate_effects(self, ontrue);
741 ast_propagate_effects(self, onfalse);
746 void ast_ifthen_delete(ast_ifthen *self)
748 ast_unref(self->cond);
750 ast_unref(self->on_true);
752 ast_unref(self->on_false);
753 ast_expression_delete((ast_expression*)self);
757 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
759 ast_expression *exprtype = ontrue;
760 ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
761 /* This time NEITHER must be nullptr */
762 if (!ontrue || !onfalse) {
766 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
769 self->on_true = ontrue;
770 self->on_false = onfalse;
771 ast_propagate_effects(self, cond);
772 ast_propagate_effects(self, ontrue);
773 ast_propagate_effects(self, onfalse);
775 if (ontrue->vtype == TYPE_NIL)
777 ast_type_adopt(self, exprtype);
782 void ast_ternary_delete(ast_ternary *self)
784 /* the if()s are only there because computed-gotos can set them
787 if (self->cond) ast_unref(self->cond);
788 if (self->on_true) ast_unref(self->on_true);
789 if (self->on_false) ast_unref(self->on_false);
790 ast_expression_delete((ast_expression*)self);
794 ast_loop* ast_loop_new(lex_ctx_t ctx,
795 ast_expression *initexpr,
796 ast_expression *precond, bool pre_not,
797 ast_expression *postcond, bool post_not,
798 ast_expression *increment,
799 ast_expression *body)
801 ast_instantiate(ast_loop, ctx, ast_loop_delete);
802 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
804 self->initexpr = initexpr;
805 self->precond = precond;
806 self->postcond = postcond;
807 self->increment = increment;
810 self->pre_not = pre_not;
811 self->post_not = post_not;
814 ast_propagate_effects(self, initexpr);
816 ast_propagate_effects(self, precond);
818 ast_propagate_effects(self, postcond);
820 ast_propagate_effects(self, increment);
822 ast_propagate_effects(self, body);
827 void ast_loop_delete(ast_loop *self)
830 ast_unref(self->initexpr);
832 ast_unref(self->precond);
834 ast_unref(self->postcond);
836 ast_unref(self->increment);
838 ast_unref(self->body);
839 ast_expression_delete((ast_expression*)self);
843 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
845 ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
846 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
848 self->is_continue = iscont;
849 self->levels = levels;
854 void ast_breakcont_delete(ast_breakcont *self)
856 ast_expression_delete((ast_expression*)self);
860 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
862 ast_instantiate(ast_switch, ctx, ast_switch_delete);
863 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
867 ast_propagate_effects(self, op);
872 void ast_switch_delete(ast_switch *self)
874 ast_unref(self->operand);
876 for (auto &it : self->cases) {
882 ast_expression_delete((ast_expression*)self);
886 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
888 ast_instantiate(ast_label, ctx, ast_label_delete);
889 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
891 self->vtype = TYPE_NOEXPR;
893 self->name = util_strdup(name);
894 self->irblock = nullptr;
895 self->undefined = undefined;
900 void ast_label_delete(ast_label *self)
902 mem_d((void*)self->name);
903 ast_expression_delete((ast_expression*)self);
907 static void ast_label_register_goto(ast_label *self, ast_goto *g)
909 self->gotos.push_back(g);
912 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
914 ast_instantiate(ast_goto, ctx, ast_goto_delete);
915 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
917 self->name = util_strdup(name);
918 self->target = nullptr;
919 self->irblock_from = nullptr;
924 void ast_goto_delete(ast_goto *self)
926 mem_d((void*)self->name);
927 ast_expression_delete((ast_expression*)self);
931 void ast_goto_set_label(ast_goto *self, ast_label *label)
933 self->target = label;
936 ast_state* ast_state_new(lex_ctx_t ctx, ast_expression *frame, ast_expression *think)
938 ast_instantiate(ast_state, ctx, ast_state_delete);
939 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_state_codegen);
940 self->framenum = frame;
941 self->nextthink = think;
945 void ast_state_delete(ast_state *self)
948 ast_unref(self->framenum);
950 ast_unref(self->nextthink);
952 ast_expression_delete((ast_expression*)self);
956 ast_call* ast_call_new(lex_ctx_t ctx,
957 ast_expression *funcexpr)
959 ast_instantiate(ast_call, ctx, ast_call_delete);
960 if (!funcexpr->next) {
961 compile_error(ctx, "not a function");
965 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
967 ast_side_effects(self) = true;
969 self->func = funcexpr;
970 self->va_count = nullptr;
972 ast_type_adopt(self, funcexpr->next);
977 void ast_call_delete(ast_call *self)
979 for (auto &it : self->params)
983 ast_unref(self->func);
986 ast_unref(self->va_count);
988 ast_expression_delete((ast_expression*)self);
992 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
998 if (!va_type || !ast_compare_type(va_type, exp_type))
1000 if (va_type && exp_type)
1002 ast_type_to_string(va_type, tgot, sizeof(tgot));
1003 ast_type_to_string(exp_type, texp, sizeof(texp));
1004 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1005 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1006 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1010 compile_error(ast_ctx(self),
1011 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1018 ast_type_to_string(exp_type, texp, sizeof(texp));
1019 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1020 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1021 "piped variadic argument may differ in type: expected type %s",
1025 compile_error(ast_ctx(self),
1026 "piped variadic argument may differ in type: expected type %s",
1035 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1041 const ast_expression *func = self->func;
1042 size_t count = self->params.size();
1043 if (count > func->type_params.size())
1044 count = func->type_params.size();
1046 for (i = 0; i < count; ++i) {
1047 if (ast_istype(self->params[i], ast_argpipe)) {
1048 /* warn about type safety instead */
1050 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1053 if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->type_params[i]))
1056 else if (!ast_compare_type(self->params[i], (ast_expression*)(func->type_params[i])))
1058 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1059 ast_type_to_string((ast_expression*)func->type_params[i], texp, sizeof(texp));
1060 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1061 (unsigned int)(i+1), texp, tgot);
1062 /* we don't immediately return */
1066 count = self->params.size();
1067 if (count > func->type_params.size() && func->varparam) {
1068 for (; i < count; ++i) {
1069 if (ast_istype(self->params[i], ast_argpipe)) {
1070 /* warn about type safety instead */
1072 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1075 if (!ast_call_check_vararg(self, va_type, func->varparam))
1078 else if (!ast_compare_type(self->params[i], func->varparam))
1080 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1081 ast_type_to_string(func->varparam, texp, sizeof(texp));
1082 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1083 (unsigned int)(i+1), texp, tgot);
1084 /* we don't immediately return */
1092 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1093 ast_expression *dest, ast_expression *source)
1095 ast_instantiate(ast_store, ctx, ast_store_delete);
1096 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1098 ast_side_effects(self) = true;
1102 self->source = source;
1104 ast_type_adopt(self, dest);
1109 void ast_store_delete(ast_store *self)
1111 ast_unref(self->dest);
1112 ast_unref(self->source);
1113 ast_expression_delete((ast_expression*)self);
1117 ast_block* ast_block_new(lex_ctx_t ctx)
1119 ast_instantiate(ast_block, ctx, ast_block_delete);
1120 ast_expression_init((ast_expression*)self,
1121 (ast_expression_codegen*)&ast_block_codegen);
1125 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1127 ast_propagate_effects(self, e);
1128 self->exprs.push_back(e);
1130 ast_delete(self->next);
1131 self->next = nullptr;
1133 ast_type_adopt(self, e);
1137 void ast_block_collect(ast_block *self, ast_expression *expr)
1139 self->collect.push_back(expr);
1140 expr->keep_node = true;
1143 void ast_block_delete(ast_block *self)
1145 for (auto &it : self->exprs) ast_unref(it);
1146 for (auto &it : self->locals) ast_delete(it);
1147 for (auto &it : self->collect) ast_delete(it);
1148 ast_expression_delete((ast_expression*)self);
1152 void ast_block_set_type(ast_block *self, ast_expression *from)
1155 ast_delete(self->next);
1156 ast_type_adopt(self, from);
1159 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1161 ast_instantiate(ast_function, ctx, ast_function_delete);
1164 compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1166 } else if (vtype->hasvalue || vtype->vtype != TYPE_FUNCTION) {
1167 compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1169 (int)vtype->hasvalue,
1174 self->function_type = vtype;
1175 self->name = name ? util_strdup(name) : nullptr;
1177 self->labelcount = 0;
1180 self->ir_func = nullptr;
1181 self->curblock = nullptr;
1183 vtype->hasvalue = true;
1184 vtype->constval.vfunc = self;
1186 self->varargs = nullptr;
1187 self->argc = nullptr;
1188 self->fixedparams = nullptr;
1189 self->return_value = nullptr;
1190 self->static_count = 0;
1199 void ast_function_delete(ast_function *self)
1202 mem_d((void*)self->name);
1203 if (self->function_type) {
1204 /* ast_value_delete(self->function_type); */
1205 self->function_type->hasvalue = false;
1206 self->function_type->constval.vfunc = nullptr;
1207 /* We use unref - if it was stored in a global table it is supposed
1208 * to be deleted from *there*
1210 ast_unref(self->function_type);
1212 for (auto &it : self->static_names)
1214 for (auto &it : self->blocks)
1217 ast_delete(self->varargs);
1219 ast_delete(self->argc);
1220 if (self->fixedparams)
1221 ast_unref(self->fixedparams);
1222 if (self->return_value)
1223 ast_unref(self->return_value);
1227 const char* ast_function_label(ast_function *self, const char *prefix)
1233 if (!OPTS_OPTION_BOOL(OPTION_DUMP) &&
1234 !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1235 !OPTS_OPTION_BOOL(OPTION_DEBUG))
1240 id = (self->labelcount++);
1241 len = strlen(prefix);
1243 from = self->labelbuf + sizeof(self->labelbuf)-1;
1246 *from-- = (id%10) + '0';
1250 memcpy(from - len, prefix, len);
1254 /*********************************************************************/
1256 * by convention you must never pass nullptr to the 'ir_value **out'
1257 * parameter. If you really don't care about the output, pass a dummy.
1258 * But I can't imagine a pituation where the output is truly unnecessary.
1261 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1263 if (out->vtype == TYPE_FIELD)
1264 out->fieldtype = self->next->vtype;
1265 if (out->vtype == TYPE_FUNCTION)
1266 out->outtype = self->next->vtype;
1269 #define codegen_output_type(a,o) (_ast_codegen_output_type(static_cast<ast_expression*>((a)),(o)))
1271 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1275 if (self->vtype == TYPE_NIL) {
1276 *out = func->ir_func->owner->nil;
1279 /* NOTE: This is the codegen for a variable used in an
1280 * It is not the codegen to generate the value. For this purpose,
1281 * ast_local_codegen and ast_global_codegen are to be used before this
1282 * is executed. ast_function_codegen should take care of its locals,
1283 * and the ast-user should take care of ast_global_codegen to be used
1284 * on all the globals.
1287 char tname[1024]; /* typename is reserved in C++ */
1288 ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1289 compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1296 static bool ast_global_array_set(ast_value *self)
1298 size_t count = self->initlist.size();
1301 if (count > self->count) {
1302 compile_error(ast_ctx(self), "too many elements in initializer");
1303 count = self->count;
1305 else if (count < self->count) {
1307 compile_warning(ast_ctx(self), "not all elements are initialized");
1311 for (i = 0; i != count; ++i) {
1312 switch (self->next->vtype) {
1314 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1318 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1322 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1326 /* we don't support them in any other place yet either */
1327 compile_error(ast_ctx(self), "TODO: nested arrays");
1330 /* this requiers a bit more work - similar to the fields I suppose */
1331 compile_error(ast_ctx(self), "global of type function not properly generated");
1334 if (!self->initlist[i].vfield) {
1335 compile_error(ast_ctx(self), "field constant without vfield set");
1338 if (!self->initlist[i].vfield->ir_v) {
1339 compile_error(ast_ctx(self), "field constant generated before its field");
1342 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1346 compile_error(ast_ctx(self), "TODO: global constant type %i", self->vtype);
1353 static bool check_array(ast_value *self, ast_value *array)
1355 if (array->flags & AST_FLAG_ARRAY_INIT && array->initlist.empty()) {
1356 compile_error(ast_ctx(self), "array without size: %s", self->name);
1359 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1360 if (!array->count || array->count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1361 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->count);
1367 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1369 ir_value *v = nullptr;
1371 if (self->vtype == TYPE_NIL) {
1372 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1376 if (self->hasvalue && self->vtype == TYPE_FUNCTION)
1378 ir_function *func = ir_builder_create_function(ir, self->name, self->next->vtype);
1381 func->context = ast_ctx(self);
1382 func->value->context = ast_ctx(self);
1384 self->constval.vfunc->ir_func = func;
1385 self->ir_v = func->value;
1386 if (self->flags & AST_FLAG_INCLUDE_DEF)
1387 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1388 if (self->flags & AST_FLAG_ERASEABLE)
1389 self->ir_v->flags |= IR_FLAG_ERASABLE;
1390 if (self->flags & AST_FLAG_BLOCK_COVERAGE)
1391 func->flags |= IR_FLAG_BLOCK_COVERAGE;
1392 /* The function is filled later on ast_function_codegen... */
1396 if (isfield && self->vtype == TYPE_FIELD) {
1397 ast_expression *fieldtype = self->next;
1399 if (self->hasvalue) {
1400 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1404 if (fieldtype->vtype == TYPE_ARRAY) {
1409 ast_expression *elemtype;
1411 ast_value *array = (ast_value*)fieldtype;
1413 if (!ast_istype(fieldtype, ast_value)) {
1414 compile_error(ast_ctx(self), "internal error: ast_value required");
1418 if (!check_array(self, array))
1421 elemtype = array->next;
1422 vtype = elemtype->vtype;
1424 v = ir_builder_create_field(ir, self->name, vtype);
1426 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1429 v->context = ast_ctx(self);
1430 v->unique_life = true;
1432 array->ir_v = self->ir_v = v;
1434 if (self->flags & AST_FLAG_INCLUDE_DEF)
1435 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1436 if (self->flags & AST_FLAG_ERASEABLE)
1437 self->ir_v->flags |= IR_FLAG_ERASABLE;
1439 namelen = strlen(self->name);
1440 name = (char*)mem_a(namelen + 16);
1441 util_strncpy(name, self->name, namelen);
1443 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->count);
1444 array->ir_values[0] = v;
1445 for (ai = 1; ai < array->count; ++ai) {
1446 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1447 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1448 if (!array->ir_values[ai]) {
1450 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1453 array->ir_values[ai]->context = ast_ctx(self);
1454 array->ir_values[ai]->unique_life = true;
1455 array->ir_values[ai]->locked = true;
1456 if (self->flags & AST_FLAG_INCLUDE_DEF)
1457 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1463 v = ir_builder_create_field(ir, self->name, self->next->vtype);
1466 v->context = ast_ctx(self);
1468 if (self->flags & AST_FLAG_INCLUDE_DEF)
1469 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1471 if (self->flags & AST_FLAG_ERASEABLE)
1472 self->ir_v->flags |= IR_FLAG_ERASABLE;
1477 if (self->vtype == TYPE_ARRAY) {
1482 ast_expression *elemtype = self->next;
1483 qc_type vtype = elemtype->vtype;
1485 if (self->flags & AST_FLAG_ARRAY_INIT && !self->count) {
1486 compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1490 /* same as with field arrays */
1491 if (!check_array(self, self))
1494 v = ir_builder_create_global(ir, self->name, vtype);
1496 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1499 v->context = ast_ctx(self);
1500 v->unique_life = true;
1503 if (self->flags & AST_FLAG_INCLUDE_DEF)
1504 v->flags |= IR_FLAG_INCLUDE_DEF;
1505 if (self->flags & AST_FLAG_ERASEABLE)
1506 self->ir_v->flags |= IR_FLAG_ERASABLE;
1508 namelen = strlen(self->name);
1509 name = (char*)mem_a(namelen + 16);
1510 util_strncpy(name, self->name, namelen);
1512 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->count);
1513 self->ir_values[0] = v;
1514 for (ai = 1; ai < self->count; ++ai) {
1515 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1516 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1517 if (!self->ir_values[ai]) {
1519 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1522 self->ir_values[ai]->context = ast_ctx(self);
1523 self->ir_values[ai]->unique_life = true;
1524 self->ir_values[ai]->locked = true;
1525 if (self->flags & AST_FLAG_INCLUDE_DEF)
1526 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1532 /* Arrays don't do this since there's no "array" value which spans across the
1535 v = ir_builder_create_global(ir, self->name, self->vtype);
1537 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1540 codegen_output_type(self, v);
1541 v->context = ast_ctx(self);
1544 /* link us to the ir_value */
1548 if (self->flags & AST_FLAG_INCLUDE_DEF)
1549 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1550 if (self->flags & AST_FLAG_ERASEABLE)
1551 self->ir_v->flags |= IR_FLAG_ERASABLE;
1554 if (self->hasvalue) {
1555 switch (self->vtype)
1558 if (!ir_value_set_float(v, self->constval.vfloat))
1562 if (!ir_value_set_vector(v, self->constval.vvec))
1566 if (!ir_value_set_string(v, self->constval.vstring))
1570 ast_global_array_set(self);
1573 compile_error(ast_ctx(self), "global of type function not properly generated");
1575 /* Cannot generate an IR value for a function,
1576 * need a pointer pointing to a function rather.
1579 if (!self->constval.vfield) {
1580 compile_error(ast_ctx(self), "field constant without vfield set");
1583 if (!self->constval.vfield->ir_v) {
1584 compile_error(ast_ctx(self), "field constant generated before its field");
1587 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1591 compile_error(ast_ctx(self), "TODO: global constant type %i", self->vtype);
1597 error: /* clean up */
1602 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1604 ir_value *v = nullptr;
1606 if (self->vtype == TYPE_NIL) {
1607 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1611 if (self->hasvalue && self->vtype == TYPE_FUNCTION)
1613 /* Do we allow local functions? I think not...
1614 * this is NOT a function pointer atm.
1619 if (self->vtype == TYPE_ARRAY) {
1624 ast_expression *elemtype = self->next;
1625 qc_type vtype = elemtype->vtype;
1627 func->flags |= IR_FLAG_HAS_ARRAYS;
1629 if (param && !(self->flags & AST_FLAG_IS_VARARG)) {
1630 compile_error(ast_ctx(self), "array-parameters are not supported");
1634 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1635 if (!check_array(self, self))
1638 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->count);
1639 if (!self->ir_values) {
1640 compile_error(ast_ctx(self), "failed to allocate array values");
1644 v = ir_function_create_local(func, self->name, vtype, param);
1646 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1649 v->context = ast_ctx(self);
1650 v->unique_life = true;
1653 namelen = strlen(self->name);
1654 name = (char*)mem_a(namelen + 16);
1655 util_strncpy(name, self->name, namelen);
1657 self->ir_values[0] = v;
1658 for (ai = 1; ai < self->count; ++ai) {
1659 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1660 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1661 if (!self->ir_values[ai]) {
1662 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1665 self->ir_values[ai]->context = ast_ctx(self);
1666 self->ir_values[ai]->unique_life = true;
1667 self->ir_values[ai]->locked = true;
1673 v = ir_function_create_local(func, self->name, self->vtype, param);
1676 codegen_output_type(self, v);
1677 v->context = ast_ctx(self);
1680 /* A constant local... hmmm...
1681 * I suppose the IR will have to deal with this
1683 if (self->hasvalue) {
1684 switch (self->vtype)
1687 if (!ir_value_set_float(v, self->constval.vfloat))
1691 if (!ir_value_set_vector(v, self->constval.vvec))
1695 if (!ir_value_set_string(v, self->constval.vstring))
1699 compile_error(ast_ctx(self), "TODO: global constant type %i", self->vtype);
1704 /* link us to the ir_value */
1708 if (!ast_generate_accessors(self, func->owner))
1712 error: /* clean up */
1717 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1720 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1721 if (!self->setter || !self->getter)
1723 for (i = 0; i < self->count; ++i) {
1724 if (!self->ir_values) {
1725 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1728 if (!self->ir_values[i]) {
1729 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1732 if (!self->ir_values[i]->life.empty()) {
1733 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1738 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1740 if (!ast_global_codegen (self->setter, ir, false) ||
1741 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1742 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1744 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1745 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1750 if (!ast_global_codegen (self->getter, ir, false) ||
1751 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1752 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1754 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1755 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1759 for (i = 0; i < self->count; ++i)
1760 self->ir_values[i]->life.clear();
1761 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1765 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1770 ast_expression_codegen *cgen;
1774 irf = self->ir_func;
1776 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1780 /* fill the parameter list */
1781 ec = self->function_type;
1782 for (auto &it : ec->type_params) {
1783 if (it->vtype == TYPE_FIELD)
1784 vec_push(irf->params, it->next->vtype);
1786 vec_push(irf->params, it->vtype);
1787 if (!self->builtin) {
1788 if (!ast_local_codegen(it, self->ir_func, true))
1793 if (self->varargs) {
1794 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1796 irf->max_varargs = self->varargs->count;
1799 if (self->builtin) {
1800 irf->builtin = self->builtin;
1804 /* have a local return value variable? */
1805 if (self->return_value) {
1806 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1810 if (self->blocks.empty()) {
1811 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1815 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1816 if (!self->curblock) {
1817 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1825 if (!ast_local_codegen(self->argc, self->ir_func, true))
1827 cgen = self->argc->codegen;
1828 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1830 cgen = self->fixedparams->codegen;
1831 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1833 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1834 ast_function_label(self, "va_count"), INSTR_SUB_F,
1835 ir_builder_get_va_count(ir), fixed);
1838 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1845 for (auto &it : self->blocks) {
1847 if (!(*cgen)((ast_expression*)it, self, false, &dummy))
1851 /* TODO: check return types */
1852 if (!self->curblock->final)
1854 if (!self->function_type->next ||
1855 self->function_type->next->vtype == TYPE_VOID)
1857 return ir_block_create_return(self->curblock, ast_ctx(self), nullptr);
1859 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1861 if (self->return_value) {
1862 cgen = self->return_value->codegen;
1863 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1865 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1867 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1868 "control reaches end of non-void function (`%s`) via %s",
1869 self->name, self->curblock->label.c_str()))
1873 return ir_block_create_return(self->curblock, ast_ctx(self), nullptr);
1879 static bool starts_a_label(ast_expression *ex)
1881 while (ex && ast_istype(ex, ast_block)) {
1882 ast_block *b = (ast_block*)ex;
1887 return ast_istype(ex, ast_label);
1890 /* Note, you will not see ast_block_codegen generate ir_blocks.
1891 * To the AST and the IR, blocks are 2 different things.
1892 * In the AST it represents a block of code, usually enclosed in
1893 * curly braces {...}.
1894 * While in the IR it represents a block in terms of control-flow.
1896 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1898 /* We don't use this
1899 * Note: an ast-representation using the comma-operator
1900 * of the form: (a, b, c) = x should not assign to c...
1903 compile_error(ast_ctx(self), "not an l-value (code-block)");
1912 /* output is nullptr at first, we'll have each expression
1913 * assign to out output, thus, a comma-operator represention
1914 * using an ast_block will return the last generated value,
1915 * so: (b, c) + a executed both b and c, and returns c,
1916 * which is then added to a.
1920 /* generate locals */
1921 for (auto &it : self->locals) {
1922 if (!ast_local_codegen(it, func->ir_func, false)) {
1923 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1924 compile_error(ast_ctx(self), "failed to generate local `%s`", it->name);
1929 for (auto &it : self->exprs) {
1930 ast_expression_codegen *gen;
1931 if (func->curblock->final && !starts_a_label(it)) {
1932 if (compile_warning(ast_ctx(it), WARN_UNREACHABLE_CODE, "unreachable statement"))
1937 if (!(*gen)(it, func, false, out))
1946 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1948 ast_expression_codegen *cgen;
1949 ir_value *left = nullptr;
1950 ir_value *right = nullptr;
1954 ast_array_index *ai = nullptr;
1956 if (lvalue && self->outl) {
1961 if (!lvalue && self->outr) {
1966 if (ast_istype(self->dest, ast_array_index))
1969 ai = (ast_array_index*)self->dest;
1970 idx = (ast_value*)ai->index;
1972 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
1977 /* we need to call the setter */
1978 ir_value *iridx, *funval;
1982 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1986 arr = (ast_value*)ai->array;
1987 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1988 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
1992 cgen = idx->codegen;
1993 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1996 cgen = arr->setter->codegen;
1997 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2000 cgen = self->source->codegen;
2001 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2004 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2007 ir_call_param(call, iridx);
2008 ir_call_param(call, right);
2015 cgen = self->dest->codegen;
2017 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
2021 cgen = self->source->codegen;
2023 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2026 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2031 /* Theoretically, an assinment returns its left side as an
2032 * lvalue, if we don't need an lvalue though, we return
2033 * the right side as an rvalue, otherwise we have to
2034 * somehow know whether or not we need to dereference the pointer
2035 * on the left side - that is: OP_LOAD if it was an address.
2036 * Also: in original QC we cannot OP_LOADP *anyway*.
2038 *out = (lvalue ? left : right);
2043 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2045 ast_expression_codegen *cgen;
2046 ir_value *left, *right;
2048 /* A binary operation cannot yield an l-value */
2050 compile_error(ast_ctx(self), "not an l-value (binop)");
2059 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2060 (self->op == INSTR_AND || self->op == INSTR_OR))
2062 /* NOTE: The short-logic path will ignore right_first */
2064 /* short circuit evaluation */
2065 ir_block *other, *merge;
2066 ir_block *from_left, *from_right;
2070 /* prepare end-block */
2071 merge_id = func->ir_func->blocks.size();
2072 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2074 /* generate the left expression */
2075 cgen = self->left->codegen;
2076 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2078 /* remember the block */
2079 from_left = func->curblock;
2081 /* create a new block for the right expression */
2082 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2083 if (self->op == INSTR_AND) {
2084 /* on AND: left==true -> other */
2085 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2088 /* on OR: left==false -> other */
2089 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2092 /* use the likely flag */
2093 vec_last(func->curblock->instr)->likely = true;
2095 /* enter the right-expression's block */
2096 func->curblock = other;
2098 cgen = self->right->codegen;
2099 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2101 /* remember block */
2102 from_right = func->curblock;
2104 /* jump to the merge block */
2105 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2108 func->ir_func->blocks.erase(func->ir_func->blocks.begin() + merge_id);
2109 func->ir_func->blocks.emplace_back(merge);
2111 func->curblock = merge;
2112 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2113 ast_function_label(func, "sce_value"),
2115 ir_phi_add(phi, from_left, left);
2116 ir_phi_add(phi, from_right, right);
2117 *out = ir_phi_value(phi);
2121 if (!OPTS_FLAG(PERL_LOGIC)) {
2123 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2124 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2125 ast_function_label(func, "sce_bool_v"),
2129 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2130 ast_function_label(func, "sce_bool"),
2135 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2136 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2137 ast_function_label(func, "sce_bool_s"),
2141 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2142 ast_function_label(func, "sce_bool"),
2148 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2149 ast_function_label(func, "sce_bool"),
2150 INSTR_AND, *out, *out);
2157 codegen_output_type(self, *out);
2161 if (self->right_first) {
2162 cgen = self->right->codegen;
2163 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2165 cgen = self->left->codegen;
2166 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2169 cgen = self->left->codegen;
2170 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2172 cgen = self->right->codegen;
2173 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2177 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2178 self->op, left, right);
2182 codegen_output_type(self, *out);
2187 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2189 ast_expression_codegen *cgen;
2190 ir_value *leftl = nullptr, *leftr, *right, *bin;
2194 ast_array_index *ai = nullptr;
2195 ir_value *iridx = nullptr;
2197 if (lvalue && self->outl) {
2202 if (!lvalue && self->outr) {
2207 if (ast_istype(self->dest, ast_array_index))
2210 ai = (ast_array_index*)self->dest;
2211 idx = (ast_value*)ai->index;
2213 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2217 /* for a binstore we need both an lvalue and an rvalue for the left side */
2218 /* rvalue of destination! */
2220 cgen = idx->codegen;
2221 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2224 cgen = self->dest->codegen;
2225 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2228 /* source as rvalue only */
2229 cgen = self->source->codegen;
2230 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2233 /* now the binary */
2234 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2235 self->opbin, leftr, right);
2239 /* we need to call the setter */
2244 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2248 arr = (ast_value*)ai->array;
2249 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2250 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2254 cgen = arr->setter->codegen;
2255 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2258 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2261 ir_call_param(call, iridx);
2262 ir_call_param(call, bin);
2265 /* now store them */
2266 cgen = self->dest->codegen;
2267 /* lvalue of destination */
2268 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2272 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2277 /* Theoretically, an assinment returns its left side as an
2278 * lvalue, if we don't need an lvalue though, we return
2279 * the right side as an rvalue, otherwise we have to
2280 * somehow know whether or not we need to dereference the pointer
2281 * on the left side - that is: OP_LOAD if it was an address.
2282 * Also: in original QC we cannot OP_LOADP *anyway*.
2284 *out = (lvalue ? leftl : bin);
2289 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2291 ast_expression_codegen *cgen;
2294 /* An unary operation cannot yield an l-value */
2296 compile_error(ast_ctx(self), "not an l-value (binop)");
2305 cgen = self->operand->codegen;
2307 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2310 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2319 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2321 ast_expression_codegen *cgen;
2326 /* In the context of a return operation, we don't actually return
2330 compile_error(ast_ctx(self), "return-expression is not an l-value");
2335 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2338 self->outr = (ir_value*)1;
2340 if (self->operand) {
2341 cgen = self->operand->codegen;
2343 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2346 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2349 if (!ir_block_create_return(func->curblock, ast_ctx(self), nullptr))
2356 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2358 ast_expression_codegen *cgen;
2359 ir_value *ent, *field;
2361 /* This function needs to take the 'lvalue' flag into account!
2362 * As lvalue we provide a field-pointer, as rvalue we provide the
2366 if (lvalue && self->outl) {
2371 if (!lvalue && self->outr) {
2376 cgen = self->entity->codegen;
2377 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2380 cgen = self->field->codegen;
2381 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2386 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2389 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2390 ent, field, self->vtype);
2391 /* Done AFTER error checking:
2392 codegen_output_type(self, *out);
2396 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2397 (lvalue ? "ADDRESS" : "FIELD"),
2398 type_name[self->vtype]);
2402 codegen_output_type(self, *out);
2409 /* Hm that should be it... */
2413 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2415 ast_expression_codegen *cgen;
2418 /* in QC this is always an lvalue */
2419 if (lvalue && self->rvalue) {
2420 compile_error(ast_ctx(self), "not an l-value (member access)");
2428 cgen = self->owner->codegen;
2429 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2432 if (vec->vtype != TYPE_VECTOR &&
2433 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2438 *out = ir_value_vector_member(vec, self->field);
2441 return (*out != nullptr);
2444 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2449 if (!lvalue && self->outr) {
2453 if (lvalue && self->outl) {
2458 if (!ast_istype(self->array, ast_value)) {
2459 compile_error(ast_ctx(self), "array indexing this way is not supported");
2460 /* note this would actually be pointer indexing because the left side is
2461 * not an actual array but (hopefully) an indexable expression.
2462 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2463 * support this path will be filled.
2468 arr = (ast_value*)self->array;
2469 idx = (ast_value*)self->index;
2471 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2472 /* Time to use accessor functions */
2473 ast_expression_codegen *cgen;
2474 ir_value *iridx, *funval;
2478 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2483 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2487 cgen = self->index->codegen;
2488 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2491 cgen = arr->getter->codegen;
2492 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2495 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2498 ir_call_param(call, iridx);
2500 *out = ir_call_value(call);
2502 (*out)->vtype = self->vtype;
2503 codegen_output_type(self, *out);
2507 if (idx->vtype == TYPE_FLOAT) {
2508 unsigned int arridx = idx->constval.vfloat;
2509 if (arridx >= self->array->count)
2511 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2514 *out = arr->ir_values[arridx];
2516 else if (idx->vtype == TYPE_INTEGER) {
2517 unsigned int arridx = idx->constval.vint;
2518 if (arridx >= self->array->count)
2520 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2523 *out = arr->ir_values[arridx];
2526 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2529 (*out)->vtype = self->vtype;
2530 codegen_output_type(self, *out);
2534 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2538 compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2543 compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2547 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2549 ast_expression_codegen *cgen;
2557 ir_block *ontrue_endblock = nullptr;
2558 ir_block *onfalse_endblock = nullptr;
2559 ir_block *merge = nullptr;
2562 /* We don't output any value, thus also don't care about r/lvalue */
2567 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2570 self->outr = (ir_value*)1;
2572 /* generate the condition */
2573 cgen = self->cond->codegen;
2574 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2576 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2577 cond = func->curblock;
2579 /* try constant folding away the condition */
2580 if ((folded = fold::cond_ifthen(condval, func, self)) != -1)
2583 if (self->on_true) {
2584 /* create on-true block */
2585 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2589 /* enter the block */
2590 func->curblock = ontrue;
2593 cgen = self->on_true->codegen;
2594 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2597 /* we now need to work from the current endpoint */
2598 ontrue_endblock = func->curblock;
2603 if (self->on_false) {
2604 /* create on-false block */
2605 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2609 /* enter the block */
2610 func->curblock = onfalse;
2613 cgen = self->on_false->codegen;
2614 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2617 /* we now need to work from the current endpoint */
2618 onfalse_endblock = func->curblock;
2622 /* Merge block were they all merge in to */
2623 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2625 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2628 /* add jumps ot the merge block */
2629 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2631 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2634 /* Now enter the merge block */
2635 func->curblock = merge;
2638 /* we create the if here, that way all blocks are ordered :)
2640 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2641 (ontrue ? ontrue : merge),
2642 (onfalse ? onfalse : merge)))
2650 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2652 ast_expression_codegen *cgen;
2655 ir_value *trueval, *falseval;
2658 ir_block *cond = func->curblock;
2659 ir_block *cond_out = nullptr;
2660 ir_block *ontrue, *ontrue_out = nullptr;
2661 ir_block *onfalse, *onfalse_out = nullptr;
2665 /* Ternary can never create an lvalue... */
2669 /* In theory it shouldn't be possible to pass through a node twice, but
2670 * in case we add any kind of optimization pass for the AST itself, it
2671 * may still happen, thus we remember a created ir_value and simply return one
2672 * if it already exists.
2679 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2681 /* generate the condition */
2682 func->curblock = cond;
2683 cgen = self->cond->codegen;
2684 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2686 cond_out = func->curblock;
2688 /* try constant folding away the condition */
2689 if ((folded = fold::cond_ternary(condval, func, self)) != -1)
2692 /* create on-true block */
2693 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2698 /* enter the block */
2699 func->curblock = ontrue;
2702 cgen = self->on_true->codegen;
2703 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2706 ontrue_out = func->curblock;
2709 /* create on-false block */
2710 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2715 /* enter the block */
2716 func->curblock = onfalse;
2719 cgen = self->on_false->codegen;
2720 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2723 onfalse_out = func->curblock;
2726 /* create merge block */
2727 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2730 /* jump to merge block */
2731 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2733 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2736 /* create if instruction */
2737 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2740 /* Now enter the merge block */
2741 func->curblock = merge;
2743 /* Here, now, we need a PHI node
2744 * but first some sanity checking...
2746 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2747 /* error("ternary with different types on the two sides"); */
2748 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2753 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->vtype);
2755 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2758 ir_phi_add(phi, ontrue_out, trueval);
2759 ir_phi_add(phi, onfalse_out, falseval);
2761 self->outr = ir_phi_value(phi);
2764 codegen_output_type(self, *out);
2769 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2771 ast_expression_codegen *cgen;
2773 ir_value *dummy = nullptr;
2774 ir_value *precond = nullptr;
2775 ir_value *postcond = nullptr;
2777 /* Since we insert some jumps "late" so we have blocks
2778 * ordered "nicely", we need to keep track of the actual end-blocks
2779 * of expressions to add the jumps to.
2781 ir_block *bbody = nullptr, *end_bbody = nullptr;
2782 ir_block *bprecond = nullptr, *end_bprecond = nullptr;
2783 ir_block *bpostcond = nullptr, *end_bpostcond = nullptr;
2784 ir_block *bincrement = nullptr, *end_bincrement = nullptr;
2785 ir_block *bout = nullptr, *bin = nullptr;
2787 /* let's at least move the outgoing block to the end */
2790 /* 'break' and 'continue' need to be able to find the right blocks */
2791 ir_block *bcontinue = nullptr;
2792 ir_block *bbreak = nullptr;
2794 ir_block *tmpblock = nullptr;
2800 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2803 self->outr = (ir_value*)1;
2806 * Should we ever need some kind of block ordering, better make this function
2807 * move blocks around than write a block ordering algorithm later... after all
2808 * the ast and ir should work together, not against each other.
2811 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2812 * anyway if for example it contains a ternary.
2816 cgen = self->initexpr->codegen;
2817 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2821 /* Store the block from which we enter this chaos */
2822 bin = func->curblock;
2824 /* The pre-loop condition needs its own block since we
2825 * need to be able to jump to the start of that expression.
2829 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2833 /* the pre-loop-condition the least important place to 'continue' at */
2834 bcontinue = bprecond;
2837 func->curblock = bprecond;
2840 cgen = self->precond->codegen;
2841 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2844 end_bprecond = func->curblock;
2846 bprecond = end_bprecond = nullptr;
2849 /* Now the next blocks won't be ordered nicely, but we need to
2850 * generate them this early for 'break' and 'continue'.
2852 if (self->increment) {
2853 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2856 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2858 bincrement = end_bincrement = nullptr;
2861 if (self->postcond) {
2862 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2865 bcontinue = bpostcond; /* postcond comes before the increment */
2867 bpostcond = end_bpostcond = nullptr;
2870 bout_id = func->ir_func->blocks.size();
2871 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2876 /* The loop body... */
2877 /* if (self->body) */
2879 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2884 func->curblock = bbody;
2886 func->breakblocks.push_back(bbreak);
2888 func->continueblocks.push_back(bcontinue);
2890 func->continueblocks.push_back(bbody);
2894 cgen = self->body->codegen;
2895 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2899 end_bbody = func->curblock;
2900 func->breakblocks.pop_back();
2901 func->continueblocks.pop_back();
2904 /* post-loop-condition */
2908 func->curblock = bpostcond;
2911 cgen = self->postcond->codegen;
2912 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2915 end_bpostcond = func->curblock;
2918 /* The incrementor */
2919 if (self->increment)
2922 func->curblock = bincrement;
2925 cgen = self->increment->codegen;
2926 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2929 end_bincrement = func->curblock;
2932 /* In any case now, we continue from the outgoing block */
2933 func->curblock = bout;
2935 /* Now all blocks are in place */
2936 /* From 'bin' we jump to whatever comes first */
2937 if (bprecond) tmpblock = bprecond;
2938 else tmpblock = bbody; /* can never be null */
2941 else if (bpostcond) tmpblock = bpostcond;
2942 else tmpblock = bout;
2945 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2951 ir_block *ontrue, *onfalse;
2952 ontrue = bbody; /* can never be null */
2954 /* all of this is dead code
2955 else if (bincrement) ontrue = bincrement;
2956 else ontrue = bpostcond;
2960 if (self->pre_not) {
2965 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
2972 if (bincrement) tmpblock = bincrement;
2973 else if (bpostcond) tmpblock = bpostcond;
2974 else if (bprecond) tmpblock = bprecond;
2975 else tmpblock = bbody;
2976 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
2980 /* from increment */
2983 if (bpostcond) tmpblock = bpostcond;
2984 else if (bprecond) tmpblock = bprecond;
2985 else if (bbody) tmpblock = bbody;
2986 else tmpblock = bout;
2987 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
2994 ir_block *ontrue, *onfalse;
2995 if (bprecond) ontrue = bprecond;
2996 else ontrue = bbody; /* can never be null */
2998 /* all of this is dead code
2999 else if (bincrement) ontrue = bincrement;
3000 else ontrue = bpostcond;
3004 if (self->post_not) {
3009 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
3013 /* Move 'bout' to the end */
3014 func->ir_func->blocks.erase(func->ir_func->blocks.begin() + bout_id);
3015 func->ir_func->blocks.emplace_back(bout);
3020 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
3027 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3032 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3035 self->outr = (ir_value*)1;
3037 if (self->is_continue)
3038 target = func->continueblocks[func->continueblocks.size()-1-self->levels];
3040 target = func->breakblocks[func->breakblocks.size()-1-self->levels];
3043 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3047 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3052 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3054 ast_expression_codegen *cgen;
3056 ast_switch_case *def_case = nullptr;
3057 ir_block *def_bfall = nullptr;
3058 ir_block *def_bfall_to = nullptr;
3059 bool set_def_bfall_to = false;
3061 ir_value *dummy = nullptr;
3062 ir_value *irop = nullptr;
3063 ir_block *bout = nullptr;
3064 ir_block *bfall = nullptr;
3071 compile_error(ast_ctx(self), "switch expression is not an l-value");
3076 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3079 self->outr = (ir_value*)1;
3084 cgen = self->operand->codegen;
3085 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3088 if (self->cases.empty())
3091 cmpinstr = type_eq_instr[irop->vtype];
3092 if (cmpinstr >= VINSTR_END) {
3093 ast_type_to_string(self->operand, typestr, sizeof(typestr));
3094 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3098 bout_id = func->ir_func->blocks.size();
3099 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3103 /* setup the break block */
3104 func->breakblocks.push_back(bout);
3106 /* Now create all cases */
3107 for (auto &it : self->cases) {
3108 ir_value *cond, *val;
3109 ir_block *bcase, *bnot;
3112 ast_switch_case *swcase = ⁢
3114 if (swcase->value) {
3115 /* A regular case */
3116 /* generate the condition operand */
3117 cgen = swcase->value->codegen;
3118 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3120 /* generate the condition */
3121 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3125 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3126 bnot_id = func->ir_func->blocks.size();
3127 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3128 if (!bcase || !bnot)
3130 if (set_def_bfall_to) {
3131 set_def_bfall_to = false;
3132 def_bfall_to = bcase;
3134 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3137 /* Make the previous case-end fall through */
3138 if (bfall && !bfall->final) {
3139 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3143 /* enter the case */
3144 func->curblock = bcase;
3145 cgen = swcase->code->codegen;
3146 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3149 /* remember this block to fall through from */
3150 bfall = func->curblock;
3152 /* enter the else and move it down */
3153 func->curblock = bnot;
3154 func->ir_func->blocks.erase(func->ir_func->blocks.begin() + bnot_id);
3155 func->ir_func->blocks.emplace_back(bnot);
3157 /* The default case */
3158 /* Remember where to fall through from: */
3161 /* remember which case it was */
3163 /* And the next case will be remembered */
3164 set_def_bfall_to = true;
3168 /* Jump from the last bnot to bout */
3169 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3171 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3176 /* If there was a default case, put it down here */
3180 /* No need to create an extra block */
3181 bcase = func->curblock;
3183 /* Insert the fallthrough jump */
3184 if (def_bfall && !def_bfall->final) {
3185 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3189 /* Now generate the default code */
3190 cgen = def_case->code->codegen;
3191 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3194 /* see if we need to fall through */
3195 if (def_bfall_to && !func->curblock->final)
3197 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3202 /* Jump from the last bnot to bout */
3203 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3205 /* enter the outgoing block */
3206 func->curblock = bout;
3208 /* restore the break block */
3209 func->breakblocks.pop_back();
3211 /* Move 'bout' to the end, it's nicer */
3212 func->ir_func->blocks.erase(func->ir_func->blocks.begin() + bout_id);
3213 func->ir_func->blocks.emplace_back(bout);
3218 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3222 if (self->undefined) {
3223 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3229 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3233 /* simply create a new block and jump to it */
3234 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3235 if (!self->irblock) {
3236 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3239 if (!func->curblock->final) {
3240 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3244 /* enter the new block */
3245 func->curblock = self->irblock;
3247 /* Generate all the leftover gotos */
3248 for (auto &it : self->gotos) {
3249 if (!ast_goto_codegen(it, func, false, &dummy))
3256 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3260 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3264 if (self->target->irblock) {
3265 if (self->irblock_from) {
3266 /* we already tried once, this is the callback */
3267 self->irblock_from->final = false;
3268 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3269 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3275 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3276 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3283 /* the target has not yet been created...
3284 * close this block in a sneaky way:
3286 func->curblock->final = true;
3287 self->irblock_from = func->curblock;
3288 ast_label_register_goto(self->target, self);
3295 bool ast_state_codegen(ast_state *self, ast_function *func, bool lvalue, ir_value **out)
3297 ast_expression_codegen *cgen;
3299 ir_value *frameval, *thinkval;
3302 compile_error(ast_ctx(self), "not an l-value (state operation)");
3306 compile_error(ast_ctx(self), "internal error: ast_state cannot be reused!");
3311 cgen = self->framenum->codegen;
3312 if (!(*cgen)((ast_expression*)(self->framenum), func, false, &frameval))
3317 cgen = self->nextthink->codegen;
3318 if (!(*cgen)((ast_expression*)(self->nextthink), func, false, &thinkval))
3323 if (!ir_block_create_state_op(func->curblock, ast_ctx(self), frameval, thinkval)) {
3324 compile_error(ast_ctx(self), "failed to create STATE instruction");
3328 self->outr = (ir_value*)1;
3332 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3334 ast_expression_codegen *cgen;
3335 std::vector<ir_value*> params;
3336 ir_instr *callinstr;
3338 ir_value *funval = nullptr;
3340 /* return values are never lvalues */
3342 compile_error(ast_ctx(self), "not an l-value (function call)");
3351 cgen = self->func->codegen;
3352 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3358 for (auto &it : self->params) {
3361 if (!(*cgen)(it, func, false, ¶m))
3365 params.push_back(param);
3368 /* varargs counter */
3369 if (self->va_count) {
3371 ir_builder *builder = func->curblock->owner->owner;
3372 cgen = self->va_count->codegen;
3373 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3375 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3376 ir_builder_get_va_count(builder), va_count))
3382 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3383 ast_function_label(func, "call"),
3384 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3388 for (auto &it : params)
3389 ir_call_param(callinstr, it);
3391 *out = ir_call_value(callinstr);
3394 codegen_output_type(self, *out);