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 const char *type_name[TYPE_COUNT] = {
49 size_t type_sizeof[TYPE_COUNT] = {
56 1, /* TYPE_FUNCTION */
61 4, /* TYPE_QUATERNION */
63 16, /* TYPE_VARIANT */
66 uint16_t type_store_instr[TYPE_COUNT] = {
67 INSTR_STORE_F, /* should use I when having integer support */
74 INSTR_STORE_ENT, /* should use I */
76 INSTR_STORE_I, /* integer type */
81 INSTR_STORE_M, /* variant, should never be accessed */
84 uint16_t type_storep_instr[TYPE_COUNT] = {
85 INSTR_STOREP_F, /* should use I when having integer support */
92 INSTR_STOREP_ENT, /* should use I */
94 INSTR_STOREP_ENT, /* integer type */
99 INSTR_STOREP_M, /* variant, should never be accessed */
102 MEM_VEC_FUNCTIONS(ir_value_vector, ir_value*, v)
104 /***********************************************************************
108 ir_builder* ir_builder_new(const char *modulename)
112 self = (ir_builder*)mem_a(sizeof(*self));
116 MEM_VECTOR_INIT(self, functions);
117 MEM_VECTOR_INIT(self, globals);
119 if (!ir_builder_set_name(self, modulename)) {
124 /* globals which always exist */
126 /* for now we give it a vector size */
127 ir_builder_create_global(self, "OFS_RETURN", TYPE_VARIANT);
132 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
133 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
135 void ir_builder_delete(ir_builder* self)
138 mem_d((void*)self->name);
139 for (i = 0; i != self->functions_count; ++i) {
140 ir_function_delete(self->functions[i]);
142 MEM_VECTOR_CLEAR(self, functions);
143 for (i = 0; i != self->globals_count; ++i) {
144 ir_value_delete(self->globals[i]);
146 MEM_VECTOR_CLEAR(self, globals);
150 bool ir_builder_set_name(ir_builder *self, const char *name)
153 mem_d((void*)self->name);
154 self->name = util_strdup(name);
158 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
161 for (i = 0; i < self->functions_count; ++i) {
162 if (!strcmp(name, self->functions[i]->name))
163 return self->functions[i];
168 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
170 ir_function *fn = ir_builder_get_function(self, name);
175 fn = ir_function_new(self, outtype);
176 if (!ir_function_set_name(fn, name) ||
177 !ir_builder_functions_add(self, fn) )
179 ir_function_delete(fn);
183 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
185 ir_function_delete(fn);
189 fn->value->isconst = true;
190 fn->value->outtype = outtype;
191 fn->value->constval.vfunc = fn;
192 fn->value->context = fn->context;
197 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
200 for (i = 0; i < self->globals_count; ++i) {
201 if (!strcmp(self->globals[i]->name, name))
202 return self->globals[i];
207 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
209 ir_value *ve = ir_builder_get_global(self, name);
214 ve = ir_value_var(name, store_global, vtype);
215 if (!ir_builder_globals_add(self, ve)) {
222 /***********************************************************************
226 bool ir_function_naive_phi(ir_function*);
227 void ir_function_enumerate(ir_function*);
228 bool ir_function_calculate_liferanges(ir_function*);
229 bool ir_function_allocate_locals(ir_function*);
231 ir_function* ir_function_new(ir_builder* owner, int outtype)
234 self = (ir_function*)mem_a(sizeof(*self));
240 if (!ir_function_set_name(self, "<@unnamed>")) {
245 self->context.file = "<@no context>";
246 self->context.line = 0;
247 self->outtype = outtype;
250 MEM_VECTOR_INIT(self, params);
251 MEM_VECTOR_INIT(self, blocks);
252 MEM_VECTOR_INIT(self, values);
253 MEM_VECTOR_INIT(self, locals);
258 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
259 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
260 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
261 MEM_VEC_FUNCTIONS(ir_function, int, params)
263 bool ir_function_set_name(ir_function *self, const char *name)
266 mem_d((void*)self->name);
267 self->name = util_strdup(name);
271 void ir_function_delete(ir_function *self)
274 mem_d((void*)self->name);
276 for (i = 0; i != self->blocks_count; ++i)
277 ir_block_delete(self->blocks[i]);
278 MEM_VECTOR_CLEAR(self, blocks);
280 MEM_VECTOR_CLEAR(self, params);
282 for (i = 0; i != self->values_count; ++i)
283 ir_value_delete(self->values[i]);
284 MEM_VECTOR_CLEAR(self, values);
286 for (i = 0; i != self->locals_count; ++i)
287 ir_value_delete(self->locals[i]);
288 MEM_VECTOR_CLEAR(self, locals);
290 /* self->value is deleted by the builder */
295 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
297 return ir_function_values_add(self, v);
300 ir_block* ir_function_create_block(ir_function *self, const char *label)
302 ir_block* bn = ir_block_new(self, label);
303 memcpy(&bn->context, &self->context, sizeof(self->context));
304 if (!ir_function_blocks_add(self, bn)) {
311 bool ir_function_finalize(ir_function *self)
316 if (!ir_function_naive_phi(self))
319 ir_function_enumerate(self);
321 if (!ir_function_calculate_liferanges(self))
324 if (!ir_function_allocate_locals(self))
329 ir_value* ir_function_get_local(ir_function *self, const char *name)
332 for (i = 0; i < self->locals_count; ++i) {
333 if (!strcmp(self->locals[i]->name, name))
334 return self->locals[i];
339 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype)
341 ir_value *ve = ir_function_get_local(self, name);
346 ve = ir_value_var(name, store_local, vtype);
347 if (!ir_function_locals_add(self, ve)) {
354 /***********************************************************************
358 ir_block* ir_block_new(ir_function* owner, const char *name)
361 self = (ir_block*)mem_a(sizeof(*self));
365 memset(self, 0, sizeof(*self));
368 if (!ir_block_set_label(self, name)) {
373 self->context.file = "<@no context>";
374 self->context.line = 0;
376 MEM_VECTOR_INIT(self, instr);
377 MEM_VECTOR_INIT(self, entries);
378 MEM_VECTOR_INIT(self, exits);
381 self->is_return = false;
383 MEM_VECTOR_INIT(self, living);
385 self->generated = false;
389 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
390 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
391 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
392 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
394 void ir_block_delete(ir_block* self)
398 for (i = 0; i != self->instr_count; ++i)
399 ir_instr_delete(self->instr[i]);
400 MEM_VECTOR_CLEAR(self, instr);
401 MEM_VECTOR_CLEAR(self, entries);
402 MEM_VECTOR_CLEAR(self, exits);
403 MEM_VECTOR_CLEAR(self, living);
407 bool ir_block_set_label(ir_block *self, const char *name)
410 mem_d((void*)self->label);
411 self->label = util_strdup(name);
412 return !!self->label;
415 /***********************************************************************
419 ir_instr* ir_instr_new(ir_block* owner, int op)
422 self = (ir_instr*)mem_a(sizeof(*self));
427 self->context.file = "<@no context>";
428 self->context.line = 0;
430 self->_ops[0] = NULL;
431 self->_ops[1] = NULL;
432 self->_ops[2] = NULL;
433 self->bops[0] = NULL;
434 self->bops[1] = NULL;
435 MEM_VECTOR_INIT(self, phi);
436 MEM_VECTOR_INIT(self, params);
441 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
442 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
444 void ir_instr_delete(ir_instr *self)
447 /* The following calls can only delete from
448 * vectors, we still want to delete this instruction
449 * so ignore the return value. Since with the warn_unused_result attribute
450 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
451 * I have to improvise here and use if(foo());
453 for (i = 0; i < self->phi_count; ++i) {
455 if (ir_value_writes_find(self->phi[i].value, self, &idx))
456 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
457 if (ir_value_reads_find(self->phi[i].value, self, &idx))
458 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
460 MEM_VECTOR_CLEAR(self, phi);
461 for (i = 0; i < self->params_count; ++i) {
463 if (ir_value_writes_find(self->params[i], self, &idx))
464 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
465 if (ir_value_reads_find(self->params[i], self, &idx))
466 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
468 MEM_VECTOR_CLEAR(self, params);
469 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
470 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
471 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
475 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
477 if (self->_ops[op]) {
479 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
481 if (!ir_value_writes_remove(self->_ops[op], idx))
484 else if (ir_value_reads_find(self->_ops[op], self, &idx))
486 if (!ir_value_reads_remove(self->_ops[op], idx))
492 if (!ir_value_writes_add(v, self))
495 if (!ir_value_reads_add(v, self))
503 /***********************************************************************
507 ir_value* ir_value_var(const char *name, int storetype, int vtype)
510 self = (ir_value*)mem_a(sizeof(*self));
512 self->fieldtype = TYPE_VOID;
513 self->outtype = TYPE_VOID;
514 self->store = storetype;
515 MEM_VECTOR_INIT(self, reads);
516 MEM_VECTOR_INIT(self, writes);
517 self->isconst = false;
518 self->context.file = "<@no context>";
519 self->context.line = 0;
521 ir_value_set_name(self, name);
523 memset(&self->constval, 0, sizeof(self->constval));
524 memset(&self->code, 0, sizeof(self->code));
526 MEM_VECTOR_INIT(self, life);
529 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
530 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
531 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
533 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
535 ir_value *v = ir_value_var(name, storetype, vtype);
538 if (!ir_function_collect_value(owner, v))
546 void ir_value_delete(ir_value* self)
549 mem_d((void*)self->name);
552 if (self->vtype == TYPE_STRING)
553 mem_d((void*)self->constval.vstring);
555 MEM_VECTOR_CLEAR(self, reads);
556 MEM_VECTOR_CLEAR(self, writes);
557 MEM_VECTOR_CLEAR(self, life);
561 void ir_value_set_name(ir_value *self, const char *name)
564 mem_d((void*)self->name);
565 self->name = util_strdup(name);
568 bool ir_value_set_float(ir_value *self, float f)
570 if (self->vtype != TYPE_FLOAT)
572 self->constval.vfloat = f;
573 self->isconst = true;
577 bool ir_value_set_func(ir_value *self, int f)
579 if (self->vtype != TYPE_FUNCTION)
581 self->constval.vint = f;
582 self->isconst = true;
586 bool ir_value_set_vector(ir_value *self, vector v)
588 if (self->vtype != TYPE_VECTOR)
590 self->constval.vvec = v;
591 self->isconst = true;
595 bool ir_value_set_quaternion(ir_value *self, quaternion v)
597 if (self->vtype != TYPE_QUATERNION)
599 memcpy(&self->constval.vquat, v, sizeof(self->constval.vquat));
600 self->isconst = true;
604 bool ir_value_set_matrix(ir_value *self, matrix v)
606 if (self->vtype != TYPE_MATRIX)
608 memcpy(&self->constval.vmat, v, sizeof(self->constval.vmat));
609 self->isconst = true;
613 bool ir_value_set_string(ir_value *self, const char *str)
615 if (self->vtype != TYPE_STRING)
617 self->constval.vstring = util_strdup(str);
618 self->isconst = true;
623 bool ir_value_set_int(ir_value *self, int i)
625 if (self->vtype != TYPE_INTEGER)
627 self->constval.vint = i;
628 self->isconst = true;
633 bool ir_value_lives(ir_value *self, size_t at)
636 for (i = 0; i < self->life_count; ++i)
638 ir_life_entry_t *life = &self->life[i];
639 if (life->start <= at && at <= life->end)
641 if (life->start > at) /* since it's ordered */
647 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
650 if (!ir_value_life_add(self, e)) /* naive... */
652 for (k = self->life_count-1; k > idx; --k)
653 self->life[k] = self->life[k-1];
658 bool ir_value_life_merge(ir_value *self, size_t s)
661 ir_life_entry_t *life = NULL;
662 ir_life_entry_t *before = NULL;
663 ir_life_entry_t new_entry;
665 /* Find the first range >= s */
666 for (i = 0; i < self->life_count; ++i)
669 life = &self->life[i];
673 /* nothing found? append */
674 if (i == self->life_count) {
676 if (life && life->end+1 == s)
678 /* previous life range can be merged in */
682 if (life && life->end >= s)
685 if (!ir_value_life_add(self, e))
686 return false; /* failing */
692 if (before->end + 1 == s &&
693 life->start - 1 == s)
696 before->end = life->end;
697 if (!ir_value_life_remove(self, i))
698 return false; /* failing */
701 if (before->end + 1 == s)
707 /* already contained */
708 if (before->end >= s)
712 if (life->start - 1 == s)
717 /* insert a new entry */
718 new_entry.start = new_entry.end = s;
719 return ir_value_life_insert(self, i, new_entry);
722 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
726 if (!other->life_count)
729 if (!self->life_count) {
730 for (i = 0; i < other->life_count; ++i) {
731 if (!ir_value_life_add(self, other->life[i]))
738 for (i = 0; i < other->life_count; ++i)
740 const ir_life_entry_t *life = &other->life[i];
743 ir_life_entry_t *entry = &self->life[myi];
745 if (life->end+1 < entry->start)
747 /* adding an interval before entry */
748 if (!ir_value_life_insert(self, myi, *life))
754 if (life->start < entry->start &&
755 life->end >= entry->start)
757 /* starts earlier and overlaps */
758 entry->start = life->start;
761 if (life->end > entry->end &&
762 life->start-1 <= entry->end)
764 /* ends later and overlaps */
765 entry->end = life->end;
768 /* see if our change combines it with the next ranges */
769 while (myi+1 < self->life_count &&
770 entry->end+1 >= self->life[1+myi].start)
772 /* overlaps with (myi+1) */
773 if (entry->end < self->life[1+myi].end)
774 entry->end = self->life[1+myi].end;
775 if (!ir_value_life_remove(self, myi+1))
777 entry = &self->life[myi];
780 /* see if we're after the entry */
781 if (life->start > entry->end)
784 /* append if we're at the end */
785 if (myi >= self->life_count) {
786 if (!ir_value_life_add(self, *life))
790 /* otherweise check the next range */
799 bool ir_values_overlap(const ir_value *a, const ir_value *b)
801 /* For any life entry in A see if it overlaps with
802 * any life entry in B.
803 * Note that the life entries are orderes, so we can make a
804 * more efficient algorithm there than naively translating the
808 ir_life_entry_t *la, *lb, *enda, *endb;
810 /* first of all, if either has no life range, they cannot clash */
811 if (!a->life_count || !b->life_count)
816 enda = la + a->life_count;
817 endb = lb + b->life_count;
820 /* check if the entries overlap, for that,
821 * both must start before the other one ends.
823 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
824 if (la->start <= lb->end &&
825 lb->start <= la->end)
827 if (la->start < lb->end &&
834 /* entries are ordered
835 * one entry is earlier than the other
836 * that earlier entry will be moved forward
838 if (la->start < lb->start)
840 /* order: A B, move A forward
841 * check if we hit the end with A
846 else if (lb->start < la->start)
848 /* order: B A, move B forward
849 * check if we hit the end with B
858 /***********************************************************************
862 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
864 if (target->store == store_value) {
865 fprintf(stderr, "cannot store to an SSA value\n");
866 fprintf(stderr, "trying to store: %s <- %s\n", target->name, what->name);
869 ir_instr *in = ir_instr_new(self, op);
872 if (!ir_instr_op(in, 0, target, true) ||
873 !ir_instr_op(in, 1, what, false) ||
874 !ir_block_instr_add(self, in) )
882 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
886 if (target->vtype == TYPE_VARIANT)
889 vtype = target->vtype;
892 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
893 op = INSTR_CONV_ITOF;
894 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
895 op = INSTR_CONV_FTOI;
897 op = type_store_instr[vtype];
899 return ir_block_create_store_op(self, op, target, what);
902 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
907 if (target->vtype != TYPE_POINTER)
910 /* storing using pointer - target is a pointer, type must be
911 * inferred from source
915 op = type_storep_instr[vtype];
916 return ir_block_create_store_op(self, op, target, what);
919 bool ir_block_create_return(ir_block *self, ir_value *v)
923 fprintf(stderr, "block already ended (%s)\n", self->label);
927 self->is_return = true;
928 in = ir_instr_new(self, INSTR_RETURN);
932 if (!ir_instr_op(in, 0, v, false) ||
933 !ir_block_instr_add(self, in) )
940 bool ir_block_create_if(ir_block *self, ir_value *v,
941 ir_block *ontrue, ir_block *onfalse)
945 fprintf(stderr, "block already ended (%s)\n", self->label);
949 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
950 in = ir_instr_new(self, VINSTR_COND);
954 if (!ir_instr_op(in, 0, v, false)) {
959 in->bops[0] = ontrue;
960 in->bops[1] = onfalse;
962 if (!ir_block_instr_add(self, in))
965 if (!ir_block_exits_add(self, ontrue) ||
966 !ir_block_exits_add(self, onfalse) ||
967 !ir_block_entries_add(ontrue, self) ||
968 !ir_block_entries_add(onfalse, self) )
975 bool ir_block_create_jump(ir_block *self, ir_block *to)
979 fprintf(stderr, "block already ended (%s)\n", self->label);
983 in = ir_instr_new(self, VINSTR_JUMP);
988 if (!ir_block_instr_add(self, in))
991 if (!ir_block_exits_add(self, to) ||
992 !ir_block_entries_add(to, self) )
999 bool ir_block_create_goto(ir_block *self, ir_block *to)
1003 fprintf(stderr, "block already ended (%s)\n", self->label);
1007 in = ir_instr_new(self, INSTR_GOTO);
1012 if (!ir_block_instr_add(self, in))
1015 if (!ir_block_exits_add(self, to) ||
1016 !ir_block_entries_add(to, self) )
1023 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1027 in = ir_instr_new(self, VINSTR_PHI);
1030 out = ir_value_out(self->owner, label, store_value, ot);
1032 ir_instr_delete(in);
1035 if (!ir_instr_op(in, 0, out, true)) {
1036 ir_instr_delete(in);
1037 ir_value_delete(out);
1040 if (!ir_block_instr_add(self, in)) {
1041 ir_instr_delete(in);
1042 ir_value_delete(out);
1048 ir_value* ir_phi_value(ir_instr *self)
1050 return self->_ops[0];
1053 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1057 if (!ir_block_entries_find(self->owner, b, NULL)) {
1058 /* Must not be possible to cause this, otherwise the AST
1059 * is doing something wrong.
1061 fprintf(stderr, "Invalid entry block for PHI\n");
1067 if (!ir_value_reads_add(v, self))
1069 return ir_instr_phi_add(self, pe);
1072 /* call related code */
1073 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1077 in = ir_instr_new(self, INSTR_CALL0);
1080 out = ir_value_out(self->owner, label, store_return, func->outtype);
1082 ir_instr_delete(in);
1085 if (!ir_instr_op(in, 0, out, true) ||
1086 !ir_instr_op(in, 1, func, false) ||
1087 !ir_block_instr_add(self, in))
1089 ir_instr_delete(in);
1090 ir_value_delete(out);
1096 ir_value* ir_call_value(ir_instr *self)
1098 return self->_ops[0];
1101 bool ir_call_param(ir_instr* self, ir_value *v)
1103 if (!ir_instr_params_add(self, v))
1105 if (!ir_value_reads_add(v, self)) {
1106 if (!ir_instr_params_remove(self, self->params_count-1))
1107 GMQCC_SUPPRESS_EMPTY_BODY;
1113 /* binary op related code */
1115 ir_value* ir_block_create_binop(ir_block *self,
1116 const char *label, int opcode,
1117 ir_value *left, ir_value *right)
1139 case INSTR_SUB_S: /* -- offset of string as float */
1144 case INSTR_BITOR_IF:
1145 case INSTR_BITOR_FI:
1146 case INSTR_BITAND_FI:
1147 case INSTR_BITAND_IF:
1162 case INSTR_BITAND_I:
1165 case INSTR_RSHIFT_I:
1166 case INSTR_LSHIFT_I:
1187 /* boolean operations result in floats */
1188 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1190 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1193 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1198 if (ot == TYPE_VOID) {
1199 /* The AST or parser were supposed to check this! */
1203 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1206 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1207 int op, ir_value *a, ir_value *b, int outype)
1212 out = ir_value_out(self->owner, label, store_value, outype);
1216 instr = ir_instr_new(self, op);
1218 ir_value_delete(out);
1222 if (!ir_instr_op(instr, 0, out, true) ||
1223 !ir_instr_op(instr, 1, a, false) ||
1224 !ir_instr_op(instr, 2, b, false) )
1229 if (!ir_block_instr_add(self, instr))
1234 ir_instr_delete(instr);
1235 ir_value_delete(out);
1239 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1241 /* Support for various pointer types todo if so desired */
1242 if (ent->vtype != TYPE_ENTITY)
1245 if (field->vtype != TYPE_FIELD)
1248 return ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1251 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1254 if (ent->vtype != TYPE_ENTITY)
1257 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1258 if (field->vtype != TYPE_FIELD)
1263 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1264 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1265 case TYPE_STRING: op = INSTR_LOAD_S; break;
1266 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1267 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1269 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1270 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1272 case TYPE_QUATERNION: op = INSTR_LOAD_Q; break;
1273 case TYPE_MATRIX: op = INSTR_LOAD_M; break;
1278 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1281 ir_value* ir_block_create_add(ir_block *self,
1283 ir_value *left, ir_value *right)
1286 int l = left->vtype;
1287 int r = right->vtype;
1306 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1308 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1314 return ir_block_create_binop(self, label, op, left, right);
1317 ir_value* ir_block_create_sub(ir_block *self,
1319 ir_value *left, ir_value *right)
1322 int l = left->vtype;
1323 int r = right->vtype;
1343 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1345 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1351 return ir_block_create_binop(self, label, op, left, right);
1354 ir_value* ir_block_create_mul(ir_block *self,
1356 ir_value *left, ir_value *right)
1359 int l = left->vtype;
1360 int r = right->vtype;
1377 case TYPE_QUATERNION:
1385 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1387 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1389 else if ( (l == TYPE_QUATERNION && r == TYPE_FLOAT) )
1391 else if ( (l == TYPE_MATRIX && r == TYPE_FLOAT) )
1394 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1396 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1398 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1400 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1406 return ir_block_create_binop(self, label, op, left, right);
1409 ir_value* ir_block_create_div(ir_block *self,
1411 ir_value *left, ir_value *right)
1414 int l = left->vtype;
1415 int r = right->vtype;
1432 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1434 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1436 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1442 return ir_block_create_binop(self, label, op, left, right);
1445 /* PHI resolving breaks the SSA, and must thus be the last
1446 * step before life-range calculation.
1449 static bool ir_block_naive_phi(ir_block *self);
1450 bool ir_function_naive_phi(ir_function *self)
1454 for (i = 0; i < self->blocks_count; ++i)
1456 if (!ir_block_naive_phi(self->blocks[i]))
1462 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1467 /* create a store */
1468 if (!ir_block_create_store(block, old, what))
1471 /* we now move it up */
1472 instr = block->instr[block->instr_count-1];
1473 for (i = block->instr_count; i > iid; --i)
1474 block->instr[i] = block->instr[i-1];
1475 block->instr[i] = instr;
1480 static bool ir_block_naive_phi(ir_block *self)
1483 /* FIXME: optionally, create_phi can add the phis
1484 * to a list so we don't need to loop through blocks
1485 * - anyway: "don't optimize YET"
1487 for (i = 0; i < self->instr_count; ++i)
1489 ir_instr *instr = self->instr[i];
1490 if (instr->opcode != VINSTR_PHI)
1493 if (!ir_block_instr_remove(self, i))
1495 --i; /* NOTE: i+1 below */
1497 for (p = 0; p < instr->phi_count; ++p)
1499 ir_value *v = instr->phi[p].value;
1500 for (w = 0; w < v->writes_count; ++w) {
1503 if (!v->writes[w]->_ops[0])
1506 /* When the write was to a global, we have to emit a mov */
1507 old = v->writes[w]->_ops[0];
1509 /* The original instruction now writes to the PHI target local */
1510 if (v->writes[w]->_ops[0] == v)
1511 v->writes[w]->_ops[0] = instr->_ops[0];
1513 if (old->store != store_value && old->store != store_local)
1515 /* If it originally wrote to a global we need to store the value
1518 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1520 if (i+1 < self->instr_count)
1521 instr = self->instr[i+1];
1524 /* In case I forget and access instr later, it'll be NULL
1525 * when it's a problem, to make sure we crash, rather than accessing
1531 /* If it didn't, we can replace all reads by the phi target now. */
1533 for (r = 0; r < old->reads_count; ++r)
1536 ir_instr *ri = old->reads[r];
1537 for (op = 0; op < ri->phi_count; ++op) {
1538 if (ri->phi[op].value == old)
1539 ri->phi[op].value = v;
1541 for (op = 0; op < 3; ++op) {
1542 if (ri->_ops[op] == old)
1549 ir_instr_delete(instr);
1554 /***********************************************************************
1555 *IR Temp allocation code
1556 * Propagating value life ranges by walking through the function backwards
1557 * until no more changes are made.
1558 * In theory this should happen once more than once for every nested loop
1560 * Though this implementation might run an additional time for if nests.
1569 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1571 /* Enumerate instructions used by value's life-ranges
1573 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1577 for (i = 0; i < self->instr_count; ++i)
1579 self->instr[i]->eid = eid++;
1584 /* Enumerate blocks and instructions.
1585 * The block-enumeration is unordered!
1586 * We do not really use the block enumreation, however
1587 * the instruction enumeration is important for life-ranges.
1589 void ir_function_enumerate(ir_function *self)
1592 size_t instruction_id = 0;
1593 for (i = 0; i < self->blocks_count; ++i)
1595 self->blocks[i]->eid = i;
1596 self->blocks[i]->run_id = 0;
1597 ir_block_enumerate(self->blocks[i], &instruction_id);
1601 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1602 bool ir_function_calculate_liferanges(ir_function *self)
1610 for (i = 0; i != self->blocks_count; ++i)
1612 if (self->blocks[i]->is_return)
1614 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1622 /* Local-value allocator
1623 * After finishing creating the liferange of all values used in a function
1624 * we can allocate their global-positions.
1625 * This is the counterpart to register-allocation in register machines.
1628 MEM_VECTOR_MAKE(ir_value*, locals);
1629 MEM_VECTOR_MAKE(size_t, sizes);
1630 MEM_VECTOR_MAKE(size_t, positions);
1631 } function_allocator;
1632 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1633 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1634 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1636 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1639 size_t vsize = type_sizeof[var->vtype];
1641 slot = ir_value_var("reg", store_global, var->vtype);
1645 if (!ir_value_life_merge_into(slot, var))
1648 if (!function_allocator_locals_add(alloc, slot))
1651 if (!function_allocator_sizes_add(alloc, vsize))
1657 ir_value_delete(slot);
1661 bool ir_function_allocate_locals(ir_function *self)
1670 function_allocator alloc;
1672 if (!self->locals_count)
1675 MEM_VECTOR_INIT(&alloc, locals);
1676 MEM_VECTOR_INIT(&alloc, sizes);
1677 MEM_VECTOR_INIT(&alloc, positions);
1679 for (i = 0; i < self->locals_count; ++i)
1681 if (!function_allocator_alloc(&alloc, self->locals[i]))
1685 /* Allocate a slot for any value that still exists */
1686 for (i = 0; i < self->values_count; ++i)
1688 v = self->values[i];
1693 for (a = 0; a < alloc.locals_count; ++a)
1695 slot = alloc.locals[a];
1697 if (ir_values_overlap(v, slot))
1700 if (!ir_value_life_merge_into(slot, v))
1703 /* adjust size for this slot */
1704 if (alloc.sizes[a] < type_sizeof[v->vtype])
1705 alloc.sizes[a] = type_sizeof[v->vtype];
1707 self->values[i]->code.local = a;
1710 if (a >= alloc.locals_count) {
1711 self->values[i]->code.local = alloc.locals_count;
1712 if (!function_allocator_alloc(&alloc, v))
1717 /* Adjust slot positions based on sizes */
1718 if (!function_allocator_positions_add(&alloc, 0))
1721 if (alloc.sizes_count)
1722 pos = alloc.positions[0] + alloc.sizes[0];
1725 for (i = 1; i < alloc.sizes_count; ++i)
1727 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1728 if (!function_allocator_positions_add(&alloc, pos))
1732 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1734 /* Take over the actual slot positions */
1735 for (i = 0; i < self->values_count; ++i)
1736 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1743 for (i = 0; i < alloc.locals_count; ++i)
1744 ir_value_delete(alloc.locals[i]);
1745 MEM_VECTOR_CLEAR(&alloc, locals);
1746 MEM_VECTOR_CLEAR(&alloc, sizes);
1747 MEM_VECTOR_CLEAR(&alloc, positions);
1751 /* Get information about which operand
1752 * is read from, or written to.
1754 static void ir_op_read_write(int op, size_t *read, size_t *write)
1781 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1784 bool changed = false;
1786 for (i = 0; i != self->living_count; ++i)
1788 tempbool = ir_value_life_merge(self->living[i], eid);
1791 fprintf(stderr, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1793 changed = changed || tempbool;
1798 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1801 /* values which have been read in a previous iteration are now
1802 * in the "living" array even if the previous block doesn't use them.
1803 * So we have to remove whatever does not exist in the previous block.
1804 * They will be re-added on-read, but the liferange merge won't cause
1807 for (i = 0; i < self->living_count; ++i)
1809 if (!ir_block_living_find(prev, self->living[i], NULL)) {
1810 if (!ir_block_living_remove(self, i))
1816 /* Whatever the previous block still has in its living set
1817 * must now be added to ours as well.
1819 for (i = 0; i < prev->living_count; ++i)
1821 if (ir_block_living_find(self, prev->living[i], NULL))
1823 if (!ir_block_living_add(self, prev->living[i]))
1826 printf("%s got from prev: %s\n", self->label, prev->living[i]->_name);
1832 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
1838 /* bitmasks which operands are read from or written to */
1840 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1842 new_reads_t new_reads;
1844 char dbg_ind[16] = { '#', '0' };
1847 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1848 MEM_VECTOR_INIT(&new_reads, v);
1853 if (!ir_block_life_prop_previous(self, prev, changed))
1857 i = self->instr_count;
1860 instr = self->instr[i];
1862 /* PHI operands are always read operands */
1863 for (p = 0; p < instr->phi_count; ++p)
1865 value = instr->phi[p].value;
1866 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1867 if (!ir_block_living_find(self, value, NULL) &&
1868 !ir_block_living_add(self, value))
1873 if (!new_reads_t_v_find(&new_reads, value, NULL))
1875 if (!new_reads_t_v_add(&new_reads, value))
1881 /* See which operands are read and write operands */
1882 ir_op_read_write(instr->opcode, &read, &write);
1884 /* Go through the 3 main operands */
1885 for (o = 0; o < 3; ++o)
1887 if (!instr->_ops[o]) /* no such operand */
1890 value = instr->_ops[o];
1892 /* We only care about locals */
1893 if (value->store != store_value &&
1894 value->store != store_local)
1900 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1901 if (!ir_block_living_find(self, value, NULL) &&
1902 !ir_block_living_add(self, value))
1907 /* fprintf(stderr, "read: %s\n", value->_name); */
1908 if (!new_reads_t_v_find(&new_reads, value, NULL))
1910 if (!new_reads_t_v_add(&new_reads, value))
1916 /* write operands */
1917 /* When we write to a local, we consider it "dead" for the
1918 * remaining upper part of the function, since in SSA a value
1919 * can only be written once (== created)
1924 bool in_living = ir_block_living_find(self, value, &idx);
1925 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1927 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
1928 if (!in_living && !in_reads)
1933 /* If the value isn't alive it hasn't been read before... */
1934 /* TODO: See if the warning can be emitted during parsing or AST processing
1935 * otherwise have warning printed here.
1936 * IF printing a warning here: include filecontext_t,
1937 * and make sure it's only printed once
1938 * since this function is run multiple times.
1940 /* For now: debug info: */
1941 fprintf(stderr, "Value only written %s\n", value->name);
1942 tempbool = ir_value_life_merge(value, instr->eid);
1943 *changed = *changed || tempbool;
1945 ir_instr_dump(instr, dbg_ind, printf);
1949 /* since 'living' won't contain it
1950 * anymore, merge the value, since
1953 tempbool = ir_value_life_merge(value, instr->eid);
1956 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
1958 *changed = *changed || tempbool;
1960 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1961 if (!ir_block_living_remove(self, idx))
1966 if (!new_reads_t_v_remove(&new_reads, readidx))
1974 tempbool = ir_block_living_add_instr(self, instr->eid);
1975 /*fprintf(stderr, "living added values\n");*/
1976 *changed = *changed || tempbool;
1978 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1980 for (rd = 0; rd < new_reads.v_count; ++rd)
1982 if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
1983 if (!ir_block_living_add(self, new_reads.v[rd]))
1986 if (!i && !self->entries_count) {
1988 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
1991 MEM_VECTOR_CLEAR(&new_reads, v);
1995 if (self->run_id == self->owner->run_id)
1998 self->run_id = self->owner->run_id;
2000 for (i = 0; i < self->entries_count; ++i)
2002 ir_block *entry = self->entries[i];
2003 ir_block_life_propagate(entry, self, changed);
2008 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2009 MEM_VECTOR_CLEAR(&new_reads, v);
2014 /***********************************************************************
2017 * Since the IR has the convention of putting 'write' operands
2018 * at the beginning, we have to rotate the operands of instructions
2019 * properly in order to generate valid QCVM code.
2021 * Having destinations at a fixed position is more convenient. In QC
2022 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2023 * read from from OPA, and store to OPB rather than OPC. Which is
2024 * partially the reason why the implementation of these instructions
2025 * in darkplaces has been delayed for so long.
2027 * Breaking conventions is annoying...
2029 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2031 static bool gen_global_field(ir_value *global)
2033 if (global->isconst)
2035 ir_value *fld = global->constval.vpointer;
2037 printf("Invalid field constant with no field: %s\n", global->name);
2041 /* Now, in this case, a relocation would be impossible to code
2042 * since it looks like this:
2043 * .vector v = origin; <- parse error, wtf is 'origin'?
2046 * But we will need a general relocation support later anyway
2047 * for functions... might as well support that here.
2049 if (!fld->code.globaladdr) {
2050 printf("FIXME: Relocation support\n");
2054 /* copy the field's value */
2055 global->code.globaladdr = code_globals_add(code_globals_data[fld->code.globaladdr]);
2059 prog_section_field fld;
2061 fld.name = global->code.name;
2062 fld.offset = code_fields_elements;
2063 fld.type = global->fieldtype;
2065 if (fld.type == TYPE_VOID) {
2066 printf("Field is missing a type: %s\n", global->name);
2070 if (code_fields_add(fld) < 0)
2073 global->code.globaladdr = code_globals_add(fld.offset);
2075 if (global->code.globaladdr < 0)
2080 static bool gen_global_pointer(ir_value *global)
2082 if (global->isconst)
2084 ir_value *target = global->constval.vpointer;
2086 printf("Invalid pointer constant: %s\n", global->name);
2087 /* NULL pointers are pointing to the NULL constant, which also
2088 * sits at address 0, but still has an ir_value for itself.
2093 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2094 * void() foo; <- proto
2095 * void() *fooptr = &foo;
2096 * void() foo = { code }
2098 if (!target->code.globaladdr) {
2099 /* FIXME: Check for the constant nullptr ir_value!
2100 * because then code.globaladdr being 0 is valid.
2102 printf("FIXME: Relocation support\n");
2106 global->code.globaladdr = code_globals_add(target->code.globaladdr);
2110 global->code.globaladdr = code_globals_add(0);
2112 if (global->code.globaladdr < 0)
2117 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2119 prog_section_statement stmt;
2128 block->generated = true;
2129 block->code_start = code_statements_elements;
2130 for (i = 0; i < block->instr_count; ++i)
2132 instr = block->instr[i];
2134 if (instr->opcode == VINSTR_PHI) {
2135 printf("cannot generate virtual instruction (phi)\n");
2139 if (instr->opcode == VINSTR_JUMP) {
2140 target = instr->bops[0];
2141 /* for uncoditional jumps, if the target hasn't been generated
2142 * yet, we generate them right here.
2144 if (!target->generated) {
2149 /* otherwise we generate a jump instruction */
2150 stmt.opcode = INSTR_GOTO;
2151 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2154 if (code_statements_add(stmt) < 0)
2157 /* no further instructions can be in this block */
2161 if (instr->opcode == VINSTR_COND) {
2162 ontrue = instr->bops[0];
2163 onfalse = instr->bops[1];
2164 /* TODO: have the AST signal which block should
2165 * come first: eg. optimize IFs without ELSE...
2168 stmt.o1.u1 = instr->_ops[0]->code.globaladdr;
2172 if (ontrue->generated) {
2173 stmt.opcode = INSTR_IF;
2174 stmt.o2.s1 = (ontrue->code_start-1) - code_statements_elements;
2175 if (code_statements_add(stmt) < 0)
2178 if (onfalse->generated) {
2179 stmt.opcode = INSTR_IFNOT;
2180 stmt.o2.s1 = (onfalse->code_start-1) - code_statements_elements;
2181 if (code_statements_add(stmt) < 0)
2184 if (!ontrue->generated) {
2185 if (onfalse->generated) {
2190 if (!onfalse->generated) {
2191 if (ontrue->generated) {
2196 /* neither ontrue nor onfalse exist */
2197 stmt.opcode = INSTR_IFNOT;
2198 stidx = code_statements_elements;
2199 if (code_statements_add(stmt) < 0)
2201 /* on false we jump, so add ontrue-path */
2202 if (!gen_blocks_recursive(func, ontrue))
2204 /* fixup the jump address */
2205 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2206 /* generate onfalse path */
2207 if (onfalse->generated) {
2208 /* fixup the jump address */
2209 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2210 /* may have been generated in the previous recursive call */
2211 stmt.opcode = INSTR_GOTO;
2212 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2215 return (code_statements_add(stmt) >= 0);
2217 /* if not, generate now */
2222 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2223 /* Trivial call translation:
2224 * copy all params to OFS_PARM*
2225 * if the output's storetype is not store_return,
2226 * add append a STORE instruction!
2228 * NOTES on how to do it better without much trouble:
2229 * -) The liferanges!
2230 * Simply check the liferange of all parameters for
2231 * other CALLs. For each param with no CALL in its
2232 * liferange, we can store it in an OFS_PARM at
2233 * generation already. This would even include later
2234 * reuse.... probably... :)
2239 for (p = 0; p < instr->params_count; ++p)
2241 ir_value *param = instr->params[p];
2243 stmt.opcode = INSTR_STORE_F;
2246 stmt.opcode = type_store_instr[param->vtype];
2247 stmt.o1.u1 = param->code.globaladdr;
2248 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2249 if (code_statements_add(stmt) < 0)
2252 stmt.opcode = INSTR_CALL0 + instr->params_count;
2253 if (stmt.opcode > INSTR_CALL8)
2254 stmt.opcode = INSTR_CALL8;
2255 stmt.o1.u1 = instr->_ops[1]->code.globaladdr;
2258 if (code_statements_add(stmt) < 0)
2261 retvalue = instr->_ops[0];
2262 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2264 /* not to be kept in OFS_RETURN */
2265 stmt.opcode = type_store_instr[retvalue->vtype];
2266 stmt.o1.u1 = OFS_RETURN;
2267 stmt.o2.u1 = retvalue->code.globaladdr;
2269 if (code_statements_add(stmt) < 0)
2275 if (instr->opcode == INSTR_STATE) {
2276 printf("TODO: state instruction\n");
2280 stmt.opcode = instr->opcode;
2285 /* This is the general order of operands */
2287 stmt.o3.u1 = instr->_ops[0]->code.globaladdr;
2290 stmt.o1.u1 = instr->_ops[1]->code.globaladdr;
2293 stmt.o2.u1 = instr->_ops[2]->code.globaladdr;
2295 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2297 stmt.o1.u1 = stmt.o3.u1;
2300 else if ((stmt.opcode >= INSTR_STORE_F &&
2301 stmt.opcode <= INSTR_STORE_FNC) ||
2302 (stmt.opcode >= INSTR_NOT_F &&
2303 stmt.opcode <= INSTR_NOT_FNC))
2305 /* 2-operand instructions with A -> B */
2306 stmt.o2.u1 = stmt.o3.u1;
2310 if (code_statements_add(stmt) < 0)
2316 static bool gen_function_code(ir_function *self)
2319 prog_section_statement stmt;
2321 /* Starting from entry point, we generate blocks "as they come"
2322 * for now. Dead blocks will not be translated obviously.
2324 if (!self->blocks_count) {
2325 printf("Function '%s' declared without body.\n", self->name);
2329 block = self->blocks[0];
2330 if (block->generated)
2333 if (!gen_blocks_recursive(self, block)) {
2334 printf("failed to generate blocks for '%s'\n", self->name);
2338 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2339 stmt.opcode = AINSTR_END;
2343 if (code_statements_add(stmt) < 0)
2348 static bool gen_global_function(ir_builder *ir, ir_value *global)
2350 prog_section_function fun;
2354 size_t local_var_end;
2356 if (!global->isconst || (!global->constval.vfunc))
2358 printf("Invalid state of function-global: not constant: %s\n", global->name);
2362 irfun = global->constval.vfunc;
2364 fun.name = global->code.name;
2365 fun.file = code_cachedstring(global->context.file);
2366 fun.profile = 0; /* always 0 */
2367 fun.nargs = irfun->params_count;
2369 for (i = 0;i < 8; ++i) {
2373 fun.argsize[i] = type_sizeof[irfun->params[i]];
2376 fun.firstlocal = code_globals_elements;
2377 fun.locals = irfun->allocated_locals + irfun->locals_count;
2380 for (i = 0; i < irfun->locals_count; ++i) {
2381 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2382 printf("Failed to generate global %s\n", irfun->locals[i]->name);
2386 if (irfun->locals_count) {
2387 ir_value *last = irfun->locals[irfun->locals_count-1];
2388 local_var_end = last->code.globaladdr;
2389 local_var_end += type_sizeof[last->vtype];
2391 for (i = 0; i < irfun->values_count; ++i)
2393 /* generate code.globaladdr for ssa values */
2394 ir_value *v = irfun->values[i];
2395 v->code.globaladdr = local_var_end + v->code.local;
2397 for (i = 0; i < irfun->locals_count; ++i) {
2398 /* fill the locals with zeros */
2399 code_globals_add(0);
2403 fun.entry = irfun->builtin;
2405 fun.entry = code_statements_elements;
2406 if (!gen_function_code(irfun)) {
2407 printf("Failed to generate code for function %s\n", irfun->name);
2412 return (code_functions_add(fun) >= 0);
2415 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2418 prog_section_def def;
2420 def.type = global->vtype;
2421 def.offset = code_globals_elements;
2422 def.name = global->code.name = code_genstring(global->name);
2424 switch (global->vtype)
2427 if (code_defs_add(def) < 0)
2429 return gen_global_pointer(global);
2431 if (code_defs_add(def) < 0)
2433 return gen_global_field(global);
2438 if (code_defs_add(def) < 0)
2441 if (global->isconst) {
2442 iptr = (int32_t*)&global->constval.vfloat;
2443 global->code.globaladdr = code_globals_add(*iptr);
2445 global->code.globaladdr = code_globals_add(0);
2447 return global->code.globaladdr >= 0;
2451 if (code_defs_add(def) < 0)
2453 if (global->isconst)
2454 global->code.globaladdr = code_globals_add(code_cachedstring(global->constval.vstring));
2456 global->code.globaladdr = code_globals_add(0);
2457 return global->code.globaladdr >= 0;
2460 case TYPE_QUATERNION:
2464 if (code_defs_add(def) < 0)
2467 if (global->isconst) {
2468 iptr = (int32_t*)&global->constval.vvec;
2469 global->code.globaladdr = code_globals_add(iptr[0]);
2470 if (global->code.globaladdr < 0)
2472 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2474 if (code_globals_add(iptr[d]) < 0)
2478 global->code.globaladdr = code_globals_add(0);
2479 if (global->code.globaladdr < 0)
2481 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2483 if (code_globals_add(0) < 0)
2487 return global->code.globaladdr >= 0;
2490 if (code_defs_add(def) < 0)
2492 global->code.globaladdr = code_globals_elements;
2493 code_globals_add(code_functions_elements);
2494 return gen_global_function(self, global);
2496 /* assume biggest type */
2497 global->code.globaladdr = code_globals_add(0);
2498 code_globals_add(0);
2499 code_globals_add(0);
2502 /* refuse to create 'void' type or any other fancy business. */
2503 printf("Invalid type for global variable %s\n", global->name);
2508 bool ir_builder_generate(ir_builder *self, const char *filename)
2514 for (i = 0; i < self->globals_count; ++i)
2516 if (!ir_builder_gen_global(self, self->globals[i])) {
2521 printf("writing '%s'...\n", filename);
2522 return code_write(filename);
2525 /***********************************************************************
2526 *IR DEBUG Dump functions...
2529 #define IND_BUFSZ 1024
2531 const char *qc_opname(int op)
2533 if (op < 0) return "<INVALID>";
2534 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2535 return asm_instr[op].m;
2537 case VINSTR_PHI: return "PHI";
2538 case VINSTR_JUMP: return "JUMP";
2539 case VINSTR_COND: return "COND";
2540 default: return "<UNK>";
2544 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2547 char indent[IND_BUFSZ];
2551 oprintf("module %s\n", b->name);
2552 for (i = 0; i < b->globals_count; ++i)
2555 if (b->globals[i]->isconst)
2556 oprintf("%s = ", b->globals[i]->name);
2557 ir_value_dump(b->globals[i], oprintf);
2560 for (i = 0; i < b->functions_count; ++i)
2561 ir_function_dump(b->functions[i], indent, oprintf);
2562 oprintf("endmodule %s\n", b->name);
2565 void ir_function_dump(ir_function *f, char *ind,
2566 int (*oprintf)(const char*, ...))
2569 if (f->builtin != 0) {
2570 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2573 oprintf("%sfunction %s\n", ind, f->name);
2574 strncat(ind, "\t", IND_BUFSZ);
2575 if (f->locals_count)
2577 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2578 for (i = 0; i < f->locals_count; ++i) {
2579 oprintf("%s\t", ind);
2580 ir_value_dump(f->locals[i], oprintf);
2584 if (f->blocks_count)
2586 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2587 for (i = 0; i < f->blocks_count; ++i) {
2588 if (f->blocks[i]->run_id != f->run_id) {
2589 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2591 ir_block_dump(f->blocks[i], ind, oprintf);
2595 ind[strlen(ind)-1] = 0;
2596 oprintf("%sendfunction %s\n", ind, f->name);
2599 void ir_block_dump(ir_block* b, char *ind,
2600 int (*oprintf)(const char*, ...))
2603 oprintf("%s:%s\n", ind, b->label);
2604 strncat(ind, "\t", IND_BUFSZ);
2606 for (i = 0; i < b->instr_count; ++i)
2607 ir_instr_dump(b->instr[i], ind, oprintf);
2608 ind[strlen(ind)-1] = 0;
2611 void dump_phi(ir_instr *in, char *ind,
2612 int (*oprintf)(const char*, ...))
2615 oprintf("%s <- phi ", in->_ops[0]->name);
2616 for (i = 0; i < in->phi_count; ++i)
2618 oprintf("([%s] : %s) ", in->phi[i].from->label,
2619 in->phi[i].value->name);
2624 void ir_instr_dump(ir_instr *in, char *ind,
2625 int (*oprintf)(const char*, ...))
2628 const char *comma = NULL;
2630 oprintf("%s (%i) ", ind, (int)in->eid);
2632 if (in->opcode == VINSTR_PHI) {
2633 dump_phi(in, ind, oprintf);
2637 strncat(ind, "\t", IND_BUFSZ);
2639 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2640 ir_value_dump(in->_ops[0], oprintf);
2641 if (in->_ops[1] || in->_ops[2])
2644 oprintf("%s\t", qc_opname(in->opcode));
2645 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2646 ir_value_dump(in->_ops[0], oprintf);
2651 for (i = 1; i != 3; ++i) {
2655 ir_value_dump(in->_ops[i], oprintf);
2663 oprintf("[%s]", in->bops[0]->label);
2667 oprintf("%s[%s]", comma, in->bops[1]->label);
2669 ind[strlen(ind)-1] = 0;
2672 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
2681 oprintf("%g", v->constval.vfloat);
2684 oprintf("'%g %g %g'",
2687 v->constval.vvec.z);
2690 oprintf("(entity)");
2693 oprintf("\"%s\"", v->constval.vstring);
2697 oprintf("%i", v->constval.vint);
2702 v->constval.vpointer->name);
2706 oprintf("%s", v->name);
2710 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
2713 oprintf("Life of %s:\n", self->name);
2714 for (i = 0; i < self->life_count; ++i)
2716 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);