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 self->members[0] = NULL;
579 self->members[1] = NULL;
580 self->members[2] = NULL;
582 MEM_VECTOR_INIT(self, life);
586 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
592 if (self->members[member])
593 return self->members[member];
595 if (self->vtype == TYPE_VECTOR)
597 m = ir_value_var(self->name, self->store, TYPE_FLOAT);
600 m->context = self->context;
602 self->members[member] = m;
603 m->code.addroffset = member;
605 else if (self->vtype == TYPE_FIELD)
607 if (self->fieldtype != TYPE_VECTOR)
609 m = ir_value_var(self->name, self->store, TYPE_FIELD);
612 m->fieldtype = TYPE_FLOAT;
613 m->context = self->context;
615 self->members[member] = m;
616 m->code.addroffset = member;
620 printf("invalid member access on %s\n", self->name);
627 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
628 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
629 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
631 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
633 ir_value *v = ir_value_var(name, storetype, vtype);
636 if (!ir_function_collect_value(owner, v))
644 void ir_value_delete(ir_value* self)
648 mem_d((void*)self->name);
651 if (self->vtype == TYPE_STRING)
652 mem_d((void*)self->constval.vstring);
654 for (i = 0; i < 3; ++i) {
655 if (self->members[i])
656 ir_value_delete(self->members[i]);
658 MEM_VECTOR_CLEAR(self, reads);
659 MEM_VECTOR_CLEAR(self, writes);
660 MEM_VECTOR_CLEAR(self, life);
664 void ir_value_set_name(ir_value *self, const char *name)
667 mem_d((void*)self->name);
668 self->name = util_strdup(name);
671 bool ir_value_set_float(ir_value *self, float f)
673 if (self->vtype != TYPE_FLOAT)
675 self->constval.vfloat = f;
676 self->isconst = true;
680 bool ir_value_set_func(ir_value *self, int f)
682 if (self->vtype != TYPE_FUNCTION)
684 self->constval.vint = f;
685 self->isconst = true;
689 bool ir_value_set_vector(ir_value *self, vector v)
691 if (self->vtype != TYPE_VECTOR)
693 self->constval.vvec = v;
694 self->isconst = true;
698 bool ir_value_set_field(ir_value *self, ir_value *fld)
700 if (self->vtype != TYPE_FIELD)
702 self->constval.vpointer = fld;
703 self->isconst = true;
707 bool ir_value_set_string(ir_value *self, const char *str)
709 if (self->vtype != TYPE_STRING)
711 self->constval.vstring = util_strdup(str);
712 self->isconst = true;
717 bool ir_value_set_int(ir_value *self, int i)
719 if (self->vtype != TYPE_INTEGER)
721 self->constval.vint = i;
722 self->isconst = true;
727 bool ir_value_lives(ir_value *self, size_t at)
730 for (i = 0; i < self->life_count; ++i)
732 ir_life_entry_t *life = &self->life[i];
733 if (life->start <= at && at <= life->end)
735 if (life->start > at) /* since it's ordered */
741 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
744 if (!ir_value_life_add(self, e)) /* naive... */
746 for (k = self->life_count-1; k > idx; --k)
747 self->life[k] = self->life[k-1];
752 bool ir_value_life_merge(ir_value *self, size_t s)
755 ir_life_entry_t *life = NULL;
756 ir_life_entry_t *before = NULL;
757 ir_life_entry_t new_entry;
759 /* Find the first range >= s */
760 for (i = 0; i < self->life_count; ++i)
763 life = &self->life[i];
767 /* nothing found? append */
768 if (i == self->life_count) {
770 if (life && life->end+1 == s)
772 /* previous life range can be merged in */
776 if (life && life->end >= s)
779 if (!ir_value_life_add(self, e))
780 return false; /* failing */
786 if (before->end + 1 == s &&
787 life->start - 1 == s)
790 before->end = life->end;
791 if (!ir_value_life_remove(self, i))
792 return false; /* failing */
795 if (before->end + 1 == s)
801 /* already contained */
802 if (before->end >= s)
806 if (life->start - 1 == s)
811 /* insert a new entry */
812 new_entry.start = new_entry.end = s;
813 return ir_value_life_insert(self, i, new_entry);
816 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
820 if (!other->life_count)
823 if (!self->life_count) {
824 for (i = 0; i < other->life_count; ++i) {
825 if (!ir_value_life_add(self, other->life[i]))
832 for (i = 0; i < other->life_count; ++i)
834 const ir_life_entry_t *life = &other->life[i];
837 ir_life_entry_t *entry = &self->life[myi];
839 if (life->end+1 < entry->start)
841 /* adding an interval before entry */
842 if (!ir_value_life_insert(self, myi, *life))
848 if (life->start < entry->start &&
849 life->end >= entry->start)
851 /* starts earlier and overlaps */
852 entry->start = life->start;
855 if (life->end > entry->end &&
856 life->start-1 <= entry->end)
858 /* ends later and overlaps */
859 entry->end = life->end;
862 /* see if our change combines it with the next ranges */
863 while (myi+1 < self->life_count &&
864 entry->end+1 >= self->life[1+myi].start)
866 /* overlaps with (myi+1) */
867 if (entry->end < self->life[1+myi].end)
868 entry->end = self->life[1+myi].end;
869 if (!ir_value_life_remove(self, myi+1))
871 entry = &self->life[myi];
874 /* see if we're after the entry */
875 if (life->start > entry->end)
878 /* append if we're at the end */
879 if (myi >= self->life_count) {
880 if (!ir_value_life_add(self, *life))
884 /* otherweise check the next range */
893 bool ir_values_overlap(const ir_value *a, const ir_value *b)
895 /* For any life entry in A see if it overlaps with
896 * any life entry in B.
897 * Note that the life entries are orderes, so we can make a
898 * more efficient algorithm there than naively translating the
902 ir_life_entry_t *la, *lb, *enda, *endb;
904 /* first of all, if either has no life range, they cannot clash */
905 if (!a->life_count || !b->life_count)
910 enda = la + a->life_count;
911 endb = lb + b->life_count;
914 /* check if the entries overlap, for that,
915 * both must start before the other one ends.
917 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
918 if (la->start <= lb->end &&
919 lb->start <= la->end)
921 if (la->start < lb->end &&
928 /* entries are ordered
929 * one entry is earlier than the other
930 * that earlier entry will be moved forward
932 if (la->start < lb->start)
934 /* order: A B, move A forward
935 * check if we hit the end with A
940 else if (lb->start < la->start)
942 /* order: B A, move B forward
943 * check if we hit the end with B
952 /***********************************************************************
956 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
958 ir_instr *in = ir_instr_new(self, op);
962 if (target->store == store_value &&
963 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
965 fprintf(stderr, "cannot store to an SSA value\n");
966 fprintf(stderr, "trying to store: %s <- %s\n", target->name, what->name);
967 fprintf(stderr, "instruction: %s\n", asm_instr[op].m);
971 if (!ir_instr_op(in, 0, target, true) ||
972 !ir_instr_op(in, 1, what, false) ||
973 !ir_block_instr_add(self, in) )
980 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
984 if (target->vtype == TYPE_VARIANT)
987 vtype = target->vtype;
990 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
991 op = INSTR_CONV_ITOF;
992 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
993 op = INSTR_CONV_FTOI;
995 op = type_store_instr[vtype];
997 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
998 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1002 return ir_block_create_store_op(self, op, target, what);
1005 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
1010 if (target->vtype != TYPE_POINTER)
1013 /* storing using pointer - target is a pointer, type must be
1014 * inferred from source
1016 vtype = what->vtype;
1018 op = type_storep_instr[vtype];
1019 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1020 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1021 op = INSTR_STOREP_V;
1024 return ir_block_create_store_op(self, op, target, what);
1027 bool ir_block_create_return(ir_block *self, ir_value *v)
1031 fprintf(stderr, "block already ended (%s)\n", self->label);
1035 self->is_return = true;
1036 in = ir_instr_new(self, INSTR_RETURN);
1040 if (!ir_instr_op(in, 0, v, false) ||
1041 !ir_block_instr_add(self, in) )
1048 bool ir_block_create_if(ir_block *self, ir_value *v,
1049 ir_block *ontrue, ir_block *onfalse)
1053 fprintf(stderr, "block already ended (%s)\n", self->label);
1057 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1058 in = ir_instr_new(self, VINSTR_COND);
1062 if (!ir_instr_op(in, 0, v, false)) {
1063 ir_instr_delete(in);
1067 in->bops[0] = ontrue;
1068 in->bops[1] = onfalse;
1070 if (!ir_block_instr_add(self, in))
1073 if (!ir_block_exits_add(self, ontrue) ||
1074 !ir_block_exits_add(self, onfalse) ||
1075 !ir_block_entries_add(ontrue, self) ||
1076 !ir_block_entries_add(onfalse, self) )
1083 bool ir_block_create_jump(ir_block *self, ir_block *to)
1087 fprintf(stderr, "block already ended (%s)\n", self->label);
1091 in = ir_instr_new(self, VINSTR_JUMP);
1096 if (!ir_block_instr_add(self, in))
1099 if (!ir_block_exits_add(self, to) ||
1100 !ir_block_entries_add(to, self) )
1107 bool ir_block_create_goto(ir_block *self, ir_block *to)
1111 fprintf(stderr, "block already ended (%s)\n", self->label);
1115 in = ir_instr_new(self, INSTR_GOTO);
1120 if (!ir_block_instr_add(self, in))
1123 if (!ir_block_exits_add(self, to) ||
1124 !ir_block_entries_add(to, self) )
1131 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1135 in = ir_instr_new(self, VINSTR_PHI);
1138 out = ir_value_out(self->owner, label, store_value, ot);
1140 ir_instr_delete(in);
1143 if (!ir_instr_op(in, 0, out, true)) {
1144 ir_instr_delete(in);
1145 ir_value_delete(out);
1148 if (!ir_block_instr_add(self, in)) {
1149 ir_instr_delete(in);
1150 ir_value_delete(out);
1156 ir_value* ir_phi_value(ir_instr *self)
1158 return self->_ops[0];
1161 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1165 if (!ir_block_entries_find(self->owner, b, NULL)) {
1166 /* Must not be possible to cause this, otherwise the AST
1167 * is doing something wrong.
1169 fprintf(stderr, "Invalid entry block for PHI\n");
1175 if (!ir_value_reads_add(v, self))
1177 return ir_instr_phi_add(self, pe);
1180 /* call related code */
1181 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1185 in = ir_instr_new(self, INSTR_CALL0);
1188 out = ir_value_out(self->owner, label, store_return, func->outtype);
1190 ir_instr_delete(in);
1193 if (!ir_instr_op(in, 0, out, true) ||
1194 !ir_instr_op(in, 1, func, false) ||
1195 !ir_block_instr_add(self, in))
1197 ir_instr_delete(in);
1198 ir_value_delete(out);
1204 ir_value* ir_call_value(ir_instr *self)
1206 return self->_ops[0];
1209 bool ir_call_param(ir_instr* self, ir_value *v)
1211 if (!ir_instr_params_add(self, v))
1213 if (!ir_value_reads_add(v, self)) {
1214 if (!ir_instr_params_remove(self, self->params_count-1))
1215 GMQCC_SUPPRESS_EMPTY_BODY;
1221 /* binary op related code */
1223 ir_value* ir_block_create_binop(ir_block *self,
1224 const char *label, int opcode,
1225 ir_value *left, ir_value *right)
1247 case INSTR_SUB_S: /* -- offset of string as float */
1252 case INSTR_BITOR_IF:
1253 case INSTR_BITOR_FI:
1254 case INSTR_BITAND_FI:
1255 case INSTR_BITAND_IF:
1270 case INSTR_BITAND_I:
1273 case INSTR_RSHIFT_I:
1274 case INSTR_LSHIFT_I:
1296 /* boolean operations result in floats */
1297 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1299 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1302 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1307 if (ot == TYPE_VOID) {
1308 /* The AST or parser were supposed to check this! */
1312 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1315 ir_value* ir_block_create_unary(ir_block *self,
1316 const char *label, int opcode,
1319 int ot = TYPE_FLOAT;
1331 /* QC doesn't have other unary operations. We expect extensions to fill
1332 * the above list, otherwise we assume out-type = in-type, eg for an
1336 ot = operand->vtype;
1339 if (ot == TYPE_VOID) {
1340 /* The AST or parser were supposed to check this! */
1344 /* let's use the general instruction creator and pass NULL for OPB */
1345 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1348 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1349 int op, ir_value *a, ir_value *b, int outype)
1354 out = ir_value_out(self->owner, label, store_value, outype);
1358 instr = ir_instr_new(self, op);
1360 ir_value_delete(out);
1364 if (!ir_instr_op(instr, 0, out, true) ||
1365 !ir_instr_op(instr, 1, a, false) ||
1366 !ir_instr_op(instr, 2, b, false) )
1371 if (!ir_block_instr_add(self, instr))
1376 ir_instr_delete(instr);
1377 ir_value_delete(out);
1381 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1385 /* Support for various pointer types todo if so desired */
1386 if (ent->vtype != TYPE_ENTITY)
1389 if (field->vtype != TYPE_FIELD)
1392 v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1393 v->fieldtype = field->fieldtype;
1397 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1400 if (ent->vtype != TYPE_ENTITY)
1403 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1404 if (field->vtype != TYPE_FIELD)
1409 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1410 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1411 case TYPE_STRING: op = INSTR_LOAD_S; break;
1412 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1413 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1415 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1416 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1422 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1425 ir_value* ir_block_create_add(ir_block *self,
1427 ir_value *left, ir_value *right)
1430 int l = left->vtype;
1431 int r = right->vtype;
1450 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1452 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1458 return ir_block_create_binop(self, label, op, left, right);
1461 ir_value* ir_block_create_sub(ir_block *self,
1463 ir_value *left, ir_value *right)
1466 int l = left->vtype;
1467 int r = right->vtype;
1487 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1489 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1495 return ir_block_create_binop(self, label, op, left, right);
1498 ir_value* ir_block_create_mul(ir_block *self,
1500 ir_value *left, ir_value *right)
1503 int l = left->vtype;
1504 int r = right->vtype;
1523 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1525 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1528 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1530 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1532 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1534 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1540 return ir_block_create_binop(self, label, op, left, right);
1543 ir_value* ir_block_create_div(ir_block *self,
1545 ir_value *left, ir_value *right)
1548 int l = left->vtype;
1549 int r = right->vtype;
1566 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1568 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1570 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1576 return ir_block_create_binop(self, label, op, left, right);
1579 /* PHI resolving breaks the SSA, and must thus be the last
1580 * step before life-range calculation.
1583 static bool ir_block_naive_phi(ir_block *self);
1584 bool ir_function_naive_phi(ir_function *self)
1588 for (i = 0; i < self->blocks_count; ++i)
1590 if (!ir_block_naive_phi(self->blocks[i]))
1596 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1601 /* create a store */
1602 if (!ir_block_create_store(block, old, what))
1605 /* we now move it up */
1606 instr = block->instr[block->instr_count-1];
1607 for (i = block->instr_count; i > iid; --i)
1608 block->instr[i] = block->instr[i-1];
1609 block->instr[i] = instr;
1614 static bool ir_block_naive_phi(ir_block *self)
1617 /* FIXME: optionally, create_phi can add the phis
1618 * to a list so we don't need to loop through blocks
1619 * - anyway: "don't optimize YET"
1621 for (i = 0; i < self->instr_count; ++i)
1623 ir_instr *instr = self->instr[i];
1624 if (instr->opcode != VINSTR_PHI)
1627 if (!ir_block_instr_remove(self, i))
1629 --i; /* NOTE: i+1 below */
1631 for (p = 0; p < instr->phi_count; ++p)
1633 ir_value *v = instr->phi[p].value;
1634 for (w = 0; w < v->writes_count; ++w) {
1637 if (!v->writes[w]->_ops[0])
1640 /* When the write was to a global, we have to emit a mov */
1641 old = v->writes[w]->_ops[0];
1643 /* The original instruction now writes to the PHI target local */
1644 if (v->writes[w]->_ops[0] == v)
1645 v->writes[w]->_ops[0] = instr->_ops[0];
1647 if (old->store != store_value && old->store != store_local && old->store != store_param)
1649 /* If it originally wrote to a global we need to store the value
1652 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1654 if (i+1 < self->instr_count)
1655 instr = self->instr[i+1];
1658 /* In case I forget and access instr later, it'll be NULL
1659 * when it's a problem, to make sure we crash, rather than accessing
1665 /* If it didn't, we can replace all reads by the phi target now. */
1667 for (r = 0; r < old->reads_count; ++r)
1670 ir_instr *ri = old->reads[r];
1671 for (op = 0; op < ri->phi_count; ++op) {
1672 if (ri->phi[op].value == old)
1673 ri->phi[op].value = v;
1675 for (op = 0; op < 3; ++op) {
1676 if (ri->_ops[op] == old)
1683 ir_instr_delete(instr);
1688 /***********************************************************************
1689 *IR Temp allocation code
1690 * Propagating value life ranges by walking through the function backwards
1691 * until no more changes are made.
1692 * In theory this should happen once more than once for every nested loop
1694 * Though this implementation might run an additional time for if nests.
1703 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1705 /* Enumerate instructions used by value's life-ranges
1707 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1711 for (i = 0; i < self->instr_count; ++i)
1713 self->instr[i]->eid = eid++;
1718 /* Enumerate blocks and instructions.
1719 * The block-enumeration is unordered!
1720 * We do not really use the block enumreation, however
1721 * the instruction enumeration is important for life-ranges.
1723 void ir_function_enumerate(ir_function *self)
1726 size_t instruction_id = 0;
1727 for (i = 0; i < self->blocks_count; ++i)
1729 self->blocks[i]->eid = i;
1730 self->blocks[i]->run_id = 0;
1731 ir_block_enumerate(self->blocks[i], &instruction_id);
1735 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1736 bool ir_function_calculate_liferanges(ir_function *self)
1744 for (i = 0; i != self->blocks_count; ++i)
1746 if (self->blocks[i]->is_return)
1748 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1756 /* Local-value allocator
1757 * After finishing creating the liferange of all values used in a function
1758 * we can allocate their global-positions.
1759 * This is the counterpart to register-allocation in register machines.
1762 MEM_VECTOR_MAKE(ir_value*, locals);
1763 MEM_VECTOR_MAKE(size_t, sizes);
1764 MEM_VECTOR_MAKE(size_t, positions);
1765 } function_allocator;
1766 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1767 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1768 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1770 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1773 size_t vsize = type_sizeof[var->vtype];
1775 slot = ir_value_var("reg", store_global, var->vtype);
1779 if (!ir_value_life_merge_into(slot, var))
1782 if (!function_allocator_locals_add(alloc, slot))
1785 if (!function_allocator_sizes_add(alloc, vsize))
1791 ir_value_delete(slot);
1795 bool ir_function_allocate_locals(ir_function *self)
1804 function_allocator alloc;
1806 if (!self->locals_count)
1809 MEM_VECTOR_INIT(&alloc, locals);
1810 MEM_VECTOR_INIT(&alloc, sizes);
1811 MEM_VECTOR_INIT(&alloc, positions);
1813 for (i = 0; i < self->locals_count; ++i)
1815 if (!function_allocator_alloc(&alloc, self->locals[i]))
1819 /* Allocate a slot for any value that still exists */
1820 for (i = 0; i < self->values_count; ++i)
1822 v = self->values[i];
1827 for (a = 0; a < alloc.locals_count; ++a)
1829 slot = alloc.locals[a];
1831 if (ir_values_overlap(v, slot))
1834 if (!ir_value_life_merge_into(slot, v))
1837 /* adjust size for this slot */
1838 if (alloc.sizes[a] < type_sizeof[v->vtype])
1839 alloc.sizes[a] = type_sizeof[v->vtype];
1841 self->values[i]->code.local = a;
1844 if (a >= alloc.locals_count) {
1845 self->values[i]->code.local = alloc.locals_count;
1846 if (!function_allocator_alloc(&alloc, v))
1851 /* Adjust slot positions based on sizes */
1852 if (!function_allocator_positions_add(&alloc, 0))
1855 if (alloc.sizes_count)
1856 pos = alloc.positions[0] + alloc.sizes[0];
1859 for (i = 1; i < alloc.sizes_count; ++i)
1861 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1862 if (!function_allocator_positions_add(&alloc, pos))
1866 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1868 /* Take over the actual slot positions */
1869 for (i = 0; i < self->values_count; ++i)
1870 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1877 for (i = 0; i < alloc.locals_count; ++i)
1878 ir_value_delete(alloc.locals[i]);
1879 MEM_VECTOR_CLEAR(&alloc, locals);
1880 MEM_VECTOR_CLEAR(&alloc, sizes);
1881 MEM_VECTOR_CLEAR(&alloc, positions);
1885 /* Get information about which operand
1886 * is read from, or written to.
1888 static void ir_op_read_write(int op, size_t *read, size_t *write)
1915 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1918 bool changed = false;
1920 for (i = 0; i != self->living_count; ++i)
1922 tempbool = ir_value_life_merge(self->living[i], eid);
1925 fprintf(stderr, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1927 changed = changed || tempbool;
1932 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1935 /* values which have been read in a previous iteration are now
1936 * in the "living" array even if the previous block doesn't use them.
1937 * So we have to remove whatever does not exist in the previous block.
1938 * They will be re-added on-read, but the liferange merge won't cause
1941 for (i = 0; i < self->living_count; ++i)
1943 if (!ir_block_living_find(prev, self->living[i], NULL)) {
1944 if (!ir_block_living_remove(self, i))
1950 /* Whatever the previous block still has in its living set
1951 * must now be added to ours as well.
1953 for (i = 0; i < prev->living_count; ++i)
1955 if (ir_block_living_find(self, prev->living[i], NULL))
1957 if (!ir_block_living_add(self, prev->living[i]))
1960 printf("%s got from prev: %s\n", self->label, prev->living[i]->_name);
1966 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
1972 /* bitmasks which operands are read from or written to */
1974 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1976 new_reads_t new_reads;
1978 char dbg_ind[16] = { '#', '0' };
1981 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1982 MEM_VECTOR_INIT(&new_reads, v);
1987 if (!ir_block_life_prop_previous(self, prev, changed))
1991 i = self->instr_count;
1994 instr = self->instr[i];
1996 /* PHI operands are always read operands */
1997 for (p = 0; p < instr->phi_count; ++p)
1999 value = instr->phi[p].value;
2000 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2001 if (!ir_block_living_find(self, value, NULL) &&
2002 !ir_block_living_add(self, value))
2007 if (!new_reads_t_v_find(&new_reads, value, NULL))
2009 if (!new_reads_t_v_add(&new_reads, value))
2015 /* See which operands are read and write operands */
2016 ir_op_read_write(instr->opcode, &read, &write);
2018 /* Go through the 3 main operands */
2019 for (o = 0; o < 3; ++o)
2021 if (!instr->_ops[o]) /* no such operand */
2024 value = instr->_ops[o];
2026 /* We only care about locals */
2027 /* we also calculate parameter liferanges so that locals
2028 * can take up parameter slots */
2029 if (value->store != store_value &&
2030 value->store != store_local &&
2031 value->store != store_param)
2037 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2038 if (!ir_block_living_find(self, value, NULL) &&
2039 !ir_block_living_add(self, value))
2044 /* fprintf(stderr, "read: %s\n", value->_name); */
2045 if (!new_reads_t_v_find(&new_reads, value, NULL))
2047 if (!new_reads_t_v_add(&new_reads, value))
2053 /* write operands */
2054 /* When we write to a local, we consider it "dead" for the
2055 * remaining upper part of the function, since in SSA a value
2056 * can only be written once (== created)
2061 bool in_living = ir_block_living_find(self, value, &idx);
2062 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2064 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
2065 if (!in_living && !in_reads)
2070 /* If the value isn't alive it hasn't been read before... */
2071 /* TODO: See if the warning can be emitted during parsing or AST processing
2072 * otherwise have warning printed here.
2073 * IF printing a warning here: include filecontext_t,
2074 * and make sure it's only printed once
2075 * since this function is run multiple times.
2077 /* For now: debug info: */
2078 fprintf(stderr, "Value only written %s\n", value->name);
2079 tempbool = ir_value_life_merge(value, instr->eid);
2080 *changed = *changed || tempbool;
2082 ir_instr_dump(instr, dbg_ind, printf);
2086 /* since 'living' won't contain it
2087 * anymore, merge the value, since
2090 tempbool = ir_value_life_merge(value, instr->eid);
2093 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2095 *changed = *changed || tempbool;
2097 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2098 if (!ir_block_living_remove(self, idx))
2103 if (!new_reads_t_v_remove(&new_reads, readidx))
2111 tempbool = ir_block_living_add_instr(self, instr->eid);
2112 /*fprintf(stderr, "living added values\n");*/
2113 *changed = *changed || tempbool;
2115 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2117 for (rd = 0; rd < new_reads.v_count; ++rd)
2119 if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
2120 if (!ir_block_living_add(self, new_reads.v[rd]))
2123 if (!i && !self->entries_count) {
2125 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
2128 MEM_VECTOR_CLEAR(&new_reads, v);
2132 if (self->run_id == self->owner->run_id)
2135 self->run_id = self->owner->run_id;
2137 for (i = 0; i < self->entries_count; ++i)
2139 ir_block *entry = self->entries[i];
2140 ir_block_life_propagate(entry, self, changed);
2145 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2146 MEM_VECTOR_CLEAR(&new_reads, v);
2151 /***********************************************************************
2154 * Since the IR has the convention of putting 'write' operands
2155 * at the beginning, we have to rotate the operands of instructions
2156 * properly in order to generate valid QCVM code.
2158 * Having destinations at a fixed position is more convenient. In QC
2159 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2160 * read from from OPA, and store to OPB rather than OPC. Which is
2161 * partially the reason why the implementation of these instructions
2162 * in darkplaces has been delayed for so long.
2164 * Breaking conventions is annoying...
2166 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2168 static bool gen_global_field(ir_value *global)
2170 if (global->isconst)
2172 ir_value *fld = global->constval.vpointer;
2174 printf("Invalid field constant with no field: %s\n", global->name);
2178 /* Now, in this case, a relocation would be impossible to code
2179 * since it looks like this:
2180 * .vector v = origin; <- parse error, wtf is 'origin'?
2183 * But we will need a general relocation support later anyway
2184 * for functions... might as well support that here.
2186 if (!fld->code.globaladdr) {
2187 printf("FIXME: Relocation support\n");
2191 /* copy the field's value */
2192 ir_value_code_setaddr(global, code_globals_add(code_globals_data[fld->code.globaladdr]));
2193 if (global->fieldtype == TYPE_VECTOR) {
2194 code_globals_add(code_globals_data[fld->code.globaladdr]+1);
2195 code_globals_add(code_globals_data[fld->code.globaladdr]+2);
2200 ir_value_code_setaddr(global, code_globals_add(0));
2201 if (global->fieldtype == TYPE_VECTOR) {
2202 code_globals_add(0);
2203 code_globals_add(0);
2206 if (global->code.globaladdr < 0)
2211 static bool gen_global_pointer(ir_value *global)
2213 if (global->isconst)
2215 ir_value *target = global->constval.vpointer;
2217 printf("Invalid pointer constant: %s\n", global->name);
2218 /* NULL pointers are pointing to the NULL constant, which also
2219 * sits at address 0, but still has an ir_value for itself.
2224 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2225 * void() foo; <- proto
2226 * void() *fooptr = &foo;
2227 * void() foo = { code }
2229 if (!target->code.globaladdr) {
2230 /* FIXME: Check for the constant nullptr ir_value!
2231 * because then code.globaladdr being 0 is valid.
2233 printf("FIXME: Relocation support\n");
2237 ir_value_code_setaddr(global, code_globals_add(target->code.globaladdr));
2241 ir_value_code_setaddr(global, code_globals_add(0));
2243 if (global->code.globaladdr < 0)
2248 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2250 prog_section_statement stmt;
2259 block->generated = true;
2260 block->code_start = code_statements_elements;
2261 for (i = 0; i < block->instr_count; ++i)
2263 instr = block->instr[i];
2265 if (instr->opcode == VINSTR_PHI) {
2266 printf("cannot generate virtual instruction (phi)\n");
2270 if (instr->opcode == VINSTR_JUMP) {
2271 target = instr->bops[0];
2272 /* for uncoditional jumps, if the target hasn't been generated
2273 * yet, we generate them right here.
2275 if (!target->generated) {
2280 /* otherwise we generate a jump instruction */
2281 stmt.opcode = INSTR_GOTO;
2282 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2285 if (code_statements_add(stmt) < 0)
2288 /* no further instructions can be in this block */
2292 if (instr->opcode == VINSTR_COND) {
2293 ontrue = instr->bops[0];
2294 onfalse = instr->bops[1];
2295 /* TODO: have the AST signal which block should
2296 * come first: eg. optimize IFs without ELSE...
2299 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2303 if (ontrue->generated) {
2304 stmt.opcode = INSTR_IF;
2305 stmt.o2.s1 = (ontrue->code_start-1) - code_statements_elements;
2306 if (code_statements_add(stmt) < 0)
2309 if (onfalse->generated) {
2310 stmt.opcode = INSTR_IFNOT;
2311 stmt.o2.s1 = (onfalse->code_start-1) - code_statements_elements;
2312 if (code_statements_add(stmt) < 0)
2315 if (!ontrue->generated) {
2316 if (onfalse->generated) {
2321 if (!onfalse->generated) {
2322 if (ontrue->generated) {
2327 /* neither ontrue nor onfalse exist */
2328 stmt.opcode = INSTR_IFNOT;
2329 stidx = code_statements_elements;
2330 if (code_statements_add(stmt) < 0)
2332 /* on false we jump, so add ontrue-path */
2333 if (!gen_blocks_recursive(func, ontrue))
2335 /* fixup the jump address */
2336 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2337 /* generate onfalse path */
2338 if (onfalse->generated) {
2339 /* fixup the jump address */
2340 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2341 /* may have been generated in the previous recursive call */
2342 stmt.opcode = INSTR_GOTO;
2343 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2346 return (code_statements_add(stmt) >= 0);
2348 /* if not, generate now */
2353 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2354 /* Trivial call translation:
2355 * copy all params to OFS_PARM*
2356 * if the output's storetype is not store_return,
2357 * add append a STORE instruction!
2359 * NOTES on how to do it better without much trouble:
2360 * -) The liferanges!
2361 * Simply check the liferange of all parameters for
2362 * other CALLs. For each param with no CALL in its
2363 * liferange, we can store it in an OFS_PARM at
2364 * generation already. This would even include later
2365 * reuse.... probably... :)
2370 for (p = 0; p < instr->params_count; ++p)
2372 ir_value *param = instr->params[p];
2374 stmt.opcode = INSTR_STORE_F;
2377 stmt.opcode = type_store_instr[param->vtype];
2378 stmt.o1.u1 = ir_value_code_addr(param);
2379 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2380 if (code_statements_add(stmt) < 0)
2383 stmt.opcode = INSTR_CALL0 + instr->params_count;
2384 if (stmt.opcode > INSTR_CALL8)
2385 stmt.opcode = INSTR_CALL8;
2386 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2389 if (code_statements_add(stmt) < 0)
2392 retvalue = instr->_ops[0];
2393 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2395 /* not to be kept in OFS_RETURN */
2396 stmt.opcode = type_store_instr[retvalue->vtype];
2397 stmt.o1.u1 = OFS_RETURN;
2398 stmt.o2.u1 = ir_value_code_addr(retvalue);
2400 if (code_statements_add(stmt) < 0)
2406 if (instr->opcode == INSTR_STATE) {
2407 printf("TODO: state instruction\n");
2411 stmt.opcode = instr->opcode;
2416 /* This is the general order of operands */
2418 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2421 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2424 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2426 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2428 stmt.o1.u1 = stmt.o3.u1;
2431 else if ((stmt.opcode >= INSTR_STORE_F &&
2432 stmt.opcode <= INSTR_STORE_FNC) ||
2433 (stmt.opcode >= INSTR_STOREP_F &&
2434 stmt.opcode <= INSTR_STOREP_FNC))
2436 /* 2-operand instructions with A -> B */
2437 stmt.o2.u1 = stmt.o3.u1;
2441 if (code_statements_add(stmt) < 0)
2447 static bool gen_function_code(ir_function *self)
2450 prog_section_statement stmt;
2452 /* Starting from entry point, we generate blocks "as they come"
2453 * for now. Dead blocks will not be translated obviously.
2455 if (!self->blocks_count) {
2456 printf("Function '%s' declared without body.\n", self->name);
2460 block = self->blocks[0];
2461 if (block->generated)
2464 if (!gen_blocks_recursive(self, block)) {
2465 printf("failed to generate blocks for '%s'\n", self->name);
2469 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2470 stmt.opcode = AINSTR_END;
2474 if (code_statements_add(stmt) < 0)
2479 static bool gen_global_function(ir_builder *ir, ir_value *global)
2481 prog_section_function fun;
2485 size_t local_var_end;
2487 if (!global->isconst || (!global->constval.vfunc))
2489 printf("Invalid state of function-global: not constant: %s\n", global->name);
2493 irfun = global->constval.vfunc;
2495 fun.name = global->code.name;
2496 fun.file = code_cachedstring(global->context.file);
2497 fun.profile = 0; /* always 0 */
2498 fun.nargs = irfun->params_count;
2500 for (i = 0;i < 8; ++i) {
2504 fun.argsize[i] = type_sizeof[irfun->params[i]];
2507 fun.firstlocal = code_globals_elements;
2508 fun.locals = irfun->allocated_locals + irfun->locals_count;
2511 for (i = 0; i < irfun->locals_count; ++i) {
2512 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2513 printf("Failed to generate global %s\n", irfun->locals[i]->name);
2517 if (irfun->locals_count) {
2518 ir_value *last = irfun->locals[irfun->locals_count-1];
2519 local_var_end = last->code.globaladdr;
2520 local_var_end += type_sizeof[last->vtype];
2522 for (i = 0; i < irfun->values_count; ++i)
2524 /* generate code.globaladdr for ssa values */
2525 ir_value *v = irfun->values[i];
2526 ir_value_code_setaddr(v, local_var_end + v->code.local);
2528 for (i = 0; i < irfun->locals_count; ++i) {
2529 /* fill the locals with zeros */
2530 code_globals_add(0);
2534 fun.entry = irfun->builtin;
2536 fun.entry = code_statements_elements;
2537 if (!gen_function_code(irfun)) {
2538 printf("Failed to generate code for function %s\n", irfun->name);
2543 return (code_functions_add(fun) >= 0);
2546 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2550 prog_section_def def;
2552 def.type = global->vtype;
2553 def.offset = code_globals_elements;
2554 def.name = global->code.name = code_genstring(global->name);
2556 switch (global->vtype)
2559 if (code_defs_add(def) < 0)
2561 return gen_global_pointer(global);
2563 if (code_defs_add(def) < 0)
2565 return gen_global_field(global);
2570 if (code_defs_add(def) < 0)
2573 if (global->isconst) {
2574 iptr = (int32_t*)&global->constval.vfloat;
2575 ir_value_code_setaddr(global, code_globals_add(*iptr));
2577 ir_value_code_setaddr(global, code_globals_add(0));
2579 return global->code.globaladdr >= 0;
2583 if (code_defs_add(def) < 0)
2585 if (global->isconst)
2586 ir_value_code_setaddr(global, code_globals_add(code_cachedstring(global->constval.vstring)));
2588 ir_value_code_setaddr(global, code_globals_add(0));
2589 return global->code.globaladdr >= 0;
2594 if (code_defs_add(def) < 0)
2597 if (global->isconst) {
2598 iptr = (int32_t*)&global->constval.vvec;
2599 ir_value_code_setaddr(global, code_globals_add(iptr[0]));
2600 if (global->code.globaladdr < 0)
2602 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2604 if (code_globals_add(iptr[d]) < 0)
2608 ir_value_code_setaddr(global, code_globals_add(0));
2609 if (global->code.globaladdr < 0)
2611 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2613 if (code_globals_add(0) < 0)
2617 return global->code.globaladdr >= 0;
2620 if (code_defs_add(def) < 0)
2622 ir_value_code_setaddr(global, code_globals_elements);
2623 code_globals_add(code_functions_elements);
2624 return gen_global_function(self, global);
2626 /* assume biggest type */
2627 ir_value_code_setaddr(global, code_globals_add(0));
2628 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2629 code_globals_add(0);
2632 /* refuse to create 'void' type or any other fancy business. */
2633 printf("Invalid type for global variable %s\n", global->name);
2638 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2640 prog_section_def def;
2641 prog_section_field fld;
2643 def.type = field->vtype;
2644 def.offset = code_globals_elements;
2646 /* create a global named the same as the field */
2647 if (opts_standard == COMPILER_GMQCC) {
2648 /* in our standard, the global gets a dot prefix */
2649 size_t len = strlen(field->name);
2652 /* we really don't want to have to allocate this, and 1024
2653 * bytes is more than enough for a variable/field name
2655 if (len+2 >= sizeof(name)) {
2656 printf("invalid field name size: %u\n", (unsigned int)len);
2661 strcpy(name+1, field->name); /* no strncpy - we used strlen above */
2664 def.name = code_genstring(name);
2665 fld.name = def.name + 1; /* we reuse that string table entry */
2667 /* in plain QC, there cannot be a global with the same name,
2668 * and so we also name the global the same.
2669 * FIXME: fteqcc should create a global as well
2670 * check if it actually uses the same name. Probably does
2672 def.name = code_genstring(field->name);
2673 fld.name = def.name;
2676 field->code.name = def.name;
2678 if (code_defs_add(def) < 0)
2681 fld.type = field->fieldtype;
2683 if (fld.type == TYPE_VOID) {
2684 printf("field is missing a type: %s - don't know its size\n", field->name);
2688 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2690 if (code_fields_add(fld) < 0)
2693 ir_value_code_setaddr(field, code_globals_elements);
2694 if (!code_globals_add(fld.offset))
2696 if (fld.type == TYPE_VECTOR) {
2697 if (!code_globals_add(fld.offset+1))
2699 if (!code_globals_add(fld.offset+2))
2703 return field->code.globaladdr >= 0;
2706 bool ir_builder_generate(ir_builder *self, const char *filename)
2712 for (i = 0; i < self->fields_count; ++i)
2714 if (!ir_builder_gen_field(self, self->fields[i])) {
2719 for (i = 0; i < self->globals_count; ++i)
2721 if (!ir_builder_gen_global(self, self->globals[i])) {
2726 printf("writing '%s'...\n", filename);
2727 return code_write(filename);
2730 /***********************************************************************
2731 *IR DEBUG Dump functions...
2734 #define IND_BUFSZ 1024
2736 const char *qc_opname(int op)
2738 if (op < 0) return "<INVALID>";
2739 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2740 return asm_instr[op].m;
2742 case VINSTR_PHI: return "PHI";
2743 case VINSTR_JUMP: return "JUMP";
2744 case VINSTR_COND: return "COND";
2745 default: return "<UNK>";
2749 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2752 char indent[IND_BUFSZ];
2756 oprintf("module %s\n", b->name);
2757 for (i = 0; i < b->globals_count; ++i)
2760 if (b->globals[i]->isconst)
2761 oprintf("%s = ", b->globals[i]->name);
2762 ir_value_dump(b->globals[i], oprintf);
2765 for (i = 0; i < b->functions_count; ++i)
2766 ir_function_dump(b->functions[i], indent, oprintf);
2767 oprintf("endmodule %s\n", b->name);
2770 void ir_function_dump(ir_function *f, char *ind,
2771 int (*oprintf)(const char*, ...))
2774 if (f->builtin != 0) {
2775 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2778 oprintf("%sfunction %s\n", ind, f->name);
2779 strncat(ind, "\t", IND_BUFSZ);
2780 if (f->locals_count)
2782 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2783 for (i = 0; i < f->locals_count; ++i) {
2784 oprintf("%s\t", ind);
2785 ir_value_dump(f->locals[i], oprintf);
2789 if (f->blocks_count)
2791 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2792 for (i = 0; i < f->blocks_count; ++i) {
2793 if (f->blocks[i]->run_id != f->run_id) {
2794 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2796 ir_block_dump(f->blocks[i], ind, oprintf);
2800 ind[strlen(ind)-1] = 0;
2801 oprintf("%sendfunction %s\n", ind, f->name);
2804 void ir_block_dump(ir_block* b, char *ind,
2805 int (*oprintf)(const char*, ...))
2808 oprintf("%s:%s\n", ind, b->label);
2809 strncat(ind, "\t", IND_BUFSZ);
2811 for (i = 0; i < b->instr_count; ++i)
2812 ir_instr_dump(b->instr[i], ind, oprintf);
2813 ind[strlen(ind)-1] = 0;
2816 void dump_phi(ir_instr *in, char *ind,
2817 int (*oprintf)(const char*, ...))
2820 oprintf("%s <- phi ", in->_ops[0]->name);
2821 for (i = 0; i < in->phi_count; ++i)
2823 oprintf("([%s] : %s) ", in->phi[i].from->label,
2824 in->phi[i].value->name);
2829 void ir_instr_dump(ir_instr *in, char *ind,
2830 int (*oprintf)(const char*, ...))
2833 const char *comma = NULL;
2835 oprintf("%s (%i) ", ind, (int)in->eid);
2837 if (in->opcode == VINSTR_PHI) {
2838 dump_phi(in, ind, oprintf);
2842 strncat(ind, "\t", IND_BUFSZ);
2844 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2845 ir_value_dump(in->_ops[0], oprintf);
2846 if (in->_ops[1] || in->_ops[2])
2849 if (in->opcode == INSTR_CALL0) {
2850 oprintf("CALL%i\t", in->params_count);
2852 oprintf("%s\t", qc_opname(in->opcode));
2854 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2855 ir_value_dump(in->_ops[0], oprintf);
2860 for (i = 1; i != 3; ++i) {
2864 ir_value_dump(in->_ops[i], oprintf);
2872 oprintf("[%s]", in->bops[0]->label);
2876 oprintf("%s[%s]", comma, in->bops[1]->label);
2878 ind[strlen(ind)-1] = 0;
2881 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
2890 oprintf("(function)");
2893 oprintf("%g", v->constval.vfloat);
2896 oprintf("'%g %g %g'",
2899 v->constval.vvec.z);
2902 oprintf("(entity)");
2905 oprintf("\"%s\"", v->constval.vstring);
2909 oprintf("%i", v->constval.vint);
2914 v->constval.vpointer->name);
2918 oprintf("%s", v->name);
2922 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
2925 oprintf("Life of %s:\n", self->name);
2926 for (i = 0; i < self->life_count; ++i)
2928 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);