5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 * this software and associated documentation files (the "Software"), to deal in
7 * the Software without restriction, including without limitation the rights to
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9 * of the Software, and to permit persons to whom the Software is furnished to do
10 * so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 /***********************************************************************
29 * Type sizes used at multiple points in the IR codegen
32 size_t type_sizeof[TYPE_COUNT] = {
39 1, /* TYPE_FUNCTION */
47 uint16_t type_store_instr[TYPE_COUNT] = {
48 INSTR_STORE_F, /* should use I when having integer support */
55 INSTR_STORE_ENT, /* should use I */
57 INSTR_STORE_ENT, /* integer type */
59 INSTR_STORE_V, /* variant, should never be accessed */
62 MEM_VEC_FUNCTIONS(ir_value_vector, ir_value*, v)
64 /***********************************************************************
68 ir_builder* ir_builder_new(const char *modulename)
72 self = (ir_builder*)mem_a(sizeof(*self));
76 MEM_VECTOR_INIT(self, functions);
77 MEM_VECTOR_INIT(self, globals);
79 if (!ir_builder_set_name(self, modulename)) {
84 /* globals which always exist */
86 /* for now we give it a vector size */
87 ir_builder_create_global(self, "OFS_RETURN", TYPE_VARIANT);
92 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
93 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
95 void ir_builder_delete(ir_builder* self)
98 mem_d((void*)self->name);
99 for (i = 0; i != self->functions_count; ++i) {
100 ir_function_delete(self->functions[i]);
102 MEM_VECTOR_CLEAR(self, functions);
103 for (i = 0; i != self->globals_count; ++i) {
104 ir_value_delete(self->globals[i]);
106 MEM_VECTOR_CLEAR(self, globals);
110 bool ir_builder_set_name(ir_builder *self, const char *name)
113 mem_d((void*)self->name);
114 self->name = util_strdup(name);
118 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
121 for (i = 0; i < self->functions_count; ++i) {
122 if (!strcmp(name, self->functions[i]->name))
123 return self->functions[i];
128 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
130 ir_function *fn = ir_builder_get_function(self, name);
135 fn = ir_function_new(self, outtype);
136 if (!ir_function_set_name(fn, name) ||
137 !ir_builder_functions_add(self, fn) )
139 ir_function_delete(fn);
143 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
145 ir_function_delete(fn);
149 fn->value->isconst = true;
150 fn->value->outtype = outtype;
151 fn->value->constval.vfunc = fn;
152 fn->value->context = fn->context;
157 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
160 for (i = 0; i < self->globals_count; ++i) {
161 if (!strcmp(self->globals[i]->name, name))
162 return self->globals[i];
167 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
169 ir_value *ve = ir_builder_get_global(self, name);
174 ve = ir_value_var(name, store_global, vtype);
175 if (!ir_builder_globals_add(self, ve)) {
182 /***********************************************************************
186 bool ir_function_naive_phi(ir_function*);
187 void ir_function_enumerate(ir_function*);
188 bool ir_function_calculate_liferanges(ir_function*);
189 bool ir_function_allocate_locals(ir_function*);
191 ir_function* ir_function_new(ir_builder* owner, int outtype)
194 self = (ir_function*)mem_a(sizeof(*self));
200 if (!ir_function_set_name(self, "<@unnamed>")) {
205 self->context.file = "<@no context>";
206 self->context.line = 0;
207 self->outtype = outtype;
210 MEM_VECTOR_INIT(self, params);
211 MEM_VECTOR_INIT(self, blocks);
212 MEM_VECTOR_INIT(self, values);
213 MEM_VECTOR_INIT(self, locals);
218 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
219 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
220 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
221 MEM_VEC_FUNCTIONS(ir_function, int, params)
223 bool ir_function_set_name(ir_function *self, const char *name)
226 mem_d((void*)self->name);
227 self->name = util_strdup(name);
231 void ir_function_delete(ir_function *self)
234 mem_d((void*)self->name);
236 for (i = 0; i != self->blocks_count; ++i)
237 ir_block_delete(self->blocks[i]);
238 MEM_VECTOR_CLEAR(self, blocks);
240 MEM_VECTOR_CLEAR(self, params);
242 for (i = 0; i != self->values_count; ++i)
243 ir_value_delete(self->values[i]);
244 MEM_VECTOR_CLEAR(self, values);
246 for (i = 0; i != self->locals_count; ++i)
247 ir_value_delete(self->locals[i]);
248 MEM_VECTOR_CLEAR(self, locals);
250 /* self->value is deleted by the builder */
255 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
257 return ir_function_values_add(self, v);
260 ir_block* ir_function_create_block(ir_function *self, const char *label)
262 ir_block* bn = ir_block_new(self, label);
263 memcpy(&bn->context, &self->context, sizeof(self->context));
264 if (!ir_function_blocks_add(self, bn)) {
271 bool ir_function_finalize(ir_function *self)
276 if (!ir_function_naive_phi(self))
279 ir_function_enumerate(self);
281 if (!ir_function_calculate_liferanges(self))
284 if (!ir_function_allocate_locals(self))
289 ir_value* ir_function_get_local(ir_function *self, const char *name)
292 for (i = 0; i < self->locals_count; ++i) {
293 if (!strcmp(self->locals[i]->name, name))
294 return self->locals[i];
299 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype)
301 ir_value *ve = ir_function_get_local(self, name);
306 ve = ir_value_var(name, store_local, vtype);
307 if (!ir_function_locals_add(self, ve)) {
314 /***********************************************************************
318 ir_block* ir_block_new(ir_function* owner, const char *name)
321 self = (ir_block*)mem_a(sizeof(*self));
325 memset(self, 0, sizeof(*self));
328 if (!ir_block_set_label(self, name)) {
333 self->context.file = "<@no context>";
334 self->context.line = 0;
336 MEM_VECTOR_INIT(self, instr);
337 MEM_VECTOR_INIT(self, entries);
338 MEM_VECTOR_INIT(self, exits);
341 self->is_return = false;
343 MEM_VECTOR_INIT(self, living);
345 self->generated = false;
349 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
350 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
351 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
352 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
354 void ir_block_delete(ir_block* self)
358 for (i = 0; i != self->instr_count; ++i)
359 ir_instr_delete(self->instr[i]);
360 MEM_VECTOR_CLEAR(self, instr);
361 MEM_VECTOR_CLEAR(self, entries);
362 MEM_VECTOR_CLEAR(self, exits);
363 MEM_VECTOR_CLEAR(self, living);
367 bool ir_block_set_label(ir_block *self, const char *name)
370 mem_d((void*)self->label);
371 self->label = util_strdup(name);
372 return !!self->label;
375 /***********************************************************************
379 ir_instr* ir_instr_new(ir_block* owner, int op)
382 self = (ir_instr*)mem_a(sizeof(*self));
387 self->context.file = "<@no context>";
388 self->context.line = 0;
390 self->_ops[0] = NULL;
391 self->_ops[1] = NULL;
392 self->_ops[2] = NULL;
393 self->bops[0] = NULL;
394 self->bops[1] = NULL;
395 MEM_VECTOR_INIT(self, phi);
396 MEM_VECTOR_INIT(self, params);
401 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
402 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
404 void ir_instr_delete(ir_instr *self)
407 /* The following calls can only delete from
408 * vectors, we still want to delete this instruction
409 * so ignore the return value. Since with the warn_unused_result attribute
410 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
411 * I have to improvise here and use if(foo());
413 for (i = 0; i < self->phi_count; ++i) {
415 if (ir_value_writes_find(self->phi[i].value, self, &idx))
416 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
417 if (ir_value_reads_find(self->phi[i].value, self, &idx))
418 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
420 MEM_VECTOR_CLEAR(self, phi);
421 for (i = 0; i < self->params_count; ++i) {
423 if (ir_value_writes_find(self->params[i], self, &idx))
424 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
425 if (ir_value_reads_find(self->params[i], self, &idx))
426 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
428 MEM_VECTOR_CLEAR(self, params);
429 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
430 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
431 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
435 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
437 if (self->_ops[op]) {
439 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
441 if (!ir_value_writes_remove(self->_ops[op], idx))
444 else if (ir_value_reads_find(self->_ops[op], self, &idx))
446 if (!ir_value_reads_remove(self->_ops[op], idx))
452 if (!ir_value_writes_add(v, self))
455 if (!ir_value_reads_add(v, self))
463 /***********************************************************************
467 ir_value* ir_value_var(const char *name, int storetype, int vtype)
470 self = (ir_value*)mem_a(sizeof(*self));
472 self->fieldtype = TYPE_VOID;
473 self->outtype = TYPE_VOID;
474 self->store = storetype;
475 MEM_VECTOR_INIT(self, reads);
476 MEM_VECTOR_INIT(self, writes);
477 self->isconst = false;
478 self->context.file = "<@no context>";
479 self->context.line = 0;
481 ir_value_set_name(self, name);
483 memset(&self->constval, 0, sizeof(self->constval));
484 memset(&self->code, 0, sizeof(self->code));
486 MEM_VECTOR_INIT(self, life);
489 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
490 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
491 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
493 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
495 ir_value *v = ir_value_var(name, storetype, vtype);
498 if (!ir_function_collect_value(owner, v))
506 void ir_value_delete(ir_value* self)
509 mem_d((void*)self->name);
512 if (self->vtype == TYPE_STRING)
513 mem_d((void*)self->constval.vstring);
515 MEM_VECTOR_CLEAR(self, reads);
516 MEM_VECTOR_CLEAR(self, writes);
517 MEM_VECTOR_CLEAR(self, life);
521 void ir_value_set_name(ir_value *self, const char *name)
524 mem_d((void*)self->name);
525 self->name = util_strdup(name);
528 bool ir_value_set_float(ir_value *self, float f)
530 if (self->vtype != TYPE_FLOAT)
532 self->constval.vfloat = f;
533 self->isconst = true;
537 bool ir_value_set_func(ir_value *self, int f)
539 if (self->vtype != TYPE_FUNCTION)
541 self->constval.vint = f;
542 self->isconst = true;
546 bool ir_value_set_vector(ir_value *self, vector v)
548 if (self->vtype != TYPE_VECTOR)
550 self->constval.vvec = v;
551 self->isconst = true;
555 bool ir_value_set_string(ir_value *self, const char *str)
557 if (self->vtype != TYPE_STRING)
559 self->constval.vstring = util_strdup(str);
560 self->isconst = true;
565 bool ir_value_set_int(ir_value *self, int i)
567 if (self->vtype != TYPE_INTEGER)
569 self->constval.vint = i;
570 self->isconst = true;
575 bool ir_value_lives(ir_value *self, size_t at)
578 for (i = 0; i < self->life_count; ++i)
580 ir_life_entry_t *life = &self->life[i];
581 if (life->start <= at && at <= life->end)
583 if (life->start > at) /* since it's ordered */
589 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
592 if (!ir_value_life_add(self, e)) /* naive... */
594 for (k = self->life_count-1; k > idx; --k)
595 self->life[k] = self->life[k-1];
600 bool ir_value_life_merge(ir_value *self, size_t s)
603 ir_life_entry_t *life = NULL;
604 ir_life_entry_t *before = NULL;
605 ir_life_entry_t new_entry;
607 /* Find the first range >= s */
608 for (i = 0; i < self->life_count; ++i)
611 life = &self->life[i];
615 /* nothing found? append */
616 if (i == self->life_count) {
618 if (life && life->end+1 == s)
620 /* previous life range can be merged in */
624 if (life && life->end >= s)
627 if (!ir_value_life_add(self, e))
628 return false; /* failing */
634 if (before->end + 1 == s &&
635 life->start - 1 == s)
638 before->end = life->end;
639 if (!ir_value_life_remove(self, i))
640 return false; /* failing */
643 if (before->end + 1 == s)
649 /* already contained */
650 if (before->end >= s)
654 if (life->start - 1 == s)
659 /* insert a new entry */
660 new_entry.start = new_entry.end = s;
661 return ir_value_life_insert(self, i, new_entry);
664 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
668 if (!other->life_count)
671 if (!self->life_count) {
672 for (i = 0; i < other->life_count; ++i) {
673 if (!ir_value_life_add(self, other->life[i]))
680 for (i = 0; i < other->life_count; ++i)
682 const ir_life_entry_t *life = &other->life[i];
685 ir_life_entry_t *entry = &self->life[myi];
687 if (life->end+1 < entry->start)
689 /* adding an interval before entry */
690 if (!ir_value_life_insert(self, myi, *life))
696 if (life->start < entry->start &&
697 life->end >= entry->start)
699 /* starts earlier and overlaps */
700 entry->start = life->start;
703 if (life->end > entry->end &&
704 life->start-1 <= entry->end)
706 /* ends later and overlaps */
707 entry->end = life->end;
710 /* see if our change combines it with the next ranges */
711 while (myi+1 < self->life_count &&
712 entry->end+1 >= self->life[1+myi].start)
714 /* overlaps with (myi+1) */
715 if (entry->end < self->life[1+myi].end)
716 entry->end = self->life[1+myi].end;
717 if (!ir_value_life_remove(self, myi+1))
719 entry = &self->life[myi];
722 /* see if we're after the entry */
723 if (life->start > entry->end)
726 /* append if we're at the end */
727 if (myi >= self->life_count) {
728 if (!ir_value_life_add(self, *life))
732 /* otherweise check the next range */
741 bool ir_values_overlap(const ir_value *a, const ir_value *b)
743 /* For any life entry in A see if it overlaps with
744 * any life entry in B.
745 * Note that the life entries are orderes, so we can make a
746 * more efficient algorithm there than naively translating the
750 ir_life_entry_t *la, *lb, *enda, *endb;
752 /* first of all, if either has no life range, they cannot clash */
753 if (!a->life_count || !b->life_count)
758 enda = la + a->life_count;
759 endb = lb + b->life_count;
762 /* check if the entries overlap, for that,
763 * both must start before the other one ends.
765 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
766 if (la->start <= lb->end &&
767 lb->start <= la->end)
769 if (la->start < lb->end &&
776 /* entries are ordered
777 * one entry is earlier than the other
778 * that earlier entry will be moved forward
780 if (la->start < lb->start)
782 /* order: A B, move A forward
783 * check if we hit the end with A
788 else if (lb->start < la->start)
790 /* order: B A, move B forward
791 * check if we hit the end with B
800 /***********************************************************************
804 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
806 if (target->store == store_value) {
807 fprintf(stderr, "cannot store to an SSA value\n");
808 fprintf(stderr, "trying to store: %s <- %s\n", target->name, what->name);
811 ir_instr *in = ir_instr_new(self, op);
814 if (!ir_instr_op(in, 0, target, true) ||
815 !ir_instr_op(in, 1, what, false) ||
816 !ir_block_instr_add(self, in) )
824 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
828 if (target->vtype == TYPE_VARIANT)
831 vtype = target->vtype;
836 if (what->vtype == TYPE_INTEGER)
837 op = INSTR_CONV_ITOF;
846 op = INSTR_STORE_ENT;
852 op = INSTR_STORE_FLD;
856 if (what->vtype == TYPE_INTEGER)
857 op = INSTR_CONV_FTOI;
866 op = INSTR_STORE_ENT;
873 return ir_block_create_store_op(self, op, target, what);
876 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
881 if (target->vtype != TYPE_POINTER)
884 /* storing using pointer - target is a pointer, type must be
885 * inferred from source
897 op = INSTR_STOREP_ENT;
903 op = INSTR_STOREP_FLD;
914 op = INSTR_STOREP_ENT;
921 return ir_block_create_store_op(self, op, target, what);
924 bool ir_block_create_return(ir_block *self, ir_value *v)
928 fprintf(stderr, "block already ended (%s)\n", self->label);
932 self->is_return = true;
933 in = ir_instr_new(self, INSTR_RETURN);
937 if (!ir_instr_op(in, 0, v, false) ||
938 !ir_block_instr_add(self, in) )
945 bool ir_block_create_if(ir_block *self, ir_value *v,
946 ir_block *ontrue, ir_block *onfalse)
950 fprintf(stderr, "block already ended (%s)\n", self->label);
954 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
955 in = ir_instr_new(self, VINSTR_COND);
959 if (!ir_instr_op(in, 0, v, false)) {
964 in->bops[0] = ontrue;
965 in->bops[1] = onfalse;
967 if (!ir_block_instr_add(self, in))
970 if (!ir_block_exits_add(self, ontrue) ||
971 !ir_block_exits_add(self, onfalse) ||
972 !ir_block_entries_add(ontrue, self) ||
973 !ir_block_entries_add(onfalse, self) )
980 bool ir_block_create_jump(ir_block *self, ir_block *to)
984 fprintf(stderr, "block already ended (%s)\n", self->label);
988 in = ir_instr_new(self, VINSTR_JUMP);
993 if (!ir_block_instr_add(self, in))
996 if (!ir_block_exits_add(self, to) ||
997 !ir_block_entries_add(to, self) )
1004 bool ir_block_create_goto(ir_block *self, ir_block *to)
1008 fprintf(stderr, "block already ended (%s)\n", self->label);
1012 in = ir_instr_new(self, INSTR_GOTO);
1017 if (!ir_block_instr_add(self, in))
1020 if (!ir_block_exits_add(self, to) ||
1021 !ir_block_entries_add(to, self) )
1028 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1032 in = ir_instr_new(self, VINSTR_PHI);
1035 out = ir_value_out(self->owner, label, store_value, ot);
1037 ir_instr_delete(in);
1040 if (!ir_instr_op(in, 0, out, true)) {
1041 ir_instr_delete(in);
1042 ir_value_delete(out);
1045 if (!ir_block_instr_add(self, in)) {
1046 ir_instr_delete(in);
1047 ir_value_delete(out);
1053 ir_value* ir_phi_value(ir_instr *self)
1055 return self->_ops[0];
1058 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1062 if (!ir_block_entries_find(self->owner, b, NULL)) {
1063 /* Must not be possible to cause this, otherwise the AST
1064 * is doing something wrong.
1066 fprintf(stderr, "Invalid entry block for PHI\n");
1072 if (!ir_value_reads_add(v, self))
1074 return ir_instr_phi_add(self, pe);
1077 /* call related code */
1078 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1082 in = ir_instr_new(self, INSTR_CALL0);
1085 out = ir_value_out(self->owner, label, store_return, func->outtype);
1087 ir_instr_delete(in);
1090 if (!ir_instr_op(in, 0, out, true) ||
1091 !ir_instr_op(in, 1, func, false) ||
1092 !ir_block_instr_add(self, in))
1094 ir_instr_delete(in);
1095 ir_value_delete(out);
1101 ir_value* ir_call_value(ir_instr *self)
1103 return self->_ops[0];
1106 bool ir_call_param(ir_instr* self, ir_value *v)
1108 if (!ir_instr_params_add(self, v))
1110 if (!ir_value_reads_add(v, self)) {
1111 if (!ir_instr_params_remove(self, self->params_count-1))
1112 GMQCC_SUPPRESS_EMPTY_BODY;
1118 /* binary op related code */
1120 ir_value* ir_block_create_binop(ir_block *self,
1121 const char *label, int opcode,
1122 ir_value *left, ir_value *right)
1144 case INSTR_SUB_S: /* -- offset of string as float */
1149 case INSTR_BITOR_IF:
1150 case INSTR_BITOR_FI:
1151 case INSTR_BITAND_FI:
1152 case INSTR_BITAND_IF:
1167 case INSTR_BITAND_I:
1170 case INSTR_RSHIFT_I:
1171 case INSTR_LSHIFT_I:
1193 /* boolean operations result in floats */
1194 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1196 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1199 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1204 if (ot == TYPE_VOID) {
1205 /* The AST or parser were supposed to check this! */
1209 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1212 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1213 int op, ir_value *a, ir_value *b, int outype)
1218 out = ir_value_out(self->owner, label, store_value, outype);
1222 instr = ir_instr_new(self, op);
1224 ir_value_delete(out);
1228 if (!ir_instr_op(instr, 0, out, true) ||
1229 !ir_instr_op(instr, 1, a, false) ||
1230 !ir_instr_op(instr, 2, b, false) )
1235 if (!ir_block_instr_add(self, instr))
1240 ir_instr_delete(instr);
1241 ir_value_delete(out);
1245 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1247 /* Support for various pointer types todo if so desired */
1248 if (ent->vtype != TYPE_ENTITY)
1251 if (field->vtype != TYPE_FIELD)
1254 return ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1257 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1260 if (ent->vtype != TYPE_ENTITY)
1263 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1264 if (field->vtype != TYPE_FIELD)
1269 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1270 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1271 case TYPE_STRING: op = INSTR_LOAD_S; break;
1272 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1273 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1275 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1276 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1282 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1285 ir_value* ir_block_create_add(ir_block *self,
1287 ir_value *left, ir_value *right)
1290 int l = left->vtype;
1291 int r = right->vtype;
1310 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1312 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1318 return ir_block_create_binop(self, label, op, left, right);
1321 ir_value* ir_block_create_sub(ir_block *self,
1323 ir_value *left, ir_value *right)
1326 int l = left->vtype;
1327 int r = right->vtype;
1347 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1349 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1355 return ir_block_create_binop(self, label, op, left, right);
1358 ir_value* ir_block_create_mul(ir_block *self,
1360 ir_value *left, ir_value *right)
1363 int l = left->vtype;
1364 int r = right->vtype;
1383 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1385 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1388 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1390 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1392 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1394 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1400 return ir_block_create_binop(self, label, op, left, right);
1403 ir_value* ir_block_create_div(ir_block *self,
1405 ir_value *left, ir_value *right)
1408 int l = left->vtype;
1409 int r = right->vtype;
1426 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1428 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1430 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1436 return ir_block_create_binop(self, label, op, left, right);
1439 /* PHI resolving breaks the SSA, and must thus be the last
1440 * step before life-range calculation.
1443 static bool ir_block_naive_phi(ir_block *self);
1444 bool ir_function_naive_phi(ir_function *self)
1448 for (i = 0; i < self->blocks_count; ++i)
1450 if (!ir_block_naive_phi(self->blocks[i]))
1456 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1461 /* create a store */
1462 if (!ir_block_create_store(block, old, what))
1465 /* we now move it up */
1466 instr = block->instr[block->instr_count-1];
1467 for (i = block->instr_count; i > iid; --i)
1468 block->instr[i] = block->instr[i-1];
1469 block->instr[i] = instr;
1474 static bool ir_block_naive_phi(ir_block *self)
1477 /* FIXME: optionally, create_phi can add the phis
1478 * to a list so we don't need to loop through blocks
1479 * - anyway: "don't optimize YET"
1481 for (i = 0; i < self->instr_count; ++i)
1483 ir_instr *instr = self->instr[i];
1484 if (instr->opcode != VINSTR_PHI)
1487 if (!ir_block_instr_remove(self, i))
1489 --i; /* NOTE: i+1 below */
1491 for (p = 0; p < instr->phi_count; ++p)
1493 ir_value *v = instr->phi[p].value;
1494 for (w = 0; w < v->writes_count; ++w) {
1497 if (!v->writes[w]->_ops[0])
1500 /* When the write was to a global, we have to emit a mov */
1501 old = v->writes[w]->_ops[0];
1503 /* The original instruction now writes to the PHI target local */
1504 if (v->writes[w]->_ops[0] == v)
1505 v->writes[w]->_ops[0] = instr->_ops[0];
1507 if (old->store != store_value && old->store != store_local)
1509 /* If it originally wrote to a global we need to store the value
1512 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1514 if (i+1 < self->instr_count)
1515 instr = self->instr[i+1];
1518 /* In case I forget and access instr later, it'll be NULL
1519 * when it's a problem, to make sure we crash, rather than accessing
1525 /* If it didn't, we can replace all reads by the phi target now. */
1527 for (r = 0; r < old->reads_count; ++r)
1530 ir_instr *ri = old->reads[r];
1531 for (op = 0; op < ri->phi_count; ++op) {
1532 if (ri->phi[op].value == old)
1533 ri->phi[op].value = v;
1535 for (op = 0; op < 3; ++op) {
1536 if (ri->_ops[op] == old)
1543 ir_instr_delete(instr);
1548 /***********************************************************************
1549 *IR Temp allocation code
1550 * Propagating value life ranges by walking through the function backwards
1551 * until no more changes are made.
1552 * In theory this should happen once more than once for every nested loop
1554 * Though this implementation might run an additional time for if nests.
1563 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1565 /* Enumerate instructions used by value's life-ranges
1567 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1571 for (i = 0; i < self->instr_count; ++i)
1573 self->instr[i]->eid = eid++;
1578 /* Enumerate blocks and instructions.
1579 * The block-enumeration is unordered!
1580 * We do not really use the block enumreation, however
1581 * the instruction enumeration is important for life-ranges.
1583 void ir_function_enumerate(ir_function *self)
1586 size_t instruction_id = 0;
1587 for (i = 0; i < self->blocks_count; ++i)
1589 self->blocks[i]->eid = i;
1590 self->blocks[i]->run_id = 0;
1591 ir_block_enumerate(self->blocks[i], &instruction_id);
1595 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1596 bool ir_function_calculate_liferanges(ir_function *self)
1604 for (i = 0; i != self->blocks_count; ++i)
1606 if (self->blocks[i]->is_return)
1608 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1616 /* Local-value allocator
1617 * After finishing creating the liferange of all values used in a function
1618 * we can allocate their global-positions.
1619 * This is the counterpart to register-allocation in register machines.
1622 MEM_VECTOR_MAKE(ir_value*, locals);
1623 MEM_VECTOR_MAKE(size_t, sizes);
1624 MEM_VECTOR_MAKE(size_t, positions);
1625 } function_allocator;
1626 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1627 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1628 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1630 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1633 size_t vsize = type_sizeof[var->vtype];
1635 slot = ir_value_var("reg", store_global, var->vtype);
1639 if (!ir_value_life_merge_into(slot, var))
1642 if (!function_allocator_locals_add(alloc, slot))
1645 if (!function_allocator_sizes_add(alloc, vsize))
1651 ir_value_delete(slot);
1655 bool ir_function_allocate_locals(ir_function *self)
1664 function_allocator alloc;
1666 MEM_VECTOR_INIT(&alloc, locals);
1667 MEM_VECTOR_INIT(&alloc, sizes);
1668 MEM_VECTOR_INIT(&alloc, positions);
1670 for (i = 0; i < self->locals_count; ++i)
1672 if (!function_allocator_alloc(&alloc, self->locals[i]))
1676 /* Allocate a slot for any value that still exists */
1677 for (i = 0; i < self->values_count; ++i)
1679 v = self->values[i];
1684 for (a = 0; a < alloc.locals_count; ++a)
1686 slot = alloc.locals[a];
1688 if (ir_values_overlap(v, slot))
1691 if (!ir_value_life_merge_into(slot, v))
1694 /* adjust size for this slot */
1695 if (alloc.sizes[a] < type_sizeof[v->vtype])
1696 alloc.sizes[a] = type_sizeof[v->vtype];
1698 self->values[i]->code.local = a;
1701 if (a >= alloc.locals_count) {
1702 self->values[i]->code.local = alloc.locals_count;
1703 if (!function_allocator_alloc(&alloc, v))
1708 /* Adjust slot positions based on sizes */
1709 if (!function_allocator_positions_add(&alloc, 0))
1712 if (alloc.sizes_count)
1713 pos = alloc.positions[0] + alloc.sizes[0];
1716 for (i = 1; i < alloc.sizes_count; ++i)
1718 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1719 if (!function_allocator_positions_add(&alloc, pos))
1723 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1725 /* Take over the actual slot positions */
1726 for (i = 0; i < self->values_count; ++i)
1727 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1734 for (i = 0; i < alloc.locals_count; ++i)
1735 ir_value_delete(alloc.locals[i]);
1736 MEM_VECTOR_CLEAR(&alloc, locals);
1737 MEM_VECTOR_CLEAR(&alloc, sizes);
1738 MEM_VECTOR_CLEAR(&alloc, positions);
1742 /* Get information about which operand
1743 * is read from, or written to.
1745 static void ir_op_read_write(int op, size_t *read, size_t *write)
1772 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1775 bool changed = false;
1777 for (i = 0; i != self->living_count; ++i)
1779 tempbool = ir_value_life_merge(self->living[i], eid);
1782 fprintf(stderr, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1784 changed = changed || tempbool;
1789 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1792 /* values which have been read in a previous iteration are now
1793 * in the "living" array even if the previous block doesn't use them.
1794 * So we have to remove whatever does not exist in the previous block.
1795 * They will be re-added on-read, but the liferange merge won't cause
1798 for (i = 0; i < self->living_count; ++i)
1800 if (!ir_block_living_find(prev, self->living[i], NULL)) {
1801 if (!ir_block_living_remove(self, i))
1807 /* Whatever the previous block still has in its living set
1808 * must now be added to ours as well.
1810 for (i = 0; i < prev->living_count; ++i)
1812 if (ir_block_living_find(self, prev->living[i], NULL))
1814 if (!ir_block_living_add(self, prev->living[i]))
1817 printf("%s got from prev: %s\n", self->label, prev->living[i]->_name);
1823 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
1829 /* bitmasks which operands are read from or written to */
1831 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1833 new_reads_t new_reads;
1835 char dbg_ind[16] = { '#', '0' };
1838 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1839 MEM_VECTOR_INIT(&new_reads, v);
1844 if (!ir_block_life_prop_previous(self, prev, changed))
1848 i = self->instr_count;
1851 instr = self->instr[i];
1853 /* PHI operands are always read operands */
1854 for (p = 0; p < instr->phi_count; ++p)
1856 value = instr->phi[p].value;
1857 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1858 if (!ir_block_living_find(self, value, NULL) &&
1859 !ir_block_living_add(self, value))
1864 if (!new_reads_t_v_find(&new_reads, value, NULL))
1866 if (!new_reads_t_v_add(&new_reads, value))
1872 /* See which operands are read and write operands */
1873 ir_op_read_write(instr->opcode, &read, &write);
1875 /* Go through the 3 main operands */
1876 for (o = 0; o < 3; ++o)
1878 if (!instr->_ops[o]) /* no such operand */
1881 value = instr->_ops[o];
1883 /* We only care about locals */
1884 if (value->store != store_value &&
1885 value->store != store_local)
1891 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1892 if (!ir_block_living_find(self, value, NULL) &&
1893 !ir_block_living_add(self, value))
1898 /* fprintf(stderr, "read: %s\n", value->_name); */
1899 if (!new_reads_t_v_find(&new_reads, value, NULL))
1901 if (!new_reads_t_v_add(&new_reads, value))
1907 /* write operands */
1908 /* When we write to a local, we consider it "dead" for the
1909 * remaining upper part of the function, since in SSA a value
1910 * can only be written once (== created)
1915 bool in_living = ir_block_living_find(self, value, &idx);
1916 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1918 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
1919 if (!in_living && !in_reads)
1924 /* If the value isn't alive it hasn't been read before... */
1925 /* TODO: See if the warning can be emitted during parsing or AST processing
1926 * otherwise have warning printed here.
1927 * IF printing a warning here: include filecontext_t,
1928 * and make sure it's only printed once
1929 * since this function is run multiple times.
1931 /* For now: debug info: */
1932 fprintf(stderr, "Value only written %s\n", value->name);
1933 tempbool = ir_value_life_merge(value, instr->eid);
1934 *changed = *changed || tempbool;
1936 ir_instr_dump(instr, dbg_ind, printf);
1940 /* since 'living' won't contain it
1941 * anymore, merge the value, since
1944 tempbool = ir_value_life_merge(value, instr->eid);
1947 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
1949 *changed = *changed || tempbool;
1951 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1952 if (!ir_block_living_remove(self, idx))
1957 if (!new_reads_t_v_remove(&new_reads, readidx))
1965 tempbool = ir_block_living_add_instr(self, instr->eid);
1966 /*fprintf(stderr, "living added values\n");*/
1967 *changed = *changed || tempbool;
1969 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1971 for (rd = 0; rd < new_reads.v_count; ++rd)
1973 if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
1974 if (!ir_block_living_add(self, new_reads.v[rd]))
1977 if (!i && !self->entries_count) {
1979 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
1982 MEM_VECTOR_CLEAR(&new_reads, v);
1986 if (self->run_id == self->owner->run_id)
1989 self->run_id = self->owner->run_id;
1991 for (i = 0; i < self->entries_count; ++i)
1993 ir_block *entry = self->entries[i];
1994 ir_block_life_propagate(entry, self, changed);
1999 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2000 MEM_VECTOR_CLEAR(&new_reads, v);
2005 /***********************************************************************
2008 * Since the IR has the convention of putting 'write' operands
2009 * at the beginning, we have to rotate the operands of instructions
2010 * properly in order to generate valid QCVM code.
2012 * Having destinations at a fixed position is more convenient. In QC
2013 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2014 * read from from OPA, and store to OPB rather than OPC. Which is
2015 * partially the reason why the implementation of these instructions
2016 * in darkplaces has been delayed for so long.
2018 * Breaking conventions is annoying...
2020 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2022 static bool gen_global_field(ir_value *global)
2024 if (global->isconst)
2026 ir_value *fld = global->constval.vpointer;
2028 printf("Invalid field constant with no field: %s\n", global->name);
2032 /* Now, in this case, a relocation would be impossible to code
2033 * since it looks like this:
2034 * .vector v = origin; <- parse error, wtf is 'origin'?
2037 * But we will need a general relocation support later anyway
2038 * for functions... might as well support that here.
2040 if (!fld->code.globaladdr) {
2041 printf("FIXME: Relocation support\n");
2045 /* copy the field's value */
2046 global->code.globaladdr = code_globals_add(code_globals_data[fld->code.globaladdr]);
2050 prog_section_field fld;
2052 fld.name = global->code.name;
2053 fld.offset = code_fields_elements;
2054 fld.type = global->fieldtype;
2056 if (fld.type == TYPE_VOID) {
2057 printf("Field is missing a type: %s\n", global->name);
2061 if (code_fields_add(fld) < 0)
2064 global->code.globaladdr = code_globals_add(fld.offset);
2066 if (global->code.globaladdr < 0)
2071 static bool gen_global_pointer(ir_value *global)
2073 if (global->isconst)
2075 ir_value *target = global->constval.vpointer;
2077 printf("Invalid pointer constant: %s\n", global->name);
2078 /* NULL pointers are pointing to the NULL constant, which also
2079 * sits at address 0, but still has an ir_value for itself.
2084 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2085 * void() foo; <- proto
2086 * void() *fooptr = &foo;
2087 * void() foo = { code }
2089 if (!target->code.globaladdr) {
2090 /* FIXME: Check for the constant nullptr ir_value!
2091 * because then code.globaladdr being 0 is valid.
2093 printf("FIXME: Relocation support\n");
2097 global->code.globaladdr = code_globals_add(target->code.globaladdr);
2101 global->code.globaladdr = code_globals_add(0);
2103 if (global->code.globaladdr < 0)
2108 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2110 prog_section_statement stmt;
2119 block->generated = true;
2120 block->code_start = code_statements_elements;
2121 for (i = 0; i < block->instr_count; ++i)
2123 instr = block->instr[i];
2125 if (instr->opcode == VINSTR_PHI) {
2126 printf("cannot generate virtual instruction (phi)\n");
2130 if (instr->opcode == VINSTR_JUMP) {
2131 target = instr->bops[0];
2132 /* for uncoditional jumps, if the target hasn't been generated
2133 * yet, we generate them right here.
2135 if (!target->generated) {
2140 /* otherwise we generate a jump instruction */
2141 stmt.opcode = INSTR_GOTO;
2142 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2145 if (code_statements_add(stmt) < 0)
2148 /* no further instructions can be in this block */
2152 if (instr->opcode == VINSTR_COND) {
2153 ontrue = instr->bops[0];
2154 onfalse = instr->bops[1];
2155 /* TODO: have the AST signal which block should
2156 * come first: eg. optimize IFs without ELSE...
2159 stmt.o1.u1 = instr->_ops[0]->code.globaladdr;
2163 if (ontrue->generated) {
2164 stmt.opcode = INSTR_IF;
2165 stmt.o2.s1 = (ontrue->code_start-1) - code_statements_elements;
2166 if (code_statements_add(stmt) < 0)
2169 if (onfalse->generated) {
2170 stmt.opcode = INSTR_IFNOT;
2171 stmt.o2.s1 = (onfalse->code_start-1) - code_statements_elements;
2172 if (code_statements_add(stmt) < 0)
2175 if (!ontrue->generated) {
2176 if (onfalse->generated) {
2181 if (!onfalse->generated) {
2182 if (ontrue->generated) {
2187 /* neither ontrue nor onfalse exist */
2188 stmt.opcode = INSTR_IFNOT;
2189 stidx = code_statements_elements;
2190 if (code_statements_add(stmt) < 0)
2192 /* on false we jump, so add ontrue-path */
2193 if (!gen_blocks_recursive(func, ontrue))
2195 /* fixup the jump address */
2196 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2197 /* generate onfalse path */
2198 if (onfalse->generated) {
2199 /* fixup the jump address */
2200 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2201 /* may have been generated in the previous recursive call */
2202 stmt.opcode = INSTR_GOTO;
2203 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2206 return (code_statements_add(stmt) >= 0);
2208 /* if not, generate now */
2213 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2214 /* Trivial call translation:
2215 * copy all params to OFS_PARM*
2216 * if the output's storetype is not store_return,
2217 * add append a STORE instruction!
2219 * NOTES on how to do it better without much trouble:
2220 * -) The liferanges!
2221 * Simply check the liferange of all parameters for
2222 * other CALLs. For each param with no CALL in its
2223 * liferange, we can store it in an OFS_PARM at
2224 * generation already. This would even include later
2225 * reuse.... probably... :)
2230 for (p = 0; p < instr->params_count; ++p)
2232 ir_value *param = instr->params[p];
2234 stmt.opcode = INSTR_STORE_F;
2237 stmt.opcode = type_store_instr[param->vtype];
2238 stmt.o1.u1 = param->code.globaladdr;
2239 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2240 if (code_statements_add(stmt) < 0)
2243 stmt.opcode = INSTR_CALL0 + instr->params_count;
2244 if (stmt.opcode > INSTR_CALL8)
2245 stmt.opcode = INSTR_CALL8;
2246 stmt.o1.u1 = instr->_ops[1]->code.globaladdr;
2249 if (code_statements_add(stmt) < 0)
2252 retvalue = instr->_ops[0];
2253 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2255 /* not to be kept in OFS_RETURN */
2256 stmt.opcode = type_store_instr[retvalue->vtype];
2257 stmt.o1.u1 = OFS_RETURN;
2258 stmt.o2.u1 = retvalue->code.globaladdr;
2260 if (code_statements_add(stmt) < 0)
2266 if (instr->opcode == INSTR_STATE) {
2267 printf("TODO: state instruction\n");
2271 stmt.opcode = instr->opcode;
2276 /* This is the general order of operands */
2278 stmt.o3.u1 = instr->_ops[0]->code.globaladdr;
2281 stmt.o1.u1 = instr->_ops[1]->code.globaladdr;
2284 stmt.o2.u1 = instr->_ops[2]->code.globaladdr;
2286 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2288 stmt.o1.u1 = stmt.o3.u1;
2291 else if ((stmt.opcode >= INSTR_STORE_F &&
2292 stmt.opcode <= INSTR_STORE_FNC) ||
2293 (stmt.opcode >= INSTR_NOT_F &&
2294 stmt.opcode <= INSTR_NOT_FNC))
2296 /* 2-operand instructions with A -> B */
2297 stmt.o2.u1 = stmt.o3.u1;
2301 if (code_statements_add(stmt) < 0)
2307 static bool gen_function_code(ir_function *self)
2311 /* Starting from entry point, we generate blocks "as they come"
2312 * for now. Dead blocks will not be translated obviously.
2314 if (!self->blocks_count) {
2315 printf("Function '%s' declared without body.\n", self->name);
2319 block = self->blocks[0];
2320 if (block->generated)
2323 if (!gen_blocks_recursive(self, block)) {
2324 printf("failed to generate blocks for '%s'\n", self->name);
2330 static bool gen_global_function(ir_builder *ir, ir_value *global)
2332 prog_section_function fun;
2336 size_t local_var_end;
2338 if (!global->isconst || (!global->constval.vfunc))
2340 printf("Invalid state of function-global: not constant: %s\n", global->name);
2344 irfun = global->constval.vfunc;
2346 fun.name = global->code.name;
2347 fun.file = code_cachedstring(global->context.file);
2348 fun.profile = 0; /* always 0 */
2349 fun.nargs = irfun->params_count;
2351 for (i = 0;i < 8; ++i) {
2354 else if (irfun->params[i] == TYPE_VECTOR)
2360 fun.firstlocal = code_globals_elements;
2361 fun.locals = irfun->allocated_locals + irfun->locals_count;
2364 for (i = 0; i < irfun->locals_count; ++i) {
2365 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2366 printf("Failed to generate global %s\n", irfun->locals[i]->name);
2370 if (irfun->locals_count) {
2371 ir_value *last = irfun->locals[irfun->locals_count-1];
2372 local_var_end = last->code.globaladdr;
2373 local_var_end += type_sizeof[last->vtype];
2375 for (i = 0; i < irfun->values_count; ++i)
2377 /* generate code.globaladdr for ssa values */
2378 ir_value *v = irfun->values[i];
2379 v->code.globaladdr = local_var_end + v->code.local;
2381 for (i = 0; i < irfun->locals_count; ++i) {
2382 /* fill the locals with zeros */
2383 code_globals_add(0);
2387 fun.entry = irfun->builtin;
2389 fun.entry = code_statements_elements;
2390 if (!gen_function_code(irfun)) {
2391 printf("Failed to generate code for function %s\n", irfun->name);
2396 return (code_functions_add(fun) >= 0);
2399 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2402 prog_section_def def;
2404 def.type = global->vtype;
2405 def.offset = code_globals_elements;
2406 def.name = global->code.name = code_genstring(global->name);
2408 switch (global->vtype)
2411 if (code_defs_add(def) < 0)
2413 return gen_global_pointer(global);
2415 if (code_defs_add(def) < 0)
2417 return gen_global_field(global);
2422 if (code_defs_add(def) < 0)
2425 if (global->isconst) {
2426 iptr = (int32_t*)&global->constval.vfloat;
2427 global->code.globaladdr = code_globals_add(*iptr);
2429 global->code.globaladdr = code_globals_add(0);
2431 return global->code.globaladdr >= 0;
2435 if (code_defs_add(def) < 0)
2437 if (global->isconst)
2438 global->code.globaladdr = code_globals_add(code_cachedstring(global->constval.vstring));
2440 global->code.globaladdr = code_globals_add(0);
2441 return global->code.globaladdr >= 0;
2445 if (code_defs_add(def) < 0)
2448 if (global->isconst) {
2449 iptr = (int32_t*)&global->constval.vvec;
2450 global->code.globaladdr = code_globals_add(iptr[0]);
2451 if (code_globals_add(iptr[1]) < 0 || code_globals_add(iptr[2]) < 0)
2454 global->code.globaladdr = code_globals_add(0);
2455 if (code_globals_add(0) < 0 || code_globals_add(0) < 0)
2458 return global->code.globaladdr >= 0;
2461 if (code_defs_add(def) < 0)
2463 code_globals_add(code_functions_elements);
2464 return gen_global_function(self, global);
2466 /* assume biggest type */
2467 global->code.globaladdr = code_globals_add(0);
2468 code_globals_add(0);
2469 code_globals_add(0);
2472 /* refuse to create 'void' type or any other fancy business. */
2473 printf("Invalid type for global variable %s\n", global->name);
2478 bool ir_builder_generate(ir_builder *self, const char *filename)
2484 for (i = 0; i < self->globals_count; ++i)
2486 if (!ir_builder_gen_global(self, self->globals[i])) {
2491 printf("writing '%s'...\n", filename);
2492 return code_write(filename);
2495 /***********************************************************************
2496 *IR DEBUG Dump functions...
2499 #define IND_BUFSZ 1024
2501 const char *qc_opname(int op)
2503 if (op < 0) return "<INVALID>";
2504 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2505 return asm_instr[op].m;
2507 case VINSTR_PHI: return "PHI";
2508 case VINSTR_JUMP: return "JUMP";
2509 case VINSTR_COND: return "COND";
2510 default: return "<UNK>";
2514 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2517 char indent[IND_BUFSZ];
2521 oprintf("module %s\n", b->name);
2522 for (i = 0; i < b->globals_count; ++i)
2525 if (b->globals[i]->isconst)
2526 oprintf("%s = ", b->globals[i]->name);
2527 ir_value_dump(b->globals[i], oprintf);
2530 for (i = 0; i < b->functions_count; ++i)
2531 ir_function_dump(b->functions[i], indent, oprintf);
2532 oprintf("endmodule %s\n", b->name);
2535 void ir_function_dump(ir_function *f, char *ind,
2536 int (*oprintf)(const char*, ...))
2539 oprintf("%sfunction %s\n", ind, f->name);
2540 strncat(ind, "\t", IND_BUFSZ);
2541 if (f->locals_count)
2543 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2544 for (i = 0; i < f->locals_count; ++i) {
2545 oprintf("%s\t", ind);
2546 ir_value_dump(f->locals[i], oprintf);
2550 if (f->blocks_count)
2552 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2553 for (i = 0; i < f->blocks_count; ++i) {
2554 if (f->blocks[i]->run_id != f->run_id) {
2555 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2557 ir_block_dump(f->blocks[i], ind, oprintf);
2561 ind[strlen(ind)-1] = 0;
2562 oprintf("%sendfunction %s\n", ind, f->name);
2565 void ir_block_dump(ir_block* b, char *ind,
2566 int (*oprintf)(const char*, ...))
2569 oprintf("%s:%s\n", ind, b->label);
2570 strncat(ind, "\t", IND_BUFSZ);
2572 for (i = 0; i < b->instr_count; ++i)
2573 ir_instr_dump(b->instr[i], ind, oprintf);
2574 ind[strlen(ind)-1] = 0;
2577 void dump_phi(ir_instr *in, char *ind,
2578 int (*oprintf)(const char*, ...))
2581 oprintf("%s <- phi ", in->_ops[0]->name);
2582 for (i = 0; i < in->phi_count; ++i)
2584 oprintf("([%s] : %s) ", in->phi[i].from->label,
2585 in->phi[i].value->name);
2590 void ir_instr_dump(ir_instr *in, char *ind,
2591 int (*oprintf)(const char*, ...))
2594 const char *comma = NULL;
2596 oprintf("%s (%i) ", ind, (int)in->eid);
2598 if (in->opcode == VINSTR_PHI) {
2599 dump_phi(in, ind, oprintf);
2603 strncat(ind, "\t", IND_BUFSZ);
2605 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2606 ir_value_dump(in->_ops[0], oprintf);
2607 if (in->_ops[1] || in->_ops[2])
2610 oprintf("%s\t", qc_opname(in->opcode));
2611 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2612 ir_value_dump(in->_ops[0], oprintf);
2617 for (i = 1; i != 3; ++i) {
2621 ir_value_dump(in->_ops[i], oprintf);
2629 oprintf("[%s]", in->bops[0]->label);
2633 oprintf("%s[%s]", comma, in->bops[1]->label);
2635 ind[strlen(ind)-1] = 0;
2638 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
2646 oprintf("%g", v->constval.vfloat);
2649 oprintf("'%g %g %g'",
2652 v->constval.vvec.z);
2655 oprintf("(entity)");
2658 oprintf("\"%s\"", v->constval.vstring);
2662 oprintf("%i", v->constval.vint);
2667 v->constval.vpointer->name);
2671 oprintf("%s", v->name);
2675 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
2678 oprintf("Life of %s:\n", self->name);
2679 for (i = 0; i < self->life_count; ++i)
2681 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);