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 bool ir_value_set_string(ir_value *self, const char *str)
754 if (self->vtype != TYPE_STRING)
756 self->constval.vstring = util_strdup(str);
757 self->isconst = true;
762 bool ir_value_set_int(ir_value *self, int i)
764 if (self->vtype != TYPE_INTEGER)
766 self->constval.vint = i;
767 self->isconst = true;
772 bool ir_value_lives(ir_value *self, size_t at)
775 for (i = 0; i < self->life_count; ++i)
777 ir_life_entry_t *life = &self->life[i];
778 if (life->start <= at && at <= life->end)
780 if (life->start > at) /* since it's ordered */
786 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
789 if (!ir_value_life_add(self, e)) /* naive... */
791 for (k = self->life_count-1; k > idx; --k)
792 self->life[k] = self->life[k-1];
797 bool ir_value_life_merge(ir_value *self, size_t s)
800 ir_life_entry_t *life = NULL;
801 ir_life_entry_t *before = NULL;
802 ir_life_entry_t new_entry;
804 /* Find the first range >= s */
805 for (i = 0; i < self->life_count; ++i)
808 life = &self->life[i];
812 /* nothing found? append */
813 if (i == self->life_count) {
815 if (life && life->end+1 == s)
817 /* previous life range can be merged in */
821 if (life && life->end >= s)
824 if (!ir_value_life_add(self, e))
825 return false; /* failing */
831 if (before->end + 1 == s &&
832 life->start - 1 == s)
835 before->end = life->end;
836 if (!ir_value_life_remove(self, i))
837 return false; /* failing */
840 if (before->end + 1 == s)
846 /* already contained */
847 if (before->end >= s)
851 if (life->start - 1 == s)
856 /* insert a new entry */
857 new_entry.start = new_entry.end = s;
858 return ir_value_life_insert(self, i, new_entry);
861 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
865 if (!other->life_count)
868 if (!self->life_count) {
869 for (i = 0; i < other->life_count; ++i) {
870 if (!ir_value_life_add(self, other->life[i]))
877 for (i = 0; i < other->life_count; ++i)
879 const ir_life_entry_t *life = &other->life[i];
882 ir_life_entry_t *entry = &self->life[myi];
884 if (life->end+1 < entry->start)
886 /* adding an interval before entry */
887 if (!ir_value_life_insert(self, myi, *life))
893 if (life->start < entry->start &&
894 life->end >= entry->start)
896 /* starts earlier and overlaps */
897 entry->start = life->start;
900 if (life->end > entry->end &&
901 life->start-1 <= entry->end)
903 /* ends later and overlaps */
904 entry->end = life->end;
907 /* see if our change combines it with the next ranges */
908 while (myi+1 < self->life_count &&
909 entry->end+1 >= self->life[1+myi].start)
911 /* overlaps with (myi+1) */
912 if (entry->end < self->life[1+myi].end)
913 entry->end = self->life[1+myi].end;
914 if (!ir_value_life_remove(self, myi+1))
916 entry = &self->life[myi];
919 /* see if we're after the entry */
920 if (life->start > entry->end)
923 /* append if we're at the end */
924 if (myi >= self->life_count) {
925 if (!ir_value_life_add(self, *life))
929 /* otherweise check the next range */
938 bool ir_values_overlap(const ir_value *a, const ir_value *b)
940 /* For any life entry in A see if it overlaps with
941 * any life entry in B.
942 * Note that the life entries are orderes, so we can make a
943 * more efficient algorithm there than naively translating the
947 ir_life_entry_t *la, *lb, *enda, *endb;
949 /* first of all, if either has no life range, they cannot clash */
950 if (!a->life_count || !b->life_count)
955 enda = la + a->life_count;
956 endb = lb + b->life_count;
959 /* check if the entries overlap, for that,
960 * both must start before the other one ends.
962 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
963 if (la->start <= lb->end &&
964 lb->start <= la->end)
966 if (la->start < lb->end &&
973 /* entries are ordered
974 * one entry is earlier than the other
975 * that earlier entry will be moved forward
977 if (la->start < lb->start)
979 /* order: A B, move A forward
980 * check if we hit the end with A
985 else /* if (lb->start < la->start) actually <= */
987 /* order: B A, move B forward
988 * check if we hit the end with B
997 /***********************************************************************
1001 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
1003 ir_instr *in = ir_instr_new(self, op);
1007 if (target->store == store_value &&
1008 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1010 irerror(self->context, "cannot store to an SSA value\n");
1011 irerror(self->context, "trying to store: %s <- %s\n", target->name, what->name);
1012 irerror(self->context, "instruction: %s\n", asm_instr[op].m);
1016 if (!ir_instr_op(in, 0, target, true) ||
1017 !ir_instr_op(in, 1, what, false) ||
1018 !ir_block_instr_add(self, in) )
1025 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
1029 if (target->vtype == TYPE_VARIANT)
1030 vtype = what->vtype;
1032 vtype = target->vtype;
1035 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1036 op = INSTR_CONV_ITOF;
1037 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1038 op = INSTR_CONV_FTOI;
1040 op = type_store_instr[vtype];
1042 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1043 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1047 return ir_block_create_store_op(self, op, target, what);
1050 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
1055 if (target->vtype != TYPE_POINTER)
1058 /* storing using pointer - target is a pointer, type must be
1059 * inferred from source
1061 vtype = what->vtype;
1063 op = type_storep_instr[vtype];
1064 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1065 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1066 op = INSTR_STOREP_V;
1069 return ir_block_create_store_op(self, op, target, what);
1072 bool ir_block_create_return(ir_block *self, ir_value *v)
1076 irerror(self->context, "block already ended (%s)\n", self->label);
1080 self->is_return = true;
1081 in = ir_instr_new(self, INSTR_RETURN);
1085 if (v && !ir_instr_op(in, 0, v, false))
1088 if (!ir_block_instr_add(self, in))
1093 bool ir_block_create_if(ir_block *self, ir_value *v,
1094 ir_block *ontrue, ir_block *onfalse)
1098 irerror(self->context, "block already ended (%s)\n", self->label);
1102 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1103 in = ir_instr_new(self, VINSTR_COND);
1107 if (!ir_instr_op(in, 0, v, false)) {
1108 ir_instr_delete(in);
1112 in->bops[0] = ontrue;
1113 in->bops[1] = onfalse;
1115 if (!ir_block_instr_add(self, in))
1118 if (!ir_block_exits_add(self, ontrue) ||
1119 !ir_block_exits_add(self, onfalse) ||
1120 !ir_block_entries_add(ontrue, self) ||
1121 !ir_block_entries_add(onfalse, self) )
1128 bool ir_block_create_jump(ir_block *self, ir_block *to)
1132 irerror(self->context, "block already ended (%s)\n", self->label);
1136 in = ir_instr_new(self, VINSTR_JUMP);
1141 if (!ir_block_instr_add(self, in))
1144 if (!ir_block_exits_add(self, to) ||
1145 !ir_block_entries_add(to, self) )
1152 bool ir_block_create_goto(ir_block *self, ir_block *to)
1156 irerror(self->context, "block already ended (%s)\n", self->label);
1160 in = ir_instr_new(self, INSTR_GOTO);
1165 if (!ir_block_instr_add(self, in))
1168 if (!ir_block_exits_add(self, to) ||
1169 !ir_block_entries_add(to, self) )
1176 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1180 in = ir_instr_new(self, VINSTR_PHI);
1183 out = ir_value_out(self->owner, label, store_value, ot);
1185 ir_instr_delete(in);
1188 if (!ir_instr_op(in, 0, out, true)) {
1189 ir_instr_delete(in);
1190 ir_value_delete(out);
1193 if (!ir_block_instr_add(self, in)) {
1194 ir_instr_delete(in);
1195 ir_value_delete(out);
1201 ir_value* ir_phi_value(ir_instr *self)
1203 return self->_ops[0];
1206 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1210 if (!ir_block_entries_find(self->owner, b, NULL)) {
1211 /* Must not be possible to cause this, otherwise the AST
1212 * is doing something wrong.
1214 irerror(self->context, "Invalid entry block for PHI\n");
1220 if (!ir_value_reads_add(v, self))
1222 return ir_instr_phi_add(self, pe);
1225 /* call related code */
1226 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1230 in = ir_instr_new(self, INSTR_CALL0);
1233 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1235 ir_instr_delete(in);
1238 if (!ir_instr_op(in, 0, out, true) ||
1239 !ir_instr_op(in, 1, func, false) ||
1240 !ir_block_instr_add(self, in))
1242 ir_instr_delete(in);
1243 ir_value_delete(out);
1249 ir_value* ir_call_value(ir_instr *self)
1251 return self->_ops[0];
1254 bool ir_call_param(ir_instr* self, ir_value *v)
1256 if (!ir_instr_params_add(self, v))
1258 if (!ir_value_reads_add(v, self)) {
1259 if (!ir_instr_params_remove(self, self->params_count-1))
1260 GMQCC_SUPPRESS_EMPTY_BODY;
1266 /* binary op related code */
1268 ir_value* ir_block_create_binop(ir_block *self,
1269 const char *label, int opcode,
1270 ir_value *left, ir_value *right)
1292 case INSTR_SUB_S: /* -- offset of string as float */
1297 case INSTR_BITOR_IF:
1298 case INSTR_BITOR_FI:
1299 case INSTR_BITAND_FI:
1300 case INSTR_BITAND_IF:
1315 case INSTR_BITAND_I:
1318 case INSTR_RSHIFT_I:
1319 case INSTR_LSHIFT_I:
1341 /* boolean operations result in floats */
1342 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1344 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1347 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1352 if (ot == TYPE_VOID) {
1353 /* The AST or parser were supposed to check this! */
1357 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1360 ir_value* ir_block_create_unary(ir_block *self,
1361 const char *label, int opcode,
1364 int ot = TYPE_FLOAT;
1376 /* QC doesn't have other unary operations. We expect extensions to fill
1377 * the above list, otherwise we assume out-type = in-type, eg for an
1381 ot = operand->vtype;
1384 if (ot == TYPE_VOID) {
1385 /* The AST or parser were supposed to check this! */
1389 /* let's use the general instruction creator and pass NULL for OPB */
1390 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1393 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1394 int op, ir_value *a, ir_value *b, int outype)
1399 out = ir_value_out(self->owner, label, store_value, outype);
1403 instr = ir_instr_new(self, op);
1405 ir_value_delete(out);
1409 if (!ir_instr_op(instr, 0, out, true) ||
1410 !ir_instr_op(instr, 1, a, false) ||
1411 !ir_instr_op(instr, 2, b, false) )
1416 if (!ir_block_instr_add(self, instr))
1421 ir_instr_delete(instr);
1422 ir_value_delete(out);
1426 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1430 /* Support for various pointer types todo if so desired */
1431 if (ent->vtype != TYPE_ENTITY)
1434 if (field->vtype != TYPE_FIELD)
1437 v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1438 v->fieldtype = field->fieldtype;
1442 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1445 if (ent->vtype != TYPE_ENTITY)
1448 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1449 if (field->vtype != TYPE_FIELD)
1454 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1455 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1456 case TYPE_STRING: op = INSTR_LOAD_S; break;
1457 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1458 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1459 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1461 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1462 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1468 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1471 ir_value* ir_block_create_add(ir_block *self,
1473 ir_value *left, ir_value *right)
1476 int l = left->vtype;
1477 int r = right->vtype;
1496 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1498 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1504 return ir_block_create_binop(self, label, op, left, right);
1507 ir_value* ir_block_create_sub(ir_block *self,
1509 ir_value *left, ir_value *right)
1512 int l = left->vtype;
1513 int r = right->vtype;
1533 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1535 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1541 return ir_block_create_binop(self, label, op, left, right);
1544 ir_value* ir_block_create_mul(ir_block *self,
1546 ir_value *left, ir_value *right)
1549 int l = left->vtype;
1550 int r = right->vtype;
1569 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1571 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1574 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1576 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1578 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1580 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1586 return ir_block_create_binop(self, label, op, left, right);
1589 ir_value* ir_block_create_div(ir_block *self,
1591 ir_value *left, ir_value *right)
1594 int l = left->vtype;
1595 int r = right->vtype;
1612 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1614 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1616 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1622 return ir_block_create_binop(self, label, op, left, right);
1625 /* PHI resolving breaks the SSA, and must thus be the last
1626 * step before life-range calculation.
1629 static bool ir_block_naive_phi(ir_block *self);
1630 bool ir_function_naive_phi(ir_function *self)
1634 for (i = 0; i < self->blocks_count; ++i)
1636 if (!ir_block_naive_phi(self->blocks[i]))
1642 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1647 /* create a store */
1648 if (!ir_block_create_store(block, old, what))
1651 /* we now move it up */
1652 instr = block->instr[block->instr_count-1];
1653 for (i = block->instr_count; i > iid; --i)
1654 block->instr[i] = block->instr[i-1];
1655 block->instr[i] = instr;
1660 static bool ir_block_naive_phi(ir_block *self)
1663 /* FIXME: optionally, create_phi can add the phis
1664 * to a list so we don't need to loop through blocks
1665 * - anyway: "don't optimize YET"
1667 for (i = 0; i < self->instr_count; ++i)
1669 ir_instr *instr = self->instr[i];
1670 if (instr->opcode != VINSTR_PHI)
1673 if (!ir_block_instr_remove(self, i))
1675 --i; /* NOTE: i+1 below */
1677 for (p = 0; p < instr->phi_count; ++p)
1679 ir_value *v = instr->phi[p].value;
1680 for (w = 0; w < v->writes_count; ++w) {
1683 if (!v->writes[w]->_ops[0])
1686 /* When the write was to a global, we have to emit a mov */
1687 old = v->writes[w]->_ops[0];
1689 /* The original instruction now writes to the PHI target local */
1690 if (v->writes[w]->_ops[0] == v)
1691 v->writes[w]->_ops[0] = instr->_ops[0];
1693 if (old->store != store_value && old->store != store_local && old->store != store_param)
1695 /* If it originally wrote to a global we need to store the value
1698 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1700 if (i+1 < self->instr_count)
1701 instr = self->instr[i+1];
1704 /* In case I forget and access instr later, it'll be NULL
1705 * when it's a problem, to make sure we crash, rather than accessing
1711 /* If it didn't, we can replace all reads by the phi target now. */
1713 for (r = 0; r < old->reads_count; ++r)
1716 ir_instr *ri = old->reads[r];
1717 for (op = 0; op < ri->phi_count; ++op) {
1718 if (ri->phi[op].value == old)
1719 ri->phi[op].value = v;
1721 for (op = 0; op < 3; ++op) {
1722 if (ri->_ops[op] == old)
1729 ir_instr_delete(instr);
1734 /***********************************************************************
1735 *IR Temp allocation code
1736 * Propagating value life ranges by walking through the function backwards
1737 * until no more changes are made.
1738 * In theory this should happen once more than once for every nested loop
1740 * Though this implementation might run an additional time for if nests.
1749 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1751 /* Enumerate instructions used by value's life-ranges
1753 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1757 for (i = 0; i < self->instr_count; ++i)
1759 self->instr[i]->eid = eid++;
1764 /* Enumerate blocks and instructions.
1765 * The block-enumeration is unordered!
1766 * We do not really use the block enumreation, however
1767 * the instruction enumeration is important for life-ranges.
1769 void ir_function_enumerate(ir_function *self)
1772 size_t instruction_id = 0;
1773 for (i = 0; i < self->blocks_count; ++i)
1775 self->blocks[i]->eid = i;
1776 self->blocks[i]->run_id = 0;
1777 ir_block_enumerate(self->blocks[i], &instruction_id);
1781 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1782 bool ir_function_calculate_liferanges(ir_function *self)
1790 for (i = 0; i != self->blocks_count; ++i)
1792 if (self->blocks[i]->is_return)
1794 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1802 /* Local-value allocator
1803 * After finishing creating the liferange of all values used in a function
1804 * we can allocate their global-positions.
1805 * This is the counterpart to register-allocation in register machines.
1808 MEM_VECTOR_MAKE(ir_value*, locals);
1809 MEM_VECTOR_MAKE(size_t, sizes);
1810 MEM_VECTOR_MAKE(size_t, positions);
1811 } function_allocator;
1812 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1813 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1814 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1816 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1819 size_t vsize = type_sizeof[var->vtype];
1821 slot = ir_value_var("reg", store_global, var->vtype);
1825 if (!ir_value_life_merge_into(slot, var))
1828 if (!function_allocator_locals_add(alloc, slot))
1831 if (!function_allocator_sizes_add(alloc, vsize))
1837 ir_value_delete(slot);
1841 bool ir_function_allocate_locals(ir_function *self)
1850 function_allocator alloc;
1852 if (!self->locals_count && !self->values_count)
1855 MEM_VECTOR_INIT(&alloc, locals);
1856 MEM_VECTOR_INIT(&alloc, sizes);
1857 MEM_VECTOR_INIT(&alloc, positions);
1859 for (i = 0; i < self->locals_count; ++i)
1861 if (!function_allocator_alloc(&alloc, self->locals[i]))
1865 /* Allocate a slot for any value that still exists */
1866 for (i = 0; i < self->values_count; ++i)
1868 v = self->values[i];
1873 for (a = 0; a < alloc.locals_count; ++a)
1875 slot = alloc.locals[a];
1877 if (ir_values_overlap(v, slot))
1880 if (!ir_value_life_merge_into(slot, v))
1883 /* adjust size for this slot */
1884 if (alloc.sizes[a] < type_sizeof[v->vtype])
1885 alloc.sizes[a] = type_sizeof[v->vtype];
1887 self->values[i]->code.local = a;
1890 if (a >= alloc.locals_count) {
1891 self->values[i]->code.local = alloc.locals_count;
1892 if (!function_allocator_alloc(&alloc, v))
1897 /* Adjust slot positions based on sizes */
1898 if (!function_allocator_positions_add(&alloc, 0))
1901 if (alloc.sizes_count)
1902 pos = alloc.positions[0] + alloc.sizes[0];
1905 for (i = 1; i < alloc.sizes_count; ++i)
1907 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1908 if (!function_allocator_positions_add(&alloc, pos))
1912 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1914 /* Take over the actual slot positions */
1915 for (i = 0; i < self->values_count; ++i) {
1916 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1924 for (i = 0; i < alloc.locals_count; ++i)
1925 ir_value_delete(alloc.locals[i]);
1926 MEM_VECTOR_CLEAR(&alloc, locals);
1927 MEM_VECTOR_CLEAR(&alloc, sizes);
1928 MEM_VECTOR_CLEAR(&alloc, positions);
1932 /* Get information about which operand
1933 * is read from, or written to.
1935 static void ir_op_read_write(int op, size_t *read, size_t *write)
1955 case INSTR_STOREP_F:
1956 case INSTR_STOREP_V:
1957 case INSTR_STOREP_S:
1958 case INSTR_STOREP_ENT:
1959 case INSTR_STOREP_FLD:
1960 case INSTR_STOREP_FNC:
1971 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1974 bool changed = false;
1976 for (i = 0; i != self->living_count; ++i)
1978 tempbool = ir_value_life_merge(self->living[i], eid);
1981 irerror(self->context, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1983 changed = changed || tempbool;
1988 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1991 /* values which have been read in a previous iteration are now
1992 * in the "living" array even if the previous block doesn't use them.
1993 * So we have to remove whatever does not exist in the previous block.
1994 * They will be re-added on-read, but the liferange merge won't cause
1997 for (i = 0; i < self->living_count; ++i)
1999 if (!ir_block_living_find(prev, self->living[i], NULL)) {
2000 if (!ir_block_living_remove(self, i))
2006 /* Whatever the previous block still has in its living set
2007 * must now be added to ours as well.
2009 for (i = 0; i < prev->living_count; ++i)
2011 if (ir_block_living_find(self, prev->living[i], NULL))
2013 if (!ir_block_living_add(self, prev->living[i]))
2016 irerror(self->contextt from prev: %s\n", self->label, prev->living[i]->_name);
2022 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2028 /* bitmasks which operands are read from or written to */
2030 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2032 new_reads_t new_reads;
2034 char dbg_ind[16] = { '#', '0' };
2037 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2038 MEM_VECTOR_INIT(&new_reads, v);
2043 if (!ir_block_life_prop_previous(self, prev, changed))
2047 i = self->instr_count;
2050 instr = self->instr[i];
2052 /* PHI operands are always read operands */
2053 for (p = 0; p < instr->phi_count; ++p)
2055 value = instr->phi[p].value;
2056 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2057 if (!ir_block_living_find(self, value, NULL) &&
2058 !ir_block_living_add(self, value))
2063 if (!new_reads_t_v_find(&new_reads, value, NULL))
2065 if (!new_reads_t_v_add(&new_reads, value))
2071 /* call params are read operands too */
2072 for (p = 0; p < instr->params_count; ++p)
2074 value = instr->params[p];
2075 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2076 if (!ir_block_living_find(self, value, NULL) &&
2077 !ir_block_living_add(self, value))
2082 if (!new_reads_t_v_find(&new_reads, value, NULL))
2084 if (!new_reads_t_v_add(&new_reads, value))
2090 /* See which operands are read and write operands */
2091 ir_op_read_write(instr->opcode, &read, &write);
2093 /* Go through the 3 main operands */
2094 for (o = 0; o < 3; ++o)
2096 if (!instr->_ops[o]) /* no such operand */
2099 value = instr->_ops[o];
2101 /* We only care about locals */
2102 /* we also calculate parameter liferanges so that locals
2103 * can take up parameter slots */
2104 if (value->store != store_value &&
2105 value->store != store_local &&
2106 value->store != store_param)
2112 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2113 if (!ir_block_living_find(self, value, NULL) &&
2114 !ir_block_living_add(self, value))
2119 /* fprintf(stderr, "read: %s\n", value->_name); */
2120 if (!new_reads_t_v_find(&new_reads, value, NULL))
2122 if (!new_reads_t_v_add(&new_reads, value))
2128 /* write operands */
2129 /* When we write to a local, we consider it "dead" for the
2130 * remaining upper part of the function, since in SSA a value
2131 * can only be written once (== created)
2136 bool in_living = ir_block_living_find(self, value, &idx);
2137 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2139 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
2140 if (!in_living && !in_reads)
2145 /* If the value isn't alive it hasn't been read before... */
2146 /* TODO: See if the warning can be emitted during parsing or AST processing
2147 * otherwise have warning printed here.
2148 * IF printing a warning here: include filecontext_t,
2149 * and make sure it's only printed once
2150 * since this function is run multiple times.
2152 /* For now: debug info: */
2153 /* fprintf(stderr, "Value only written %s\n", value->name); */
2154 tempbool = ir_value_life_merge(value, instr->eid);
2155 *changed = *changed || tempbool;
2157 ir_instr_dump(instr, dbg_ind, printf);
2161 /* since 'living' won't contain it
2162 * anymore, merge the value, since
2165 tempbool = ir_value_life_merge(value, instr->eid);
2168 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2170 *changed = *changed || tempbool;
2172 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2173 if (!ir_block_living_remove(self, idx))
2178 if (!new_reads_t_v_remove(&new_reads, readidx))
2186 tempbool = ir_block_living_add_instr(self, instr->eid);
2187 /*fprintf(stderr, "living added values\n");*/
2188 *changed = *changed || tempbool;
2190 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2192 for (rd = 0; rd < new_reads.v_count; ++rd)
2194 if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
2195 if (!ir_block_living_add(self, new_reads.v[rd]))
2198 if (!i && !self->entries_count) {
2200 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
2203 MEM_VECTOR_CLEAR(&new_reads, v);
2207 if (self->run_id == self->owner->run_id)
2210 self->run_id = self->owner->run_id;
2212 for (i = 0; i < self->entries_count; ++i)
2214 ir_block *entry = self->entries[i];
2215 ir_block_life_propagate(entry, self, changed);
2220 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2221 MEM_VECTOR_CLEAR(&new_reads, v);
2226 /***********************************************************************
2229 * Since the IR has the convention of putting 'write' operands
2230 * at the beginning, we have to rotate the operands of instructions
2231 * properly in order to generate valid QCVM code.
2233 * Having destinations at a fixed position is more convenient. In QC
2234 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2235 * read from from OPA, and store to OPB rather than OPC. Which is
2236 * partially the reason why the implementation of these instructions
2237 * in darkplaces has been delayed for so long.
2239 * Breaking conventions is annoying...
2241 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2243 static bool gen_global_field(ir_value *global)
2245 if (global->isconst)
2247 ir_value *fld = global->constval.vpointer;
2249 irerror(global->context, "Invalid field constant with no field: %s\n", global->name);
2253 /* Now, in this case, a relocation would be impossible to code
2254 * since it looks like this:
2255 * .vector v = origin; <- parse error, wtf is 'origin'?
2258 * But we will need a general relocation support later anyway
2259 * for functions... might as well support that here.
2261 if (!fld->code.globaladdr) {
2262 irerror(global->context, "FIXME: Relocation support\n");
2266 /* copy the field's value */
2267 ir_value_code_setaddr(global, code_globals_add(code_globals_data[fld->code.globaladdr]));
2268 if (global->fieldtype == TYPE_VECTOR) {
2269 code_globals_add(code_globals_data[fld->code.globaladdr]+1);
2270 code_globals_add(code_globals_data[fld->code.globaladdr]+2);
2275 ir_value_code_setaddr(global, code_globals_add(0));
2276 if (global->fieldtype == TYPE_VECTOR) {
2277 code_globals_add(0);
2278 code_globals_add(0);
2281 if (global->code.globaladdr < 0)
2286 static bool gen_global_pointer(ir_value *global)
2288 if (global->isconst)
2290 ir_value *target = global->constval.vpointer;
2292 irerror(global->context, "Invalid pointer constant: %s\n", global->name);
2293 /* NULL pointers are pointing to the NULL constant, which also
2294 * sits at address 0, but still has an ir_value for itself.
2299 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2300 * void() foo; <- proto
2301 * void() *fooptr = &foo;
2302 * void() foo = { code }
2304 if (!target->code.globaladdr) {
2305 /* FIXME: Check for the constant nullptr ir_value!
2306 * because then code.globaladdr being 0 is valid.
2308 irerror(global->context, "FIXME: Relocation support\n");
2312 ir_value_code_setaddr(global, code_globals_add(target->code.globaladdr));
2316 ir_value_code_setaddr(global, code_globals_add(0));
2318 if (global->code.globaladdr < 0)
2323 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2325 prog_section_statement stmt;
2334 block->generated = true;
2335 block->code_start = code_statements_elements;
2336 for (i = 0; i < block->instr_count; ++i)
2338 instr = block->instr[i];
2340 if (instr->opcode == VINSTR_PHI) {
2341 irerror(block->context, "cannot generate virtual instruction (phi)\n");
2345 if (instr->opcode == VINSTR_JUMP) {
2346 target = instr->bops[0];
2347 /* for uncoditional jumps, if the target hasn't been generated
2348 * yet, we generate them right here.
2350 if (!target->generated) {
2355 /* otherwise we generate a jump instruction */
2356 stmt.opcode = INSTR_GOTO;
2357 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2360 if (code_statements_add(stmt) < 0)
2363 /* no further instructions can be in this block */
2367 if (instr->opcode == VINSTR_COND) {
2368 ontrue = instr->bops[0];
2369 onfalse = instr->bops[1];
2370 /* TODO: have the AST signal which block should
2371 * come first: eg. optimize IFs without ELSE...
2374 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2378 if (ontrue->generated) {
2379 stmt.opcode = INSTR_IF;
2380 stmt.o2.s1 = (ontrue->code_start) - code_statements_elements;
2381 if (code_statements_add(stmt) < 0)
2384 if (onfalse->generated) {
2385 stmt.opcode = INSTR_IFNOT;
2386 stmt.o2.s1 = (onfalse->code_start) - code_statements_elements;
2387 if (code_statements_add(stmt) < 0)
2390 if (!ontrue->generated) {
2391 if (onfalse->generated) {
2396 if (!onfalse->generated) {
2397 if (ontrue->generated) {
2402 /* neither ontrue nor onfalse exist */
2403 stmt.opcode = INSTR_IFNOT;
2404 stidx = code_statements_elements;
2405 if (code_statements_add(stmt) < 0)
2407 /* on false we jump, so add ontrue-path */
2408 if (!gen_blocks_recursive(func, ontrue))
2410 /* fixup the jump address */
2411 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2412 /* generate onfalse path */
2413 if (onfalse->generated) {
2414 /* fixup the jump address */
2415 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2416 /* may have been generated in the previous recursive call */
2417 stmt.opcode = INSTR_GOTO;
2418 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2421 return (code_statements_add(stmt) >= 0);
2423 /* if not, generate now */
2428 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2429 /* Trivial call translation:
2430 * copy all params to OFS_PARM*
2431 * if the output's storetype is not store_return,
2432 * add append a STORE instruction!
2434 * NOTES on how to do it better without much trouble:
2435 * -) The liferanges!
2436 * Simply check the liferange of all parameters for
2437 * other CALLs. For each param with no CALL in its
2438 * liferange, we can store it in an OFS_PARM at
2439 * generation already. This would even include later
2440 * reuse.... probably... :)
2445 for (p = 0; p < instr->params_count; ++p)
2447 ir_value *param = instr->params[p];
2449 stmt.opcode = INSTR_STORE_F;
2452 stmt.opcode = type_store_instr[param->vtype];
2453 stmt.o1.u1 = ir_value_code_addr(param);
2454 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2455 if (code_statements_add(stmt) < 0)
2458 stmt.opcode = INSTR_CALL0 + instr->params_count;
2459 if (stmt.opcode > INSTR_CALL8)
2460 stmt.opcode = INSTR_CALL8;
2461 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2464 if (code_statements_add(stmt) < 0)
2467 retvalue = instr->_ops[0];
2468 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2470 /* not to be kept in OFS_RETURN */
2471 stmt.opcode = type_store_instr[retvalue->vtype];
2472 stmt.o1.u1 = OFS_RETURN;
2473 stmt.o2.u1 = ir_value_code_addr(retvalue);
2475 if (code_statements_add(stmt) < 0)
2481 if (instr->opcode == INSTR_STATE) {
2482 irerror(block->context, "TODO: state instruction\n");
2486 stmt.opcode = instr->opcode;
2491 /* This is the general order of operands */
2493 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2496 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2499 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2501 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2503 stmt.o1.u1 = stmt.o3.u1;
2506 else if ((stmt.opcode >= INSTR_STORE_F &&
2507 stmt.opcode <= INSTR_STORE_FNC) ||
2508 (stmt.opcode >= INSTR_STOREP_F &&
2509 stmt.opcode <= INSTR_STOREP_FNC))
2511 /* 2-operand instructions with A -> B */
2512 stmt.o2.u1 = stmt.o3.u1;
2516 if (code_statements_add(stmt) < 0)
2522 static bool gen_function_code(ir_function *self)
2525 prog_section_statement stmt;
2527 /* Starting from entry point, we generate blocks "as they come"
2528 * for now. Dead blocks will not be translated obviously.
2530 if (!self->blocks_count) {
2531 irerror(self->context, "Function '%s' declared without body.\n", self->name);
2535 block = self->blocks[0];
2536 if (block->generated)
2539 if (!gen_blocks_recursive(self, block)) {
2540 irerror(self->context, "failed to generate blocks for '%s'\n", self->name);
2544 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2545 stmt.opcode = AINSTR_END;
2549 if (code_statements_add(stmt) < 0)
2554 static bool gen_global_function(ir_builder *ir, ir_value *global)
2556 prog_section_function fun;
2560 size_t local_var_end;
2562 if (!global->isconst || (!global->constval.vfunc))
2564 irerror(global->context, "Invalid state of function-global: not constant: %s\n", global->name);
2568 irfun = global->constval.vfunc;
2570 fun.name = global->code.name;
2571 fun.file = code_cachedstring(global->context.file);
2572 fun.profile = 0; /* always 0 */
2573 fun.nargs = irfun->params_count;
2575 for (i = 0;i < 8; ++i) {
2579 fun.argsize[i] = type_sizeof[irfun->params[i]];
2582 fun.firstlocal = code_globals_elements;
2583 fun.locals = irfun->allocated_locals + irfun->locals_count;
2585 local_var_end = fun.firstlocal;
2586 for (i = 0; i < irfun->locals_count; ++i) {
2587 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2588 irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
2592 if (irfun->locals_count) {
2593 ir_value *last = irfun->locals[irfun->locals_count-1];
2594 local_var_end = last->code.globaladdr;
2595 local_var_end += type_sizeof[last->vtype];
2597 for (i = 0; i < irfun->values_count; ++i)
2599 /* generate code.globaladdr for ssa values */
2600 ir_value *v = irfun->values[i];
2601 ir_value_code_setaddr(v, local_var_end + v->code.local);
2603 for (i = 0; i < irfun->allocated_locals; ++i) {
2604 /* fill the locals with zeros */
2605 code_globals_add(0);
2609 fun.entry = irfun->builtin;
2611 irfun->code_function_def = code_functions_elements;
2612 fun.entry = code_statements_elements;
2613 /* done in second pass: gen_global_function_code!
2614 if (!gen_function_code(irfun)) {
2615 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
2621 return (code_functions_add(fun) >= 0);
2624 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
2626 prog_section_function *fundef;
2629 irfun = global->constval.vfunc;
2633 if (irfun->code_function_def < 0) {
2634 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
2637 fundef = &code_functions_data[irfun->code_function_def];
2639 fundef->entry = code_statements_elements;
2640 if (!gen_function_code(irfun)) {
2641 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
2647 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2651 prog_section_def def;
2653 def.type = global->vtype;
2654 def.offset = code_globals_elements;
2655 def.name = global->code.name = code_genstring(global->name);
2657 switch (global->vtype)
2660 if (code_defs_add(def) < 0)
2662 return gen_global_pointer(global);
2664 if (code_defs_add(def) < 0)
2666 return gen_global_field(global);
2671 if (code_defs_add(def) < 0)
2674 if (global->isconst) {
2675 iptr = (int32_t*)&global->constval.vfloat;
2676 ir_value_code_setaddr(global, code_globals_add(*iptr));
2678 ir_value_code_setaddr(global, code_globals_add(0));
2680 return global->code.globaladdr >= 0;
2684 if (code_defs_add(def) < 0)
2686 if (global->isconst)
2687 ir_value_code_setaddr(global, code_globals_add(code_cachedstring(global->constval.vstring)));
2689 ir_value_code_setaddr(global, code_globals_add(0));
2690 return global->code.globaladdr >= 0;
2695 if (code_defs_add(def) < 0)
2698 if (global->isconst) {
2699 iptr = (int32_t*)&global->constval.vvec;
2700 ir_value_code_setaddr(global, code_globals_add(iptr[0]));
2701 if (global->code.globaladdr < 0)
2703 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2705 if (code_globals_add(iptr[d]) < 0)
2709 ir_value_code_setaddr(global, code_globals_add(0));
2710 if (global->code.globaladdr < 0)
2712 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2714 if (code_globals_add(0) < 0)
2718 return global->code.globaladdr >= 0;
2721 if (code_defs_add(def) < 0)
2723 ir_value_code_setaddr(global, code_globals_elements);
2724 code_globals_add(code_functions_elements);
2725 return gen_global_function(self, global);
2727 /* assume biggest type */
2728 ir_value_code_setaddr(global, code_globals_add(0));
2729 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2730 code_globals_add(0);
2733 /* refuse to create 'void' type or any other fancy business. */
2734 irerror(global->context, "Invalid type for global variable %s\n", global->name);
2739 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2741 prog_section_def def;
2742 prog_section_field fld;
2744 def.type = field->vtype;
2745 def.offset = code_globals_elements;
2747 /* create a global named the same as the field */
2748 if (opts_standard == COMPILER_GMQCC) {
2749 /* in our standard, the global gets a dot prefix */
2750 size_t len = strlen(field->name);
2753 /* we really don't want to have to allocate this, and 1024
2754 * bytes is more than enough for a variable/field name
2756 if (len+2 >= sizeof(name)) {
2757 irerror(field->context, "invalid field name size: %u\n", (unsigned int)len);
2762 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
2765 def.name = code_genstring(name);
2766 fld.name = def.name + 1; /* we reuse that string table entry */
2768 /* in plain QC, there cannot be a global with the same name,
2769 * and so we also name the global the same.
2770 * FIXME: fteqcc should create a global as well
2771 * check if it actually uses the same name. Probably does
2773 def.name = code_genstring(field->name);
2774 fld.name = def.name;
2777 field->code.name = def.name;
2779 if (code_defs_add(def) < 0)
2782 fld.type = field->fieldtype;
2784 if (fld.type == TYPE_VOID) {
2785 irerror(field->context, "field is missing a type: %s - don't know its size\n", field->name);
2789 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2791 if (code_fields_add(fld) < 0)
2794 ir_value_code_setaddr(field, code_globals_elements);
2795 if (!code_globals_add(fld.offset))
2797 if (fld.type == TYPE_VECTOR) {
2798 if (!code_globals_add(fld.offset+1))
2800 if (!code_globals_add(fld.offset+2))
2804 return field->code.globaladdr >= 0;
2807 bool ir_builder_generate(ir_builder *self, const char *filename)
2813 for (i = 0; i < self->fields_count; ++i)
2815 if (!ir_builder_gen_field(self, self->fields[i])) {
2820 for (i = 0; i < self->globals_count; ++i)
2822 if (!ir_builder_gen_global(self, self->globals[i])) {
2827 /* generate function code */
2828 for (i = 0; i < self->globals_count; ++i)
2830 if (self->globals[i]->vtype == TYPE_FUNCTION) {
2831 if (!gen_global_function_code(self, self->globals[i])) {
2837 printf("writing '%s'...\n", filename);
2838 return code_write(filename);
2841 /***********************************************************************
2842 *IR DEBUG Dump functions...
2845 #define IND_BUFSZ 1024
2848 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
2850 # define strncat strncat
2853 const char *qc_opname(int op)
2855 if (op < 0) return "<INVALID>";
2856 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2857 return asm_instr[op].m;
2859 case VINSTR_PHI: return "PHI";
2860 case VINSTR_JUMP: return "JUMP";
2861 case VINSTR_COND: return "COND";
2862 default: return "<UNK>";
2866 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2869 char indent[IND_BUFSZ];
2873 oprintf("module %s\n", b->name);
2874 for (i = 0; i < b->globals_count; ++i)
2877 if (b->globals[i]->isconst)
2878 oprintf("%s = ", b->globals[i]->name);
2879 ir_value_dump(b->globals[i], oprintf);
2882 for (i = 0; i < b->functions_count; ++i)
2883 ir_function_dump(b->functions[i], indent, oprintf);
2884 oprintf("endmodule %s\n", b->name);
2887 void ir_function_dump(ir_function *f, char *ind,
2888 int (*oprintf)(const char*, ...))
2891 if (f->builtin != 0) {
2892 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2895 oprintf("%sfunction %s\n", ind, f->name);
2896 strncat(ind, "\t", IND_BUFSZ);
2897 if (f->locals_count)
2899 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2900 for (i = 0; i < f->locals_count; ++i) {
2901 oprintf("%s\t", ind);
2902 ir_value_dump(f->locals[i], oprintf);
2906 if (f->blocks_count)
2908 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2909 for (i = 0; i < f->blocks_count; ++i) {
2910 if (f->blocks[i]->run_id != f->run_id) {
2911 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2913 ir_block_dump(f->blocks[i], ind, oprintf);
2917 ind[strlen(ind)-1] = 0;
2918 oprintf("%sendfunction %s\n", ind, f->name);
2921 void ir_block_dump(ir_block* b, char *ind,
2922 int (*oprintf)(const char*, ...))
2925 oprintf("%s:%s\n", ind, b->label);
2926 strncat(ind, "\t", IND_BUFSZ);
2928 for (i = 0; i < b->instr_count; ++i)
2929 ir_instr_dump(b->instr[i], ind, oprintf);
2930 ind[strlen(ind)-1] = 0;
2933 void dump_phi(ir_instr *in, char *ind,
2934 int (*oprintf)(const char*, ...))
2937 oprintf("%s <- phi ", in->_ops[0]->name);
2938 for (i = 0; i < in->phi_count; ++i)
2940 oprintf("([%s] : %s) ", in->phi[i].from->label,
2941 in->phi[i].value->name);
2946 void ir_instr_dump(ir_instr *in, char *ind,
2947 int (*oprintf)(const char*, ...))
2950 const char *comma = NULL;
2952 oprintf("%s (%i) ", ind, (int)in->eid);
2954 if (in->opcode == VINSTR_PHI) {
2955 dump_phi(in, ind, oprintf);
2959 strncat(ind, "\t", IND_BUFSZ);
2961 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2962 ir_value_dump(in->_ops[0], oprintf);
2963 if (in->_ops[1] || in->_ops[2])
2966 if (in->opcode == INSTR_CALL0) {
2967 oprintf("CALL%i\t", in->params_count);
2969 oprintf("%s\t", qc_opname(in->opcode));
2971 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2972 ir_value_dump(in->_ops[0], oprintf);
2977 for (i = 1; i != 3; ++i) {
2981 ir_value_dump(in->_ops[i], oprintf);
2989 oprintf("[%s]", in->bops[0]->label);
2993 oprintf("%s[%s]", comma, in->bops[1]->label);
2995 ind[strlen(ind)-1] = 0;
2998 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3007 oprintf("(function)");
3010 oprintf("%g", v->constval.vfloat);
3013 oprintf("'%g %g %g'",
3016 v->constval.vvec.z);
3019 oprintf("(entity)");
3022 oprintf("\"%s\"", v->constval.vstring);
3026 oprintf("%i", v->constval.vint);
3031 v->constval.vpointer->name);
3035 oprintf("%s", v->name);
3039 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
3042 oprintf("Life of %s:\n", self->name);
3043 for (i = 0; i < self->life_count; ++i)
3045 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);