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, fields);
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));
310 if (!ir_function_set_name(self, "<@unnamed>")) {
315 self->context.file = "<@no context>";
316 self->context.line = 0;
317 self->outtype = outtype;
320 MEM_VECTOR_INIT(self, params);
321 MEM_VECTOR_INIT(self, blocks);
322 MEM_VECTOR_INIT(self, values);
323 MEM_VECTOR_INIT(self, locals);
328 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
329 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
330 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
331 MEM_VEC_FUNCTIONS(ir_function, int, params)
333 bool ir_function_set_name(ir_function *self, const char *name)
336 mem_d((void*)self->name);
337 self->name = util_strdup(name);
341 void ir_function_delete(ir_function *self)
344 mem_d((void*)self->name);
346 for (i = 0; i != self->blocks_count; ++i)
347 ir_block_delete(self->blocks[i]);
348 MEM_VECTOR_CLEAR(self, blocks);
350 MEM_VECTOR_CLEAR(self, params);
352 for (i = 0; i != self->values_count; ++i)
353 ir_value_delete(self->values[i]);
354 MEM_VECTOR_CLEAR(self, values);
356 for (i = 0; i != self->locals_count; ++i)
357 ir_value_delete(self->locals[i]);
358 MEM_VECTOR_CLEAR(self, locals);
360 /* self->value is deleted by the builder */
365 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
367 return ir_function_values_add(self, v);
370 ir_block* ir_function_create_block(ir_function *self, const char *label)
372 ir_block* bn = ir_block_new(self, label);
373 memcpy(&bn->context, &self->context, sizeof(self->context));
374 if (!ir_function_blocks_add(self, bn)) {
381 bool ir_function_finalize(ir_function *self)
386 if (!ir_function_naive_phi(self))
389 ir_function_enumerate(self);
391 if (!ir_function_calculate_liferanges(self))
394 if (!ir_function_allocate_locals(self))
399 ir_value* ir_function_get_local(ir_function *self, const char *name)
402 for (i = 0; i < self->locals_count; ++i) {
403 if (!strcmp(self->locals[i]->name, name))
404 return self->locals[i];
409 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
411 ir_value *ve = ir_function_get_local(self, name);
417 self->locals_count &&
418 self->locals[self->locals_count-1]->store != store_param) {
419 irerror(self->context, "cannot add parameters after adding locals\n");
423 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
424 if (!ir_function_locals_add(self, ve)) {
431 /***********************************************************************
435 ir_block* ir_block_new(ir_function* owner, const char *name)
438 self = (ir_block*)mem_a(sizeof(*self));
442 memset(self, 0, sizeof(*self));
445 if (!ir_block_set_label(self, name)) {
450 self->context.file = "<@no context>";
451 self->context.line = 0;
453 MEM_VECTOR_INIT(self, instr);
454 MEM_VECTOR_INIT(self, entries);
455 MEM_VECTOR_INIT(self, exits);
458 self->is_return = false;
460 MEM_VECTOR_INIT(self, living);
462 self->generated = false;
466 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
467 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
468 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
469 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
471 void ir_block_delete(ir_block* self)
475 for (i = 0; i != self->instr_count; ++i)
476 ir_instr_delete(self->instr[i]);
477 MEM_VECTOR_CLEAR(self, instr);
478 MEM_VECTOR_CLEAR(self, entries);
479 MEM_VECTOR_CLEAR(self, exits);
480 MEM_VECTOR_CLEAR(self, living);
484 bool ir_block_set_label(ir_block *self, const char *name)
487 mem_d((void*)self->label);
488 self->label = util_strdup(name);
489 return !!self->label;
492 /***********************************************************************
496 ir_instr* ir_instr_new(ir_block* owner, int op)
499 self = (ir_instr*)mem_a(sizeof(*self));
504 self->context.file = "<@no context>";
505 self->context.line = 0;
507 self->_ops[0] = NULL;
508 self->_ops[1] = NULL;
509 self->_ops[2] = NULL;
510 self->bops[0] = NULL;
511 self->bops[1] = NULL;
512 MEM_VECTOR_INIT(self, phi);
513 MEM_VECTOR_INIT(self, params);
518 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
519 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
521 void ir_instr_delete(ir_instr *self)
524 /* The following calls can only delete from
525 * vectors, we still want to delete this instruction
526 * so ignore the return value. Since with the warn_unused_result attribute
527 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
528 * I have to improvise here and use if(foo());
530 for (i = 0; i < self->phi_count; ++i) {
532 if (ir_value_writes_find(self->phi[i].value, self, &idx))
533 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
534 if (ir_value_reads_find(self->phi[i].value, self, &idx))
535 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
537 MEM_VECTOR_CLEAR(self, phi);
538 for (i = 0; i < self->params_count; ++i) {
540 if (ir_value_writes_find(self->params[i], self, &idx))
541 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
542 if (ir_value_reads_find(self->params[i], self, &idx))
543 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
545 MEM_VECTOR_CLEAR(self, params);
546 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
547 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
548 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
552 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
554 if (self->_ops[op]) {
556 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
558 if (!ir_value_writes_remove(self->_ops[op], idx))
561 else if (ir_value_reads_find(self->_ops[op], self, &idx))
563 if (!ir_value_reads_remove(self->_ops[op], idx))
569 if (!ir_value_writes_add(v, self))
572 if (!ir_value_reads_add(v, self))
580 /***********************************************************************
584 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
586 self->code.globaladdr = gaddr;
587 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
588 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
589 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
592 int32_t ir_value_code_addr(const ir_value *self)
594 if (self->store == store_return)
595 return OFS_RETURN + self->code.addroffset;
596 return self->code.globaladdr + self->code.addroffset;
599 ir_value* ir_value_var(const char *name, int storetype, int vtype)
602 self = (ir_value*)mem_a(sizeof(*self));
604 self->fieldtype = TYPE_VOID;
605 self->outtype = TYPE_VOID;
606 self->store = storetype;
607 MEM_VECTOR_INIT(self, reads);
608 MEM_VECTOR_INIT(self, writes);
609 self->isconst = false;
610 self->context.file = "<@no context>";
611 self->context.line = 0;
613 ir_value_set_name(self, name);
615 memset(&self->constval, 0, sizeof(self->constval));
616 memset(&self->code, 0, sizeof(self->code));
618 self->members[0] = NULL;
619 self->members[1] = NULL;
620 self->members[2] = NULL;
622 MEM_VECTOR_INIT(self, life);
626 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
632 if (self->members[member])
633 return self->members[member];
635 if (self->vtype == TYPE_VECTOR)
637 m = ir_value_var(self->name, self->store, TYPE_FLOAT);
640 m->context = self->context;
642 self->members[member] = m;
643 m->code.addroffset = member;
645 else if (self->vtype == TYPE_FIELD)
647 if (self->fieldtype != TYPE_VECTOR)
649 m = ir_value_var(self->name, self->store, TYPE_FIELD);
652 m->fieldtype = TYPE_FLOAT;
653 m->context = self->context;
655 self->members[member] = m;
656 m->code.addroffset = member;
660 irerror(self->context, "invalid member access on %s\n", self->name);
667 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
668 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
669 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
671 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
673 ir_value *v = ir_value_var(name, storetype, vtype);
676 if (!ir_function_collect_value(owner, v))
684 void ir_value_delete(ir_value* self)
688 mem_d((void*)self->name);
691 if (self->vtype == TYPE_STRING)
692 mem_d((void*)self->constval.vstring);
694 for (i = 0; i < 3; ++i) {
695 if (self->members[i])
696 ir_value_delete(self->members[i]);
698 MEM_VECTOR_CLEAR(self, reads);
699 MEM_VECTOR_CLEAR(self, writes);
700 MEM_VECTOR_CLEAR(self, life);
704 void ir_value_set_name(ir_value *self, const char *name)
707 mem_d((void*)self->name);
708 self->name = util_strdup(name);
711 bool ir_value_set_float(ir_value *self, float f)
713 if (self->vtype != TYPE_FLOAT)
715 self->constval.vfloat = f;
716 self->isconst = true;
720 bool ir_value_set_func(ir_value *self, int f)
722 if (self->vtype != TYPE_FUNCTION)
724 self->constval.vint = f;
725 self->isconst = true;
729 bool ir_value_set_vector(ir_value *self, vector v)
731 if (self->vtype != TYPE_VECTOR)
733 self->constval.vvec = v;
734 self->isconst = true;
738 bool ir_value_set_field(ir_value *self, ir_value *fld)
740 if (self->vtype != TYPE_FIELD)
742 self->constval.vpointer = fld;
743 self->isconst = true;
747 bool ir_value_set_string(ir_value *self, const char *str)
749 if (self->vtype != TYPE_STRING)
751 self->constval.vstring = util_strdup(str);
752 self->isconst = true;
757 bool ir_value_set_int(ir_value *self, int i)
759 if (self->vtype != TYPE_INTEGER)
761 self->constval.vint = i;
762 self->isconst = true;
767 bool ir_value_lives(ir_value *self, size_t at)
770 for (i = 0; i < self->life_count; ++i)
772 ir_life_entry_t *life = &self->life[i];
773 if (life->start <= at && at <= life->end)
775 if (life->start > at) /* since it's ordered */
781 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
784 if (!ir_value_life_add(self, e)) /* naive... */
786 for (k = self->life_count-1; k > idx; --k)
787 self->life[k] = self->life[k-1];
792 bool ir_value_life_merge(ir_value *self, size_t s)
795 ir_life_entry_t *life = NULL;
796 ir_life_entry_t *before = NULL;
797 ir_life_entry_t new_entry;
799 /* Find the first range >= s */
800 for (i = 0; i < self->life_count; ++i)
803 life = &self->life[i];
807 /* nothing found? append */
808 if (i == self->life_count) {
810 if (life && life->end+1 == s)
812 /* previous life range can be merged in */
816 if (life && life->end >= s)
819 if (!ir_value_life_add(self, e))
820 return false; /* failing */
826 if (before->end + 1 == s &&
827 life->start - 1 == s)
830 before->end = life->end;
831 if (!ir_value_life_remove(self, i))
832 return false; /* failing */
835 if (before->end + 1 == s)
841 /* already contained */
842 if (before->end >= s)
846 if (life->start - 1 == s)
851 /* insert a new entry */
852 new_entry.start = new_entry.end = s;
853 return ir_value_life_insert(self, i, new_entry);
856 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
860 if (!other->life_count)
863 if (!self->life_count) {
864 for (i = 0; i < other->life_count; ++i) {
865 if (!ir_value_life_add(self, other->life[i]))
872 for (i = 0; i < other->life_count; ++i)
874 const ir_life_entry_t *life = &other->life[i];
877 ir_life_entry_t *entry = &self->life[myi];
879 if (life->end+1 < entry->start)
881 /* adding an interval before entry */
882 if (!ir_value_life_insert(self, myi, *life))
888 if (life->start < entry->start &&
889 life->end >= entry->start)
891 /* starts earlier and overlaps */
892 entry->start = life->start;
895 if (life->end > entry->end &&
896 life->start-1 <= entry->end)
898 /* ends later and overlaps */
899 entry->end = life->end;
902 /* see if our change combines it with the next ranges */
903 while (myi+1 < self->life_count &&
904 entry->end+1 >= self->life[1+myi].start)
906 /* overlaps with (myi+1) */
907 if (entry->end < self->life[1+myi].end)
908 entry->end = self->life[1+myi].end;
909 if (!ir_value_life_remove(self, myi+1))
911 entry = &self->life[myi];
914 /* see if we're after the entry */
915 if (life->start > entry->end)
918 /* append if we're at the end */
919 if (myi >= self->life_count) {
920 if (!ir_value_life_add(self, *life))
924 /* otherweise check the next range */
933 bool ir_values_overlap(const ir_value *a, const ir_value *b)
935 /* For any life entry in A see if it overlaps with
936 * any life entry in B.
937 * Note that the life entries are orderes, so we can make a
938 * more efficient algorithm there than naively translating the
942 ir_life_entry_t *la, *lb, *enda, *endb;
944 /* first of all, if either has no life range, they cannot clash */
945 if (!a->life_count || !b->life_count)
950 enda = la + a->life_count;
951 endb = lb + b->life_count;
954 /* check if the entries overlap, for that,
955 * both must start before the other one ends.
957 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
958 if (la->start <= lb->end &&
959 lb->start <= la->end)
961 if (la->start < lb->end &&
968 /* entries are ordered
969 * one entry is earlier than the other
970 * that earlier entry will be moved forward
972 if (la->start < lb->start)
974 /* order: A B, move A forward
975 * check if we hit the end with A
980 else if (lb->start < la->start)
982 /* order: B A, move B forward
983 * check if we hit the end with B
992 /***********************************************************************
996 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
998 ir_instr *in = ir_instr_new(self, op);
1002 if (target->store == store_value &&
1003 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1005 irerror(self->context, "cannot store to an SSA value\n");
1006 irerror(self->context, "trying to store: %s <- %s\n", target->name, what->name);
1007 irerror(self->context, "instruction: %s\n", asm_instr[op].m);
1011 if (!ir_instr_op(in, 0, target, true) ||
1012 !ir_instr_op(in, 1, what, false) ||
1013 !ir_block_instr_add(self, in) )
1020 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
1024 if (target->vtype == TYPE_VARIANT)
1025 vtype = what->vtype;
1027 vtype = target->vtype;
1030 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1031 op = INSTR_CONV_ITOF;
1032 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1033 op = INSTR_CONV_FTOI;
1035 op = type_store_instr[vtype];
1037 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1038 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1042 return ir_block_create_store_op(self, op, target, what);
1045 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
1050 if (target->vtype != TYPE_POINTER)
1053 /* storing using pointer - target is a pointer, type must be
1054 * inferred from source
1056 vtype = what->vtype;
1058 op = type_storep_instr[vtype];
1059 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1060 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1061 op = INSTR_STOREP_V;
1064 return ir_block_create_store_op(self, op, target, what);
1067 bool ir_block_create_return(ir_block *self, ir_value *v)
1071 irerror(self->context, "block already ended (%s)\n", self->label);
1075 self->is_return = true;
1076 in = ir_instr_new(self, INSTR_RETURN);
1080 if (!ir_instr_op(in, 0, v, false) ||
1081 !ir_block_instr_add(self, in) )
1088 bool ir_block_create_if(ir_block *self, ir_value *v,
1089 ir_block *ontrue, ir_block *onfalse)
1093 irerror(self->context, "block already ended (%s)\n", self->label);
1097 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1098 in = ir_instr_new(self, VINSTR_COND);
1102 if (!ir_instr_op(in, 0, v, false)) {
1103 ir_instr_delete(in);
1107 in->bops[0] = ontrue;
1108 in->bops[1] = onfalse;
1110 if (!ir_block_instr_add(self, in))
1113 if (!ir_block_exits_add(self, ontrue) ||
1114 !ir_block_exits_add(self, onfalse) ||
1115 !ir_block_entries_add(ontrue, self) ||
1116 !ir_block_entries_add(onfalse, self) )
1123 bool ir_block_create_jump(ir_block *self, ir_block *to)
1127 irerror(self->context, "block already ended (%s)\n", self->label);
1131 in = ir_instr_new(self, VINSTR_JUMP);
1136 if (!ir_block_instr_add(self, in))
1139 if (!ir_block_exits_add(self, to) ||
1140 !ir_block_entries_add(to, self) )
1147 bool ir_block_create_goto(ir_block *self, ir_block *to)
1151 irerror(self->context, "block already ended (%s)\n", self->label);
1155 in = ir_instr_new(self, INSTR_GOTO);
1160 if (!ir_block_instr_add(self, in))
1163 if (!ir_block_exits_add(self, to) ||
1164 !ir_block_entries_add(to, self) )
1171 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1175 in = ir_instr_new(self, VINSTR_PHI);
1178 out = ir_value_out(self->owner, label, store_value, ot);
1180 ir_instr_delete(in);
1183 if (!ir_instr_op(in, 0, out, true)) {
1184 ir_instr_delete(in);
1185 ir_value_delete(out);
1188 if (!ir_block_instr_add(self, in)) {
1189 ir_instr_delete(in);
1190 ir_value_delete(out);
1196 ir_value* ir_phi_value(ir_instr *self)
1198 return self->_ops[0];
1201 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1205 if (!ir_block_entries_find(self->owner, b, NULL)) {
1206 /* Must not be possible to cause this, otherwise the AST
1207 * is doing something wrong.
1209 irerror(self->context, "Invalid entry block for PHI\n");
1215 if (!ir_value_reads_add(v, self))
1217 return ir_instr_phi_add(self, pe);
1220 /* call related code */
1221 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1225 in = ir_instr_new(self, INSTR_CALL0);
1228 out = ir_value_out(self->owner, label, store_return, func->outtype);
1230 ir_instr_delete(in);
1233 if (!ir_instr_op(in, 0, out, true) ||
1234 !ir_instr_op(in, 1, func, false) ||
1235 !ir_block_instr_add(self, in))
1237 ir_instr_delete(in);
1238 ir_value_delete(out);
1244 ir_value* ir_call_value(ir_instr *self)
1246 return self->_ops[0];
1249 bool ir_call_param(ir_instr* self, ir_value *v)
1251 if (!ir_instr_params_add(self, v))
1253 if (!ir_value_reads_add(v, self)) {
1254 if (!ir_instr_params_remove(self, self->params_count-1))
1255 GMQCC_SUPPRESS_EMPTY_BODY;
1261 /* binary op related code */
1263 ir_value* ir_block_create_binop(ir_block *self,
1264 const char *label, int opcode,
1265 ir_value *left, ir_value *right)
1287 case INSTR_SUB_S: /* -- offset of string as float */
1292 case INSTR_BITOR_IF:
1293 case INSTR_BITOR_FI:
1294 case INSTR_BITAND_FI:
1295 case INSTR_BITAND_IF:
1310 case INSTR_BITAND_I:
1313 case INSTR_RSHIFT_I:
1314 case INSTR_LSHIFT_I:
1336 /* boolean operations result in floats */
1337 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1339 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1342 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1347 if (ot == TYPE_VOID) {
1348 /* The AST or parser were supposed to check this! */
1352 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1355 ir_value* ir_block_create_unary(ir_block *self,
1356 const char *label, int opcode,
1359 int ot = TYPE_FLOAT;
1371 /* QC doesn't have other unary operations. We expect extensions to fill
1372 * the above list, otherwise we assume out-type = in-type, eg for an
1376 ot = operand->vtype;
1379 if (ot == TYPE_VOID) {
1380 /* The AST or parser were supposed to check this! */
1384 /* let's use the general instruction creator and pass NULL for OPB */
1385 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1388 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1389 int op, ir_value *a, ir_value *b, int outype)
1394 out = ir_value_out(self->owner, label, store_value, outype);
1398 instr = ir_instr_new(self, op);
1400 ir_value_delete(out);
1404 if (!ir_instr_op(instr, 0, out, true) ||
1405 !ir_instr_op(instr, 1, a, false) ||
1406 !ir_instr_op(instr, 2, b, false) )
1411 if (!ir_block_instr_add(self, instr))
1416 ir_instr_delete(instr);
1417 ir_value_delete(out);
1421 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1425 /* Support for various pointer types todo if so desired */
1426 if (ent->vtype != TYPE_ENTITY)
1429 if (field->vtype != TYPE_FIELD)
1432 v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1433 v->fieldtype = field->fieldtype;
1437 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1440 if (ent->vtype != TYPE_ENTITY)
1443 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1444 if (field->vtype != TYPE_FIELD)
1449 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1450 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1451 case TYPE_STRING: op = INSTR_LOAD_S; break;
1452 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1453 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1455 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1456 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1462 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1465 ir_value* ir_block_create_add(ir_block *self,
1467 ir_value *left, ir_value *right)
1470 int l = left->vtype;
1471 int r = right->vtype;
1490 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1492 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1498 return ir_block_create_binop(self, label, op, left, right);
1501 ir_value* ir_block_create_sub(ir_block *self,
1503 ir_value *left, ir_value *right)
1506 int l = left->vtype;
1507 int r = right->vtype;
1527 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1529 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1535 return ir_block_create_binop(self, label, op, left, right);
1538 ir_value* ir_block_create_mul(ir_block *self,
1540 ir_value *left, ir_value *right)
1543 int l = left->vtype;
1544 int r = right->vtype;
1563 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1565 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1568 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1570 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1572 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1574 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1580 return ir_block_create_binop(self, label, op, left, right);
1583 ir_value* ir_block_create_div(ir_block *self,
1585 ir_value *left, ir_value *right)
1588 int l = left->vtype;
1589 int r = right->vtype;
1606 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1608 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1610 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1616 return ir_block_create_binop(self, label, op, left, right);
1619 /* PHI resolving breaks the SSA, and must thus be the last
1620 * step before life-range calculation.
1623 static bool ir_block_naive_phi(ir_block *self);
1624 bool ir_function_naive_phi(ir_function *self)
1628 for (i = 0; i < self->blocks_count; ++i)
1630 if (!ir_block_naive_phi(self->blocks[i]))
1636 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1641 /* create a store */
1642 if (!ir_block_create_store(block, old, what))
1645 /* we now move it up */
1646 instr = block->instr[block->instr_count-1];
1647 for (i = block->instr_count; i > iid; --i)
1648 block->instr[i] = block->instr[i-1];
1649 block->instr[i] = instr;
1654 static bool ir_block_naive_phi(ir_block *self)
1657 /* FIXME: optionally, create_phi can add the phis
1658 * to a list so we don't need to loop through blocks
1659 * - anyway: "don't optimize YET"
1661 for (i = 0; i < self->instr_count; ++i)
1663 ir_instr *instr = self->instr[i];
1664 if (instr->opcode != VINSTR_PHI)
1667 if (!ir_block_instr_remove(self, i))
1669 --i; /* NOTE: i+1 below */
1671 for (p = 0; p < instr->phi_count; ++p)
1673 ir_value *v = instr->phi[p].value;
1674 for (w = 0; w < v->writes_count; ++w) {
1677 if (!v->writes[w]->_ops[0])
1680 /* When the write was to a global, we have to emit a mov */
1681 old = v->writes[w]->_ops[0];
1683 /* The original instruction now writes to the PHI target local */
1684 if (v->writes[w]->_ops[0] == v)
1685 v->writes[w]->_ops[0] = instr->_ops[0];
1687 if (old->store != store_value && old->store != store_local && old->store != store_param)
1689 /* If it originally wrote to a global we need to store the value
1692 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1694 if (i+1 < self->instr_count)
1695 instr = self->instr[i+1];
1698 /* In case I forget and access instr later, it'll be NULL
1699 * when it's a problem, to make sure we crash, rather than accessing
1705 /* If it didn't, we can replace all reads by the phi target now. */
1707 for (r = 0; r < old->reads_count; ++r)
1710 ir_instr *ri = old->reads[r];
1711 for (op = 0; op < ri->phi_count; ++op) {
1712 if (ri->phi[op].value == old)
1713 ri->phi[op].value = v;
1715 for (op = 0; op < 3; ++op) {
1716 if (ri->_ops[op] == old)
1723 ir_instr_delete(instr);
1728 /***********************************************************************
1729 *IR Temp allocation code
1730 * Propagating value life ranges by walking through the function backwards
1731 * until no more changes are made.
1732 * In theory this should happen once more than once for every nested loop
1734 * Though this implementation might run an additional time for if nests.
1743 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1745 /* Enumerate instructions used by value's life-ranges
1747 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1751 for (i = 0; i < self->instr_count; ++i)
1753 self->instr[i]->eid = eid++;
1758 /* Enumerate blocks and instructions.
1759 * The block-enumeration is unordered!
1760 * We do not really use the block enumreation, however
1761 * the instruction enumeration is important for life-ranges.
1763 void ir_function_enumerate(ir_function *self)
1766 size_t instruction_id = 0;
1767 for (i = 0; i < self->blocks_count; ++i)
1769 self->blocks[i]->eid = i;
1770 self->blocks[i]->run_id = 0;
1771 ir_block_enumerate(self->blocks[i], &instruction_id);
1775 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1776 bool ir_function_calculate_liferanges(ir_function *self)
1784 for (i = 0; i != self->blocks_count; ++i)
1786 if (self->blocks[i]->is_return)
1788 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1796 /* Local-value allocator
1797 * After finishing creating the liferange of all values used in a function
1798 * we can allocate their global-positions.
1799 * This is the counterpart to register-allocation in register machines.
1802 MEM_VECTOR_MAKE(ir_value*, locals);
1803 MEM_VECTOR_MAKE(size_t, sizes);
1804 MEM_VECTOR_MAKE(size_t, positions);
1805 } function_allocator;
1806 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1807 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1808 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1810 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1813 size_t vsize = type_sizeof[var->vtype];
1815 slot = ir_value_var("reg", store_global, var->vtype);
1819 if (!ir_value_life_merge_into(slot, var))
1822 if (!function_allocator_locals_add(alloc, slot))
1825 if (!function_allocator_sizes_add(alloc, vsize))
1831 ir_value_delete(slot);
1835 bool ir_function_allocate_locals(ir_function *self)
1844 function_allocator alloc;
1846 if (!self->locals_count)
1849 MEM_VECTOR_INIT(&alloc, locals);
1850 MEM_VECTOR_INIT(&alloc, sizes);
1851 MEM_VECTOR_INIT(&alloc, positions);
1853 for (i = 0; i < self->locals_count; ++i)
1855 if (!function_allocator_alloc(&alloc, self->locals[i]))
1859 /* Allocate a slot for any value that still exists */
1860 for (i = 0; i < self->values_count; ++i)
1862 v = self->values[i];
1867 for (a = 0; a < alloc.locals_count; ++a)
1869 slot = alloc.locals[a];
1871 if (ir_values_overlap(v, slot))
1874 if (!ir_value_life_merge_into(slot, v))
1877 /* adjust size for this slot */
1878 if (alloc.sizes[a] < type_sizeof[v->vtype])
1879 alloc.sizes[a] = type_sizeof[v->vtype];
1881 self->values[i]->code.local = a;
1884 if (a >= alloc.locals_count) {
1885 self->values[i]->code.local = alloc.locals_count;
1886 if (!function_allocator_alloc(&alloc, v))
1891 /* Adjust slot positions based on sizes */
1892 if (!function_allocator_positions_add(&alloc, 0))
1895 if (alloc.sizes_count)
1896 pos = alloc.positions[0] + alloc.sizes[0];
1899 for (i = 1; i < alloc.sizes_count; ++i)
1901 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1902 if (!function_allocator_positions_add(&alloc, pos))
1906 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1908 /* Take over the actual slot positions */
1909 for (i = 0; i < self->values_count; ++i)
1910 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1917 for (i = 0; i < alloc.locals_count; ++i)
1918 ir_value_delete(alloc.locals[i]);
1919 MEM_VECTOR_CLEAR(&alloc, locals);
1920 MEM_VECTOR_CLEAR(&alloc, sizes);
1921 MEM_VECTOR_CLEAR(&alloc, positions);
1925 /* Get information about which operand
1926 * is read from, or written to.
1928 static void ir_op_read_write(int op, size_t *read, size_t *write)
1955 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1958 bool changed = false;
1960 for (i = 0; i != self->living_count; ++i)
1962 tempbool = ir_value_life_merge(self->living[i], eid);
1965 irerror(self->context, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1967 changed = changed || tempbool;
1972 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1975 /* values which have been read in a previous iteration are now
1976 * in the "living" array even if the previous block doesn't use them.
1977 * So we have to remove whatever does not exist in the previous block.
1978 * They will be re-added on-read, but the liferange merge won't cause
1981 for (i = 0; i < self->living_count; ++i)
1983 if (!ir_block_living_find(prev, self->living[i], NULL)) {
1984 if (!ir_block_living_remove(self, i))
1990 /* Whatever the previous block still has in its living set
1991 * must now be added to ours as well.
1993 for (i = 0; i < prev->living_count; ++i)
1995 if (ir_block_living_find(self, prev->living[i], NULL))
1997 if (!ir_block_living_add(self, prev->living[i]))
2000 irerror(self->contextt from prev: %s\n", self->label, prev->living[i]->_name);
2006 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2012 /* bitmasks which operands are read from or written to */
2014 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2016 new_reads_t new_reads;
2018 char dbg_ind[16] = { '#', '0' };
2021 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2022 MEM_VECTOR_INIT(&new_reads, v);
2027 if (!ir_block_life_prop_previous(self, prev, changed))
2031 i = self->instr_count;
2034 instr = self->instr[i];
2036 /* PHI operands are always read operands */
2037 for (p = 0; p < instr->phi_count; ++p)
2039 value = instr->phi[p].value;
2040 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2041 if (!ir_block_living_find(self, value, NULL) &&
2042 !ir_block_living_add(self, value))
2047 if (!new_reads_t_v_find(&new_reads, value, NULL))
2049 if (!new_reads_t_v_add(&new_reads, value))
2055 /* See which operands are read and write operands */
2056 ir_op_read_write(instr->opcode, &read, &write);
2058 /* Go through the 3 main operands */
2059 for (o = 0; o < 3; ++o)
2061 if (!instr->_ops[o]) /* no such operand */
2064 value = instr->_ops[o];
2066 /* We only care about locals */
2067 /* we also calculate parameter liferanges so that locals
2068 * can take up parameter slots */
2069 if (value->store != store_value &&
2070 value->store != store_local &&
2071 value->store != store_param)
2077 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2078 if (!ir_block_living_find(self, value, NULL) &&
2079 !ir_block_living_add(self, value))
2084 /* fprintf(stderr, "read: %s\n", value->_name); */
2085 if (!new_reads_t_v_find(&new_reads, value, NULL))
2087 if (!new_reads_t_v_add(&new_reads, value))
2093 /* write operands */
2094 /* When we write to a local, we consider it "dead" for the
2095 * remaining upper part of the function, since in SSA a value
2096 * can only be written once (== created)
2101 bool in_living = ir_block_living_find(self, value, &idx);
2102 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2104 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
2105 if (!in_living && !in_reads)
2110 /* If the value isn't alive it hasn't been read before... */
2111 /* TODO: See if the warning can be emitted during parsing or AST processing
2112 * otherwise have warning printed here.
2113 * IF printing a warning here: include filecontext_t,
2114 * and make sure it's only printed once
2115 * since this function is run multiple times.
2117 /* For now: debug info: */
2118 /* fprintf(stderr, "Value only written %s\n", value->name); */
2119 tempbool = ir_value_life_merge(value, instr->eid);
2120 *changed = *changed || tempbool;
2122 ir_instr_dump(instr, dbg_ind, printf);
2126 /* since 'living' won't contain it
2127 * anymore, merge the value, since
2130 tempbool = ir_value_life_merge(value, instr->eid);
2133 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2135 *changed = *changed || tempbool;
2137 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2138 if (!ir_block_living_remove(self, idx))
2143 if (!new_reads_t_v_remove(&new_reads, readidx))
2151 tempbool = ir_block_living_add_instr(self, instr->eid);
2152 /*fprintf(stderr, "living added values\n");*/
2153 *changed = *changed || tempbool;
2155 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2157 for (rd = 0; rd < new_reads.v_count; ++rd)
2159 if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
2160 if (!ir_block_living_add(self, new_reads.v[rd]))
2163 if (!i && !self->entries_count) {
2165 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
2168 MEM_VECTOR_CLEAR(&new_reads, v);
2172 if (self->run_id == self->owner->run_id)
2175 self->run_id = self->owner->run_id;
2177 for (i = 0; i < self->entries_count; ++i)
2179 ir_block *entry = self->entries[i];
2180 ir_block_life_propagate(entry, self, changed);
2185 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2186 MEM_VECTOR_CLEAR(&new_reads, v);
2191 /***********************************************************************
2194 * Since the IR has the convention of putting 'write' operands
2195 * at the beginning, we have to rotate the operands of instructions
2196 * properly in order to generate valid QCVM code.
2198 * Having destinations at a fixed position is more convenient. In QC
2199 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2200 * read from from OPA, and store to OPB rather than OPC. Which is
2201 * partially the reason why the implementation of these instructions
2202 * in darkplaces has been delayed for so long.
2204 * Breaking conventions is annoying...
2206 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2208 static bool gen_global_field(ir_value *global)
2210 if (global->isconst)
2212 ir_value *fld = global->constval.vpointer;
2214 irerror(global->context, "Invalid field constant with no field: %s\n", global->name);
2218 /* Now, in this case, a relocation would be impossible to code
2219 * since it looks like this:
2220 * .vector v = origin; <- parse error, wtf is 'origin'?
2223 * But we will need a general relocation support later anyway
2224 * for functions... might as well support that here.
2226 if (!fld->code.globaladdr) {
2227 irerror(global->context, "FIXME: Relocation support\n");
2231 /* copy the field's value */
2232 ir_value_code_setaddr(global, code_globals_add(code_globals_data[fld->code.globaladdr]));
2233 if (global->fieldtype == TYPE_VECTOR) {
2234 code_globals_add(code_globals_data[fld->code.globaladdr]+1);
2235 code_globals_add(code_globals_data[fld->code.globaladdr]+2);
2240 ir_value_code_setaddr(global, code_globals_add(0));
2241 if (global->fieldtype == TYPE_VECTOR) {
2242 code_globals_add(0);
2243 code_globals_add(0);
2246 if (global->code.globaladdr < 0)
2251 static bool gen_global_pointer(ir_value *global)
2253 if (global->isconst)
2255 ir_value *target = global->constval.vpointer;
2257 irerror(global->context, "Invalid pointer constant: %s\n", global->name);
2258 /* NULL pointers are pointing to the NULL constant, which also
2259 * sits at address 0, but still has an ir_value for itself.
2264 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2265 * void() foo; <- proto
2266 * void() *fooptr = &foo;
2267 * void() foo = { code }
2269 if (!target->code.globaladdr) {
2270 /* FIXME: Check for the constant nullptr ir_value!
2271 * because then code.globaladdr being 0 is valid.
2273 irerror(global->context, "FIXME: Relocation support\n");
2277 ir_value_code_setaddr(global, code_globals_add(target->code.globaladdr));
2281 ir_value_code_setaddr(global, code_globals_add(0));
2283 if (global->code.globaladdr < 0)
2288 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2290 prog_section_statement stmt;
2299 block->generated = true;
2300 block->code_start = code_statements_elements;
2301 for (i = 0; i < block->instr_count; ++i)
2303 instr = block->instr[i];
2305 if (instr->opcode == VINSTR_PHI) {
2306 irerror(block->context, "cannot generate virtual instruction (phi)\n");
2310 if (instr->opcode == VINSTR_JUMP) {
2311 target = instr->bops[0];
2312 /* for uncoditional jumps, if the target hasn't been generated
2313 * yet, we generate them right here.
2315 if (!target->generated) {
2320 /* otherwise we generate a jump instruction */
2321 stmt.opcode = INSTR_GOTO;
2322 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2325 if (code_statements_add(stmt) < 0)
2328 /* no further instructions can be in this block */
2332 if (instr->opcode == VINSTR_COND) {
2333 ontrue = instr->bops[0];
2334 onfalse = instr->bops[1];
2335 /* TODO: have the AST signal which block should
2336 * come first: eg. optimize IFs without ELSE...
2339 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2343 if (ontrue->generated) {
2344 stmt.opcode = INSTR_IF;
2345 stmt.o2.s1 = (ontrue->code_start) - code_statements_elements;
2346 if (code_statements_add(stmt) < 0)
2349 if (onfalse->generated) {
2350 stmt.opcode = INSTR_IFNOT;
2351 stmt.o2.s1 = (onfalse->code_start) - code_statements_elements;
2352 if (code_statements_add(stmt) < 0)
2355 if (!ontrue->generated) {
2356 if (onfalse->generated) {
2361 if (!onfalse->generated) {
2362 if (ontrue->generated) {
2367 /* neither ontrue nor onfalse exist */
2368 stmt.opcode = INSTR_IFNOT;
2369 stidx = code_statements_elements;
2370 if (code_statements_add(stmt) < 0)
2372 /* on false we jump, so add ontrue-path */
2373 if (!gen_blocks_recursive(func, ontrue))
2375 /* fixup the jump address */
2376 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2377 /* generate onfalse path */
2378 if (onfalse->generated) {
2379 /* fixup the jump address */
2380 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2381 /* may have been generated in the previous recursive call */
2382 stmt.opcode = INSTR_GOTO;
2383 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2386 return (code_statements_add(stmt) >= 0);
2388 /* if not, generate now */
2393 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2394 /* Trivial call translation:
2395 * copy all params to OFS_PARM*
2396 * if the output's storetype is not store_return,
2397 * add append a STORE instruction!
2399 * NOTES on how to do it better without much trouble:
2400 * -) The liferanges!
2401 * Simply check the liferange of all parameters for
2402 * other CALLs. For each param with no CALL in its
2403 * liferange, we can store it in an OFS_PARM at
2404 * generation already. This would even include later
2405 * reuse.... probably... :)
2410 for (p = 0; p < instr->params_count; ++p)
2412 ir_value *param = instr->params[p];
2414 stmt.opcode = INSTR_STORE_F;
2417 stmt.opcode = type_store_instr[param->vtype];
2418 stmt.o1.u1 = ir_value_code_addr(param);
2419 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2420 if (code_statements_add(stmt) < 0)
2423 stmt.opcode = INSTR_CALL0 + instr->params_count;
2424 if (stmt.opcode > INSTR_CALL8)
2425 stmt.opcode = INSTR_CALL8;
2426 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2429 if (code_statements_add(stmt) < 0)
2432 retvalue = instr->_ops[0];
2433 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2435 /* not to be kept in OFS_RETURN */
2436 stmt.opcode = type_store_instr[retvalue->vtype];
2437 stmt.o1.u1 = OFS_RETURN;
2438 stmt.o2.u1 = ir_value_code_addr(retvalue);
2440 if (code_statements_add(stmt) < 0)
2446 if (instr->opcode == INSTR_STATE) {
2447 irerror(block->context, "TODO: state instruction\n");
2451 stmt.opcode = instr->opcode;
2456 /* This is the general order of operands */
2458 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2461 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2464 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2466 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2468 stmt.o1.u1 = stmt.o3.u1;
2471 else if ((stmt.opcode >= INSTR_STORE_F &&
2472 stmt.opcode <= INSTR_STORE_FNC) ||
2473 (stmt.opcode >= INSTR_STOREP_F &&
2474 stmt.opcode <= INSTR_STOREP_FNC))
2476 /* 2-operand instructions with A -> B */
2477 stmt.o2.u1 = stmt.o3.u1;
2481 if (code_statements_add(stmt) < 0)
2487 static bool gen_function_code(ir_function *self)
2490 prog_section_statement stmt;
2492 /* Starting from entry point, we generate blocks "as they come"
2493 * for now. Dead blocks will not be translated obviously.
2495 if (!self->blocks_count) {
2496 irerror(self->context, "Function '%s' declared without body.\n", self->name);
2500 block = self->blocks[0];
2501 if (block->generated)
2504 if (!gen_blocks_recursive(self, block)) {
2505 irerror(self->context, "failed to generate blocks for '%s'\n", self->name);
2509 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2510 stmt.opcode = AINSTR_END;
2514 if (code_statements_add(stmt) < 0)
2519 static bool gen_global_function(ir_builder *ir, ir_value *global)
2521 prog_section_function fun;
2525 size_t local_var_end;
2527 if (!global->isconst || (!global->constval.vfunc))
2529 irerror(global->context, "Invalid state of function-global: not constant: %s\n", global->name);
2533 irfun = global->constval.vfunc;
2535 fun.name = global->code.name;
2536 fun.file = code_cachedstring(global->context.file);
2537 fun.profile = 0; /* always 0 */
2538 fun.nargs = irfun->params_count;
2540 for (i = 0;i < 8; ++i) {
2544 fun.argsize[i] = type_sizeof[irfun->params[i]];
2547 fun.firstlocal = code_globals_elements;
2548 fun.locals = irfun->allocated_locals + irfun->locals_count;
2551 for (i = 0; i < irfun->locals_count; ++i) {
2552 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2553 irerror(irfun->locals[i]->context, "Failed to generate global %s\n", irfun->locals[i]->name);
2557 if (irfun->locals_count) {
2558 ir_value *last = irfun->locals[irfun->locals_count-1];
2559 local_var_end = last->code.globaladdr;
2560 local_var_end += type_sizeof[last->vtype];
2562 for (i = 0; i < irfun->values_count; ++i)
2564 /* generate code.globaladdr for ssa values */
2565 ir_value *v = irfun->values[i];
2566 ir_value_code_setaddr(v, local_var_end + v->code.local);
2568 for (i = 0; i < irfun->locals_count; ++i) {
2569 /* fill the locals with zeros */
2570 code_globals_add(0);
2574 fun.entry = irfun->builtin;
2576 fun.entry = code_statements_elements;
2577 if (!gen_function_code(irfun)) {
2578 irerror(irfun->context, "Failed to generate code for function %s\n", irfun->name);
2583 return (code_functions_add(fun) >= 0);
2586 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2590 prog_section_def def;
2592 def.type = global->vtype;
2593 def.offset = code_globals_elements;
2594 def.name = global->code.name = code_genstring(global->name);
2596 switch (global->vtype)
2599 if (code_defs_add(def) < 0)
2601 return gen_global_pointer(global);
2603 if (code_defs_add(def) < 0)
2605 return gen_global_field(global);
2610 if (code_defs_add(def) < 0)
2613 if (global->isconst) {
2614 iptr = (int32_t*)&global->constval.vfloat;
2615 ir_value_code_setaddr(global, code_globals_add(*iptr));
2617 ir_value_code_setaddr(global, code_globals_add(0));
2619 return global->code.globaladdr >= 0;
2623 if (code_defs_add(def) < 0)
2625 if (global->isconst)
2626 ir_value_code_setaddr(global, code_globals_add(code_cachedstring(global->constval.vstring)));
2628 ir_value_code_setaddr(global, code_globals_add(0));
2629 return global->code.globaladdr >= 0;
2634 if (code_defs_add(def) < 0)
2637 if (global->isconst) {
2638 iptr = (int32_t*)&global->constval.vvec;
2639 ir_value_code_setaddr(global, code_globals_add(iptr[0]));
2640 if (global->code.globaladdr < 0)
2642 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2644 if (code_globals_add(iptr[d]) < 0)
2648 ir_value_code_setaddr(global, code_globals_add(0));
2649 if (global->code.globaladdr < 0)
2651 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2653 if (code_globals_add(0) < 0)
2657 return global->code.globaladdr >= 0;
2660 if (code_defs_add(def) < 0)
2662 ir_value_code_setaddr(global, code_globals_elements);
2663 code_globals_add(code_functions_elements);
2664 return gen_global_function(self, global);
2666 /* assume biggest type */
2667 ir_value_code_setaddr(global, code_globals_add(0));
2668 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2669 code_globals_add(0);
2672 /* refuse to create 'void' type or any other fancy business. */
2673 irerror(global->context, "Invalid type for global variable %s\n", global->name);
2678 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2680 prog_section_def def;
2681 prog_section_field fld;
2683 def.type = field->vtype;
2684 def.offset = code_globals_elements;
2686 /* create a global named the same as the field */
2687 if (opts_standard == COMPILER_GMQCC) {
2688 /* in our standard, the global gets a dot prefix */
2689 size_t len = strlen(field->name);
2692 /* we really don't want to have to allocate this, and 1024
2693 * bytes is more than enough for a variable/field name
2695 if (len+2 >= sizeof(name)) {
2696 irerror(field->context, "invalid field name size: %u\n", (unsigned int)len);
2701 strcpy(name+1, field->name); /* no strncpy - we used strlen above */
2704 def.name = code_genstring(name);
2705 fld.name = def.name + 1; /* we reuse that string table entry */
2707 /* in plain QC, there cannot be a global with the same name,
2708 * and so we also name the global the same.
2709 * FIXME: fteqcc should create a global as well
2710 * check if it actually uses the same name. Probably does
2712 def.name = code_genstring(field->name);
2713 fld.name = def.name;
2716 field->code.name = def.name;
2718 if (code_defs_add(def) < 0)
2721 fld.type = field->fieldtype;
2723 if (fld.type == TYPE_VOID) {
2724 irerror(field->context, "field is missing a type: %s - don't know its size\n", field->name);
2728 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2730 if (code_fields_add(fld) < 0)
2733 ir_value_code_setaddr(field, code_globals_elements);
2734 if (!code_globals_add(fld.offset))
2736 if (fld.type == TYPE_VECTOR) {
2737 if (!code_globals_add(fld.offset+1))
2739 if (!code_globals_add(fld.offset+2))
2743 return field->code.globaladdr >= 0;
2746 bool ir_builder_generate(ir_builder *self, const char *filename)
2752 for (i = 0; i < self->fields_count; ++i)
2754 if (!ir_builder_gen_field(self, self->fields[i])) {
2759 for (i = 0; i < self->globals_count; ++i)
2761 if (!ir_builder_gen_global(self, self->globals[i])) {
2766 printf("writing '%s'...\n", filename);
2767 return code_write(filename);
2770 /***********************************************************************
2771 *IR DEBUG Dump functions...
2774 #define IND_BUFSZ 1024
2776 const char *qc_opname(int op)
2778 if (op < 0) return "<INVALID>";
2779 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2780 return asm_instr[op].m;
2782 case VINSTR_PHI: return "PHI";
2783 case VINSTR_JUMP: return "JUMP";
2784 case VINSTR_COND: return "COND";
2785 default: return "<UNK>";
2789 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2792 char indent[IND_BUFSZ];
2796 oprintf("module %s\n", b->name);
2797 for (i = 0; i < b->globals_count; ++i)
2800 if (b->globals[i]->isconst)
2801 oprintf("%s = ", b->globals[i]->name);
2802 ir_value_dump(b->globals[i], oprintf);
2805 for (i = 0; i < b->functions_count; ++i)
2806 ir_function_dump(b->functions[i], indent, oprintf);
2807 oprintf("endmodule %s\n", b->name);
2810 void ir_function_dump(ir_function *f, char *ind,
2811 int (*oprintf)(const char*, ...))
2814 if (f->builtin != 0) {
2815 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2818 oprintf("%sfunction %s\n", ind, f->name);
2819 strncat(ind, "\t", IND_BUFSZ);
2820 if (f->locals_count)
2822 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2823 for (i = 0; i < f->locals_count; ++i) {
2824 oprintf("%s\t", ind);
2825 ir_value_dump(f->locals[i], oprintf);
2829 if (f->blocks_count)
2831 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2832 for (i = 0; i < f->blocks_count; ++i) {
2833 if (f->blocks[i]->run_id != f->run_id) {
2834 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2836 ir_block_dump(f->blocks[i], ind, oprintf);
2840 ind[strlen(ind)-1] = 0;
2841 oprintf("%sendfunction %s\n", ind, f->name);
2844 void ir_block_dump(ir_block* b, char *ind,
2845 int (*oprintf)(const char*, ...))
2848 oprintf("%s:%s\n", ind, b->label);
2849 strncat(ind, "\t", IND_BUFSZ);
2851 for (i = 0; i < b->instr_count; ++i)
2852 ir_instr_dump(b->instr[i], ind, oprintf);
2853 ind[strlen(ind)-1] = 0;
2856 void dump_phi(ir_instr *in, char *ind,
2857 int (*oprintf)(const char*, ...))
2860 oprintf("%s <- phi ", in->_ops[0]->name);
2861 for (i = 0; i < in->phi_count; ++i)
2863 oprintf("([%s] : %s) ", in->phi[i].from->label,
2864 in->phi[i].value->name);
2869 void ir_instr_dump(ir_instr *in, char *ind,
2870 int (*oprintf)(const char*, ...))
2873 const char *comma = NULL;
2875 oprintf("%s (%i) ", ind, (int)in->eid);
2877 if (in->opcode == VINSTR_PHI) {
2878 dump_phi(in, ind, oprintf);
2882 strncat(ind, "\t", IND_BUFSZ);
2884 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2885 ir_value_dump(in->_ops[0], oprintf);
2886 if (in->_ops[1] || in->_ops[2])
2889 if (in->opcode == INSTR_CALL0) {
2890 oprintf("CALL%i\t", in->params_count);
2892 oprintf("%s\t", qc_opname(in->opcode));
2894 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2895 ir_value_dump(in->_ops[0], oprintf);
2900 for (i = 1; i != 3; ++i) {
2904 ir_value_dump(in->_ops[i], oprintf);
2912 oprintf("[%s]", in->bops[0]->label);
2916 oprintf("%s[%s]", comma, in->bops[1]->label);
2918 ind[strlen(ind)-1] = 0;
2921 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
2930 oprintf("(function)");
2933 oprintf("%g", v->constval.vfloat);
2936 oprintf("'%g %g %g'",
2939 v->constval.vvec.z);
2942 oprintf("(entity)");
2945 oprintf("\"%s\"", v->constval.vstring);
2949 oprintf("%i", v->constval.vint);
2954 v->constval.vpointer->name);
2958 oprintf("%s", v->name);
2962 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
2965 oprintf("Life of %s:\n", self->name);
2966 for (i = 0; i < self->life_count; ++i)
2968 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);