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));
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) actually <= */
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;
1454 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1456 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1457 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1463 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1466 ir_value* ir_block_create_add(ir_block *self,
1468 ir_value *left, ir_value *right)
1471 int l = left->vtype;
1472 int r = right->vtype;
1491 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1493 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1499 return ir_block_create_binop(self, label, op, left, right);
1502 ir_value* ir_block_create_sub(ir_block *self,
1504 ir_value *left, ir_value *right)
1507 int l = left->vtype;
1508 int r = right->vtype;
1528 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1530 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1536 return ir_block_create_binop(self, label, op, left, right);
1539 ir_value* ir_block_create_mul(ir_block *self,
1541 ir_value *left, ir_value *right)
1544 int l = left->vtype;
1545 int r = right->vtype;
1564 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1566 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1569 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1571 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1573 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1575 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1581 return ir_block_create_binop(self, label, op, left, right);
1584 ir_value* ir_block_create_div(ir_block *self,
1586 ir_value *left, ir_value *right)
1589 int l = left->vtype;
1590 int r = right->vtype;
1607 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1609 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1611 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1617 return ir_block_create_binop(self, label, op, left, right);
1620 /* PHI resolving breaks the SSA, and must thus be the last
1621 * step before life-range calculation.
1624 static bool ir_block_naive_phi(ir_block *self);
1625 bool ir_function_naive_phi(ir_function *self)
1629 for (i = 0; i < self->blocks_count; ++i)
1631 if (!ir_block_naive_phi(self->blocks[i]))
1637 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1642 /* create a store */
1643 if (!ir_block_create_store(block, old, what))
1646 /* we now move it up */
1647 instr = block->instr[block->instr_count-1];
1648 for (i = block->instr_count; i > iid; --i)
1649 block->instr[i] = block->instr[i-1];
1650 block->instr[i] = instr;
1655 static bool ir_block_naive_phi(ir_block *self)
1658 /* FIXME: optionally, create_phi can add the phis
1659 * to a list so we don't need to loop through blocks
1660 * - anyway: "don't optimize YET"
1662 for (i = 0; i < self->instr_count; ++i)
1664 ir_instr *instr = self->instr[i];
1665 if (instr->opcode != VINSTR_PHI)
1668 if (!ir_block_instr_remove(self, i))
1670 --i; /* NOTE: i+1 below */
1672 for (p = 0; p < instr->phi_count; ++p)
1674 ir_value *v = instr->phi[p].value;
1675 for (w = 0; w < v->writes_count; ++w) {
1678 if (!v->writes[w]->_ops[0])
1681 /* When the write was to a global, we have to emit a mov */
1682 old = v->writes[w]->_ops[0];
1684 /* The original instruction now writes to the PHI target local */
1685 if (v->writes[w]->_ops[0] == v)
1686 v->writes[w]->_ops[0] = instr->_ops[0];
1688 if (old->store != store_value && old->store != store_local && old->store != store_param)
1690 /* If it originally wrote to a global we need to store the value
1693 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1695 if (i+1 < self->instr_count)
1696 instr = self->instr[i+1];
1699 /* In case I forget and access instr later, it'll be NULL
1700 * when it's a problem, to make sure we crash, rather than accessing
1706 /* If it didn't, we can replace all reads by the phi target now. */
1708 for (r = 0; r < old->reads_count; ++r)
1711 ir_instr *ri = old->reads[r];
1712 for (op = 0; op < ri->phi_count; ++op) {
1713 if (ri->phi[op].value == old)
1714 ri->phi[op].value = v;
1716 for (op = 0; op < 3; ++op) {
1717 if (ri->_ops[op] == old)
1724 ir_instr_delete(instr);
1729 /***********************************************************************
1730 *IR Temp allocation code
1731 * Propagating value life ranges by walking through the function backwards
1732 * until no more changes are made.
1733 * In theory this should happen once more than once for every nested loop
1735 * Though this implementation might run an additional time for if nests.
1744 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1746 /* Enumerate instructions used by value's life-ranges
1748 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1752 for (i = 0; i < self->instr_count; ++i)
1754 self->instr[i]->eid = eid++;
1759 /* Enumerate blocks and instructions.
1760 * The block-enumeration is unordered!
1761 * We do not really use the block enumreation, however
1762 * the instruction enumeration is important for life-ranges.
1764 void ir_function_enumerate(ir_function *self)
1767 size_t instruction_id = 0;
1768 for (i = 0; i < self->blocks_count; ++i)
1770 self->blocks[i]->eid = i;
1771 self->blocks[i]->run_id = 0;
1772 ir_block_enumerate(self->blocks[i], &instruction_id);
1776 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1777 bool ir_function_calculate_liferanges(ir_function *self)
1785 for (i = 0; i != self->blocks_count; ++i)
1787 if (self->blocks[i]->is_return)
1789 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1797 /* Local-value allocator
1798 * After finishing creating the liferange of all values used in a function
1799 * we can allocate their global-positions.
1800 * This is the counterpart to register-allocation in register machines.
1803 MEM_VECTOR_MAKE(ir_value*, locals);
1804 MEM_VECTOR_MAKE(size_t, sizes);
1805 MEM_VECTOR_MAKE(size_t, positions);
1806 } function_allocator;
1807 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1808 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1809 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1811 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1814 size_t vsize = type_sizeof[var->vtype];
1816 slot = ir_value_var("reg", store_global, var->vtype);
1820 if (!ir_value_life_merge_into(slot, var))
1823 if (!function_allocator_locals_add(alloc, slot))
1826 if (!function_allocator_sizes_add(alloc, vsize))
1832 ir_value_delete(slot);
1836 bool ir_function_allocate_locals(ir_function *self)
1845 function_allocator alloc;
1847 if (!self->locals_count)
1850 MEM_VECTOR_INIT(&alloc, locals);
1851 MEM_VECTOR_INIT(&alloc, sizes);
1852 MEM_VECTOR_INIT(&alloc, positions);
1854 for (i = 0; i < self->locals_count; ++i)
1856 if (!function_allocator_alloc(&alloc, self->locals[i]))
1860 /* Allocate a slot for any value that still exists */
1861 for (i = 0; i < self->values_count; ++i)
1863 v = self->values[i];
1868 for (a = 0; a < alloc.locals_count; ++a)
1870 slot = alloc.locals[a];
1872 if (ir_values_overlap(v, slot))
1875 if (!ir_value_life_merge_into(slot, v))
1878 /* adjust size for this slot */
1879 if (alloc.sizes[a] < type_sizeof[v->vtype])
1880 alloc.sizes[a] = type_sizeof[v->vtype];
1882 self->values[i]->code.local = a;
1885 if (a >= alloc.locals_count) {
1886 self->values[i]->code.local = alloc.locals_count;
1887 if (!function_allocator_alloc(&alloc, v))
1892 /* Adjust slot positions based on sizes */
1893 if (!function_allocator_positions_add(&alloc, 0))
1896 if (alloc.sizes_count)
1897 pos = alloc.positions[0] + alloc.sizes[0];
1900 for (i = 1; i < alloc.sizes_count; ++i)
1902 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1903 if (!function_allocator_positions_add(&alloc, pos))
1907 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1909 /* Take over the actual slot positions */
1910 for (i = 0; i < self->values_count; ++i)
1911 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1918 for (i = 0; i < alloc.locals_count; ++i)
1919 ir_value_delete(alloc.locals[i]);
1920 MEM_VECTOR_CLEAR(&alloc, locals);
1921 MEM_VECTOR_CLEAR(&alloc, sizes);
1922 MEM_VECTOR_CLEAR(&alloc, positions);
1926 /* Get information about which operand
1927 * is read from, or written to.
1929 static void ir_op_read_write(int op, size_t *read, size_t *write)
1956 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1959 bool changed = false;
1961 for (i = 0; i != self->living_count; ++i)
1963 tempbool = ir_value_life_merge(self->living[i], eid);
1966 irerror(self->context, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1968 changed = changed || tempbool;
1973 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1976 /* values which have been read in a previous iteration are now
1977 * in the "living" array even if the previous block doesn't use them.
1978 * So we have to remove whatever does not exist in the previous block.
1979 * They will be re-added on-read, but the liferange merge won't cause
1982 for (i = 0; i < self->living_count; ++i)
1984 if (!ir_block_living_find(prev, self->living[i], NULL)) {
1985 if (!ir_block_living_remove(self, i))
1991 /* Whatever the previous block still has in its living set
1992 * must now be added to ours as well.
1994 for (i = 0; i < prev->living_count; ++i)
1996 if (ir_block_living_find(self, prev->living[i], NULL))
1998 if (!ir_block_living_add(self, prev->living[i]))
2001 irerror(self->contextt from prev: %s\n", self->label, prev->living[i]->_name);
2007 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2013 /* bitmasks which operands are read from or written to */
2015 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2017 new_reads_t new_reads;
2019 char dbg_ind[16] = { '#', '0' };
2022 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2023 MEM_VECTOR_INIT(&new_reads, v);
2028 if (!ir_block_life_prop_previous(self, prev, changed))
2032 i = self->instr_count;
2035 instr = self->instr[i];
2037 /* PHI operands are always read operands */
2038 for (p = 0; p < instr->phi_count; ++p)
2040 value = instr->phi[p].value;
2041 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2042 if (!ir_block_living_find(self, value, NULL) &&
2043 !ir_block_living_add(self, value))
2048 if (!new_reads_t_v_find(&new_reads, value, NULL))
2050 if (!new_reads_t_v_add(&new_reads, value))
2056 /* See which operands are read and write operands */
2057 ir_op_read_write(instr->opcode, &read, &write);
2059 /* Go through the 3 main operands */
2060 for (o = 0; o < 3; ++o)
2062 if (!instr->_ops[o]) /* no such operand */
2065 value = instr->_ops[o];
2067 /* We only care about locals */
2068 /* we also calculate parameter liferanges so that locals
2069 * can take up parameter slots */
2070 if (value->store != store_value &&
2071 value->store != store_local &&
2072 value->store != store_param)
2078 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2079 if (!ir_block_living_find(self, value, NULL) &&
2080 !ir_block_living_add(self, value))
2085 /* fprintf(stderr, "read: %s\n", value->_name); */
2086 if (!new_reads_t_v_find(&new_reads, value, NULL))
2088 if (!new_reads_t_v_add(&new_reads, value))
2094 /* write operands */
2095 /* When we write to a local, we consider it "dead" for the
2096 * remaining upper part of the function, since in SSA a value
2097 * can only be written once (== created)
2102 bool in_living = ir_block_living_find(self, value, &idx);
2103 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2105 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
2106 if (!in_living && !in_reads)
2111 /* If the value isn't alive it hasn't been read before... */
2112 /* TODO: See if the warning can be emitted during parsing or AST processing
2113 * otherwise have warning printed here.
2114 * IF printing a warning here: include filecontext_t,
2115 * and make sure it's only printed once
2116 * since this function is run multiple times.
2118 /* For now: debug info: */
2119 /* fprintf(stderr, "Value only written %s\n", value->name); */
2120 tempbool = ir_value_life_merge(value, instr->eid);
2121 *changed = *changed || tempbool;
2123 ir_instr_dump(instr, dbg_ind, printf);
2127 /* since 'living' won't contain it
2128 * anymore, merge the value, since
2131 tempbool = ir_value_life_merge(value, instr->eid);
2134 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2136 *changed = *changed || tempbool;
2138 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2139 if (!ir_block_living_remove(self, idx))
2144 if (!new_reads_t_v_remove(&new_reads, readidx))
2152 tempbool = ir_block_living_add_instr(self, instr->eid);
2153 /*fprintf(stderr, "living added values\n");*/
2154 *changed = *changed || tempbool;
2156 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2158 for (rd = 0; rd < new_reads.v_count; ++rd)
2160 if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
2161 if (!ir_block_living_add(self, new_reads.v[rd]))
2164 if (!i && !self->entries_count) {
2166 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
2169 MEM_VECTOR_CLEAR(&new_reads, v);
2173 if (self->run_id == self->owner->run_id)
2176 self->run_id = self->owner->run_id;
2178 for (i = 0; i < self->entries_count; ++i)
2180 ir_block *entry = self->entries[i];
2181 ir_block_life_propagate(entry, self, changed);
2186 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2187 MEM_VECTOR_CLEAR(&new_reads, v);
2192 /***********************************************************************
2195 * Since the IR has the convention of putting 'write' operands
2196 * at the beginning, we have to rotate the operands of instructions
2197 * properly in order to generate valid QCVM code.
2199 * Having destinations at a fixed position is more convenient. In QC
2200 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2201 * read from from OPA, and store to OPB rather than OPC. Which is
2202 * partially the reason why the implementation of these instructions
2203 * in darkplaces has been delayed for so long.
2205 * Breaking conventions is annoying...
2207 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2209 static bool gen_global_field(ir_value *global)
2211 if (global->isconst)
2213 ir_value *fld = global->constval.vpointer;
2215 irerror(global->context, "Invalid field constant with no field: %s\n", global->name);
2219 /* Now, in this case, a relocation would be impossible to code
2220 * since it looks like this:
2221 * .vector v = origin; <- parse error, wtf is 'origin'?
2224 * But we will need a general relocation support later anyway
2225 * for functions... might as well support that here.
2227 if (!fld->code.globaladdr) {
2228 irerror(global->context, "FIXME: Relocation support\n");
2232 /* copy the field's value */
2233 ir_value_code_setaddr(global, code_globals_add(code_globals_data[fld->code.globaladdr]));
2234 if (global->fieldtype == TYPE_VECTOR) {
2235 code_globals_add(code_globals_data[fld->code.globaladdr]+1);
2236 code_globals_add(code_globals_data[fld->code.globaladdr]+2);
2241 ir_value_code_setaddr(global, code_globals_add(0));
2242 if (global->fieldtype == TYPE_VECTOR) {
2243 code_globals_add(0);
2244 code_globals_add(0);
2247 if (global->code.globaladdr < 0)
2252 static bool gen_global_pointer(ir_value *global)
2254 if (global->isconst)
2256 ir_value *target = global->constval.vpointer;
2258 irerror(global->context, "Invalid pointer constant: %s\n", global->name);
2259 /* NULL pointers are pointing to the NULL constant, which also
2260 * sits at address 0, but still has an ir_value for itself.
2265 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2266 * void() foo; <- proto
2267 * void() *fooptr = &foo;
2268 * void() foo = { code }
2270 if (!target->code.globaladdr) {
2271 /* FIXME: Check for the constant nullptr ir_value!
2272 * because then code.globaladdr being 0 is valid.
2274 irerror(global->context, "FIXME: Relocation support\n");
2278 ir_value_code_setaddr(global, code_globals_add(target->code.globaladdr));
2282 ir_value_code_setaddr(global, code_globals_add(0));
2284 if (global->code.globaladdr < 0)
2289 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2291 prog_section_statement stmt;
2300 block->generated = true;
2301 block->code_start = code_statements_elements;
2302 for (i = 0; i < block->instr_count; ++i)
2304 instr = block->instr[i];
2306 if (instr->opcode == VINSTR_PHI) {
2307 irerror(block->context, "cannot generate virtual instruction (phi)\n");
2311 if (instr->opcode == VINSTR_JUMP) {
2312 target = instr->bops[0];
2313 /* for uncoditional jumps, if the target hasn't been generated
2314 * yet, we generate them right here.
2316 if (!target->generated) {
2321 /* otherwise we generate a jump instruction */
2322 stmt.opcode = INSTR_GOTO;
2323 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2326 if (code_statements_add(stmt) < 0)
2329 /* no further instructions can be in this block */
2333 if (instr->opcode == VINSTR_COND) {
2334 ontrue = instr->bops[0];
2335 onfalse = instr->bops[1];
2336 /* TODO: have the AST signal which block should
2337 * come first: eg. optimize IFs without ELSE...
2340 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2344 if (ontrue->generated) {
2345 stmt.opcode = INSTR_IF;
2346 stmt.o2.s1 = (ontrue->code_start) - code_statements_elements;
2347 if (code_statements_add(stmt) < 0)
2350 if (onfalse->generated) {
2351 stmt.opcode = INSTR_IFNOT;
2352 stmt.o2.s1 = (onfalse->code_start) - code_statements_elements;
2353 if (code_statements_add(stmt) < 0)
2356 if (!ontrue->generated) {
2357 if (onfalse->generated) {
2362 if (!onfalse->generated) {
2363 if (ontrue->generated) {
2368 /* neither ontrue nor onfalse exist */
2369 stmt.opcode = INSTR_IFNOT;
2370 stidx = code_statements_elements;
2371 if (code_statements_add(stmt) < 0)
2373 /* on false we jump, so add ontrue-path */
2374 if (!gen_blocks_recursive(func, ontrue))
2376 /* fixup the jump address */
2377 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2378 /* generate onfalse path */
2379 if (onfalse->generated) {
2380 /* fixup the jump address */
2381 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2382 /* may have been generated in the previous recursive call */
2383 stmt.opcode = INSTR_GOTO;
2384 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2387 return (code_statements_add(stmt) >= 0);
2389 /* if not, generate now */
2394 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2395 /* Trivial call translation:
2396 * copy all params to OFS_PARM*
2397 * if the output's storetype is not store_return,
2398 * add append a STORE instruction!
2400 * NOTES on how to do it better without much trouble:
2401 * -) The liferanges!
2402 * Simply check the liferange of all parameters for
2403 * other CALLs. For each param with no CALL in its
2404 * liferange, we can store it in an OFS_PARM at
2405 * generation already. This would even include later
2406 * reuse.... probably... :)
2411 for (p = 0; p < instr->params_count; ++p)
2413 ir_value *param = instr->params[p];
2415 stmt.opcode = INSTR_STORE_F;
2418 stmt.opcode = type_store_instr[param->vtype];
2419 stmt.o1.u1 = ir_value_code_addr(param);
2420 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2421 if (code_statements_add(stmt) < 0)
2424 stmt.opcode = INSTR_CALL0 + instr->params_count;
2425 if (stmt.opcode > INSTR_CALL8)
2426 stmt.opcode = INSTR_CALL8;
2427 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2430 if (code_statements_add(stmt) < 0)
2433 retvalue = instr->_ops[0];
2434 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2436 /* not to be kept in OFS_RETURN */
2437 stmt.opcode = type_store_instr[retvalue->vtype];
2438 stmt.o1.u1 = OFS_RETURN;
2439 stmt.o2.u1 = ir_value_code_addr(retvalue);
2441 if (code_statements_add(stmt) < 0)
2447 if (instr->opcode == INSTR_STATE) {
2448 irerror(block->context, "TODO: state instruction\n");
2452 stmt.opcode = instr->opcode;
2457 /* This is the general order of operands */
2459 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2462 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2465 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2467 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2469 stmt.o1.u1 = stmt.o3.u1;
2472 else if ((stmt.opcode >= INSTR_STORE_F &&
2473 stmt.opcode <= INSTR_STORE_FNC) ||
2474 (stmt.opcode >= INSTR_STOREP_F &&
2475 stmt.opcode <= INSTR_STOREP_FNC))
2477 /* 2-operand instructions with A -> B */
2478 stmt.o2.u1 = stmt.o3.u1;
2482 if (code_statements_add(stmt) < 0)
2488 static bool gen_function_code(ir_function *self)
2491 prog_section_statement stmt;
2493 /* Starting from entry point, we generate blocks "as they come"
2494 * for now. Dead blocks will not be translated obviously.
2496 if (!self->blocks_count) {
2497 irerror(self->context, "Function '%s' declared without body.\n", self->name);
2501 block = self->blocks[0];
2502 if (block->generated)
2505 if (!gen_blocks_recursive(self, block)) {
2506 irerror(self->context, "failed to generate blocks for '%s'\n", self->name);
2510 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2511 stmt.opcode = AINSTR_END;
2515 if (code_statements_add(stmt) < 0)
2520 static bool gen_global_function(ir_builder *ir, ir_value *global)
2522 prog_section_function fun;
2526 size_t local_var_end;
2528 if (!global->isconst || (!global->constval.vfunc))
2530 irerror(global->context, "Invalid state of function-global: not constant: %s\n", global->name);
2534 irfun = global->constval.vfunc;
2536 fun.name = global->code.name;
2537 fun.file = code_cachedstring(global->context.file);
2538 fun.profile = 0; /* always 0 */
2539 fun.nargs = irfun->params_count;
2541 for (i = 0;i < 8; ++i) {
2545 fun.argsize[i] = type_sizeof[irfun->params[i]];
2548 fun.firstlocal = code_globals_elements;
2549 fun.locals = irfun->allocated_locals + irfun->locals_count;
2552 for (i = 0; i < irfun->locals_count; ++i) {
2553 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2554 irerror(irfun->locals[i]->context, "Failed to generate global %s\n", irfun->locals[i]->name);
2558 if (irfun->locals_count) {
2559 ir_value *last = irfun->locals[irfun->locals_count-1];
2560 local_var_end = last->code.globaladdr;
2561 local_var_end += type_sizeof[last->vtype];
2563 for (i = 0; i < irfun->values_count; ++i)
2565 /* generate code.globaladdr for ssa values */
2566 ir_value *v = irfun->values[i];
2567 ir_value_code_setaddr(v, local_var_end + v->code.local);
2569 for (i = 0; i < irfun->locals_count; ++i) {
2570 /* fill the locals with zeros */
2571 code_globals_add(0);
2575 fun.entry = irfun->builtin;
2577 fun.entry = code_statements_elements;
2578 if (!gen_function_code(irfun)) {
2579 irerror(irfun->context, "Failed to generate code for function %s\n", irfun->name);
2584 return (code_functions_add(fun) >= 0);
2587 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2591 prog_section_def def;
2593 def.type = global->vtype;
2594 def.offset = code_globals_elements;
2595 def.name = global->code.name = code_genstring(global->name);
2597 switch (global->vtype)
2600 if (code_defs_add(def) < 0)
2602 return gen_global_pointer(global);
2604 if (code_defs_add(def) < 0)
2606 return gen_global_field(global);
2611 if (code_defs_add(def) < 0)
2614 if (global->isconst) {
2615 iptr = (int32_t*)&global->constval.vfloat;
2616 ir_value_code_setaddr(global, code_globals_add(*iptr));
2618 ir_value_code_setaddr(global, code_globals_add(0));
2620 return global->code.globaladdr >= 0;
2624 if (code_defs_add(def) < 0)
2626 if (global->isconst)
2627 ir_value_code_setaddr(global, code_globals_add(code_cachedstring(global->constval.vstring)));
2629 ir_value_code_setaddr(global, code_globals_add(0));
2630 return global->code.globaladdr >= 0;
2635 if (code_defs_add(def) < 0)
2638 if (global->isconst) {
2639 iptr = (int32_t*)&global->constval.vvec;
2640 ir_value_code_setaddr(global, code_globals_add(iptr[0]));
2641 if (global->code.globaladdr < 0)
2643 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2645 if (code_globals_add(iptr[d]) < 0)
2649 ir_value_code_setaddr(global, code_globals_add(0));
2650 if (global->code.globaladdr < 0)
2652 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2654 if (code_globals_add(0) < 0)
2658 return global->code.globaladdr >= 0;
2661 if (code_defs_add(def) < 0)
2663 ir_value_code_setaddr(global, code_globals_elements);
2664 code_globals_add(code_functions_elements);
2665 return gen_global_function(self, global);
2667 /* assume biggest type */
2668 ir_value_code_setaddr(global, code_globals_add(0));
2669 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2670 code_globals_add(0);
2673 /* refuse to create 'void' type or any other fancy business. */
2674 irerror(global->context, "Invalid type for global variable %s\n", global->name);
2679 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2681 prog_section_def def;
2682 prog_section_field fld;
2684 def.type = field->vtype;
2685 def.offset = code_globals_elements;
2687 /* create a global named the same as the field */
2688 if (opts_standard == COMPILER_GMQCC) {
2689 /* in our standard, the global gets a dot prefix */
2690 size_t len = strlen(field->name);
2693 /* we really don't want to have to allocate this, and 1024
2694 * bytes is more than enough for a variable/field name
2696 if (len+2 >= sizeof(name)) {
2697 irerror(field->context, "invalid field name size: %u\n", (unsigned int)len);
2702 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
2705 def.name = code_genstring(name);
2706 fld.name = def.name + 1; /* we reuse that string table entry */
2708 /* in plain QC, there cannot be a global with the same name,
2709 * and so we also name the global the same.
2710 * FIXME: fteqcc should create a global as well
2711 * check if it actually uses the same name. Probably does
2713 def.name = code_genstring(field->name);
2714 fld.name = def.name;
2717 field->code.name = def.name;
2719 if (code_defs_add(def) < 0)
2722 fld.type = field->fieldtype;
2724 if (fld.type == TYPE_VOID) {
2725 irerror(field->context, "field is missing a type: %s - don't know its size\n", field->name);
2729 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2731 if (code_fields_add(fld) < 0)
2734 ir_value_code_setaddr(field, code_globals_elements);
2735 if (!code_globals_add(fld.offset))
2737 if (fld.type == TYPE_VECTOR) {
2738 if (!code_globals_add(fld.offset+1))
2740 if (!code_globals_add(fld.offset+2))
2744 return field->code.globaladdr >= 0;
2747 bool ir_builder_generate(ir_builder *self, const char *filename)
2753 for (i = 0; i < self->fields_count; ++i)
2755 if (!ir_builder_gen_field(self, self->fields[i])) {
2760 for (i = 0; i < self->globals_count; ++i)
2762 if (!ir_builder_gen_global(self, self->globals[i])) {
2767 printf("writing '%s'...\n", filename);
2768 return code_write(filename);
2771 /***********************************************************************
2772 *IR DEBUG Dump functions...
2775 #define IND_BUFSZ 1024
2778 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
2780 # define strncat strncat
2783 const char *qc_opname(int op)
2785 if (op < 0) return "<INVALID>";
2786 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2787 return asm_instr[op].m;
2789 case VINSTR_PHI: return "PHI";
2790 case VINSTR_JUMP: return "JUMP";
2791 case VINSTR_COND: return "COND";
2792 default: return "<UNK>";
2796 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2799 char indent[IND_BUFSZ];
2803 oprintf("module %s\n", b->name);
2804 for (i = 0; i < b->globals_count; ++i)
2807 if (b->globals[i]->isconst)
2808 oprintf("%s = ", b->globals[i]->name);
2809 ir_value_dump(b->globals[i], oprintf);
2812 for (i = 0; i < b->functions_count; ++i)
2813 ir_function_dump(b->functions[i], indent, oprintf);
2814 oprintf("endmodule %s\n", b->name);
2817 void ir_function_dump(ir_function *f, char *ind,
2818 int (*oprintf)(const char*, ...))
2821 if (f->builtin != 0) {
2822 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2825 oprintf("%sfunction %s\n", ind, f->name);
2826 strncat(ind, "\t", IND_BUFSZ);
2827 if (f->locals_count)
2829 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2830 for (i = 0; i < f->locals_count; ++i) {
2831 oprintf("%s\t", ind);
2832 ir_value_dump(f->locals[i], oprintf);
2836 if (f->blocks_count)
2838 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2839 for (i = 0; i < f->blocks_count; ++i) {
2840 if (f->blocks[i]->run_id != f->run_id) {
2841 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2843 ir_block_dump(f->blocks[i], ind, oprintf);
2847 ind[strlen(ind)-1] = 0;
2848 oprintf("%sendfunction %s\n", ind, f->name);
2851 void ir_block_dump(ir_block* b, char *ind,
2852 int (*oprintf)(const char*, ...))
2855 oprintf("%s:%s\n", ind, b->label);
2856 strncat(ind, "\t", IND_BUFSZ);
2858 for (i = 0; i < b->instr_count; ++i)
2859 ir_instr_dump(b->instr[i], ind, oprintf);
2860 ind[strlen(ind)-1] = 0;
2863 void dump_phi(ir_instr *in, char *ind,
2864 int (*oprintf)(const char*, ...))
2867 oprintf("%s <- phi ", in->_ops[0]->name);
2868 for (i = 0; i < in->phi_count; ++i)
2870 oprintf("([%s] : %s) ", in->phi[i].from->label,
2871 in->phi[i].value->name);
2876 void ir_instr_dump(ir_instr *in, char *ind,
2877 int (*oprintf)(const char*, ...))
2880 const char *comma = NULL;
2882 oprintf("%s (%i) ", ind, (int)in->eid);
2884 if (in->opcode == VINSTR_PHI) {
2885 dump_phi(in, ind, oprintf);
2889 strncat(ind, "\t", IND_BUFSZ);
2891 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2892 ir_value_dump(in->_ops[0], oprintf);
2893 if (in->_ops[1] || in->_ops[2])
2896 if (in->opcode == INSTR_CALL0) {
2897 oprintf("CALL%i\t", in->params_count);
2899 oprintf("%s\t", qc_opname(in->opcode));
2901 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2902 ir_value_dump(in->_ops[0], oprintf);
2907 for (i = 1; i != 3; ++i) {
2911 ir_value_dump(in->_ops[i], oprintf);
2919 oprintf("[%s]", in->bops[0]->label);
2923 oprintf("%s[%s]", comma, in->bops[1]->label);
2925 ind[strlen(ind)-1] = 0;
2928 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
2937 oprintf("(function)");
2940 oprintf("%g", v->constval.vfloat);
2943 oprintf("'%g %g %g'",
2946 v->constval.vvec.z);
2949 oprintf("(entity)");
2952 oprintf("\"%s\"", v->constval.vstring);
2956 oprintf("%i", v->constval.vint);
2961 v->constval.vpointer->name);
2965 oprintf("%s", v->name);
2969 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
2972 oprintf("Life of %s:\n", self->name);
2973 for (i = 0; i < self->life_count; ++i)
2975 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);