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 size_t type_sizeof[TYPE_COUNT] = {
39 1, /* TYPE_FUNCTION */
47 uint16_t type_store_instr[TYPE_COUNT] = {
48 INSTR_STORE_F, /* should use I when having integer support */
55 INSTR_STORE_ENT, /* should use I */
57 INSTR_STORE_ENT, /* integer type */
59 INSTR_STORE_V, /* variant, should never be accessed */
62 uint16_t type_storep_instr[TYPE_COUNT] = {
63 INSTR_STOREP_F, /* should use I when having integer support */
70 INSTR_STOREP_ENT, /* should use I */
72 INSTR_STOREP_ENT, /* integer type */
74 INSTR_STOREP_V, /* variant, should never be accessed */
77 MEM_VEC_FUNCTIONS(ir_value_vector, ir_value*, v)
79 /***********************************************************************
83 ir_builder* ir_builder_new(const char *modulename)
87 self = (ir_builder*)mem_a(sizeof(*self));
91 MEM_VECTOR_INIT(self, functions);
92 MEM_VECTOR_INIT(self, globals);
93 MEM_VECTOR_INIT(self, fields);
95 if (!ir_builder_set_name(self, modulename)) {
100 /* globals which always exist */
102 /* for now we give it a vector size */
103 ir_builder_create_global(self, "OFS_RETURN", TYPE_VARIANT);
108 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
109 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, fields)
110 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
112 void ir_builder_delete(ir_builder* self)
115 mem_d((void*)self->name);
116 for (i = 0; i != self->functions_count; ++i) {
117 ir_function_delete(self->functions[i]);
119 MEM_VECTOR_CLEAR(self, functions);
120 for (i = 0; i != self->globals_count; ++i) {
121 ir_value_delete(self->globals[i]);
123 MEM_VECTOR_CLEAR(self, fields);
124 for (i = 0; i != self->fields_count; ++i) {
125 ir_value_delete(self->fields[i]);
127 MEM_VECTOR_CLEAR(self, fields);
131 bool ir_builder_set_name(ir_builder *self, const char *name)
134 mem_d((void*)self->name);
135 self->name = util_strdup(name);
139 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
142 for (i = 0; i < self->functions_count; ++i) {
143 if (!strcmp(name, self->functions[i]->name))
144 return self->functions[i];
149 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
151 ir_function *fn = ir_builder_get_function(self, name);
156 fn = ir_function_new(self, outtype);
157 if (!ir_function_set_name(fn, name) ||
158 !ir_builder_functions_add(self, fn) )
160 ir_function_delete(fn);
164 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
166 ir_function_delete(fn);
170 fn->value->isconst = true;
171 fn->value->outtype = outtype;
172 fn->value->constval.vfunc = fn;
173 fn->value->context = fn->context;
178 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
181 for (i = 0; i < self->globals_count; ++i) {
182 if (!strcmp(self->globals[i]->name, name))
183 return self->globals[i];
188 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
190 ir_value *ve = ir_builder_get_global(self, name);
195 ve = ir_value_var(name, store_global, vtype);
196 if (!ir_builder_globals_add(self, ve)) {
203 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
206 for (i = 0; i < self->fields_count; ++i) {
207 if (!strcmp(self->fields[i]->name, name))
208 return self->fields[i];
214 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
216 ir_value *ve = ir_builder_get_field(self, name);
221 ve = ir_value_var(name, store_global, TYPE_FIELD);
222 ve->fieldtype = vtype;
223 if (!ir_builder_fields_add(self, ve)) {
230 /***********************************************************************
234 bool ir_function_naive_phi(ir_function*);
235 void ir_function_enumerate(ir_function*);
236 bool ir_function_calculate_liferanges(ir_function*);
237 bool ir_function_allocate_locals(ir_function*);
239 ir_function* ir_function_new(ir_builder* owner, int outtype)
242 self = (ir_function*)mem_a(sizeof(*self));
248 if (!ir_function_set_name(self, "<@unnamed>")) {
253 self->context.file = "<@no context>";
254 self->context.line = 0;
255 self->outtype = outtype;
258 MEM_VECTOR_INIT(self, params);
259 MEM_VECTOR_INIT(self, blocks);
260 MEM_VECTOR_INIT(self, values);
261 MEM_VECTOR_INIT(self, locals);
266 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
267 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
268 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
269 MEM_VEC_FUNCTIONS(ir_function, int, params)
271 bool ir_function_set_name(ir_function *self, const char *name)
274 mem_d((void*)self->name);
275 self->name = util_strdup(name);
279 void ir_function_delete(ir_function *self)
282 mem_d((void*)self->name);
284 for (i = 0; i != self->blocks_count; ++i)
285 ir_block_delete(self->blocks[i]);
286 MEM_VECTOR_CLEAR(self, blocks);
288 MEM_VECTOR_CLEAR(self, params);
290 for (i = 0; i != self->values_count; ++i)
291 ir_value_delete(self->values[i]);
292 MEM_VECTOR_CLEAR(self, values);
294 for (i = 0; i != self->locals_count; ++i)
295 ir_value_delete(self->locals[i]);
296 MEM_VECTOR_CLEAR(self, locals);
298 /* self->value is deleted by the builder */
303 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
305 return ir_function_values_add(self, v);
308 ir_block* ir_function_create_block(ir_function *self, const char *label)
310 ir_block* bn = ir_block_new(self, label);
311 memcpy(&bn->context, &self->context, sizeof(self->context));
312 if (!ir_function_blocks_add(self, bn)) {
319 bool ir_function_finalize(ir_function *self)
324 if (!ir_function_naive_phi(self))
327 ir_function_enumerate(self);
329 if (!ir_function_calculate_liferanges(self))
332 if (!ir_function_allocate_locals(self))
337 ir_value* ir_function_get_local(ir_function *self, const char *name)
340 for (i = 0; i < self->locals_count; ++i) {
341 if (!strcmp(self->locals[i]->name, name))
342 return self->locals[i];
347 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
349 ir_value *ve = ir_function_get_local(self, name);
355 self->locals_count &&
356 self->locals[self->locals_count-1]->store != store_param) {
357 printf("cannot add parameters after adding locals\n");
361 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
362 if (!ir_function_locals_add(self, ve)) {
369 /***********************************************************************
373 ir_block* ir_block_new(ir_function* owner, const char *name)
376 self = (ir_block*)mem_a(sizeof(*self));
380 memset(self, 0, sizeof(*self));
383 if (!ir_block_set_label(self, name)) {
388 self->context.file = "<@no context>";
389 self->context.line = 0;
391 MEM_VECTOR_INIT(self, instr);
392 MEM_VECTOR_INIT(self, entries);
393 MEM_VECTOR_INIT(self, exits);
396 self->is_return = false;
398 MEM_VECTOR_INIT(self, living);
400 self->generated = false;
404 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
405 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
406 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
407 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
409 void ir_block_delete(ir_block* self)
413 for (i = 0; i != self->instr_count; ++i)
414 ir_instr_delete(self->instr[i]);
415 MEM_VECTOR_CLEAR(self, instr);
416 MEM_VECTOR_CLEAR(self, entries);
417 MEM_VECTOR_CLEAR(self, exits);
418 MEM_VECTOR_CLEAR(self, living);
422 bool ir_block_set_label(ir_block *self, const char *name)
425 mem_d((void*)self->label);
426 self->label = util_strdup(name);
427 return !!self->label;
430 /***********************************************************************
434 ir_instr* ir_instr_new(ir_block* owner, int op)
437 self = (ir_instr*)mem_a(sizeof(*self));
442 self->context.file = "<@no context>";
443 self->context.line = 0;
445 self->_ops[0] = NULL;
446 self->_ops[1] = NULL;
447 self->_ops[2] = NULL;
448 self->bops[0] = NULL;
449 self->bops[1] = NULL;
450 MEM_VECTOR_INIT(self, phi);
451 MEM_VECTOR_INIT(self, params);
456 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
457 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
459 void ir_instr_delete(ir_instr *self)
462 /* The following calls can only delete from
463 * vectors, we still want to delete this instruction
464 * so ignore the return value. Since with the warn_unused_result attribute
465 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
466 * I have to improvise here and use if(foo());
468 for (i = 0; i < self->phi_count; ++i) {
470 if (ir_value_writes_find(self->phi[i].value, self, &idx))
471 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
472 if (ir_value_reads_find(self->phi[i].value, self, &idx))
473 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
475 MEM_VECTOR_CLEAR(self, phi);
476 for (i = 0; i < self->params_count; ++i) {
478 if (ir_value_writes_find(self->params[i], self, &idx))
479 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
480 if (ir_value_reads_find(self->params[i], self, &idx))
481 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
483 MEM_VECTOR_CLEAR(self, params);
484 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
485 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
486 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
490 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
492 if (self->_ops[op]) {
494 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
496 if (!ir_value_writes_remove(self->_ops[op], idx))
499 else if (ir_value_reads_find(self->_ops[op], self, &idx))
501 if (!ir_value_reads_remove(self->_ops[op], idx))
507 if (!ir_value_writes_add(v, self))
510 if (!ir_value_reads_add(v, self))
518 /***********************************************************************
522 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
524 self->code.globaladdr = gaddr;
525 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
526 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
527 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
530 int32_t ir_value_code_addr(const ir_value *self)
532 if (self->store == store_return)
533 return OFS_RETURN + self->code.addroffset;
534 return self->code.globaladdr + self->code.addroffset;
537 ir_value* ir_value_var(const char *name, int storetype, int vtype)
540 self = (ir_value*)mem_a(sizeof(*self));
542 self->fieldtype = TYPE_VOID;
543 self->outtype = TYPE_VOID;
544 self->store = storetype;
545 MEM_VECTOR_INIT(self, reads);
546 MEM_VECTOR_INIT(self, writes);
547 self->isconst = false;
548 self->context.file = "<@no context>";
549 self->context.line = 0;
551 ir_value_set_name(self, name);
553 memset(&self->constval, 0, sizeof(self->constval));
554 memset(&self->code, 0, sizeof(self->code));
556 MEM_VECTOR_INIT(self, life);
560 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
566 if (self->members[member])
567 return self->members[member];
569 m = ir_value_var(self->name, self->store, TYPE_FLOAT);
572 m->context = self->context;
574 self->members[member] = m;
575 m->code.addroffset = member;
580 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
581 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
582 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
584 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
586 ir_value *v = ir_value_var(name, storetype, vtype);
589 if (!ir_function_collect_value(owner, v))
597 void ir_value_delete(ir_value* self)
601 mem_d((void*)self->name);
604 if (self->vtype == TYPE_STRING)
605 mem_d((void*)self->constval.vstring);
607 for (i = 0; i < 3; ++i) {
608 if (self->members[i])
609 ir_value_delete(self->members[i]);
611 MEM_VECTOR_CLEAR(self, reads);
612 MEM_VECTOR_CLEAR(self, writes);
613 MEM_VECTOR_CLEAR(self, life);
617 void ir_value_set_name(ir_value *self, const char *name)
620 mem_d((void*)self->name);
621 self->name = util_strdup(name);
624 bool ir_value_set_float(ir_value *self, float f)
626 if (self->vtype != TYPE_FLOAT)
628 self->constval.vfloat = f;
629 self->isconst = true;
633 bool ir_value_set_func(ir_value *self, int f)
635 if (self->vtype != TYPE_FUNCTION)
637 self->constval.vint = f;
638 self->isconst = true;
642 bool ir_value_set_vector(ir_value *self, vector v)
644 if (self->vtype != TYPE_VECTOR)
646 self->constval.vvec = v;
647 self->isconst = true;
651 bool ir_value_set_field(ir_value *self, ir_value *fld)
653 if (self->vtype != TYPE_FIELD)
655 self->constval.vpointer = fld;
656 self->isconst = true;
660 bool ir_value_set_string(ir_value *self, const char *str)
662 if (self->vtype != TYPE_STRING)
664 self->constval.vstring = util_strdup(str);
665 self->isconst = true;
670 bool ir_value_set_int(ir_value *self, int i)
672 if (self->vtype != TYPE_INTEGER)
674 self->constval.vint = i;
675 self->isconst = true;
680 bool ir_value_lives(ir_value *self, size_t at)
683 for (i = 0; i < self->life_count; ++i)
685 ir_life_entry_t *life = &self->life[i];
686 if (life->start <= at && at <= life->end)
688 if (life->start > at) /* since it's ordered */
694 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
697 if (!ir_value_life_add(self, e)) /* naive... */
699 for (k = self->life_count-1; k > idx; --k)
700 self->life[k] = self->life[k-1];
705 bool ir_value_life_merge(ir_value *self, size_t s)
708 ir_life_entry_t *life = NULL;
709 ir_life_entry_t *before = NULL;
710 ir_life_entry_t new_entry;
712 /* Find the first range >= s */
713 for (i = 0; i < self->life_count; ++i)
716 life = &self->life[i];
720 /* nothing found? append */
721 if (i == self->life_count) {
723 if (life && life->end+1 == s)
725 /* previous life range can be merged in */
729 if (life && life->end >= s)
732 if (!ir_value_life_add(self, e))
733 return false; /* failing */
739 if (before->end + 1 == s &&
740 life->start - 1 == s)
743 before->end = life->end;
744 if (!ir_value_life_remove(self, i))
745 return false; /* failing */
748 if (before->end + 1 == s)
754 /* already contained */
755 if (before->end >= s)
759 if (life->start - 1 == s)
764 /* insert a new entry */
765 new_entry.start = new_entry.end = s;
766 return ir_value_life_insert(self, i, new_entry);
769 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
773 if (!other->life_count)
776 if (!self->life_count) {
777 for (i = 0; i < other->life_count; ++i) {
778 if (!ir_value_life_add(self, other->life[i]))
785 for (i = 0; i < other->life_count; ++i)
787 const ir_life_entry_t *life = &other->life[i];
790 ir_life_entry_t *entry = &self->life[myi];
792 if (life->end+1 < entry->start)
794 /* adding an interval before entry */
795 if (!ir_value_life_insert(self, myi, *life))
801 if (life->start < entry->start &&
802 life->end >= entry->start)
804 /* starts earlier and overlaps */
805 entry->start = life->start;
808 if (life->end > entry->end &&
809 life->start-1 <= entry->end)
811 /* ends later and overlaps */
812 entry->end = life->end;
815 /* see if our change combines it with the next ranges */
816 while (myi+1 < self->life_count &&
817 entry->end+1 >= self->life[1+myi].start)
819 /* overlaps with (myi+1) */
820 if (entry->end < self->life[1+myi].end)
821 entry->end = self->life[1+myi].end;
822 if (!ir_value_life_remove(self, myi+1))
824 entry = &self->life[myi];
827 /* see if we're after the entry */
828 if (life->start > entry->end)
831 /* append if we're at the end */
832 if (myi >= self->life_count) {
833 if (!ir_value_life_add(self, *life))
837 /* otherweise check the next range */
846 bool ir_values_overlap(const ir_value *a, const ir_value *b)
848 /* For any life entry in A see if it overlaps with
849 * any life entry in B.
850 * Note that the life entries are orderes, so we can make a
851 * more efficient algorithm there than naively translating the
855 ir_life_entry_t *la, *lb, *enda, *endb;
857 /* first of all, if either has no life range, they cannot clash */
858 if (!a->life_count || !b->life_count)
863 enda = la + a->life_count;
864 endb = lb + b->life_count;
867 /* check if the entries overlap, for that,
868 * both must start before the other one ends.
870 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
871 if (la->start <= lb->end &&
872 lb->start <= la->end)
874 if (la->start < lb->end &&
881 /* entries are ordered
882 * one entry is earlier than the other
883 * that earlier entry will be moved forward
885 if (la->start < lb->start)
887 /* order: A B, move A forward
888 * check if we hit the end with A
893 else if (lb->start < la->start)
895 /* order: B A, move B forward
896 * check if we hit the end with B
905 /***********************************************************************
909 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
911 ir_instr *in = ir_instr_new(self, op);
915 if (target->store == store_value &&
916 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
918 fprintf(stderr, "cannot store to an SSA value\n");
919 fprintf(stderr, "trying to store: %s <- %s\n", target->name, what->name);
920 fprintf(stderr, "instruction: %s\n", asm_instr[op].m);
924 if (!ir_instr_op(in, 0, target, true) ||
925 !ir_instr_op(in, 1, what, false) ||
926 !ir_block_instr_add(self, in) )
933 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
937 if (target->vtype == TYPE_VARIANT)
940 vtype = target->vtype;
943 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
944 op = INSTR_CONV_ITOF;
945 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
946 op = INSTR_CONV_FTOI;
948 op = type_store_instr[vtype];
950 return ir_block_create_store_op(self, op, target, what);
953 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
958 if (target->vtype != TYPE_POINTER)
961 /* storing using pointer - target is a pointer, type must be
962 * inferred from source
966 op = type_storep_instr[vtype];
968 return ir_block_create_store_op(self, op, target, what);
971 bool ir_block_create_return(ir_block *self, ir_value *v)
975 fprintf(stderr, "block already ended (%s)\n", self->label);
979 self->is_return = true;
980 in = ir_instr_new(self, INSTR_RETURN);
984 if (!ir_instr_op(in, 0, v, false) ||
985 !ir_block_instr_add(self, in) )
992 bool ir_block_create_if(ir_block *self, ir_value *v,
993 ir_block *ontrue, ir_block *onfalse)
997 fprintf(stderr, "block already ended (%s)\n", self->label);
1001 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1002 in = ir_instr_new(self, VINSTR_COND);
1006 if (!ir_instr_op(in, 0, v, false)) {
1007 ir_instr_delete(in);
1011 in->bops[0] = ontrue;
1012 in->bops[1] = onfalse;
1014 if (!ir_block_instr_add(self, in))
1017 if (!ir_block_exits_add(self, ontrue) ||
1018 !ir_block_exits_add(self, onfalse) ||
1019 !ir_block_entries_add(ontrue, self) ||
1020 !ir_block_entries_add(onfalse, self) )
1027 bool ir_block_create_jump(ir_block *self, ir_block *to)
1031 fprintf(stderr, "block already ended (%s)\n", self->label);
1035 in = ir_instr_new(self, VINSTR_JUMP);
1040 if (!ir_block_instr_add(self, in))
1043 if (!ir_block_exits_add(self, to) ||
1044 !ir_block_entries_add(to, self) )
1051 bool ir_block_create_goto(ir_block *self, ir_block *to)
1055 fprintf(stderr, "block already ended (%s)\n", self->label);
1059 in = ir_instr_new(self, INSTR_GOTO);
1064 if (!ir_block_instr_add(self, in))
1067 if (!ir_block_exits_add(self, to) ||
1068 !ir_block_entries_add(to, self) )
1075 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1079 in = ir_instr_new(self, VINSTR_PHI);
1082 out = ir_value_out(self->owner, label, store_value, ot);
1084 ir_instr_delete(in);
1087 if (!ir_instr_op(in, 0, out, true)) {
1088 ir_instr_delete(in);
1089 ir_value_delete(out);
1092 if (!ir_block_instr_add(self, in)) {
1093 ir_instr_delete(in);
1094 ir_value_delete(out);
1100 ir_value* ir_phi_value(ir_instr *self)
1102 return self->_ops[0];
1105 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1109 if (!ir_block_entries_find(self->owner, b, NULL)) {
1110 /* Must not be possible to cause this, otherwise the AST
1111 * is doing something wrong.
1113 fprintf(stderr, "Invalid entry block for PHI\n");
1119 if (!ir_value_reads_add(v, self))
1121 return ir_instr_phi_add(self, pe);
1124 /* call related code */
1125 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1129 in = ir_instr_new(self, INSTR_CALL0);
1132 out = ir_value_out(self->owner, label, store_return, func->outtype);
1134 ir_instr_delete(in);
1137 if (!ir_instr_op(in, 0, out, true) ||
1138 !ir_instr_op(in, 1, func, false) ||
1139 !ir_block_instr_add(self, in))
1141 ir_instr_delete(in);
1142 ir_value_delete(out);
1148 ir_value* ir_call_value(ir_instr *self)
1150 return self->_ops[0];
1153 bool ir_call_param(ir_instr* self, ir_value *v)
1155 if (!ir_instr_params_add(self, v))
1157 if (!ir_value_reads_add(v, self)) {
1158 if (!ir_instr_params_remove(self, self->params_count-1))
1159 GMQCC_SUPPRESS_EMPTY_BODY;
1165 /* binary op related code */
1167 ir_value* ir_block_create_binop(ir_block *self,
1168 const char *label, int opcode,
1169 ir_value *left, ir_value *right)
1191 case INSTR_SUB_S: /* -- offset of string as float */
1196 case INSTR_BITOR_IF:
1197 case INSTR_BITOR_FI:
1198 case INSTR_BITAND_FI:
1199 case INSTR_BITAND_IF:
1214 case INSTR_BITAND_I:
1217 case INSTR_RSHIFT_I:
1218 case INSTR_LSHIFT_I:
1240 /* boolean operations result in floats */
1241 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1243 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1246 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1251 if (ot == TYPE_VOID) {
1252 /* The AST or parser were supposed to check this! */
1256 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1259 ir_value* ir_block_create_unary(ir_block *self,
1260 const char *label, int opcode,
1263 int ot = TYPE_FLOAT;
1275 /* QC doesn't have other unary operations. We expect extensions to fill
1276 * the above list, otherwise we assume out-type = in-type, eg for an
1280 ot = operand->vtype;
1283 if (ot == TYPE_VOID) {
1284 /* The AST or parser were supposed to check this! */
1288 /* let's use the general instruction creator and pass NULL for OPB */
1289 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1292 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1293 int op, ir_value *a, ir_value *b, int outype)
1298 out = ir_value_out(self->owner, label, store_value, outype);
1302 instr = ir_instr_new(self, op);
1304 ir_value_delete(out);
1308 if (!ir_instr_op(instr, 0, out, true) ||
1309 !ir_instr_op(instr, 1, a, false) ||
1310 !ir_instr_op(instr, 2, b, false) )
1315 if (!ir_block_instr_add(self, instr))
1320 ir_instr_delete(instr);
1321 ir_value_delete(out);
1325 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1329 /* Support for various pointer types todo if so desired */
1330 if (ent->vtype != TYPE_ENTITY)
1333 if (field->vtype != TYPE_FIELD)
1336 v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1337 v->fieldtype = field->fieldtype;
1341 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1344 if (ent->vtype != TYPE_ENTITY)
1347 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1348 if (field->vtype != TYPE_FIELD)
1353 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1354 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1355 case TYPE_STRING: op = INSTR_LOAD_S; break;
1356 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1357 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1359 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1360 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1366 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1369 ir_value* ir_block_create_add(ir_block *self,
1371 ir_value *left, ir_value *right)
1374 int l = left->vtype;
1375 int r = right->vtype;
1394 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1396 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1402 return ir_block_create_binop(self, label, op, left, right);
1405 ir_value* ir_block_create_sub(ir_block *self,
1407 ir_value *left, ir_value *right)
1410 int l = left->vtype;
1411 int r = right->vtype;
1431 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1433 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1439 return ir_block_create_binop(self, label, op, left, right);
1442 ir_value* ir_block_create_mul(ir_block *self,
1444 ir_value *left, ir_value *right)
1447 int l = left->vtype;
1448 int r = right->vtype;
1467 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1469 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1472 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1474 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1476 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1478 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1484 return ir_block_create_binop(self, label, op, left, right);
1487 ir_value* ir_block_create_div(ir_block *self,
1489 ir_value *left, ir_value *right)
1492 int l = left->vtype;
1493 int r = right->vtype;
1510 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1512 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1514 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1520 return ir_block_create_binop(self, label, op, left, right);
1523 /* PHI resolving breaks the SSA, and must thus be the last
1524 * step before life-range calculation.
1527 static bool ir_block_naive_phi(ir_block *self);
1528 bool ir_function_naive_phi(ir_function *self)
1532 for (i = 0; i < self->blocks_count; ++i)
1534 if (!ir_block_naive_phi(self->blocks[i]))
1540 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1545 /* create a store */
1546 if (!ir_block_create_store(block, old, what))
1549 /* we now move it up */
1550 instr = block->instr[block->instr_count-1];
1551 for (i = block->instr_count; i > iid; --i)
1552 block->instr[i] = block->instr[i-1];
1553 block->instr[i] = instr;
1558 static bool ir_block_naive_phi(ir_block *self)
1561 /* FIXME: optionally, create_phi can add the phis
1562 * to a list so we don't need to loop through blocks
1563 * - anyway: "don't optimize YET"
1565 for (i = 0; i < self->instr_count; ++i)
1567 ir_instr *instr = self->instr[i];
1568 if (instr->opcode != VINSTR_PHI)
1571 if (!ir_block_instr_remove(self, i))
1573 --i; /* NOTE: i+1 below */
1575 for (p = 0; p < instr->phi_count; ++p)
1577 ir_value *v = instr->phi[p].value;
1578 for (w = 0; w < v->writes_count; ++w) {
1581 if (!v->writes[w]->_ops[0])
1584 /* When the write was to a global, we have to emit a mov */
1585 old = v->writes[w]->_ops[0];
1587 /* The original instruction now writes to the PHI target local */
1588 if (v->writes[w]->_ops[0] == v)
1589 v->writes[w]->_ops[0] = instr->_ops[0];
1591 if (old->store != store_value && old->store != store_local && old->store != store_param)
1593 /* If it originally wrote to a global we need to store the value
1596 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1598 if (i+1 < self->instr_count)
1599 instr = self->instr[i+1];
1602 /* In case I forget and access instr later, it'll be NULL
1603 * when it's a problem, to make sure we crash, rather than accessing
1609 /* If it didn't, we can replace all reads by the phi target now. */
1611 for (r = 0; r < old->reads_count; ++r)
1614 ir_instr *ri = old->reads[r];
1615 for (op = 0; op < ri->phi_count; ++op) {
1616 if (ri->phi[op].value == old)
1617 ri->phi[op].value = v;
1619 for (op = 0; op < 3; ++op) {
1620 if (ri->_ops[op] == old)
1627 ir_instr_delete(instr);
1632 /***********************************************************************
1633 *IR Temp allocation code
1634 * Propagating value life ranges by walking through the function backwards
1635 * until no more changes are made.
1636 * In theory this should happen once more than once for every nested loop
1638 * Though this implementation might run an additional time for if nests.
1647 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1649 /* Enumerate instructions used by value's life-ranges
1651 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1655 for (i = 0; i < self->instr_count; ++i)
1657 self->instr[i]->eid = eid++;
1662 /* Enumerate blocks and instructions.
1663 * The block-enumeration is unordered!
1664 * We do not really use the block enumreation, however
1665 * the instruction enumeration is important for life-ranges.
1667 void ir_function_enumerate(ir_function *self)
1670 size_t instruction_id = 0;
1671 for (i = 0; i < self->blocks_count; ++i)
1673 self->blocks[i]->eid = i;
1674 self->blocks[i]->run_id = 0;
1675 ir_block_enumerate(self->blocks[i], &instruction_id);
1679 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1680 bool ir_function_calculate_liferanges(ir_function *self)
1688 for (i = 0; i != self->blocks_count; ++i)
1690 if (self->blocks[i]->is_return)
1692 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1700 /* Local-value allocator
1701 * After finishing creating the liferange of all values used in a function
1702 * we can allocate their global-positions.
1703 * This is the counterpart to register-allocation in register machines.
1706 MEM_VECTOR_MAKE(ir_value*, locals);
1707 MEM_VECTOR_MAKE(size_t, sizes);
1708 MEM_VECTOR_MAKE(size_t, positions);
1709 } function_allocator;
1710 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1711 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1712 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1714 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1717 size_t vsize = type_sizeof[var->vtype];
1719 slot = ir_value_var("reg", store_global, var->vtype);
1723 if (!ir_value_life_merge_into(slot, var))
1726 if (!function_allocator_locals_add(alloc, slot))
1729 if (!function_allocator_sizes_add(alloc, vsize))
1735 ir_value_delete(slot);
1739 bool ir_function_allocate_locals(ir_function *self)
1748 function_allocator alloc;
1750 if (!self->locals_count)
1753 MEM_VECTOR_INIT(&alloc, locals);
1754 MEM_VECTOR_INIT(&alloc, sizes);
1755 MEM_VECTOR_INIT(&alloc, positions);
1757 for (i = 0; i < self->locals_count; ++i)
1759 if (!function_allocator_alloc(&alloc, self->locals[i]))
1763 /* Allocate a slot for any value that still exists */
1764 for (i = 0; i < self->values_count; ++i)
1766 v = self->values[i];
1771 for (a = 0; a < alloc.locals_count; ++a)
1773 slot = alloc.locals[a];
1775 if (ir_values_overlap(v, slot))
1778 if (!ir_value_life_merge_into(slot, v))
1781 /* adjust size for this slot */
1782 if (alloc.sizes[a] < type_sizeof[v->vtype])
1783 alloc.sizes[a] = type_sizeof[v->vtype];
1785 self->values[i]->code.local = a;
1788 if (a >= alloc.locals_count) {
1789 self->values[i]->code.local = alloc.locals_count;
1790 if (!function_allocator_alloc(&alloc, v))
1795 /* Adjust slot positions based on sizes */
1796 if (!function_allocator_positions_add(&alloc, 0))
1799 if (alloc.sizes_count)
1800 pos = alloc.positions[0] + alloc.sizes[0];
1803 for (i = 1; i < alloc.sizes_count; ++i)
1805 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1806 if (!function_allocator_positions_add(&alloc, pos))
1810 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1812 /* Take over the actual slot positions */
1813 for (i = 0; i < self->values_count; ++i)
1814 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1821 for (i = 0; i < alloc.locals_count; ++i)
1822 ir_value_delete(alloc.locals[i]);
1823 MEM_VECTOR_CLEAR(&alloc, locals);
1824 MEM_VECTOR_CLEAR(&alloc, sizes);
1825 MEM_VECTOR_CLEAR(&alloc, positions);
1829 /* Get information about which operand
1830 * is read from, or written to.
1832 static void ir_op_read_write(int op, size_t *read, size_t *write)
1859 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1862 bool changed = false;
1864 for (i = 0; i != self->living_count; ++i)
1866 tempbool = ir_value_life_merge(self->living[i], eid);
1869 fprintf(stderr, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1871 changed = changed || tempbool;
1876 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1879 /* values which have been read in a previous iteration are now
1880 * in the "living" array even if the previous block doesn't use them.
1881 * So we have to remove whatever does not exist in the previous block.
1882 * They will be re-added on-read, but the liferange merge won't cause
1885 for (i = 0; i < self->living_count; ++i)
1887 if (!ir_block_living_find(prev, self->living[i], NULL)) {
1888 if (!ir_block_living_remove(self, i))
1894 /* Whatever the previous block still has in its living set
1895 * must now be added to ours as well.
1897 for (i = 0; i < prev->living_count; ++i)
1899 if (ir_block_living_find(self, prev->living[i], NULL))
1901 if (!ir_block_living_add(self, prev->living[i]))
1904 printf("%s got from prev: %s\n", self->label, prev->living[i]->_name);
1910 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
1916 /* bitmasks which operands are read from or written to */
1918 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1920 new_reads_t new_reads;
1922 char dbg_ind[16] = { '#', '0' };
1925 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1926 MEM_VECTOR_INIT(&new_reads, v);
1931 if (!ir_block_life_prop_previous(self, prev, changed))
1935 i = self->instr_count;
1938 instr = self->instr[i];
1940 /* PHI operands are always read operands */
1941 for (p = 0; p < instr->phi_count; ++p)
1943 value = instr->phi[p].value;
1944 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1945 if (!ir_block_living_find(self, value, NULL) &&
1946 !ir_block_living_add(self, value))
1951 if (!new_reads_t_v_find(&new_reads, value, NULL))
1953 if (!new_reads_t_v_add(&new_reads, value))
1959 /* See which operands are read and write operands */
1960 ir_op_read_write(instr->opcode, &read, &write);
1962 /* Go through the 3 main operands */
1963 for (o = 0; o < 3; ++o)
1965 if (!instr->_ops[o]) /* no such operand */
1968 value = instr->_ops[o];
1970 /* We only care about locals */
1971 /* we also calculate parameter liferanges so that locals
1972 * can take up parameter slots */
1973 if (value->store != store_value &&
1974 value->store != store_local &&
1975 value->store != store_param)
1981 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1982 if (!ir_block_living_find(self, value, NULL) &&
1983 !ir_block_living_add(self, value))
1988 /* fprintf(stderr, "read: %s\n", value->_name); */
1989 if (!new_reads_t_v_find(&new_reads, value, NULL))
1991 if (!new_reads_t_v_add(&new_reads, value))
1997 /* write operands */
1998 /* When we write to a local, we consider it "dead" for the
1999 * remaining upper part of the function, since in SSA a value
2000 * can only be written once (== created)
2005 bool in_living = ir_block_living_find(self, value, &idx);
2006 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2008 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
2009 if (!in_living && !in_reads)
2014 /* If the value isn't alive it hasn't been read before... */
2015 /* TODO: See if the warning can be emitted during parsing or AST processing
2016 * otherwise have warning printed here.
2017 * IF printing a warning here: include filecontext_t,
2018 * and make sure it's only printed once
2019 * since this function is run multiple times.
2021 /* For now: debug info: */
2022 fprintf(stderr, "Value only written %s\n", value->name);
2023 tempbool = ir_value_life_merge(value, instr->eid);
2024 *changed = *changed || tempbool;
2026 ir_instr_dump(instr, dbg_ind, printf);
2030 /* since 'living' won't contain it
2031 * anymore, merge the value, since
2034 tempbool = ir_value_life_merge(value, instr->eid);
2037 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2039 *changed = *changed || tempbool;
2041 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
2042 if (!ir_block_living_remove(self, idx))
2047 if (!new_reads_t_v_remove(&new_reads, readidx))
2055 tempbool = ir_block_living_add_instr(self, instr->eid);
2056 /*fprintf(stderr, "living added values\n");*/
2057 *changed = *changed || tempbool;
2059 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2061 for (rd = 0; rd < new_reads.v_count; ++rd)
2063 if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
2064 if (!ir_block_living_add(self, new_reads.v[rd]))
2067 if (!i && !self->entries_count) {
2069 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
2072 MEM_VECTOR_CLEAR(&new_reads, v);
2076 if (self->run_id == self->owner->run_id)
2079 self->run_id = self->owner->run_id;
2081 for (i = 0; i < self->entries_count; ++i)
2083 ir_block *entry = self->entries[i];
2084 ir_block_life_propagate(entry, self, changed);
2089 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
2090 MEM_VECTOR_CLEAR(&new_reads, v);
2095 /***********************************************************************
2098 * Since the IR has the convention of putting 'write' operands
2099 * at the beginning, we have to rotate the operands of instructions
2100 * properly in order to generate valid QCVM code.
2102 * Having destinations at a fixed position is more convenient. In QC
2103 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2104 * read from from OPA, and store to OPB rather than OPC. Which is
2105 * partially the reason why the implementation of these instructions
2106 * in darkplaces has been delayed for so long.
2108 * Breaking conventions is annoying...
2110 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2112 static bool gen_global_field(ir_value *global)
2114 if (global->isconst)
2116 ir_value *fld = global->constval.vpointer;
2118 printf("Invalid field constant with no field: %s\n", global->name);
2122 /* Now, in this case, a relocation would be impossible to code
2123 * since it looks like this:
2124 * .vector v = origin; <- parse error, wtf is 'origin'?
2127 * But we will need a general relocation support later anyway
2128 * for functions... might as well support that here.
2130 if (!fld->code.globaladdr) {
2131 printf("FIXME: Relocation support\n");
2135 /* copy the field's value */
2136 ir_value_code_setaddr(global, code_globals_add(code_globals_data[fld->code.globaladdr]));
2140 ir_value_code_setaddr(global, code_globals_add(0));
2142 if (global->code.globaladdr < 0)
2147 static bool gen_global_pointer(ir_value *global)
2149 if (global->isconst)
2151 ir_value *target = global->constval.vpointer;
2153 printf("Invalid pointer constant: %s\n", global->name);
2154 /* NULL pointers are pointing to the NULL constant, which also
2155 * sits at address 0, but still has an ir_value for itself.
2160 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2161 * void() foo; <- proto
2162 * void() *fooptr = &foo;
2163 * void() foo = { code }
2165 if (!target->code.globaladdr) {
2166 /* FIXME: Check for the constant nullptr ir_value!
2167 * because then code.globaladdr being 0 is valid.
2169 printf("FIXME: Relocation support\n");
2173 ir_value_code_setaddr(global, code_globals_add(target->code.globaladdr));
2177 ir_value_code_setaddr(global, code_globals_add(0));
2179 if (global->code.globaladdr < 0)
2184 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2186 prog_section_statement stmt;
2195 block->generated = true;
2196 block->code_start = code_statements_elements;
2197 for (i = 0; i < block->instr_count; ++i)
2199 instr = block->instr[i];
2201 if (instr->opcode == VINSTR_PHI) {
2202 printf("cannot generate virtual instruction (phi)\n");
2206 if (instr->opcode == VINSTR_JUMP) {
2207 target = instr->bops[0];
2208 /* for uncoditional jumps, if the target hasn't been generated
2209 * yet, we generate them right here.
2211 if (!target->generated) {
2216 /* otherwise we generate a jump instruction */
2217 stmt.opcode = INSTR_GOTO;
2218 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2221 if (code_statements_add(stmt) < 0)
2224 /* no further instructions can be in this block */
2228 if (instr->opcode == VINSTR_COND) {
2229 ontrue = instr->bops[0];
2230 onfalse = instr->bops[1];
2231 /* TODO: have the AST signal which block should
2232 * come first: eg. optimize IFs without ELSE...
2235 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2239 if (ontrue->generated) {
2240 stmt.opcode = INSTR_IF;
2241 stmt.o2.s1 = (ontrue->code_start-1) - code_statements_elements;
2242 if (code_statements_add(stmt) < 0)
2245 if (onfalse->generated) {
2246 stmt.opcode = INSTR_IFNOT;
2247 stmt.o2.s1 = (onfalse->code_start-1) - code_statements_elements;
2248 if (code_statements_add(stmt) < 0)
2251 if (!ontrue->generated) {
2252 if (onfalse->generated) {
2257 if (!onfalse->generated) {
2258 if (ontrue->generated) {
2263 /* neither ontrue nor onfalse exist */
2264 stmt.opcode = INSTR_IFNOT;
2265 stidx = code_statements_elements;
2266 if (code_statements_add(stmt) < 0)
2268 /* on false we jump, so add ontrue-path */
2269 if (!gen_blocks_recursive(func, ontrue))
2271 /* fixup the jump address */
2272 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2273 /* generate onfalse path */
2274 if (onfalse->generated) {
2275 /* fixup the jump address */
2276 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2277 /* may have been generated in the previous recursive call */
2278 stmt.opcode = INSTR_GOTO;
2279 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2282 return (code_statements_add(stmt) >= 0);
2284 /* if not, generate now */
2289 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2290 /* Trivial call translation:
2291 * copy all params to OFS_PARM*
2292 * if the output's storetype is not store_return,
2293 * add append a STORE instruction!
2295 * NOTES on how to do it better without much trouble:
2296 * -) The liferanges!
2297 * Simply check the liferange of all parameters for
2298 * other CALLs. For each param with no CALL in its
2299 * liferange, we can store it in an OFS_PARM at
2300 * generation already. This would even include later
2301 * reuse.... probably... :)
2306 for (p = 0; p < instr->params_count; ++p)
2308 ir_value *param = instr->params[p];
2310 stmt.opcode = INSTR_STORE_F;
2313 stmt.opcode = type_store_instr[param->vtype];
2314 stmt.o1.u1 = ir_value_code_addr(param);
2315 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2316 if (code_statements_add(stmt) < 0)
2319 stmt.opcode = INSTR_CALL0 + instr->params_count;
2320 if (stmt.opcode > INSTR_CALL8)
2321 stmt.opcode = INSTR_CALL8;
2322 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2325 if (code_statements_add(stmt) < 0)
2328 retvalue = instr->_ops[0];
2329 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2331 /* not to be kept in OFS_RETURN */
2332 stmt.opcode = type_store_instr[retvalue->vtype];
2333 stmt.o1.u1 = OFS_RETURN;
2334 stmt.o2.u1 = ir_value_code_addr(retvalue);
2336 if (code_statements_add(stmt) < 0)
2342 if (instr->opcode == INSTR_STATE) {
2343 printf("TODO: state instruction\n");
2347 stmt.opcode = instr->opcode;
2352 /* This is the general order of operands */
2354 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2357 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2360 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2362 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2364 stmt.o1.u1 = stmt.o3.u1;
2367 else if ((stmt.opcode >= INSTR_STORE_F &&
2368 stmt.opcode <= INSTR_STORE_FNC) ||
2369 (stmt.opcode >= INSTR_STOREP_F &&
2370 stmt.opcode <= INSTR_STOREP_FNC))
2372 /* 2-operand instructions with A -> B */
2373 stmt.o2.u1 = stmt.o3.u1;
2377 if (code_statements_add(stmt) < 0)
2383 static bool gen_function_code(ir_function *self)
2386 prog_section_statement stmt;
2388 /* Starting from entry point, we generate blocks "as they come"
2389 * for now. Dead blocks will not be translated obviously.
2391 if (!self->blocks_count) {
2392 printf("Function '%s' declared without body.\n", self->name);
2396 block = self->blocks[0];
2397 if (block->generated)
2400 if (!gen_blocks_recursive(self, block)) {
2401 printf("failed to generate blocks for '%s'\n", self->name);
2405 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2406 stmt.opcode = AINSTR_END;
2410 if (code_statements_add(stmt) < 0)
2415 static bool gen_global_function(ir_builder *ir, ir_value *global)
2417 prog_section_function fun;
2421 size_t local_var_end;
2423 if (!global->isconst || (!global->constval.vfunc))
2425 printf("Invalid state of function-global: not constant: %s\n", global->name);
2429 irfun = global->constval.vfunc;
2431 fun.name = global->code.name;
2432 fun.file = code_cachedstring(global->context.file);
2433 fun.profile = 0; /* always 0 */
2434 fun.nargs = irfun->params_count;
2436 for (i = 0;i < 8; ++i) {
2440 fun.argsize[i] = type_sizeof[irfun->params[i]];
2443 fun.firstlocal = code_globals_elements;
2444 fun.locals = irfun->allocated_locals + irfun->locals_count;
2447 for (i = 0; i < irfun->locals_count; ++i) {
2448 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2449 printf("Failed to generate global %s\n", irfun->locals[i]->name);
2453 if (irfun->locals_count) {
2454 ir_value *last = irfun->locals[irfun->locals_count-1];
2455 local_var_end = last->code.globaladdr;
2456 local_var_end += type_sizeof[last->vtype];
2458 for (i = 0; i < irfun->values_count; ++i)
2460 /* generate code.globaladdr for ssa values */
2461 ir_value *v = irfun->values[i];
2462 ir_value_code_setaddr(v, local_var_end + v->code.local);
2464 for (i = 0; i < irfun->locals_count; ++i) {
2465 /* fill the locals with zeros */
2466 code_globals_add(0);
2470 fun.entry = irfun->builtin;
2472 fun.entry = code_statements_elements;
2473 if (!gen_function_code(irfun)) {
2474 printf("Failed to generate code for function %s\n", irfun->name);
2479 return (code_functions_add(fun) >= 0);
2482 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2486 prog_section_def def;
2488 def.type = global->vtype;
2489 def.offset = code_globals_elements;
2490 def.name = global->code.name = code_genstring(global->name);
2492 switch (global->vtype)
2495 if (code_defs_add(def) < 0)
2497 return gen_global_pointer(global);
2499 if (code_defs_add(def) < 0)
2501 return gen_global_field(global);
2506 if (code_defs_add(def) < 0)
2509 if (global->isconst) {
2510 iptr = (int32_t*)&global->constval.vfloat;
2511 ir_value_code_setaddr(global, code_globals_add(*iptr));
2513 ir_value_code_setaddr(global, code_globals_add(0));
2515 return global->code.globaladdr >= 0;
2519 if (code_defs_add(def) < 0)
2521 if (global->isconst)
2522 ir_value_code_setaddr(global, code_globals_add(code_cachedstring(global->constval.vstring)));
2524 ir_value_code_setaddr(global, code_globals_add(0));
2525 return global->code.globaladdr >= 0;
2530 if (code_defs_add(def) < 0)
2533 if (global->isconst) {
2534 iptr = (int32_t*)&global->constval.vvec;
2535 ir_value_code_setaddr(global, code_globals_add(iptr[0]));
2536 if (global->code.globaladdr < 0)
2538 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2540 if (code_globals_add(iptr[d]) < 0)
2544 ir_value_code_setaddr(global, code_globals_add(0));
2545 if (global->code.globaladdr < 0)
2547 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2549 if (code_globals_add(0) < 0)
2553 return global->code.globaladdr >= 0;
2556 if (code_defs_add(def) < 0)
2558 ir_value_code_setaddr(global, code_globals_elements);
2559 code_globals_add(code_functions_elements);
2560 return gen_global_function(self, global);
2562 /* assume biggest type */
2563 ir_value_code_setaddr(global, code_globals_add(0));
2564 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2565 code_globals_add(0);
2568 /* refuse to create 'void' type or any other fancy business. */
2569 printf("Invalid type for global variable %s\n", global->name);
2574 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2576 prog_section_def def;
2577 prog_section_field fld;
2579 def.type = field->vtype;
2580 def.offset = code_globals_elements;
2582 /* create a global named the same as the field */
2583 if (opts_standard == COMPILER_GMQCC) {
2584 /* in our standard, the global gets a dot prefix */
2585 size_t len = strlen(field->name);
2588 /* we really don't want to have to allocate this, and 1024
2589 * bytes is more than enough for a variable/field name
2591 if (len+2 >= sizeof(name)) {
2592 printf("invalid field name size: %u\n", (unsigned int)len);
2597 strcpy(name+1, field->name); /* no strncpy - we used strlen above */
2600 def.name = code_genstring(name);
2601 fld.name = def.name + 1; /* we reuse that string table entry */
2603 /* in plain QC, there cannot be a global with the same name,
2604 * and so we also name the global the same.
2605 * FIXME: fteqcc should create a global as well
2606 * check if it actually uses the same name. Probably does
2608 def.name = code_genstring(field->name);
2609 fld.name = def.name;
2612 field->code.name = def.name;
2614 if (code_defs_add(def) < 0)
2617 fld.type = field->fieldtype;
2619 if (fld.type == TYPE_VOID) {
2620 printf("field is missing a type: %s - don't know its size\n", field->name);
2624 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2626 if (code_fields_add(fld) < 0)
2629 if (!code_globals_add(fld.offset))
2632 ir_value_code_setaddr(field, code_globals_add(fld.offset));
2633 return field->code.globaladdr >= 0;
2636 bool ir_builder_generate(ir_builder *self, const char *filename)
2642 for (i = 0; i < self->fields_count; ++i)
2644 if (!ir_builder_gen_field(self, self->fields[i])) {
2649 for (i = 0; i < self->globals_count; ++i)
2651 if (!ir_builder_gen_global(self, self->globals[i])) {
2656 printf("writing '%s'...\n", filename);
2657 return code_write(filename);
2660 /***********************************************************************
2661 *IR DEBUG Dump functions...
2664 #define IND_BUFSZ 1024
2666 const char *qc_opname(int op)
2668 if (op < 0) return "<INVALID>";
2669 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2670 return asm_instr[op].m;
2672 case VINSTR_PHI: return "PHI";
2673 case VINSTR_JUMP: return "JUMP";
2674 case VINSTR_COND: return "COND";
2675 default: return "<UNK>";
2679 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2682 char indent[IND_BUFSZ];
2686 oprintf("module %s\n", b->name);
2687 for (i = 0; i < b->globals_count; ++i)
2690 if (b->globals[i]->isconst)
2691 oprintf("%s = ", b->globals[i]->name);
2692 ir_value_dump(b->globals[i], oprintf);
2695 for (i = 0; i < b->functions_count; ++i)
2696 ir_function_dump(b->functions[i], indent, oprintf);
2697 oprintf("endmodule %s\n", b->name);
2700 void ir_function_dump(ir_function *f, char *ind,
2701 int (*oprintf)(const char*, ...))
2704 if (f->builtin != 0) {
2705 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2708 oprintf("%sfunction %s\n", ind, f->name);
2709 strncat(ind, "\t", IND_BUFSZ);
2710 if (f->locals_count)
2712 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2713 for (i = 0; i < f->locals_count; ++i) {
2714 oprintf("%s\t", ind);
2715 ir_value_dump(f->locals[i], oprintf);
2719 if (f->blocks_count)
2721 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2722 for (i = 0; i < f->blocks_count; ++i) {
2723 if (f->blocks[i]->run_id != f->run_id) {
2724 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2726 ir_block_dump(f->blocks[i], ind, oprintf);
2730 ind[strlen(ind)-1] = 0;
2731 oprintf("%sendfunction %s\n", ind, f->name);
2734 void ir_block_dump(ir_block* b, char *ind,
2735 int (*oprintf)(const char*, ...))
2738 oprintf("%s:%s\n", ind, b->label);
2739 strncat(ind, "\t", IND_BUFSZ);
2741 for (i = 0; i < b->instr_count; ++i)
2742 ir_instr_dump(b->instr[i], ind, oprintf);
2743 ind[strlen(ind)-1] = 0;
2746 void dump_phi(ir_instr *in, char *ind,
2747 int (*oprintf)(const char*, ...))
2750 oprintf("%s <- phi ", in->_ops[0]->name);
2751 for (i = 0; i < in->phi_count; ++i)
2753 oprintf("([%s] : %s) ", in->phi[i].from->label,
2754 in->phi[i].value->name);
2759 void ir_instr_dump(ir_instr *in, char *ind,
2760 int (*oprintf)(const char*, ...))
2763 const char *comma = NULL;
2765 oprintf("%s (%i) ", ind, (int)in->eid);
2767 if (in->opcode == VINSTR_PHI) {
2768 dump_phi(in, ind, oprintf);
2772 strncat(ind, "\t", IND_BUFSZ);
2774 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2775 ir_value_dump(in->_ops[0], oprintf);
2776 if (in->_ops[1] || in->_ops[2])
2779 oprintf("%s\t", qc_opname(in->opcode));
2780 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2781 ir_value_dump(in->_ops[0], oprintf);
2786 for (i = 1; i != 3; ++i) {
2790 ir_value_dump(in->_ops[i], oprintf);
2798 oprintf("[%s]", in->bops[0]->label);
2802 oprintf("%s[%s]", comma, in->bops[1]->label);
2804 ind[strlen(ind)-1] = 0;
2807 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
2815 oprintf("%g", v->constval.vfloat);
2818 oprintf("'%g %g %g'",
2821 v->constval.vvec.z);
2824 oprintf("(entity)");
2827 oprintf("\"%s\"", v->constval.vstring);
2831 oprintf("%i", v->constval.vint);
2836 v->constval.vpointer->name);
2840 oprintf("%s", v->name);
2844 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
2847 oprintf("Life of %s:\n", self->name);
2848 for (i = 0; i < self->life_count; ++i)
2850 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);