8 #define ast_instantiate(T, ctx, destroyfn) \
9 T* self = (T*)mem_a(sizeof(T)); \
13 ast_node_init((ast_node*)self, ctx, TYPE_##T); \
14 ( (ast_node*)self )->destroy = (ast_node_delete*)destroyfn
17 * forward declarations, these need not be in ast.h for obvious
20 static bool ast_member_codegen(ast_member*, ast_function*, bool lvalue, ir_value**);
21 static void ast_array_index_delete(ast_array_index*);
22 static bool ast_array_index_codegen(ast_array_index*, ast_function*, bool lvalue, ir_value**);
23 static void ast_argpipe_delete(ast_argpipe*);
24 static bool ast_argpipe_codegen(ast_argpipe*, ast_function*, bool lvalue, ir_value**);
25 static void ast_store_delete(ast_store*);
26 static bool ast_store_codegen(ast_store*, ast_function*, bool lvalue, ir_value**);
27 static void ast_ifthen_delete(ast_ifthen*);
28 static bool ast_ifthen_codegen(ast_ifthen*, ast_function*, bool lvalue, ir_value**);
29 static void ast_ternary_delete(ast_ternary*);
30 static bool ast_ternary_codegen(ast_ternary*, ast_function*, bool lvalue, ir_value**);
31 static void ast_loop_delete(ast_loop*);
32 static bool ast_loop_codegen(ast_loop*, ast_function*, bool lvalue, ir_value**);
33 static void ast_breakcont_delete(ast_breakcont*);
34 static bool ast_breakcont_codegen(ast_breakcont*, ast_function*, bool lvalue, ir_value**);
35 static void ast_switch_delete(ast_switch*);
36 static bool ast_switch_codegen(ast_switch*, ast_function*, bool lvalue, ir_value**);
37 static void ast_label_delete(ast_label*);
38 static void ast_label_register_goto(ast_label*, ast_goto*);
39 static bool ast_label_codegen(ast_label*, ast_function*, bool lvalue, ir_value**);
40 static bool ast_goto_codegen(ast_goto*, ast_function*, bool lvalue, ir_value**);
41 static void ast_goto_delete(ast_goto*);
42 static void ast_call_delete(ast_call*);
43 static bool ast_call_codegen(ast_call*, ast_function*, bool lvalue, ir_value**);
44 static bool ast_block_codegen(ast_block*, ast_function*, bool lvalue, ir_value**);
45 static void ast_unary_delete(ast_unary*);
46 static bool ast_unary_codegen(ast_unary*, ast_function*, bool lvalue, ir_value**);
47 static void ast_entfield_delete(ast_entfield*);
48 static bool ast_entfield_codegen(ast_entfield*, ast_function*, bool lvalue, ir_value**);
49 static void ast_return_delete(ast_return*);
50 static bool ast_return_codegen(ast_return*, ast_function*, bool lvalue, ir_value**);
51 static void ast_binstore_delete(ast_binstore*);
52 static bool ast_binstore_codegen(ast_binstore*, ast_function*, bool lvalue, ir_value**);
53 static void ast_binary_delete(ast_binary*);
54 static bool ast_binary_codegen(ast_binary*, ast_function*, bool lvalue, ir_value**);
55 static bool ast_state_codegen(ast_state*, ast_function*, bool lvalue, ir_value**);
57 /* It must not be possible to get here. */
58 static GMQCC_NORETURN void _ast_node_destroy(ast_node *self)
61 con_err("ast node missing destroy()\n");
65 /* Initialize main ast node aprts */
66 static void ast_node_init(ast_node *self, lex_ctx_t ctx, int nodetype)
69 self->destroy = &_ast_node_destroy;
71 self->nodetype = nodetype;
72 self->side_effects = false;
75 /* weight and side effects */
76 static void _ast_propagate_effects(ast_node *self, ast_node *other)
78 if (ast_side_effects(other))
79 ast_side_effects(self) = true;
81 #define ast_propagate_effects(s,o) _ast_propagate_effects(((ast_node*)(s)), ((ast_node*)(o)))
83 /* General expression initialization */
84 static void ast_expression_init(ast_expression *self,
85 ast_expression_codegen *codegen)
87 self->codegen = codegen;
88 self->vtype = TYPE_VOID;
94 self->varparam = NULL;
96 if (OPTS_OPTION_BOOL(OPTION_COVERAGE))
97 self->flags |= AST_FLAG_BLOCK_COVERAGE;
100 static void ast_expression_delete(ast_expression *self)
104 ast_delete(self->next);
105 for (i = 0; i < vec_size(self->params); ++i) {
106 ast_delete(self->params[i]);
108 vec_free(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)
122 const ast_expression *fromex;
123 ast_expression *selfex;
124 ast_value *cp = ast_value_new(self->expression.node.context, self->name, self->expression.vtype);
125 if (self->expression.next) {
126 cp->expression.next = ast_type_copy(self->expression.node.context, self->expression.next);
128 fromex = &self->expression;
129 selfex = &cp->expression;
130 selfex->count = fromex->count;
131 selfex->flags = fromex->flags;
132 for (i = 0; i < vec_size(fromex->params); ++i) {
133 ast_value *v = ast_value_copy(fromex->params[i]);
134 vec_push(selfex->params, v);
139 void ast_type_adopt_impl(ast_expression *self, const ast_expression *other)
142 const ast_expression *fromex;
143 ast_expression *selfex;
144 self->vtype = other->vtype;
146 self->next = (ast_expression*)ast_type_copy(ast_ctx(self), other->next);
150 selfex->count = fromex->count;
151 selfex->flags = fromex->flags;
152 for (i = 0; i < vec_size(fromex->params); ++i) {
153 ast_value *v = ast_value_copy(fromex->params[i]);
154 vec_push(selfex->params, v);
158 static ast_expression* ast_shallow_type(lex_ctx_t ctx, int vtype)
160 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
161 ast_expression_init(self, NULL);
162 self->codegen = NULL;
168 ast_expression* ast_type_copy(lex_ctx_t ctx, const ast_expression *ex)
171 const ast_expression *fromex;
172 ast_expression *selfex;
178 ast_instantiate(ast_expression, ctx, ast_expression_delete_full);
179 ast_expression_init(self, NULL);
184 /* This may never be codegen()d */
185 selfex->codegen = NULL;
187 selfex->vtype = fromex->vtype;
189 selfex->next = ast_type_copy(ctx, fromex->next);
193 selfex->count = fromex->count;
194 selfex->flags = fromex->flags;
195 for (i = 0; i < vec_size(fromex->params); ++i) {
196 ast_value *v = ast_value_copy(fromex->params[i]);
197 vec_push(selfex->params, v);
204 bool ast_compare_type(ast_expression *a, ast_expression *b)
206 if (a->vtype == TYPE_NIL ||
207 b->vtype == TYPE_NIL)
209 if (a->vtype != b->vtype)
211 if (!a->next != !b->next)
213 if (vec_size(a->params) != vec_size(b->params))
215 if ((a->flags & AST_FLAG_TYPE_MASK) !=
216 (b->flags & AST_FLAG_TYPE_MASK) )
220 if (vec_size(a->params)) {
222 for (i = 0; i < vec_size(a->params); ++i) {
223 if (!ast_compare_type((ast_expression*)a->params[i],
224 (ast_expression*)b->params[i]))
229 return ast_compare_type(a->next, b->next);
233 static size_t ast_type_to_string_impl(ast_expression *e, char *buf, size_t bufsize, size_t pos)
240 if (pos + 6 >= bufsize)
242 util_strncpy(buf + pos, "(null)", 6);
246 if (pos + 1 >= bufsize)
251 util_strncpy(buf + pos, "(variant)", 9);
256 return ast_type_to_string_impl(e->next, buf, bufsize, pos);
259 if (pos + 3 >= bufsize)
263 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
264 if (pos + 1 >= bufsize)
270 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
271 if (pos + 2 >= bufsize)
273 if (!vec_size(e->params)) {
279 pos = ast_type_to_string_impl((ast_expression*)(e->params[0]), buf, bufsize, pos);
280 for (i = 1; i < vec_size(e->params); ++i) {
281 if (pos + 2 >= bufsize)
285 pos = ast_type_to_string_impl((ast_expression*)(e->params[i]), buf, bufsize, pos);
287 if (pos + 1 >= bufsize)
293 pos = ast_type_to_string_impl(e->next, buf, bufsize, pos);
294 if (pos + 1 >= bufsize)
297 pos += util_snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->count);
298 if (pos + 1 >= bufsize)
304 typestr = type_name[e->vtype];
305 typelen = strlen(typestr);
306 if (pos + typelen >= bufsize)
308 util_strncpy(buf + pos, typestr, typelen);
309 return pos + typelen;
313 buf[bufsize-3] = '.';
314 buf[bufsize-2] = '.';
315 buf[bufsize-1] = '.';
319 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize)
321 size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
325 static bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out);
326 ast_value* ast_value_new(lex_ctx_t ctx, const char *name, int t)
328 ast_instantiate(ast_value, ctx, ast_value_delete);
329 ast_expression_init((ast_expression*)self,
330 (ast_expression_codegen*)&ast_value_codegen);
331 self->expression.node.keep = true; /* keep */
333 self->name = name ? util_strdup(name) : NULL;
334 self->expression.vtype = t;
335 self->expression.next = NULL;
336 self->isfield = false;
338 self->hasvalue = false;
340 self->inexact = false;
342 memset(&self->constval, 0, sizeof(self->constval));
343 self->initlist = NULL;
346 self->ir_values = NULL;
347 self->ir_value_count = 0;
353 self->argcounter = NULL;
354 self->intrinsic = false;
359 void ast_value_delete(ast_value* self)
362 mem_d((void*)self->name);
363 if (self->argcounter)
364 mem_d((void*)self->argcounter);
365 if (self->hasvalue) {
366 switch (self->expression.vtype)
369 mem_d((void*)self->constval.vstring);
372 /* unlink us from the function node */
373 self->constval.vfunc->vtype = NULL;
375 /* NOTE: delete function? currently collected in
376 * the parser structure
383 mem_d(self->ir_values);
388 if (self->initlist) {
389 if (self->expression.next->vtype == TYPE_STRING) {
390 /* strings are allocated, free them */
391 size_t i, len = vec_size(self->initlist);
392 /* in theory, len should be expression.count
393 * but let's not take any chances */
394 for (i = 0; i < len; ++i) {
395 if (self->initlist[i].vstring)
396 mem_d(self->initlist[i].vstring);
399 vec_free(self->initlist);
402 ast_expression_delete((ast_expression*)self);
406 void ast_value_params_add(ast_value *self, ast_value *p)
408 vec_push(self->expression.params, p);
411 bool ast_value_set_name(ast_value *self, const char *name)
414 mem_d((void*)self->name);
415 self->name = util_strdup(name);
419 ast_binary* ast_binary_new(lex_ctx_t ctx, int op,
420 ast_expression* left, ast_expression* right)
422 ast_instantiate(ast_binary, ctx, ast_binary_delete);
423 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
425 if (ast_istype(right, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
426 ast_unary *unary = ((ast_unary*)right);
427 ast_expression *normal = unary->operand;
429 /* make a-(-b) => a + b */
430 if (unary->op == VINSTR_NEG_F || unary->op == VINSTR_NEG_V) {
431 if (op == INSTR_SUB_F) {
434 ++opts_optimizationcount[OPTIM_PEEPHOLE];
435 } else if (op == INSTR_SUB_V) {
438 ++opts_optimizationcount[OPTIM_PEEPHOLE];
446 self->right_first = false;
448 ast_propagate_effects(self, left);
449 ast_propagate_effects(self, right);
451 if (op >= INSTR_EQ_F && op <= INSTR_GT)
452 self->expression.vtype = TYPE_FLOAT;
453 else if (op == INSTR_AND || op == INSTR_OR) {
454 if (OPTS_FLAG(PERL_LOGIC))
455 ast_type_adopt(self, right);
457 self->expression.vtype = TYPE_FLOAT;
459 else if (op == INSTR_BITAND || op == INSTR_BITOR)
460 self->expression.vtype = TYPE_FLOAT;
461 else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
462 self->expression.vtype = TYPE_VECTOR;
463 else if (op == INSTR_MUL_V)
464 self->expression.vtype = TYPE_FLOAT;
466 self->expression.vtype = left->vtype;
469 self->refs = AST_REF_ALL;
474 void ast_binary_delete(ast_binary *self)
476 if (self->refs & AST_REF_LEFT) ast_unref(self->left);
477 if (self->refs & AST_REF_RIGHT) ast_unref(self->right);
479 ast_expression_delete((ast_expression*)self);
483 ast_binstore* ast_binstore_new(lex_ctx_t ctx, int storop, int op,
484 ast_expression* left, ast_expression* right)
486 ast_instantiate(ast_binstore, ctx, ast_binstore_delete);
487 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binstore_codegen);
489 ast_side_effects(self) = true;
491 self->opstore = storop;
494 self->source = right;
496 self->keep_dest = false;
498 ast_type_adopt(self, left);
502 void ast_binstore_delete(ast_binstore *self)
504 if (!self->keep_dest)
505 ast_unref(self->dest);
506 ast_unref(self->source);
507 ast_expression_delete((ast_expression*)self);
511 ast_unary* ast_unary_new(lex_ctx_t ctx, int op,
512 ast_expression *expr)
514 ast_instantiate(ast_unary, ctx, ast_unary_delete);
515 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_unary_codegen);
518 self->operand = expr;
521 if (ast_istype(expr, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
522 ast_unary *prev = (ast_unary*)((ast_unary*)expr)->operand;
524 /* Handle for double negation */
525 if (((ast_unary*)expr)->op == op)
526 prev = (ast_unary*)((ast_unary*)expr)->operand;
528 if (ast_istype(prev, ast_unary)) {
529 ast_expression_delete((ast_expression*)self);
531 ++opts_optimizationcount[OPTIM_PEEPHOLE];
536 ast_propagate_effects(self, expr);
538 if ((op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) || op == VINSTR_NEG_F) {
539 self->expression.vtype = TYPE_FLOAT;
540 } else if (op == VINSTR_NEG_V) {
541 self->expression.vtype = TYPE_VECTOR;
543 compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
549 void ast_unary_delete(ast_unary *self)
551 if (self->operand) ast_unref(self->operand);
552 ast_expression_delete((ast_expression*)self);
556 ast_return* ast_return_new(lex_ctx_t ctx, ast_expression *expr)
558 ast_instantiate(ast_return, ctx, ast_return_delete);
559 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_return_codegen);
561 self->operand = expr;
564 ast_propagate_effects(self, expr);
569 void ast_return_delete(ast_return *self)
572 ast_unref(self->operand);
573 ast_expression_delete((ast_expression*)self);
577 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
579 if (field->vtype != TYPE_FIELD) {
580 compile_error(ctx, "ast_entfield_new with expression not of type field");
583 return ast_entfield_new_force(ctx, entity, field, field->next);
586 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
588 ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
592 /* Error: field has no type... */
596 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
598 self->entity = entity;
600 ast_propagate_effects(self, entity);
601 ast_propagate_effects(self, field);
603 ast_type_adopt(self, outtype);
607 void ast_entfield_delete(ast_entfield *self)
609 ast_unref(self->entity);
610 ast_unref(self->field);
611 ast_expression_delete((ast_expression*)self);
615 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name)
617 ast_instantiate(ast_member, ctx, ast_member_delete);
623 if (owner->vtype != TYPE_VECTOR &&
624 owner->vtype != TYPE_FIELD) {
625 compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->vtype]);
630 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_member_codegen);
631 self->expression.node.keep = true; /* keep */
633 if (owner->vtype == TYPE_VECTOR) {
634 self->expression.vtype = TYPE_FLOAT;
635 self->expression.next = NULL;
637 self->expression.vtype = TYPE_FIELD;
638 self->expression.next = ast_shallow_type(ctx, TYPE_FLOAT);
641 self->rvalue = false;
643 ast_propagate_effects(self, owner);
647 self->name = util_strdup(name);
654 void ast_member_delete(ast_member *self)
656 /* The owner is always an ast_value, which has .keep=true,
657 * also: ast_members are usually deleted after the owner, thus
658 * this will cause invalid access
659 ast_unref(self->owner);
660 * once we allow (expression).x to access a vector-member, we need
661 * to change this: preferably by creating an alternate ast node for this
662 * purpose that is not garbage-collected.
664 ast_expression_delete((ast_expression*)self);
669 bool ast_member_set_name(ast_member *self, const char *name)
672 mem_d((void*)self->name);
673 self->name = util_strdup(name);
677 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
679 ast_expression *outtype;
680 ast_instantiate(ast_array_index, ctx, ast_array_index_delete);
682 outtype = array->next;
685 /* Error: field has no type... */
689 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_array_index_codegen);
693 ast_propagate_effects(self, array);
694 ast_propagate_effects(self, index);
696 ast_type_adopt(self, outtype);
697 if (array->vtype == TYPE_FIELD && outtype->vtype == TYPE_ARRAY) {
698 if (self->expression.vtype != TYPE_ARRAY) {
699 compile_error(ast_ctx(self), "array_index node on type");
700 ast_array_index_delete(self);
703 self->array = outtype;
704 self->expression.vtype = TYPE_FIELD;
710 void ast_array_index_delete(ast_array_index *self)
713 ast_unref(self->array);
715 ast_unref(self->index);
716 ast_expression_delete((ast_expression*)self);
720 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index)
722 ast_instantiate(ast_argpipe, ctx, ast_argpipe_delete);
723 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_argpipe_codegen);
725 self->expression.vtype = TYPE_NOEXPR;
729 void ast_argpipe_delete(ast_argpipe *self)
732 ast_unref(self->index);
733 ast_expression_delete((ast_expression*)self);
737 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
739 ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
740 if (!ontrue && !onfalse) {
741 /* because it is invalid */
745 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
748 self->on_true = ontrue;
749 self->on_false = onfalse;
750 ast_propagate_effects(self, cond);
752 ast_propagate_effects(self, ontrue);
754 ast_propagate_effects(self, onfalse);
759 void ast_ifthen_delete(ast_ifthen *self)
761 ast_unref(self->cond);
763 ast_unref(self->on_true);
765 ast_unref(self->on_false);
766 ast_expression_delete((ast_expression*)self);
770 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
772 ast_expression *exprtype = ontrue;
773 ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
774 /* This time NEITHER must be NULL */
775 if (!ontrue || !onfalse) {
779 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
782 self->on_true = ontrue;
783 self->on_false = onfalse;
784 ast_propagate_effects(self, cond);
785 ast_propagate_effects(self, ontrue);
786 ast_propagate_effects(self, onfalse);
788 if (ontrue->vtype == TYPE_NIL)
790 ast_type_adopt(self, exprtype);
795 void ast_ternary_delete(ast_ternary *self)
797 /* the if()s are only there because computed-gotos can set them
800 if (self->cond) ast_unref(self->cond);
801 if (self->on_true) ast_unref(self->on_true);
802 if (self->on_false) ast_unref(self->on_false);
803 ast_expression_delete((ast_expression*)self);
807 ast_loop* ast_loop_new(lex_ctx_t ctx,
808 ast_expression *initexpr,
809 ast_expression *precond, bool pre_not,
810 ast_expression *postcond, bool post_not,
811 ast_expression *increment,
812 ast_expression *body)
814 ast_instantiate(ast_loop, ctx, ast_loop_delete);
815 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_loop_codegen);
817 self->initexpr = initexpr;
818 self->precond = precond;
819 self->postcond = postcond;
820 self->increment = increment;
823 self->pre_not = pre_not;
824 self->post_not = post_not;
827 ast_propagate_effects(self, initexpr);
829 ast_propagate_effects(self, precond);
831 ast_propagate_effects(self, postcond);
833 ast_propagate_effects(self, increment);
835 ast_propagate_effects(self, body);
840 void ast_loop_delete(ast_loop *self)
843 ast_unref(self->initexpr);
845 ast_unref(self->precond);
847 ast_unref(self->postcond);
849 ast_unref(self->increment);
851 ast_unref(self->body);
852 ast_expression_delete((ast_expression*)self);
856 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels)
858 ast_instantiate(ast_breakcont, ctx, ast_breakcont_delete);
859 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_breakcont_codegen);
861 self->is_continue = iscont;
862 self->levels = levels;
867 void ast_breakcont_delete(ast_breakcont *self)
869 ast_expression_delete((ast_expression*)self);
873 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op)
875 ast_instantiate(ast_switch, ctx, ast_switch_delete);
876 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_switch_codegen);
881 ast_propagate_effects(self, op);
886 void ast_switch_delete(ast_switch *self)
889 ast_unref(self->operand);
891 for (i = 0; i < vec_size(self->cases); ++i) {
892 if (self->cases[i].value)
893 ast_unref(self->cases[i].value);
894 ast_unref(self->cases[i].code);
896 vec_free(self->cases);
898 ast_expression_delete((ast_expression*)self);
902 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined)
904 ast_instantiate(ast_label, ctx, ast_label_delete);
905 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_label_codegen);
907 self->expression.vtype = TYPE_NOEXPR;
909 self->name = util_strdup(name);
910 self->irblock = NULL;
912 self->undefined = undefined;
917 void ast_label_delete(ast_label *self)
919 mem_d((void*)self->name);
920 vec_free(self->gotos);
921 ast_expression_delete((ast_expression*)self);
925 static void ast_label_register_goto(ast_label *self, ast_goto *g)
927 vec_push(self->gotos, g);
930 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name)
932 ast_instantiate(ast_goto, ctx, ast_goto_delete);
933 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_goto_codegen);
935 self->name = util_strdup(name);
937 self->irblock_from = NULL;
942 void ast_goto_delete(ast_goto *self)
944 mem_d((void*)self->name);
945 ast_expression_delete((ast_expression*)self);
949 void ast_goto_set_label(ast_goto *self, ast_label *label)
951 self->target = label;
954 ast_state* ast_state_new(lex_ctx_t ctx, ast_expression *frame, ast_expression *think)
956 ast_instantiate(ast_state, ctx, ast_state_delete);
957 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_state_codegen);
958 self->framenum = frame;
959 self->nextthink = think;
963 void ast_state_delete(ast_state *self)
966 ast_unref(self->framenum);
968 ast_unref(self->nextthink);
970 ast_expression_delete((ast_expression*)self);
974 ast_call* ast_call_new(lex_ctx_t ctx,
975 ast_expression *funcexpr)
977 ast_instantiate(ast_call, ctx, ast_call_delete);
978 if (!funcexpr->next) {
979 compile_error(ctx, "not a function");
983 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_call_codegen);
985 ast_side_effects(self) = true;
988 self->func = funcexpr;
989 self->va_count = NULL;
991 ast_type_adopt(self, funcexpr->next);
996 void ast_call_delete(ast_call *self)
999 for (i = 0; i < vec_size(self->params); ++i)
1000 ast_unref(self->params[i]);
1001 vec_free(self->params);
1004 ast_unref(self->func);
1007 ast_unref(self->va_count);
1009 ast_expression_delete((ast_expression*)self);
1013 static bool ast_call_check_vararg(ast_call *self, ast_expression *va_type, ast_expression *exp_type)
1019 if (!va_type || !ast_compare_type(va_type, exp_type))
1021 if (va_type && exp_type)
1023 ast_type_to_string(va_type, tgot, sizeof(tgot));
1024 ast_type_to_string(exp_type, texp, sizeof(texp));
1025 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1026 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1027 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1031 compile_error(ast_ctx(self),
1032 "piped variadic argument differs in type: constrained to type %s, expected type %s",
1039 ast_type_to_string(exp_type, texp, sizeof(texp));
1040 if (OPTS_FLAG(UNSAFE_VARARGS)) {
1041 if (compile_warning(ast_ctx(self), WARN_UNSAFE_TYPES,
1042 "piped variadic argument may differ in type: expected type %s",
1046 compile_error(ast_ctx(self),
1047 "piped variadic argument may differ in type: expected type %s",
1056 bool ast_call_check_types(ast_call *self, ast_expression *va_type)
1062 const ast_expression *func = self->func;
1063 size_t count = vec_size(self->params);
1064 if (count > vec_size(func->params))
1065 count = vec_size(func->params);
1067 for (i = 0; i < count; ++i) {
1068 if (ast_istype(self->params[i], ast_argpipe)) {
1069 /* warn about type safety instead */
1071 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1074 if (!ast_call_check_vararg(self, va_type, (ast_expression*)func->params[i]))
1077 else if (!ast_compare_type(self->params[i], (ast_expression*)(func->params[i])))
1079 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1080 ast_type_to_string((ast_expression*)func->params[i], texp, sizeof(texp));
1081 compile_error(ast_ctx(self), "invalid type for parameter %u in function call: expected %s, got %s",
1082 (unsigned int)(i+1), texp, tgot);
1083 /* we don't immediately return */
1087 count = vec_size(self->params);
1088 if (count > vec_size(func->params) && func->varparam) {
1089 for (; i < count; ++i) {
1090 if (ast_istype(self->params[i], ast_argpipe)) {
1091 /* warn about type safety instead */
1093 compile_error(ast_ctx(self), "argpipe must be the last parameter to a function call");
1096 if (!ast_call_check_vararg(self, va_type, func->varparam))
1099 else if (!ast_compare_type(self->params[i], func->varparam))
1101 ast_type_to_string(self->params[i], tgot, sizeof(tgot));
1102 ast_type_to_string(func->varparam, texp, sizeof(texp));
1103 compile_error(ast_ctx(self), "invalid type for variadic parameter %u in function call: expected %s, got %s",
1104 (unsigned int)(i+1), texp, tgot);
1105 /* we don't immediately return */
1113 ast_store* ast_store_new(lex_ctx_t ctx, int op,
1114 ast_expression *dest, ast_expression *source)
1116 ast_instantiate(ast_store, ctx, ast_store_delete);
1117 ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
1119 ast_side_effects(self) = true;
1123 self->source = source;
1125 ast_type_adopt(self, dest);
1130 void ast_store_delete(ast_store *self)
1132 ast_unref(self->dest);
1133 ast_unref(self->source);
1134 ast_expression_delete((ast_expression*)self);
1138 ast_block* ast_block_new(lex_ctx_t ctx)
1140 ast_instantiate(ast_block, ctx, ast_block_delete);
1141 ast_expression_init((ast_expression*)self,
1142 (ast_expression_codegen*)&ast_block_codegen);
1144 self->locals = NULL;
1146 self->collect = NULL;
1151 bool ast_block_add_expr(ast_block *self, ast_expression *e)
1153 ast_propagate_effects(self, e);
1154 vec_push(self->exprs, e);
1155 if (self->expression.next) {
1156 ast_delete(self->expression.next);
1157 self->expression.next = NULL;
1159 ast_type_adopt(self, e);
1163 void ast_block_collect(ast_block *self, ast_expression *expr)
1165 vec_push(self->collect, expr);
1166 expr->node.keep = true;
1169 void ast_block_delete(ast_block *self)
1172 for (i = 0; i < vec_size(self->exprs); ++i)
1173 ast_unref(self->exprs[i]);
1174 vec_free(self->exprs);
1175 for (i = 0; i < vec_size(self->locals); ++i)
1176 ast_delete(self->locals[i]);
1177 vec_free(self->locals);
1178 for (i = 0; i < vec_size(self->collect); ++i)
1179 ast_delete(self->collect[i]);
1180 vec_free(self->collect);
1181 ast_expression_delete((ast_expression*)self);
1185 void ast_block_set_type(ast_block *self, ast_expression *from)
1187 if (self->expression.next)
1188 ast_delete(self->expression.next);
1189 ast_type_adopt(self, from);
1192 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype)
1194 ast_instantiate(ast_function, ctx, ast_function_delete);
1197 compile_error(ast_ctx(self), "internal error: ast_function_new condition 0");
1199 } else if (vtype->hasvalue || vtype->expression.vtype != TYPE_FUNCTION) {
1200 compile_error(ast_ctx(self), "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
1202 (int)vtype->hasvalue,
1203 vtype->expression.vtype);
1207 self->vtype = vtype;
1208 self->name = name ? util_strdup(name) : NULL;
1209 self->blocks = NULL;
1211 self->labelcount = 0;
1214 self->ir_func = NULL;
1215 self->curblock = NULL;
1217 self->breakblocks = NULL;
1218 self->continueblocks = NULL;
1220 vtype->hasvalue = true;
1221 vtype->constval.vfunc = self;
1223 self->varargs = NULL;
1225 self->fixedparams = NULL;
1226 self->return_value = NULL;
1228 self->static_names = NULL;
1229 self->static_count = 0;
1238 void ast_function_delete(ast_function *self)
1242 mem_d((void*)self->name);
1244 /* ast_value_delete(self->vtype); */
1245 self->vtype->hasvalue = false;
1246 self->vtype->constval.vfunc = NULL;
1247 /* We use unref - if it was stored in a global table it is supposed
1248 * to be deleted from *there*
1250 ast_unref(self->vtype);
1252 for (i = 0; i < vec_size(self->static_names); ++i)
1253 mem_d(self->static_names[i]);
1254 vec_free(self->static_names);
1255 for (i = 0; i < vec_size(self->blocks); ++i)
1256 ast_delete(self->blocks[i]);
1257 vec_free(self->blocks);
1258 vec_free(self->breakblocks);
1259 vec_free(self->continueblocks);
1261 ast_delete(self->varargs);
1263 ast_delete(self->argc);
1264 if (self->fixedparams)
1265 ast_unref(self->fixedparams);
1266 if (self->return_value)
1267 ast_unref(self->return_value);
1271 const char* ast_function_label(ast_function *self, const char *prefix)
1277 if (!OPTS_OPTION_BOOL(OPTION_DUMP) &&
1278 !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
1279 !OPTS_OPTION_BOOL(OPTION_DEBUG))
1284 id = (self->labelcount++);
1285 len = strlen(prefix);
1287 from = self->labelbuf + sizeof(self->labelbuf)-1;
1290 *from-- = (id%10) + '0';
1294 memcpy(from - len, prefix, len);
1298 /*********************************************************************/
1300 * by convention you must never pass NULL to the 'ir_value **out'
1301 * parameter. If you really don't care about the output, pass a dummy.
1302 * But I can't imagine a pituation where the output is truly unnecessary.
1305 static void _ast_codegen_output_type(ast_expression *self, ir_value *out)
1307 if (out->vtype == TYPE_FIELD)
1308 out->fieldtype = self->next->vtype;
1309 if (out->vtype == TYPE_FUNCTION)
1310 out->outtype = self->next->vtype;
1313 #define codegen_output_type(a,o) (_ast_codegen_output_type(&((a)->expression),(o)))
1315 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
1319 if (self->expression.vtype == TYPE_NIL) {
1320 *out = func->ir_func->owner->nil;
1323 /* NOTE: This is the codegen for a variable used in an expression.
1324 * It is not the codegen to generate the value. For this purpose,
1325 * ast_local_codegen and ast_global_codegen are to be used before this
1326 * is executed. ast_function_codegen should take care of its locals,
1327 * and the ast-user should take care of ast_global_codegen to be used
1328 * on all the globals.
1331 char tname[1024]; /* typename is reserved in C++ */
1332 ast_type_to_string((ast_expression*)self, tname, sizeof(tname));
1333 compile_error(ast_ctx(self), "ast_value used before generated %s %s", tname, self->name);
1340 static bool ast_global_array_set(ast_value *self)
1342 size_t count = vec_size(self->initlist);
1345 if (count > self->expression.count) {
1346 compile_error(ast_ctx(self), "too many elements in initializer");
1347 count = self->expression.count;
1349 else if (count < self->expression.count) {
1351 compile_warning(ast_ctx(self), "not all elements are initialized");
1355 for (i = 0; i != count; ++i) {
1356 switch (self->expression.next->vtype) {
1358 if (!ir_value_set_float(self->ir_values[i], self->initlist[i].vfloat))
1362 if (!ir_value_set_vector(self->ir_values[i], self->initlist[i].vvec))
1366 if (!ir_value_set_string(self->ir_values[i], self->initlist[i].vstring))
1370 /* we don't support them in any other place yet either */
1371 compile_error(ast_ctx(self), "TODO: nested arrays");
1374 /* this requiers a bit more work - similar to the fields I suppose */
1375 compile_error(ast_ctx(self), "global of type function not properly generated");
1378 if (!self->initlist[i].vfield) {
1379 compile_error(ast_ctx(self), "field constant without vfield set");
1382 if (!self->initlist[i].vfield->ir_v) {
1383 compile_error(ast_ctx(self), "field constant generated before its field");
1386 if (!ir_value_set_field(self->ir_values[i], self->initlist[i].vfield->ir_v))
1390 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1397 static bool check_array(ast_value *self, ast_value *array)
1399 if (array->expression.flags & AST_FLAG_ARRAY_INIT && !array->initlist) {
1400 compile_error(ast_ctx(self), "array without size: %s", self->name);
1403 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1404 if (!array->expression.count || array->expression.count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1405 compile_error(ast_ctx(self), "Invalid array of size %lu", (unsigned long)array->expression.count);
1411 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield)
1415 if (self->expression.vtype == TYPE_NIL) {
1416 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1420 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1422 ir_function *func = ir_builder_create_function(ir, self->name, self->expression.next->vtype);
1425 func->context = ast_ctx(self);
1426 func->value->context = ast_ctx(self);
1428 self->constval.vfunc->ir_func = func;
1429 self->ir_v = func->value;
1430 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1431 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1432 if (self->expression.flags & AST_FLAG_ERASEABLE)
1433 self->ir_v->flags |= IR_FLAG_ERASABLE;
1434 if (self->expression.flags & AST_FLAG_BLOCK_COVERAGE)
1435 func->flags |= IR_FLAG_BLOCK_COVERAGE;
1436 /* The function is filled later on ast_function_codegen... */
1440 if (isfield && self->expression.vtype == TYPE_FIELD) {
1441 ast_expression *fieldtype = self->expression.next;
1443 if (self->hasvalue) {
1444 compile_error(ast_ctx(self), "TODO: constant field pointers with value");
1448 if (fieldtype->vtype == TYPE_ARRAY) {
1453 ast_expression *elemtype;
1455 ast_value *array = (ast_value*)fieldtype;
1457 if (!ast_istype(fieldtype, ast_value)) {
1458 compile_error(ast_ctx(self), "internal error: ast_value required");
1462 if (!check_array(self, array))
1465 elemtype = array->expression.next;
1466 vtype = elemtype->vtype;
1468 v = ir_builder_create_field(ir, self->name, vtype);
1470 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1473 v->context = ast_ctx(self);
1474 v->unique_life = true;
1476 array->ir_v = self->ir_v = v;
1478 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1479 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1480 if (self->expression.flags & AST_FLAG_ERASEABLE)
1481 self->ir_v->flags |= IR_FLAG_ERASABLE;
1483 namelen = strlen(self->name);
1484 name = (char*)mem_a(namelen + 16);
1485 util_strncpy(name, self->name, namelen);
1487 array->ir_values = (ir_value**)mem_a(sizeof(array->ir_values[0]) * array->expression.count);
1488 array->ir_values[0] = v;
1489 for (ai = 1; ai < array->expression.count; ++ai) {
1490 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1491 array->ir_values[ai] = ir_builder_create_field(ir, name, vtype);
1492 if (!array->ir_values[ai]) {
1494 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", name);
1497 array->ir_values[ai]->context = ast_ctx(self);
1498 array->ir_values[ai]->unique_life = true;
1499 array->ir_values[ai]->locked = true;
1500 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1501 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1507 v = ir_builder_create_field(ir, self->name, self->expression.next->vtype);
1510 v->context = ast_ctx(self);
1512 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1513 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1515 if (self->expression.flags & AST_FLAG_ERASEABLE)
1516 self->ir_v->flags |= IR_FLAG_ERASABLE;
1521 if (self->expression.vtype == TYPE_ARRAY) {
1526 ast_expression *elemtype = self->expression.next;
1527 int vtype = elemtype->vtype;
1529 if (self->expression.flags & AST_FLAG_ARRAY_INIT && !self->expression.count) {
1530 compile_error(ast_ctx(self), "array `%s' has no size", self->name);
1534 /* same as with field arrays */
1535 if (!check_array(self, self))
1538 v = ir_builder_create_global(ir, self->name, vtype);
1540 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", self->name);
1543 v->context = ast_ctx(self);
1544 v->unique_life = true;
1547 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1548 v->flags |= IR_FLAG_INCLUDE_DEF;
1549 if (self->expression.flags & AST_FLAG_ERASEABLE)
1550 self->ir_v->flags |= IR_FLAG_ERASABLE;
1552 namelen = strlen(self->name);
1553 name = (char*)mem_a(namelen + 16);
1554 util_strncpy(name, self->name, namelen);
1556 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1557 self->ir_values[0] = v;
1558 for (ai = 1; ai < self->expression.count; ++ai) {
1559 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1560 self->ir_values[ai] = ir_builder_create_global(ir, name, vtype);
1561 if (!self->ir_values[ai]) {
1563 compile_error(ast_ctx(self), "ir_builder_create_global failed `%s`", name);
1566 self->ir_values[ai]->context = ast_ctx(self);
1567 self->ir_values[ai]->unique_life = true;
1568 self->ir_values[ai]->locked = true;
1569 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1570 self->ir_values[ai]->flags |= IR_FLAG_INCLUDE_DEF;
1576 /* Arrays don't do this since there's no "array" value which spans across the
1579 v = ir_builder_create_global(ir, self->name, self->expression.vtype);
1581 compile_error(ast_ctx(self), "ir_builder_create_global failed on `%s`", self->name);
1584 codegen_output_type(self, v);
1585 v->context = ast_ctx(self);
1588 /* link us to the ir_value */
1592 if (self->expression.flags & AST_FLAG_INCLUDE_DEF)
1593 self->ir_v->flags |= IR_FLAG_INCLUDE_DEF;
1594 if (self->expression.flags & AST_FLAG_ERASEABLE)
1595 self->ir_v->flags |= IR_FLAG_ERASABLE;
1598 if (self->hasvalue) {
1599 switch (self->expression.vtype)
1602 if (!ir_value_set_float(v, self->constval.vfloat))
1606 if (!ir_value_set_vector(v, self->constval.vvec))
1610 if (!ir_value_set_string(v, self->constval.vstring))
1614 ast_global_array_set(self);
1617 compile_error(ast_ctx(self), "global of type function not properly generated");
1619 /* Cannot generate an IR value for a function,
1620 * need a pointer pointing to a function rather.
1623 if (!self->constval.vfield) {
1624 compile_error(ast_ctx(self), "field constant without vfield set");
1627 if (!self->constval.vfield->ir_v) {
1628 compile_error(ast_ctx(self), "field constant generated before its field");
1631 if (!ir_value_set_field(v, self->constval.vfield->ir_v))
1635 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1641 error: /* clean up */
1642 if(v) ir_value_delete(v);
1646 static bool ast_local_codegen(ast_value *self, ir_function *func, bool param)
1650 if (self->expression.vtype == TYPE_NIL) {
1651 compile_error(ast_ctx(self), "internal error: trying to generate a variable of TYPE_NIL");
1655 if (self->hasvalue && self->expression.vtype == TYPE_FUNCTION)
1657 /* Do we allow local functions? I think not...
1658 * this is NOT a function pointer atm.
1663 if (self->expression.vtype == TYPE_ARRAY) {
1668 ast_expression *elemtype = self->expression.next;
1669 int vtype = elemtype->vtype;
1671 func->flags |= IR_FLAG_HAS_ARRAYS;
1673 if (param && !(self->expression.flags & AST_FLAG_IS_VARARG)) {
1674 compile_error(ast_ctx(self), "array-parameters are not supported");
1678 /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1679 if (!check_array(self, self))
1682 self->ir_values = (ir_value**)mem_a(sizeof(self->ir_values[0]) * self->expression.count);
1683 if (!self->ir_values) {
1684 compile_error(ast_ctx(self), "failed to allocate array values");
1688 v = ir_function_create_local(func, self->name, vtype, param);
1690 compile_error(ast_ctx(self), "internal error: ir_function_create_local failed");
1693 v->context = ast_ctx(self);
1694 v->unique_life = true;
1697 namelen = strlen(self->name);
1698 name = (char*)mem_a(namelen + 16);
1699 util_strncpy(name, self->name, namelen);
1701 self->ir_values[0] = v;
1702 for (ai = 1; ai < self->expression.count; ++ai) {
1703 util_snprintf(name + namelen, 16, "[%u]", (unsigned int)ai);
1704 self->ir_values[ai] = ir_function_create_local(func, name, vtype, param);
1705 if (!self->ir_values[ai]) {
1706 compile_error(ast_ctx(self), "internal_error: ir_builder_create_global failed on `%s`", name);
1709 self->ir_values[ai]->context = ast_ctx(self);
1710 self->ir_values[ai]->unique_life = true;
1711 self->ir_values[ai]->locked = true;
1717 v = ir_function_create_local(func, self->name, self->expression.vtype, param);
1720 codegen_output_type(self, v);
1721 v->context = ast_ctx(self);
1724 /* A constant local... hmmm...
1725 * I suppose the IR will have to deal with this
1727 if (self->hasvalue) {
1728 switch (self->expression.vtype)
1731 if (!ir_value_set_float(v, self->constval.vfloat))
1735 if (!ir_value_set_vector(v, self->constval.vvec))
1739 if (!ir_value_set_string(v, self->constval.vstring))
1743 compile_error(ast_ctx(self), "TODO: global constant type %i", self->expression.vtype);
1748 /* link us to the ir_value */
1752 if (!ast_generate_accessors(self, func->owner))
1756 error: /* clean up */
1761 bool ast_generate_accessors(ast_value *self, ir_builder *ir)
1764 bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1765 if (!self->setter || !self->getter)
1767 for (i = 0; i < self->expression.count; ++i) {
1768 if (!self->ir_values) {
1769 compile_error(ast_ctx(self), "internal error: no array values generated for `%s`", self->name);
1772 if (!self->ir_values[i]) {
1773 compile_error(ast_ctx(self), "internal error: not all array values have been generated for `%s`", self->name);
1776 if (self->ir_values[i]->life) {
1777 compile_error(ast_ctx(self), "internal error: function containing `%s` already generated", self->name);
1782 opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1784 if (!ast_global_codegen (self->setter, ir, false) ||
1785 !ast_function_codegen(self->setter->constval.vfunc, ir) ||
1786 !ir_function_finalize(self->setter->constval.vfunc->ir_func))
1788 compile_error(ast_ctx(self), "internal error: failed to generate setter for `%s`", self->name);
1789 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1794 if (!ast_global_codegen (self->getter, ir, false) ||
1795 !ast_function_codegen(self->getter->constval.vfunc, ir) ||
1796 !ir_function_finalize(self->getter->constval.vfunc->ir_func))
1798 compile_error(ast_ctx(self), "internal error: failed to generate getter for `%s`", self->name);
1799 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1803 for (i = 0; i < self->expression.count; ++i) {
1804 vec_free(self->ir_values[i]->life);
1806 opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1810 bool ast_function_codegen(ast_function *self, ir_builder *ir)
1815 ast_expression_codegen *cgen;
1821 irf = self->ir_func;
1823 compile_error(ast_ctx(self), "internal error: ast_function's related ast_value was not generated yet");
1827 /* fill the parameter list */
1828 ec = &self->vtype->expression;
1829 for (i = 0; i < vec_size(ec->params); ++i)
1831 if (ec->params[i]->expression.vtype == TYPE_FIELD)
1832 vec_push(irf->params, ec->params[i]->expression.next->vtype);
1834 vec_push(irf->params, ec->params[i]->expression.vtype);
1835 if (!self->builtin) {
1836 if (!ast_local_codegen(ec->params[i], self->ir_func, true))
1841 if (self->varargs) {
1842 if (!ast_local_codegen(self->varargs, self->ir_func, true))
1844 irf->max_varargs = self->varargs->expression.count;
1847 if (self->builtin) {
1848 irf->builtin = self->builtin;
1852 /* have a local return value variable? */
1853 if (self->return_value) {
1854 if (!ast_local_codegen(self->return_value, self->ir_func, false))
1858 if (!vec_size(self->blocks)) {
1859 compile_error(ast_ctx(self), "function `%s` has no body", self->name);
1863 irf->first = self->curblock = ir_function_create_block(ast_ctx(self), irf, "entry");
1864 if (!self->curblock) {
1865 compile_error(ast_ctx(self), "failed to allocate entry block for `%s`", self->name);
1873 if (!ast_local_codegen(self->argc, self->ir_func, true))
1875 cgen = self->argc->expression.codegen;
1876 if (!(*cgen)((ast_expression*)(self->argc), self, false, &va_count))
1878 cgen = self->fixedparams->expression.codegen;
1879 if (!(*cgen)((ast_expression*)(self->fixedparams), self, false, &fixed))
1881 sub = ir_block_create_binop(self->curblock, ast_ctx(self),
1882 ast_function_label(self, "va_count"), INSTR_SUB_F,
1883 ir_builder_get_va_count(ir), fixed);
1886 if (!ir_block_create_store_op(self->curblock, ast_ctx(self), INSTR_STORE_F,
1893 for (i = 0; i < vec_size(self->blocks); ++i) {
1894 cgen = self->blocks[i]->expression.codegen;
1895 if (!(*cgen)((ast_expression*)self->blocks[i], self, false, &dummy))
1899 /* TODO: check return types */
1900 if (!self->curblock->final)
1902 if (!self->vtype->expression.next ||
1903 self->vtype->expression.next->vtype == TYPE_VOID)
1905 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1907 else if (vec_size(self->curblock->entries) || self->curblock == irf->first)
1909 if (self->return_value) {
1910 cgen = self->return_value->expression.codegen;
1911 if (!(*cgen)((ast_expression*)(self->return_value), self, false, &dummy))
1913 return ir_block_create_return(self->curblock, ast_ctx(self), dummy);
1915 else if (compile_warning(ast_ctx(self), WARN_MISSING_RETURN_VALUES,
1916 "control reaches end of non-void function (`%s`) via %s",
1917 self->name, self->curblock->label))
1921 return ir_block_create_return(self->curblock, ast_ctx(self), NULL);
1927 static bool starts_a_label(ast_expression *ex)
1929 while (ex && ast_istype(ex, ast_block)) {
1930 ast_block *b = (ast_block*)ex;
1935 return ast_istype(ex, ast_label);
1938 /* Note, you will not see ast_block_codegen generate ir_blocks.
1939 * To the AST and the IR, blocks are 2 different things.
1940 * In the AST it represents a block of code, usually enclosed in
1941 * curly braces {...}.
1942 * While in the IR it represents a block in terms of control-flow.
1944 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
1948 /* We don't use this
1949 * Note: an ast-representation using the comma-operator
1950 * of the form: (a, b, c) = x should not assign to c...
1953 compile_error(ast_ctx(self), "not an l-value (code-block)");
1957 if (self->expression.outr) {
1958 *out = self->expression.outr;
1962 /* output is NULL at first, we'll have each expression
1963 * assign to out output, thus, a comma-operator represention
1964 * using an ast_block will return the last generated value,
1965 * so: (b, c) + a executed both b and c, and returns c,
1966 * which is then added to a.
1970 /* generate locals */
1971 for (i = 0; i < vec_size(self->locals); ++i)
1973 if (!ast_local_codegen(self->locals[i], func->ir_func, false)) {
1974 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1975 compile_error(ast_ctx(self), "failed to generate local `%s`", self->locals[i]->name);
1980 for (i = 0; i < vec_size(self->exprs); ++i)
1982 ast_expression_codegen *gen;
1983 if (func->curblock->final && !starts_a_label(self->exprs[i])) {
1984 if (compile_warning(ast_ctx(self->exprs[i]), WARN_UNREACHABLE_CODE, "unreachable statement"))
1988 gen = self->exprs[i]->codegen;
1989 if (!(*gen)(self->exprs[i], func, false, out))
1993 self->expression.outr = *out;
1998 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
2000 ast_expression_codegen *cgen;
2001 ir_value *left = NULL;
2002 ir_value *right = NULL;
2006 ast_array_index *ai = NULL;
2008 if (lvalue && self->expression.outl) {
2009 *out = self->expression.outl;
2013 if (!lvalue && self->expression.outr) {
2014 *out = self->expression.outr;
2018 if (ast_istype(self->dest, ast_array_index))
2021 ai = (ast_array_index*)self->dest;
2022 idx = (ast_value*)ai->index;
2024 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2029 /* we need to call the setter */
2030 ir_value *iridx, *funval;
2034 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2038 arr = (ast_value*)ai->array;
2039 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2040 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2044 cgen = idx->expression.codegen;
2045 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2048 cgen = arr->setter->expression.codegen;
2049 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2052 cgen = self->source->codegen;
2053 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2056 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2059 ir_call_param(call, iridx);
2060 ir_call_param(call, right);
2061 self->expression.outr = right;
2067 cgen = self->dest->codegen;
2069 if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
2071 self->expression.outl = left;
2073 cgen = self->source->codegen;
2075 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2078 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->op, left, right))
2080 self->expression.outr = right;
2083 /* Theoretically, an assinment returns its left side as an
2084 * lvalue, if we don't need an lvalue though, we return
2085 * the right side as an rvalue, otherwise we have to
2086 * somehow know whether or not we need to dereference the pointer
2087 * on the left side - that is: OP_LOAD if it was an address.
2088 * Also: in original QC we cannot OP_LOADP *anyway*.
2090 *out = (lvalue ? left : right);
2095 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
2097 ast_expression_codegen *cgen;
2098 ir_value *left, *right;
2100 /* A binary operation cannot yield an l-value */
2102 compile_error(ast_ctx(self), "not an l-value (binop)");
2106 if (self->expression.outr) {
2107 *out = self->expression.outr;
2111 if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
2112 (self->op == INSTR_AND || self->op == INSTR_OR))
2114 /* NOTE: The short-logic path will ignore right_first */
2116 /* short circuit evaluation */
2117 ir_block *other, *merge;
2118 ir_block *from_left, *from_right;
2122 /* prepare end-block */
2123 merge_id = vec_size(func->ir_func->blocks);
2124 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_merge"));
2126 /* generate the left expression */
2127 cgen = self->left->codegen;
2128 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2130 /* remember the block */
2131 from_left = func->curblock;
2133 /* create a new block for the right expression */
2134 other = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "sce_other"));
2135 if (self->op == INSTR_AND) {
2136 /* on AND: left==true -> other */
2137 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, other, merge))
2140 /* on OR: left==false -> other */
2141 if (!ir_block_create_if(func->curblock, ast_ctx(self), left, merge, other))
2144 /* use the likely flag */
2145 vec_last(func->curblock->instr)->likely = true;
2147 /* enter the right-expression's block */
2148 func->curblock = other;
2150 cgen = self->right->codegen;
2151 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2153 /* remember block */
2154 from_right = func->curblock;
2156 /* jump to the merge block */
2157 if (!ir_block_create_jump(func->curblock, ast_ctx(self), merge))
2160 vec_remove(func->ir_func->blocks, merge_id, 1);
2161 vec_push(func->ir_func->blocks, merge);
2163 func->curblock = merge;
2164 phi = ir_block_create_phi(func->curblock, ast_ctx(self),
2165 ast_function_label(func, "sce_value"),
2166 self->expression.vtype);
2167 ir_phi_add(phi, from_left, left);
2168 ir_phi_add(phi, from_right, right);
2169 *out = ir_phi_value(phi);
2173 if (!OPTS_FLAG(PERL_LOGIC)) {
2175 if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->vtype == TYPE_VECTOR) {
2176 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2177 ast_function_label(func, "sce_bool_v"),
2181 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2182 ast_function_label(func, "sce_bool"),
2187 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->vtype == TYPE_STRING) {
2188 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2189 ast_function_label(func, "sce_bool_s"),
2193 *out = ir_block_create_unary(func->curblock, ast_ctx(self),
2194 ast_function_label(func, "sce_bool"),
2200 *out = ir_block_create_binop(func->curblock, ast_ctx(self),
2201 ast_function_label(func, "sce_bool"),
2202 INSTR_AND, *out, *out);
2208 self->expression.outr = *out;
2209 codegen_output_type(self, *out);
2213 if (self->right_first) {
2214 cgen = self->right->codegen;
2215 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2217 cgen = self->left->codegen;
2218 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2221 cgen = self->left->codegen;
2222 if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
2224 cgen = self->right->codegen;
2225 if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
2229 *out = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "bin"),
2230 self->op, left, right);
2233 self->expression.outr = *out;
2234 codegen_output_type(self, *out);
2239 bool ast_binstore_codegen(ast_binstore *self, ast_function *func, bool lvalue, ir_value **out)
2241 ast_expression_codegen *cgen;
2242 ir_value *leftl = NULL, *leftr, *right, *bin;
2246 ast_array_index *ai = NULL;
2247 ir_value *iridx = NULL;
2249 if (lvalue && self->expression.outl) {
2250 *out = self->expression.outl;
2254 if (!lvalue && self->expression.outr) {
2255 *out = self->expression.outr;
2259 if (ast_istype(self->dest, ast_array_index))
2262 ai = (ast_array_index*)self->dest;
2263 idx = (ast_value*)ai->index;
2265 if (ast_istype(ai->index, ast_value) && idx->hasvalue && idx->cvq == CV_CONST)
2269 /* for a binstore we need both an lvalue and an rvalue for the left side */
2270 /* rvalue of destination! */
2272 cgen = idx->expression.codegen;
2273 if (!(*cgen)((ast_expression*)(idx), func, false, &iridx))
2276 cgen = self->dest->codegen;
2277 if (!(*cgen)((ast_expression*)(self->dest), func, false, &leftr))
2280 /* source as rvalue only */
2281 cgen = self->source->codegen;
2282 if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
2285 /* now the binary */
2286 bin = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "binst"),
2287 self->opbin, leftr, right);
2288 self->expression.outr = bin;
2292 /* we need to call the setter */
2297 compile_error(ast_ctx(self), "array-subscript assignment cannot produce lvalues");
2301 arr = (ast_value*)ai->array;
2302 if (!ast_istype(ai->array, ast_value) || !arr->setter) {
2303 compile_error(ast_ctx(self), "value has no setter (%s)", arr->name);
2307 cgen = arr->setter->expression.codegen;
2308 if (!(*cgen)((ast_expression*)(arr->setter), func, true, &funval))
2311 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "store"), funval, false);
2314 ir_call_param(call, iridx);
2315 ir_call_param(call, bin);
2316 self->expression.outr = bin;
2318 /* now store them */
2319 cgen = self->dest->codegen;
2320 /* lvalue of destination */
2321 if (!(*cgen)((ast_expression*)(self->dest), func, true, &leftl))
2323 self->expression.outl = leftl;
2325 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), self->opstore, leftl, bin))
2327 self->expression.outr = bin;
2330 /* Theoretically, an assinment returns its left side as an
2331 * lvalue, if we don't need an lvalue though, we return
2332 * the right side as an rvalue, otherwise we have to
2333 * somehow know whether or not we need to dereference the pointer
2334 * on the left side - that is: OP_LOAD if it was an address.
2335 * Also: in original QC we cannot OP_LOADP *anyway*.
2337 *out = (lvalue ? leftl : bin);
2342 bool ast_unary_codegen(ast_unary *self, ast_function *func, bool lvalue, ir_value **out)
2344 ast_expression_codegen *cgen;
2347 /* An unary operation cannot yield an l-value */
2349 compile_error(ast_ctx(self), "not an l-value (binop)");
2353 if (self->expression.outr) {
2354 *out = self->expression.outr;
2358 cgen = self->operand->codegen;
2360 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2363 *out = ir_block_create_unary(func->curblock, ast_ctx(self), ast_function_label(func, "unary"),
2367 self->expression.outr = *out;
2372 bool ast_return_codegen(ast_return *self, ast_function *func, bool lvalue, ir_value **out)
2374 ast_expression_codegen *cgen;
2379 /* In the context of a return operation, we don't actually return
2383 compile_error(ast_ctx(self), "return-expression is not an l-value");
2387 if (self->expression.outr) {
2388 compile_error(ast_ctx(self), "internal error: ast_return cannot be reused, it bears no result!");
2391 self->expression.outr = (ir_value*)1;
2393 if (self->operand) {
2394 cgen = self->operand->codegen;
2396 if (!(*cgen)((ast_expression*)(self->operand), func, false, &operand))
2399 if (!ir_block_create_return(func->curblock, ast_ctx(self), operand))
2402 if (!ir_block_create_return(func->curblock, ast_ctx(self), NULL))
2409 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
2411 ast_expression_codegen *cgen;
2412 ir_value *ent, *field;
2414 /* This function needs to take the 'lvalue' flag into account!
2415 * As lvalue we provide a field-pointer, as rvalue we provide the
2419 if (lvalue && self->expression.outl) {
2420 *out = self->expression.outl;
2424 if (!lvalue && self->expression.outr) {
2425 *out = self->expression.outr;
2429 cgen = self->entity->codegen;
2430 if (!(*cgen)((ast_expression*)(self->entity), func, false, &ent))
2433 cgen = self->field->codegen;
2434 if (!(*cgen)((ast_expression*)(self->field), func, false, &field))
2439 *out = ir_block_create_fieldaddress(func->curblock, ast_ctx(self), ast_function_label(func, "efa"),
2442 *out = ir_block_create_load_from_ent(func->curblock, ast_ctx(self), ast_function_label(func, "efv"),
2443 ent, field, self->expression.vtype);
2444 /* Done AFTER error checking:
2445 codegen_output_type(self, *out);
2449 compile_error(ast_ctx(self), "failed to create %s instruction (output type %s)",
2450 (lvalue ? "ADDRESS" : "FIELD"),
2451 type_name[self->expression.vtype]);
2455 codegen_output_type(self, *out);
2458 self->expression.outl = *out;
2460 self->expression.outr = *out;
2462 /* Hm that should be it... */
2466 bool ast_member_codegen(ast_member *self, ast_function *func, bool lvalue, ir_value **out)
2468 ast_expression_codegen *cgen;
2471 /* in QC this is always an lvalue */
2472 if (lvalue && self->rvalue) {
2473 compile_error(ast_ctx(self), "not an l-value (member access)");
2476 if (self->expression.outl) {
2477 *out = self->expression.outl;
2481 cgen = self->owner->codegen;
2482 if (!(*cgen)((ast_expression*)(self->owner), func, false, &vec))
2485 if (vec->vtype != TYPE_VECTOR &&
2486 !(vec->vtype == TYPE_FIELD && self->owner->next->vtype == TYPE_VECTOR))
2491 *out = ir_value_vector_member(vec, self->field);
2492 self->expression.outl = *out;
2494 return (*out != NULL);
2497 bool ast_array_index_codegen(ast_array_index *self, ast_function *func, bool lvalue, ir_value **out)
2502 if (!lvalue && self->expression.outr) {
2503 *out = self->expression.outr;
2506 if (lvalue && self->expression.outl) {
2507 *out = self->expression.outl;
2511 if (!ast_istype(self->array, ast_value)) {
2512 compile_error(ast_ctx(self), "array indexing this way is not supported");
2513 /* note this would actually be pointer indexing because the left side is
2514 * not an actual array but (hopefully) an indexable expression.
2515 * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2516 * support this path will be filled.
2521 arr = (ast_value*)self->array;
2522 idx = (ast_value*)self->index;
2524 if (!ast_istype(self->index, ast_value) || !idx->hasvalue || idx->cvq != CV_CONST) {
2525 /* Time to use accessor functions */
2526 ast_expression_codegen *cgen;
2527 ir_value *iridx, *funval;
2531 compile_error(ast_ctx(self), "(.2) array indexing here needs a compile-time constant");
2536 compile_error(ast_ctx(self), "value has no getter, don't know how to index it");
2540 cgen = self->index->codegen;
2541 if (!(*cgen)((ast_expression*)(self->index), func, false, &iridx))
2544 cgen = arr->getter->expression.codegen;
2545 if (!(*cgen)((ast_expression*)(arr->getter), func, true, &funval))
2548 call = ir_block_create_call(func->curblock, ast_ctx(self), ast_function_label(func, "fetch"), funval, false);
2551 ir_call_param(call, iridx);
2553 *out = ir_call_value(call);
2554 self->expression.outr = *out;
2555 (*out)->vtype = self->expression.vtype;
2556 codegen_output_type(self, *out);
2560 if (idx->expression.vtype == TYPE_FLOAT) {
2561 unsigned int arridx = idx->constval.vfloat;
2562 if (arridx >= self->array->count)
2564 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2567 *out = arr->ir_values[arridx];
2569 else if (idx->expression.vtype == TYPE_INTEGER) {
2570 unsigned int arridx = idx->constval.vint;
2571 if (arridx >= self->array->count)
2573 compile_error(ast_ctx(self), "array index out of bounds: %i", arridx);
2576 *out = arr->ir_values[arridx];
2579 compile_error(ast_ctx(self), "array indexing here needs an integer constant");
2582 (*out)->vtype = self->expression.vtype;
2583 codegen_output_type(self, *out);
2587 bool ast_argpipe_codegen(ast_argpipe *self, ast_function *func, bool lvalue, ir_value **out)
2591 compile_error(ast_ctx(self), "argpipe node: not an lvalue");
2596 compile_error(ast_ctx(self), "TODO: argpipe codegen not implemented");
2600 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
2602 ast_expression_codegen *cgen;
2610 ir_block *ontrue_endblock = NULL;
2611 ir_block *onfalse_endblock = NULL;
2612 ir_block *merge = NULL;
2615 /* We don't output any value, thus also don't care about r/lvalue */
2619 if (self->expression.outr) {
2620 compile_error(ast_ctx(self), "internal error: ast_ifthen cannot be reused, it bears no result!");
2623 self->expression.outr = (ir_value*)1;
2625 /* generate the condition */
2626 cgen = self->cond->codegen;
2627 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2629 /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2630 cond = func->curblock;
2632 /* try constant folding away the condition */
2633 if ((fold = fold_cond_ifthen(condval, func, self)) != -1)
2636 if (self->on_true) {
2637 /* create on-true block */
2638 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "ontrue"));
2642 /* enter the block */
2643 func->curblock = ontrue;
2646 cgen = self->on_true->codegen;
2647 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &dummy))
2650 /* we now need to work from the current endpoint */
2651 ontrue_endblock = func->curblock;
2656 if (self->on_false) {
2657 /* create on-false block */
2658 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "onfalse"));
2662 /* enter the block */
2663 func->curblock = onfalse;
2666 cgen = self->on_false->codegen;
2667 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &dummy))
2670 /* we now need to work from the current endpoint */
2671 onfalse_endblock = func->curblock;
2675 /* Merge block were they all merge in to */
2676 if (!ontrue || !onfalse || !ontrue_endblock->final || !onfalse_endblock->final)
2678 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "endif"));
2681 /* add jumps ot the merge block */
2682 if (ontrue && !ontrue_endblock->final && !ir_block_create_jump(ontrue_endblock, ast_ctx(self), merge))
2684 if (onfalse && !onfalse_endblock->final && !ir_block_create_jump(onfalse_endblock, ast_ctx(self), merge))
2687 /* Now enter the merge block */
2688 func->curblock = merge;
2691 /* we create the if here, that way all blocks are ordered :)
2693 if (!ir_block_create_if(cond, ast_ctx(self), condval,
2694 (ontrue ? ontrue : merge),
2695 (onfalse ? onfalse : merge)))
2703 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
2705 ast_expression_codegen *cgen;
2708 ir_value *trueval, *falseval;
2711 ir_block *cond = func->curblock;
2712 ir_block *cond_out = NULL;
2713 ir_block *ontrue, *ontrue_out = NULL;
2714 ir_block *onfalse, *onfalse_out = NULL;
2718 /* Ternary can never create an lvalue... */
2722 /* In theory it shouldn't be possible to pass through a node twice, but
2723 * in case we add any kind of optimization pass for the AST itself, it
2724 * may still happen, thus we remember a created ir_value and simply return one
2725 * if it already exists.
2727 if (self->expression.outr) {
2728 *out = self->expression.outr;
2732 /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2734 /* generate the condition */
2735 func->curblock = cond;
2736 cgen = self->cond->codegen;
2737 if (!(*cgen)((ast_expression*)(self->cond), func, false, &condval))
2739 cond_out = func->curblock;
2741 /* try constant folding away the condition */
2742 if ((fold = fold_cond_ternary(condval, func, self)) != -1)
2745 /* create on-true block */
2746 ontrue = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_T"));
2751 /* enter the block */
2752 func->curblock = ontrue;
2755 cgen = self->on_true->codegen;
2756 if (!(*cgen)((ast_expression*)(self->on_true), func, false, &trueval))
2759 ontrue_out = func->curblock;
2762 /* create on-false block */
2763 onfalse = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_F"));
2768 /* enter the block */
2769 func->curblock = onfalse;
2772 cgen = self->on_false->codegen;
2773 if (!(*cgen)((ast_expression*)(self->on_false), func, false, &falseval))
2776 onfalse_out = func->curblock;
2779 /* create merge block */
2780 merge = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "tern_out"));
2783 /* jump to merge block */
2784 if (!ir_block_create_jump(ontrue_out, ast_ctx(self), merge))
2786 if (!ir_block_create_jump(onfalse_out, ast_ctx(self), merge))
2789 /* create if instruction */
2790 if (!ir_block_create_if(cond_out, ast_ctx(self), condval, ontrue, onfalse))
2793 /* Now enter the merge block */
2794 func->curblock = merge;
2796 /* Here, now, we need a PHI node
2797 * but first some sanity checking...
2799 if (trueval->vtype != falseval->vtype && trueval->vtype != TYPE_NIL && falseval->vtype != TYPE_NIL) {
2800 /* error("ternary with different types on the two sides"); */
2801 compile_error(ast_ctx(self), "internal error: ternary operand types invalid");
2806 phi = ir_block_create_phi(merge, ast_ctx(self), ast_function_label(func, "phi"), self->expression.vtype);
2808 compile_error(ast_ctx(self), "internal error: failed to generate phi node");
2811 ir_phi_add(phi, ontrue_out, trueval);
2812 ir_phi_add(phi, onfalse_out, falseval);
2814 self->expression.outr = ir_phi_value(phi);
2815 *out = self->expression.outr;
2817 codegen_output_type(self, *out);
2822 bool ast_loop_codegen(ast_loop *self, ast_function *func, bool lvalue, ir_value **out)
2824 ast_expression_codegen *cgen;
2826 ir_value *dummy = NULL;
2827 ir_value *precond = NULL;
2828 ir_value *postcond = NULL;
2830 /* Since we insert some jumps "late" so we have blocks
2831 * ordered "nicely", we need to keep track of the actual end-blocks
2832 * of expressions to add the jumps to.
2834 ir_block *bbody = NULL, *end_bbody = NULL;
2835 ir_block *bprecond = NULL, *end_bprecond = NULL;
2836 ir_block *bpostcond = NULL, *end_bpostcond = NULL;
2837 ir_block *bincrement = NULL, *end_bincrement = NULL;
2838 ir_block *bout = NULL, *bin = NULL;
2840 /* let's at least move the outgoing block to the end */
2843 /* 'break' and 'continue' need to be able to find the right blocks */
2844 ir_block *bcontinue = NULL;
2845 ir_block *bbreak = NULL;
2847 ir_block *tmpblock = NULL;
2852 if (self->expression.outr) {
2853 compile_error(ast_ctx(self), "internal error: ast_loop cannot be reused, it bears no result!");
2856 self->expression.outr = (ir_value*)1;
2859 * Should we ever need some kind of block ordering, better make this function
2860 * move blocks around than write a block ordering algorithm later... after all
2861 * the ast and ir should work together, not against each other.
2864 /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2865 * anyway if for example it contains a ternary.
2869 cgen = self->initexpr->codegen;
2870 if (!(*cgen)((ast_expression*)(self->initexpr), func, false, &dummy))
2874 /* Store the block from which we enter this chaos */
2875 bin = func->curblock;
2877 /* The pre-loop condition needs its own block since we
2878 * need to be able to jump to the start of that expression.
2882 bprecond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "pre_loop_cond"));
2886 /* the pre-loop-condition the least important place to 'continue' at */
2887 bcontinue = bprecond;
2890 func->curblock = bprecond;
2893 cgen = self->precond->codegen;
2894 if (!(*cgen)((ast_expression*)(self->precond), func, false, &precond))
2897 end_bprecond = func->curblock;
2899 bprecond = end_bprecond = NULL;
2902 /* Now the next blocks won't be ordered nicely, but we need to
2903 * generate them this early for 'break' and 'continue'.
2905 if (self->increment) {
2906 bincrement = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_increment"));
2909 bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2911 bincrement = end_bincrement = NULL;
2914 if (self->postcond) {
2915 bpostcond = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "post_loop_cond"));
2918 bcontinue = bpostcond; /* postcond comes before the increment */
2920 bpostcond = end_bpostcond = NULL;
2923 bout_id = vec_size(func->ir_func->blocks);
2924 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_loop"));
2929 /* The loop body... */
2930 /* if (self->body) */
2932 bbody = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "loop_body"));
2937 func->curblock = bbody;
2939 vec_push(func->breakblocks, bbreak);
2941 vec_push(func->continueblocks, bcontinue);
2943 vec_push(func->continueblocks, bbody);
2947 cgen = self->body->codegen;
2948 if (!(*cgen)((ast_expression*)(self->body), func, false, &dummy))
2952 end_bbody = func->curblock;
2953 vec_pop(func->breakblocks);
2954 vec_pop(func->continueblocks);
2957 /* post-loop-condition */
2961 func->curblock = bpostcond;
2964 cgen = self->postcond->codegen;
2965 if (!(*cgen)((ast_expression*)(self->postcond), func, false, &postcond))
2968 end_bpostcond = func->curblock;
2971 /* The incrementor */
2972 if (self->increment)
2975 func->curblock = bincrement;
2978 cgen = self->increment->codegen;
2979 if (!(*cgen)((ast_expression*)(self->increment), func, false, &dummy))
2982 end_bincrement = func->curblock;
2985 /* In any case now, we continue from the outgoing block */
2986 func->curblock = bout;
2988 /* Now all blocks are in place */
2989 /* From 'bin' we jump to whatever comes first */
2990 if (bprecond) tmpblock = bprecond;
2991 else tmpblock = bbody; /* can never be null */
2994 else if (bpostcond) tmpblock = bpostcond;
2995 else tmpblock = bout;
2998 if (!ir_block_create_jump(bin, ast_ctx(self), tmpblock))
3004 ir_block *ontrue, *onfalse;
3005 ontrue = bbody; /* can never be null */
3007 /* all of this is dead code
3008 else if (bincrement) ontrue = bincrement;
3009 else ontrue = bpostcond;
3013 if (self->pre_not) {
3018 if (!ir_block_create_if(end_bprecond, ast_ctx(self), precond, ontrue, onfalse))
3025 if (bincrement) tmpblock = bincrement;
3026 else if (bpostcond) tmpblock = bpostcond;
3027 else if (bprecond) tmpblock = bprecond;
3028 else tmpblock = bbody;
3029 if (!end_bbody->final && !ir_block_create_jump(end_bbody, ast_ctx(self), tmpblock))
3033 /* from increment */
3036 if (bpostcond) tmpblock = bpostcond;
3037 else if (bprecond) tmpblock = bprecond;
3038 else if (bbody) tmpblock = bbody;
3039 else tmpblock = bout;
3040 if (!ir_block_create_jump(end_bincrement, ast_ctx(self), tmpblock))
3047 ir_block *ontrue, *onfalse;
3048 if (bprecond) ontrue = bprecond;
3049 else ontrue = bbody; /* can never be null */
3051 /* all of this is dead code
3052 else if (bincrement) ontrue = bincrement;
3053 else ontrue = bpostcond;
3057 if (self->post_not) {
3062 if (!ir_block_create_if(end_bpostcond, ast_ctx(self), postcond, ontrue, onfalse))
3066 /* Move 'bout' to the end */
3067 vec_remove(func->ir_func->blocks, bout_id, 1);
3068 vec_push(func->ir_func->blocks, bout);
3073 bool ast_breakcont_codegen(ast_breakcont *self, ast_function *func, bool lvalue, ir_value **out)
3080 compile_error(ast_ctx(self), "break/continue expression is not an l-value");
3084 if (self->expression.outr) {
3085 compile_error(ast_ctx(self), "internal error: ast_breakcont cannot be reused!");
3088 self->expression.outr = (ir_value*)1;
3090 if (self->is_continue)
3091 target = func->continueblocks[vec_size(func->continueblocks)-1-self->levels];
3093 target = func->breakblocks[vec_size(func->breakblocks)-1-self->levels];
3096 compile_error(ast_ctx(self), "%s is lacking a target block", (self->is_continue ? "continue" : "break"));
3100 if (!ir_block_create_jump(func->curblock, ast_ctx(self), target))
3105 bool ast_switch_codegen(ast_switch *self, ast_function *func, bool lvalue, ir_value **out)
3107 ast_expression_codegen *cgen;
3109 ast_switch_case *def_case = NULL;
3110 ir_block *def_bfall = NULL;
3111 ir_block *def_bfall_to = NULL;
3112 bool set_def_bfall_to = false;
3114 ir_value *dummy = NULL;
3115 ir_value *irop = NULL;
3116 ir_block *bout = NULL;
3117 ir_block *bfall = NULL;
3125 compile_error(ast_ctx(self), "switch expression is not an l-value");
3129 if (self->expression.outr) {
3130 compile_error(ast_ctx(self), "internal error: ast_switch cannot be reused!");
3133 self->expression.outr = (ir_value*)1;
3138 cgen = self->operand->codegen;
3139 if (!(*cgen)((ast_expression*)(self->operand), func, false, &irop))
3142 if (!vec_size(self->cases))
3145 cmpinstr = type_eq_instr[irop->vtype];
3146 if (cmpinstr >= VINSTR_END) {
3147 ast_type_to_string(self->operand, typestr, sizeof(typestr));
3148 compile_error(ast_ctx(self), "invalid type to perform a switch on: %s", typestr);
3152 bout_id = vec_size(func->ir_func->blocks);
3153 bout = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "after_switch"));
3157 /* setup the break block */
3158 vec_push(func->breakblocks, bout);
3160 /* Now create all cases */
3161 for (c = 0; c < vec_size(self->cases); ++c) {
3162 ir_value *cond, *val;
3163 ir_block *bcase, *bnot;
3166 ast_switch_case *swcase = &self->cases[c];
3168 if (swcase->value) {
3169 /* A regular case */
3170 /* generate the condition operand */
3171 cgen = swcase->value->codegen;
3172 if (!(*cgen)((ast_expression*)(swcase->value), func, false, &val))
3174 /* generate the condition */
3175 cond = ir_block_create_binop(func->curblock, ast_ctx(self), ast_function_label(func, "switch_eq"), cmpinstr, irop, val);
3179 bcase = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "case"));
3180 bnot_id = vec_size(func->ir_func->blocks);
3181 bnot = ir_function_create_block(ast_ctx(self), func->ir_func, ast_function_label(func, "not_case"));
3182 if (!bcase || !bnot)
3184 if (set_def_bfall_to) {
3185 set_def_bfall_to = false;
3186 def_bfall_to = bcase;
3188 if (!ir_block_create_if(func->curblock, ast_ctx(self), cond, bcase, bnot))
3191 /* Make the previous case-end fall through */
3192 if (bfall && !bfall->final) {
3193 if (!ir_block_create_jump(bfall, ast_ctx(self), bcase))
3197 /* enter the case */
3198 func->curblock = bcase;
3199 cgen = swcase->code->codegen;
3200 if (!(*cgen)((ast_expression*)swcase->code, func, false, &dummy))
3203 /* remember this block to fall through from */
3204 bfall = func->curblock;
3206 /* enter the else and move it down */
3207 func->curblock = bnot;
3208 vec_remove(func->ir_func->blocks, bnot_id, 1);
3209 vec_push(func->ir_func->blocks, bnot);
3211 /* The default case */
3212 /* Remember where to fall through from: */
3215 /* remember which case it was */
3217 /* And the next case will be remembered */
3218 set_def_bfall_to = true;
3222 /* Jump from the last bnot to bout */
3223 if (bfall && !bfall->final && !ir_block_create_jump(bfall, ast_ctx(self), bout)) {
3225 astwarning(ast_ctx(bfall), WARN_???, "missing break after last case");
3230 /* If there was a default case, put it down here */
3234 /* No need to create an extra block */
3235 bcase = func->curblock;
3237 /* Insert the fallthrough jump */
3238 if (def_bfall && !def_bfall->final) {
3239 if (!ir_block_create_jump(def_bfall, ast_ctx(self), bcase))
3243 /* Now generate the default code */
3244 cgen = def_case->code->codegen;
3245 if (!(*cgen)((ast_expression*)def_case->code, func, false, &dummy))
3248 /* see if we need to fall through */
3249 if (def_bfall_to && !func->curblock->final)
3251 if (!ir_block_create_jump(func->curblock, ast_ctx(self), def_bfall_to))
3256 /* Jump from the last bnot to bout */
3257 if (!func->curblock->final && !ir_block_create_jump(func->curblock, ast_ctx(self), bout))
3259 /* enter the outgoing block */
3260 func->curblock = bout;
3262 /* restore the break block */
3263 vec_pop(func->breakblocks);
3265 /* Move 'bout' to the end, it's nicer */
3266 vec_remove(func->ir_func->blocks, bout_id, 1);
3267 vec_push(func->ir_func->blocks, bout);
3272 bool ast_label_codegen(ast_label *self, ast_function *func, bool lvalue, ir_value **out)
3277 if (self->undefined) {
3278 compile_error(ast_ctx(self), "internal error: ast_label never defined");
3284 compile_error(ast_ctx(self), "internal error: ast_label cannot be an lvalue");
3288 /* simply create a new block and jump to it */
3289 self->irblock = ir_function_create_block(ast_ctx(self), func->ir_func, self->name);
3290 if (!self->irblock) {
3291 compile_error(ast_ctx(self), "failed to allocate label block `%s`", self->name);
3294 if (!func->curblock->final) {
3295 if (!ir_block_create_jump(func->curblock, ast_ctx(self), self->irblock))
3299 /* enter the new block */
3300 func->curblock = self->irblock;
3302 /* Generate all the leftover gotos */
3303 for (i = 0; i < vec_size(self->gotos); ++i) {
3304 if (!ast_goto_codegen(self->gotos[i], func, false, &dummy))
3311 bool ast_goto_codegen(ast_goto *self, ast_function *func, bool lvalue, ir_value **out)
3315 compile_error(ast_ctx(self), "internal error: ast_goto cannot be an lvalue");
3319 if (self->target->irblock) {
3320 if (self->irblock_from) {
3321 /* we already tried once, this is the callback */
3322 self->irblock_from->final = false;
3323 if (!ir_block_create_goto(self->irblock_from, ast_ctx(self), self->target->irblock)) {
3324 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3330 if (!ir_block_create_goto(func->curblock, ast_ctx(self), self->target->irblock)) {
3331 compile_error(ast_ctx(self), "failed to generate goto to `%s`", self->name);
3338 /* the target has not yet been created...
3339 * close this block in a sneaky way:
3341 func->curblock->final = true;
3342 self->irblock_from = func->curblock;
3343 ast_label_register_goto(self->target, self);
3350 bool ast_state_codegen(ast_state *self, ast_function *func, bool lvalue, ir_value **out)
3352 ast_expression_codegen *cgen;
3354 ir_value *frameval, *thinkval;
3357 compile_error(ast_ctx(self), "not an l-value (state operation)");
3360 if (self->expression.outr) {
3361 compile_error(ast_ctx(self), "internal error: ast_state cannot be reused!");
3366 cgen = self->framenum->codegen;
3367 if (!(*cgen)((ast_expression*)(self->framenum), func, false, &frameval))
3372 cgen = self->nextthink->codegen;
3373 if (!(*cgen)((ast_expression*)(self->nextthink), func, false, &thinkval))
3378 if (!ir_block_create_state_op(func->curblock, ast_ctx(self), frameval, thinkval)) {
3379 compile_error(ast_ctx(self), "failed to create STATE instruction");
3383 self->expression.outr = (ir_value*)1;
3387 bool ast_call_codegen(ast_call *self, ast_function *func, bool lvalue, ir_value **out)
3389 ast_expression_codegen *cgen;
3391 ir_instr *callinstr;
3394 ir_value *funval = NULL;
3396 /* return values are never lvalues */
3398 compile_error(ast_ctx(self), "not an l-value (function call)");
3402 if (self->expression.outr) {
3403 *out = self->expression.outr;
3407 cgen = self->func->codegen;
3408 if (!(*cgen)((ast_expression*)(self->func), func, false, &funval))
3416 for (i = 0; i < vec_size(self->params); ++i)
3419 ast_expression *expr = self->params[i];
3421 cgen = expr->codegen;
3422 if (!(*cgen)(expr, func, false, ¶m))
3426 vec_push(params, param);
3429 /* varargs counter */
3430 if (self->va_count) {
3432 ir_builder *builder = func->curblock->owner->owner;
3433 cgen = self->va_count->codegen;
3434 if (!(*cgen)((ast_expression*)(self->va_count), func, false, &va_count))
3436 if (!ir_block_create_store_op(func->curblock, ast_ctx(self), INSTR_STORE_F,
3437 ir_builder_get_va_count(builder), va_count))
3443 callinstr = ir_block_create_call(func->curblock, ast_ctx(self),
3444 ast_function_label(func, "call"),
3445 funval, !!(self->func->flags & AST_FLAG_NORETURN));
3449 for (i = 0; i < vec_size(params); ++i) {
3450 ir_call_param(callinstr, params[i]);
3453 *out = ir_call_value(callinstr);
3454 self->expression.outr = *out;
3456 codegen_output_type(self, *out);