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 nodetype)
73 self->destroy = &_ast_node_destroy;
75 self->nodetype = nodetype;
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->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 const ast_expression *fromex;
122 ast_expression *selfex;
123 ast_value *cp = ast_value_new(self->expression.node.context, self->name, self->expression.vtype);
124 if (self->expression.next) {
125 cp->expression.next = ast_type_copy(self->expression.node.context, self->expression.next);
127 fromex = &self->expression;
128 selfex = &cp->expression;
129 selfex->count = fromex->count;
130 selfex->flags = fromex->flags;
131 for (auto &it : fromex->params) {
132 ast_value *v = ast_value_copy(it);
133 selfex->params.push_back(v);
138 void ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
140 const ast_expression *fromex;
141 ast_expression *selfex;
142 self->vtype = other->vtype;
144 self->next = (ast_expression*)ast_type_copy(ast_ctx(self), other->next);
148 selfex->count = fromex->count;
149 selfex->flags = fromex->flags;
150 for (auto &it : fromex->params) {
151 ast_value *v = ast_value_copy(it);
152 selfex->params.push_back(v);
156 static ast_expression* ast_shallow_type(lex_ctx_t ctx, int vtype)
158 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
159 ast_expression_init(self, nullptr);
160 self->codegen = nullptr;
161 self->next = nullptr;
166 ast_expression* ast_type_copy(lex_ctx_t ctx, const ast_expression *ex)
168 const ast_expression *fromex;
169 ast_expression *selfex;
175 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
176 ast_expression_init(self, nullptr);
181 /* This may never be codegen()d */
182 selfex->codegen = nullptr;
184 selfex->vtype = fromex->vtype;
186 selfex->next = ast_type_copy(ctx, fromex->next);
188 selfex->next = nullptr;
190 selfex->count = fromex->count;
191 selfex->flags = fromex->flags;
192 for (auto &it : fromex->params) {
193 ast_value *v = ast_value_copy(it);
194 selfex->params.push_back(v);
201 bool ast_compare_type(ast_expression *a, ast_expression *b)
203 if (a->vtype == TYPE_NIL ||
204 b->vtype == TYPE_NIL)
206 if (a->vtype != b->vtype)
208 if (!a->next != !b->next)
210 if (a->params.size() != b->params.size())
212 if ((a->flags & AST_FLAG_TYPE_MASK) !=
213 (b->flags & AST_FLAG_TYPE_MASK) )
217 if (a->params.size()) {
219 for (i = 0; i < a->params.size(); ++i) {
220 if (!ast_compare_type((ast_expression*)a->params[i],
221 (ast_expression*)b->params[i]))
226 return ast_compare_type(a->next, b->next);
230 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
237 if (pos + 6 >= bufsize)
239 util_strncpy(buf + pos, "(null)", 6);
243 if (pos + 1 >= bufsize)
248 util_strncpy(buf + pos, "(variant)", 9);
253 return ast_type_to_string_impl(e->next, buf, bufsize, pos);
256 if (pos + 3 >= bufsize)
260 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
261 if (pos + 1 >= bufsize)
267 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
268 if (pos + 2 >= bufsize)
270 if (e->params.empty()) {
276 pos = ast_type_to_string_impl((ast_expression*)(e->params[0]), buf, bufsize, pos);
277 for (i = 1; i < e->params.size(); ++i) {
278 if (pos + 2 >= bufsize)
282 pos = ast_type_to_string_impl((ast_expression*)(e->params[i]), buf, bufsize, pos);
284 if (pos + 1 >= bufsize)
290 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
291 if (pos + 1 >= bufsize)
294 pos += util_snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->count);
295 if (pos + 1 >= bufsize)
301 typestr = type_name[e->vtype];
302 typelen = strlen(typestr);
303 if (pos + typelen >= bufsize)
305 util_strncpy(buf + pos, typestr, typelen);
306 return pos + typelen;
310 buf[bufsize-3] = '.';
311 buf[bufsize-2] = '.';
312 buf[bufsize-1] = '.';
316 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
318 size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
322 static bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out);
323 ast_value* ast_value_new(lex_ctx_t ctx, const char *name, int t)
325 ast_instantiate(ast_value, ctx, ast_value_delete);
326 ast_expression_init((ast_expression*)self,
327 (ast_expression_codegen*)&ast_value_codegen);
328 self->expression.node.keep = true; /* keep */
330 self->name = name ? util_strdup(name) : nullptr;
331 self->expression.vtype = t;
332 self->expression.next = nullptr;
333 self->isfield = false;
335 self->hasvalue = false;
337 self->inexact = false;
339 memset(&self->constval, 0, sizeof(self->constval));
341 self->ir_v = nullptr;
342 self->ir_values = nullptr;
343 self->ir_value_count = 0;
345 self->setter = nullptr;
346 self->getter = nullptr;
347 self->desc = nullptr;
349 self->argcounter = nullptr;
350 self->intrinsic = false;
355 void ast_value_delete(ast_value* self)
358 mem_d((void*)self->name);
359 if (self->argcounter)
360 mem_d((void*)self->argcounter);
361 if (self->hasvalue) {
362 switch (self->expression.vtype)
365 mem_d((void*)self->constval.vstring);
368 /* unlink us from the function node */
369 self->constval.vfunc->vtype = nullptr;
371 /* NOTE: delete function? currently collected in
372 * the parser structure
379 mem_d(self->ir_values);
384 // initlist imples an array which implies .next in the expression exists.
385 if (self->initlist.size() && self->expression.next->vtype == TYPE_STRING) {
386 for (auto &it : self->initlist)
391 ast_expression_delete((ast_expression*)self);
395 void ast_value_params_add(ast_value *self, ast_value *p)
397 self->expression.params.push_back(p);
400 bool ast_value_set_name(ast_value *self, const char *name)
403 mem_d((void*)self->name);
404 self->name = util_strdup(name);
408 ast_binary* ast_binary_new(lex_ctx_t ctx, int op,
409 ast_expression* left, ast_expression* right)
411 ast_instantiate(ast_binary, ctx, ast_binary_delete);
412 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
414 if (ast_istype(right, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
415 ast_unary *unary = ((ast_unary*)right);
416 ast_expression *normal = unary->operand;
418 /* make a-(-b) => a + b */
419 if (unary->op == VINSTR_NEG_F || unary->op == VINSTR_NEG_V) {
420 if (op == INSTR_SUB_F) {
423 ++opts_optimizationcount[OPTIM_PEEPHOLE];
424 } else if (op == INSTR_SUB_V) {
427 ++opts_optimizationcount[OPTIM_PEEPHOLE];
435 self->right_first = false;
437 ast_propagate_effects(self, left);
438 ast_propagate_effects(self, right);
440 if (op >= INSTR_EQ_F && op <= INSTR_GT)
441 self->expression.vtype = TYPE_FLOAT;
442 else if (op == INSTR_AND || op == INSTR_OR) {
443 if (OPTS_FLAG(PERL_LOGIC))
444 ast_type_adopt(self, right);
446 self->expression.vtype = TYPE_FLOAT;
448 else if (op == INSTR_BITAND || op == INSTR_BITOR)
449 self->expression.vtype = TYPE_FLOAT;
450 else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
451 self->expression.vtype = TYPE_VECTOR;
452 else if (op == INSTR_MUL_V)
453 self->expression.vtype = TYPE_FLOAT;
455 self->expression.vtype = left->vtype;
458 self->refs = AST_REF_ALL;
463 void ast_binary_delete(ast_binary *self)
465 if (self->refs & AST_REF_LEFT) ast_unref(self->left);
466 if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
468 ast_expression_delete((ast_expression*)self);
472 ast_binstore* ast_binstore_new(lex_ctx_t ctx, int storop, int op,
473 ast_expression* left, ast_expression* right)
475 ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
476 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
478 ast_side_effects(self) = true;
480 self->opstore = storop;
483 self->source = right;
485 self->keep_dest = false;
487 ast_type_adopt(self, left);
491 void ast_binstore_delete(ast_binstore *self)
493 if (!self->keep_dest)
494 ast_unref(self->dest);
495 ast_unref(self->source);
496 ast_expression_delete((ast_expression*)self);
500 ast_unary* ast_unary_new(lex_ctx_t ctx, int op,
501 ast_expression *expr)
503 ast_instantiate(ast_unary, ctx, ast_unary_delete);
504 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
507 self->operand = expr;
510 if (ast_istype(expr, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
511 ast_unary *prev = (ast_unary*)((ast_unary*)expr)->operand;
513 /* Handle for double negation */
514 if (((ast_unary*)expr)->op == op)
515 prev = (ast_unary*)((ast_unary*)expr)->operand;
517 if (ast_istype(prev, ast_unary)) {
518 ast_expression_delete((ast_expression*)self);
520 ++opts_optimizationcount[OPTIM_PEEPHOLE];
525 ast_propagate_effects(self, expr);
527 if ((op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) || op == VINSTR_NEG_F) {
528 self->expression.vtype = TYPE_FLOAT;
529 } else if (op == VINSTR_NEG_V) {
530 self->expression.vtype = TYPE_VECTOR;
532 compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
538 void ast_unary_delete(ast_unary *self)
540 if (self->operand) ast_unref(self->operand);
541 ast_expression_delete((ast_expression*)self);
545 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
547 ast_instantiate(ast_return, ctx, ast_return_delete);
548 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
550 self->operand = expr;
553 ast_propagate_effects(self, expr);
558 void ast_return_delete(ast_return *self)
561 ast_unref(self->operand);
562 ast_expression_delete((ast_expression*)self);
566 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
568 if (field->vtype != TYPE_FIELD) {
569 compile_error(ctx, "ast_entfield_new with expression not of type field");
572 return ast_entfield_new_force(ctx, entity, field, field->next);
575 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
577 ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
581 /* Error: field has no type... */
585 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
587 self->entity = entity;
589 ast_propagate_effects(self, entity);
590 ast_propagate_effects(self, field);
592 ast_type_adopt(self, outtype);
596 void ast_entfield_delete(ast_entfield *self)
598 ast_unref(self->entity);
599 ast_unref(self->field);
600 ast_expression_delete((ast_expression*)self);
604 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
606 ast_instantiate(ast_member, ctx, ast_member_delete);
612 if (owner->vtype != TYPE_VECTOR &&
613 owner->vtype != TYPE_FIELD) {
614 compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
619 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
620 self->expression.node.keep = true; /* keep */
622 if (owner->vtype == TYPE_VECTOR) {
623 self->expression.vtype = TYPE_FLOAT;
624 self->expression.next = nullptr;
626 self->expression.vtype = TYPE_FIELD;
627 self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
630 self->rvalue = false;
632 ast_propagate_effects(self, owner);
636 self->name = util_strdup(name);
638 self->name = nullptr;
643 void ast_member_delete(ast_member *self)
645 /* The owner is always an ast_value, which has .keep=true,
646 * also: ast_members are usually deleted after the owner, thus
647 * this will cause invalid access
648 ast_unref(self->owner);
649 * once we allow (expression).x to access a vector-member, we need
650 * to change this: preferably by creating an alternate ast node for this
651 * purpose that is not garbage-collected.
653 ast_expression_delete((ast_expression*)self);
658 bool ast_member_set_name(ast_member *self, const char *name)
661 mem_d((void*)self->name);
662 self->name = util_strdup(name);
666 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
668 ast_expression *outtype;
669 ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
671 outtype = array->next;
674 /* Error: field has no type... */
678 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
682 ast_propagate_effects(self, array);
683 ast_propagate_effects(self, index);
685 ast_type_adopt(self, outtype);
686 if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
687 if (self->expression.vtype != TYPE_ARRAY) {
688 compile_error(ast_ctx(self), "array_index node on type");
689 ast_array_index_delete(self);
692 self->array = outtype;
693 self->expression.vtype = TYPE_FIELD;
699 void ast_array_index_delete(ast_array_index *self)
702 ast_unref(self->array);
704 ast_unref(self->index);
705 ast_expression_delete((ast_expression*)self);
709 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
711 ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete);
712 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
714 self->expression.vtype = TYPE_NOEXPR;
718 void ast_argpipe_delete(ast_argpipe *self)
721 ast_unref(self->index);
722 ast_expression_delete((ast_expression*)self);
726 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
728 ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
729 if (!ontrue && !onfalse) {
730 /* because it is invalid */
734 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
737 self->on_true = ontrue;
738 self->on_false = onfalse;
739 ast_propagate_effects(self, cond);
741 ast_propagate_effects(self, ontrue);
743 ast_propagate_effects(self, onfalse);
748 void ast_ifthen_delete(ast_ifthen *self)
750 ast_unref(self->cond);
752 ast_unref(self->on_true);
754 ast_unref(self->on_false);
755 ast_expression_delete((ast_expression*)self);
759 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
761 ast_expression *exprtype = ontrue;
762 ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
763 /* This time NEITHER must be nullptr */
764 if (!ontrue || !onfalse) {
768 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
771 self->on_true = ontrue;
772 self->on_false = onfalse;
773 ast_propagate_effects(self, cond);
774 ast_propagate_effects(self, ontrue);
775 ast_propagate_effects(self, onfalse);
777 if (ontrue->vtype == TYPE_NIL)
779 ast_type_adopt(self, exprtype);
784 void ast_ternary_delete(ast_ternary *self)
786 /* the if()s are only there because computed-gotos can set them
789 if (self->cond) ast_unref(self->cond);
790 if (self->on_true) ast_unref(self->on_true);
791 if (self->on_false) ast_unref(self->on_false);
792 ast_expression_delete((ast_expression*)self);
796 ast_loop* ast_loop_new(lex_ctx_t ctx,
797 ast_expression *initexpr,
798 ast_expression *precond, bool pre_not,
799 ast_expression *postcond, bool post_not,
800 ast_expression *increment,
801 ast_expression *body)
803 ast_instantiate(ast_loop, ctx, ast_loop_delete);
804 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
806 self->initexpr = initexpr;
807 self->precond = precond;
808 self->postcond = postcond;
809 self->increment = increment;
812 self->pre_not = pre_not;
813 self->post_not = post_not;
816 ast_propagate_effects(self, initexpr);
818 ast_propagate_effects(self, precond);
820 ast_propagate_effects(self, postcond);
822 ast_propagate_effects(self, increment);
824 ast_propagate_effects(self, body);
829 void ast_loop_delete(ast_loop *self)
832 ast_unref(self->initexpr);
834 ast_unref(self->precond);
836 ast_unref(self->postcond);
838 ast_unref(self->increment);
840 ast_unref(self->body);
841 ast_expression_delete((ast_expression*)self);
845 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
847 ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
848 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
850 self->is_continue = iscont;
851 self->levels = levels;
856 void ast_breakcont_delete(ast_breakcont *self)
858 ast_expression_delete((ast_expression*)self);
862 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
864 ast_instantiate(ast_switch, ctx, ast_switch_delete);
865 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
869 ast_propagate_effects(self, op);
874 void ast_switch_delete(ast_switch *self)
876 ast_unref(self->operand);
878 for (auto &it : self->cases) {
884 ast_expression_delete((ast_expression*)self);
888 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
890 ast_instantiate(ast_label, ctx, ast_label_delete);
891 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
893 self->expression.vtype = TYPE_NOEXPR;
895 self->name = util_strdup(name);
896 self->irblock = nullptr;
897 self->undefined = undefined;
902 void ast_label_delete(ast_label *self)
904 mem_d((void*)self->name);
905 ast_expression_delete((ast_expression*)self);
909 static void ast_label_register_goto(ast_label *self, ast_goto *g)
911 self->gotos.push_back(g);
914 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
916 ast_instantiate(ast_goto, ctx, ast_goto_delete);
917 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
919 self->name = util_strdup(name);
920 self->target = nullptr;
921 self->irblock_from = nullptr;
926 void ast_goto_delete(ast_goto *self)
928 mem_d((void*)self->name);
929 ast_expression_delete((ast_expression*)self);
933 void ast_goto_set_label(ast_goto *self, ast_label *label)
935 self->target = label;
938 ast_state* ast_state_new(lex_ctx_t ctx, ast_expression *frame, ast_expression *think)
940 ast_instantiate(ast_state, ctx, ast_state_delete);
941 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_state_codegen);
942 self->framenum = frame;
943 self->nextthink = think;
947 void ast_state_delete(ast_state *self)
950 ast_unref(self->framenum);
952 ast_unref(self->nextthink);
954 ast_expression_delete((ast_expression*)self);
958 ast_call* ast_call_new(lex_ctx_t ctx,
959 ast_expression *funcexpr)
961 ast_instantiate(ast_call, ctx, ast_call_delete);
962 if (!funcexpr->next) {
963 compile_error(ctx, "not a function");
967 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
969 ast_side_effects(self) = true;
971 self->func = funcexpr;
972 self->va_count = nullptr;
974 ast_type_adopt(self, funcexpr->next);
979 void ast_call_delete(ast_call *self)
981 for (auto &it : self->params)
985 ast_unref(self->func);
988 ast_unref(self->va_count);
990 ast_expression_delete((ast_expression*)self);
994 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
1000 if (!va_type || !ast_compare_type(va_type, exp_type))
1002 if (va_type && exp_type)
1004 ast_type_to_string(va_type, tgot, sizeof(tgot));
1005 ast_type_to_string(exp_type, texp, sizeof(texp));
1006 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1007 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1008 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1012 compile_error(ast_ctx(self),
1013 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1020 ast_type_to_string(exp_type, texp, sizeof(texp));
1021 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1022 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1023 "piped variadic argument may differ in type: expected type %s",
1027 compile_error(ast_ctx(self),
1028 "piped variadic argument may differ in type: expected type %s",
1037 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1043 const ast_expression *func = self->func;
1044 size_t count = self->params.size();
1045 if (count > func->params.size())
1046 count = func->params.size();
1048 for (i = 0; i < count; ++i) {
1049 if (ast_istype(self->params[i], ast_argpipe)) {
1050 /* warn about type safety instead */
1052 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1055 if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->params[i]))
1058 else if (!ast_compare_type(self->params[i], (ast_expression*)(func->params[i])))
1060 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1061 ast_type_to_string((ast_expression*)func->params[i], texp, sizeof(texp));
1062 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1063 (unsigned int)(i+1), texp, tgot);
1064 /* we don't immediately return */
1068 count = self->params.size();
1069 if (count > func->params.size() && func->varparam) {
1070 for (; i < count; ++i) {
1071 if (ast_istype(self->params[i], ast_argpipe)) {
1072 /* warn about type safety instead */
1074 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1077 if (!ast_call_check_vararg(self, va_type, func->varparam))
1080 else if (!ast_compare_type(self->params[i], func->varparam))
1082 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1083 ast_type_to_string(func->varparam, texp, sizeof(texp));
1084 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1085 (unsigned int)(i+1), texp, tgot);
1086 /* we don't immediately return */
1094 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1095 ast_expression *dest, ast_expression *source)
1097 ast_instantiate(ast_store, ctx, ast_store_delete);
1098 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1100 ast_side_effects(self) = true;
1104 self->source = source;
1106 ast_type_adopt(self, dest);
1111 void ast_store_delete(ast_store *self)
1113 ast_unref(self->dest);
1114 ast_unref(self->source);
1115 ast_expression_delete((ast_expression*)self);
1119 ast_block* ast_block_new(lex_ctx_t ctx)
1121 ast_instantiate(ast_block, ctx, ast_block_delete);
1122 ast_expression_init((ast_expression*)self,
1123 (ast_expression_codegen*)&ast_block_codegen);
1127 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1129 ast_propagate_effects(self, e);
1130 self->exprs.push_back(e);
1131 if (self->expression.next) {
1132 ast_delete(self->expression.next);
1133 self->expression.next = nullptr;
1135 ast_type_adopt(self, e);
1139 void ast_block_collect(ast_block *self, ast_expression *expr)
1141 self->collect.push_back(expr);
1142 expr->node.keep = true;
1145 void ast_block_delete(ast_block *self)
1147 for (auto &it : self->exprs) ast_unref(it);
1148 for (auto &it : self->locals) ast_delete(it);
1149 for (auto &it : self->collect) ast_delete(it);
1150 ast_expression_delete((ast_expression*)self);
1154 void ast_block_set_type(ast_block *self, ast_expression *from)
1156 if (self->expression.next)
1157 ast_delete(self->expression.next);
1158 ast_type_adopt(self, from);
1161 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1163 ast_instantiate(ast_function, ctx, ast_function_delete);
1166 compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1168 } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1169 compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1171 (int)vtype->hasvalue,
1172 vtype->expression.vtype);
1176 self->vtype = vtype;
1177 self->name = name ? util_strdup(name) : nullptr;
1179 self->labelcount = 0;
1182 self->ir_func = nullptr;
1183 self->curblock = nullptr;
1185 vtype->hasvalue = true;
1186 vtype->constval.vfunc = self;
1188 self->varargs = nullptr;
1189 self->argc = nullptr;
1190 self->fixedparams = nullptr;
1191 self->return_value = nullptr;
1192 self->static_count = 0;
1201 void ast_function_delete(ast_function *self)
1204 mem_d((void*)self->name);
1206 /* ast_value_delete(self->vtype); */
1207 self->vtype->hasvalue = false;
1208 self->vtype->constval.vfunc = nullptr;
1209 /* We use unref - if it was stored in a global table it is supposed
1210 * to be deleted from *there*
1212 ast_unref(self->vtype);
1214 for (auto &it : self->static_names)
1216 for (auto &it : self->blocks)
1219 ast_delete(self->varargs);
1221 ast_delete(self->argc);
1222 if (self->fixedparams)
1223 ast_unref(self->fixedparams);
1224 if (self->return_value)
1225 ast_unref(self->return_value);
1229 const char* ast_function_label(ast_function *self, const char *prefix)
1235 if (!OPTS_OPTION_BOOL(OPTION_DUMP) &&
1236 !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1237 !OPTS_OPTION_BOOL(OPTION_DEBUG))
1242 id = (self->labelcount++);
1243 len = strlen(prefix);
1245 from = self->labelbuf + sizeof(self->labelbuf)-1;
1248 *from-- = (id%10) + '0';
1252 memcpy(from - len, prefix, len);
1256 /*********************************************************************/
1258 * by convention you must never pass nullptr to the 'ir_value **out'
1259 * parameter. If you really don't care about the output, pass a dummy.
1260 * But I can't imagine a pituation where the output is truly unnecessary.
1263 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1265 if (out->vtype == TYPE_FIELD)
1266 out->fieldtype = self->next->vtype;
1267 if (out->vtype == TYPE_FUNCTION)
1268 out->outtype = self->next->vtype;
1271 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1273 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1277 if (self->expression.vtype == TYPE_NIL) {
1278 *out = func->ir_func->owner->nil;
1281 /* NOTE: This is the codegen for a variable used in an expression.
1282 * It is not the codegen to generate the value. For this purpose,
1283 * ast_local_codegen and ast_global_codegen are to be used before this
1284 * is executed. ast_function_codegen should take care of its locals,
1285 * and the ast-user should take care of ast_global_codegen to be used
1286 * on all the globals.
1289 char tname[1024]; /* typename is reserved in C++ */
1290 ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1291 compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1298 static bool ast_global_array_set(ast_value *self)
1300 size_t count = self->initlist.size();
1303 if (count > self->expression.count) {
1304 compile_error(ast_ctx(self), "too many elements in initializer");
1305 count = self->expression.count;
1307 else if (count < self->expression.count) {
1309 compile_warning(ast_ctx(self), "not all elements are initialized");
1313 for (i = 0; i != count; ++i) {
1314 switch (self->expression.next->vtype) {
1316 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1320 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1324 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1328 /* we don't support them in any other place yet either */
1329 compile_error(ast_ctx(self), "TODO: nested arrays");
1332 /* this requiers a bit more work - similar to the fields I suppose */
1333 compile_error(ast_ctx(self), "global of type function not properly generated");
1336 if (!self->initlist[i].vfield) {
1337 compile_error(ast_ctx(self), "field constant without vfield set");
1340 if (!self->initlist[i].vfield->ir_v) {
1341 compile_error(ast_ctx(self), "field constant generated before its field");
1344 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1348 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1355 static bool check_array(ast_value *self, ast_value *array)
1357 if (array->expression.flags & AST_FLAG_ARRAY_INIT && array->initlist.empty()) {
1358 compile_error(ast_ctx(self), "array without size: %s", self->name);
1361 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1362 if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1363 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1369 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1371 ir_value *v = nullptr;
1373 if (self->expression.vtype == TYPE_NIL) {
1374 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1378 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1380 ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1383 func->context = ast_ctx(self);
1384 func->value->context = ast_ctx(self);
1386 self->constval.vfunc->ir_func = func;
1387 self->ir_v = func->value;
1388 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1389 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1390 if (self->expression.flags & AST_FLAG_ERASEABLE)
1391 self->ir_v->flags |= IR_FLAG_ERASABLE;
1392 if (self->expression.flags & AST_FLAG_BLOCK_COVERAGE)
1393 func->flags |= IR_FLAG_BLOCK_COVERAGE;
1394 /* The function is filled later on ast_function_codegen... */
1398 if (isfield && self->expression.vtype == TYPE_FIELD) {
1399 ast_expression *fieldtype = self->expression.next;
1401 if (self->hasvalue) {
1402 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1406 if (fieldtype->vtype == TYPE_ARRAY) {
1411 ast_expression *elemtype;
1413 ast_value *array = (ast_value*)fieldtype;
1415 if (!ast_istype(fieldtype, ast_value)) {
1416 compile_error(ast_ctx(self), "internal error: ast_value required");
1420 if (!check_array(self, array))
1423 elemtype = array->expression.next;
1424 vtype = elemtype->vtype;
1426 v = ir_builder_create_field(ir, self->name, vtype);
1428 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1431 v->context = ast_ctx(self);
1432 v->unique_life = true;
1434 array->ir_v = self->ir_v = v;
1436 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1437 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1438 if (self->expression.flags & AST_FLAG_ERASEABLE)
1439 self->ir_v->flags |= IR_FLAG_ERASABLE;
1441 namelen = strlen(self->name);
1442 name = (char*)mem_a(namelen + 16);
1443 util_strncpy(name, self->name, namelen);
1445 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1446 array->ir_values[0] = v;
1447 for (ai = 1; ai < array->expression.count; ++ai) {
1448 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1449 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1450 if (!array->ir_values[ai]) {
1452 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1455 array->ir_values[ai]->context = ast_ctx(self);
1456 array->ir_values[ai]->unique_life = true;
1457 array->ir_values[ai]->locked = true;
1458 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1459 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1465 v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1468 v->context = ast_ctx(self);
1470 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1471 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1473 if (self->expression.flags & AST_FLAG_ERASEABLE)
1474 self->ir_v->flags |= IR_FLAG_ERASABLE;
1479 if (self->expression.vtype == TYPE_ARRAY) {
1484 ast_expression *elemtype = self->expression.next;
1485 int vtype = elemtype->vtype;
1487 if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1488 compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1492 /* same as with field arrays */
1493 if (!check_array(self, self))
1496 v = ir_builder_create_global(ir, self->name, vtype);
1498 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1501 v->context = ast_ctx(self);
1502 v->unique_life = true;
1505 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1506 v->flags |= IR_FLAG_INCLUDE_DEF;
1507 if (self->expression.flags & AST_FLAG_ERASEABLE)
1508 self->ir_v->flags |= IR_FLAG_ERASABLE;
1510 namelen = strlen(self->name);
1511 name = (char*)mem_a(namelen + 16);
1512 util_strncpy(name, self->name, namelen);
1514 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1515 self->ir_values[0] = v;
1516 for (ai = 1; ai < self->expression.count; ++ai) {
1517 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1518 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1519 if (!self->ir_values[ai]) {
1521 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1524 self->ir_values[ai]->context = ast_ctx(self);
1525 self->ir_values[ai]->unique_life = true;
1526 self->ir_values[ai]->locked = true;
1527 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1528 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1534 /* Arrays don't do this since there's no "array" value which spans across the
1537 v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1539 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1542 codegen_output_type(self, v);
1543 v->context = ast_ctx(self);
1546 /* link us to the ir_value */
1550 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1551 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1552 if (self->expression.flags & AST_FLAG_ERASEABLE)
1553 self->ir_v->flags |= IR_FLAG_ERASABLE;
1556 if (self->hasvalue) {
1557 switch (self->expression.vtype)
1560 if (!ir_value_set_float(v, self->constval.vfloat))
1564 if (!ir_value_set_vector(v, self->constval.vvec))
1568 if (!ir_value_set_string(v, self->constval.vstring))
1572 ast_global_array_set(self);
1575 compile_error(ast_ctx(self), "global of type function not properly generated");
1577 /* Cannot generate an IR value for a function,
1578 * need a pointer pointing to a function rather.
1581 if (!self->constval.vfield) {
1582 compile_error(ast_ctx(self), "field constant without vfield set");
1585 if (!self->constval.vfield->ir_v) {
1586 compile_error(ast_ctx(self), "field constant generated before its field");
1589 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1593 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1599 error: /* clean up */
1600 if(v) ir_value_delete(v);
1604 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1606 ir_value *v = nullptr;
1608 if (self->expression.vtype == TYPE_NIL) {
1609 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1613 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1615 /* Do we allow local functions? I think not...
1616 * this is NOT a function pointer atm.
1621 if (self->expression.vtype == TYPE_ARRAY) {
1626 ast_expression *elemtype = self->expression.next;
1627 int vtype = elemtype->vtype;
1629 func->flags |= IR_FLAG_HAS_ARRAYS;
1631 if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1632 compile_error(ast_ctx(self), "array-parameters are not supported");
1636 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1637 if (!check_array(self, self))
1640 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1641 if (!self->ir_values) {
1642 compile_error(ast_ctx(self), "failed to allocate array values");
1646 v = ir_function_create_local(func, self->name, vtype, param);
1648 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1651 v->context = ast_ctx(self);
1652 v->unique_life = true;
1655 namelen = strlen(self->name);
1656 name = (char*)mem_a(namelen + 16);
1657 util_strncpy(name, self->name, namelen);
1659 self->ir_values[0] = v;
1660 for (ai = 1; ai < self->expression.count; ++ai) {
1661 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1662 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1663 if (!self->ir_values[ai]) {
1664 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1667 self->ir_values[ai]->context = ast_ctx(self);
1668 self->ir_values[ai]->unique_life = true;
1669 self->ir_values[ai]->locked = true;
1675 v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1678 codegen_output_type(self, v);
1679 v->context = ast_ctx(self);
1682 /* A constant local... hmmm...
1683 * I suppose the IR will have to deal with this
1685 if (self->hasvalue) {
1686 switch (self->expression.vtype)
1689 if (!ir_value_set_float(v, self->constval.vfloat))
1693 if (!ir_value_set_vector(v, self->constval.vvec))
1697 if (!ir_value_set_string(v, self->constval.vstring))
1701 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1706 /* link us to the ir_value */
1710 if (!ast_generate_accessors(self, func->owner))
1714 error: /* clean up */
1719 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1722 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1723 if (!self->setter || !self->getter)
1725 for (i = 0; i < self->expression.count; ++i) {
1726 if (!self->ir_values) {
1727 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1730 if (!self->ir_values[i]) {
1731 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1734 if (self->ir_values[i]->life) {
1735 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1740 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1742 if (!ast_global_codegen (self->setter, ir, false) ||
1743 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1744 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1746 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1747 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1752 if (!ast_global_codegen (self->getter, ir, false) ||
1753 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1754 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1756 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1757 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1761 for (i = 0; i < self->expression.count; ++i) {
1762 vec_free(self->ir_values[i]->life);
1764 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1768 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1773 ast_expression_codegen *cgen;
1777 irf = self->ir_func;
1779 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1783 /* fill the parameter list */
1784 ec = &self->vtype->expression;
1785 for (auto &it : ec->params) {
1786 if (it->expression.vtype == TYPE_FIELD)
1787 vec_push(irf->params, it->expression.next->vtype);
1789 vec_push(irf->params, it->expression.vtype);
1790 if (!self->builtin) {
1791 if (!ast_local_codegen(it, self->ir_func, true))
1796 if (self->varargs) {
1797 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1799 irf->max_varargs = self->varargs->expression.count;
1802 if (self->builtin) {
1803 irf->builtin = self->builtin;
1807 /* have a local return value variable? */
1808 if (self->return_value) {
1809 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1813 if (self->blocks.empty()) {
1814 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1818 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1819 if (!self->curblock) {
1820 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1828 if (!ast_local_codegen(self->argc, self->ir_func, true))
1830 cgen = self->argc->expression.codegen;
1831 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1833 cgen = self->fixedparams->expression.codegen;
1834 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1836 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1837 ast_function_label(self, "va_count"), INSTR_SUB_F,
1838 ir_builder_get_va_count(ir), fixed);
1841 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1848 for (auto &it : self->blocks) {
1849 cgen = it->expression.codegen;
1850 if (!(*cgen)((ast_expression*)it, self, false, &dummy))
1854 /* TODO: check return types */
1855 if (!self->curblock->final)
1857 if (!self->vtype->expression.next ||
1858 self->vtype->expression.next->vtype == TYPE_VOID)
1860 return ir_block_create_return(self->curblock, ast_ctx(self), nullptr);
1862 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1864 if (self->return_value) {
1865 cgen = self->return_value->expression.codegen;
1866 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1868 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1870 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1871 "control reaches end of non-void function (`%s`) via %s",
1872 self->name, self->curblock->label))
1876 return ir_block_create_return(self->curblock, ast_ctx(self), nullptr);
1882 static bool starts_a_label(ast_expression *ex)
1884 while (ex && ast_istype(ex, ast_block)) {
1885 ast_block *b = (ast_block*)ex;
1890 return ast_istype(ex, ast_label);
1893 /* Note, you will not see ast_block_codegen generate ir_blocks.
1894 * To the AST and the IR, blocks are 2 different things.
1895 * In the AST it represents a block of code, usually enclosed in
1896 * curly braces {...}.
1897 * While in the IR it represents a block in terms of control-flow.
1899 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1901 /* We don't use this
1902 * Note: an ast-representation using the comma-operator
1903 * of the form: (a, b, c) = x should not assign to c...
1906 compile_error(ast_ctx(self), "not an l-value (code-block)");
1910 if (self->expression.outr) {
1911 *out = self->expression.outr;
1915 /* output is nullptr at first, we'll have each expression
1916 * assign to out output, thus, a comma-operator represention
1917 * using an ast_block will return the last generated value,
1918 * so: (b, c) + a executed both b and c, and returns c,
1919 * which is then added to a.
1923 /* generate locals */
1924 for (auto &it : self->locals) {
1925 if (!ast_local_codegen(it, func->ir_func, false)) {
1926 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1927 compile_error(ast_ctx(self), "failed to generate local `%s`", it->name);
1932 for (auto &it : self->exprs) {
1933 ast_expression_codegen *gen;
1934 if (func->curblock->final && !starts_a_label(it)) {
1935 if (compile_warning(ast_ctx(it), WARN_UNREACHABLE_CODE, "unreachable statement"))
1940 if (!(*gen)(it, func, false, out))
1944 self->expression.outr = *out;
1949 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
1951 ast_expression_codegen *cgen;
1952 ir_value *left = nullptr;
1953 ir_value *right = nullptr;
1957 ast_array_index *ai = nullptr;
1959 if (lvalue && self->expression.outl) {
1960 *out = self->expression.outl;
1964 if (!lvalue && self->expression.outr) {
1965 *out = self->expression.outr;
1969 if (ast_istype(self->dest, ast_array_index))
1972 ai = (ast_array_index*)self->dest;
1973 idx = (ast_value*)ai->index;
1975 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
1980 /* we need to call the setter */
1981 ir_value *iridx, *funval;
1985 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
1989 arr = (ast_value*)ai->array;
1990 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
1991 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
1995 cgen = idx->expression.codegen;
1996 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
1999 cgen = arr->setter->expression.codegen;
2000 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2003 cgen = self->source->codegen;
2004 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2007 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2010 ir_call_param(call, iridx);
2011 ir_call_param(call, right);
2012 self->expression.outr = right;
2018 cgen = self->dest->codegen;
2020 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
2022 self->expression.outl = left;
2024 cgen = self->source->codegen;
2026 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2029 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2031 self->expression.outr = right;
2034 /* Theoretically, an assinment returns its left side as an
2035 * lvalue, if we don't need an lvalue though, we return
2036 * the right side as an rvalue, otherwise we have to
2037 * somehow know whether or not we need to dereference the pointer
2038 * on the left side - that is: OP_LOAD if it was an address.
2039 * Also: in original QC we cannot OP_LOADP *anyway*.
2041 *out = (lvalue ? left : right);
2046 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2048 ast_expression_codegen *cgen;
2049 ir_value *left, *right;
2051 /* A binary operation cannot yield an l-value */
2053 compile_error(ast_ctx(self), "not an l-value (binop)");
2057 if (self->expression.outr) {
2058 *out = self->expression.outr;
2062 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2063 (self->op == INSTR_AND || self->op == INSTR_OR))
2065 /* NOTE: The short-logic path will ignore right_first */
2067 /* short circuit evaluation */
2068 ir_block *other, *merge;
2069 ir_block *from_left, *from_right;
2073 /* prepare end-block */
2074 merge_id = vec_size(func->ir_func->blocks);
2075 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2077 /* generate the left expression */
2078 cgen = self->left->codegen;
2079 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2081 /* remember the block */
2082 from_left = func->curblock;
2084 /* create a new block for the right expression */
2085 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2086 if (self->op == INSTR_AND) {
2087 /* on AND: left==true -> other */
2088 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2091 /* on OR: left==false -> other */
2092 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2095 /* use the likely flag */
2096 vec_last(func->curblock->instr)->likely = true;
2098 /* enter the right-expression's block */
2099 func->curblock = other;
2101 cgen = self->right->codegen;
2102 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2104 /* remember block */
2105 from_right = func->curblock;
2107 /* jump to the merge block */
2108 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2111 vec_remove(func->ir_func->blocks, merge_id, 1);
2112 vec_push(func->ir_func->blocks, merge);
2114 func->curblock = merge;
2115 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2116 ast_function_label(func, "sce_value"),
2117 self->expression.vtype);
2118 ir_phi_add(phi, from_left, left);
2119 ir_phi_add(phi, from_right, right);
2120 *out = ir_phi_value(phi);
2124 if (!OPTS_FLAG(PERL_LOGIC)) {
2126 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2127 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2128 ast_function_label(func, "sce_bool_v"),
2132 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2133 ast_function_label(func, "sce_bool"),
2138 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2139 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2140 ast_function_label(func, "sce_bool_s"),
2144 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2145 ast_function_label(func, "sce_bool"),
2151 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2152 ast_function_label(func, "sce_bool"),
2153 INSTR_AND, *out, *out);
2159 self->expression.outr = *out;
2160 codegen_output_type(self, *out);
2164 if (self->right_first) {
2165 cgen = self->right->codegen;
2166 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2168 cgen = self->left->codegen;
2169 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2172 cgen = self->left->codegen;
2173 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2175 cgen = self->right->codegen;
2176 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2180 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2181 self->op, left, right);
2184 self->expression.outr = *out;
2185 codegen_output_type(self, *out);
2190 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2192 ast_expression_codegen *cgen;
2193 ir_value *leftl = nullptr, *leftr, *right, *bin;
2197 ast_array_index *ai = nullptr;
2198 ir_value *iridx = nullptr;
2200 if (lvalue && self->expression.outl) {
2201 *out = self->expression.outl;
2205 if (!lvalue && self->expression.outr) {
2206 *out = self->expression.outr;
2210 if (ast_istype(self->dest, ast_array_index))
2213 ai = (ast_array_index*)self->dest;
2214 idx = (ast_value*)ai->index;
2216 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2220 /* for a binstore we need both an lvalue and an rvalue for the left side */
2221 /* rvalue of destination! */
2223 cgen = idx->expression.codegen;
2224 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2227 cgen = self->dest->codegen;
2228 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2231 /* source as rvalue only */
2232 cgen = self->source->codegen;
2233 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2236 /* now the binary */
2237 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2238 self->opbin, leftr, right);
2239 self->expression.outr = bin;
2243 /* we need to call the setter */
2248 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2252 arr = (ast_value*)ai->array;
2253 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2254 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2258 cgen = arr->setter->expression.codegen;
2259 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2262 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2265 ir_call_param(call, iridx);
2266 ir_call_param(call, bin);
2267 self->expression.outr = bin;
2269 /* now store them */
2270 cgen = self->dest->codegen;
2271 /* lvalue of destination */
2272 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2274 self->expression.outl = leftl;
2276 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2278 self->expression.outr = bin;
2281 /* Theoretically, an assinment returns its left side as an
2282 * lvalue, if we don't need an lvalue though, we return
2283 * the right side as an rvalue, otherwise we have to
2284 * somehow know whether or not we need to dereference the pointer
2285 * on the left side - that is: OP_LOAD if it was an address.
2286 * Also: in original QC we cannot OP_LOADP *anyway*.
2288 *out = (lvalue ? leftl : bin);
2293 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2295 ast_expression_codegen *cgen;
2298 /* An unary operation cannot yield an l-value */
2300 compile_error(ast_ctx(self), "not an l-value (binop)");
2304 if (self->expression.outr) {
2305 *out = self->expression.outr;
2309 cgen = self->operand->codegen;
2311 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2314 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2318 self->expression.outr = *out;
2323 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2325 ast_expression_codegen *cgen;
2330 /* In the context of a return operation, we don't actually return
2334 compile_error(ast_ctx(self), "return-expression is not an l-value");
2338 if (self->expression.outr) {
2339 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2342 self->expression.outr = (ir_value*)1;
2344 if (self->operand) {
2345 cgen = self->operand->codegen;
2347 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2350 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2353 if (!ir_block_create_return(func->curblock, ast_ctx(self), nullptr))
2360 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2362 ast_expression_codegen *cgen;
2363 ir_value *ent, *field;
2365 /* This function needs to take the 'lvalue' flag into account!
2366 * As lvalue we provide a field-pointer, as rvalue we provide the
2370 if (lvalue && self->expression.outl) {
2371 *out = self->expression.outl;
2375 if (!lvalue && self->expression.outr) {
2376 *out = self->expression.outr;
2380 cgen = self->entity->codegen;
2381 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2384 cgen = self->field->codegen;
2385 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2390 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2393 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2394 ent, field, self->expression.vtype);
2395 /* Done AFTER error checking:
2396 codegen_output_type(self, *out);
2400 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2401 (lvalue ? "ADDRESS" : "FIELD"),
2402 type_name[self->expression.vtype]);
2406 codegen_output_type(self, *out);
2409 self->expression.outl = *out;
2411 self->expression.outr = *out;
2413 /* Hm that should be it... */
2417 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2419 ast_expression_codegen *cgen;
2422 /* in QC this is always an lvalue */
2423 if (lvalue && self->rvalue) {
2424 compile_error(ast_ctx(self), "not an l-value (member access)");
2427 if (self->expression.outl) {
2428 *out = self->expression.outl;
2432 cgen = self->owner->codegen;
2433 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2436 if (vec->vtype != TYPE_VECTOR &&
2437 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2442 *out = ir_value_vector_member(vec, self->field);
2443 self->expression.outl = *out;
2445 return (*out != nullptr);
2448 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2453 if (!lvalue && self->expression.outr) {
2454 *out = self->expression.outr;
2457 if (lvalue && self->expression.outl) {
2458 *out = self->expression.outl;
2462 if (!ast_istype(self->array, ast_value)) {
2463 compile_error(ast_ctx(self), "array indexing this way is not supported");
2464 /* note this would actually be pointer indexing because the left side is
2465 * not an actual array but (hopefully) an indexable expression.
2466 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2467 * support this path will be filled.
2472 arr = (ast_value*)self->array;
2473 idx = (ast_value*)self->index;
2475 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2476 /* Time to use accessor functions */
2477 ast_expression_codegen *cgen;
2478 ir_value *iridx, *funval;
2482 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2487 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2491 cgen = self->index->codegen;
2492 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2495 cgen = arr->getter->expression.codegen;
2496 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2499 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2502 ir_call_param(call, iridx);
2504 *out = ir_call_value(call);
2505 self->expression.outr = *out;
2506 (*out)->vtype = self->expression.vtype;
2507 codegen_output_type(self, *out);
2511 if (idx->expression.vtype == TYPE_FLOAT) {
2512 unsigned int arridx = idx->constval.vfloat;
2513 if (arridx >= self->array->count)
2515 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2518 *out = arr->ir_values[arridx];
2520 else if (idx->expression.vtype == TYPE_INTEGER) {
2521 unsigned int arridx = idx->constval.vint;
2522 if (arridx >= self->array->count)
2524 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2527 *out = arr->ir_values[arridx];
2530 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2533 (*out)->vtype = self->expression.vtype;
2534 codegen_output_type(self, *out);
2538 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2542 compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2547 compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2551 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2553 ast_expression_codegen *cgen;
2561 ir_block *ontrue_endblock = nullptr;
2562 ir_block *onfalse_endblock = nullptr;
2563 ir_block *merge = nullptr;
2566 /* We don't output any value, thus also don't care about r/lvalue */
2570 if (self->expression.outr) {
2571 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2574 self->expression.outr = (ir_value*)1;
2576 /* generate the condition */
2577 cgen = self->cond->codegen;
2578 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2580 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2581 cond = func->curblock;
2583 /* try constant folding away the condition */
2584 if ((folded = fold::cond_ifthen(condval, func, self)) != -1)
2587 if (self->on_true) {
2588 /* create on-true block */
2589 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2593 /* enter the block */
2594 func->curblock = ontrue;
2597 cgen = self->on_true->codegen;
2598 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2601 /* we now need to work from the current endpoint */
2602 ontrue_endblock = func->curblock;
2607 if (self->on_false) {
2608 /* create on-false block */
2609 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2613 /* enter the block */
2614 func->curblock = onfalse;
2617 cgen = self->on_false->codegen;
2618 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2621 /* we now need to work from the current endpoint */
2622 onfalse_endblock = func->curblock;
2626 /* Merge block were they all merge in to */
2627 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2629 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2632 /* add jumps ot the merge block */
2633 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2635 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2638 /* Now enter the merge block */
2639 func->curblock = merge;
2642 /* we create the if here, that way all blocks are ordered :)
2644 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2645 (ontrue ? ontrue : merge),
2646 (onfalse ? onfalse : merge)))
2654 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2656 ast_expression_codegen *cgen;
2659 ir_value *trueval, *falseval;
2662 ir_block *cond = func->curblock;
2663 ir_block *cond_out = nullptr;
2664 ir_block *ontrue, *ontrue_out = nullptr;
2665 ir_block *onfalse, *onfalse_out = nullptr;
2669 /* Ternary can never create an lvalue... */
2673 /* In theory it shouldn't be possible to pass through a node twice, but
2674 * in case we add any kind of optimization pass for the AST itself, it
2675 * may still happen, thus we remember a created ir_value and simply return one
2676 * if it already exists.
2678 if (self->expression.outr) {
2679 *out = self->expression.outr;
2683 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2685 /* generate the condition */
2686 func->curblock = cond;
2687 cgen = self->cond->codegen;
2688 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2690 cond_out = func->curblock;
2692 /* try constant folding away the condition */
2693 if ((folded = fold::cond_ternary(condval, func, self)) != -1)
2696 /* create on-true block */
2697 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2702 /* enter the block */
2703 func->curblock = ontrue;
2706 cgen = self->on_true->codegen;
2707 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2710 ontrue_out = func->curblock;
2713 /* create on-false block */
2714 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2719 /* enter the block */
2720 func->curblock = onfalse;
2723 cgen = self->on_false->codegen;
2724 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2727 onfalse_out = func->curblock;
2730 /* create merge block */
2731 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2734 /* jump to merge block */
2735 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2737 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2740 /* create if instruction */
2741 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2744 /* Now enter the merge block */
2745 func->curblock = merge;
2747 /* Here, now, we need a PHI node
2748 * but first some sanity checking...
2750 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2751 /* error("ternary with different types on the two sides"); */
2752 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2757 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2759 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2762 ir_phi_add(phi, ontrue_out, trueval);
2763 ir_phi_add(phi, onfalse_out, falseval);
2765 self->expression.outr = ir_phi_value(phi);
2766 *out = self->expression.outr;
2768 codegen_output_type(self, *out);
2773 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2775 ast_expression_codegen *cgen;
2777 ir_value *dummy = nullptr;
2778 ir_value *precond = nullptr;
2779 ir_value *postcond = nullptr;
2781 /* Since we insert some jumps "late" so we have blocks
2782 * ordered "nicely", we need to keep track of the actual end-blocks
2783 * of expressions to add the jumps to.
2785 ir_block *bbody = nullptr, *end_bbody = nullptr;
2786 ir_block *bprecond = nullptr, *end_bprecond = nullptr;
2787 ir_block *bpostcond = nullptr, *end_bpostcond = nullptr;
2788 ir_block *bincrement = nullptr, *end_bincrement = nullptr;
2789 ir_block *bout = nullptr, *bin = nullptr;
2791 /* let's at least move the outgoing block to the end */
2794 /* 'break' and 'continue' need to be able to find the right blocks */
2795 ir_block *bcontinue = nullptr;
2796 ir_block *bbreak = nullptr;
2798 ir_block *tmpblock = nullptr;
2803 if (self->expression.outr) {
2804 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2807 self->expression.outr = (ir_value*)1;
2810 * Should we ever need some kind of block ordering, better make this function
2811 * move blocks around than write a block ordering algorithm later... after all
2812 * the ast and ir should work together, not against each other.
2815 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2816 * anyway if for example it contains a ternary.
2820 cgen = self->initexpr->codegen;
2821 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2825 /* Store the block from which we enter this chaos */
2826 bin = func->curblock;
2828 /* The pre-loop condition needs its own block since we
2829 * need to be able to jump to the start of that expression.
2833 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2837 /* the pre-loop-condition the least important place to 'continue' at */
2838 bcontinue = bprecond;
2841 func->curblock = bprecond;
2844 cgen = self->precond->codegen;
2845 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2848 end_bprecond = func->curblock;
2850 bprecond = end_bprecond = nullptr;
2853 /* Now the next blocks won't be ordered nicely, but we need to
2854 * generate them this early for 'break' and 'continue'.
2856 if (self->increment) {
2857 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2860 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2862 bincrement = end_bincrement = nullptr;
2865 if (self->postcond) {
2866 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2869 bcontinue = bpostcond; /* postcond comes before the increment */
2871 bpostcond = end_bpostcond = nullptr;
2874 bout_id = vec_size(func->ir_func->blocks);
2875 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2880 /* The loop body... */
2881 /* if (self->body) */
2883 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2888 func->curblock = bbody;
2890 func->breakblocks.push_back(bbreak);
2892 func->continueblocks.push_back(bcontinue);
2894 func->continueblocks.push_back(bbody);
2898 cgen = self->body->codegen;
2899 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2903 end_bbody = func->curblock;
2904 func->breakblocks.pop_back();
2905 func->continueblocks.pop_back();
2908 /* post-loop-condition */
2912 func->curblock = bpostcond;
2915 cgen = self->postcond->codegen;
2916 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2919 end_bpostcond = func->curblock;
2922 /* The incrementor */
2923 if (self->increment)
2926 func->curblock = bincrement;
2929 cgen = self->increment->codegen;
2930 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2933 end_bincrement = func->curblock;
2936 /* In any case now, we continue from the outgoing block */
2937 func->curblock = bout;
2939 /* Now all blocks are in place */
2940 /* From 'bin' we jump to whatever comes first */
2941 if (bprecond) tmpblock = bprecond;
2942 else tmpblock = bbody; /* can never be null */
2945 else if (bpostcond) tmpblock = bpostcond;
2946 else tmpblock = bout;
2949 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
2955 ir_block *ontrue, *onfalse;
2956 ontrue = bbody; /* can never be null */
2958 /* all of this is dead code
2959 else if (bincrement) ontrue = bincrement;
2960 else ontrue = bpostcond;
2964 if (self->pre_not) {
2969 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
2976 if (bincrement) tmpblock = bincrement;
2977 else if (bpostcond) tmpblock = bpostcond;
2978 else if (bprecond) tmpblock = bprecond;
2979 else tmpblock = bbody;
2980 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
2984 /* from increment */
2987 if (bpostcond) tmpblock = bpostcond;
2988 else if (bprecond) tmpblock = bprecond;
2989 else if (bbody) tmpblock = bbody;
2990 else tmpblock = bout;
2991 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
2998 ir_block *ontrue, *onfalse;
2999 if (bprecond) ontrue = bprecond;
3000 else ontrue = bbody; /* can never be null */
3002 /* all of this is dead code
3003 else if (bincrement) ontrue = bincrement;
3004 else ontrue = bpostcond;
3008 if (self->post_not) {
3013 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
3017 /* Move 'bout' to the end */
3018 vec_remove(func->ir_func->blocks, bout_id, 1);
3019 vec_push(func->ir_func->blocks, bout);
3024 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
3031 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3035 if (self->expression.outr) {
3036 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3039 self->expression.outr = (ir_value*)1;
3041 if (self->is_continue)
3042 target = func->continueblocks[func->continueblocks.size()-1-self->levels];
3044 target = func->breakblocks[func->breakblocks.size()-1-self->levels];
3047 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3051 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3056 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3058 ast_expression_codegen *cgen;
3060 ast_switch_case *def_case = nullptr;
3061 ir_block *def_bfall = nullptr;
3062 ir_block *def_bfall_to = nullptr;
3063 bool set_def_bfall_to = false;
3065 ir_value *dummy = nullptr;
3066 ir_value *irop = nullptr;
3067 ir_block *bout = nullptr;
3068 ir_block *bfall = nullptr;
3075 compile_error(ast_ctx(self), "switch expression is not an l-value");
3079 if (self->expression.outr) {
3080 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3083 self->expression.outr = (ir_value*)1;
3088 cgen = self->operand->codegen;
3089 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3092 if (self->cases.empty())
3095 cmpinstr = type_eq_instr[irop->vtype];
3096 if (cmpinstr >= VINSTR_END) {
3097 ast_type_to_string(self->operand, typestr, sizeof(typestr));
3098 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3102 bout_id = vec_size(func->ir_func->blocks);
3103 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3107 /* setup the break block */
3108 func->breakblocks.push_back(bout);
3110 /* Now create all cases */
3111 for (auto &it : self->cases) {
3112 ir_value *cond, *val;
3113 ir_block *bcase, *bnot;
3116 ast_switch_case *swcase = ⁢
3118 if (swcase->value) {
3119 /* A regular case */
3120 /* generate the condition operand */
3121 cgen = swcase->value->codegen;
3122 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3124 /* generate the condition */
3125 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3129 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3130 bnot_id = vec_size(func->ir_func->blocks);
3131 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3132 if (!bcase || !bnot)
3134 if (set_def_bfall_to) {
3135 set_def_bfall_to = false;
3136 def_bfall_to = bcase;
3138 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3141 /* Make the previous case-end fall through */
3142 if (bfall && !bfall->final) {
3143 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3147 /* enter the case */
3148 func->curblock = bcase;
3149 cgen = swcase->code->codegen;
3150 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3153 /* remember this block to fall through from */
3154 bfall = func->curblock;
3156 /* enter the else and move it down */
3157 func->curblock = bnot;
3158 vec_remove(func->ir_func->blocks, bnot_id, 1);
3159 vec_push(func->ir_func->blocks, bnot);
3161 /* The default case */
3162 /* Remember where to fall through from: */
3165 /* remember which case it was */
3167 /* And the next case will be remembered */
3168 set_def_bfall_to = true;
3172 /* Jump from the last bnot to bout */
3173 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3175 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3180 /* If there was a default case, put it down here */
3184 /* No need to create an extra block */
3185 bcase = func->curblock;
3187 /* Insert the fallthrough jump */
3188 if (def_bfall && !def_bfall->final) {
3189 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3193 /* Now generate the default code */
3194 cgen = def_case->code->codegen;
3195 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3198 /* see if we need to fall through */
3199 if (def_bfall_to && !func->curblock->final)
3201 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3206 /* Jump from the last bnot to bout */
3207 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3209 /* enter the outgoing block */
3210 func->curblock = bout;
3212 /* restore the break block */
3213 func->breakblocks.pop_back();
3215 /* Move 'bout' to the end, it's nicer */
3216 vec_remove(func->ir_func->blocks, bout_id, 1);
3217 vec_push(func->ir_func->blocks, bout);
3222 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3226 if (self->undefined) {
3227 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3233 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3237 /* simply create a new block and jump to it */
3238 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3239 if (!self->irblock) {
3240 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3243 if (!func->curblock->final) {
3244 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3248 /* enter the new block */
3249 func->curblock = self->irblock;
3251 /* Generate all the leftover gotos */
3252 for (auto &it : self->gotos) {
3253 if (!ast_goto_codegen(it, func, false, &dummy))
3260 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3264 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3268 if (self->target->irblock) {
3269 if (self->irblock_from) {
3270 /* we already tried once, this is the callback */
3271 self->irblock_from->final = false;
3272 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3273 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3279 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3280 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3287 /* the target has not yet been created...
3288 * close this block in a sneaky way:
3290 func->curblock->final = true;
3291 self->irblock_from = func->curblock;
3292 ast_label_register_goto(self->target, self);
3299 bool ast_state_codegen(ast_state *self, ast_function *func, bool lvalue, ir_value **out)
3301 ast_expression_codegen *cgen;
3303 ir_value *frameval, *thinkval;
3306 compile_error(ast_ctx(self), "not an l-value (state operation)");
3309 if (self->expression.outr) {
3310 compile_error(ast_ctx(self), "internal error: ast_state cannot be reused!");
3315 cgen = self->framenum->codegen;
3316 if (!(*cgen)((ast_expression*)(self->framenum), func, false, &frameval))
3321 cgen = self->nextthink->codegen;
3322 if (!(*cgen)((ast_expression*)(self->nextthink), func, false, &thinkval))
3327 if (!ir_block_create_state_op(func->curblock, ast_ctx(self), frameval, thinkval)) {
3328 compile_error(ast_ctx(self), "failed to create STATE instruction");
3332 self->expression.outr = (ir_value*)1;
3336 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3338 ast_expression_codegen *cgen;
3339 std::vector<ir_value*> params;
3340 ir_instr *callinstr;
3342 ir_value *funval = nullptr;
3344 /* return values are never lvalues */
3346 compile_error(ast_ctx(self), "not an l-value (function call)");
3350 if (self->expression.outr) {
3351 *out = self->expression.outr;
3355 cgen = self->func->codegen;
3356 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3362 for (auto &it : self->params) {
3365 if (!(*cgen)(it, func, false, ¶m))
3369 params.push_back(param);
3372 /* varargs counter */
3373 if (self->va_count) {
3375 ir_builder *builder = func->curblock->owner->owner;
3376 cgen = self->va_count->codegen;
3377 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3379 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3380 ir_builder_get_va_count(builder), va_count))
3386 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3387 ast_function_label(func, "call"),
3388 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3392 for (auto &it : params)
3393 ir_call_param(callinstr, it);
3395 *out = ir_call_value(callinstr);
3396 self->expression.outr = *out;
3398 codegen_output_type(self, *out);