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 uint16_t type_eq_instr[TYPE_COUNT] = {
95 INSTR_EQ_F, /* should use I when having integer support */
100 INSTR_EQ_E, /* FLD has no comparison */
102 INSTR_EQ_E, /* should use I */
107 INSTR_EQ_V, /* variant, should never be accessed */
110 uint16_t type_ne_instr[TYPE_COUNT] = {
111 INSTR_NE_F, /* should use I when having integer support */
116 INSTR_NE_E, /* FLD has no comparison */
118 INSTR_NE_E, /* should use I */
123 INSTR_NE_V, /* variant, should never be accessed */
126 MEM_VEC_FUNCTIONS(ir_value_vector, ir_value*, v)
128 /***********************************************************************
132 ir_builder* ir_builder_new(const char *modulename)
136 self = (ir_builder*)mem_a(sizeof(*self));
140 MEM_VECTOR_INIT(self, functions);
141 MEM_VECTOR_INIT(self, globals);
142 MEM_VECTOR_INIT(self, fields);
144 if (!ir_builder_set_name(self, modulename)) {
149 /* globals which always exist */
151 /* for now we give it a vector size */
152 ir_builder_create_global(self, "OFS_RETURN", TYPE_VARIANT);
157 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
158 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, fields)
159 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
161 void ir_builder_delete(ir_builder* self)
164 mem_d((void*)self->name);
165 for (i = 0; i != self->functions_count; ++i) {
166 ir_function_delete(self->functions[i]);
168 MEM_VECTOR_CLEAR(self, functions);
169 for (i = 0; i != self->globals_count; ++i) {
170 ir_value_delete(self->globals[i]);
172 MEM_VECTOR_CLEAR(self, fields);
173 for (i = 0; i != self->fields_count; ++i) {
174 ir_value_delete(self->fields[i]);
176 MEM_VECTOR_CLEAR(self, fields);
180 bool ir_builder_set_name(ir_builder *self, const char *name)
183 mem_d((void*)self->name);
184 self->name = util_strdup(name);
188 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
191 for (i = 0; i < self->functions_count; ++i) {
192 if (!strcmp(name, self->functions[i]->name))
193 return self->functions[i];
198 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
200 ir_function *fn = ir_builder_get_function(self, name);
205 fn = ir_function_new(self, outtype);
206 if (!ir_function_set_name(fn, name) ||
207 !ir_builder_functions_add(self, fn) )
209 ir_function_delete(fn);
213 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
215 ir_function_delete(fn);
219 fn->value->isconst = true;
220 fn->value->outtype = outtype;
221 fn->value->constval.vfunc = fn;
222 fn->value->context = fn->context;
227 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
230 for (i = 0; i < self->globals_count; ++i) {
231 if (!strcmp(self->globals[i]->name, name))
232 return self->globals[i];
237 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
241 if (name && name[0] != '#')
243 ve = ir_builder_get_global(self, name);
249 ve = ir_value_var(name, store_global, vtype);
250 if (!ir_builder_globals_add(self, ve)) {
257 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
260 for (i = 0; i < self->fields_count; ++i) {
261 if (!strcmp(self->fields[i]->name, name))
262 return self->fields[i];
268 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
270 ir_value *ve = ir_builder_get_field(self, name);
275 ve = ir_value_var(name, store_global, TYPE_FIELD);
276 ve->fieldtype = vtype;
277 if (!ir_builder_fields_add(self, ve)) {
284 /***********************************************************************
288 bool ir_function_naive_phi(ir_function*);
289 void ir_function_enumerate(ir_function*);
290 bool ir_function_calculate_liferanges(ir_function*);
291 bool ir_function_allocate_locals(ir_function*);
293 ir_function* ir_function_new(ir_builder* owner, int outtype)
296 self = (ir_function*)mem_a(sizeof(*self));
302 if (!ir_function_set_name(self, "<@unnamed>")) {
307 self->context.file = "<@no context>";
308 self->context.line = 0;
309 self->outtype = outtype;
312 MEM_VECTOR_INIT(self, params);
313 MEM_VECTOR_INIT(self, blocks);
314 MEM_VECTOR_INIT(self, values);
315 MEM_VECTOR_INIT(self, locals);
320 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
321 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
322 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
323 MEM_VEC_FUNCTIONS(ir_function, int, params)
325 bool ir_function_set_name(ir_function *self, const char *name)
328 mem_d((void*)self->name);
329 self->name = util_strdup(name);
333 void ir_function_delete(ir_function *self)
336 mem_d((void*)self->name);
338 for (i = 0; i != self->blocks_count; ++i)
339 ir_block_delete(self->blocks[i]);
340 MEM_VECTOR_CLEAR(self, blocks);
342 MEM_VECTOR_CLEAR(self, params);
344 for (i = 0; i != self->values_count; ++i)
345 ir_value_delete(self->values[i]);
346 MEM_VECTOR_CLEAR(self, values);
348 for (i = 0; i != self->locals_count; ++i)
349 ir_value_delete(self->locals[i]);
350 MEM_VECTOR_CLEAR(self, locals);
352 /* self->value is deleted by the builder */
357 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
359 return ir_function_values_add(self, v);
362 ir_block* ir_function_create_block(ir_function *self, const char *label)
364 ir_block* bn = ir_block_new(self, label);
365 memcpy(&bn->context, &self->context, sizeof(self->context));
366 if (!ir_function_blocks_add(self, bn)) {
373 bool ir_function_finalize(ir_function *self)
378 if (!ir_function_naive_phi(self))
381 ir_function_enumerate(self);
383 if (!ir_function_calculate_liferanges(self))
386 if (!ir_function_allocate_locals(self))
391 ir_value* ir_function_get_local(ir_function *self, const char *name)
394 for (i = 0; i < self->locals_count; ++i) {
395 if (!strcmp(self->locals[i]->name, name))
396 return self->locals[i];
401 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
403 ir_value *ve = ir_function_get_local(self, name);
409 self->locals_count &&
410 self->locals[self->locals_count-1]->store != store_param) {
411 printf("cannot add parameters after adding locals\n");
415 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
416 if (!ir_function_locals_add(self, ve)) {
423 /***********************************************************************
427 ir_block* ir_block_new(ir_function* owner, const char *name)
430 self = (ir_block*)mem_a(sizeof(*self));
434 memset(self, 0, sizeof(*self));
437 if (!ir_block_set_label(self, name)) {
442 self->context.file = "<@no context>";
443 self->context.line = 0;
445 MEM_VECTOR_INIT(self, instr);
446 MEM_VECTOR_INIT(self, entries);
447 MEM_VECTOR_INIT(self, exits);
450 self->is_return = false;
452 MEM_VECTOR_INIT(self, living);
454 self->generated = false;
458 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
459 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
460 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
461 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
463 void ir_block_delete(ir_block* self)
467 for (i = 0; i != self->instr_count; ++i)
468 ir_instr_delete(self->instr[i]);
469 MEM_VECTOR_CLEAR(self, instr);
470 MEM_VECTOR_CLEAR(self, entries);
471 MEM_VECTOR_CLEAR(self, exits);
472 MEM_VECTOR_CLEAR(self, living);
476 bool ir_block_set_label(ir_block *self, const char *name)
479 mem_d((void*)self->label);
480 self->label = util_strdup(name);
481 return !!self->label;
484 /***********************************************************************
488 ir_instr* ir_instr_new(ir_block* owner, int op)
491 self = (ir_instr*)mem_a(sizeof(*self));
496 self->context.file = "<@no context>";
497 self->context.line = 0;
499 self->_ops[0] = NULL;
500 self->_ops[1] = NULL;
501 self->_ops[2] = NULL;
502 self->bops[0] = NULL;
503 self->bops[1] = NULL;
504 MEM_VECTOR_INIT(self, phi);
505 MEM_VECTOR_INIT(self, params);
510 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
511 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
513 void ir_instr_delete(ir_instr *self)
516 /* The following calls can only delete from
517 * vectors, we still want to delete this instruction
518 * so ignore the return value. Since with the warn_unused_result attribute
519 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
520 * I have to improvise here and use if(foo());
522 for (i = 0; i < self->phi_count; ++i) {
524 if (ir_value_writes_find(self->phi[i].value, self, &idx))
525 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
526 if (ir_value_reads_find(self->phi[i].value, self, &idx))
527 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
529 MEM_VECTOR_CLEAR(self, phi);
530 for (i = 0; i < self->params_count; ++i) {
532 if (ir_value_writes_find(self->params[i], self, &idx))
533 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
534 if (ir_value_reads_find(self->params[i], self, &idx))
535 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
537 MEM_VECTOR_CLEAR(self, params);
538 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
539 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
540 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
544 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
546 if (self->_ops[op]) {
548 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
550 if (!ir_value_writes_remove(self->_ops[op], idx))
553 else if (ir_value_reads_find(self->_ops[op], self, &idx))
555 if (!ir_value_reads_remove(self->_ops[op], idx))
561 if (!ir_value_writes_add(v, self))
564 if (!ir_value_reads_add(v, self))
572 /***********************************************************************
576 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
578 self->code.globaladdr = gaddr;
579 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
580 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
581 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
584 int32_t ir_value_code_addr(const ir_value *self)
586 if (self->store == store_return)
587 return OFS_RETURN + self->code.addroffset;
588 return self->code.globaladdr + self->code.addroffset;
591 ir_value* ir_value_var(const char *name, int storetype, int vtype)
594 self = (ir_value*)mem_a(sizeof(*self));
596 self->fieldtype = TYPE_VOID;
597 self->outtype = TYPE_VOID;
598 self->store = storetype;
599 MEM_VECTOR_INIT(self, reads);
600 MEM_VECTOR_INIT(self, writes);
601 self->isconst = false;
602 self->context.file = "<@no context>";
603 self->context.line = 0;
605 ir_value_set_name(self, name);
607 memset(&self->constval, 0, sizeof(self->constval));
608 memset(&self->code, 0, sizeof(self->code));
610 self->members[0] = NULL;
611 self->members[1] = NULL;
612 self->members[2] = NULL;
614 MEM_VECTOR_INIT(self, life);
618 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
624 if (self->members[member])
625 return self->members[member];
627 if (self->vtype == TYPE_VECTOR)
629 m = ir_value_var(self->name, self->store, TYPE_FLOAT);
632 m->context = self->context;
634 self->members[member] = m;
635 m->code.addroffset = member;
637 else if (self->vtype == TYPE_FIELD)
639 if (self->fieldtype != TYPE_VECTOR)
641 m = ir_value_var(self->name, self->store, TYPE_FIELD);
644 m->fieldtype = TYPE_FLOAT;
645 m->context = self->context;
647 self->members[member] = m;
648 m->code.addroffset = member;
652 printf("invalid member access on %s\n", self->name);
659 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
660 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
661 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
663 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
665 ir_value *v = ir_value_var(name, storetype, vtype);
668 if (!ir_function_collect_value(owner, v))
676 void ir_value_delete(ir_value* self)
680 mem_d((void*)self->name);
683 if (self->vtype == TYPE_STRING)
684 mem_d((void*)self->constval.vstring);
686 for (i = 0; i < 3; ++i) {
687 if (self->members[i])
688 ir_value_delete(self->members[i]);
690 MEM_VECTOR_CLEAR(self, reads);
691 MEM_VECTOR_CLEAR(self, writes);
692 MEM_VECTOR_CLEAR(self, life);
696 void ir_value_set_name(ir_value *self, const char *name)
699 mem_d((void*)self->name);
700 self->name = util_strdup(name);
703 bool ir_value_set_float(ir_value *self, float f)
705 if (self->vtype != TYPE_FLOAT)
707 self->constval.vfloat = f;
708 self->isconst = true;
712 bool ir_value_set_func(ir_value *self, int f)
714 if (self->vtype != TYPE_FUNCTION)
716 self->constval.vint = f;
717 self->isconst = true;
721 bool ir_value_set_vector(ir_value *self, vector v)
723 if (self->vtype != TYPE_VECTOR)
725 self->constval.vvec = v;
726 self->isconst = true;
730 bool ir_value_set_field(ir_value *self, ir_value *fld)
732 if (self->vtype != TYPE_FIELD)
734 self->constval.vpointer = fld;
735 self->isconst = true;
739 bool ir_value_set_string(ir_value *self, const char *str)
741 if (self->vtype != TYPE_STRING)
743 self->constval.vstring = util_strdup(str);
744 self->isconst = true;
749 bool ir_value_set_int(ir_value *self, int i)
751 if (self->vtype != TYPE_INTEGER)
753 self->constval.vint = i;
754 self->isconst = true;
759 bool ir_value_lives(ir_value *self, size_t at)
762 for (i = 0; i < self->life_count; ++i)
764 ir_life_entry_t *life = &self->life[i];
765 if (life->start <= at && at <= life->end)
767 if (life->start > at) /* since it's ordered */
773 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
776 if (!ir_value_life_add(self, e)) /* naive... */
778 for (k = self->life_count-1; k > idx; --k)
779 self->life[k] = self->life[k-1];
784 bool ir_value_life_merge(ir_value *self, size_t s)
787 ir_life_entry_t *life = NULL;
788 ir_life_entry_t *before = NULL;
789 ir_life_entry_t new_entry;
791 /* Find the first range >= s */
792 for (i = 0; i < self->life_count; ++i)
795 life = &self->life[i];
799 /* nothing found? append */
800 if (i == self->life_count) {
802 if (life && life->end+1 == s)
804 /* previous life range can be merged in */
808 if (life && life->end >= s)
811 if (!ir_value_life_add(self, e))
812 return false; /* failing */
818 if (before->end + 1 == s &&
819 life->start - 1 == s)
822 before->end = life->end;
823 if (!ir_value_life_remove(self, i))
824 return false; /* failing */
827 if (before->end + 1 == s)
833 /* already contained */
834 if (before->end >= s)
838 if (life->start - 1 == s)
843 /* insert a new entry */
844 new_entry.start = new_entry.end = s;
845 return ir_value_life_insert(self, i, new_entry);
848 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
852 if (!other->life_count)
855 if (!self->life_count) {
856 for (i = 0; i < other->life_count; ++i) {
857 if (!ir_value_life_add(self, other->life[i]))
864 for (i = 0; i < other->life_count; ++i)
866 const ir_life_entry_t *life = &other->life[i];
869 ir_life_entry_t *entry = &self->life[myi];
871 if (life->end+1 < entry->start)
873 /* adding an interval before entry */
874 if (!ir_value_life_insert(self, myi, *life))
880 if (life->start < entry->start &&
881 life->end >= entry->start)
883 /* starts earlier and overlaps */
884 entry->start = life->start;
887 if (life->end > entry->end &&
888 life->start-1 <= entry->end)
890 /* ends later and overlaps */
891 entry->end = life->end;
894 /* see if our change combines it with the next ranges */
895 while (myi+1 < self->life_count &&
896 entry->end+1 >= self->life[1+myi].start)
898 /* overlaps with (myi+1) */
899 if (entry->end < self->life[1+myi].end)
900 entry->end = self->life[1+myi].end;
901 if (!ir_value_life_remove(self, myi+1))
903 entry = &self->life[myi];
906 /* see if we're after the entry */
907 if (life->start > entry->end)
910 /* append if we're at the end */
911 if (myi >= self->life_count) {
912 if (!ir_value_life_add(self, *life))
916 /* otherweise check the next range */
925 bool ir_values_overlap(const ir_value *a, const ir_value *b)
927 /* For any life entry in A see if it overlaps with
928 * any life entry in B.
929 * Note that the life entries are orderes, so we can make a
930 * more efficient algorithm there than naively translating the
934 ir_life_entry_t *la, *lb, *enda, *endb;
936 /* first of all, if either has no life range, they cannot clash */
937 if (!a->life_count || !b->life_count)
942 enda = la + a->life_count;
943 endb = lb + b->life_count;
946 /* check if the entries overlap, for that,
947 * both must start before the other one ends.
949 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
950 if (la->start <= lb->end &&
951 lb->start <= la->end)
953 if (la->start < lb->end &&
960 /* entries are ordered
961 * one entry is earlier than the other
962 * that earlier entry will be moved forward
964 if (la->start < lb->start)
966 /* order: A B, move A forward
967 * check if we hit the end with A
972 else if (lb->start < la->start)
974 /* order: B A, move B forward
975 * check if we hit the end with B
984 /***********************************************************************
988 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
990 ir_instr *in = ir_instr_new(self, op);
994 if (target->store == store_value &&
995 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
997 fprintf(stderr, "cannot store to an SSA value\n");
998 fprintf(stderr, "trying to store: %s <- %s\n", target->name, what->name);
999 fprintf(stderr, "instruction: %s\n", asm_instr[op].m);
1003 if (!ir_instr_op(in, 0, target, true) ||
1004 !ir_instr_op(in, 1, what, false) ||
1005 !ir_block_instr_add(self, in) )
1012 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
1016 if (target->vtype == TYPE_VARIANT)
1017 vtype = what->vtype;
1019 vtype = target->vtype;
1022 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1023 op = INSTR_CONV_ITOF;
1024 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1025 op = INSTR_CONV_FTOI;
1027 op = type_store_instr[vtype];
1029 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1030 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1034 return ir_block_create_store_op(self, op, target, what);
1037 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
1042 if (target->vtype != TYPE_POINTER)
1045 /* storing using pointer - target is a pointer, type must be
1046 * inferred from source
1048 vtype = what->vtype;
1050 op = type_storep_instr[vtype];
1051 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1052 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1053 op = INSTR_STOREP_V;
1056 return ir_block_create_store_op(self, op, target, what);
1059 bool ir_block_create_return(ir_block *self, ir_value *v)
1063 fprintf(stderr, "block already ended (%s)\n", self->label);
1067 self->is_return = true;
1068 in = ir_instr_new(self, INSTR_RETURN);
1072 if (!ir_instr_op(in, 0, v, false) ||
1073 !ir_block_instr_add(self, in) )
1080 bool ir_block_create_if(ir_block *self, ir_value *v,
1081 ir_block *ontrue, ir_block *onfalse)
1085 fprintf(stderr, "block already ended (%s)\n", self->label);
1089 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1090 in = ir_instr_new(self, VINSTR_COND);
1094 if (!ir_instr_op(in, 0, v, false)) {
1095 ir_instr_delete(in);
1099 in->bops[0] = ontrue;
1100 in->bops[1] = onfalse;
1102 if (!ir_block_instr_add(self, in))
1105 if (!ir_block_exits_add(self, ontrue) ||
1106 !ir_block_exits_add(self, onfalse) ||
1107 !ir_block_entries_add(ontrue, self) ||
1108 !ir_block_entries_add(onfalse, self) )
1115 bool ir_block_create_jump(ir_block *self, ir_block *to)
1119 fprintf(stderr, "block already ended (%s)\n", self->label);
1123 in = ir_instr_new(self, VINSTR_JUMP);
1128 if (!ir_block_instr_add(self, in))
1131 if (!ir_block_exits_add(self, to) ||
1132 !ir_block_entries_add(to, self) )
1139 bool ir_block_create_goto(ir_block *self, ir_block *to)
1143 fprintf(stderr, "block already ended (%s)\n", self->label);
1147 in = ir_instr_new(self, INSTR_GOTO);
1152 if (!ir_block_instr_add(self, in))
1155 if (!ir_block_exits_add(self, to) ||
1156 !ir_block_entries_add(to, self) )
1163 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1167 in = ir_instr_new(self, VINSTR_PHI);
1170 out = ir_value_out(self->owner, label, store_value, ot);
1172 ir_instr_delete(in);
1175 if (!ir_instr_op(in, 0, out, true)) {
1176 ir_instr_delete(in);
1177 ir_value_delete(out);
1180 if (!ir_block_instr_add(self, in)) {
1181 ir_instr_delete(in);
1182 ir_value_delete(out);
1188 ir_value* ir_phi_value(ir_instr *self)
1190 return self->_ops[0];
1193 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1197 if (!ir_block_entries_find(self->owner, b, NULL)) {
1198 /* Must not be possible to cause this, otherwise the AST
1199 * is doing something wrong.
1201 fprintf(stderr, "Invalid entry block for PHI\n");
1207 if (!ir_value_reads_add(v, self))
1209 return ir_instr_phi_add(self, pe);
1212 /* call related code */
1213 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1217 in = ir_instr_new(self, INSTR_CALL0);
1220 out = ir_value_out(self->owner, label, store_return, func->outtype);
1222 ir_instr_delete(in);
1225 if (!ir_instr_op(in, 0, out, true) ||
1226 !ir_instr_op(in, 1, func, false) ||
1227 !ir_block_instr_add(self, in))
1229 ir_instr_delete(in);
1230 ir_value_delete(out);
1236 ir_value* ir_call_value(ir_instr *self)
1238 return self->_ops[0];
1241 bool ir_call_param(ir_instr* self, ir_value *v)
1243 if (!ir_instr_params_add(self, v))
1245 if (!ir_value_reads_add(v, self)) {
1246 if (!ir_instr_params_remove(self, self->params_count-1))
1247 GMQCC_SUPPRESS_EMPTY_BODY;
1253 /* binary op related code */
1255 ir_value* ir_block_create_binop(ir_block *self,
1256 const char *label, int opcode,
1257 ir_value *left, ir_value *right)
1279 case INSTR_SUB_S: /* -- offset of string as float */
1284 case INSTR_BITOR_IF:
1285 case INSTR_BITOR_FI:
1286 case INSTR_BITAND_FI:
1287 case INSTR_BITAND_IF:
1302 case INSTR_BITAND_I:
1305 case INSTR_RSHIFT_I:
1306 case INSTR_LSHIFT_I:
1328 /* boolean operations result in floats */
1329 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1331 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1334 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1339 if (ot == TYPE_VOID) {
1340 /* The AST or parser were supposed to check this! */
1344 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1347 ir_value* ir_block_create_unary(ir_block *self,
1348 const char *label, int opcode,
1351 int ot = TYPE_FLOAT;
1363 /* QC doesn't have other unary operations. We expect extensions to fill
1364 * the above list, otherwise we assume out-type = in-type, eg for an
1368 ot = operand->vtype;
1371 if (ot == TYPE_VOID) {
1372 /* The AST or parser were supposed to check this! */
1376 /* let's use the general instruction creator and pass NULL for OPB */
1377 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1380 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1381 int op, ir_value *a, ir_value *b, int outype)
1386 out = ir_value_out(self->owner, label, store_value, outype);
1390 instr = ir_instr_new(self, op);
1392 ir_value_delete(out);
1396 if (!ir_instr_op(instr, 0, out, true) ||
1397 !ir_instr_op(instr, 1, a, false) ||
1398 !ir_instr_op(instr, 2, b, false) )
1403 if (!ir_block_instr_add(self, instr))
1408 ir_instr_delete(instr);
1409 ir_value_delete(out);
1413 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1417 /* Support for various pointer types todo if so desired */
1418 if (ent->vtype != TYPE_ENTITY)
1421 if (field->vtype != TYPE_FIELD)
1424 v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1425 v->fieldtype = field->fieldtype;
1429 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1432 if (ent->vtype != TYPE_ENTITY)
1435 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1436 if (field->vtype != TYPE_FIELD)
1441 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1442 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1443 case TYPE_STRING: op = INSTR_LOAD_S; break;
1444 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1445 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1447 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1448 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1454 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1457 ir_value* ir_block_create_add(ir_block *self,
1459 ir_value *left, ir_value *right)
1462 int l = left->vtype;
1463 int r = right->vtype;
1482 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1484 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1490 return ir_block_create_binop(self, label, op, left, right);
1493 ir_value* ir_block_create_sub(ir_block *self,
1495 ir_value *left, ir_value *right)
1498 int l = left->vtype;
1499 int r = right->vtype;
1519 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1521 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1527 return ir_block_create_binop(self, label, op, left, right);
1530 ir_value* ir_block_create_mul(ir_block *self,
1532 ir_value *left, ir_value *right)
1535 int l = left->vtype;
1536 int r = right->vtype;
1555 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1557 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1560 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1562 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1564 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1566 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1572 return ir_block_create_binop(self, label, op, left, right);
1575 ir_value* ir_block_create_div(ir_block *self,
1577 ir_value *left, ir_value *right)
1580 int l = left->vtype;
1581 int r = right->vtype;
1598 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1600 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1602 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1608 return ir_block_create_binop(self, label, op, left, right);
1611 /* PHI resolving breaks the SSA, and must thus be the last
1612 * step before life-range calculation.
1615 static bool ir_block_naive_phi(ir_block *self);
1616 bool ir_function_naive_phi(ir_function *self)
1620 for (i = 0; i < self->blocks_count; ++i)
1622 if (!ir_block_naive_phi(self->blocks[i]))
1628 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1633 /* create a store */
1634 if (!ir_block_create_store(block, old, what))
1637 /* we now move it up */
1638 instr = block->instr[block->instr_count-1];
1639 for (i = block->instr_count; i > iid; --i)
1640 block->instr[i] = block->instr[i-1];
1641 block->instr[i] = instr;
1646 static bool ir_block_naive_phi(ir_block *self)
1649 /* FIXME: optionally, create_phi can add the phis
1650 * to a list so we don't need to loop through blocks
1651 * - anyway: "don't optimize YET"
1653 for (i = 0; i < self->instr_count; ++i)
1655 ir_instr *instr = self->instr[i];
1656 if (instr->opcode != VINSTR_PHI)
1659 if (!ir_block_instr_remove(self, i))
1661 --i; /* NOTE: i+1 below */
1663 for (p = 0; p < instr->phi_count; ++p)
1665 ir_value *v = instr->phi[p].value;
1666 for (w = 0; w < v->writes_count; ++w) {
1669 if (!v->writes[w]->_ops[0])
1672 /* When the write was to a global, we have to emit a mov */
1673 old = v->writes[w]->_ops[0];
1675 /* The original instruction now writes to the PHI target local */
1676 if (v->writes[w]->_ops[0] == v)
1677 v->writes[w]->_ops[0] = instr->_ops[0];
1679 if (old->store != store_value && old->store != store_local && old->store != store_param)
1681 /* If it originally wrote to a global we need to store the value
1684 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1686 if (i+1 < self->instr_count)
1687 instr = self->instr[i+1];
1690 /* In case I forget and access instr later, it'll be NULL
1691 * when it's a problem, to make sure we crash, rather than accessing
1697 /* If it didn't, we can replace all reads by the phi target now. */
1699 for (r = 0; r < old->reads_count; ++r)
1702 ir_instr *ri = old->reads[r];
1703 for (op = 0; op < ri->phi_count; ++op) {
1704 if (ri->phi[op].value == old)
1705 ri->phi[op].value = v;
1707 for (op = 0; op < 3; ++op) {
1708 if (ri->_ops[op] == old)
1715 ir_instr_delete(instr);
1720 /***********************************************************************
1721 *IR Temp allocation code
1722 * Propagating value life ranges by walking through the function backwards
1723 * until no more changes are made.
1724 * In theory this should happen once more than once for every nested loop
1726 * Though this implementation might run an additional time for if nests.
1735 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1737 /* Enumerate instructions used by value's life-ranges
1739 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1743 for (i = 0; i < self->instr_count; ++i)
1745 self->instr[i]->eid = eid++;
1750 /* Enumerate blocks and instructions.
1751 * The block-enumeration is unordered!
1752 * We do not really use the block enumreation, however
1753 * the instruction enumeration is important for life-ranges.
1755 void ir_function_enumerate(ir_function *self)
1758 size_t instruction_id = 0;
1759 for (i = 0; i < self->blocks_count; ++i)
1761 self->blocks[i]->eid = i;
1762 self->blocks[i]->run_id = 0;
1763 ir_block_enumerate(self->blocks[i], &instruction_id);
1767 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1768 bool ir_function_calculate_liferanges(ir_function *self)
1776 for (i = 0; i != self->blocks_count; ++i)
1778 if (self->blocks[i]->is_return)
1780 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1788 /* Local-value allocator
1789 * After finishing creating the liferange of all values used in a function
1790 * we can allocate their global-positions.
1791 * This is the counterpart to register-allocation in register machines.
1794 MEM_VECTOR_MAKE(ir_value*, locals);
1795 MEM_VECTOR_MAKE(size_t, sizes);
1796 MEM_VECTOR_MAKE(size_t, positions);
1797 } function_allocator;
1798 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1799 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1800 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1802 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1805 size_t vsize = type_sizeof[var->vtype];
1807 slot = ir_value_var("reg", store_global, var->vtype);
1811 if (!ir_value_life_merge_into(slot, var))
1814 if (!function_allocator_locals_add(alloc, slot))
1817 if (!function_allocator_sizes_add(alloc, vsize))
1823 ir_value_delete(slot);
1827 bool ir_function_allocate_locals(ir_function *self)
1836 function_allocator alloc;
1838 if (!self->locals_count)
1841 MEM_VECTOR_INIT(&alloc, locals);
1842 MEM_VECTOR_INIT(&alloc, sizes);
1843 MEM_VECTOR_INIT(&alloc, positions);
1845 for (i = 0; i < self->locals_count; ++i)
1847 if (!function_allocator_alloc(&alloc, self->locals[i]))
1851 /* Allocate a slot for any value that still exists */
1852 for (i = 0; i < self->values_count; ++i)
1854 v = self->values[i];
1859 for (a = 0; a < alloc.locals_count; ++a)
1861 slot = alloc.locals[a];
1863 if (ir_values_overlap(v, slot))
1866 if (!ir_value_life_merge_into(slot, v))
1869 /* adjust size for this slot */
1870 if (alloc.sizes[a] < type_sizeof[v->vtype])
1871 alloc.sizes[a] = type_sizeof[v->vtype];
1873 self->values[i]->code.local = a;
1876 if (a >= alloc.locals_count) {
1877 self->values[i]->code.local = alloc.locals_count;
1878 if (!function_allocator_alloc(&alloc, v))
1883 /* Adjust slot positions based on sizes */
1884 if (!function_allocator_positions_add(&alloc, 0))
1887 if (alloc.sizes_count)
1888 pos = alloc.positions[0] + alloc.sizes[0];
1891 for (i = 1; i < alloc.sizes_count; ++i)
1893 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1894 if (!function_allocator_positions_add(&alloc, pos))
1898 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1900 /* Take over the actual slot positions */
1901 for (i = 0; i < self->values_count; ++i)
1902 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1909 for (i = 0; i < alloc.locals_count; ++i)
1910 ir_value_delete(alloc.locals[i]);
1911 MEM_VECTOR_CLEAR(&alloc, locals);
1912 MEM_VECTOR_CLEAR(&alloc, sizes);
1913 MEM_VECTOR_CLEAR(&alloc, positions);
1917 /* Get information about which operand
1918 * is read from, or written to.
1920 static void ir_op_read_write(int op, size_t *read, size_t *write)
1947 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1950 bool changed = false;
1952 for (i = 0; i != self->living_count; ++i)
1954 tempbool = ir_value_life_merge(self->living[i], eid);
1957 fprintf(stderr, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1959 changed = changed || tempbool;
1964 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1967 /* values which have been read in a previous iteration are now
1968 * in the "living" array even if the previous block doesn't use them.
1969 * So we have to remove whatever does not exist in the previous block.
1970 * They will be re-added on-read, but the liferange merge won't cause
1973 for (i = 0; i < self->living_count; ++i)
1975 if (!ir_block_living_find(prev, self->living[i], NULL)) {
1976 if (!ir_block_living_remove(self, i))
1982 /* Whatever the previous block still has in its living set
1983 * must now be added to ours as well.
1985 for (i = 0; i < prev->living_count; ++i)
1987 if (ir_block_living_find(self, prev->living[i], NULL))
1989 if (!ir_block_living_add(self, prev->living[i]))
1992 printf("%s got from prev: %s\n", self->label, prev->living[i]->_name);
1998 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2004 /* bitmasks which operands are read from or written to */
2006 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2008 new_reads_t new_reads;
2010 char dbg_ind[16] = { '#', '0' };
2013 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2014 MEM_VECTOR_INIT(&new_reads, v);
2019 if (!ir_block_life_prop_previous(self, prev, changed))
2023 i = self->instr_count;
2026 instr = self->instr[i];
2028 /* PHI operands are always read operands */
2029 for (p = 0; p < instr->phi_count; ++p)
2031 value = instr->phi[p].value;
2032 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2033 if (!ir_block_living_find(self, value, NULL) &&
2034 !ir_block_living_add(self, value))
2039 if (!new_reads_t_v_find(&new_reads, value, NULL))
2041 if (!new_reads_t_v_add(&new_reads, value))
2047 /* See which operands are read and write operands */
2048 ir_op_read_write(instr->opcode, &read, &write);
2050 /* Go through the 3 main operands */
2051 for (o = 0; o < 3; ++o)
2053 if (!instr->_ops[o]) /* no such operand */
2056 value = instr->_ops[o];
2058 /* We only care about locals */
2059 /* we also calculate parameter liferanges so that locals
2060 * can take up parameter slots */
2061 if (value->store != store_value &&
2062 value->store != store_local &&
2063 value->store != store_param)
2069 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2070 if (!ir_block_living_find(self, value, NULL) &&
2071 !ir_block_living_add(self, value))
2076 /* fprintf(stderr, "read: %s\n", value->_name); */
2077 if (!new_reads_t_v_find(&new_reads, value, NULL))
2079 if (!new_reads_t_v_add(&new_reads, value))
2085 /* write operands */
2086 /* When we write to a local, we consider it "dead" for the
2087 * remaining upper part of the function, since in SSA a value
2088 * can only be written once (== created)
2093 bool in_living = ir_block_living_find(self, value, &idx);
2094 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2096 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
2097 if (!in_living && !in_reads)
2102 /* If the value isn't alive it hasn't been read before... */
2103 /* TODO: See if the warning can be emitted during parsing or AST processing
2104 * otherwise have warning printed here.
2105 * IF printing a warning here: include filecontext_t,
2106 * and make sure it's only printed once
2107 * since this function is run multiple times.
2109 /* For now: debug info: */
2110 fprintf(stderr, "Value only written %s\n", value->name);
2111 tempbool = ir_value_life_merge(value, instr->eid);
2112 *changed = *changed || tempbool;
2114 ir_instr_dump(instr, dbg_ind, printf);
2118 /* since 'living' won't contain it
2119 * anymore, merge the value, since
2122 tempbool = ir_value_life_merge(value, instr->eid);
2125 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2127 *changed = *changed || tempbool;
2129 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2130 if (!ir_block_living_remove(self, idx))
2135 if (!new_reads_t_v_remove(&new_reads, readidx))
2143 tempbool = ir_block_living_add_instr(self, instr->eid);
2144 /*fprintf(stderr, "living added values\n");*/
2145 *changed = *changed || tempbool;
2147 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2149 for (rd = 0; rd < new_reads.v_count; ++rd)
2151 if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
2152 if (!ir_block_living_add(self, new_reads.v[rd]))
2155 if (!i && !self->entries_count) {
2157 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
2160 MEM_VECTOR_CLEAR(&new_reads, v);
2164 if (self->run_id == self->owner->run_id)
2167 self->run_id = self->owner->run_id;
2169 for (i = 0; i < self->entries_count; ++i)
2171 ir_block *entry = self->entries[i];
2172 ir_block_life_propagate(entry, self, changed);
2177 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2178 MEM_VECTOR_CLEAR(&new_reads, v);
2183 /***********************************************************************
2186 * Since the IR has the convention of putting 'write' operands
2187 * at the beginning, we have to rotate the operands of instructions
2188 * properly in order to generate valid QCVM code.
2190 * Having destinations at a fixed position is more convenient. In QC
2191 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2192 * read from from OPA, and store to OPB rather than OPC. Which is
2193 * partially the reason why the implementation of these instructions
2194 * in darkplaces has been delayed for so long.
2196 * Breaking conventions is annoying...
2198 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2200 static bool gen_global_field(ir_value *global)
2202 if (global->isconst)
2204 ir_value *fld = global->constval.vpointer;
2206 printf("Invalid field constant with no field: %s\n", global->name);
2210 /* Now, in this case, a relocation would be impossible to code
2211 * since it looks like this:
2212 * .vector v = origin; <- parse error, wtf is 'origin'?
2215 * But we will need a general relocation support later anyway
2216 * for functions... might as well support that here.
2218 if (!fld->code.globaladdr) {
2219 printf("FIXME: Relocation support\n");
2223 /* copy the field's value */
2224 ir_value_code_setaddr(global, code_globals_add(code_globals_data[fld->code.globaladdr]));
2225 if (global->fieldtype == TYPE_VECTOR) {
2226 code_globals_add(code_globals_data[fld->code.globaladdr]+1);
2227 code_globals_add(code_globals_data[fld->code.globaladdr]+2);
2232 ir_value_code_setaddr(global, code_globals_add(0));
2233 if (global->fieldtype == TYPE_VECTOR) {
2234 code_globals_add(0);
2235 code_globals_add(0);
2238 if (global->code.globaladdr < 0)
2243 static bool gen_global_pointer(ir_value *global)
2245 if (global->isconst)
2247 ir_value *target = global->constval.vpointer;
2249 printf("Invalid pointer constant: %s\n", global->name);
2250 /* NULL pointers are pointing to the NULL constant, which also
2251 * sits at address 0, but still has an ir_value for itself.
2256 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2257 * void() foo; <- proto
2258 * void() *fooptr = &foo;
2259 * void() foo = { code }
2261 if (!target->code.globaladdr) {
2262 /* FIXME: Check for the constant nullptr ir_value!
2263 * because then code.globaladdr being 0 is valid.
2265 printf("FIXME: Relocation support\n");
2269 ir_value_code_setaddr(global, code_globals_add(target->code.globaladdr));
2273 ir_value_code_setaddr(global, code_globals_add(0));
2275 if (global->code.globaladdr < 0)
2280 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2282 prog_section_statement stmt;
2291 block->generated = true;
2292 block->code_start = code_statements_elements;
2293 for (i = 0; i < block->instr_count; ++i)
2295 instr = block->instr[i];
2297 if (instr->opcode == VINSTR_PHI) {
2298 printf("cannot generate virtual instruction (phi)\n");
2302 if (instr->opcode == VINSTR_JUMP) {
2303 target = instr->bops[0];
2304 /* for uncoditional jumps, if the target hasn't been generated
2305 * yet, we generate them right here.
2307 if (!target->generated) {
2312 /* otherwise we generate a jump instruction */
2313 stmt.opcode = INSTR_GOTO;
2314 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2317 if (code_statements_add(stmt) < 0)
2320 /* no further instructions can be in this block */
2324 if (instr->opcode == VINSTR_COND) {
2325 ontrue = instr->bops[0];
2326 onfalse = instr->bops[1];
2327 /* TODO: have the AST signal which block should
2328 * come first: eg. optimize IFs without ELSE...
2331 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2335 if (ontrue->generated) {
2336 stmt.opcode = INSTR_IF;
2337 stmt.o2.s1 = (ontrue->code_start-1) - code_statements_elements;
2338 if (code_statements_add(stmt) < 0)
2341 if (onfalse->generated) {
2342 stmt.opcode = INSTR_IFNOT;
2343 stmt.o2.s1 = (onfalse->code_start-1) - code_statements_elements;
2344 if (code_statements_add(stmt) < 0)
2347 if (!ontrue->generated) {
2348 if (onfalse->generated) {
2353 if (!onfalse->generated) {
2354 if (ontrue->generated) {
2359 /* neither ontrue nor onfalse exist */
2360 stmt.opcode = INSTR_IFNOT;
2361 stidx = code_statements_elements;
2362 if (code_statements_add(stmt) < 0)
2364 /* on false we jump, so add ontrue-path */
2365 if (!gen_blocks_recursive(func, ontrue))
2367 /* fixup the jump address */
2368 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2369 /* generate onfalse path */
2370 if (onfalse->generated) {
2371 /* fixup the jump address */
2372 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2373 /* may have been generated in the previous recursive call */
2374 stmt.opcode = INSTR_GOTO;
2375 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2378 return (code_statements_add(stmt) >= 0);
2380 /* if not, generate now */
2385 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2386 /* Trivial call translation:
2387 * copy all params to OFS_PARM*
2388 * if the output's storetype is not store_return,
2389 * add append a STORE instruction!
2391 * NOTES on how to do it better without much trouble:
2392 * -) The liferanges!
2393 * Simply check the liferange of all parameters for
2394 * other CALLs. For each param with no CALL in its
2395 * liferange, we can store it in an OFS_PARM at
2396 * generation already. This would even include later
2397 * reuse.... probably... :)
2402 for (p = 0; p < instr->params_count; ++p)
2404 ir_value *param = instr->params[p];
2406 stmt.opcode = INSTR_STORE_F;
2409 stmt.opcode = type_store_instr[param->vtype];
2410 stmt.o1.u1 = ir_value_code_addr(param);
2411 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2412 if (code_statements_add(stmt) < 0)
2415 stmt.opcode = INSTR_CALL0 + instr->params_count;
2416 if (stmt.opcode > INSTR_CALL8)
2417 stmt.opcode = INSTR_CALL8;
2418 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2421 if (code_statements_add(stmt) < 0)
2424 retvalue = instr->_ops[0];
2425 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2427 /* not to be kept in OFS_RETURN */
2428 stmt.opcode = type_store_instr[retvalue->vtype];
2429 stmt.o1.u1 = OFS_RETURN;
2430 stmt.o2.u1 = ir_value_code_addr(retvalue);
2432 if (code_statements_add(stmt) < 0)
2438 if (instr->opcode == INSTR_STATE) {
2439 printf("TODO: state instruction\n");
2443 stmt.opcode = instr->opcode;
2448 /* This is the general order of operands */
2450 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2453 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2456 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2458 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2460 stmt.o1.u1 = stmt.o3.u1;
2463 else if ((stmt.opcode >= INSTR_STORE_F &&
2464 stmt.opcode <= INSTR_STORE_FNC) ||
2465 (stmt.opcode >= INSTR_STOREP_F &&
2466 stmt.opcode <= INSTR_STOREP_FNC))
2468 /* 2-operand instructions with A -> B */
2469 stmt.o2.u1 = stmt.o3.u1;
2473 if (code_statements_add(stmt) < 0)
2479 static bool gen_function_code(ir_function *self)
2482 prog_section_statement stmt;
2484 /* Starting from entry point, we generate blocks "as they come"
2485 * for now. Dead blocks will not be translated obviously.
2487 if (!self->blocks_count) {
2488 printf("Function '%s' declared without body.\n", self->name);
2492 block = self->blocks[0];
2493 if (block->generated)
2496 if (!gen_blocks_recursive(self, block)) {
2497 printf("failed to generate blocks for '%s'\n", self->name);
2501 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2502 stmt.opcode = AINSTR_END;
2506 if (code_statements_add(stmt) < 0)
2511 static bool gen_global_function(ir_builder *ir, ir_value *global)
2513 prog_section_function fun;
2517 size_t local_var_end;
2519 if (!global->isconst || (!global->constval.vfunc))
2521 printf("Invalid state of function-global: not constant: %s\n", global->name);
2525 irfun = global->constval.vfunc;
2527 fun.name = global->code.name;
2528 fun.file = code_cachedstring(global->context.file);
2529 fun.profile = 0; /* always 0 */
2530 fun.nargs = irfun->params_count;
2532 for (i = 0;i < 8; ++i) {
2536 fun.argsize[i] = type_sizeof[irfun->params[i]];
2539 fun.firstlocal = code_globals_elements;
2540 fun.locals = irfun->allocated_locals + irfun->locals_count;
2543 for (i = 0; i < irfun->locals_count; ++i) {
2544 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2545 printf("Failed to generate global %s\n", irfun->locals[i]->name);
2549 if (irfun->locals_count) {
2550 ir_value *last = irfun->locals[irfun->locals_count-1];
2551 local_var_end = last->code.globaladdr;
2552 local_var_end += type_sizeof[last->vtype];
2554 for (i = 0; i < irfun->values_count; ++i)
2556 /* generate code.globaladdr for ssa values */
2557 ir_value *v = irfun->values[i];
2558 ir_value_code_setaddr(v, local_var_end + v->code.local);
2560 for (i = 0; i < irfun->locals_count; ++i) {
2561 /* fill the locals with zeros */
2562 code_globals_add(0);
2566 fun.entry = irfun->builtin;
2568 fun.entry = code_statements_elements;
2569 if (!gen_function_code(irfun)) {
2570 printf("Failed to generate code for function %s\n", irfun->name);
2575 return (code_functions_add(fun) >= 0);
2578 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2582 prog_section_def def;
2584 def.type = global->vtype;
2585 def.offset = code_globals_elements;
2586 def.name = global->code.name = code_genstring(global->name);
2588 switch (global->vtype)
2591 if (code_defs_add(def) < 0)
2593 return gen_global_pointer(global);
2595 if (code_defs_add(def) < 0)
2597 return gen_global_field(global);
2602 if (code_defs_add(def) < 0)
2605 if (global->isconst) {
2606 iptr = (int32_t*)&global->constval.vfloat;
2607 ir_value_code_setaddr(global, code_globals_add(*iptr));
2609 ir_value_code_setaddr(global, code_globals_add(0));
2611 return global->code.globaladdr >= 0;
2615 if (code_defs_add(def) < 0)
2617 if (global->isconst)
2618 ir_value_code_setaddr(global, code_globals_add(code_cachedstring(global->constval.vstring)));
2620 ir_value_code_setaddr(global, code_globals_add(0));
2621 return global->code.globaladdr >= 0;
2626 if (code_defs_add(def) < 0)
2629 if (global->isconst) {
2630 iptr = (int32_t*)&global->constval.vvec;
2631 ir_value_code_setaddr(global, code_globals_add(iptr[0]));
2632 if (global->code.globaladdr < 0)
2634 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2636 if (code_globals_add(iptr[d]) < 0)
2640 ir_value_code_setaddr(global, code_globals_add(0));
2641 if (global->code.globaladdr < 0)
2643 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2645 if (code_globals_add(0) < 0)
2649 return global->code.globaladdr >= 0;
2652 if (code_defs_add(def) < 0)
2654 ir_value_code_setaddr(global, code_globals_elements);
2655 code_globals_add(code_functions_elements);
2656 return gen_global_function(self, global);
2658 /* assume biggest type */
2659 ir_value_code_setaddr(global, code_globals_add(0));
2660 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2661 code_globals_add(0);
2664 /* refuse to create 'void' type or any other fancy business. */
2665 printf("Invalid type for global variable %s\n", global->name);
2670 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2672 prog_section_def def;
2673 prog_section_field fld;
2675 def.type = field->vtype;
2676 def.offset = code_globals_elements;
2678 /* create a global named the same as the field */
2679 if (opts_standard == COMPILER_GMQCC) {
2680 /* in our standard, the global gets a dot prefix */
2681 size_t len = strlen(field->name);
2684 /* we really don't want to have to allocate this, and 1024
2685 * bytes is more than enough for a variable/field name
2687 if (len+2 >= sizeof(name)) {
2688 printf("invalid field name size: %u\n", (unsigned int)len);
2693 strcpy(name+1, field->name); /* no strncpy - we used strlen above */
2696 def.name = code_genstring(name);
2697 fld.name = def.name + 1; /* we reuse that string table entry */
2699 /* in plain QC, there cannot be a global with the same name,
2700 * and so we also name the global the same.
2701 * FIXME: fteqcc should create a global as well
2702 * check if it actually uses the same name. Probably does
2704 def.name = code_genstring(field->name);
2705 fld.name = def.name;
2708 field->code.name = def.name;
2710 if (code_defs_add(def) < 0)
2713 fld.type = field->fieldtype;
2715 if (fld.type == TYPE_VOID) {
2716 printf("field is missing a type: %s - don't know its size\n", field->name);
2720 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2722 if (code_fields_add(fld) < 0)
2725 ir_value_code_setaddr(field, code_globals_elements);
2726 if (!code_globals_add(fld.offset))
2728 if (fld.type == TYPE_VECTOR) {
2729 if (!code_globals_add(fld.offset+1))
2731 if (!code_globals_add(fld.offset+2))
2735 return field->code.globaladdr >= 0;
2738 bool ir_builder_generate(ir_builder *self, const char *filename)
2744 for (i = 0; i < self->fields_count; ++i)
2746 if (!ir_builder_gen_field(self, self->fields[i])) {
2751 for (i = 0; i < self->globals_count; ++i)
2753 if (!ir_builder_gen_global(self, self->globals[i])) {
2758 printf("writing '%s'...\n", filename);
2759 return code_write(filename);
2762 /***********************************************************************
2763 *IR DEBUG Dump functions...
2766 #define IND_BUFSZ 1024
2768 const char *qc_opname(int op)
2770 if (op < 0) return "<INVALID>";
2771 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2772 return asm_instr[op].m;
2774 case VINSTR_PHI: return "PHI";
2775 case VINSTR_JUMP: return "JUMP";
2776 case VINSTR_COND: return "COND";
2777 default: return "<UNK>";
2781 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2784 char indent[IND_BUFSZ];
2788 oprintf("module %s\n", b->name);
2789 for (i = 0; i < b->globals_count; ++i)
2792 if (b->globals[i]->isconst)
2793 oprintf("%s = ", b->globals[i]->name);
2794 ir_value_dump(b->globals[i], oprintf);
2797 for (i = 0; i < b->functions_count; ++i)
2798 ir_function_dump(b->functions[i], indent, oprintf);
2799 oprintf("endmodule %s\n", b->name);
2802 void ir_function_dump(ir_function *f, char *ind,
2803 int (*oprintf)(const char*, ...))
2806 if (f->builtin != 0) {
2807 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2810 oprintf("%sfunction %s\n", ind, f->name);
2811 strncat(ind, "\t", IND_BUFSZ);
2812 if (f->locals_count)
2814 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2815 for (i = 0; i < f->locals_count; ++i) {
2816 oprintf("%s\t", ind);
2817 ir_value_dump(f->locals[i], oprintf);
2821 if (f->blocks_count)
2823 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2824 for (i = 0; i < f->blocks_count; ++i) {
2825 if (f->blocks[i]->run_id != f->run_id) {
2826 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2828 ir_block_dump(f->blocks[i], ind, oprintf);
2832 ind[strlen(ind)-1] = 0;
2833 oprintf("%sendfunction %s\n", ind, f->name);
2836 void ir_block_dump(ir_block* b, char *ind,
2837 int (*oprintf)(const char*, ...))
2840 oprintf("%s:%s\n", ind, b->label);
2841 strncat(ind, "\t", IND_BUFSZ);
2843 for (i = 0; i < b->instr_count; ++i)
2844 ir_instr_dump(b->instr[i], ind, oprintf);
2845 ind[strlen(ind)-1] = 0;
2848 void dump_phi(ir_instr *in, char *ind,
2849 int (*oprintf)(const char*, ...))
2852 oprintf("%s <- phi ", in->_ops[0]->name);
2853 for (i = 0; i < in->phi_count; ++i)
2855 oprintf("([%s] : %s) ", in->phi[i].from->label,
2856 in->phi[i].value->name);
2861 void ir_instr_dump(ir_instr *in, char *ind,
2862 int (*oprintf)(const char*, ...))
2865 const char *comma = NULL;
2867 oprintf("%s (%i) ", ind, (int)in->eid);
2869 if (in->opcode == VINSTR_PHI) {
2870 dump_phi(in, ind, oprintf);
2874 strncat(ind, "\t", IND_BUFSZ);
2876 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2877 ir_value_dump(in->_ops[0], oprintf);
2878 if (in->_ops[1] || in->_ops[2])
2881 if (in->opcode == INSTR_CALL0) {
2882 oprintf("CALL%i\t", in->params_count);
2884 oprintf("%s\t", qc_opname(in->opcode));
2886 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2887 ir_value_dump(in->_ops[0], oprintf);
2892 for (i = 1; i != 3; ++i) {
2896 ir_value_dump(in->_ops[i], oprintf);
2904 oprintf("[%s]", in->bops[0]->label);
2908 oprintf("%s[%s]", comma, in->bops[1]->label);
2910 ind[strlen(ind)-1] = 0;
2913 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
2922 oprintf("(function)");
2925 oprintf("%g", v->constval.vfloat);
2928 oprintf("'%g %g %g'",
2931 v->constval.vvec.z);
2934 oprintf("(entity)");
2937 oprintf("\"%s\"", v->constval.vstring);
2941 oprintf("%i", v->constval.vint);
2946 v->constval.vpointer->name);
2950 oprintf("%s", v->name);
2954 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
2957 oprintf("Life of %s:\n", self->name);
2958 for (i = 0; i < self->life_count; ++i)
2960 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);