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 */
44 4, /* TYPE_QUATERNION */
46 16, /* TYPE_VARIANT */
49 uint16_t type_store_instr[TYPE_COUNT] = {
50 INSTR_STORE_F, /* should use I when having integer support */
57 INSTR_STORE_ENT, /* should use I */
59 INSTR_STORE_I, /* integer type */
64 INSTR_STORE_M, /* variant, should never be accessed */
67 MEM_VEC_FUNCTIONS(ir_value_vector, ir_value*, v)
69 /***********************************************************************
73 ir_builder* ir_builder_new(const char *modulename)
77 self = (ir_builder*)mem_a(sizeof(*self));
81 MEM_VECTOR_INIT(self, functions);
82 MEM_VECTOR_INIT(self, globals);
84 if (!ir_builder_set_name(self, modulename)) {
89 /* globals which always exist */
91 /* for now we give it a vector size */
92 ir_builder_create_global(self, "OFS_RETURN", TYPE_VARIANT);
97 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
98 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
100 void ir_builder_delete(ir_builder* self)
103 mem_d((void*)self->name);
104 for (i = 0; i != self->functions_count; ++i) {
105 ir_function_delete(self->functions[i]);
107 MEM_VECTOR_CLEAR(self, functions);
108 for (i = 0; i != self->globals_count; ++i) {
109 ir_value_delete(self->globals[i]);
111 MEM_VECTOR_CLEAR(self, globals);
115 bool ir_builder_set_name(ir_builder *self, const char *name)
118 mem_d((void*)self->name);
119 self->name = util_strdup(name);
123 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
126 for (i = 0; i < self->functions_count; ++i) {
127 if (!strcmp(name, self->functions[i]->name))
128 return self->functions[i];
133 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
135 ir_function *fn = ir_builder_get_function(self, name);
140 fn = ir_function_new(self, outtype);
141 if (!ir_function_set_name(fn, name) ||
142 !ir_builder_functions_add(self, fn) )
144 ir_function_delete(fn);
148 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
150 ir_function_delete(fn);
154 fn->value->isconst = true;
155 fn->value->outtype = outtype;
156 fn->value->constval.vfunc = fn;
157 fn->value->context = fn->context;
162 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
165 for (i = 0; i < self->globals_count; ++i) {
166 if (!strcmp(self->globals[i]->name, name))
167 return self->globals[i];
172 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
174 ir_value *ve = ir_builder_get_global(self, name);
179 ve = ir_value_var(name, store_global, vtype);
180 if (!ir_builder_globals_add(self, ve)) {
187 /***********************************************************************
191 bool ir_function_naive_phi(ir_function*);
192 void ir_function_enumerate(ir_function*);
193 bool ir_function_calculate_liferanges(ir_function*);
194 bool ir_function_allocate_locals(ir_function*);
196 ir_function* ir_function_new(ir_builder* owner, int outtype)
199 self = (ir_function*)mem_a(sizeof(*self));
205 if (!ir_function_set_name(self, "<@unnamed>")) {
210 self->context.file = "<@no context>";
211 self->context.line = 0;
212 self->outtype = outtype;
215 MEM_VECTOR_INIT(self, params);
216 MEM_VECTOR_INIT(self, blocks);
217 MEM_VECTOR_INIT(self, values);
218 MEM_VECTOR_INIT(self, locals);
223 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
224 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
225 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
226 MEM_VEC_FUNCTIONS(ir_function, int, params)
228 bool ir_function_set_name(ir_function *self, const char *name)
231 mem_d((void*)self->name);
232 self->name = util_strdup(name);
236 void ir_function_delete(ir_function *self)
239 mem_d((void*)self->name);
241 for (i = 0; i != self->blocks_count; ++i)
242 ir_block_delete(self->blocks[i]);
243 MEM_VECTOR_CLEAR(self, blocks);
245 MEM_VECTOR_CLEAR(self, params);
247 for (i = 0; i != self->values_count; ++i)
248 ir_value_delete(self->values[i]);
249 MEM_VECTOR_CLEAR(self, values);
251 for (i = 0; i != self->locals_count; ++i)
252 ir_value_delete(self->locals[i]);
253 MEM_VECTOR_CLEAR(self, locals);
255 /* self->value is deleted by the builder */
260 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
262 return ir_function_values_add(self, v);
265 ir_block* ir_function_create_block(ir_function *self, const char *label)
267 ir_block* bn = ir_block_new(self, label);
268 memcpy(&bn->context, &self->context, sizeof(self->context));
269 if (!ir_function_blocks_add(self, bn)) {
276 bool ir_function_finalize(ir_function *self)
281 if (!ir_function_naive_phi(self))
284 ir_function_enumerate(self);
286 if (!ir_function_calculate_liferanges(self))
289 if (!ir_function_allocate_locals(self))
294 ir_value* ir_function_get_local(ir_function *self, const char *name)
297 for (i = 0; i < self->locals_count; ++i) {
298 if (!strcmp(self->locals[i]->name, name))
299 return self->locals[i];
304 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype)
306 ir_value *ve = ir_function_get_local(self, name);
311 ve = ir_value_var(name, store_local, vtype);
312 if (!ir_function_locals_add(self, ve)) {
319 /***********************************************************************
323 ir_block* ir_block_new(ir_function* owner, const char *name)
326 self = (ir_block*)mem_a(sizeof(*self));
330 memset(self, 0, sizeof(*self));
333 if (!ir_block_set_label(self, name)) {
338 self->context.file = "<@no context>";
339 self->context.line = 0;
341 MEM_VECTOR_INIT(self, instr);
342 MEM_VECTOR_INIT(self, entries);
343 MEM_VECTOR_INIT(self, exits);
346 self->is_return = false;
348 MEM_VECTOR_INIT(self, living);
350 self->generated = false;
354 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
355 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
356 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
357 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
359 void ir_block_delete(ir_block* self)
363 for (i = 0; i != self->instr_count; ++i)
364 ir_instr_delete(self->instr[i]);
365 MEM_VECTOR_CLEAR(self, instr);
366 MEM_VECTOR_CLEAR(self, entries);
367 MEM_VECTOR_CLEAR(self, exits);
368 MEM_VECTOR_CLEAR(self, living);
372 bool ir_block_set_label(ir_block *self, const char *name)
375 mem_d((void*)self->label);
376 self->label = util_strdup(name);
377 return !!self->label;
380 /***********************************************************************
384 ir_instr* ir_instr_new(ir_block* owner, int op)
387 self = (ir_instr*)mem_a(sizeof(*self));
392 self->context.file = "<@no context>";
393 self->context.line = 0;
395 self->_ops[0] = NULL;
396 self->_ops[1] = NULL;
397 self->_ops[2] = NULL;
398 self->bops[0] = NULL;
399 self->bops[1] = NULL;
400 MEM_VECTOR_INIT(self, phi);
401 MEM_VECTOR_INIT(self, params);
406 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
407 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
409 void ir_instr_delete(ir_instr *self)
412 /* The following calls can only delete from
413 * vectors, we still want to delete this instruction
414 * so ignore the return value. Since with the warn_unused_result attribute
415 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
416 * I have to improvise here and use if(foo());
418 for (i = 0; i < self->phi_count; ++i) {
420 if (ir_value_writes_find(self->phi[i].value, self, &idx))
421 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
422 if (ir_value_reads_find(self->phi[i].value, self, &idx))
423 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
425 MEM_VECTOR_CLEAR(self, phi);
426 for (i = 0; i < self->params_count; ++i) {
428 if (ir_value_writes_find(self->params[i], self, &idx))
429 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
430 if (ir_value_reads_find(self->params[i], self, &idx))
431 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
433 MEM_VECTOR_CLEAR(self, params);
434 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
435 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
436 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
440 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
442 if (self->_ops[op]) {
444 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
446 if (!ir_value_writes_remove(self->_ops[op], idx))
449 else if (ir_value_reads_find(self->_ops[op], self, &idx))
451 if (!ir_value_reads_remove(self->_ops[op], idx))
457 if (!ir_value_writes_add(v, self))
460 if (!ir_value_reads_add(v, self))
468 /***********************************************************************
472 ir_value* ir_value_var(const char *name, int storetype, int vtype)
475 self = (ir_value*)mem_a(sizeof(*self));
477 self->fieldtype = TYPE_VOID;
478 self->outtype = TYPE_VOID;
479 self->store = storetype;
480 MEM_VECTOR_INIT(self, reads);
481 MEM_VECTOR_INIT(self, writes);
482 self->isconst = false;
483 self->context.file = "<@no context>";
484 self->context.line = 0;
486 ir_value_set_name(self, name);
488 memset(&self->constval, 0, sizeof(self->constval));
489 memset(&self->code, 0, sizeof(self->code));
491 MEM_VECTOR_INIT(self, life);
494 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
495 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
496 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
498 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
500 ir_value *v = ir_value_var(name, storetype, vtype);
503 if (!ir_function_collect_value(owner, v))
511 void ir_value_delete(ir_value* self)
514 mem_d((void*)self->name);
517 if (self->vtype == TYPE_STRING)
518 mem_d((void*)self->constval.vstring);
520 MEM_VECTOR_CLEAR(self, reads);
521 MEM_VECTOR_CLEAR(self, writes);
522 MEM_VECTOR_CLEAR(self, life);
526 void ir_value_set_name(ir_value *self, const char *name)
529 mem_d((void*)self->name);
530 self->name = util_strdup(name);
533 bool ir_value_set_float(ir_value *self, float f)
535 if (self->vtype != TYPE_FLOAT)
537 self->constval.vfloat = f;
538 self->isconst = true;
542 bool ir_value_set_func(ir_value *self, int f)
544 if (self->vtype != TYPE_FUNCTION)
546 self->constval.vint = f;
547 self->isconst = true;
551 bool ir_value_set_vector(ir_value *self, vector v)
553 if (self->vtype != TYPE_VECTOR)
555 self->constval.vvec = v;
556 self->isconst = true;
560 bool ir_value_set_quaternion(ir_value *self, quaternion v)
562 if (self->vtype != TYPE_QUATERNION)
564 self->constval.vquat = v;
565 self->isconst = true;
569 bool ir_value_set_matrix(ir_value *self, matrix v)
571 if (self->vtype != TYPE_MATRIX)
573 self->constval.vmat = v;
574 self->isconst = true;
578 bool ir_value_set_string(ir_value *self, const char *str)
580 if (self->vtype != TYPE_STRING)
582 self->constval.vstring = util_strdup(str);
583 self->isconst = true;
588 bool ir_value_set_int(ir_value *self, int i)
590 if (self->vtype != TYPE_INTEGER)
592 self->constval.vint = i;
593 self->isconst = true;
598 bool ir_value_lives(ir_value *self, size_t at)
601 for (i = 0; i < self->life_count; ++i)
603 ir_life_entry_t *life = &self->life[i];
604 if (life->start <= at && at <= life->end)
606 if (life->start > at) /* since it's ordered */
612 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
615 if (!ir_value_life_add(self, e)) /* naive... */
617 for (k = self->life_count-1; k > idx; --k)
618 self->life[k] = self->life[k-1];
623 bool ir_value_life_merge(ir_value *self, size_t s)
626 ir_life_entry_t *life = NULL;
627 ir_life_entry_t *before = NULL;
628 ir_life_entry_t new_entry;
630 /* Find the first range >= s */
631 for (i = 0; i < self->life_count; ++i)
634 life = &self->life[i];
638 /* nothing found? append */
639 if (i == self->life_count) {
641 if (life && life->end+1 == s)
643 /* previous life range can be merged in */
647 if (life && life->end >= s)
650 if (!ir_value_life_add(self, e))
651 return false; /* failing */
657 if (before->end + 1 == s &&
658 life->start - 1 == s)
661 before->end = life->end;
662 if (!ir_value_life_remove(self, i))
663 return false; /* failing */
666 if (before->end + 1 == s)
672 /* already contained */
673 if (before->end >= s)
677 if (life->start - 1 == s)
682 /* insert a new entry */
683 new_entry.start = new_entry.end = s;
684 return ir_value_life_insert(self, i, new_entry);
687 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
691 if (!other->life_count)
694 if (!self->life_count) {
695 for (i = 0; i < other->life_count; ++i) {
696 if (!ir_value_life_add(self, other->life[i]))
703 for (i = 0; i < other->life_count; ++i)
705 const ir_life_entry_t *life = &other->life[i];
708 ir_life_entry_t *entry = &self->life[myi];
710 if (life->end+1 < entry->start)
712 /* adding an interval before entry */
713 if (!ir_value_life_insert(self, myi, *life))
719 if (life->start < entry->start &&
720 life->end >= entry->start)
722 /* starts earlier and overlaps */
723 entry->start = life->start;
726 if (life->end > entry->end &&
727 life->start-1 <= entry->end)
729 /* ends later and overlaps */
730 entry->end = life->end;
733 /* see if our change combines it with the next ranges */
734 while (myi+1 < self->life_count &&
735 entry->end+1 >= self->life[1+myi].start)
737 /* overlaps with (myi+1) */
738 if (entry->end < self->life[1+myi].end)
739 entry->end = self->life[1+myi].end;
740 if (!ir_value_life_remove(self, myi+1))
742 entry = &self->life[myi];
745 /* see if we're after the entry */
746 if (life->start > entry->end)
749 /* append if we're at the end */
750 if (myi >= self->life_count) {
751 if (!ir_value_life_add(self, *life))
755 /* otherweise check the next range */
764 bool ir_values_overlap(const ir_value *a, const ir_value *b)
766 /* For any life entry in A see if it overlaps with
767 * any life entry in B.
768 * Note that the life entries are orderes, so we can make a
769 * more efficient algorithm there than naively translating the
773 ir_life_entry_t *la, *lb, *enda, *endb;
775 /* first of all, if either has no life range, they cannot clash */
776 if (!a->life_count || !b->life_count)
781 enda = la + a->life_count;
782 endb = lb + b->life_count;
785 /* check if the entries overlap, for that,
786 * both must start before the other one ends.
788 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
789 if (la->start <= lb->end &&
790 lb->start <= la->end)
792 if (la->start < lb->end &&
799 /* entries are ordered
800 * one entry is earlier than the other
801 * that earlier entry will be moved forward
803 if (la->start < lb->start)
805 /* order: A B, move A forward
806 * check if we hit the end with A
811 else if (lb->start < la->start)
813 /* order: B A, move B forward
814 * check if we hit the end with B
823 /***********************************************************************
827 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
829 if (target->store == store_value) {
830 fprintf(stderr, "cannot store to an SSA value\n");
831 fprintf(stderr, "trying to store: %s <- %s\n", target->name, what->name);
834 ir_instr *in = ir_instr_new(self, op);
837 if (!ir_instr_op(in, 0, target, true) ||
838 !ir_instr_op(in, 1, what, false) ||
839 !ir_block_instr_add(self, in) )
847 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
851 if (target->vtype == TYPE_VARIANT)
854 vtype = target->vtype;
859 if (what->vtype == TYPE_INTEGER)
860 op = INSTR_CONV_ITOF;
869 op = INSTR_STORE_ENT;
875 op = INSTR_STORE_FLD;
879 if (what->vtype == TYPE_INTEGER)
880 op = INSTR_CONV_FTOI;
889 op = INSTR_STORE_ENT;
892 case TYPE_QUATERNION:
902 return ir_block_create_store_op(self, op, target, what);
905 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
910 if (target->vtype != TYPE_POINTER)
913 /* storing using pointer - target is a pointer, type must be
914 * inferred from source
926 op = INSTR_STOREP_ENT;
932 op = INSTR_STOREP_FLD;
943 op = INSTR_STOREP_ENT;
946 case TYPE_QUATERNION:
956 return ir_block_create_store_op(self, op, target, what);
959 bool ir_block_create_return(ir_block *self, ir_value *v)
963 fprintf(stderr, "block already ended (%s)\n", self->label);
967 self->is_return = true;
968 in = ir_instr_new(self, INSTR_RETURN);
972 if (!ir_instr_op(in, 0, v, false) ||
973 !ir_block_instr_add(self, in) )
980 bool ir_block_create_if(ir_block *self, ir_value *v,
981 ir_block *ontrue, ir_block *onfalse)
985 fprintf(stderr, "block already ended (%s)\n", self->label);
989 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
990 in = ir_instr_new(self, VINSTR_COND);
994 if (!ir_instr_op(in, 0, v, false)) {
999 in->bops[0] = ontrue;
1000 in->bops[1] = onfalse;
1002 if (!ir_block_instr_add(self, in))
1005 if (!ir_block_exits_add(self, ontrue) ||
1006 !ir_block_exits_add(self, onfalse) ||
1007 !ir_block_entries_add(ontrue, self) ||
1008 !ir_block_entries_add(onfalse, self) )
1015 bool ir_block_create_jump(ir_block *self, ir_block *to)
1019 fprintf(stderr, "block already ended (%s)\n", self->label);
1023 in = ir_instr_new(self, VINSTR_JUMP);
1028 if (!ir_block_instr_add(self, in))
1031 if (!ir_block_exits_add(self, to) ||
1032 !ir_block_entries_add(to, self) )
1039 bool ir_block_create_goto(ir_block *self, ir_block *to)
1043 fprintf(stderr, "block already ended (%s)\n", self->label);
1047 in = ir_instr_new(self, INSTR_GOTO);
1052 if (!ir_block_instr_add(self, in))
1055 if (!ir_block_exits_add(self, to) ||
1056 !ir_block_entries_add(to, self) )
1063 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1067 in = ir_instr_new(self, VINSTR_PHI);
1070 out = ir_value_out(self->owner, label, store_value, ot);
1072 ir_instr_delete(in);
1075 if (!ir_instr_op(in, 0, out, true)) {
1076 ir_instr_delete(in);
1077 ir_value_delete(out);
1080 if (!ir_block_instr_add(self, in)) {
1081 ir_instr_delete(in);
1082 ir_value_delete(out);
1088 ir_value* ir_phi_value(ir_instr *self)
1090 return self->_ops[0];
1093 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1097 if (!ir_block_entries_find(self->owner, b, NULL)) {
1098 /* Must not be possible to cause this, otherwise the AST
1099 * is doing something wrong.
1101 fprintf(stderr, "Invalid entry block for PHI\n");
1107 if (!ir_value_reads_add(v, self))
1109 return ir_instr_phi_add(self, pe);
1112 /* call related code */
1113 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1117 in = ir_instr_new(self, INSTR_CALL0);
1120 out = ir_value_out(self->owner, label, store_return, func->outtype);
1122 ir_instr_delete(in);
1125 if (!ir_instr_op(in, 0, out, true) ||
1126 !ir_instr_op(in, 1, func, false) ||
1127 !ir_block_instr_add(self, in))
1129 ir_instr_delete(in);
1130 ir_value_delete(out);
1136 ir_value* ir_call_value(ir_instr *self)
1138 return self->_ops[0];
1141 bool ir_call_param(ir_instr* self, ir_value *v)
1143 if (!ir_instr_params_add(self, v))
1145 if (!ir_value_reads_add(v, self)) {
1146 if (!ir_instr_params_remove(self, self->params_count-1))
1147 GMQCC_SUPPRESS_EMPTY_BODY;
1153 /* binary op related code */
1155 ir_value* ir_block_create_binop(ir_block *self,
1156 const char *label, int opcode,
1157 ir_value *left, ir_value *right)
1179 case INSTR_SUB_S: /* -- offset of string as float */
1184 case INSTR_BITOR_IF:
1185 case INSTR_BITOR_FI:
1186 case INSTR_BITAND_FI:
1187 case INSTR_BITAND_IF:
1202 case INSTR_BITAND_I:
1205 case INSTR_RSHIFT_I:
1206 case INSTR_LSHIFT_I:
1227 /* boolean operations result in floats */
1228 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1230 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1233 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1238 if (ot == TYPE_VOID) {
1239 /* The AST or parser were supposed to check this! */
1243 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1246 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1247 int op, ir_value *a, ir_value *b, int outype)
1252 out = ir_value_out(self->owner, label, store_value, outype);
1256 instr = ir_instr_new(self, op);
1258 ir_value_delete(out);
1262 if (!ir_instr_op(instr, 0, out, true) ||
1263 !ir_instr_op(instr, 1, a, false) ||
1264 !ir_instr_op(instr, 2, b, false) )
1269 if (!ir_block_instr_add(self, instr))
1274 ir_instr_delete(instr);
1275 ir_value_delete(out);
1279 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1281 /* Support for various pointer types todo if so desired */
1282 if (ent->vtype != TYPE_ENTITY)
1285 if (field->vtype != TYPE_FIELD)
1288 return ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1291 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1294 if (ent->vtype != TYPE_ENTITY)
1297 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1298 if (field->vtype != TYPE_FIELD)
1303 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1304 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1305 case TYPE_STRING: op = INSTR_LOAD_S; break;
1306 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1307 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1309 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1310 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1312 case TYPE_QUATERNION: op = INSTR_LOAD_Q; break;
1313 case TYPE_MATRIX: op = INSTR_LOAD_M; break;
1318 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1321 ir_value* ir_block_create_add(ir_block *self,
1323 ir_value *left, ir_value *right)
1326 int l = left->vtype;
1327 int r = right->vtype;
1346 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1348 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1354 return ir_block_create_binop(self, label, op, left, right);
1357 ir_value* ir_block_create_sub(ir_block *self,
1359 ir_value *left, ir_value *right)
1362 int l = left->vtype;
1363 int r = right->vtype;
1383 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1385 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1391 return ir_block_create_binop(self, label, op, left, right);
1394 ir_value* ir_block_create_mul(ir_block *self,
1396 ir_value *left, ir_value *right)
1399 int l = left->vtype;
1400 int r = right->vtype;
1417 case TYPE_QUATERNION:
1425 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1427 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1429 else if ( (l == TYPE_QUATERNION && r == TYPE_FLOAT) )
1431 else if ( (l == TYPE_MATRIX && r == TYPE_FLOAT) )
1434 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1436 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1438 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1440 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1446 return ir_block_create_binop(self, label, op, left, right);
1449 ir_value* ir_block_create_div(ir_block *self,
1451 ir_value *left, ir_value *right)
1454 int l = left->vtype;
1455 int r = right->vtype;
1472 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1474 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1476 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1482 return ir_block_create_binop(self, label, op, left, right);
1485 /* PHI resolving breaks the SSA, and must thus be the last
1486 * step before life-range calculation.
1489 static bool ir_block_naive_phi(ir_block *self);
1490 bool ir_function_naive_phi(ir_function *self)
1494 for (i = 0; i < self->blocks_count; ++i)
1496 if (!ir_block_naive_phi(self->blocks[i]))
1502 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1507 /* create a store */
1508 if (!ir_block_create_store(block, old, what))
1511 /* we now move it up */
1512 instr = block->instr[block->instr_count-1];
1513 for (i = block->instr_count; i > iid; --i)
1514 block->instr[i] = block->instr[i-1];
1515 block->instr[i] = instr;
1520 static bool ir_block_naive_phi(ir_block *self)
1523 /* FIXME: optionally, create_phi can add the phis
1524 * to a list so we don't need to loop through blocks
1525 * - anyway: "don't optimize YET"
1527 for (i = 0; i < self->instr_count; ++i)
1529 ir_instr *instr = self->instr[i];
1530 if (instr->opcode != VINSTR_PHI)
1533 if (!ir_block_instr_remove(self, i))
1535 --i; /* NOTE: i+1 below */
1537 for (p = 0; p < instr->phi_count; ++p)
1539 ir_value *v = instr->phi[p].value;
1540 for (w = 0; w < v->writes_count; ++w) {
1543 if (!v->writes[w]->_ops[0])
1546 /* When the write was to a global, we have to emit a mov */
1547 old = v->writes[w]->_ops[0];
1549 /* The original instruction now writes to the PHI target local */
1550 if (v->writes[w]->_ops[0] == v)
1551 v->writes[w]->_ops[0] = instr->_ops[0];
1553 if (old->store != store_value && old->store != store_local)
1555 /* If it originally wrote to a global we need to store the value
1558 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1560 if (i+1 < self->instr_count)
1561 instr = self->instr[i+1];
1564 /* In case I forget and access instr later, it'll be NULL
1565 * when it's a problem, to make sure we crash, rather than accessing
1571 /* If it didn't, we can replace all reads by the phi target now. */
1573 for (r = 0; r < old->reads_count; ++r)
1576 ir_instr *ri = old->reads[r];
1577 for (op = 0; op < ri->phi_count; ++op) {
1578 if (ri->phi[op].value == old)
1579 ri->phi[op].value = v;
1581 for (op = 0; op < 3; ++op) {
1582 if (ri->_ops[op] == old)
1589 ir_instr_delete(instr);
1594 /***********************************************************************
1595 *IR Temp allocation code
1596 * Propagating value life ranges by walking through the function backwards
1597 * until no more changes are made.
1598 * In theory this should happen once more than once for every nested loop
1600 * Though this implementation might run an additional time for if nests.
1609 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1611 /* Enumerate instructions used by value's life-ranges
1613 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1617 for (i = 0; i < self->instr_count; ++i)
1619 self->instr[i]->eid = eid++;
1624 /* Enumerate blocks and instructions.
1625 * The block-enumeration is unordered!
1626 * We do not really use the block enumreation, however
1627 * the instruction enumeration is important for life-ranges.
1629 void ir_function_enumerate(ir_function *self)
1632 size_t instruction_id = 0;
1633 for (i = 0; i < self->blocks_count; ++i)
1635 self->blocks[i]->eid = i;
1636 self->blocks[i]->run_id = 0;
1637 ir_block_enumerate(self->blocks[i], &instruction_id);
1641 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1642 bool ir_function_calculate_liferanges(ir_function *self)
1650 for (i = 0; i != self->blocks_count; ++i)
1652 if (self->blocks[i]->is_return)
1654 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1662 /* Local-value allocator
1663 * After finishing creating the liferange of all values used in a function
1664 * we can allocate their global-positions.
1665 * This is the counterpart to register-allocation in register machines.
1668 MEM_VECTOR_MAKE(ir_value*, locals);
1669 MEM_VECTOR_MAKE(size_t, sizes);
1670 MEM_VECTOR_MAKE(size_t, positions);
1671 } function_allocator;
1672 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1673 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1674 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1676 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1679 size_t vsize = type_sizeof[var->vtype];
1681 slot = ir_value_var("reg", store_global, var->vtype);
1685 if (!ir_value_life_merge_into(slot, var))
1688 if (!function_allocator_locals_add(alloc, slot))
1691 if (!function_allocator_sizes_add(alloc, vsize))
1697 ir_value_delete(slot);
1701 bool ir_function_allocate_locals(ir_function *self)
1710 function_allocator alloc;
1712 if (!self->locals_count)
1715 MEM_VECTOR_INIT(&alloc, locals);
1716 MEM_VECTOR_INIT(&alloc, sizes);
1717 MEM_VECTOR_INIT(&alloc, positions);
1719 for (i = 0; i < self->locals_count; ++i)
1721 if (!function_allocator_alloc(&alloc, self->locals[i]))
1725 /* Allocate a slot for any value that still exists */
1726 for (i = 0; i < self->values_count; ++i)
1728 v = self->values[i];
1733 for (a = 0; a < alloc.locals_count; ++a)
1735 slot = alloc.locals[a];
1737 if (ir_values_overlap(v, slot))
1740 if (!ir_value_life_merge_into(slot, v))
1743 /* adjust size for this slot */
1744 if (alloc.sizes[a] < type_sizeof[v->vtype])
1745 alloc.sizes[a] = type_sizeof[v->vtype];
1747 self->values[i]->code.local = a;
1750 if (a >= alloc.locals_count) {
1751 self->values[i]->code.local = alloc.locals_count;
1752 if (!function_allocator_alloc(&alloc, v))
1757 /* Adjust slot positions based on sizes */
1758 if (!function_allocator_positions_add(&alloc, 0))
1761 if (alloc.sizes_count)
1762 pos = alloc.positions[0] + alloc.sizes[0];
1765 for (i = 1; i < alloc.sizes_count; ++i)
1767 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1768 if (!function_allocator_positions_add(&alloc, pos))
1772 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1774 /* Take over the actual slot positions */
1775 for (i = 0; i < self->values_count; ++i)
1776 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1783 for (i = 0; i < alloc.locals_count; ++i)
1784 ir_value_delete(alloc.locals[i]);
1785 MEM_VECTOR_CLEAR(&alloc, locals);
1786 MEM_VECTOR_CLEAR(&alloc, sizes);
1787 MEM_VECTOR_CLEAR(&alloc, positions);
1791 /* Get information about which operand
1792 * is read from, or written to.
1794 static void ir_op_read_write(int op, size_t *read, size_t *write)
1821 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1824 bool changed = false;
1826 for (i = 0; i != self->living_count; ++i)
1828 tempbool = ir_value_life_merge(self->living[i], eid);
1831 fprintf(stderr, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1833 changed = changed || tempbool;
1838 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1841 /* values which have been read in a previous iteration are now
1842 * in the "living" array even if the previous block doesn't use them.
1843 * So we have to remove whatever does not exist in the previous block.
1844 * They will be re-added on-read, but the liferange merge won't cause
1847 for (i = 0; i < self->living_count; ++i)
1849 if (!ir_block_living_find(prev, self->living[i], NULL)) {
1850 if (!ir_block_living_remove(self, i))
1856 /* Whatever the previous block still has in its living set
1857 * must now be added to ours as well.
1859 for (i = 0; i < prev->living_count; ++i)
1861 if (ir_block_living_find(self, prev->living[i], NULL))
1863 if (!ir_block_living_add(self, prev->living[i]))
1866 printf("%s got from prev: %s\n", self->label, prev->living[i]->_name);
1872 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
1878 /* bitmasks which operands are read from or written to */
1880 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1882 new_reads_t new_reads;
1884 char dbg_ind[16] = { '#', '0' };
1887 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1888 MEM_VECTOR_INIT(&new_reads, v);
1893 if (!ir_block_life_prop_previous(self, prev, changed))
1897 i = self->instr_count;
1900 instr = self->instr[i];
1902 /* PHI operands are always read operands */
1903 for (p = 0; p < instr->phi_count; ++p)
1905 value = instr->phi[p].value;
1906 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1907 if (!ir_block_living_find(self, value, NULL) &&
1908 !ir_block_living_add(self, value))
1913 if (!new_reads_t_v_find(&new_reads, value, NULL))
1915 if (!new_reads_t_v_add(&new_reads, value))
1921 /* See which operands are read and write operands */
1922 ir_op_read_write(instr->opcode, &read, &write);
1924 /* Go through the 3 main operands */
1925 for (o = 0; o < 3; ++o)
1927 if (!instr->_ops[o]) /* no such operand */
1930 value = instr->_ops[o];
1932 /* We only care about locals */
1933 if (value->store != store_value &&
1934 value->store != store_local)
1940 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1941 if (!ir_block_living_find(self, value, NULL) &&
1942 !ir_block_living_add(self, value))
1947 /* fprintf(stderr, "read: %s\n", value->_name); */
1948 if (!new_reads_t_v_find(&new_reads, value, NULL))
1950 if (!new_reads_t_v_add(&new_reads, value))
1956 /* write operands */
1957 /* When we write to a local, we consider it "dead" for the
1958 * remaining upper part of the function, since in SSA a value
1959 * can only be written once (== created)
1964 bool in_living = ir_block_living_find(self, value, &idx);
1965 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1967 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
1968 if (!in_living && !in_reads)
1973 /* If the value isn't alive it hasn't been read before... */
1974 /* TODO: See if the warning can be emitted during parsing or AST processing
1975 * otherwise have warning printed here.
1976 * IF printing a warning here: include filecontext_t,
1977 * and make sure it's only printed once
1978 * since this function is run multiple times.
1980 /* For now: debug info: */
1981 fprintf(stderr, "Value only written %s\n", value->name);
1982 tempbool = ir_value_life_merge(value, instr->eid);
1983 *changed = *changed || tempbool;
1985 ir_instr_dump(instr, dbg_ind, printf);
1989 /* since 'living' won't contain it
1990 * anymore, merge the value, since
1993 tempbool = ir_value_life_merge(value, instr->eid);
1996 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
1998 *changed = *changed || tempbool;
2000 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2001 if (!ir_block_living_remove(self, idx))
2006 if (!new_reads_t_v_remove(&new_reads, readidx))
2014 tempbool = ir_block_living_add_instr(self, instr->eid);
2015 /*fprintf(stderr, "living added values\n");*/
2016 *changed = *changed || tempbool;
2018 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2020 for (rd = 0; rd < new_reads.v_count; ++rd)
2022 if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
2023 if (!ir_block_living_add(self, new_reads.v[rd]))
2026 if (!i && !self->entries_count) {
2028 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
2031 MEM_VECTOR_CLEAR(&new_reads, v);
2035 if (self->run_id == self->owner->run_id)
2038 self->run_id = self->owner->run_id;
2040 for (i = 0; i < self->entries_count; ++i)
2042 ir_block *entry = self->entries[i];
2043 ir_block_life_propagate(entry, self, changed);
2048 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2049 MEM_VECTOR_CLEAR(&new_reads, v);
2054 /***********************************************************************
2057 * Since the IR has the convention of putting 'write' operands
2058 * at the beginning, we have to rotate the operands of instructions
2059 * properly in order to generate valid QCVM code.
2061 * Having destinations at a fixed position is more convenient. In QC
2062 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2063 * read from from OPA, and store to OPB rather than OPC. Which is
2064 * partially the reason why the implementation of these instructions
2065 * in darkplaces has been delayed for so long.
2067 * Breaking conventions is annoying...
2069 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2071 static bool gen_global_field(ir_value *global)
2073 if (global->isconst)
2075 ir_value *fld = global->constval.vpointer;
2077 printf("Invalid field constant with no field: %s\n", global->name);
2081 /* Now, in this case, a relocation would be impossible to code
2082 * since it looks like this:
2083 * .vector v = origin; <- parse error, wtf is 'origin'?
2086 * But we will need a general relocation support later anyway
2087 * for functions... might as well support that here.
2089 if (!fld->code.globaladdr) {
2090 printf("FIXME: Relocation support\n");
2094 /* copy the field's value */
2095 global->code.globaladdr = code_globals_add(code_globals_data[fld->code.globaladdr]);
2099 prog_section_field fld;
2101 fld.name = global->code.name;
2102 fld.offset = code_fields_elements;
2103 fld.type = global->fieldtype;
2105 if (fld.type == TYPE_VOID) {
2106 printf("Field is missing a type: %s\n", global->name);
2110 if (code_fields_add(fld) < 0)
2113 global->code.globaladdr = code_globals_add(fld.offset);
2115 if (global->code.globaladdr < 0)
2120 static bool gen_global_pointer(ir_value *global)
2122 if (global->isconst)
2124 ir_value *target = global->constval.vpointer;
2126 printf("Invalid pointer constant: %s\n", global->name);
2127 /* NULL pointers are pointing to the NULL constant, which also
2128 * sits at address 0, but still has an ir_value for itself.
2133 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2134 * void() foo; <- proto
2135 * void() *fooptr = &foo;
2136 * void() foo = { code }
2138 if (!target->code.globaladdr) {
2139 /* FIXME: Check for the constant nullptr ir_value!
2140 * because then code.globaladdr being 0 is valid.
2142 printf("FIXME: Relocation support\n");
2146 global->code.globaladdr = code_globals_add(target->code.globaladdr);
2150 global->code.globaladdr = code_globals_add(0);
2152 if (global->code.globaladdr < 0)
2157 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2159 prog_section_statement stmt;
2168 block->generated = true;
2169 block->code_start = code_statements_elements;
2170 for (i = 0; i < block->instr_count; ++i)
2172 instr = block->instr[i];
2174 if (instr->opcode == VINSTR_PHI) {
2175 printf("cannot generate virtual instruction (phi)\n");
2179 if (instr->opcode == VINSTR_JUMP) {
2180 target = instr->bops[0];
2181 /* for uncoditional jumps, if the target hasn't been generated
2182 * yet, we generate them right here.
2184 if (!target->generated) {
2189 /* otherwise we generate a jump instruction */
2190 stmt.opcode = INSTR_GOTO;
2191 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2194 if (code_statements_add(stmt) < 0)
2197 /* no further instructions can be in this block */
2201 if (instr->opcode == VINSTR_COND) {
2202 ontrue = instr->bops[0];
2203 onfalse = instr->bops[1];
2204 /* TODO: have the AST signal which block should
2205 * come first: eg. optimize IFs without ELSE...
2208 stmt.o1.u1 = instr->_ops[0]->code.globaladdr;
2212 if (ontrue->generated) {
2213 stmt.opcode = INSTR_IF;
2214 stmt.o2.s1 = (ontrue->code_start-1) - code_statements_elements;
2215 if (code_statements_add(stmt) < 0)
2218 if (onfalse->generated) {
2219 stmt.opcode = INSTR_IFNOT;
2220 stmt.o2.s1 = (onfalse->code_start-1) - code_statements_elements;
2221 if (code_statements_add(stmt) < 0)
2224 if (!ontrue->generated) {
2225 if (onfalse->generated) {
2230 if (!onfalse->generated) {
2231 if (ontrue->generated) {
2236 /* neither ontrue nor onfalse exist */
2237 stmt.opcode = INSTR_IFNOT;
2238 stidx = code_statements_elements;
2239 if (code_statements_add(stmt) < 0)
2241 /* on false we jump, so add ontrue-path */
2242 if (!gen_blocks_recursive(func, ontrue))
2244 /* fixup the jump address */
2245 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2246 /* generate onfalse path */
2247 if (onfalse->generated) {
2248 /* fixup the jump address */
2249 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2250 /* may have been generated in the previous recursive call */
2251 stmt.opcode = INSTR_GOTO;
2252 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2255 return (code_statements_add(stmt) >= 0);
2257 /* if not, generate now */
2262 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2263 /* Trivial call translation:
2264 * copy all params to OFS_PARM*
2265 * if the output's storetype is not store_return,
2266 * add append a STORE instruction!
2268 * NOTES on how to do it better without much trouble:
2269 * -) The liferanges!
2270 * Simply check the liferange of all parameters for
2271 * other CALLs. For each param with no CALL in its
2272 * liferange, we can store it in an OFS_PARM at
2273 * generation already. This would even include later
2274 * reuse.... probably... :)
2279 for (p = 0; p < instr->params_count; ++p)
2281 ir_value *param = instr->params[p];
2283 stmt.opcode = INSTR_STORE_F;
2286 stmt.opcode = type_store_instr[param->vtype];
2287 stmt.o1.u1 = param->code.globaladdr;
2288 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2289 if (code_statements_add(stmt) < 0)
2292 stmt.opcode = INSTR_CALL0 + instr->params_count;
2293 if (stmt.opcode > INSTR_CALL8)
2294 stmt.opcode = INSTR_CALL8;
2295 stmt.o1.u1 = instr->_ops[1]->code.globaladdr;
2298 if (code_statements_add(stmt) < 0)
2301 retvalue = instr->_ops[0];
2302 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2304 /* not to be kept in OFS_RETURN */
2305 stmt.opcode = type_store_instr[retvalue->vtype];
2306 stmt.o1.u1 = OFS_RETURN;
2307 stmt.o2.u1 = retvalue->code.globaladdr;
2309 if (code_statements_add(stmt) < 0)
2315 if (instr->opcode == INSTR_STATE) {
2316 printf("TODO: state instruction\n");
2320 stmt.opcode = instr->opcode;
2325 /* This is the general order of operands */
2327 stmt.o3.u1 = instr->_ops[0]->code.globaladdr;
2330 stmt.o1.u1 = instr->_ops[1]->code.globaladdr;
2333 stmt.o2.u1 = instr->_ops[2]->code.globaladdr;
2335 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2337 stmt.o1.u1 = stmt.o3.u1;
2340 else if ((stmt.opcode >= INSTR_STORE_F &&
2341 stmt.opcode <= INSTR_STORE_FNC) ||
2342 (stmt.opcode >= INSTR_NOT_F &&
2343 stmt.opcode <= INSTR_NOT_FNC))
2345 /* 2-operand instructions with A -> B */
2346 stmt.o2.u1 = stmt.o3.u1;
2350 if (code_statements_add(stmt) < 0)
2356 static bool gen_function_code(ir_function *self)
2359 prog_section_statement stmt;
2361 /* Starting from entry point, we generate blocks "as they come"
2362 * for now. Dead blocks will not be translated obviously.
2364 if (!self->blocks_count) {
2365 printf("Function '%s' declared without body.\n", self->name);
2369 block = self->blocks[0];
2370 if (block->generated)
2373 if (!gen_blocks_recursive(self, block)) {
2374 printf("failed to generate blocks for '%s'\n", self->name);
2378 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2379 stmt.opcode = AINSTR_END;
2383 if (code_statements_add(stmt) < 0)
2388 static bool gen_global_function(ir_builder *ir, ir_value *global)
2390 prog_section_function fun;
2394 size_t local_var_end;
2396 if (!global->isconst || (!global->constval.vfunc))
2398 printf("Invalid state of function-global: not constant: %s\n", global->name);
2402 irfun = global->constval.vfunc;
2404 fun.name = global->code.name;
2405 fun.file = code_cachedstring(global->context.file);
2406 fun.profile = 0; /* always 0 */
2407 fun.nargs = irfun->params_count;
2409 for (i = 0;i < 8; ++i) {
2413 fun.argsize[i] = type_sizeof[irfun->params[i]];
2416 fun.firstlocal = code_globals_elements;
2417 fun.locals = irfun->allocated_locals + irfun->locals_count;
2420 for (i = 0; i < irfun->locals_count; ++i) {
2421 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2422 printf("Failed to generate global %s\n", irfun->locals[i]->name);
2426 if (irfun->locals_count) {
2427 ir_value *last = irfun->locals[irfun->locals_count-1];
2428 local_var_end = last->code.globaladdr;
2429 local_var_end += type_sizeof[last->vtype];
2431 for (i = 0; i < irfun->values_count; ++i)
2433 /* generate code.globaladdr for ssa values */
2434 ir_value *v = irfun->values[i];
2435 v->code.globaladdr = local_var_end + v->code.local;
2437 for (i = 0; i < irfun->locals_count; ++i) {
2438 /* fill the locals with zeros */
2439 code_globals_add(0);
2443 fun.entry = irfun->builtin;
2445 fun.entry = code_statements_elements;
2446 if (!gen_function_code(irfun)) {
2447 printf("Failed to generate code for function %s\n", irfun->name);
2452 return (code_functions_add(fun) >= 0);
2455 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2458 prog_section_def def;
2460 def.type = global->vtype;
2461 def.offset = code_globals_elements;
2462 def.name = global->code.name = code_genstring(global->name);
2464 switch (global->vtype)
2467 if (code_defs_add(def) < 0)
2469 return gen_global_pointer(global);
2471 if (code_defs_add(def) < 0)
2473 return gen_global_field(global);
2478 if (code_defs_add(def) < 0)
2481 if (global->isconst) {
2482 iptr = (int32_t*)&global->constval.vfloat;
2483 global->code.globaladdr = code_globals_add(*iptr);
2485 global->code.globaladdr = code_globals_add(0);
2487 return global->code.globaladdr >= 0;
2491 if (code_defs_add(def) < 0)
2493 if (global->isconst)
2494 global->code.globaladdr = code_globals_add(code_cachedstring(global->constval.vstring));
2496 global->code.globaladdr = code_globals_add(0);
2497 return global->code.globaladdr >= 0;
2500 case TYPE_QUATERNION:
2504 if (code_defs_add(def) < 0)
2507 if (global->isconst) {
2508 iptr = (int32_t*)&global->constval.vvec;
2509 global->code.globaladdr = code_globals_add(iptr[0]);
2510 if (global->code.globaladdr < 0)
2512 for (d = 1; d < type_sizeof(global->vtype); ++d)
2514 if (code_globals_add(iptr[d]) < 0)
2518 global->code.globaladdr = code_globals_add(0);
2519 if (global->code.globaladdr < 0)
2521 for (d = 1; d < type_sizeof(global->vtype); ++d)
2523 if (code_globals_add(0) < 0)
2527 return global->code.globaladdr >= 0;
2530 if (code_defs_add(def) < 0)
2532 global->code.globaladdr = code_globals_elements;
2533 code_globals_add(code_functions_elements);
2534 return gen_global_function(self, global);
2536 /* assume biggest type */
2537 global->code.globaladdr = code_globals_add(0);
2538 code_globals_add(0);
2539 code_globals_add(0);
2542 /* refuse to create 'void' type or any other fancy business. */
2543 printf("Invalid type for global variable %s\n", global->name);
2548 bool ir_builder_generate(ir_builder *self, const char *filename)
2554 for (i = 0; i < self->globals_count; ++i)
2556 if (!ir_builder_gen_global(self, self->globals[i])) {
2561 printf("writing '%s'...\n", filename);
2562 return code_write(filename);
2565 /***********************************************************************
2566 *IR DEBUG Dump functions...
2569 #define IND_BUFSZ 1024
2571 const char *qc_opname(int op)
2573 if (op < 0) return "<INVALID>";
2574 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2575 return asm_instr[op].m;
2577 case VINSTR_PHI: return "PHI";
2578 case VINSTR_JUMP: return "JUMP";
2579 case VINSTR_COND: return "COND";
2580 default: return "<UNK>";
2584 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2587 char indent[IND_BUFSZ];
2591 oprintf("module %s\n", b->name);
2592 for (i = 0; i < b->globals_count; ++i)
2595 if (b->globals[i]->isconst)
2596 oprintf("%s = ", b->globals[i]->name);
2597 ir_value_dump(b->globals[i], oprintf);
2600 for (i = 0; i < b->functions_count; ++i)
2601 ir_function_dump(b->functions[i], indent, oprintf);
2602 oprintf("endmodule %s\n", b->name);
2605 void ir_function_dump(ir_function *f, char *ind,
2606 int (*oprintf)(const char*, ...))
2609 oprintf("%sfunction %s\n", ind, f->name);
2610 strncat(ind, "\t", IND_BUFSZ);
2611 if (f->locals_count)
2613 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2614 for (i = 0; i < f->locals_count; ++i) {
2615 oprintf("%s\t", ind);
2616 ir_value_dump(f->locals[i], oprintf);
2620 if (f->blocks_count)
2622 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2623 for (i = 0; i < f->blocks_count; ++i) {
2624 if (f->blocks[i]->run_id != f->run_id) {
2625 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2627 ir_block_dump(f->blocks[i], ind, oprintf);
2631 ind[strlen(ind)-1] = 0;
2632 oprintf("%sendfunction %s\n", ind, f->name);
2635 void ir_block_dump(ir_block* b, char *ind,
2636 int (*oprintf)(const char*, ...))
2639 oprintf("%s:%s\n", ind, b->label);
2640 strncat(ind, "\t", IND_BUFSZ);
2642 for (i = 0; i < b->instr_count; ++i)
2643 ir_instr_dump(b->instr[i], ind, oprintf);
2644 ind[strlen(ind)-1] = 0;
2647 void dump_phi(ir_instr *in, char *ind,
2648 int (*oprintf)(const char*, ...))
2651 oprintf("%s <- phi ", in->_ops[0]->name);
2652 for (i = 0; i < in->phi_count; ++i)
2654 oprintf("([%s] : %s) ", in->phi[i].from->label,
2655 in->phi[i].value->name);
2660 void ir_instr_dump(ir_instr *in, char *ind,
2661 int (*oprintf)(const char*, ...))
2664 const char *comma = NULL;
2666 oprintf("%s (%i) ", ind, (int)in->eid);
2668 if (in->opcode == VINSTR_PHI) {
2669 dump_phi(in, ind, oprintf);
2673 strncat(ind, "\t", IND_BUFSZ);
2675 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2676 ir_value_dump(in->_ops[0], oprintf);
2677 if (in->_ops[1] || in->_ops[2])
2680 oprintf("%s\t", qc_opname(in->opcode));
2681 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2682 ir_value_dump(in->_ops[0], oprintf);
2687 for (i = 1; i != 3; ++i) {
2691 ir_value_dump(in->_ops[i], oprintf);
2699 oprintf("[%s]", in->bops[0]->label);
2703 oprintf("%s[%s]", comma, in->bops[1]->label);
2705 ind[strlen(ind)-1] = 0;
2708 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
2717 oprintf("%g", v->constval.vfloat);
2720 oprintf("'%g %g %g'",
2723 v->constval.vvec.z);
2726 oprintf("(entity)");
2729 oprintf("\"%s\"", v->constval.vstring);
2733 oprintf("%i", v->constval.vint);
2738 v->constval.vpointer->name);
2742 oprintf("%s", v->name);
2746 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
2749 oprintf("Life of %s:\n", self->name);
2750 for (i = 0; i < self->life_count; ++i)
2752 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);