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;
618 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
619 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
620 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
622 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
624 ir_value *v = ir_value_var(name, storetype, vtype);
627 if (!ir_function_collect_value(owner, v))
635 void ir_value_delete(ir_value* self)
639 mem_d((void*)self->name);
642 if (self->vtype == TYPE_STRING)
643 mem_d((void*)self->constval.vstring);
645 for (i = 0; i < 3; ++i) {
646 if (self->members[i])
647 ir_value_delete(self->members[i]);
649 MEM_VECTOR_CLEAR(self, reads);
650 MEM_VECTOR_CLEAR(self, writes);
651 MEM_VECTOR_CLEAR(self, life);
655 void ir_value_set_name(ir_value *self, const char *name)
658 mem_d((void*)self->name);
659 self->name = util_strdup(name);
662 bool ir_value_set_float(ir_value *self, float f)
664 if (self->vtype != TYPE_FLOAT)
666 self->constval.vfloat = f;
667 self->isconst = true;
671 bool ir_value_set_func(ir_value *self, int f)
673 if (self->vtype != TYPE_FUNCTION)
675 self->constval.vint = f;
676 self->isconst = true;
680 bool ir_value_set_vector(ir_value *self, vector v)
682 if (self->vtype != TYPE_VECTOR)
684 self->constval.vvec = v;
685 self->isconst = true;
689 bool ir_value_set_field(ir_value *self, ir_value *fld)
691 if (self->vtype != TYPE_FIELD)
693 self->constval.vpointer = fld;
694 self->isconst = true;
698 bool ir_value_set_string(ir_value *self, const char *str)
700 if (self->vtype != TYPE_STRING)
702 self->constval.vstring = util_strdup(str);
703 self->isconst = true;
708 bool ir_value_set_int(ir_value *self, int i)
710 if (self->vtype != TYPE_INTEGER)
712 self->constval.vint = i;
713 self->isconst = true;
718 bool ir_value_lives(ir_value *self, size_t at)
721 for (i = 0; i < self->life_count; ++i)
723 ir_life_entry_t *life = &self->life[i];
724 if (life->start <= at && at <= life->end)
726 if (life->start > at) /* since it's ordered */
732 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
735 if (!ir_value_life_add(self, e)) /* naive... */
737 for (k = self->life_count-1; k > idx; --k)
738 self->life[k] = self->life[k-1];
743 bool ir_value_life_merge(ir_value *self, size_t s)
746 ir_life_entry_t *life = NULL;
747 ir_life_entry_t *before = NULL;
748 ir_life_entry_t new_entry;
750 /* Find the first range >= s */
751 for (i = 0; i < self->life_count; ++i)
754 life = &self->life[i];
758 /* nothing found? append */
759 if (i == self->life_count) {
761 if (life && life->end+1 == s)
763 /* previous life range can be merged in */
767 if (life && life->end >= s)
770 if (!ir_value_life_add(self, e))
771 return false; /* failing */
777 if (before->end + 1 == s &&
778 life->start - 1 == s)
781 before->end = life->end;
782 if (!ir_value_life_remove(self, i))
783 return false; /* failing */
786 if (before->end + 1 == s)
792 /* already contained */
793 if (before->end >= s)
797 if (life->start - 1 == s)
802 /* insert a new entry */
803 new_entry.start = new_entry.end = s;
804 return ir_value_life_insert(self, i, new_entry);
807 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
811 if (!other->life_count)
814 if (!self->life_count) {
815 for (i = 0; i < other->life_count; ++i) {
816 if (!ir_value_life_add(self, other->life[i]))
823 for (i = 0; i < other->life_count; ++i)
825 const ir_life_entry_t *life = &other->life[i];
828 ir_life_entry_t *entry = &self->life[myi];
830 if (life->end+1 < entry->start)
832 /* adding an interval before entry */
833 if (!ir_value_life_insert(self, myi, *life))
839 if (life->start < entry->start &&
840 life->end >= entry->start)
842 /* starts earlier and overlaps */
843 entry->start = life->start;
846 if (life->end > entry->end &&
847 life->start-1 <= entry->end)
849 /* ends later and overlaps */
850 entry->end = life->end;
853 /* see if our change combines it with the next ranges */
854 while (myi+1 < self->life_count &&
855 entry->end+1 >= self->life[1+myi].start)
857 /* overlaps with (myi+1) */
858 if (entry->end < self->life[1+myi].end)
859 entry->end = self->life[1+myi].end;
860 if (!ir_value_life_remove(self, myi+1))
862 entry = &self->life[myi];
865 /* see if we're after the entry */
866 if (life->start > entry->end)
869 /* append if we're at the end */
870 if (myi >= self->life_count) {
871 if (!ir_value_life_add(self, *life))
875 /* otherweise check the next range */
884 bool ir_values_overlap(const ir_value *a, const ir_value *b)
886 /* For any life entry in A see if it overlaps with
887 * any life entry in B.
888 * Note that the life entries are orderes, so we can make a
889 * more efficient algorithm there than naively translating the
893 ir_life_entry_t *la, *lb, *enda, *endb;
895 /* first of all, if either has no life range, they cannot clash */
896 if (!a->life_count || !b->life_count)
901 enda = la + a->life_count;
902 endb = lb + b->life_count;
905 /* check if the entries overlap, for that,
906 * both must start before the other one ends.
908 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
909 if (la->start <= lb->end &&
910 lb->start <= la->end)
912 if (la->start < lb->end &&
919 /* entries are ordered
920 * one entry is earlier than the other
921 * that earlier entry will be moved forward
923 if (la->start < lb->start)
925 /* order: A B, move A forward
926 * check if we hit the end with A
931 else if (lb->start < la->start)
933 /* order: B A, move B forward
934 * check if we hit the end with B
943 /***********************************************************************
947 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
949 ir_instr *in = ir_instr_new(self, op);
953 if (target->store == store_value &&
954 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
956 fprintf(stderr, "cannot store to an SSA value\n");
957 fprintf(stderr, "trying to store: %s <- %s\n", target->name, what->name);
958 fprintf(stderr, "instruction: %s\n", asm_instr[op].m);
962 if (!ir_instr_op(in, 0, target, true) ||
963 !ir_instr_op(in, 1, what, false) ||
964 !ir_block_instr_add(self, in) )
971 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
975 if (target->vtype == TYPE_VARIANT)
978 vtype = target->vtype;
981 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
982 op = INSTR_CONV_ITOF;
983 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
984 op = INSTR_CONV_FTOI;
986 op = type_store_instr[vtype];
988 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
989 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
993 return ir_block_create_store_op(self, op, target, what);
996 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
1001 if (target->vtype != TYPE_POINTER)
1004 /* storing using pointer - target is a pointer, type must be
1005 * inferred from source
1007 vtype = what->vtype;
1009 op = type_storep_instr[vtype];
1010 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1011 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1012 op = INSTR_STOREP_V;
1015 return ir_block_create_store_op(self, op, target, what);
1018 bool ir_block_create_return(ir_block *self, ir_value *v)
1022 fprintf(stderr, "block already ended (%s)\n", self->label);
1026 self->is_return = true;
1027 in = ir_instr_new(self, INSTR_RETURN);
1031 if (!ir_instr_op(in, 0, v, false) ||
1032 !ir_block_instr_add(self, in) )
1039 bool ir_block_create_if(ir_block *self, ir_value *v,
1040 ir_block *ontrue, ir_block *onfalse)
1044 fprintf(stderr, "block already ended (%s)\n", self->label);
1048 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1049 in = ir_instr_new(self, VINSTR_COND);
1053 if (!ir_instr_op(in, 0, v, false)) {
1054 ir_instr_delete(in);
1058 in->bops[0] = ontrue;
1059 in->bops[1] = onfalse;
1061 if (!ir_block_instr_add(self, in))
1064 if (!ir_block_exits_add(self, ontrue) ||
1065 !ir_block_exits_add(self, onfalse) ||
1066 !ir_block_entries_add(ontrue, self) ||
1067 !ir_block_entries_add(onfalse, self) )
1074 bool ir_block_create_jump(ir_block *self, ir_block *to)
1078 fprintf(stderr, "block already ended (%s)\n", self->label);
1082 in = ir_instr_new(self, VINSTR_JUMP);
1087 if (!ir_block_instr_add(self, in))
1090 if (!ir_block_exits_add(self, to) ||
1091 !ir_block_entries_add(to, self) )
1098 bool ir_block_create_goto(ir_block *self, ir_block *to)
1102 fprintf(stderr, "block already ended (%s)\n", self->label);
1106 in = ir_instr_new(self, INSTR_GOTO);
1111 if (!ir_block_instr_add(self, in))
1114 if (!ir_block_exits_add(self, to) ||
1115 !ir_block_entries_add(to, self) )
1122 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1126 in = ir_instr_new(self, VINSTR_PHI);
1129 out = ir_value_out(self->owner, label, store_value, ot);
1131 ir_instr_delete(in);
1134 if (!ir_instr_op(in, 0, out, true)) {
1135 ir_instr_delete(in);
1136 ir_value_delete(out);
1139 if (!ir_block_instr_add(self, in)) {
1140 ir_instr_delete(in);
1141 ir_value_delete(out);
1147 ir_value* ir_phi_value(ir_instr *self)
1149 return self->_ops[0];
1152 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1156 if (!ir_block_entries_find(self->owner, b, NULL)) {
1157 /* Must not be possible to cause this, otherwise the AST
1158 * is doing something wrong.
1160 fprintf(stderr, "Invalid entry block for PHI\n");
1166 if (!ir_value_reads_add(v, self))
1168 return ir_instr_phi_add(self, pe);
1171 /* call related code */
1172 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1176 in = ir_instr_new(self, INSTR_CALL0);
1179 out = ir_value_out(self->owner, label, store_return, func->outtype);
1181 ir_instr_delete(in);
1184 if (!ir_instr_op(in, 0, out, true) ||
1185 !ir_instr_op(in, 1, func, false) ||
1186 !ir_block_instr_add(self, in))
1188 ir_instr_delete(in);
1189 ir_value_delete(out);
1195 ir_value* ir_call_value(ir_instr *self)
1197 return self->_ops[0];
1200 bool ir_call_param(ir_instr* self, ir_value *v)
1202 if (!ir_instr_params_add(self, v))
1204 if (!ir_value_reads_add(v, self)) {
1205 if (!ir_instr_params_remove(self, self->params_count-1))
1206 GMQCC_SUPPRESS_EMPTY_BODY;
1212 /* binary op related code */
1214 ir_value* ir_block_create_binop(ir_block *self,
1215 const char *label, int opcode,
1216 ir_value *left, ir_value *right)
1238 case INSTR_SUB_S: /* -- offset of string as float */
1243 case INSTR_BITOR_IF:
1244 case INSTR_BITOR_FI:
1245 case INSTR_BITAND_FI:
1246 case INSTR_BITAND_IF:
1261 case INSTR_BITAND_I:
1264 case INSTR_RSHIFT_I:
1265 case INSTR_LSHIFT_I:
1287 /* boolean operations result in floats */
1288 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1290 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1293 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1298 if (ot == TYPE_VOID) {
1299 /* The AST or parser were supposed to check this! */
1303 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1306 ir_value* ir_block_create_unary(ir_block *self,
1307 const char *label, int opcode,
1310 int ot = TYPE_FLOAT;
1322 /* QC doesn't have other unary operations. We expect extensions to fill
1323 * the above list, otherwise we assume out-type = in-type, eg for an
1327 ot = operand->vtype;
1330 if (ot == TYPE_VOID) {
1331 /* The AST or parser were supposed to check this! */
1335 /* let's use the general instruction creator and pass NULL for OPB */
1336 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1339 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1340 int op, ir_value *a, ir_value *b, int outype)
1345 out = ir_value_out(self->owner, label, store_value, outype);
1349 instr = ir_instr_new(self, op);
1351 ir_value_delete(out);
1355 if (!ir_instr_op(instr, 0, out, true) ||
1356 !ir_instr_op(instr, 1, a, false) ||
1357 !ir_instr_op(instr, 2, b, false) )
1362 if (!ir_block_instr_add(self, instr))
1367 ir_instr_delete(instr);
1368 ir_value_delete(out);
1372 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1376 /* Support for various pointer types todo if so desired */
1377 if (ent->vtype != TYPE_ENTITY)
1380 if (field->vtype != TYPE_FIELD)
1383 v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1384 v->fieldtype = field->fieldtype;
1388 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1391 if (ent->vtype != TYPE_ENTITY)
1394 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1395 if (field->vtype != TYPE_FIELD)
1400 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1401 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1402 case TYPE_STRING: op = INSTR_LOAD_S; break;
1403 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1404 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1406 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1407 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1413 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1416 ir_value* ir_block_create_add(ir_block *self,
1418 ir_value *left, ir_value *right)
1421 int l = left->vtype;
1422 int r = right->vtype;
1441 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1443 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1449 return ir_block_create_binop(self, label, op, left, right);
1452 ir_value* ir_block_create_sub(ir_block *self,
1454 ir_value *left, ir_value *right)
1457 int l = left->vtype;
1458 int r = right->vtype;
1478 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1480 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1486 return ir_block_create_binop(self, label, op, left, right);
1489 ir_value* ir_block_create_mul(ir_block *self,
1491 ir_value *left, ir_value *right)
1494 int l = left->vtype;
1495 int r = right->vtype;
1514 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1516 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1519 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1521 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1523 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1525 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1531 return ir_block_create_binop(self, label, op, left, right);
1534 ir_value* ir_block_create_div(ir_block *self,
1536 ir_value *left, ir_value *right)
1539 int l = left->vtype;
1540 int r = right->vtype;
1557 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1559 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1561 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1567 return ir_block_create_binop(self, label, op, left, right);
1570 /* PHI resolving breaks the SSA, and must thus be the last
1571 * step before life-range calculation.
1574 static bool ir_block_naive_phi(ir_block *self);
1575 bool ir_function_naive_phi(ir_function *self)
1579 for (i = 0; i < self->blocks_count; ++i)
1581 if (!ir_block_naive_phi(self->blocks[i]))
1587 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1592 /* create a store */
1593 if (!ir_block_create_store(block, old, what))
1596 /* we now move it up */
1597 instr = block->instr[block->instr_count-1];
1598 for (i = block->instr_count; i > iid; --i)
1599 block->instr[i] = block->instr[i-1];
1600 block->instr[i] = instr;
1605 static bool ir_block_naive_phi(ir_block *self)
1608 /* FIXME: optionally, create_phi can add the phis
1609 * to a list so we don't need to loop through blocks
1610 * - anyway: "don't optimize YET"
1612 for (i = 0; i < self->instr_count; ++i)
1614 ir_instr *instr = self->instr[i];
1615 if (instr->opcode != VINSTR_PHI)
1618 if (!ir_block_instr_remove(self, i))
1620 --i; /* NOTE: i+1 below */
1622 for (p = 0; p < instr->phi_count; ++p)
1624 ir_value *v = instr->phi[p].value;
1625 for (w = 0; w < v->writes_count; ++w) {
1628 if (!v->writes[w]->_ops[0])
1631 /* When the write was to a global, we have to emit a mov */
1632 old = v->writes[w]->_ops[0];
1634 /* The original instruction now writes to the PHI target local */
1635 if (v->writes[w]->_ops[0] == v)
1636 v->writes[w]->_ops[0] = instr->_ops[0];
1638 if (old->store != store_value && old->store != store_local && old->store != store_param)
1640 /* If it originally wrote to a global we need to store the value
1643 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1645 if (i+1 < self->instr_count)
1646 instr = self->instr[i+1];
1649 /* In case I forget and access instr later, it'll be NULL
1650 * when it's a problem, to make sure we crash, rather than accessing
1656 /* If it didn't, we can replace all reads by the phi target now. */
1658 for (r = 0; r < old->reads_count; ++r)
1661 ir_instr *ri = old->reads[r];
1662 for (op = 0; op < ri->phi_count; ++op) {
1663 if (ri->phi[op].value == old)
1664 ri->phi[op].value = v;
1666 for (op = 0; op < 3; ++op) {
1667 if (ri->_ops[op] == old)
1674 ir_instr_delete(instr);
1679 /***********************************************************************
1680 *IR Temp allocation code
1681 * Propagating value life ranges by walking through the function backwards
1682 * until no more changes are made.
1683 * In theory this should happen once more than once for every nested loop
1685 * Though this implementation might run an additional time for if nests.
1694 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1696 /* Enumerate instructions used by value's life-ranges
1698 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1702 for (i = 0; i < self->instr_count; ++i)
1704 self->instr[i]->eid = eid++;
1709 /* Enumerate blocks and instructions.
1710 * The block-enumeration is unordered!
1711 * We do not really use the block enumreation, however
1712 * the instruction enumeration is important for life-ranges.
1714 void ir_function_enumerate(ir_function *self)
1717 size_t instruction_id = 0;
1718 for (i = 0; i < self->blocks_count; ++i)
1720 self->blocks[i]->eid = i;
1721 self->blocks[i]->run_id = 0;
1722 ir_block_enumerate(self->blocks[i], &instruction_id);
1726 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1727 bool ir_function_calculate_liferanges(ir_function *self)
1735 for (i = 0; i != self->blocks_count; ++i)
1737 if (self->blocks[i]->is_return)
1739 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1747 /* Local-value allocator
1748 * After finishing creating the liferange of all values used in a function
1749 * we can allocate their global-positions.
1750 * This is the counterpart to register-allocation in register machines.
1753 MEM_VECTOR_MAKE(ir_value*, locals);
1754 MEM_VECTOR_MAKE(size_t, sizes);
1755 MEM_VECTOR_MAKE(size_t, positions);
1756 } function_allocator;
1757 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1758 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1759 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1761 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1764 size_t vsize = type_sizeof[var->vtype];
1766 slot = ir_value_var("reg", store_global, var->vtype);
1770 if (!ir_value_life_merge_into(slot, var))
1773 if (!function_allocator_locals_add(alloc, slot))
1776 if (!function_allocator_sizes_add(alloc, vsize))
1782 ir_value_delete(slot);
1786 bool ir_function_allocate_locals(ir_function *self)
1795 function_allocator alloc;
1797 if (!self->locals_count)
1800 MEM_VECTOR_INIT(&alloc, locals);
1801 MEM_VECTOR_INIT(&alloc, sizes);
1802 MEM_VECTOR_INIT(&alloc, positions);
1804 for (i = 0; i < self->locals_count; ++i)
1806 if (!function_allocator_alloc(&alloc, self->locals[i]))
1810 /* Allocate a slot for any value that still exists */
1811 for (i = 0; i < self->values_count; ++i)
1813 v = self->values[i];
1818 for (a = 0; a < alloc.locals_count; ++a)
1820 slot = alloc.locals[a];
1822 if (ir_values_overlap(v, slot))
1825 if (!ir_value_life_merge_into(slot, v))
1828 /* adjust size for this slot */
1829 if (alloc.sizes[a] < type_sizeof[v->vtype])
1830 alloc.sizes[a] = type_sizeof[v->vtype];
1832 self->values[i]->code.local = a;
1835 if (a >= alloc.locals_count) {
1836 self->values[i]->code.local = alloc.locals_count;
1837 if (!function_allocator_alloc(&alloc, v))
1842 /* Adjust slot positions based on sizes */
1843 if (!function_allocator_positions_add(&alloc, 0))
1846 if (alloc.sizes_count)
1847 pos = alloc.positions[0] + alloc.sizes[0];
1850 for (i = 1; i < alloc.sizes_count; ++i)
1852 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1853 if (!function_allocator_positions_add(&alloc, pos))
1857 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1859 /* Take over the actual slot positions */
1860 for (i = 0; i < self->values_count; ++i)
1861 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1868 for (i = 0; i < alloc.locals_count; ++i)
1869 ir_value_delete(alloc.locals[i]);
1870 MEM_VECTOR_CLEAR(&alloc, locals);
1871 MEM_VECTOR_CLEAR(&alloc, sizes);
1872 MEM_VECTOR_CLEAR(&alloc, positions);
1876 /* Get information about which operand
1877 * is read from, or written to.
1879 static void ir_op_read_write(int op, size_t *read, size_t *write)
1906 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1909 bool changed = false;
1911 for (i = 0; i != self->living_count; ++i)
1913 tempbool = ir_value_life_merge(self->living[i], eid);
1916 fprintf(stderr, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1918 changed = changed || tempbool;
1923 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1926 /* values which have been read in a previous iteration are now
1927 * in the "living" array even if the previous block doesn't use them.
1928 * So we have to remove whatever does not exist in the previous block.
1929 * They will be re-added on-read, but the liferange merge won't cause
1932 for (i = 0; i < self->living_count; ++i)
1934 if (!ir_block_living_find(prev, self->living[i], NULL)) {
1935 if (!ir_block_living_remove(self, i))
1941 /* Whatever the previous block still has in its living set
1942 * must now be added to ours as well.
1944 for (i = 0; i < prev->living_count; ++i)
1946 if (ir_block_living_find(self, prev->living[i], NULL))
1948 if (!ir_block_living_add(self, prev->living[i]))
1951 printf("%s got from prev: %s\n", self->label, prev->living[i]->_name);
1957 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
1963 /* bitmasks which operands are read from or written to */
1965 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1967 new_reads_t new_reads;
1969 char dbg_ind[16] = { '#', '0' };
1972 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1973 MEM_VECTOR_INIT(&new_reads, v);
1978 if (!ir_block_life_prop_previous(self, prev, changed))
1982 i = self->instr_count;
1985 instr = self->instr[i];
1987 /* PHI operands are always read operands */
1988 for (p = 0; p < instr->phi_count; ++p)
1990 value = instr->phi[p].value;
1991 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1992 if (!ir_block_living_find(self, value, NULL) &&
1993 !ir_block_living_add(self, value))
1998 if (!new_reads_t_v_find(&new_reads, value, NULL))
2000 if (!new_reads_t_v_add(&new_reads, value))
2006 /* See which operands are read and write operands */
2007 ir_op_read_write(instr->opcode, &read, &write);
2009 /* Go through the 3 main operands */
2010 for (o = 0; o < 3; ++o)
2012 if (!instr->_ops[o]) /* no such operand */
2015 value = instr->_ops[o];
2017 /* We only care about locals */
2018 /* we also calculate parameter liferanges so that locals
2019 * can take up parameter slots */
2020 if (value->store != store_value &&
2021 value->store != store_local &&
2022 value->store != store_param)
2028 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2029 if (!ir_block_living_find(self, value, NULL) &&
2030 !ir_block_living_add(self, value))
2035 /* fprintf(stderr, "read: %s\n", value->_name); */
2036 if (!new_reads_t_v_find(&new_reads, value, NULL))
2038 if (!new_reads_t_v_add(&new_reads, value))
2044 /* write operands */
2045 /* When we write to a local, we consider it "dead" for the
2046 * remaining upper part of the function, since in SSA a value
2047 * can only be written once (== created)
2052 bool in_living = ir_block_living_find(self, value, &idx);
2053 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2055 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
2056 if (!in_living && !in_reads)
2061 /* If the value isn't alive it hasn't been read before... */
2062 /* TODO: See if the warning can be emitted during parsing or AST processing
2063 * otherwise have warning printed here.
2064 * IF printing a warning here: include filecontext_t,
2065 * and make sure it's only printed once
2066 * since this function is run multiple times.
2068 /* For now: debug info: */
2069 fprintf(stderr, "Value only written %s\n", value->name);
2070 tempbool = ir_value_life_merge(value, instr->eid);
2071 *changed = *changed || tempbool;
2073 ir_instr_dump(instr, dbg_ind, printf);
2077 /* since 'living' won't contain it
2078 * anymore, merge the value, since
2081 tempbool = ir_value_life_merge(value, instr->eid);
2084 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2086 *changed = *changed || tempbool;
2088 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2089 if (!ir_block_living_remove(self, idx))
2094 if (!new_reads_t_v_remove(&new_reads, readidx))
2102 tempbool = ir_block_living_add_instr(self, instr->eid);
2103 /*fprintf(stderr, "living added values\n");*/
2104 *changed = *changed || tempbool;
2106 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2108 for (rd = 0; rd < new_reads.v_count; ++rd)
2110 if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
2111 if (!ir_block_living_add(self, new_reads.v[rd]))
2114 if (!i && !self->entries_count) {
2116 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
2119 MEM_VECTOR_CLEAR(&new_reads, v);
2123 if (self->run_id == self->owner->run_id)
2126 self->run_id = self->owner->run_id;
2128 for (i = 0; i < self->entries_count; ++i)
2130 ir_block *entry = self->entries[i];
2131 ir_block_life_propagate(entry, self, changed);
2136 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2137 MEM_VECTOR_CLEAR(&new_reads, v);
2142 /***********************************************************************
2145 * Since the IR has the convention of putting 'write' operands
2146 * at the beginning, we have to rotate the operands of instructions
2147 * properly in order to generate valid QCVM code.
2149 * Having destinations at a fixed position is more convenient. In QC
2150 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2151 * read from from OPA, and store to OPB rather than OPC. Which is
2152 * partially the reason why the implementation of these instructions
2153 * in darkplaces has been delayed for so long.
2155 * Breaking conventions is annoying...
2157 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2159 static bool gen_global_field(ir_value *global)
2161 if (global->isconst)
2163 ir_value *fld = global->constval.vpointer;
2165 printf("Invalid field constant with no field: %s\n", global->name);
2169 /* Now, in this case, a relocation would be impossible to code
2170 * since it looks like this:
2171 * .vector v = origin; <- parse error, wtf is 'origin'?
2174 * But we will need a general relocation support later anyway
2175 * for functions... might as well support that here.
2177 if (!fld->code.globaladdr) {
2178 printf("FIXME: Relocation support\n");
2182 /* copy the field's value */
2183 ir_value_code_setaddr(global, code_globals_add(code_globals_data[fld->code.globaladdr]));
2184 if (global->fieldtype == TYPE_VECTOR) {
2185 code_globals_add(code_globals_data[fld->code.globaladdr]+1);
2186 code_globals_add(code_globals_data[fld->code.globaladdr]+2);
2191 ir_value_code_setaddr(global, code_globals_add(0));
2192 if (global->fieldtype == TYPE_VECTOR) {
2193 code_globals_add(0);
2194 code_globals_add(0);
2197 if (global->code.globaladdr < 0)
2202 static bool gen_global_pointer(ir_value *global)
2204 if (global->isconst)
2206 ir_value *target = global->constval.vpointer;
2208 printf("Invalid pointer constant: %s\n", global->name);
2209 /* NULL pointers are pointing to the NULL constant, which also
2210 * sits at address 0, but still has an ir_value for itself.
2215 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2216 * void() foo; <- proto
2217 * void() *fooptr = &foo;
2218 * void() foo = { code }
2220 if (!target->code.globaladdr) {
2221 /* FIXME: Check for the constant nullptr ir_value!
2222 * because then code.globaladdr being 0 is valid.
2224 printf("FIXME: Relocation support\n");
2228 ir_value_code_setaddr(global, code_globals_add(target->code.globaladdr));
2232 ir_value_code_setaddr(global, code_globals_add(0));
2234 if (global->code.globaladdr < 0)
2239 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2241 prog_section_statement stmt;
2250 block->generated = true;
2251 block->code_start = code_statements_elements;
2252 for (i = 0; i < block->instr_count; ++i)
2254 instr = block->instr[i];
2256 if (instr->opcode == VINSTR_PHI) {
2257 printf("cannot generate virtual instruction (phi)\n");
2261 if (instr->opcode == VINSTR_JUMP) {
2262 target = instr->bops[0];
2263 /* for uncoditional jumps, if the target hasn't been generated
2264 * yet, we generate them right here.
2266 if (!target->generated) {
2271 /* otherwise we generate a jump instruction */
2272 stmt.opcode = INSTR_GOTO;
2273 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2276 if (code_statements_add(stmt) < 0)
2279 /* no further instructions can be in this block */
2283 if (instr->opcode == VINSTR_COND) {
2284 ontrue = instr->bops[0];
2285 onfalse = instr->bops[1];
2286 /* TODO: have the AST signal which block should
2287 * come first: eg. optimize IFs without ELSE...
2290 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2294 if (ontrue->generated) {
2295 stmt.opcode = INSTR_IF;
2296 stmt.o2.s1 = (ontrue->code_start-1) - code_statements_elements;
2297 if (code_statements_add(stmt) < 0)
2300 if (onfalse->generated) {
2301 stmt.opcode = INSTR_IFNOT;
2302 stmt.o2.s1 = (onfalse->code_start-1) - code_statements_elements;
2303 if (code_statements_add(stmt) < 0)
2306 if (!ontrue->generated) {
2307 if (onfalse->generated) {
2312 if (!onfalse->generated) {
2313 if (ontrue->generated) {
2318 /* neither ontrue nor onfalse exist */
2319 stmt.opcode = INSTR_IFNOT;
2320 stidx = code_statements_elements;
2321 if (code_statements_add(stmt) < 0)
2323 /* on false we jump, so add ontrue-path */
2324 if (!gen_blocks_recursive(func, ontrue))
2326 /* fixup the jump address */
2327 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2328 /* generate onfalse path */
2329 if (onfalse->generated) {
2330 /* fixup the jump address */
2331 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2332 /* may have been generated in the previous recursive call */
2333 stmt.opcode = INSTR_GOTO;
2334 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2337 return (code_statements_add(stmt) >= 0);
2339 /* if not, generate now */
2344 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2345 /* Trivial call translation:
2346 * copy all params to OFS_PARM*
2347 * if the output's storetype is not store_return,
2348 * add append a STORE instruction!
2350 * NOTES on how to do it better without much trouble:
2351 * -) The liferanges!
2352 * Simply check the liferange of all parameters for
2353 * other CALLs. For each param with no CALL in its
2354 * liferange, we can store it in an OFS_PARM at
2355 * generation already. This would even include later
2356 * reuse.... probably... :)
2361 for (p = 0; p < instr->params_count; ++p)
2363 ir_value *param = instr->params[p];
2365 stmt.opcode = INSTR_STORE_F;
2368 stmt.opcode = type_store_instr[param->vtype];
2369 stmt.o1.u1 = ir_value_code_addr(param);
2370 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2371 if (code_statements_add(stmt) < 0)
2374 stmt.opcode = INSTR_CALL0 + instr->params_count;
2375 if (stmt.opcode > INSTR_CALL8)
2376 stmt.opcode = INSTR_CALL8;
2377 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2380 if (code_statements_add(stmt) < 0)
2383 retvalue = instr->_ops[0];
2384 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2386 /* not to be kept in OFS_RETURN */
2387 stmt.opcode = type_store_instr[retvalue->vtype];
2388 stmt.o1.u1 = OFS_RETURN;
2389 stmt.o2.u1 = ir_value_code_addr(retvalue);
2391 if (code_statements_add(stmt) < 0)
2397 if (instr->opcode == INSTR_STATE) {
2398 printf("TODO: state instruction\n");
2402 stmt.opcode = instr->opcode;
2407 /* This is the general order of operands */
2409 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2412 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2415 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2417 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2419 stmt.o1.u1 = stmt.o3.u1;
2422 else if ((stmt.opcode >= INSTR_STORE_F &&
2423 stmt.opcode <= INSTR_STORE_FNC) ||
2424 (stmt.opcode >= INSTR_STOREP_F &&
2425 stmt.opcode <= INSTR_STOREP_FNC))
2427 /* 2-operand instructions with A -> B */
2428 stmt.o2.u1 = stmt.o3.u1;
2432 if (code_statements_add(stmt) < 0)
2438 static bool gen_function_code(ir_function *self)
2441 prog_section_statement stmt;
2443 /* Starting from entry point, we generate blocks "as they come"
2444 * for now. Dead blocks will not be translated obviously.
2446 if (!self->blocks_count) {
2447 printf("Function '%s' declared without body.\n", self->name);
2451 block = self->blocks[0];
2452 if (block->generated)
2455 if (!gen_blocks_recursive(self, block)) {
2456 printf("failed to generate blocks for '%s'\n", self->name);
2460 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2461 stmt.opcode = AINSTR_END;
2465 if (code_statements_add(stmt) < 0)
2470 static bool gen_global_function(ir_builder *ir, ir_value *global)
2472 prog_section_function fun;
2476 size_t local_var_end;
2478 if (!global->isconst || (!global->constval.vfunc))
2480 printf("Invalid state of function-global: not constant: %s\n", global->name);
2484 irfun = global->constval.vfunc;
2486 fun.name = global->code.name;
2487 fun.file = code_cachedstring(global->context.file);
2488 fun.profile = 0; /* always 0 */
2489 fun.nargs = irfun->params_count;
2491 for (i = 0;i < 8; ++i) {
2495 fun.argsize[i] = type_sizeof[irfun->params[i]];
2498 fun.firstlocal = code_globals_elements;
2499 fun.locals = irfun->allocated_locals + irfun->locals_count;
2502 for (i = 0; i < irfun->locals_count; ++i) {
2503 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2504 printf("Failed to generate global %s\n", irfun->locals[i]->name);
2508 if (irfun->locals_count) {
2509 ir_value *last = irfun->locals[irfun->locals_count-1];
2510 local_var_end = last->code.globaladdr;
2511 local_var_end += type_sizeof[last->vtype];
2513 for (i = 0; i < irfun->values_count; ++i)
2515 /* generate code.globaladdr for ssa values */
2516 ir_value *v = irfun->values[i];
2517 ir_value_code_setaddr(v, local_var_end + v->code.local);
2519 for (i = 0; i < irfun->locals_count; ++i) {
2520 /* fill the locals with zeros */
2521 code_globals_add(0);
2525 fun.entry = irfun->builtin;
2527 fun.entry = code_statements_elements;
2528 if (!gen_function_code(irfun)) {
2529 printf("Failed to generate code for function %s\n", irfun->name);
2534 return (code_functions_add(fun) >= 0);
2537 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2541 prog_section_def def;
2543 def.type = global->vtype;
2544 def.offset = code_globals_elements;
2545 def.name = global->code.name = code_genstring(global->name);
2547 switch (global->vtype)
2550 if (code_defs_add(def) < 0)
2552 return gen_global_pointer(global);
2554 if (code_defs_add(def) < 0)
2556 return gen_global_field(global);
2561 if (code_defs_add(def) < 0)
2564 if (global->isconst) {
2565 iptr = (int32_t*)&global->constval.vfloat;
2566 ir_value_code_setaddr(global, code_globals_add(*iptr));
2568 ir_value_code_setaddr(global, code_globals_add(0));
2570 return global->code.globaladdr >= 0;
2574 if (code_defs_add(def) < 0)
2576 if (global->isconst)
2577 ir_value_code_setaddr(global, code_globals_add(code_cachedstring(global->constval.vstring)));
2579 ir_value_code_setaddr(global, code_globals_add(0));
2580 return global->code.globaladdr >= 0;
2585 if (code_defs_add(def) < 0)
2588 if (global->isconst) {
2589 iptr = (int32_t*)&global->constval.vvec;
2590 ir_value_code_setaddr(global, code_globals_add(iptr[0]));
2591 if (global->code.globaladdr < 0)
2593 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2595 if (code_globals_add(iptr[d]) < 0)
2599 ir_value_code_setaddr(global, code_globals_add(0));
2600 if (global->code.globaladdr < 0)
2602 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2604 if (code_globals_add(0) < 0)
2608 return global->code.globaladdr >= 0;
2611 if (code_defs_add(def) < 0)
2613 ir_value_code_setaddr(global, code_globals_elements);
2614 code_globals_add(code_functions_elements);
2615 return gen_global_function(self, global);
2617 /* assume biggest type */
2618 ir_value_code_setaddr(global, code_globals_add(0));
2619 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2620 code_globals_add(0);
2623 /* refuse to create 'void' type or any other fancy business. */
2624 printf("Invalid type for global variable %s\n", global->name);
2629 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2631 prog_section_def def;
2632 prog_section_field fld;
2634 def.type = field->vtype;
2635 def.offset = code_globals_elements;
2637 /* create a global named the same as the field */
2638 if (opts_standard == COMPILER_GMQCC) {
2639 /* in our standard, the global gets a dot prefix */
2640 size_t len = strlen(field->name);
2643 /* we really don't want to have to allocate this, and 1024
2644 * bytes is more than enough for a variable/field name
2646 if (len+2 >= sizeof(name)) {
2647 printf("invalid field name size: %u\n", (unsigned int)len);
2652 strcpy(name+1, field->name); /* no strncpy - we used strlen above */
2655 def.name = code_genstring(name);
2656 fld.name = def.name + 1; /* we reuse that string table entry */
2658 /* in plain QC, there cannot be a global with the same name,
2659 * and so we also name the global the same.
2660 * FIXME: fteqcc should create a global as well
2661 * check if it actually uses the same name. Probably does
2663 def.name = code_genstring(field->name);
2664 fld.name = def.name;
2667 field->code.name = def.name;
2669 if (code_defs_add(def) < 0)
2672 fld.type = field->fieldtype;
2674 if (fld.type == TYPE_VOID) {
2675 printf("field is missing a type: %s - don't know its size\n", field->name);
2679 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2681 if (code_fields_add(fld) < 0)
2684 ir_value_code_setaddr(field, code_globals_elements);
2685 if (!code_globals_add(fld.offset))
2687 if (fld.type == TYPE_VECTOR) {
2688 if (!code_globals_add(fld.offset+1))
2690 if (!code_globals_add(fld.offset+2))
2694 return field->code.globaladdr >= 0;
2697 bool ir_builder_generate(ir_builder *self, const char *filename)
2703 for (i = 0; i < self->fields_count; ++i)
2705 if (!ir_builder_gen_field(self, self->fields[i])) {
2710 for (i = 0; i < self->globals_count; ++i)
2712 if (!ir_builder_gen_global(self, self->globals[i])) {
2717 printf("writing '%s'...\n", filename);
2718 return code_write(filename);
2721 /***********************************************************************
2722 *IR DEBUG Dump functions...
2725 #define IND_BUFSZ 1024
2727 const char *qc_opname(int op)
2729 if (op < 0) return "<INVALID>";
2730 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2731 return asm_instr[op].m;
2733 case VINSTR_PHI: return "PHI";
2734 case VINSTR_JUMP: return "JUMP";
2735 case VINSTR_COND: return "COND";
2736 default: return "<UNK>";
2740 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2743 char indent[IND_BUFSZ];
2747 oprintf("module %s\n", b->name);
2748 for (i = 0; i < b->globals_count; ++i)
2751 if (b->globals[i]->isconst)
2752 oprintf("%s = ", b->globals[i]->name);
2753 ir_value_dump(b->globals[i], oprintf);
2756 for (i = 0; i < b->functions_count; ++i)
2757 ir_function_dump(b->functions[i], indent, oprintf);
2758 oprintf("endmodule %s\n", b->name);
2761 void ir_function_dump(ir_function *f, char *ind,
2762 int (*oprintf)(const char*, ...))
2765 if (f->builtin != 0) {
2766 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2769 oprintf("%sfunction %s\n", ind, f->name);
2770 strncat(ind, "\t", IND_BUFSZ);
2771 if (f->locals_count)
2773 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2774 for (i = 0; i < f->locals_count; ++i) {
2775 oprintf("%s\t", ind);
2776 ir_value_dump(f->locals[i], oprintf);
2780 if (f->blocks_count)
2782 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2783 for (i = 0; i < f->blocks_count; ++i) {
2784 if (f->blocks[i]->run_id != f->run_id) {
2785 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2787 ir_block_dump(f->blocks[i], ind, oprintf);
2791 ind[strlen(ind)-1] = 0;
2792 oprintf("%sendfunction %s\n", ind, f->name);
2795 void ir_block_dump(ir_block* b, char *ind,
2796 int (*oprintf)(const char*, ...))
2799 oprintf("%s:%s\n", ind, b->label);
2800 strncat(ind, "\t", IND_BUFSZ);
2802 for (i = 0; i < b->instr_count; ++i)
2803 ir_instr_dump(b->instr[i], ind, oprintf);
2804 ind[strlen(ind)-1] = 0;
2807 void dump_phi(ir_instr *in, char *ind,
2808 int (*oprintf)(const char*, ...))
2811 oprintf("%s <- phi ", in->_ops[0]->name);
2812 for (i = 0; i < in->phi_count; ++i)
2814 oprintf("([%s] : %s) ", in->phi[i].from->label,
2815 in->phi[i].value->name);
2820 void ir_instr_dump(ir_instr *in, char *ind,
2821 int (*oprintf)(const char*, ...))
2824 const char *comma = NULL;
2826 oprintf("%s (%i) ", ind, (int)in->eid);
2828 if (in->opcode == VINSTR_PHI) {
2829 dump_phi(in, ind, oprintf);
2833 strncat(ind, "\t", IND_BUFSZ);
2835 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2836 ir_value_dump(in->_ops[0], oprintf);
2837 if (in->_ops[1] || in->_ops[2])
2840 if (in->opcode == INSTR_CALL0) {
2841 oprintf("CALL%i\t", in->params_count);
2843 oprintf("%s\t", qc_opname(in->opcode));
2845 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2846 ir_value_dump(in->_ops[0], oprintf);
2851 for (i = 1; i != 3; ++i) {
2855 ir_value_dump(in->_ops[i], oprintf);
2863 oprintf("[%s]", in->bops[0]->label);
2867 oprintf("%s[%s]", comma, in->bops[1]->label);
2869 ind[strlen(ind)-1] = 0;
2872 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
2881 oprintf("(function)");
2884 oprintf("%g", v->constval.vfloat);
2887 oprintf("'%g %g %g'",
2890 v->constval.vvec.z);
2893 oprintf("(entity)");
2896 oprintf("\"%s\"", v->constval.vstring);
2900 oprintf("%i", v->constval.vint);
2905 v->constval.vpointer->name);
2909 oprintf("%s", v->name);
2913 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
2916 oprintf("Life of %s:\n", self->name);
2917 for (i = 0; i < self->life_count; ++i)
2919 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);