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 static void irerror(lex_ctx ctx, const char *msg, ...)
132 cvprintmsg(ctx, LVL_ERROR, "internal error", msg, ap);
136 /***********************************************************************
140 ir_builder* ir_builder_new(const char *modulename)
144 self = (ir_builder*)mem_a(sizeof(*self));
148 MEM_VECTOR_INIT(self, functions);
149 MEM_VECTOR_INIT(self, globals);
150 MEM_VECTOR_INIT(self, fields);
152 if (!ir_builder_set_name(self, modulename)) {
157 /* globals which always exist */
159 /* for now we give it a vector size */
160 ir_builder_create_global(self, "OFS_RETURN", TYPE_VARIANT);
165 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
166 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, fields)
167 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
169 void ir_builder_delete(ir_builder* self)
172 mem_d((void*)self->name);
173 for (i = 0; i != self->functions_count; ++i) {
174 ir_function_delete(self->functions[i]);
176 MEM_VECTOR_CLEAR(self, functions);
177 for (i = 0; i != self->globals_count; ++i) {
178 ir_value_delete(self->globals[i]);
180 MEM_VECTOR_CLEAR(self, globals);
181 for (i = 0; i != self->fields_count; ++i) {
182 ir_value_delete(self->fields[i]);
184 MEM_VECTOR_CLEAR(self, fields);
188 bool ir_builder_set_name(ir_builder *self, const char *name)
191 mem_d((void*)self->name);
192 self->name = util_strdup(name);
196 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
199 for (i = 0; i < self->functions_count; ++i) {
200 if (!strcmp(name, self->functions[i]->name))
201 return self->functions[i];
206 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
208 ir_function *fn = ir_builder_get_function(self, name);
213 fn = ir_function_new(self, outtype);
214 if (!ir_function_set_name(fn, name) ||
215 !ir_builder_functions_add(self, fn) )
217 ir_function_delete(fn);
221 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
223 ir_function_delete(fn);
227 fn->value->isconst = true;
228 fn->value->outtype = outtype;
229 fn->value->constval.vfunc = fn;
230 fn->value->context = fn->context;
235 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
238 for (i = 0; i < self->globals_count; ++i) {
239 if (!strcmp(self->globals[i]->name, name))
240 return self->globals[i];
245 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
249 if (name && name[0] != '#')
251 ve = ir_builder_get_global(self, name);
257 ve = ir_value_var(name, store_global, vtype);
258 if (!ir_builder_globals_add(self, ve)) {
265 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
268 for (i = 0; i < self->fields_count; ++i) {
269 if (!strcmp(self->fields[i]->name, name))
270 return self->fields[i];
276 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
278 ir_value *ve = ir_builder_get_field(self, name);
283 ve = ir_value_var(name, store_global, TYPE_FIELD);
284 ve->fieldtype = vtype;
285 if (!ir_builder_fields_add(self, ve)) {
292 /***********************************************************************
296 bool ir_function_naive_phi(ir_function*);
297 void ir_function_enumerate(ir_function*);
298 bool ir_function_calculate_liferanges(ir_function*);
299 bool ir_function_allocate_locals(ir_function*);
301 ir_function* ir_function_new(ir_builder* owner, int outtype)
304 self = (ir_function*)mem_a(sizeof(*self));
309 memset(self, 0, sizeof(*self));
312 if (!ir_function_set_name(self, "<@unnamed>")) {
317 self->context.file = "<@no context>";
318 self->context.line = 0;
319 self->outtype = outtype;
322 MEM_VECTOR_INIT(self, params);
323 MEM_VECTOR_INIT(self, blocks);
324 MEM_VECTOR_INIT(self, values);
325 MEM_VECTOR_INIT(self, locals);
327 self->code_function_def = -1;
328 self->allocated_locals = 0;
333 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
334 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
335 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
336 MEM_VEC_FUNCTIONS(ir_function, int, params)
338 bool ir_function_set_name(ir_function *self, const char *name)
341 mem_d((void*)self->name);
342 self->name = util_strdup(name);
346 void ir_function_delete(ir_function *self)
349 mem_d((void*)self->name);
351 for (i = 0; i != self->blocks_count; ++i)
352 ir_block_delete(self->blocks[i]);
353 MEM_VECTOR_CLEAR(self, blocks);
355 MEM_VECTOR_CLEAR(self, params);
357 for (i = 0; i != self->values_count; ++i)
358 ir_value_delete(self->values[i]);
359 MEM_VECTOR_CLEAR(self, values);
361 for (i = 0; i != self->locals_count; ++i)
362 ir_value_delete(self->locals[i]);
363 MEM_VECTOR_CLEAR(self, locals);
365 /* self->value is deleted by the builder */
370 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
372 return ir_function_values_add(self, v);
375 ir_block* ir_function_create_block(ir_function *self, const char *label)
377 ir_block* bn = ir_block_new(self, label);
378 memcpy(&bn->context, &self->context, sizeof(self->context));
379 if (!ir_function_blocks_add(self, bn)) {
386 bool ir_function_finalize(ir_function *self)
391 if (!ir_function_naive_phi(self))
394 ir_function_enumerate(self);
396 if (!ir_function_calculate_liferanges(self))
399 if (!ir_function_allocate_locals(self))
404 ir_value* ir_function_get_local(ir_function *self, const char *name)
407 for (i = 0; i < self->locals_count; ++i) {
408 if (!strcmp(self->locals[i]->name, name))
409 return self->locals[i];
414 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
416 ir_value *ve = ir_function_get_local(self, name);
422 self->locals_count &&
423 self->locals[self->locals_count-1]->store != store_param) {
424 irerror(self->context, "cannot add parameters after adding locals\n");
428 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
429 if (!ir_function_locals_add(self, ve)) {
436 /***********************************************************************
440 ir_block* ir_block_new(ir_function* owner, const char *name)
443 self = (ir_block*)mem_a(sizeof(*self));
447 memset(self, 0, sizeof(*self));
450 if (!ir_block_set_label(self, name)) {
455 self->context.file = "<@no context>";
456 self->context.line = 0;
458 MEM_VECTOR_INIT(self, instr);
459 MEM_VECTOR_INIT(self, entries);
460 MEM_VECTOR_INIT(self, exits);
463 self->is_return = false;
465 MEM_VECTOR_INIT(self, living);
467 self->generated = false;
471 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
472 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
473 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
474 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
476 void ir_block_delete(ir_block* self)
480 for (i = 0; i != self->instr_count; ++i)
481 ir_instr_delete(self->instr[i]);
482 MEM_VECTOR_CLEAR(self, instr);
483 MEM_VECTOR_CLEAR(self, entries);
484 MEM_VECTOR_CLEAR(self, exits);
485 MEM_VECTOR_CLEAR(self, living);
489 bool ir_block_set_label(ir_block *self, const char *name)
492 mem_d((void*)self->label);
493 self->label = util_strdup(name);
494 return !!self->label;
497 /***********************************************************************
501 ir_instr* ir_instr_new(ir_block* owner, int op)
504 self = (ir_instr*)mem_a(sizeof(*self));
509 self->context.file = "<@no context>";
510 self->context.line = 0;
512 self->_ops[0] = NULL;
513 self->_ops[1] = NULL;
514 self->_ops[2] = NULL;
515 self->bops[0] = NULL;
516 self->bops[1] = NULL;
517 MEM_VECTOR_INIT(self, phi);
518 MEM_VECTOR_INIT(self, params);
523 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
524 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
526 void ir_instr_delete(ir_instr *self)
529 /* The following calls can only delete from
530 * vectors, we still want to delete this instruction
531 * so ignore the return value. Since with the warn_unused_result attribute
532 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
533 * I have to improvise here and use if(foo());
535 for (i = 0; i < self->phi_count; ++i) {
537 if (ir_value_writes_find(self->phi[i].value, self, &idx))
538 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
539 if (ir_value_reads_find(self->phi[i].value, self, &idx))
540 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
542 MEM_VECTOR_CLEAR(self, phi);
543 for (i = 0; i < self->params_count; ++i) {
545 if (ir_value_writes_find(self->params[i], self, &idx))
546 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
547 if (ir_value_reads_find(self->params[i], self, &idx))
548 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
550 MEM_VECTOR_CLEAR(self, params);
551 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
552 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
553 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
557 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
559 if (self->_ops[op]) {
561 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
563 if (!ir_value_writes_remove(self->_ops[op], idx))
566 else if (ir_value_reads_find(self->_ops[op], self, &idx))
568 if (!ir_value_reads_remove(self->_ops[op], idx))
574 if (!ir_value_writes_add(v, self))
577 if (!ir_value_reads_add(v, self))
585 /***********************************************************************
589 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
591 self->code.globaladdr = gaddr;
592 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
593 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
594 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
597 int32_t ir_value_code_addr(const ir_value *self)
599 if (self->store == store_return)
600 return OFS_RETURN + self->code.addroffset;
601 return self->code.globaladdr + self->code.addroffset;
604 ir_value* ir_value_var(const char *name, int storetype, int vtype)
607 self = (ir_value*)mem_a(sizeof(*self));
609 self->fieldtype = TYPE_VOID;
610 self->outtype = TYPE_VOID;
611 self->store = storetype;
612 MEM_VECTOR_INIT(self, reads);
613 MEM_VECTOR_INIT(self, writes);
614 self->isconst = false;
615 self->context.file = "<@no context>";
616 self->context.line = 0;
618 ir_value_set_name(self, name);
620 memset(&self->constval, 0, sizeof(self->constval));
621 memset(&self->code, 0, sizeof(self->code));
623 self->members[0] = NULL;
624 self->members[1] = NULL;
625 self->members[2] = NULL;
627 MEM_VECTOR_INIT(self, life);
631 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
637 if (self->members[member])
638 return self->members[member];
640 if (self->vtype == TYPE_VECTOR)
642 m = ir_value_var(self->name, self->store, TYPE_FLOAT);
645 m->context = self->context;
647 self->members[member] = m;
648 m->code.addroffset = member;
650 else if (self->vtype == TYPE_FIELD)
652 if (self->fieldtype != TYPE_VECTOR)
654 m = ir_value_var(self->name, self->store, TYPE_FIELD);
657 m->fieldtype = TYPE_FLOAT;
658 m->context = self->context;
660 self->members[member] = m;
661 m->code.addroffset = member;
665 irerror(self->context, "invalid member access on %s\n", self->name);
672 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
673 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
674 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
676 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
678 ir_value *v = ir_value_var(name, storetype, vtype);
681 if (!ir_function_collect_value(owner, v))
689 void ir_value_delete(ir_value* self)
693 mem_d((void*)self->name);
696 if (self->vtype == TYPE_STRING)
697 mem_d((void*)self->constval.vstring);
699 for (i = 0; i < 3; ++i) {
700 if (self->members[i])
701 ir_value_delete(self->members[i]);
703 MEM_VECTOR_CLEAR(self, reads);
704 MEM_VECTOR_CLEAR(self, writes);
705 MEM_VECTOR_CLEAR(self, life);
709 void ir_value_set_name(ir_value *self, const char *name)
712 mem_d((void*)self->name);
713 self->name = util_strdup(name);
716 bool ir_value_set_float(ir_value *self, float f)
718 if (self->vtype != TYPE_FLOAT)
720 self->constval.vfloat = f;
721 self->isconst = true;
725 bool ir_value_set_func(ir_value *self, int f)
727 if (self->vtype != TYPE_FUNCTION)
729 self->constval.vint = f;
730 self->isconst = true;
734 bool ir_value_set_vector(ir_value *self, vector v)
736 if (self->vtype != TYPE_VECTOR)
738 self->constval.vvec = v;
739 self->isconst = true;
743 bool ir_value_set_field(ir_value *self, ir_value *fld)
745 if (self->vtype != TYPE_FIELD)
747 self->constval.vpointer = fld;
748 self->isconst = true;
752 static char *ir_strdup(const char *str)
755 /* actually dup empty strings */
756 char *out = mem_a(1);
760 return util_strdup(str);
763 bool ir_value_set_string(ir_value *self, const char *str)
765 if (self->vtype != TYPE_STRING)
767 self->constval.vstring = ir_strdup(str);
768 self->isconst = true;
773 bool ir_value_set_int(ir_value *self, int i)
775 if (self->vtype != TYPE_INTEGER)
777 self->constval.vint = i;
778 self->isconst = true;
783 bool ir_value_lives(ir_value *self, size_t at)
786 for (i = 0; i < self->life_count; ++i)
788 ir_life_entry_t *life = &self->life[i];
789 if (life->start <= at && at <= life->end)
791 if (life->start > at) /* since it's ordered */
797 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
800 if (!ir_value_life_add(self, e)) /* naive... */
802 for (k = self->life_count-1; k > idx; --k)
803 self->life[k] = self->life[k-1];
808 bool ir_value_life_merge(ir_value *self, size_t s)
811 ir_life_entry_t *life = NULL;
812 ir_life_entry_t *before = NULL;
813 ir_life_entry_t new_entry;
815 /* Find the first range >= s */
816 for (i = 0; i < self->life_count; ++i)
819 life = &self->life[i];
823 /* nothing found? append */
824 if (i == self->life_count) {
826 if (life && life->end+1 == s)
828 /* previous life range can be merged in */
832 if (life && life->end >= s)
835 if (!ir_value_life_add(self, e))
836 return false; /* failing */
842 if (before->end + 1 == s &&
843 life->start - 1 == s)
846 before->end = life->end;
847 if (!ir_value_life_remove(self, i))
848 return false; /* failing */
851 if (before->end + 1 == s)
857 /* already contained */
858 if (before->end >= s)
862 if (life->start - 1 == s)
867 /* insert a new entry */
868 new_entry.start = new_entry.end = s;
869 return ir_value_life_insert(self, i, new_entry);
872 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
876 if (!other->life_count)
879 if (!self->life_count) {
880 for (i = 0; i < other->life_count; ++i) {
881 if (!ir_value_life_add(self, other->life[i]))
888 for (i = 0; i < other->life_count; ++i)
890 const ir_life_entry_t *life = &other->life[i];
893 ir_life_entry_t *entry = &self->life[myi];
895 if (life->end+1 < entry->start)
897 /* adding an interval before entry */
898 if (!ir_value_life_insert(self, myi, *life))
904 if (life->start < entry->start &&
905 life->end >= entry->start)
907 /* starts earlier and overlaps */
908 entry->start = life->start;
911 if (life->end > entry->end &&
912 life->start-1 <= entry->end)
914 /* ends later and overlaps */
915 entry->end = life->end;
918 /* see if our change combines it with the next ranges */
919 while (myi+1 < self->life_count &&
920 entry->end+1 >= self->life[1+myi].start)
922 /* overlaps with (myi+1) */
923 if (entry->end < self->life[1+myi].end)
924 entry->end = self->life[1+myi].end;
925 if (!ir_value_life_remove(self, myi+1))
927 entry = &self->life[myi];
930 /* see if we're after the entry */
931 if (life->start > entry->end)
934 /* append if we're at the end */
935 if (myi >= self->life_count) {
936 if (!ir_value_life_add(self, *life))
940 /* otherweise check the next range */
949 bool ir_values_overlap(const ir_value *a, const ir_value *b)
951 /* For any life entry in A see if it overlaps with
952 * any life entry in B.
953 * Note that the life entries are orderes, so we can make a
954 * more efficient algorithm there than naively translating the
958 ir_life_entry_t *la, *lb, *enda, *endb;
960 /* first of all, if either has no life range, they cannot clash */
961 if (!a->life_count || !b->life_count)
966 enda = la + a->life_count;
967 endb = lb + b->life_count;
970 /* check if the entries overlap, for that,
971 * both must start before the other one ends.
973 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
974 if (la->start <= lb->end &&
975 lb->start <= la->end)
977 if (la->start < lb->end &&
984 /* entries are ordered
985 * one entry is earlier than the other
986 * that earlier entry will be moved forward
988 if (la->start < lb->start)
990 /* order: A B, move A forward
991 * check if we hit the end with A
996 else /* if (lb->start < la->start) actually <= */
998 /* order: B A, move B forward
999 * check if we hit the end with B
1008 /***********************************************************************
1012 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
1014 ir_instr *in = ir_instr_new(self, op);
1018 if (target->store == store_value &&
1019 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1021 irerror(self->context, "cannot store to an SSA value\n");
1022 irerror(self->context, "trying to store: %s <- %s\n", target->name, what->name);
1023 irerror(self->context, "instruction: %s\n", asm_instr[op].m);
1027 if (!ir_instr_op(in, 0, target, true) ||
1028 !ir_instr_op(in, 1, what, false) ||
1029 !ir_block_instr_add(self, in) )
1036 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
1040 if (target->vtype == TYPE_VARIANT)
1041 vtype = what->vtype;
1043 vtype = target->vtype;
1046 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1047 op = INSTR_CONV_ITOF;
1048 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1049 op = INSTR_CONV_FTOI;
1051 op = type_store_instr[vtype];
1053 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1054 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1058 return ir_block_create_store_op(self, op, target, what);
1061 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
1066 if (target->vtype != TYPE_POINTER)
1069 /* storing using pointer - target is a pointer, type must be
1070 * inferred from source
1072 vtype = what->vtype;
1074 op = type_storep_instr[vtype];
1075 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1076 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1077 op = INSTR_STOREP_V;
1080 return ir_block_create_store_op(self, op, target, what);
1083 bool ir_block_create_return(ir_block *self, ir_value *v)
1087 irerror(self->context, "block already ended (%s)\n", self->label);
1091 self->is_return = true;
1092 in = ir_instr_new(self, INSTR_RETURN);
1096 if (v && !ir_instr_op(in, 0, v, false))
1099 if (!ir_block_instr_add(self, in))
1104 bool ir_block_create_if(ir_block *self, ir_value *v,
1105 ir_block *ontrue, ir_block *onfalse)
1109 irerror(self->context, "block already ended (%s)\n", self->label);
1113 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1114 in = ir_instr_new(self, VINSTR_COND);
1118 if (!ir_instr_op(in, 0, v, false)) {
1119 ir_instr_delete(in);
1123 in->bops[0] = ontrue;
1124 in->bops[1] = onfalse;
1126 if (!ir_block_instr_add(self, in))
1129 if (!ir_block_exits_add(self, ontrue) ||
1130 !ir_block_exits_add(self, onfalse) ||
1131 !ir_block_entries_add(ontrue, self) ||
1132 !ir_block_entries_add(onfalse, self) )
1139 bool ir_block_create_jump(ir_block *self, ir_block *to)
1143 irerror(self->context, "block already ended (%s)\n", self->label);
1147 in = ir_instr_new(self, VINSTR_JUMP);
1152 if (!ir_block_instr_add(self, in))
1155 if (!ir_block_exits_add(self, to) ||
1156 !ir_block_entries_add(to, self) )
1163 bool ir_block_create_goto(ir_block *self, ir_block *to)
1167 irerror(self->context, "block already ended (%s)\n", self->label);
1171 in = ir_instr_new(self, INSTR_GOTO);
1176 if (!ir_block_instr_add(self, in))
1179 if (!ir_block_exits_add(self, to) ||
1180 !ir_block_entries_add(to, self) )
1187 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1191 in = ir_instr_new(self, VINSTR_PHI);
1194 out = ir_value_out(self->owner, label, store_value, ot);
1196 ir_instr_delete(in);
1199 if (!ir_instr_op(in, 0, out, true)) {
1200 ir_instr_delete(in);
1201 ir_value_delete(out);
1204 if (!ir_block_instr_add(self, in)) {
1205 ir_instr_delete(in);
1206 ir_value_delete(out);
1212 ir_value* ir_phi_value(ir_instr *self)
1214 return self->_ops[0];
1217 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1221 if (!ir_block_entries_find(self->owner, b, NULL)) {
1222 /* Must not be possible to cause this, otherwise the AST
1223 * is doing something wrong.
1225 irerror(self->context, "Invalid entry block for PHI\n");
1231 if (!ir_value_reads_add(v, self))
1233 return ir_instr_phi_add(self, pe);
1236 /* call related code */
1237 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1241 in = ir_instr_new(self, INSTR_CALL0);
1244 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1246 ir_instr_delete(in);
1249 if (!ir_instr_op(in, 0, out, true) ||
1250 !ir_instr_op(in, 1, func, false) ||
1251 !ir_block_instr_add(self, in))
1253 ir_instr_delete(in);
1254 ir_value_delete(out);
1260 ir_value* ir_call_value(ir_instr *self)
1262 return self->_ops[0];
1265 bool ir_call_param(ir_instr* self, ir_value *v)
1267 if (!ir_instr_params_add(self, v))
1269 if (!ir_value_reads_add(v, self)) {
1270 if (!ir_instr_params_remove(self, self->params_count-1))
1271 GMQCC_SUPPRESS_EMPTY_BODY;
1277 /* binary op related code */
1279 ir_value* ir_block_create_binop(ir_block *self,
1280 const char *label, int opcode,
1281 ir_value *left, ir_value *right)
1303 case INSTR_SUB_S: /* -- offset of string as float */
1308 case INSTR_BITOR_IF:
1309 case INSTR_BITOR_FI:
1310 case INSTR_BITAND_FI:
1311 case INSTR_BITAND_IF:
1326 case INSTR_BITAND_I:
1329 case INSTR_RSHIFT_I:
1330 case INSTR_LSHIFT_I:
1352 /* boolean operations result in floats */
1353 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1355 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1358 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1363 if (ot == TYPE_VOID) {
1364 /* The AST or parser were supposed to check this! */
1368 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1371 ir_value* ir_block_create_unary(ir_block *self,
1372 const char *label, int opcode,
1375 int ot = TYPE_FLOAT;
1387 /* QC doesn't have other unary operations. We expect extensions to fill
1388 * the above list, otherwise we assume out-type = in-type, eg for an
1392 ot = operand->vtype;
1395 if (ot == TYPE_VOID) {
1396 /* The AST or parser were supposed to check this! */
1400 /* let's use the general instruction creator and pass NULL for OPB */
1401 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1404 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1405 int op, ir_value *a, ir_value *b, int outype)
1410 out = ir_value_out(self->owner, label, store_value, outype);
1414 instr = ir_instr_new(self, op);
1416 ir_value_delete(out);
1420 if (!ir_instr_op(instr, 0, out, true) ||
1421 !ir_instr_op(instr, 1, a, false) ||
1422 !ir_instr_op(instr, 2, b, false) )
1427 if (!ir_block_instr_add(self, instr))
1432 ir_instr_delete(instr);
1433 ir_value_delete(out);
1437 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1441 /* Support for various pointer types todo if so desired */
1442 if (ent->vtype != TYPE_ENTITY)
1445 if (field->vtype != TYPE_FIELD)
1448 v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1449 v->fieldtype = field->fieldtype;
1453 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1456 if (ent->vtype != TYPE_ENTITY)
1459 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1460 if (field->vtype != TYPE_FIELD)
1465 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1466 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1467 case TYPE_STRING: op = INSTR_LOAD_S; break;
1468 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1469 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1470 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1472 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1473 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1479 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1482 ir_value* ir_block_create_add(ir_block *self,
1484 ir_value *left, ir_value *right)
1487 int l = left->vtype;
1488 int r = right->vtype;
1507 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1509 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1515 return ir_block_create_binop(self, label, op, left, right);
1518 ir_value* ir_block_create_sub(ir_block *self,
1520 ir_value *left, ir_value *right)
1523 int l = left->vtype;
1524 int r = right->vtype;
1544 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1546 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1552 return ir_block_create_binop(self, label, op, left, right);
1555 ir_value* ir_block_create_mul(ir_block *self,
1557 ir_value *left, ir_value *right)
1560 int l = left->vtype;
1561 int r = right->vtype;
1580 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1582 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1585 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1587 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1589 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1591 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1597 return ir_block_create_binop(self, label, op, left, right);
1600 ir_value* ir_block_create_div(ir_block *self,
1602 ir_value *left, ir_value *right)
1605 int l = left->vtype;
1606 int r = right->vtype;
1623 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1625 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1627 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1633 return ir_block_create_binop(self, label, op, left, right);
1636 /* PHI resolving breaks the SSA, and must thus be the last
1637 * step before life-range calculation.
1640 static bool ir_block_naive_phi(ir_block *self);
1641 bool ir_function_naive_phi(ir_function *self)
1645 for (i = 0; i < self->blocks_count; ++i)
1647 if (!ir_block_naive_phi(self->blocks[i]))
1653 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1658 /* create a store */
1659 if (!ir_block_create_store(block, old, what))
1662 /* we now move it up */
1663 instr = block->instr[block->instr_count-1];
1664 for (i = block->instr_count; i > iid; --i)
1665 block->instr[i] = block->instr[i-1];
1666 block->instr[i] = instr;
1671 static bool ir_block_naive_phi(ir_block *self)
1674 /* FIXME: optionally, create_phi can add the phis
1675 * to a list so we don't need to loop through blocks
1676 * - anyway: "don't optimize YET"
1678 for (i = 0; i < self->instr_count; ++i)
1680 ir_instr *instr = self->instr[i];
1681 if (instr->opcode != VINSTR_PHI)
1684 if (!ir_block_instr_remove(self, i))
1686 --i; /* NOTE: i+1 below */
1688 for (p = 0; p < instr->phi_count; ++p)
1690 ir_value *v = instr->phi[p].value;
1691 for (w = 0; w < v->writes_count; ++w) {
1694 if (!v->writes[w]->_ops[0])
1697 /* When the write was to a global, we have to emit a mov */
1698 old = v->writes[w]->_ops[0];
1700 /* The original instruction now writes to the PHI target local */
1701 if (v->writes[w]->_ops[0] == v)
1702 v->writes[w]->_ops[0] = instr->_ops[0];
1704 if (old->store != store_value && old->store != store_local && old->store != store_param)
1706 /* If it originally wrote to a global we need to store the value
1709 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1711 if (i+1 < self->instr_count)
1712 instr = self->instr[i+1];
1715 /* In case I forget and access instr later, it'll be NULL
1716 * when it's a problem, to make sure we crash, rather than accessing
1722 /* If it didn't, we can replace all reads by the phi target now. */
1724 for (r = 0; r < old->reads_count; ++r)
1727 ir_instr *ri = old->reads[r];
1728 for (op = 0; op < ri->phi_count; ++op) {
1729 if (ri->phi[op].value == old)
1730 ri->phi[op].value = v;
1732 for (op = 0; op < 3; ++op) {
1733 if (ri->_ops[op] == old)
1740 ir_instr_delete(instr);
1745 /***********************************************************************
1746 *IR Temp allocation code
1747 * Propagating value life ranges by walking through the function backwards
1748 * until no more changes are made.
1749 * In theory this should happen once more than once for every nested loop
1751 * Though this implementation might run an additional time for if nests.
1760 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1762 /* Enumerate instructions used by value's life-ranges
1764 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1768 for (i = 0; i < self->instr_count; ++i)
1770 self->instr[i]->eid = eid++;
1775 /* Enumerate blocks and instructions.
1776 * The block-enumeration is unordered!
1777 * We do not really use the block enumreation, however
1778 * the instruction enumeration is important for life-ranges.
1780 void ir_function_enumerate(ir_function *self)
1783 size_t instruction_id = 0;
1784 for (i = 0; i < self->blocks_count; ++i)
1786 self->blocks[i]->eid = i;
1787 self->blocks[i]->run_id = 0;
1788 ir_block_enumerate(self->blocks[i], &instruction_id);
1792 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1793 bool ir_function_calculate_liferanges(ir_function *self)
1801 for (i = 0; i != self->blocks_count; ++i)
1803 if (self->blocks[i]->is_return)
1805 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1813 /* Local-value allocator
1814 * After finishing creating the liferange of all values used in a function
1815 * we can allocate their global-positions.
1816 * This is the counterpart to register-allocation in register machines.
1819 MEM_VECTOR_MAKE(ir_value*, locals);
1820 MEM_VECTOR_MAKE(size_t, sizes);
1821 MEM_VECTOR_MAKE(size_t, positions);
1822 } function_allocator;
1823 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1824 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1825 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1827 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1830 size_t vsize = type_sizeof[var->vtype];
1832 slot = ir_value_var("reg", store_global, var->vtype);
1836 if (!ir_value_life_merge_into(slot, var))
1839 if (!function_allocator_locals_add(alloc, slot))
1842 if (!function_allocator_sizes_add(alloc, vsize))
1848 ir_value_delete(slot);
1852 bool ir_function_allocate_locals(ir_function *self)
1861 function_allocator alloc;
1863 if (!self->locals_count && !self->values_count)
1866 MEM_VECTOR_INIT(&alloc, locals);
1867 MEM_VECTOR_INIT(&alloc, sizes);
1868 MEM_VECTOR_INIT(&alloc, positions);
1870 for (i = 0; i < self->locals_count; ++i)
1872 if (!function_allocator_alloc(&alloc, self->locals[i]))
1876 /* Allocate a slot for any value that still exists */
1877 for (i = 0; i < self->values_count; ++i)
1879 v = self->values[i];
1884 for (a = 0; a < alloc.locals_count; ++a)
1886 slot = alloc.locals[a];
1888 if (ir_values_overlap(v, slot))
1891 if (!ir_value_life_merge_into(slot, v))
1894 /* adjust size for this slot */
1895 if (alloc.sizes[a] < type_sizeof[v->vtype])
1896 alloc.sizes[a] = type_sizeof[v->vtype];
1898 self->values[i]->code.local = a;
1901 if (a >= alloc.locals_count) {
1902 self->values[i]->code.local = alloc.locals_count;
1903 if (!function_allocator_alloc(&alloc, v))
1912 /* Adjust slot positions based on sizes */
1913 if (!function_allocator_positions_add(&alloc, 0))
1916 if (alloc.sizes_count)
1917 pos = alloc.positions[0] + alloc.sizes[0];
1920 for (i = 1; i < alloc.sizes_count; ++i)
1922 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1923 if (!function_allocator_positions_add(&alloc, pos))
1927 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1929 /* Take over the actual slot positions */
1930 for (i = 0; i < self->values_count; ++i) {
1931 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1939 for (i = 0; i < alloc.locals_count; ++i)
1940 ir_value_delete(alloc.locals[i]);
1941 MEM_VECTOR_CLEAR(&alloc, locals);
1942 MEM_VECTOR_CLEAR(&alloc, sizes);
1943 MEM_VECTOR_CLEAR(&alloc, positions);
1947 /* Get information about which operand
1948 * is read from, or written to.
1950 static void ir_op_read_write(int op, size_t *read, size_t *write)
1970 case INSTR_STOREP_F:
1971 case INSTR_STOREP_V:
1972 case INSTR_STOREP_S:
1973 case INSTR_STOREP_ENT:
1974 case INSTR_STOREP_FLD:
1975 case INSTR_STOREP_FNC:
1986 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1989 bool changed = false;
1991 for (i = 0; i != self->living_count; ++i)
1993 tempbool = ir_value_life_merge(self->living[i], eid);
1996 irerror(self->context, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1998 changed = changed || tempbool;
2003 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
2006 /* values which have been read in a previous iteration are now
2007 * in the "living" array even if the previous block doesn't use them.
2008 * So we have to remove whatever does not exist in the previous block.
2009 * They will be re-added on-read, but the liferange merge won't cause
2012 for (i = 0; i < self->living_count; ++i)
2014 if (!ir_block_living_find(prev, self->living[i], NULL)) {
2015 if (!ir_block_living_remove(self, i))
2021 /* Whatever the previous block still has in its living set
2022 * must now be added to ours as well.
2024 for (i = 0; i < prev->living_count; ++i)
2026 if (ir_block_living_find(self, prev->living[i], NULL))
2028 if (!ir_block_living_add(self, prev->living[i]))
2031 irerror(self->contextt from prev: %s\n", self->label, prev->living[i]->_name);
2037 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2043 /* bitmasks which operands are read from or written to */
2045 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2047 new_reads_t new_reads;
2049 char dbg_ind[16] = { '#', '0' };
2052 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2053 MEM_VECTOR_INIT(&new_reads, v);
2058 if (!ir_block_life_prop_previous(self, prev, changed))
2062 i = self->instr_count;
2065 instr = self->instr[i];
2067 /* PHI operands are always read operands */
2068 for (p = 0; p < instr->phi_count; ++p)
2070 value = instr->phi[p].value;
2071 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2072 if (!ir_block_living_find(self, value, NULL) &&
2073 !ir_block_living_add(self, value))
2078 if (!new_reads_t_v_find(&new_reads, value, NULL))
2080 if (!new_reads_t_v_add(&new_reads, value))
2086 /* call params are read operands too */
2087 for (p = 0; p < instr->params_count; ++p)
2089 value = instr->params[p];
2090 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2091 if (!ir_block_living_find(self, value, NULL) &&
2092 !ir_block_living_add(self, value))
2097 if (!new_reads_t_v_find(&new_reads, value, NULL))
2099 if (!new_reads_t_v_add(&new_reads, value))
2105 /* See which operands are read and write operands */
2106 ir_op_read_write(instr->opcode, &read, &write);
2108 /* Go through the 3 main operands */
2109 for (o = 0; o < 3; ++o)
2111 if (!instr->_ops[o]) /* no such operand */
2114 value = instr->_ops[o];
2116 /* We only care about locals */
2117 /* we also calculate parameter liferanges so that locals
2118 * can take up parameter slots */
2119 if (value->store != store_value &&
2120 value->store != store_local &&
2121 value->store != store_param)
2127 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2128 if (!ir_block_living_find(self, value, NULL) &&
2129 !ir_block_living_add(self, value))
2134 /* fprintf(stderr, "read: %s\n", value->_name); */
2135 if (!new_reads_t_v_find(&new_reads, value, NULL))
2137 if (!new_reads_t_v_add(&new_reads, value))
2143 /* write operands */
2144 /* When we write to a local, we consider it "dead" for the
2145 * remaining upper part of the function, since in SSA a value
2146 * can only be written once (== created)
2151 bool in_living = ir_block_living_find(self, value, &idx);
2152 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2154 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
2155 if (!in_living && !in_reads)
2160 /* If the value isn't alive it hasn't been read before... */
2161 /* TODO: See if the warning can be emitted during parsing or AST processing
2162 * otherwise have warning printed here.
2163 * IF printing a warning here: include filecontext_t,
2164 * and make sure it's only printed once
2165 * since this function is run multiple times.
2167 /* For now: debug info: */
2168 /* fprintf(stderr, "Value only written %s\n", value->name); */
2169 tempbool = ir_value_life_merge(value, instr->eid);
2170 *changed = *changed || tempbool;
2172 ir_instr_dump(instr, dbg_ind, printf);
2176 /* since 'living' won't contain it
2177 * anymore, merge the value, since
2180 tempbool = ir_value_life_merge(value, instr->eid);
2183 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2185 *changed = *changed || tempbool;
2187 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2188 if (!ir_block_living_remove(self, idx))
2193 if (!new_reads_t_v_remove(&new_reads, readidx))
2201 tempbool = ir_block_living_add_instr(self, instr->eid);
2202 /*fprintf(stderr, "living added values\n");*/
2203 *changed = *changed || tempbool;
2205 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2207 for (rd = 0; rd < new_reads.v_count; ++rd)
2209 if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
2210 if (!ir_block_living_add(self, new_reads.v[rd]))
2213 if (!i && !self->entries_count) {
2215 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
2218 MEM_VECTOR_CLEAR(&new_reads, v);
2222 if (self->run_id == self->owner->run_id)
2225 self->run_id = self->owner->run_id;
2227 for (i = 0; i < self->entries_count; ++i)
2229 ir_block *entry = self->entries[i];
2230 ir_block_life_propagate(entry, self, changed);
2235 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2236 MEM_VECTOR_CLEAR(&new_reads, v);
2241 /***********************************************************************
2244 * Since the IR has the convention of putting 'write' operands
2245 * at the beginning, we have to rotate the operands of instructions
2246 * properly in order to generate valid QCVM code.
2248 * Having destinations at a fixed position is more convenient. In QC
2249 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2250 * read from from OPA, and store to OPB rather than OPC. Which is
2251 * partially the reason why the implementation of these instructions
2252 * in darkplaces has been delayed for so long.
2254 * Breaking conventions is annoying...
2256 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2258 static bool gen_global_field(ir_value *global)
2260 if (global->isconst)
2262 ir_value *fld = global->constval.vpointer;
2264 irerror(global->context, "Invalid field constant with no field: %s\n", global->name);
2268 /* Now, in this case, a relocation would be impossible to code
2269 * since it looks like this:
2270 * .vector v = origin; <- parse error, wtf is 'origin'?
2273 * But we will need a general relocation support later anyway
2274 * for functions... might as well support that here.
2276 if (!fld->code.globaladdr) {
2277 irerror(global->context, "FIXME: Relocation support\n");
2281 /* copy the field's value */
2282 ir_value_code_setaddr(global, code_globals_add(code_globals_data[fld->code.globaladdr]));
2283 if (global->fieldtype == TYPE_VECTOR) {
2284 code_globals_add(code_globals_data[fld->code.globaladdr]+1);
2285 code_globals_add(code_globals_data[fld->code.globaladdr]+2);
2290 ir_value_code_setaddr(global, code_globals_add(0));
2291 if (global->fieldtype == TYPE_VECTOR) {
2292 code_globals_add(0);
2293 code_globals_add(0);
2296 if (global->code.globaladdr < 0)
2301 static bool gen_global_pointer(ir_value *global)
2303 if (global->isconst)
2305 ir_value *target = global->constval.vpointer;
2307 irerror(global->context, "Invalid pointer constant: %s\n", global->name);
2308 /* NULL pointers are pointing to the NULL constant, which also
2309 * sits at address 0, but still has an ir_value for itself.
2314 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2315 * void() foo; <- proto
2316 * void() *fooptr = &foo;
2317 * void() foo = { code }
2319 if (!target->code.globaladdr) {
2320 /* FIXME: Check for the constant nullptr ir_value!
2321 * because then code.globaladdr being 0 is valid.
2323 irerror(global->context, "FIXME: Relocation support\n");
2327 ir_value_code_setaddr(global, code_globals_add(target->code.globaladdr));
2331 ir_value_code_setaddr(global, code_globals_add(0));
2333 if (global->code.globaladdr < 0)
2338 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2340 prog_section_statement stmt;
2349 block->generated = true;
2350 block->code_start = code_statements_elements;
2351 for (i = 0; i < block->instr_count; ++i)
2353 instr = block->instr[i];
2355 if (instr->opcode == VINSTR_PHI) {
2356 irerror(block->context, "cannot generate virtual instruction (phi)\n");
2360 if (instr->opcode == VINSTR_JUMP) {
2361 target = instr->bops[0];
2362 /* for uncoditional jumps, if the target hasn't been generated
2363 * yet, we generate them right here.
2365 if (!target->generated) {
2370 /* otherwise we generate a jump instruction */
2371 stmt.opcode = INSTR_GOTO;
2372 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2375 if (code_statements_add(stmt) < 0)
2378 /* no further instructions can be in this block */
2382 if (instr->opcode == VINSTR_COND) {
2383 ontrue = instr->bops[0];
2384 onfalse = instr->bops[1];
2385 /* TODO: have the AST signal which block should
2386 * come first: eg. optimize IFs without ELSE...
2389 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2393 if (ontrue->generated) {
2394 stmt.opcode = INSTR_IF;
2395 stmt.o2.s1 = (ontrue->code_start) - code_statements_elements;
2396 if (code_statements_add(stmt) < 0)
2399 if (onfalse->generated) {
2400 stmt.opcode = INSTR_IFNOT;
2401 stmt.o2.s1 = (onfalse->code_start) - code_statements_elements;
2402 if (code_statements_add(stmt) < 0)
2405 if (!ontrue->generated) {
2406 if (onfalse->generated) {
2411 if (!onfalse->generated) {
2412 if (ontrue->generated) {
2417 /* neither ontrue nor onfalse exist */
2418 stmt.opcode = INSTR_IFNOT;
2419 stidx = code_statements_elements;
2420 if (code_statements_add(stmt) < 0)
2422 /* on false we jump, so add ontrue-path */
2423 if (!gen_blocks_recursive(func, ontrue))
2425 /* fixup the jump address */
2426 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2427 /* generate onfalse path */
2428 if (onfalse->generated) {
2429 /* fixup the jump address */
2430 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2431 /* may have been generated in the previous recursive call */
2432 stmt.opcode = INSTR_GOTO;
2433 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2436 return (code_statements_add(stmt) >= 0);
2438 /* if not, generate now */
2443 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2444 /* Trivial call translation:
2445 * copy all params to OFS_PARM*
2446 * if the output's storetype is not store_return,
2447 * add append a STORE instruction!
2449 * NOTES on how to do it better without much trouble:
2450 * -) The liferanges!
2451 * Simply check the liferange of all parameters for
2452 * other CALLs. For each param with no CALL in its
2453 * liferange, we can store it in an OFS_PARM at
2454 * generation already. This would even include later
2455 * reuse.... probably... :)
2460 for (p = 0; p < instr->params_count; ++p)
2462 ir_value *param = instr->params[p];
2464 stmt.opcode = INSTR_STORE_F;
2467 stmt.opcode = type_store_instr[param->vtype];
2468 stmt.o1.u1 = ir_value_code_addr(param);
2469 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2470 if (code_statements_add(stmt) < 0)
2473 stmt.opcode = INSTR_CALL0 + instr->params_count;
2474 if (stmt.opcode > INSTR_CALL8)
2475 stmt.opcode = INSTR_CALL8;
2476 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2479 if (code_statements_add(stmt) < 0)
2482 retvalue = instr->_ops[0];
2483 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2485 /* not to be kept in OFS_RETURN */
2486 stmt.opcode = type_store_instr[retvalue->vtype];
2487 stmt.o1.u1 = OFS_RETURN;
2488 stmt.o2.u1 = ir_value_code_addr(retvalue);
2490 if (code_statements_add(stmt) < 0)
2496 if (instr->opcode == INSTR_STATE) {
2497 irerror(block->context, "TODO: state instruction\n");
2501 stmt.opcode = instr->opcode;
2506 /* This is the general order of operands */
2508 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2511 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2514 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2516 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2518 stmt.o1.u1 = stmt.o3.u1;
2521 else if ((stmt.opcode >= INSTR_STORE_F &&
2522 stmt.opcode <= INSTR_STORE_FNC) ||
2523 (stmt.opcode >= INSTR_STOREP_F &&
2524 stmt.opcode <= INSTR_STOREP_FNC))
2526 /* 2-operand instructions with A -> B */
2527 stmt.o2.u1 = stmt.o3.u1;
2531 if (code_statements_add(stmt) < 0)
2537 static bool gen_function_code(ir_function *self)
2540 prog_section_statement stmt;
2542 /* Starting from entry point, we generate blocks "as they come"
2543 * for now. Dead blocks will not be translated obviously.
2545 if (!self->blocks_count) {
2546 irerror(self->context, "Function '%s' declared without body.\n", self->name);
2550 block = self->blocks[0];
2551 if (block->generated)
2554 if (!gen_blocks_recursive(self, block)) {
2555 irerror(self->context, "failed to generate blocks for '%s'\n", self->name);
2559 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2560 stmt.opcode = AINSTR_END;
2564 if (code_statements_add(stmt) < 0)
2569 static bool gen_global_function(ir_builder *ir, ir_value *global)
2571 prog_section_function fun;
2575 size_t local_var_end;
2577 if (!global->isconst || (!global->constval.vfunc))
2579 irerror(global->context, "Invalid state of function-global: not constant: %s\n", global->name);
2583 irfun = global->constval.vfunc;
2585 fun.name = global->code.name;
2586 fun.file = code_cachedstring(global->context.file);
2587 fun.profile = 0; /* always 0 */
2588 fun.nargs = irfun->params_count;
2590 for (i = 0;i < 8; ++i) {
2594 fun.argsize[i] = type_sizeof[irfun->params[i]];
2597 fun.firstlocal = code_globals_elements;
2598 fun.locals = irfun->allocated_locals + irfun->locals_count;
2600 local_var_end = fun.firstlocal;
2601 for (i = 0; i < irfun->locals_count; ++i) {
2602 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2603 irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
2607 if (irfun->locals_count) {
2608 ir_value *last = irfun->locals[irfun->locals_count-1];
2609 local_var_end = last->code.globaladdr;
2610 local_var_end += type_sizeof[last->vtype];
2612 for (i = 0; i < irfun->values_count; ++i)
2614 /* generate code.globaladdr for ssa values */
2615 ir_value *v = irfun->values[i];
2616 ir_value_code_setaddr(v, local_var_end + v->code.local);
2618 for (i = 0; i < irfun->allocated_locals; ++i) {
2619 /* fill the locals with zeros */
2620 code_globals_add(0);
2624 fun.entry = irfun->builtin;
2626 irfun->code_function_def = code_functions_elements;
2627 fun.entry = code_statements_elements;
2630 return (code_functions_add(fun) >= 0);
2633 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
2635 prog_section_function *fundef;
2638 irfun = global->constval.vfunc;
2642 if (irfun->code_function_def < 0) {
2643 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
2646 fundef = &code_functions_data[irfun->code_function_def];
2648 fundef->entry = code_statements_elements;
2649 if (!gen_function_code(irfun)) {
2650 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
2656 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2660 prog_section_def def;
2662 def.type = global->vtype;
2663 def.offset = code_globals_elements;
2664 def.name = global->code.name = code_genstring(global->name);
2666 switch (global->vtype)
2669 if (code_defs_add(def) < 0)
2671 return gen_global_pointer(global);
2673 if (code_defs_add(def) < 0)
2675 return gen_global_field(global);
2680 if (code_defs_add(def) < 0)
2683 if (global->isconst) {
2684 iptr = (int32_t*)&global->constval.vfloat;
2685 ir_value_code_setaddr(global, code_globals_add(*iptr));
2687 ir_value_code_setaddr(global, code_globals_add(0));
2689 return global->code.globaladdr >= 0;
2693 if (code_defs_add(def) < 0)
2695 if (global->isconst)
2696 ir_value_code_setaddr(global, code_globals_add(code_cachedstring(global->constval.vstring)));
2698 ir_value_code_setaddr(global, code_globals_add(0));
2699 return global->code.globaladdr >= 0;
2704 if (code_defs_add(def) < 0)
2707 if (global->isconst) {
2708 iptr = (int32_t*)&global->constval.vvec;
2709 ir_value_code_setaddr(global, code_globals_add(iptr[0]));
2710 if (global->code.globaladdr < 0)
2712 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2714 if (code_globals_add(iptr[d]) < 0)
2718 ir_value_code_setaddr(global, code_globals_add(0));
2719 if (global->code.globaladdr < 0)
2721 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2723 if (code_globals_add(0) < 0)
2727 return global->code.globaladdr >= 0;
2730 if (code_defs_add(def) < 0)
2732 ir_value_code_setaddr(global, code_globals_elements);
2733 code_globals_add(code_functions_elements);
2734 return gen_global_function(self, global);
2736 /* assume biggest type */
2737 ir_value_code_setaddr(global, code_globals_add(0));
2738 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2739 code_globals_add(0);
2742 /* refuse to create 'void' type or any other fancy business. */
2743 irerror(global->context, "Invalid type for global variable %s\n", global->name);
2748 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2750 prog_section_def def;
2751 prog_section_field fld;
2753 def.type = field->vtype;
2754 def.offset = code_globals_elements;
2756 /* create a global named the same as the field */
2757 if (opts_standard == COMPILER_GMQCC) {
2758 /* in our standard, the global gets a dot prefix */
2759 size_t len = strlen(field->name);
2762 /* we really don't want to have to allocate this, and 1024
2763 * bytes is more than enough for a variable/field name
2765 if (len+2 >= sizeof(name)) {
2766 irerror(field->context, "invalid field name size: %u\n", (unsigned int)len);
2771 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
2774 def.name = code_genstring(name);
2775 fld.name = def.name + 1; /* we reuse that string table entry */
2777 /* in plain QC, there cannot be a global with the same name,
2778 * and so we also name the global the same.
2779 * FIXME: fteqcc should create a global as well
2780 * check if it actually uses the same name. Probably does
2782 def.name = code_genstring(field->name);
2783 fld.name = def.name;
2786 field->code.name = def.name;
2788 if (code_defs_add(def) < 0)
2791 fld.type = field->fieldtype;
2793 if (fld.type == TYPE_VOID) {
2794 irerror(field->context, "field is missing a type: %s - don't know its size\n", field->name);
2798 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2800 if (code_fields_add(fld) < 0)
2803 ir_value_code_setaddr(field, code_globals_elements);
2804 if (!code_globals_add(fld.offset))
2806 if (fld.type == TYPE_VECTOR) {
2807 if (!code_globals_add(fld.offset+1))
2809 if (!code_globals_add(fld.offset+2))
2813 return field->code.globaladdr >= 0;
2816 bool ir_builder_generate(ir_builder *self, const char *filename)
2822 for (i = 0; i < self->fields_count; ++i)
2824 if (!ir_builder_gen_field(self, self->fields[i])) {
2829 for (i = 0; i < self->globals_count; ++i)
2831 if (!ir_builder_gen_global(self, self->globals[i])) {
2836 /* generate function code */
2837 for (i = 0; i < self->globals_count; ++i)
2839 if (self->globals[i]->vtype == TYPE_FUNCTION) {
2840 if (!gen_global_function_code(self, self->globals[i])) {
2846 printf("writing '%s'...\n", filename);
2847 return code_write(filename);
2850 /***********************************************************************
2851 *IR DEBUG Dump functions...
2854 #define IND_BUFSZ 1024
2857 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
2859 # define strncat strncat
2862 const char *qc_opname(int op)
2864 if (op < 0) return "<INVALID>";
2865 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2866 return asm_instr[op].m;
2868 case VINSTR_PHI: return "PHI";
2869 case VINSTR_JUMP: return "JUMP";
2870 case VINSTR_COND: return "COND";
2871 default: return "<UNK>";
2875 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2878 char indent[IND_BUFSZ];
2882 oprintf("module %s\n", b->name);
2883 for (i = 0; i < b->globals_count; ++i)
2886 if (b->globals[i]->isconst)
2887 oprintf("%s = ", b->globals[i]->name);
2888 ir_value_dump(b->globals[i], oprintf);
2891 for (i = 0; i < b->functions_count; ++i)
2892 ir_function_dump(b->functions[i], indent, oprintf);
2893 oprintf("endmodule %s\n", b->name);
2896 void ir_function_dump(ir_function *f, char *ind,
2897 int (*oprintf)(const char*, ...))
2900 if (f->builtin != 0) {
2901 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2904 oprintf("%sfunction %s\n", ind, f->name);
2905 strncat(ind, "\t", IND_BUFSZ);
2906 if (f->locals_count)
2908 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2909 for (i = 0; i < f->locals_count; ++i) {
2910 oprintf("%s\t", ind);
2911 ir_value_dump(f->locals[i], oprintf);
2915 if (f->blocks_count)
2917 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2918 for (i = 0; i < f->blocks_count; ++i) {
2919 if (f->blocks[i]->run_id != f->run_id) {
2920 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2922 ir_block_dump(f->blocks[i], ind, oprintf);
2926 ind[strlen(ind)-1] = 0;
2927 oprintf("%sendfunction %s\n", ind, f->name);
2930 void ir_block_dump(ir_block* b, char *ind,
2931 int (*oprintf)(const char*, ...))
2934 oprintf("%s:%s\n", ind, b->label);
2935 strncat(ind, "\t", IND_BUFSZ);
2937 for (i = 0; i < b->instr_count; ++i)
2938 ir_instr_dump(b->instr[i], ind, oprintf);
2939 ind[strlen(ind)-1] = 0;
2942 void dump_phi(ir_instr *in, char *ind,
2943 int (*oprintf)(const char*, ...))
2946 oprintf("%s <- phi ", in->_ops[0]->name);
2947 for (i = 0; i < in->phi_count; ++i)
2949 oprintf("([%s] : %s) ", in->phi[i].from->label,
2950 in->phi[i].value->name);
2955 void ir_instr_dump(ir_instr *in, char *ind,
2956 int (*oprintf)(const char*, ...))
2959 const char *comma = NULL;
2961 oprintf("%s (%i) ", ind, (int)in->eid);
2963 if (in->opcode == VINSTR_PHI) {
2964 dump_phi(in, ind, oprintf);
2968 strncat(ind, "\t", IND_BUFSZ);
2970 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2971 ir_value_dump(in->_ops[0], oprintf);
2972 if (in->_ops[1] || in->_ops[2])
2975 if (in->opcode == INSTR_CALL0) {
2976 oprintf("CALL%i\t", in->params_count);
2978 oprintf("%s\t", qc_opname(in->opcode));
2980 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2981 ir_value_dump(in->_ops[0], oprintf);
2986 for (i = 1; i != 3; ++i) {
2990 ir_value_dump(in->_ops[i], oprintf);
2998 oprintf("[%s]", in->bops[0]->label);
3002 oprintf("%s[%s]", comma, in->bops[1]->label);
3004 ind[strlen(ind)-1] = 0;
3007 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3016 oprintf("(function)");
3019 oprintf("%g", v->constval.vfloat);
3022 oprintf("'%g %g %g'",
3025 v->constval.vvec.z);
3028 oprintf("(entity)");
3031 oprintf("\"%s\"", v->constval.vstring);
3035 oprintf("%i", v->constval.vint);
3040 v->constval.vpointer->name);
3044 oprintf("%s", v->name);
3048 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
3051 oprintf("Life of %s:\n", self->name);
3052 for (i = 0; i < self->life_count; ++i)
3054 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);