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] = {
47 size_t type_sizeof[TYPE_COUNT] = {
54 1, /* TYPE_FUNCTION */
62 uint16_t type_store_instr[TYPE_COUNT] = {
63 INSTR_STORE_F, /* should use I when having integer support */
70 INSTR_STORE_ENT, /* should use I */
72 INSTR_STORE_I, /* integer type */
75 INSTR_STORE_V, /* variant, should never be accessed */
78 uint16_t type_storep_instr[TYPE_COUNT] = {
79 INSTR_STOREP_F, /* should use I when having integer support */
86 INSTR_STOREP_ENT, /* should use I */
88 INSTR_STOREP_ENT, /* integer type */
91 INSTR_STOREP_V, /* variant, should never be accessed */
94 MEM_VEC_FUNCTIONS(ir_value_vector, ir_value*, v)
96 /***********************************************************************
100 ir_builder* ir_builder_new(const char *modulename)
104 self = (ir_builder*)mem_a(sizeof(*self));
108 MEM_VECTOR_INIT(self, functions);
109 MEM_VECTOR_INIT(self, globals);
110 MEM_VECTOR_INIT(self, fields);
112 if (!ir_builder_set_name(self, modulename)) {
117 /* globals which always exist */
119 /* for now we give it a vector size */
120 ir_builder_create_global(self, "OFS_RETURN", TYPE_VARIANT);
125 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
126 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, fields)
127 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
129 void ir_builder_delete(ir_builder* self)
132 mem_d((void*)self->name);
133 for (i = 0; i != self->functions_count; ++i) {
134 ir_function_delete(self->functions[i]);
136 MEM_VECTOR_CLEAR(self, functions);
137 for (i = 0; i != self->globals_count; ++i) {
138 ir_value_delete(self->globals[i]);
140 MEM_VECTOR_CLEAR(self, fields);
141 for (i = 0; i != self->fields_count; ++i) {
142 ir_value_delete(self->fields[i]);
144 MEM_VECTOR_CLEAR(self, fields);
148 bool ir_builder_set_name(ir_builder *self, const char *name)
151 mem_d((void*)self->name);
152 self->name = util_strdup(name);
156 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
159 for (i = 0; i < self->functions_count; ++i) {
160 if (!strcmp(name, self->functions[i]->name))
161 return self->functions[i];
166 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
168 ir_function *fn = ir_builder_get_function(self, name);
173 fn = ir_function_new(self, outtype);
174 if (!ir_function_set_name(fn, name) ||
175 !ir_builder_functions_add(self, fn) )
177 ir_function_delete(fn);
181 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
183 ir_function_delete(fn);
187 fn->value->isconst = true;
188 fn->value->outtype = outtype;
189 fn->value->constval.vfunc = fn;
190 fn->value->context = fn->context;
195 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
198 for (i = 0; i < self->globals_count; ++i) {
199 if (!strcmp(self->globals[i]->name, name))
200 return self->globals[i];
205 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
209 if (name && name[0] != '#')
211 ve = ir_builder_get_global(self, name);
217 ve = ir_value_var(name, store_global, vtype);
218 if (!ir_builder_globals_add(self, ve)) {
225 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
228 for (i = 0; i < self->fields_count; ++i) {
229 if (!strcmp(self->fields[i]->name, name))
230 return self->fields[i];
236 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
238 ir_value *ve = ir_builder_get_field(self, name);
243 ve = ir_value_var(name, store_global, TYPE_FIELD);
244 ve->fieldtype = vtype;
245 if (!ir_builder_fields_add(self, ve)) {
252 /***********************************************************************
256 bool ir_function_naive_phi(ir_function*);
257 void ir_function_enumerate(ir_function*);
258 bool ir_function_calculate_liferanges(ir_function*);
259 bool ir_function_allocate_locals(ir_function*);
261 ir_function* ir_function_new(ir_builder* owner, int outtype)
264 self = (ir_function*)mem_a(sizeof(*self));
270 if (!ir_function_set_name(self, "<@unnamed>")) {
275 self->context.file = "<@no context>";
276 self->context.line = 0;
277 self->outtype = outtype;
280 MEM_VECTOR_INIT(self, params);
281 MEM_VECTOR_INIT(self, blocks);
282 MEM_VECTOR_INIT(self, values);
283 MEM_VECTOR_INIT(self, locals);
288 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
289 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
290 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
291 MEM_VEC_FUNCTIONS(ir_function, int, params)
293 bool ir_function_set_name(ir_function *self, const char *name)
296 mem_d((void*)self->name);
297 self->name = util_strdup(name);
301 void ir_function_delete(ir_function *self)
304 mem_d((void*)self->name);
306 for (i = 0; i != self->blocks_count; ++i)
307 ir_block_delete(self->blocks[i]);
308 MEM_VECTOR_CLEAR(self, blocks);
310 MEM_VECTOR_CLEAR(self, params);
312 for (i = 0; i != self->values_count; ++i)
313 ir_value_delete(self->values[i]);
314 MEM_VECTOR_CLEAR(self, values);
316 for (i = 0; i != self->locals_count; ++i)
317 ir_value_delete(self->locals[i]);
318 MEM_VECTOR_CLEAR(self, locals);
320 /* self->value is deleted by the builder */
325 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
327 return ir_function_values_add(self, v);
330 ir_block* ir_function_create_block(ir_function *self, const char *label)
332 ir_block* bn = ir_block_new(self, label);
333 memcpy(&bn->context, &self->context, sizeof(self->context));
334 if (!ir_function_blocks_add(self, bn)) {
341 bool ir_function_finalize(ir_function *self)
346 if (!ir_function_naive_phi(self))
349 ir_function_enumerate(self);
351 if (!ir_function_calculate_liferanges(self))
354 if (!ir_function_allocate_locals(self))
359 ir_value* ir_function_get_local(ir_function *self, const char *name)
362 for (i = 0; i < self->locals_count; ++i) {
363 if (!strcmp(self->locals[i]->name, name))
364 return self->locals[i];
369 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
371 ir_value *ve = ir_function_get_local(self, name);
377 self->locals_count &&
378 self->locals[self->locals_count-1]->store != store_param) {
379 printf("cannot add parameters after adding locals\n");
383 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
384 if (!ir_function_locals_add(self, ve)) {
391 /***********************************************************************
395 ir_block* ir_block_new(ir_function* owner, const char *name)
398 self = (ir_block*)mem_a(sizeof(*self));
402 memset(self, 0, sizeof(*self));
405 if (!ir_block_set_label(self, name)) {
410 self->context.file = "<@no context>";
411 self->context.line = 0;
413 MEM_VECTOR_INIT(self, instr);
414 MEM_VECTOR_INIT(self, entries);
415 MEM_VECTOR_INIT(self, exits);
418 self->is_return = false;
420 MEM_VECTOR_INIT(self, living);
422 self->generated = false;
426 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
427 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
428 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
429 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
431 void ir_block_delete(ir_block* self)
435 for (i = 0; i != self->instr_count; ++i)
436 ir_instr_delete(self->instr[i]);
437 MEM_VECTOR_CLEAR(self, instr);
438 MEM_VECTOR_CLEAR(self, entries);
439 MEM_VECTOR_CLEAR(self, exits);
440 MEM_VECTOR_CLEAR(self, living);
444 bool ir_block_set_label(ir_block *self, const char *name)
447 mem_d((void*)self->label);
448 self->label = util_strdup(name);
449 return !!self->label;
452 /***********************************************************************
456 ir_instr* ir_instr_new(ir_block* owner, int op)
459 self = (ir_instr*)mem_a(sizeof(*self));
464 self->context.file = "<@no context>";
465 self->context.line = 0;
467 self->_ops[0] = NULL;
468 self->_ops[1] = NULL;
469 self->_ops[2] = NULL;
470 self->bops[0] = NULL;
471 self->bops[1] = NULL;
472 MEM_VECTOR_INIT(self, phi);
473 MEM_VECTOR_INIT(self, params);
478 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
479 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
481 void ir_instr_delete(ir_instr *self)
484 /* The following calls can only delete from
485 * vectors, we still want to delete this instruction
486 * so ignore the return value. Since with the warn_unused_result attribute
487 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
488 * I have to improvise here and use if(foo());
490 for (i = 0; i < self->phi_count; ++i) {
492 if (ir_value_writes_find(self->phi[i].value, self, &idx))
493 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
494 if (ir_value_reads_find(self->phi[i].value, self, &idx))
495 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
497 MEM_VECTOR_CLEAR(self, phi);
498 for (i = 0; i < self->params_count; ++i) {
500 if (ir_value_writes_find(self->params[i], self, &idx))
501 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
502 if (ir_value_reads_find(self->params[i], self, &idx))
503 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
505 MEM_VECTOR_CLEAR(self, params);
506 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
507 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
508 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
512 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
514 if (self->_ops[op]) {
516 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
518 if (!ir_value_writes_remove(self->_ops[op], idx))
521 else if (ir_value_reads_find(self->_ops[op], self, &idx))
523 if (!ir_value_reads_remove(self->_ops[op], idx))
529 if (!ir_value_writes_add(v, self))
532 if (!ir_value_reads_add(v, self))
540 /***********************************************************************
544 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
546 self->code.globaladdr = gaddr;
547 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
548 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
549 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
552 int32_t ir_value_code_addr(const ir_value *self)
554 if (self->store == store_return)
555 return OFS_RETURN + self->code.addroffset;
556 return self->code.globaladdr + self->code.addroffset;
559 ir_value* ir_value_var(const char *name, int storetype, int vtype)
562 self = (ir_value*)mem_a(sizeof(*self));
564 self->fieldtype = TYPE_VOID;
565 self->outtype = TYPE_VOID;
566 self->store = storetype;
567 MEM_VECTOR_INIT(self, reads);
568 MEM_VECTOR_INIT(self, writes);
569 self->isconst = false;
570 self->context.file = "<@no context>";
571 self->context.line = 0;
573 ir_value_set_name(self, name);
575 memset(&self->constval, 0, sizeof(self->constval));
576 memset(&self->code, 0, sizeof(self->code));
578 MEM_VECTOR_INIT(self, life);
582 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
588 if (self->members[member])
589 return self->members[member];
591 if (self->vtype == TYPE_VECTOR)
593 m = ir_value_var(self->name, self->store, TYPE_FLOAT);
596 m->context = self->context;
598 self->members[member] = m;
599 m->code.addroffset = member;
601 else if (self->vtype == TYPE_FIELD)
603 if (self->fieldtype != TYPE_VECTOR)
605 m = ir_value_var(self->name, self->store, TYPE_FIELD);
608 m->fieldtype = TYPE_FLOAT;
609 m->context = self->context;
611 self->members[member] = m;
612 m->code.addroffset = member;
616 printf("invalid member access on %s\n", self->name);
623 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
624 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
625 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
627 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
629 ir_value *v = ir_value_var(name, storetype, vtype);
632 if (!ir_function_collect_value(owner, v))
640 void ir_value_delete(ir_value* self)
644 mem_d((void*)self->name);
647 if (self->vtype == TYPE_STRING)
648 mem_d((void*)self->constval.vstring);
650 for (i = 0; i < 3; ++i) {
651 if (self->members[i])
652 ir_value_delete(self->members[i]);
654 MEM_VECTOR_CLEAR(self, reads);
655 MEM_VECTOR_CLEAR(self, writes);
656 MEM_VECTOR_CLEAR(self, life);
660 void ir_value_set_name(ir_value *self, const char *name)
663 mem_d((void*)self->name);
664 self->name = util_strdup(name);
667 bool ir_value_set_float(ir_value *self, float f)
669 if (self->vtype != TYPE_FLOAT)
671 self->constval.vfloat = f;
672 self->isconst = true;
676 bool ir_value_set_func(ir_value *self, int f)
678 if (self->vtype != TYPE_FUNCTION)
680 self->constval.vint = f;
681 self->isconst = true;
685 bool ir_value_set_vector(ir_value *self, vector v)
687 if (self->vtype != TYPE_VECTOR)
689 self->constval.vvec = v;
690 self->isconst = true;
694 bool ir_value_set_field(ir_value *self, ir_value *fld)
696 if (self->vtype != TYPE_FIELD)
698 self->constval.vpointer = fld;
699 self->isconst = true;
703 bool ir_value_set_string(ir_value *self, const char *str)
705 if (self->vtype != TYPE_STRING)
707 self->constval.vstring = util_strdup(str);
708 self->isconst = true;
713 bool ir_value_set_int(ir_value *self, int i)
715 if (self->vtype != TYPE_INTEGER)
717 self->constval.vint = i;
718 self->isconst = true;
723 bool ir_value_lives(ir_value *self, size_t at)
726 for (i = 0; i < self->life_count; ++i)
728 ir_life_entry_t *life = &self->life[i];
729 if (life->start <= at && at <= life->end)
731 if (life->start > at) /* since it's ordered */
737 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
740 if (!ir_value_life_add(self, e)) /* naive... */
742 for (k = self->life_count-1; k > idx; --k)
743 self->life[k] = self->life[k-1];
748 bool ir_value_life_merge(ir_value *self, size_t s)
751 ir_life_entry_t *life = NULL;
752 ir_life_entry_t *before = NULL;
753 ir_life_entry_t new_entry;
755 /* Find the first range >= s */
756 for (i = 0; i < self->life_count; ++i)
759 life = &self->life[i];
763 /* nothing found? append */
764 if (i == self->life_count) {
766 if (life && life->end+1 == s)
768 /* previous life range can be merged in */
772 if (life && life->end >= s)
775 if (!ir_value_life_add(self, e))
776 return false; /* failing */
782 if (before->end + 1 == s &&
783 life->start - 1 == s)
786 before->end = life->end;
787 if (!ir_value_life_remove(self, i))
788 return false; /* failing */
791 if (before->end + 1 == s)
797 /* already contained */
798 if (before->end >= s)
802 if (life->start - 1 == s)
807 /* insert a new entry */
808 new_entry.start = new_entry.end = s;
809 return ir_value_life_insert(self, i, new_entry);
812 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
816 if (!other->life_count)
819 if (!self->life_count) {
820 for (i = 0; i < other->life_count; ++i) {
821 if (!ir_value_life_add(self, other->life[i]))
828 for (i = 0; i < other->life_count; ++i)
830 const ir_life_entry_t *life = &other->life[i];
833 ir_life_entry_t *entry = &self->life[myi];
835 if (life->end+1 < entry->start)
837 /* adding an interval before entry */
838 if (!ir_value_life_insert(self, myi, *life))
844 if (life->start < entry->start &&
845 life->end >= entry->start)
847 /* starts earlier and overlaps */
848 entry->start = life->start;
851 if (life->end > entry->end &&
852 life->start-1 <= entry->end)
854 /* ends later and overlaps */
855 entry->end = life->end;
858 /* see if our change combines it with the next ranges */
859 while (myi+1 < self->life_count &&
860 entry->end+1 >= self->life[1+myi].start)
862 /* overlaps with (myi+1) */
863 if (entry->end < self->life[1+myi].end)
864 entry->end = self->life[1+myi].end;
865 if (!ir_value_life_remove(self, myi+1))
867 entry = &self->life[myi];
870 /* see if we're after the entry */
871 if (life->start > entry->end)
874 /* append if we're at the end */
875 if (myi >= self->life_count) {
876 if (!ir_value_life_add(self, *life))
880 /* otherweise check the next range */
889 bool ir_values_overlap(const ir_value *a, const ir_value *b)
891 /* For any life entry in A see if it overlaps with
892 * any life entry in B.
893 * Note that the life entries are orderes, so we can make a
894 * more efficient algorithm there than naively translating the
898 ir_life_entry_t *la, *lb, *enda, *endb;
900 /* first of all, if either has no life range, they cannot clash */
901 if (!a->life_count || !b->life_count)
906 enda = la + a->life_count;
907 endb = lb + b->life_count;
910 /* check if the entries overlap, for that,
911 * both must start before the other one ends.
913 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
914 if (la->start <= lb->end &&
915 lb->start <= la->end)
917 if (la->start < lb->end &&
924 /* entries are ordered
925 * one entry is earlier than the other
926 * that earlier entry will be moved forward
928 if (la->start < lb->start)
930 /* order: A B, move A forward
931 * check if we hit the end with A
936 else if (lb->start < la->start)
938 /* order: B A, move B forward
939 * check if we hit the end with B
948 /***********************************************************************
952 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
954 ir_instr *in = ir_instr_new(self, op);
958 if (target->store == store_value &&
959 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
961 fprintf(stderr, "cannot store to an SSA value\n");
962 fprintf(stderr, "trying to store: %s <- %s\n", target->name, what->name);
963 fprintf(stderr, "instruction: %s\n", asm_instr[op].m);
967 if (!ir_instr_op(in, 0, target, true) ||
968 !ir_instr_op(in, 1, what, false) ||
969 !ir_block_instr_add(self, in) )
976 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
980 if (target->vtype == TYPE_VARIANT)
983 vtype = target->vtype;
986 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
987 op = INSTR_CONV_ITOF;
988 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
989 op = INSTR_CONV_FTOI;
991 op = type_store_instr[vtype];
993 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
994 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
998 return ir_block_create_store_op(self, op, target, what);
1001 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
1006 if (target->vtype != TYPE_POINTER)
1009 /* storing using pointer - target is a pointer, type must be
1010 * inferred from source
1012 vtype = what->vtype;
1014 op = type_storep_instr[vtype];
1015 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1016 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1017 op = INSTR_STOREP_V;
1020 return ir_block_create_store_op(self, op, target, what);
1023 bool ir_block_create_return(ir_block *self, ir_value *v)
1027 fprintf(stderr, "block already ended (%s)\n", self->label);
1031 self->is_return = true;
1032 in = ir_instr_new(self, INSTR_RETURN);
1036 if (!ir_instr_op(in, 0, v, false) ||
1037 !ir_block_instr_add(self, in) )
1044 bool ir_block_create_if(ir_block *self, ir_value *v,
1045 ir_block *ontrue, ir_block *onfalse)
1049 fprintf(stderr, "block already ended (%s)\n", self->label);
1053 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1054 in = ir_instr_new(self, VINSTR_COND);
1058 if (!ir_instr_op(in, 0, v, false)) {
1059 ir_instr_delete(in);
1063 in->bops[0] = ontrue;
1064 in->bops[1] = onfalse;
1066 if (!ir_block_instr_add(self, in))
1069 if (!ir_block_exits_add(self, ontrue) ||
1070 !ir_block_exits_add(self, onfalse) ||
1071 !ir_block_entries_add(ontrue, self) ||
1072 !ir_block_entries_add(onfalse, self) )
1079 bool ir_block_create_jump(ir_block *self, ir_block *to)
1083 fprintf(stderr, "block already ended (%s)\n", self->label);
1087 in = ir_instr_new(self, VINSTR_JUMP);
1092 if (!ir_block_instr_add(self, in))
1095 if (!ir_block_exits_add(self, to) ||
1096 !ir_block_entries_add(to, self) )
1103 bool ir_block_create_goto(ir_block *self, ir_block *to)
1107 fprintf(stderr, "block already ended (%s)\n", self->label);
1111 in = ir_instr_new(self, INSTR_GOTO);
1116 if (!ir_block_instr_add(self, in))
1119 if (!ir_block_exits_add(self, to) ||
1120 !ir_block_entries_add(to, self) )
1127 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1131 in = ir_instr_new(self, VINSTR_PHI);
1134 out = ir_value_out(self->owner, label, store_value, ot);
1136 ir_instr_delete(in);
1139 if (!ir_instr_op(in, 0, out, true)) {
1140 ir_instr_delete(in);
1141 ir_value_delete(out);
1144 if (!ir_block_instr_add(self, in)) {
1145 ir_instr_delete(in);
1146 ir_value_delete(out);
1152 ir_value* ir_phi_value(ir_instr *self)
1154 return self->_ops[0];
1157 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1161 if (!ir_block_entries_find(self->owner, b, NULL)) {
1162 /* Must not be possible to cause this, otherwise the AST
1163 * is doing something wrong.
1165 fprintf(stderr, "Invalid entry block for PHI\n");
1171 if (!ir_value_reads_add(v, self))
1173 return ir_instr_phi_add(self, pe);
1176 /* call related code */
1177 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1181 in = ir_instr_new(self, INSTR_CALL0);
1184 out = ir_value_out(self->owner, label, store_return, func->outtype);
1186 ir_instr_delete(in);
1189 if (!ir_instr_op(in, 0, out, true) ||
1190 !ir_instr_op(in, 1, func, false) ||
1191 !ir_block_instr_add(self, in))
1193 ir_instr_delete(in);
1194 ir_value_delete(out);
1200 ir_value* ir_call_value(ir_instr *self)
1202 return self->_ops[0];
1205 bool ir_call_param(ir_instr* self, ir_value *v)
1207 if (!ir_instr_params_add(self, v))
1209 if (!ir_value_reads_add(v, self)) {
1210 if (!ir_instr_params_remove(self, self->params_count-1))
1211 GMQCC_SUPPRESS_EMPTY_BODY;
1217 /* binary op related code */
1219 ir_value* ir_block_create_binop(ir_block *self,
1220 const char *label, int opcode,
1221 ir_value *left, ir_value *right)
1243 case INSTR_SUB_S: /* -- offset of string as float */
1248 case INSTR_BITOR_IF:
1249 case INSTR_BITOR_FI:
1250 case INSTR_BITAND_FI:
1251 case INSTR_BITAND_IF:
1266 case INSTR_BITAND_I:
1269 case INSTR_RSHIFT_I:
1270 case INSTR_LSHIFT_I:
1292 /* boolean operations result in floats */
1293 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1295 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1298 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1303 if (ot == TYPE_VOID) {
1304 /* The AST or parser were supposed to check this! */
1308 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1311 ir_value* ir_block_create_unary(ir_block *self,
1312 const char *label, int opcode,
1315 int ot = TYPE_FLOAT;
1327 /* QC doesn't have other unary operations. We expect extensions to fill
1328 * the above list, otherwise we assume out-type = in-type, eg for an
1332 ot = operand->vtype;
1335 if (ot == TYPE_VOID) {
1336 /* The AST or parser were supposed to check this! */
1340 /* let's use the general instruction creator and pass NULL for OPB */
1341 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1344 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1345 int op, ir_value *a, ir_value *b, int outype)
1350 out = ir_value_out(self->owner, label, store_value, outype);
1354 instr = ir_instr_new(self, op);
1356 ir_value_delete(out);
1360 if (!ir_instr_op(instr, 0, out, true) ||
1361 !ir_instr_op(instr, 1, a, false) ||
1362 !ir_instr_op(instr, 2, b, false) )
1367 if (!ir_block_instr_add(self, instr))
1372 ir_instr_delete(instr);
1373 ir_value_delete(out);
1377 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1381 /* Support for various pointer types todo if so desired */
1382 if (ent->vtype != TYPE_ENTITY)
1385 if (field->vtype != TYPE_FIELD)
1388 v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1389 v->fieldtype = field->fieldtype;
1393 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1396 if (ent->vtype != TYPE_ENTITY)
1399 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1400 if (field->vtype != TYPE_FIELD)
1405 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1406 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1407 case TYPE_STRING: op = INSTR_LOAD_S; break;
1408 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1409 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1411 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1412 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1418 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1421 ir_value* ir_block_create_add(ir_block *self,
1423 ir_value *left, ir_value *right)
1426 int l = left->vtype;
1427 int r = right->vtype;
1446 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1448 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1454 return ir_block_create_binop(self, label, op, left, right);
1457 ir_value* ir_block_create_sub(ir_block *self,
1459 ir_value *left, ir_value *right)
1462 int l = left->vtype;
1463 int r = right->vtype;
1483 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1485 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1491 return ir_block_create_binop(self, label, op, left, right);
1494 ir_value* ir_block_create_mul(ir_block *self,
1496 ir_value *left, ir_value *right)
1499 int l = left->vtype;
1500 int r = right->vtype;
1519 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1521 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1524 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1526 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1528 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1530 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1536 return ir_block_create_binop(self, label, op, left, right);
1539 ir_value* ir_block_create_div(ir_block *self,
1541 ir_value *left, ir_value *right)
1544 int l = left->vtype;
1545 int r = right->vtype;
1562 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1564 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1566 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1572 return ir_block_create_binop(self, label, op, left, right);
1575 /* PHI resolving breaks the SSA, and must thus be the last
1576 * step before life-range calculation.
1579 static bool ir_block_naive_phi(ir_block *self);
1580 bool ir_function_naive_phi(ir_function *self)
1584 for (i = 0; i < self->blocks_count; ++i)
1586 if (!ir_block_naive_phi(self->blocks[i]))
1592 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1597 /* create a store */
1598 if (!ir_block_create_store(block, old, what))
1601 /* we now move it up */
1602 instr = block->instr[block->instr_count-1];
1603 for (i = block->instr_count; i > iid; --i)
1604 block->instr[i] = block->instr[i-1];
1605 block->instr[i] = instr;
1610 static bool ir_block_naive_phi(ir_block *self)
1613 /* FIXME: optionally, create_phi can add the phis
1614 * to a list so we don't need to loop through blocks
1615 * - anyway: "don't optimize YET"
1617 for (i = 0; i < self->instr_count; ++i)
1619 ir_instr *instr = self->instr[i];
1620 if (instr->opcode != VINSTR_PHI)
1623 if (!ir_block_instr_remove(self, i))
1625 --i; /* NOTE: i+1 below */
1627 for (p = 0; p < instr->phi_count; ++p)
1629 ir_value *v = instr->phi[p].value;
1630 for (w = 0; w < v->writes_count; ++w) {
1633 if (!v->writes[w]->_ops[0])
1636 /* When the write was to a global, we have to emit a mov */
1637 old = v->writes[w]->_ops[0];
1639 /* The original instruction now writes to the PHI target local */
1640 if (v->writes[w]->_ops[0] == v)
1641 v->writes[w]->_ops[0] = instr->_ops[0];
1643 if (old->store != store_value && old->store != store_local && old->store != store_param)
1645 /* If it originally wrote to a global we need to store the value
1648 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1650 if (i+1 < self->instr_count)
1651 instr = self->instr[i+1];
1654 /* In case I forget and access instr later, it'll be NULL
1655 * when it's a problem, to make sure we crash, rather than accessing
1661 /* If it didn't, we can replace all reads by the phi target now. */
1663 for (r = 0; r < old->reads_count; ++r)
1666 ir_instr *ri = old->reads[r];
1667 for (op = 0; op < ri->phi_count; ++op) {
1668 if (ri->phi[op].value == old)
1669 ri->phi[op].value = v;
1671 for (op = 0; op < 3; ++op) {
1672 if (ri->_ops[op] == old)
1679 ir_instr_delete(instr);
1684 /***********************************************************************
1685 *IR Temp allocation code
1686 * Propagating value life ranges by walking through the function backwards
1687 * until no more changes are made.
1688 * In theory this should happen once more than once for every nested loop
1690 * Though this implementation might run an additional time for if nests.
1699 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1701 /* Enumerate instructions used by value's life-ranges
1703 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1707 for (i = 0; i < self->instr_count; ++i)
1709 self->instr[i]->eid = eid++;
1714 /* Enumerate blocks and instructions.
1715 * The block-enumeration is unordered!
1716 * We do not really use the block enumreation, however
1717 * the instruction enumeration is important for life-ranges.
1719 void ir_function_enumerate(ir_function *self)
1722 size_t instruction_id = 0;
1723 for (i = 0; i < self->blocks_count; ++i)
1725 self->blocks[i]->eid = i;
1726 self->blocks[i]->run_id = 0;
1727 ir_block_enumerate(self->blocks[i], &instruction_id);
1731 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1732 bool ir_function_calculate_liferanges(ir_function *self)
1740 for (i = 0; i != self->blocks_count; ++i)
1742 if (self->blocks[i]->is_return)
1744 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1752 /* Local-value allocator
1753 * After finishing creating the liferange of all values used in a function
1754 * we can allocate their global-positions.
1755 * This is the counterpart to register-allocation in register machines.
1758 MEM_VECTOR_MAKE(ir_value*, locals);
1759 MEM_VECTOR_MAKE(size_t, sizes);
1760 MEM_VECTOR_MAKE(size_t, positions);
1761 } function_allocator;
1762 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1763 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1764 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1766 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1769 size_t vsize = type_sizeof[var->vtype];
1771 slot = ir_value_var("reg", store_global, var->vtype);
1775 if (!ir_value_life_merge_into(slot, var))
1778 if (!function_allocator_locals_add(alloc, slot))
1781 if (!function_allocator_sizes_add(alloc, vsize))
1787 ir_value_delete(slot);
1791 bool ir_function_allocate_locals(ir_function *self)
1800 function_allocator alloc;
1802 if (!self->locals_count)
1805 MEM_VECTOR_INIT(&alloc, locals);
1806 MEM_VECTOR_INIT(&alloc, sizes);
1807 MEM_VECTOR_INIT(&alloc, positions);
1809 for (i = 0; i < self->locals_count; ++i)
1811 if (!function_allocator_alloc(&alloc, self->locals[i]))
1815 /* Allocate a slot for any value that still exists */
1816 for (i = 0; i < self->values_count; ++i)
1818 v = self->values[i];
1823 for (a = 0; a < alloc.locals_count; ++a)
1825 slot = alloc.locals[a];
1827 if (ir_values_overlap(v, slot))
1830 if (!ir_value_life_merge_into(slot, v))
1833 /* adjust size for this slot */
1834 if (alloc.sizes[a] < type_sizeof[v->vtype])
1835 alloc.sizes[a] = type_sizeof[v->vtype];
1837 self->values[i]->code.local = a;
1840 if (a >= alloc.locals_count) {
1841 self->values[i]->code.local = alloc.locals_count;
1842 if (!function_allocator_alloc(&alloc, v))
1847 /* Adjust slot positions based on sizes */
1848 if (!function_allocator_positions_add(&alloc, 0))
1851 if (alloc.sizes_count)
1852 pos = alloc.positions[0] + alloc.sizes[0];
1855 for (i = 1; i < alloc.sizes_count; ++i)
1857 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1858 if (!function_allocator_positions_add(&alloc, pos))
1862 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1864 /* Take over the actual slot positions */
1865 for (i = 0; i < self->values_count; ++i)
1866 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1873 for (i = 0; i < alloc.locals_count; ++i)
1874 ir_value_delete(alloc.locals[i]);
1875 MEM_VECTOR_CLEAR(&alloc, locals);
1876 MEM_VECTOR_CLEAR(&alloc, sizes);
1877 MEM_VECTOR_CLEAR(&alloc, positions);
1881 /* Get information about which operand
1882 * is read from, or written to.
1884 static void ir_op_read_write(int op, size_t *read, size_t *write)
1911 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1914 bool changed = false;
1916 for (i = 0; i != self->living_count; ++i)
1918 tempbool = ir_value_life_merge(self->living[i], eid);
1921 fprintf(stderr, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1923 changed = changed || tempbool;
1928 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1931 /* values which have been read in a previous iteration are now
1932 * in the "living" array even if the previous block doesn't use them.
1933 * So we have to remove whatever does not exist in the previous block.
1934 * They will be re-added on-read, but the liferange merge won't cause
1937 for (i = 0; i < self->living_count; ++i)
1939 if (!ir_block_living_find(prev, self->living[i], NULL)) {
1940 if (!ir_block_living_remove(self, i))
1946 /* Whatever the previous block still has in its living set
1947 * must now be added to ours as well.
1949 for (i = 0; i < prev->living_count; ++i)
1951 if (ir_block_living_find(self, prev->living[i], NULL))
1953 if (!ir_block_living_add(self, prev->living[i]))
1956 printf("%s got from prev: %s\n", self->label, prev->living[i]->_name);
1962 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
1968 /* bitmasks which operands are read from or written to */
1970 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1972 new_reads_t new_reads;
1974 char dbg_ind[16] = { '#', '0' };
1977 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1978 MEM_VECTOR_INIT(&new_reads, v);
1983 if (!ir_block_life_prop_previous(self, prev, changed))
1987 i = self->instr_count;
1990 instr = self->instr[i];
1992 /* PHI operands are always read operands */
1993 for (p = 0; p < instr->phi_count; ++p)
1995 value = instr->phi[p].value;
1996 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1997 if (!ir_block_living_find(self, value, NULL) &&
1998 !ir_block_living_add(self, value))
2003 if (!new_reads_t_v_find(&new_reads, value, NULL))
2005 if (!new_reads_t_v_add(&new_reads, value))
2011 /* See which operands are read and write operands */
2012 ir_op_read_write(instr->opcode, &read, &write);
2014 /* Go through the 3 main operands */
2015 for (o = 0; o < 3; ++o)
2017 if (!instr->_ops[o]) /* no such operand */
2020 value = instr->_ops[o];
2022 /* We only care about locals */
2023 /* we also calculate parameter liferanges so that locals
2024 * can take up parameter slots */
2025 if (value->store != store_value &&
2026 value->store != store_local &&
2027 value->store != store_param)
2033 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2034 if (!ir_block_living_find(self, value, NULL) &&
2035 !ir_block_living_add(self, value))
2040 /* fprintf(stderr, "read: %s\n", value->_name); */
2041 if (!new_reads_t_v_find(&new_reads, value, NULL))
2043 if (!new_reads_t_v_add(&new_reads, value))
2049 /* write operands */
2050 /* When we write to a local, we consider it "dead" for the
2051 * remaining upper part of the function, since in SSA a value
2052 * can only be written once (== created)
2057 bool in_living = ir_block_living_find(self, value, &idx);
2058 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2060 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
2061 if (!in_living && !in_reads)
2066 /* If the value isn't alive it hasn't been read before... */
2067 /* TODO: See if the warning can be emitted during parsing or AST processing
2068 * otherwise have warning printed here.
2069 * IF printing a warning here: include filecontext_t,
2070 * and make sure it's only printed once
2071 * since this function is run multiple times.
2073 /* For now: debug info: */
2074 fprintf(stderr, "Value only written %s\n", value->name);
2075 tempbool = ir_value_life_merge(value, instr->eid);
2076 *changed = *changed || tempbool;
2078 ir_instr_dump(instr, dbg_ind, printf);
2082 /* since 'living' won't contain it
2083 * anymore, merge the value, since
2086 tempbool = ir_value_life_merge(value, instr->eid);
2089 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2091 *changed = *changed || tempbool;
2093 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2094 if (!ir_block_living_remove(self, idx))
2099 if (!new_reads_t_v_remove(&new_reads, readidx))
2107 tempbool = ir_block_living_add_instr(self, instr->eid);
2108 /*fprintf(stderr, "living added values\n");*/
2109 *changed = *changed || tempbool;
2111 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2113 for (rd = 0; rd < new_reads.v_count; ++rd)
2115 if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
2116 if (!ir_block_living_add(self, new_reads.v[rd]))
2119 if (!i && !self->entries_count) {
2121 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
2124 MEM_VECTOR_CLEAR(&new_reads, v);
2128 if (self->run_id == self->owner->run_id)
2131 self->run_id = self->owner->run_id;
2133 for (i = 0; i < self->entries_count; ++i)
2135 ir_block *entry = self->entries[i];
2136 ir_block_life_propagate(entry, self, changed);
2141 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2142 MEM_VECTOR_CLEAR(&new_reads, v);
2147 /***********************************************************************
2150 * Since the IR has the convention of putting 'write' operands
2151 * at the beginning, we have to rotate the operands of instructions
2152 * properly in order to generate valid QCVM code.
2154 * Having destinations at a fixed position is more convenient. In QC
2155 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2156 * read from from OPA, and store to OPB rather than OPC. Which is
2157 * partially the reason why the implementation of these instructions
2158 * in darkplaces has been delayed for so long.
2160 * Breaking conventions is annoying...
2162 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2164 static bool gen_global_field(ir_value *global)
2166 if (global->isconst)
2168 ir_value *fld = global->constval.vpointer;
2170 printf("Invalid field constant with no field: %s\n", global->name);
2174 /* Now, in this case, a relocation would be impossible to code
2175 * since it looks like this:
2176 * .vector v = origin; <- parse error, wtf is 'origin'?
2179 * But we will need a general relocation support later anyway
2180 * for functions... might as well support that here.
2182 if (!fld->code.globaladdr) {
2183 printf("FIXME: Relocation support\n");
2187 /* copy the field's value */
2188 ir_value_code_setaddr(global, code_globals_add(code_globals_data[fld->code.globaladdr]));
2189 if (global->fieldtype == TYPE_VECTOR) {
2190 code_globals_add(code_globals_data[fld->code.globaladdr]+1);
2191 code_globals_add(code_globals_data[fld->code.globaladdr]+2);
2196 ir_value_code_setaddr(global, code_globals_add(0));
2197 if (global->fieldtype == TYPE_VECTOR) {
2198 code_globals_add(0);
2199 code_globals_add(0);
2202 if (global->code.globaladdr < 0)
2207 static bool gen_global_pointer(ir_value *global)
2209 if (global->isconst)
2211 ir_value *target = global->constval.vpointer;
2213 printf("Invalid pointer constant: %s\n", global->name);
2214 /* NULL pointers are pointing to the NULL constant, which also
2215 * sits at address 0, but still has an ir_value for itself.
2220 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2221 * void() foo; <- proto
2222 * void() *fooptr = &foo;
2223 * void() foo = { code }
2225 if (!target->code.globaladdr) {
2226 /* FIXME: Check for the constant nullptr ir_value!
2227 * because then code.globaladdr being 0 is valid.
2229 printf("FIXME: Relocation support\n");
2233 ir_value_code_setaddr(global, code_globals_add(target->code.globaladdr));
2237 ir_value_code_setaddr(global, code_globals_add(0));
2239 if (global->code.globaladdr < 0)
2244 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2246 prog_section_statement stmt;
2255 block->generated = true;
2256 block->code_start = code_statements_elements;
2257 for (i = 0; i < block->instr_count; ++i)
2259 instr = block->instr[i];
2261 if (instr->opcode == VINSTR_PHI) {
2262 printf("cannot generate virtual instruction (phi)\n");
2266 if (instr->opcode == VINSTR_JUMP) {
2267 target = instr->bops[0];
2268 /* for uncoditional jumps, if the target hasn't been generated
2269 * yet, we generate them right here.
2271 if (!target->generated) {
2276 /* otherwise we generate a jump instruction */
2277 stmt.opcode = INSTR_GOTO;
2278 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2281 if (code_statements_add(stmt) < 0)
2284 /* no further instructions can be in this block */
2288 if (instr->opcode == VINSTR_COND) {
2289 ontrue = instr->bops[0];
2290 onfalse = instr->bops[1];
2291 /* TODO: have the AST signal which block should
2292 * come first: eg. optimize IFs without ELSE...
2295 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2299 if (ontrue->generated) {
2300 stmt.opcode = INSTR_IF;
2301 stmt.o2.s1 = (ontrue->code_start-1) - code_statements_elements;
2302 if (code_statements_add(stmt) < 0)
2305 if (onfalse->generated) {
2306 stmt.opcode = INSTR_IFNOT;
2307 stmt.o2.s1 = (onfalse->code_start-1) - code_statements_elements;
2308 if (code_statements_add(stmt) < 0)
2311 if (!ontrue->generated) {
2312 if (onfalse->generated) {
2317 if (!onfalse->generated) {
2318 if (ontrue->generated) {
2323 /* neither ontrue nor onfalse exist */
2324 stmt.opcode = INSTR_IFNOT;
2325 stidx = code_statements_elements;
2326 if (code_statements_add(stmt) < 0)
2328 /* on false we jump, so add ontrue-path */
2329 if (!gen_blocks_recursive(func, ontrue))
2331 /* fixup the jump address */
2332 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2333 /* generate onfalse path */
2334 if (onfalse->generated) {
2335 /* fixup the jump address */
2336 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2337 /* may have been generated in the previous recursive call */
2338 stmt.opcode = INSTR_GOTO;
2339 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2342 return (code_statements_add(stmt) >= 0);
2344 /* if not, generate now */
2349 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2350 /* Trivial call translation:
2351 * copy all params to OFS_PARM*
2352 * if the output's storetype is not store_return,
2353 * add append a STORE instruction!
2355 * NOTES on how to do it better without much trouble:
2356 * -) The liferanges!
2357 * Simply check the liferange of all parameters for
2358 * other CALLs. For each param with no CALL in its
2359 * liferange, we can store it in an OFS_PARM at
2360 * generation already. This would even include later
2361 * reuse.... probably... :)
2366 for (p = 0; p < instr->params_count; ++p)
2368 ir_value *param = instr->params[p];
2370 stmt.opcode = INSTR_STORE_F;
2373 stmt.opcode = type_store_instr[param->vtype];
2374 stmt.o1.u1 = ir_value_code_addr(param);
2375 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2376 if (code_statements_add(stmt) < 0)
2379 stmt.opcode = INSTR_CALL0 + instr->params_count;
2380 if (stmt.opcode > INSTR_CALL8)
2381 stmt.opcode = INSTR_CALL8;
2382 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2385 if (code_statements_add(stmt) < 0)
2388 retvalue = instr->_ops[0];
2389 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2391 /* not to be kept in OFS_RETURN */
2392 stmt.opcode = type_store_instr[retvalue->vtype];
2393 stmt.o1.u1 = OFS_RETURN;
2394 stmt.o2.u1 = ir_value_code_addr(retvalue);
2396 if (code_statements_add(stmt) < 0)
2402 if (instr->opcode == INSTR_STATE) {
2403 printf("TODO: state instruction\n");
2407 stmt.opcode = instr->opcode;
2412 /* This is the general order of operands */
2414 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2417 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2420 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2422 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2424 stmt.o1.u1 = stmt.o3.u1;
2427 else if ((stmt.opcode >= INSTR_STORE_F &&
2428 stmt.opcode <= INSTR_STORE_FNC) ||
2429 (stmt.opcode >= INSTR_STOREP_F &&
2430 stmt.opcode <= INSTR_STOREP_FNC))
2432 /* 2-operand instructions with A -> B */
2433 stmt.o2.u1 = stmt.o3.u1;
2437 if (code_statements_add(stmt) < 0)
2443 static bool gen_function_code(ir_function *self)
2446 prog_section_statement stmt;
2448 /* Starting from entry point, we generate blocks "as they come"
2449 * for now. Dead blocks will not be translated obviously.
2451 if (!self->blocks_count) {
2452 printf("Function '%s' declared without body.\n", self->name);
2456 block = self->blocks[0];
2457 if (block->generated)
2460 if (!gen_blocks_recursive(self, block)) {
2461 printf("failed to generate blocks for '%s'\n", self->name);
2465 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2466 stmt.opcode = AINSTR_END;
2470 if (code_statements_add(stmt) < 0)
2475 static bool gen_global_function(ir_builder *ir, ir_value *global)
2477 prog_section_function fun;
2481 size_t local_var_end;
2483 if (!global->isconst || (!global->constval.vfunc))
2485 printf("Invalid state of function-global: not constant: %s\n", global->name);
2489 irfun = global->constval.vfunc;
2491 fun.name = global->code.name;
2492 fun.file = code_cachedstring(global->context.file);
2493 fun.profile = 0; /* always 0 */
2494 fun.nargs = irfun->params_count;
2496 for (i = 0;i < 8; ++i) {
2500 fun.argsize[i] = type_sizeof[irfun->params[i]];
2503 fun.firstlocal = code_globals_elements;
2504 fun.locals = irfun->allocated_locals + irfun->locals_count;
2507 for (i = 0; i < irfun->locals_count; ++i) {
2508 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2509 printf("Failed to generate global %s\n", irfun->locals[i]->name);
2513 if (irfun->locals_count) {
2514 ir_value *last = irfun->locals[irfun->locals_count-1];
2515 local_var_end = last->code.globaladdr;
2516 local_var_end += type_sizeof[last->vtype];
2518 for (i = 0; i < irfun->values_count; ++i)
2520 /* generate code.globaladdr for ssa values */
2521 ir_value *v = irfun->values[i];
2522 ir_value_code_setaddr(v, local_var_end + v->code.local);
2524 for (i = 0; i < irfun->locals_count; ++i) {
2525 /* fill the locals with zeros */
2526 code_globals_add(0);
2530 fun.entry = irfun->builtin;
2532 fun.entry = code_statements_elements;
2533 if (!gen_function_code(irfun)) {
2534 printf("Failed to generate code for function %s\n", irfun->name);
2539 return (code_functions_add(fun) >= 0);
2542 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2546 prog_section_def def;
2548 def.type = global->vtype;
2549 def.offset = code_globals_elements;
2550 def.name = global->code.name = code_genstring(global->name);
2552 switch (global->vtype)
2555 if (code_defs_add(def) < 0)
2557 return gen_global_pointer(global);
2559 if (code_defs_add(def) < 0)
2561 return gen_global_field(global);
2566 if (code_defs_add(def) < 0)
2569 if (global->isconst) {
2570 iptr = (int32_t*)&global->constval.vfloat;
2571 ir_value_code_setaddr(global, code_globals_add(*iptr));
2573 ir_value_code_setaddr(global, code_globals_add(0));
2575 return global->code.globaladdr >= 0;
2579 if (code_defs_add(def) < 0)
2581 if (global->isconst)
2582 ir_value_code_setaddr(global, code_globals_add(code_cachedstring(global->constval.vstring)));
2584 ir_value_code_setaddr(global, code_globals_add(0));
2585 return global->code.globaladdr >= 0;
2590 if (code_defs_add(def) < 0)
2593 if (global->isconst) {
2594 iptr = (int32_t*)&global->constval.vvec;
2595 ir_value_code_setaddr(global, code_globals_add(iptr[0]));
2596 if (global->code.globaladdr < 0)
2598 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2600 if (code_globals_add(iptr[d]) < 0)
2604 ir_value_code_setaddr(global, code_globals_add(0));
2605 if (global->code.globaladdr < 0)
2607 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2609 if (code_globals_add(0) < 0)
2613 return global->code.globaladdr >= 0;
2616 if (code_defs_add(def) < 0)
2618 ir_value_code_setaddr(global, code_globals_elements);
2619 code_globals_add(code_functions_elements);
2620 return gen_global_function(self, global);
2622 /* assume biggest type */
2623 ir_value_code_setaddr(global, code_globals_add(0));
2624 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2625 code_globals_add(0);
2628 /* refuse to create 'void' type or any other fancy business. */
2629 printf("Invalid type for global variable %s\n", global->name);
2634 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2636 prog_section_def def;
2637 prog_section_field fld;
2639 def.type = field->vtype;
2640 def.offset = code_globals_elements;
2642 /* create a global named the same as the field */
2643 if (opts_standard == COMPILER_GMQCC) {
2644 /* in our standard, the global gets a dot prefix */
2645 size_t len = strlen(field->name);
2648 /* we really don't want to have to allocate this, and 1024
2649 * bytes is more than enough for a variable/field name
2651 if (len+2 >= sizeof(name)) {
2652 printf("invalid field name size: %u\n", (unsigned int)len);
2657 strcpy(name+1, field->name); /* no strncpy - we used strlen above */
2660 def.name = code_genstring(name);
2661 fld.name = def.name + 1; /* we reuse that string table entry */
2663 /* in plain QC, there cannot be a global with the same name,
2664 * and so we also name the global the same.
2665 * FIXME: fteqcc should create a global as well
2666 * check if it actually uses the same name. Probably does
2668 def.name = code_genstring(field->name);
2669 fld.name = def.name;
2672 field->code.name = def.name;
2674 if (code_defs_add(def) < 0)
2677 fld.type = field->fieldtype;
2679 if (fld.type == TYPE_VOID) {
2680 printf("field is missing a type: %s - don't know its size\n", field->name);
2684 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2686 if (code_fields_add(fld) < 0)
2689 ir_value_code_setaddr(field, code_globals_elements);
2690 if (!code_globals_add(fld.offset))
2692 if (fld.type == TYPE_VECTOR) {
2693 if (!code_globals_add(fld.offset+1))
2695 if (!code_globals_add(fld.offset+2))
2699 return field->code.globaladdr >= 0;
2702 bool ir_builder_generate(ir_builder *self, const char *filename)
2708 for (i = 0; i < self->fields_count; ++i)
2710 if (!ir_builder_gen_field(self, self->fields[i])) {
2715 for (i = 0; i < self->globals_count; ++i)
2717 if (!ir_builder_gen_global(self, self->globals[i])) {
2722 printf("writing '%s'...\n", filename);
2723 return code_write(filename);
2726 /***********************************************************************
2727 *IR DEBUG Dump functions...
2730 #define IND_BUFSZ 1024
2732 const char *qc_opname(int op)
2734 if (op < 0) return "<INVALID>";
2735 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2736 return asm_instr[op].m;
2738 case VINSTR_PHI: return "PHI";
2739 case VINSTR_JUMP: return "JUMP";
2740 case VINSTR_COND: return "COND";
2741 default: return "<UNK>";
2745 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2748 char indent[IND_BUFSZ];
2752 oprintf("module %s\n", b->name);
2753 for (i = 0; i < b->globals_count; ++i)
2756 if (b->globals[i]->isconst)
2757 oprintf("%s = ", b->globals[i]->name);
2758 ir_value_dump(b->globals[i], oprintf);
2761 for (i = 0; i < b->functions_count; ++i)
2762 ir_function_dump(b->functions[i], indent, oprintf);
2763 oprintf("endmodule %s\n", b->name);
2766 void ir_function_dump(ir_function *f, char *ind,
2767 int (*oprintf)(const char*, ...))
2770 if (f->builtin != 0) {
2771 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2774 oprintf("%sfunction %s\n", ind, f->name);
2775 strncat(ind, "\t", IND_BUFSZ);
2776 if (f->locals_count)
2778 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2779 for (i = 0; i < f->locals_count; ++i) {
2780 oprintf("%s\t", ind);
2781 ir_value_dump(f->locals[i], oprintf);
2785 if (f->blocks_count)
2787 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2788 for (i = 0; i < f->blocks_count; ++i) {
2789 if (f->blocks[i]->run_id != f->run_id) {
2790 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2792 ir_block_dump(f->blocks[i], ind, oprintf);
2796 ind[strlen(ind)-1] = 0;
2797 oprintf("%sendfunction %s\n", ind, f->name);
2800 void ir_block_dump(ir_block* b, char *ind,
2801 int (*oprintf)(const char*, ...))
2804 oprintf("%s:%s\n", ind, b->label);
2805 strncat(ind, "\t", IND_BUFSZ);
2807 for (i = 0; i < b->instr_count; ++i)
2808 ir_instr_dump(b->instr[i], ind, oprintf);
2809 ind[strlen(ind)-1] = 0;
2812 void dump_phi(ir_instr *in, char *ind,
2813 int (*oprintf)(const char*, ...))
2816 oprintf("%s <- phi ", in->_ops[0]->name);
2817 for (i = 0; i < in->phi_count; ++i)
2819 oprintf("([%s] : %s) ", in->phi[i].from->label,
2820 in->phi[i].value->name);
2825 void ir_instr_dump(ir_instr *in, char *ind,
2826 int (*oprintf)(const char*, ...))
2829 const char *comma = NULL;
2831 oprintf("%s (%i) ", ind, (int)in->eid);
2833 if (in->opcode == VINSTR_PHI) {
2834 dump_phi(in, ind, oprintf);
2838 strncat(ind, "\t", IND_BUFSZ);
2840 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2841 ir_value_dump(in->_ops[0], oprintf);
2842 if (in->_ops[1] || in->_ops[2])
2845 if (in->opcode == INSTR_CALL0) {
2846 oprintf("CALL%i\t", in->params_count);
2848 oprintf("%s\t", qc_opname(in->opcode));
2850 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2851 ir_value_dump(in->_ops[0], oprintf);
2856 for (i = 1; i != 3; ++i) {
2860 ir_value_dump(in->_ops[i], oprintf);
2868 oprintf("[%s]", in->bops[0]->label);
2872 oprintf("%s[%s]", comma, in->bops[1]->label);
2874 ind[strlen(ind)-1] = 0;
2877 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
2886 oprintf("(function)");
2889 oprintf("%g", v->constval.vfloat);
2892 oprintf("'%g %g %g'",
2895 v->constval.vvec.z);
2898 oprintf("(entity)");
2901 oprintf("\"%s\"", v->constval.vstring);
2905 oprintf("%i", v->constval.vint);
2910 v->constval.vpointer->name);
2914 oprintf("%s", v->name);
2918 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
2921 oprintf("Life of %s:\n", self->name);
2922 for (i = 0; i < self->life_count; ++i)
2924 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);