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 static bool irwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
139 int lvl = LVL_WARNING;
141 if (!OPTS_WARN(warntype))
148 vprintmsg(lvl, ctx.file, ctx.line, "warning", fmt, ap);
154 /***********************************************************************
158 ir_builder* ir_builder_new(const char *modulename)
162 self = (ir_builder*)mem_a(sizeof(*self));
166 MEM_VECTOR_INIT(self, functions);
167 MEM_VECTOR_INIT(self, globals);
168 MEM_VECTOR_INIT(self, fields);
170 if (!ir_builder_set_name(self, modulename)) {
175 /* globals which always exist */
177 /* for now we give it a vector size */
178 ir_builder_create_global(self, "OFS_RETURN", TYPE_VARIANT);
183 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
184 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, fields)
185 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
187 void ir_builder_delete(ir_builder* self)
190 mem_d((void*)self->name);
191 for (i = 0; i != self->functions_count; ++i) {
192 ir_function_delete(self->functions[i]);
194 MEM_VECTOR_CLEAR(self, functions);
195 for (i = 0; i != self->globals_count; ++i) {
196 ir_value_delete(self->globals[i]);
198 MEM_VECTOR_CLEAR(self, globals);
199 for (i = 0; i != self->fields_count; ++i) {
200 ir_value_delete(self->fields[i]);
202 MEM_VECTOR_CLEAR(self, fields);
206 bool ir_builder_set_name(ir_builder *self, const char *name)
209 mem_d((void*)self->name);
210 self->name = util_strdup(name);
214 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
217 for (i = 0; i < self->functions_count; ++i) {
218 if (!strcmp(name, self->functions[i]->name))
219 return self->functions[i];
224 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
226 ir_function *fn = ir_builder_get_function(self, name);
231 fn = ir_function_new(self, outtype);
232 if (!ir_function_set_name(fn, name) ||
233 !ir_builder_functions_add(self, fn) )
235 ir_function_delete(fn);
239 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
241 ir_function_delete(fn);
245 fn->value->isconst = true;
246 fn->value->outtype = outtype;
247 fn->value->constval.vfunc = fn;
248 fn->value->context = fn->context;
253 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
256 for (i = 0; i < self->globals_count; ++i) {
257 if (!strcmp(self->globals[i]->name, name))
258 return self->globals[i];
263 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
267 if (name && name[0] != '#')
269 ve = ir_builder_get_global(self, name);
275 ve = ir_value_var(name, store_global, vtype);
276 if (!ir_builder_globals_add(self, ve)) {
283 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
286 for (i = 0; i < self->fields_count; ++i) {
287 if (!strcmp(self->fields[i]->name, name))
288 return self->fields[i];
294 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
296 ir_value *ve = ir_builder_get_field(self, name);
301 ve = ir_value_var(name, store_global, TYPE_FIELD);
302 ve->fieldtype = vtype;
303 if (!ir_builder_fields_add(self, ve)) {
310 /***********************************************************************
314 bool ir_function_naive_phi(ir_function*);
315 void ir_function_enumerate(ir_function*);
316 bool ir_function_calculate_liferanges(ir_function*);
317 bool ir_function_allocate_locals(ir_function*);
319 ir_function* ir_function_new(ir_builder* owner, int outtype)
322 self = (ir_function*)mem_a(sizeof(*self));
327 memset(self, 0, sizeof(*self));
330 if (!ir_function_set_name(self, "<@unnamed>")) {
335 self->context.file = "<@no context>";
336 self->context.line = 0;
337 self->outtype = outtype;
340 MEM_VECTOR_INIT(self, params);
341 MEM_VECTOR_INIT(self, blocks);
342 MEM_VECTOR_INIT(self, values);
343 MEM_VECTOR_INIT(self, locals);
345 self->code_function_def = -1;
346 self->allocated_locals = 0;
351 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
352 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
353 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
354 MEM_VEC_FUNCTIONS(ir_function, int, params)
356 bool ir_function_set_name(ir_function *self, const char *name)
359 mem_d((void*)self->name);
360 self->name = util_strdup(name);
364 void ir_function_delete(ir_function *self)
367 mem_d((void*)self->name);
369 for (i = 0; i != self->blocks_count; ++i)
370 ir_block_delete(self->blocks[i]);
371 MEM_VECTOR_CLEAR(self, blocks);
373 MEM_VECTOR_CLEAR(self, params);
375 for (i = 0; i != self->values_count; ++i)
376 ir_value_delete(self->values[i]);
377 MEM_VECTOR_CLEAR(self, values);
379 for (i = 0; i != self->locals_count; ++i)
380 ir_value_delete(self->locals[i]);
381 MEM_VECTOR_CLEAR(self, locals);
383 /* self->value is deleted by the builder */
388 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
390 return ir_function_values_add(self, v);
393 ir_block* ir_function_create_block(ir_function *self, const char *label)
395 ir_block* bn = ir_block_new(self, label);
396 memcpy(&bn->context, &self->context, sizeof(self->context));
397 if (!ir_function_blocks_add(self, bn)) {
404 bool ir_function_finalize(ir_function *self)
409 if (!ir_function_naive_phi(self))
412 ir_function_enumerate(self);
414 if (!ir_function_calculate_liferanges(self))
417 if (!ir_function_allocate_locals(self))
422 ir_value* ir_function_get_local(ir_function *self, const char *name)
425 for (i = 0; i < self->locals_count; ++i) {
426 if (!strcmp(self->locals[i]->name, name))
427 return self->locals[i];
432 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
434 ir_value *ve = ir_function_get_local(self, name);
440 self->locals_count &&
441 self->locals[self->locals_count-1]->store != store_param) {
442 irerror(self->context, "cannot add parameters after adding locals");
446 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
447 if (!ir_function_locals_add(self, ve)) {
454 /***********************************************************************
458 ir_block* ir_block_new(ir_function* owner, const char *name)
461 self = (ir_block*)mem_a(sizeof(*self));
465 memset(self, 0, sizeof(*self));
468 if (!ir_block_set_label(self, name)) {
473 self->context.file = "<@no context>";
474 self->context.line = 0;
476 MEM_VECTOR_INIT(self, instr);
477 MEM_VECTOR_INIT(self, entries);
478 MEM_VECTOR_INIT(self, exits);
481 self->is_return = false;
483 MEM_VECTOR_INIT(self, living);
485 self->generated = false;
489 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
490 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
491 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
492 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
494 void ir_block_delete(ir_block* self)
498 for (i = 0; i != self->instr_count; ++i)
499 ir_instr_delete(self->instr[i]);
500 MEM_VECTOR_CLEAR(self, instr);
501 MEM_VECTOR_CLEAR(self, entries);
502 MEM_VECTOR_CLEAR(self, exits);
503 MEM_VECTOR_CLEAR(self, living);
507 bool ir_block_set_label(ir_block *self, const char *name)
510 mem_d((void*)self->label);
511 self->label = util_strdup(name);
512 return !!self->label;
515 /***********************************************************************
519 ir_instr* ir_instr_new(ir_block* owner, int op)
522 self = (ir_instr*)mem_a(sizeof(*self));
527 self->context.file = "<@no context>";
528 self->context.line = 0;
530 self->_ops[0] = NULL;
531 self->_ops[1] = NULL;
532 self->_ops[2] = NULL;
533 self->bops[0] = NULL;
534 self->bops[1] = NULL;
535 MEM_VECTOR_INIT(self, phi);
536 MEM_VECTOR_INIT(self, params);
541 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
542 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
544 void ir_instr_delete(ir_instr *self)
547 /* The following calls can only delete from
548 * vectors, we still want to delete this instruction
549 * so ignore the return value. Since with the warn_unused_result attribute
550 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
551 * I have to improvise here and use if(foo());
553 for (i = 0; i < self->phi_count; ++i) {
555 if (ir_value_writes_find(self->phi[i].value, self, &idx))
556 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
557 if (ir_value_reads_find(self->phi[i].value, self, &idx))
558 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
560 MEM_VECTOR_CLEAR(self, phi);
561 for (i = 0; i < self->params_count; ++i) {
563 if (ir_value_writes_find(self->params[i], self, &idx))
564 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
565 if (ir_value_reads_find(self->params[i], self, &idx))
566 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
568 MEM_VECTOR_CLEAR(self, params);
569 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
570 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
571 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
575 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
577 if (self->_ops[op]) {
579 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
581 if (!ir_value_writes_remove(self->_ops[op], idx))
584 else if (ir_value_reads_find(self->_ops[op], self, &idx))
586 if (!ir_value_reads_remove(self->_ops[op], idx))
592 if (!ir_value_writes_add(v, self))
595 if (!ir_value_reads_add(v, self))
603 /***********************************************************************
607 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
609 self->code.globaladdr = gaddr;
610 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
611 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
612 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
615 int32_t ir_value_code_addr(const ir_value *self)
617 if (self->store == store_return)
618 return OFS_RETURN + self->code.addroffset;
619 return self->code.globaladdr + self->code.addroffset;
622 ir_value* ir_value_var(const char *name, int storetype, int vtype)
625 self = (ir_value*)mem_a(sizeof(*self));
627 self->fieldtype = TYPE_VOID;
628 self->outtype = TYPE_VOID;
629 self->store = storetype;
630 MEM_VECTOR_INIT(self, reads);
631 MEM_VECTOR_INIT(self, writes);
632 self->isconst = false;
633 self->context.file = "<@no context>";
634 self->context.line = 0;
636 ir_value_set_name(self, name);
638 memset(&self->constval, 0, sizeof(self->constval));
639 memset(&self->code, 0, sizeof(self->code));
641 self->members[0] = NULL;
642 self->members[1] = NULL;
643 self->members[2] = NULL;
644 self->memberof = NULL;
646 MEM_VECTOR_INIT(self, life);
650 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
656 if (self->members[member])
657 return self->members[member];
659 if (self->vtype == TYPE_VECTOR)
661 m = ir_value_var(self->name, self->store, TYPE_FLOAT);
664 m->context = self->context;
666 self->members[member] = m;
667 m->code.addroffset = member;
669 else if (self->vtype == TYPE_FIELD)
671 if (self->fieldtype != TYPE_VECTOR)
673 m = ir_value_var(self->name, self->store, TYPE_FIELD);
676 m->fieldtype = TYPE_FLOAT;
677 m->context = self->context;
679 self->members[member] = m;
680 m->code.addroffset = member;
684 irerror(self->context, "invalid member access on %s", self->name);
692 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
693 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
694 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
696 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
698 ir_value *v = ir_value_var(name, storetype, vtype);
701 if (!ir_function_collect_value(owner, v))
709 void ir_value_delete(ir_value* self)
713 mem_d((void*)self->name);
716 if (self->vtype == TYPE_STRING)
717 mem_d((void*)self->constval.vstring);
719 for (i = 0; i < 3; ++i) {
720 if (self->members[i])
721 ir_value_delete(self->members[i]);
723 MEM_VECTOR_CLEAR(self, reads);
724 MEM_VECTOR_CLEAR(self, writes);
725 MEM_VECTOR_CLEAR(self, life);
729 void ir_value_set_name(ir_value *self, const char *name)
732 mem_d((void*)self->name);
733 self->name = util_strdup(name);
736 bool ir_value_set_float(ir_value *self, float f)
738 if (self->vtype != TYPE_FLOAT)
740 self->constval.vfloat = f;
741 self->isconst = true;
745 bool ir_value_set_func(ir_value *self, int f)
747 if (self->vtype != TYPE_FUNCTION)
749 self->constval.vint = f;
750 self->isconst = true;
754 bool ir_value_set_vector(ir_value *self, vector v)
756 if (self->vtype != TYPE_VECTOR)
758 self->constval.vvec = v;
759 self->isconst = true;
763 bool ir_value_set_field(ir_value *self, ir_value *fld)
765 if (self->vtype != TYPE_FIELD)
767 self->constval.vpointer = fld;
768 self->isconst = true;
772 static char *ir_strdup(const char *str)
775 /* actually dup empty strings */
776 char *out = mem_a(1);
780 return util_strdup(str);
783 bool ir_value_set_string(ir_value *self, const char *str)
785 if (self->vtype != TYPE_STRING)
787 self->constval.vstring = ir_strdup(str);
788 self->isconst = true;
793 bool ir_value_set_int(ir_value *self, int i)
795 if (self->vtype != TYPE_INTEGER)
797 self->constval.vint = i;
798 self->isconst = true;
803 bool ir_value_lives(ir_value *self, size_t at)
806 for (i = 0; i < self->life_count; ++i)
808 ir_life_entry_t *life = &self->life[i];
809 if (life->start <= at && at <= life->end)
811 if (life->start > at) /* since it's ordered */
817 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
820 if (!ir_value_life_add(self, e)) /* naive... */
822 for (k = self->life_count-1; k > idx; --k)
823 self->life[k] = self->life[k-1];
828 bool ir_value_life_merge(ir_value *self, size_t s)
831 ir_life_entry_t *life = NULL;
832 ir_life_entry_t *before = NULL;
833 ir_life_entry_t new_entry;
835 /* Find the first range >= s */
836 for (i = 0; i < self->life_count; ++i)
839 life = &self->life[i];
843 /* nothing found? append */
844 if (i == self->life_count) {
846 if (life && life->end+1 == s)
848 /* previous life range can be merged in */
852 if (life && life->end >= s)
855 if (!ir_value_life_add(self, e))
856 return false; /* failing */
862 if (before->end + 1 == s &&
863 life->start - 1 == s)
866 before->end = life->end;
867 if (!ir_value_life_remove(self, i))
868 return false; /* failing */
871 if (before->end + 1 == s)
877 /* already contained */
878 if (before->end >= s)
882 if (life->start - 1 == s)
887 /* insert a new entry */
888 new_entry.start = new_entry.end = s;
889 return ir_value_life_insert(self, i, new_entry);
892 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
896 if (!other->life_count)
899 if (!self->life_count) {
900 for (i = 0; i < other->life_count; ++i) {
901 if (!ir_value_life_add(self, other->life[i]))
908 for (i = 0; i < other->life_count; ++i)
910 const ir_life_entry_t *life = &other->life[i];
913 ir_life_entry_t *entry = &self->life[myi];
915 if (life->end+1 < entry->start)
917 /* adding an interval before entry */
918 if (!ir_value_life_insert(self, myi, *life))
924 if (life->start < entry->start &&
925 life->end >= entry->start)
927 /* starts earlier and overlaps */
928 entry->start = life->start;
931 if (life->end > entry->end &&
932 life->start-1 <= entry->end)
934 /* ends later and overlaps */
935 entry->end = life->end;
938 /* see if our change combines it with the next ranges */
939 while (myi+1 < self->life_count &&
940 entry->end+1 >= self->life[1+myi].start)
942 /* overlaps with (myi+1) */
943 if (entry->end < self->life[1+myi].end)
944 entry->end = self->life[1+myi].end;
945 if (!ir_value_life_remove(self, myi+1))
947 entry = &self->life[myi];
950 /* see if we're after the entry */
951 if (life->start > entry->end)
954 /* append if we're at the end */
955 if (myi >= self->life_count) {
956 if (!ir_value_life_add(self, *life))
960 /* otherweise check the next range */
969 bool ir_values_overlap(const ir_value *a, const ir_value *b)
971 /* For any life entry in A see if it overlaps with
972 * any life entry in B.
973 * Note that the life entries are orderes, so we can make a
974 * more efficient algorithm there than naively translating the
978 ir_life_entry_t *la, *lb, *enda, *endb;
980 /* first of all, if either has no life range, they cannot clash */
981 if (!a->life_count || !b->life_count)
986 enda = la + a->life_count;
987 endb = lb + b->life_count;
990 /* check if the entries overlap, for that,
991 * both must start before the other one ends.
993 if (la->start < lb->end &&
999 /* entries are ordered
1000 * one entry is earlier than the other
1001 * that earlier entry will be moved forward
1003 if (la->start < lb->start)
1005 /* order: A B, move A forward
1006 * check if we hit the end with A
1011 else /* if (lb->start < la->start) actually <= */
1013 /* order: B A, move B forward
1014 * check if we hit the end with B
1023 /***********************************************************************
1027 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
1029 ir_instr *in = ir_instr_new(self, op);
1033 if (target->store == store_value &&
1034 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1036 irerror(self->context, "cannot store to an SSA value");
1037 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1038 irerror(self->context, "instruction: %s", asm_instr[op].m);
1042 if (!ir_instr_op(in, 0, target, true) ||
1043 !ir_instr_op(in, 1, what, false) ||
1044 !ir_block_instr_add(self, in) )
1051 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
1055 if (target->vtype == TYPE_VARIANT)
1056 vtype = what->vtype;
1058 vtype = target->vtype;
1061 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1062 op = INSTR_CONV_ITOF;
1063 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1064 op = INSTR_CONV_FTOI;
1066 op = type_store_instr[vtype];
1068 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1069 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1073 return ir_block_create_store_op(self, op, target, what);
1076 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
1081 if (target->vtype != TYPE_POINTER)
1084 /* storing using pointer - target is a pointer, type must be
1085 * inferred from source
1087 vtype = what->vtype;
1089 op = type_storep_instr[vtype];
1090 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1091 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1092 op = INSTR_STOREP_V;
1095 return ir_block_create_store_op(self, op, target, what);
1098 bool ir_block_create_return(ir_block *self, ir_value *v)
1102 irerror(self->context, "block already ended (%s)", self->label);
1106 self->is_return = true;
1107 in = ir_instr_new(self, INSTR_RETURN);
1111 if (v && !ir_instr_op(in, 0, v, false))
1114 if (!ir_block_instr_add(self, in))
1119 bool ir_block_create_if(ir_block *self, ir_value *v,
1120 ir_block *ontrue, ir_block *onfalse)
1124 irerror(self->context, "block already ended (%s)", self->label);
1128 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1129 in = ir_instr_new(self, VINSTR_COND);
1133 if (!ir_instr_op(in, 0, v, false)) {
1134 ir_instr_delete(in);
1138 in->bops[0] = ontrue;
1139 in->bops[1] = onfalse;
1141 if (!ir_block_instr_add(self, in))
1144 if (!ir_block_exits_add(self, ontrue) ||
1145 !ir_block_exits_add(self, onfalse) ||
1146 !ir_block_entries_add(ontrue, self) ||
1147 !ir_block_entries_add(onfalse, self) )
1154 bool ir_block_create_jump(ir_block *self, ir_block *to)
1158 irerror(self->context, "block already ended (%s)", self->label);
1162 in = ir_instr_new(self, VINSTR_JUMP);
1167 if (!ir_block_instr_add(self, in))
1170 if (!ir_block_exits_add(self, to) ||
1171 !ir_block_entries_add(to, self) )
1178 bool ir_block_create_goto(ir_block *self, ir_block *to)
1182 irerror(self->context, "block already ended (%s)", self->label);
1186 in = ir_instr_new(self, INSTR_GOTO);
1191 if (!ir_block_instr_add(self, in))
1194 if (!ir_block_exits_add(self, to) ||
1195 !ir_block_entries_add(to, self) )
1202 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1206 in = ir_instr_new(self, VINSTR_PHI);
1209 out = ir_value_out(self->owner, label, store_value, ot);
1211 ir_instr_delete(in);
1214 if (!ir_instr_op(in, 0, out, true)) {
1215 ir_instr_delete(in);
1216 ir_value_delete(out);
1219 if (!ir_block_instr_add(self, in)) {
1220 ir_instr_delete(in);
1221 ir_value_delete(out);
1227 ir_value* ir_phi_value(ir_instr *self)
1229 return self->_ops[0];
1232 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1236 if (!ir_block_entries_find(self->owner, b, NULL)) {
1237 /* Must not be possible to cause this, otherwise the AST
1238 * is doing something wrong.
1240 irerror(self->context, "Invalid entry block for PHI");
1246 if (!ir_value_reads_add(v, self))
1248 return ir_instr_phi_add(self, pe);
1251 /* call related code */
1252 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1256 in = ir_instr_new(self, INSTR_CALL0);
1259 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1261 ir_instr_delete(in);
1264 if (!ir_instr_op(in, 0, out, true) ||
1265 !ir_instr_op(in, 1, func, false) ||
1266 !ir_block_instr_add(self, in))
1268 ir_instr_delete(in);
1269 ir_value_delete(out);
1275 ir_value* ir_call_value(ir_instr *self)
1277 return self->_ops[0];
1280 bool ir_call_param(ir_instr* self, ir_value *v)
1282 if (!ir_instr_params_add(self, v))
1284 if (!ir_value_reads_add(v, self)) {
1285 if (!ir_instr_params_remove(self, self->params_count-1))
1286 GMQCC_SUPPRESS_EMPTY_BODY;
1292 /* binary op related code */
1294 ir_value* ir_block_create_binop(ir_block *self,
1295 const char *label, int opcode,
1296 ir_value *left, ir_value *right)
1318 case INSTR_SUB_S: /* -- offset of string as float */
1323 case INSTR_BITOR_IF:
1324 case INSTR_BITOR_FI:
1325 case INSTR_BITAND_FI:
1326 case INSTR_BITAND_IF:
1341 case INSTR_BITAND_I:
1344 case INSTR_RSHIFT_I:
1345 case INSTR_LSHIFT_I:
1367 /* boolean operations result in floats */
1368 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1370 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1373 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1378 if (ot == TYPE_VOID) {
1379 /* The AST or parser were supposed to check this! */
1383 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1386 ir_value* ir_block_create_unary(ir_block *self,
1387 const char *label, int opcode,
1390 int ot = TYPE_FLOAT;
1402 /* QC doesn't have other unary operations. We expect extensions to fill
1403 * the above list, otherwise we assume out-type = in-type, eg for an
1407 ot = operand->vtype;
1410 if (ot == TYPE_VOID) {
1411 /* The AST or parser were supposed to check this! */
1415 /* let's use the general instruction creator and pass NULL for OPB */
1416 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1419 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1420 int op, ir_value *a, ir_value *b, int outype)
1425 out = ir_value_out(self->owner, label, store_value, outype);
1429 instr = ir_instr_new(self, op);
1431 ir_value_delete(out);
1435 if (!ir_instr_op(instr, 0, out, true) ||
1436 !ir_instr_op(instr, 1, a, false) ||
1437 !ir_instr_op(instr, 2, b, false) )
1442 if (!ir_block_instr_add(self, instr))
1447 ir_instr_delete(instr);
1448 ir_value_delete(out);
1452 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1456 /* Support for various pointer types todo if so desired */
1457 if (ent->vtype != TYPE_ENTITY)
1460 if (field->vtype != TYPE_FIELD)
1463 v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1464 v->fieldtype = field->fieldtype;
1468 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1471 if (ent->vtype != TYPE_ENTITY)
1474 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1475 if (field->vtype != TYPE_FIELD)
1480 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1481 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1482 case TYPE_STRING: op = INSTR_LOAD_S; break;
1483 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1484 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1485 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1487 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1488 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1494 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1497 ir_value* ir_block_create_add(ir_block *self,
1499 ir_value *left, ir_value *right)
1502 int l = left->vtype;
1503 int r = right->vtype;
1522 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1524 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1530 return ir_block_create_binop(self, label, op, left, right);
1533 ir_value* ir_block_create_sub(ir_block *self,
1535 ir_value *left, ir_value *right)
1538 int l = left->vtype;
1539 int r = right->vtype;
1559 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1561 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1567 return ir_block_create_binop(self, label, op, left, right);
1570 ir_value* ir_block_create_mul(ir_block *self,
1572 ir_value *left, ir_value *right)
1575 int l = left->vtype;
1576 int r = right->vtype;
1595 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1597 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1600 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1602 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1604 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1606 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1612 return ir_block_create_binop(self, label, op, left, right);
1615 ir_value* ir_block_create_div(ir_block *self,
1617 ir_value *left, ir_value *right)
1620 int l = left->vtype;
1621 int r = right->vtype;
1638 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1640 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1642 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1648 return ir_block_create_binop(self, label, op, left, right);
1651 /* PHI resolving breaks the SSA, and must thus be the last
1652 * step before life-range calculation.
1655 static bool ir_block_naive_phi(ir_block *self);
1656 bool ir_function_naive_phi(ir_function *self)
1660 for (i = 0; i < self->blocks_count; ++i)
1662 if (!ir_block_naive_phi(self->blocks[i]))
1668 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1673 /* create a store */
1674 if (!ir_block_create_store(block, old, what))
1677 /* we now move it up */
1678 instr = block->instr[block->instr_count-1];
1679 for (i = block->instr_count; i > iid; --i)
1680 block->instr[i] = block->instr[i-1];
1681 block->instr[i] = instr;
1686 static bool ir_block_naive_phi(ir_block *self)
1689 /* FIXME: optionally, create_phi can add the phis
1690 * to a list so we don't need to loop through blocks
1691 * - anyway: "don't optimize YET"
1693 for (i = 0; i < self->instr_count; ++i)
1695 ir_instr *instr = self->instr[i];
1696 if (instr->opcode != VINSTR_PHI)
1699 if (!ir_block_instr_remove(self, i))
1701 --i; /* NOTE: i+1 below */
1703 for (p = 0; p < instr->phi_count; ++p)
1705 ir_value *v = instr->phi[p].value;
1706 for (w = 0; w < v->writes_count; ++w) {
1709 if (!v->writes[w]->_ops[0])
1712 /* When the write was to a global, we have to emit a mov */
1713 old = v->writes[w]->_ops[0];
1715 /* The original instruction now writes to the PHI target local */
1716 if (v->writes[w]->_ops[0] == v)
1717 v->writes[w]->_ops[0] = instr->_ops[0];
1719 if (old->store != store_value && old->store != store_local && old->store != store_param)
1721 /* If it originally wrote to a global we need to store the value
1724 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1726 if (i+1 < self->instr_count)
1727 instr = self->instr[i+1];
1730 /* In case I forget and access instr later, it'll be NULL
1731 * when it's a problem, to make sure we crash, rather than accessing
1737 /* If it didn't, we can replace all reads by the phi target now. */
1739 for (r = 0; r < old->reads_count; ++r)
1742 ir_instr *ri = old->reads[r];
1743 for (op = 0; op < ri->phi_count; ++op) {
1744 if (ri->phi[op].value == old)
1745 ri->phi[op].value = v;
1747 for (op = 0; op < 3; ++op) {
1748 if (ri->_ops[op] == old)
1755 ir_instr_delete(instr);
1760 /***********************************************************************
1761 *IR Temp allocation code
1762 * Propagating value life ranges by walking through the function backwards
1763 * until no more changes are made.
1764 * In theory this should happen once more than once for every nested loop
1766 * Though this implementation might run an additional time for if nests.
1775 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1777 /* Enumerate instructions used by value's life-ranges
1779 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1783 for (i = 0; i < self->instr_count; ++i)
1785 self->instr[i]->eid = eid++;
1790 /* Enumerate blocks and instructions.
1791 * The block-enumeration is unordered!
1792 * We do not really use the block enumreation, however
1793 * the instruction enumeration is important for life-ranges.
1795 void ir_function_enumerate(ir_function *self)
1798 size_t instruction_id = 0;
1799 for (i = 0; i < self->blocks_count; ++i)
1801 self->blocks[i]->eid = i;
1802 self->blocks[i]->run_id = 0;
1803 ir_block_enumerate(self->blocks[i], &instruction_id);
1807 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1808 bool ir_function_calculate_liferanges(ir_function *self)
1816 for (i = 0; i != self->blocks_count; ++i)
1818 if (self->blocks[i]->is_return)
1820 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1825 if (self->blocks_count) {
1826 ir_block *block = self->blocks[0];
1827 for (i = 0; i < block->living_count; ++i) {
1828 ir_value *v = block->living[i];
1829 if (v->memberof || v->store != store_local)
1831 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
1832 "variable `%s` may be used uninitialized in this function", v->name))
1841 /* Local-value allocator
1842 * After finishing creating the liferange of all values used in a function
1843 * we can allocate their global-positions.
1844 * This is the counterpart to register-allocation in register machines.
1847 MEM_VECTOR_MAKE(ir_value*, locals);
1848 MEM_VECTOR_MAKE(size_t, sizes);
1849 MEM_VECTOR_MAKE(size_t, positions);
1850 } function_allocator;
1851 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1852 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1853 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1855 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1858 size_t vsize = type_sizeof[var->vtype];
1860 slot = ir_value_var("reg", store_global, var->vtype);
1864 if (!ir_value_life_merge_into(slot, var))
1867 if (!function_allocator_locals_add(alloc, slot))
1870 if (!function_allocator_sizes_add(alloc, vsize))
1876 ir_value_delete(slot);
1880 bool ir_function_allocate_locals(ir_function *self)
1889 function_allocator alloc;
1891 if (!self->locals_count && !self->values_count)
1894 MEM_VECTOR_INIT(&alloc, locals);
1895 MEM_VECTOR_INIT(&alloc, sizes);
1896 MEM_VECTOR_INIT(&alloc, positions);
1898 for (i = 0; i < self->locals_count; ++i)
1900 if (!function_allocator_alloc(&alloc, self->locals[i]))
1904 /* Allocate a slot for any value that still exists */
1905 for (i = 0; i < self->values_count; ++i)
1907 v = self->values[i];
1912 for (a = 0; a < alloc.locals_count; ++a)
1914 slot = alloc.locals[a];
1916 if (ir_values_overlap(v, slot))
1919 if (!ir_value_life_merge_into(slot, v))
1922 /* adjust size for this slot */
1923 if (alloc.sizes[a] < type_sizeof[v->vtype])
1924 alloc.sizes[a] = type_sizeof[v->vtype];
1926 self->values[i]->code.local = a;
1929 if (a >= alloc.locals_count) {
1930 self->values[i]->code.local = alloc.locals_count;
1931 if (!function_allocator_alloc(&alloc, v))
1940 /* Adjust slot positions based on sizes */
1941 if (!function_allocator_positions_add(&alloc, 0))
1944 if (alloc.sizes_count)
1945 pos = alloc.positions[0] + alloc.sizes[0];
1948 for (i = 1; i < alloc.sizes_count; ++i)
1950 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1951 if (!function_allocator_positions_add(&alloc, pos))
1955 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1957 /* Take over the actual slot positions */
1958 for (i = 0; i < self->values_count; ++i) {
1959 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1967 for (i = 0; i < alloc.locals_count; ++i)
1968 ir_value_delete(alloc.locals[i]);
1969 MEM_VECTOR_CLEAR(&alloc, locals);
1970 MEM_VECTOR_CLEAR(&alloc, sizes);
1971 MEM_VECTOR_CLEAR(&alloc, positions);
1975 /* Get information about which operand
1976 * is read from, or written to.
1978 static void ir_op_read_write(int op, size_t *read, size_t *write)
1998 case INSTR_STOREP_F:
1999 case INSTR_STOREP_V:
2000 case INSTR_STOREP_S:
2001 case INSTR_STOREP_ENT:
2002 case INSTR_STOREP_FLD:
2003 case INSTR_STOREP_FNC:
2014 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2017 bool changed = false;
2019 for (i = 0; i != self->living_count; ++i)
2021 tempbool = ir_value_life_merge(self->living[i], eid);
2024 irerror(self->context, "block_living_add_instr() value instruction added %s: %i", self->living[i]->_name, (int)eid);
2026 changed = changed || tempbool;
2031 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
2034 /* values which have been read in a previous iteration are now
2035 * in the "living" array even if the previous block doesn't use them.
2036 * So we have to remove whatever does not exist in the previous block.
2037 * They will be re-added on-read, but the liferange merge won't cause
2040 for (i = 0; i < self->living_count; ++i)
2042 if (!ir_block_living_find(prev, self->living[i], NULL)) {
2043 if (!ir_block_living_remove(self, i))
2049 /* Whatever the previous block still has in its living set
2050 * must now be added to ours as well.
2052 for (i = 0; i < prev->living_count; ++i)
2054 if (ir_block_living_find(self, prev->living[i], NULL))
2056 if (!ir_block_living_add(self, prev->living[i]))
2059 irerror(self->contextt from prev: %s", self->label, prev->living[i]->_name);
2065 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2071 /* bitmasks which operands are read from or written to */
2073 char dbg_ind[16] = { '#', '0' };
2078 if (!ir_block_life_prop_previous(self, prev, changed))
2082 i = self->instr_count;
2085 instr = self->instr[i];
2087 /* PHI operands are always read operands */
2088 for (p = 0; p < instr->phi_count; ++p)
2090 value = instr->phi[p].value;
2091 if (value->memberof)
2092 value = value->memberof;
2093 if (!ir_block_living_find(self, value, NULL) &&
2094 !ir_block_living_add(self, value))
2100 /* call params are read operands too */
2101 for (p = 0; p < instr->params_count; ++p)
2103 value = instr->params[p];
2104 if (value->memberof)
2105 value = value->memberof;
2106 if (!ir_block_living_find(self, value, NULL) &&
2107 !ir_block_living_add(self, value))
2113 /* See which operands are read and write operands */
2114 ir_op_read_write(instr->opcode, &read, &write);
2116 /* Go through the 3 main operands */
2117 for (o = 0; o < 3; ++o)
2119 if (!instr->_ops[o]) /* no such operand */
2122 value = instr->_ops[o];
2123 if (value->memberof)
2124 value = value->memberof;
2126 /* We only care about locals */
2127 /* we also calculate parameter liferanges so that locals
2128 * can take up parameter slots */
2129 if (value->store != store_value &&
2130 value->store != store_local &&
2131 value->store != store_param)
2137 if (!ir_block_living_find(self, value, NULL) &&
2138 !ir_block_living_add(self, value))
2144 /* write operands */
2145 /* When we write to a local, we consider it "dead" for the
2146 * remaining upper part of the function, since in SSA a value
2147 * can only be written once (== created)
2152 bool in_living = ir_block_living_find(self, value, &idx);
2155 /* If the value isn't alive it hasn't been read before... */
2156 /* TODO: See if the warning can be emitted during parsing or AST processing
2157 * otherwise have warning printed here.
2158 * IF printing a warning here: include filecontext_t,
2159 * and make sure it's only printed once
2160 * since this function is run multiple times.
2162 /* For now: debug info: */
2163 /* fprintf(stderr, "Value only written %s\n", value->name); */
2164 tempbool = ir_value_life_merge(value, instr->eid);
2165 *changed = *changed || tempbool;
2167 ir_instr_dump(instr, dbg_ind, printf);
2171 /* since 'living' won't contain it
2172 * anymore, merge the value, since
2175 tempbool = ir_value_life_merge(value, instr->eid);
2178 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2180 *changed = *changed || tempbool;
2182 if (!ir_block_living_remove(self, idx))
2188 tempbool = ir_block_living_add_instr(self, instr->eid);
2189 /*fprintf(stderr, "living added values\n");*/
2190 *changed = *changed || tempbool;
2194 if (self->run_id == self->owner->run_id)
2197 self->run_id = self->owner->run_id;
2199 for (i = 0; i < self->entries_count; ++i)
2201 ir_block *entry = self->entries[i];
2202 ir_block_life_propagate(entry, self, changed);
2208 /***********************************************************************
2211 * Since the IR has the convention of putting 'write' operands
2212 * at the beginning, we have to rotate the operands of instructions
2213 * properly in order to generate valid QCVM code.
2215 * Having destinations at a fixed position is more convenient. In QC
2216 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2217 * read from from OPA, and store to OPB rather than OPC. Which is
2218 * partially the reason why the implementation of these instructions
2219 * in darkplaces has been delayed for so long.
2221 * Breaking conventions is annoying...
2223 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
2225 static bool gen_global_field(ir_value *global)
2227 if (global->isconst)
2229 ir_value *fld = global->constval.vpointer;
2231 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2235 /* Now, in this case, a relocation would be impossible to code
2236 * since it looks like this:
2237 * .vector v = origin; <- parse error, wtf is 'origin'?
2240 * But we will need a general relocation support later anyway
2241 * for functions... might as well support that here.
2243 if (!fld->code.globaladdr) {
2244 irerror(global->context, "FIXME: Relocation support");
2248 /* copy the field's value */
2249 ir_value_code_setaddr(global, code_globals_add(code_globals_data[fld->code.globaladdr]));
2250 if (global->fieldtype == TYPE_VECTOR) {
2251 code_globals_add(code_globals_data[fld->code.globaladdr]+1);
2252 code_globals_add(code_globals_data[fld->code.globaladdr]+2);
2257 ir_value_code_setaddr(global, code_globals_add(0));
2258 if (global->fieldtype == TYPE_VECTOR) {
2259 code_globals_add(0);
2260 code_globals_add(0);
2263 if (global->code.globaladdr < 0)
2268 static bool gen_global_pointer(ir_value *global)
2270 if (global->isconst)
2272 ir_value *target = global->constval.vpointer;
2274 irerror(global->context, "Invalid pointer constant: %s", global->name);
2275 /* NULL pointers are pointing to the NULL constant, which also
2276 * sits at address 0, but still has an ir_value for itself.
2281 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2282 * void() foo; <- proto
2283 * void() *fooptr = &foo;
2284 * void() foo = { code }
2286 if (!target->code.globaladdr) {
2287 /* FIXME: Check for the constant nullptr ir_value!
2288 * because then code.globaladdr being 0 is valid.
2290 irerror(global->context, "FIXME: Relocation support");
2294 ir_value_code_setaddr(global, code_globals_add(target->code.globaladdr));
2298 ir_value_code_setaddr(global, code_globals_add(0));
2300 if (global->code.globaladdr < 0)
2305 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2307 prog_section_statement stmt;
2316 block->generated = true;
2317 block->code_start = code_statements_elements;
2318 for (i = 0; i < block->instr_count; ++i)
2320 instr = block->instr[i];
2322 if (instr->opcode == VINSTR_PHI) {
2323 irerror(block->context, "cannot generate virtual instruction (phi)");
2327 if (instr->opcode == VINSTR_JUMP) {
2328 target = instr->bops[0];
2329 /* for uncoditional jumps, if the target hasn't been generated
2330 * yet, we generate them right here.
2332 if (!target->generated) {
2337 /* otherwise we generate a jump instruction */
2338 stmt.opcode = INSTR_GOTO;
2339 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2342 if (code_statements_add(stmt) < 0)
2345 /* no further instructions can be in this block */
2349 if (instr->opcode == VINSTR_COND) {
2350 ontrue = instr->bops[0];
2351 onfalse = instr->bops[1];
2352 /* TODO: have the AST signal which block should
2353 * come first: eg. optimize IFs without ELSE...
2356 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2360 if (ontrue->generated) {
2361 stmt.opcode = INSTR_IF;
2362 stmt.o2.s1 = (ontrue->code_start) - code_statements_elements;
2363 if (code_statements_add(stmt) < 0)
2366 if (onfalse->generated) {
2367 stmt.opcode = INSTR_IFNOT;
2368 stmt.o2.s1 = (onfalse->code_start) - code_statements_elements;
2369 if (code_statements_add(stmt) < 0)
2372 if (!ontrue->generated) {
2373 if (onfalse->generated) {
2378 if (!onfalse->generated) {
2379 if (ontrue->generated) {
2384 /* neither ontrue nor onfalse exist */
2385 stmt.opcode = INSTR_IFNOT;
2386 stidx = code_statements_elements;
2387 if (code_statements_add(stmt) < 0)
2389 /* on false we jump, so add ontrue-path */
2390 if (!gen_blocks_recursive(func, ontrue))
2392 /* fixup the jump address */
2393 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2394 /* generate onfalse path */
2395 if (onfalse->generated) {
2396 /* fixup the jump address */
2397 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2398 /* may have been generated in the previous recursive call */
2399 stmt.opcode = INSTR_GOTO;
2400 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2403 return (code_statements_add(stmt) >= 0);
2405 /* if not, generate now */
2410 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2411 /* Trivial call translation:
2412 * copy all params to OFS_PARM*
2413 * if the output's storetype is not store_return,
2414 * add append a STORE instruction!
2416 * NOTES on how to do it better without much trouble:
2417 * -) The liferanges!
2418 * Simply check the liferange of all parameters for
2419 * other CALLs. For each param with no CALL in its
2420 * liferange, we can store it in an OFS_PARM at
2421 * generation already. This would even include later
2422 * reuse.... probably... :)
2427 for (p = 0; p < instr->params_count; ++p)
2429 ir_value *param = instr->params[p];
2431 stmt.opcode = INSTR_STORE_F;
2434 stmt.opcode = type_store_instr[param->vtype];
2435 stmt.o1.u1 = ir_value_code_addr(param);
2436 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2437 if (code_statements_add(stmt) < 0)
2440 stmt.opcode = INSTR_CALL0 + instr->params_count;
2441 if (stmt.opcode > INSTR_CALL8)
2442 stmt.opcode = INSTR_CALL8;
2443 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2446 if (code_statements_add(stmt) < 0)
2449 retvalue = instr->_ops[0];
2450 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2452 /* not to be kept in OFS_RETURN */
2453 stmt.opcode = type_store_instr[retvalue->vtype];
2454 stmt.o1.u1 = OFS_RETURN;
2455 stmt.o2.u1 = ir_value_code_addr(retvalue);
2457 if (code_statements_add(stmt) < 0)
2463 if (instr->opcode == INSTR_STATE) {
2464 irerror(block->context, "TODO: state instruction");
2468 stmt.opcode = instr->opcode;
2473 /* This is the general order of operands */
2475 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2478 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2481 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2483 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2485 stmt.o1.u1 = stmt.o3.u1;
2488 else if ((stmt.opcode >= INSTR_STORE_F &&
2489 stmt.opcode <= INSTR_STORE_FNC) ||
2490 (stmt.opcode >= INSTR_STOREP_F &&
2491 stmt.opcode <= INSTR_STOREP_FNC))
2493 /* 2-operand instructions with A -> B */
2494 stmt.o2.u1 = stmt.o3.u1;
2498 if (code_statements_add(stmt) < 0)
2504 static bool gen_function_code(ir_function *self)
2507 prog_section_statement stmt;
2509 /* Starting from entry point, we generate blocks "as they come"
2510 * for now. Dead blocks will not be translated obviously.
2512 if (!self->blocks_count) {
2513 irerror(self->context, "Function '%s' declared without body.", self->name);
2517 block = self->blocks[0];
2518 if (block->generated)
2521 if (!gen_blocks_recursive(self, block)) {
2522 irerror(self->context, "failed to generate blocks for '%s'", self->name);
2526 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2527 stmt.opcode = AINSTR_END;
2531 if (code_statements_add(stmt) < 0)
2536 static bool gen_global_function(ir_builder *ir, ir_value *global)
2538 prog_section_function fun;
2542 size_t local_var_end;
2544 if (!global->isconst || (!global->constval.vfunc))
2546 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
2550 irfun = global->constval.vfunc;
2552 fun.name = global->code.name;
2553 fun.file = code_cachedstring(global->context.file);
2554 fun.profile = 0; /* always 0 */
2555 fun.nargs = irfun->params_count;
2557 for (i = 0;i < 8; ++i) {
2561 fun.argsize[i] = type_sizeof[irfun->params[i]];
2564 fun.firstlocal = code_globals_elements;
2565 fun.locals = irfun->allocated_locals + irfun->locals_count;
2567 local_var_end = fun.firstlocal;
2568 for (i = 0; i < irfun->locals_count; ++i) {
2569 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2570 irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
2574 if (irfun->locals_count) {
2575 ir_value *last = irfun->locals[irfun->locals_count-1];
2576 local_var_end = last->code.globaladdr;
2577 local_var_end += type_sizeof[last->vtype];
2579 for (i = 0; i < irfun->values_count; ++i)
2581 /* generate code.globaladdr for ssa values */
2582 ir_value *v = irfun->values[i];
2583 ir_value_code_setaddr(v, local_var_end + v->code.local);
2585 for (i = 0; i < irfun->allocated_locals; ++i) {
2586 /* fill the locals with zeros */
2587 code_globals_add(0);
2591 fun.entry = irfun->builtin;
2593 irfun->code_function_def = code_functions_elements;
2594 fun.entry = code_statements_elements;
2597 return (code_functions_add(fun) >= 0);
2600 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
2602 prog_section_function *fundef;
2605 irfun = global->constval.vfunc;
2609 if (irfun->code_function_def < 0) {
2610 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
2613 fundef = &code_functions_data[irfun->code_function_def];
2615 fundef->entry = code_statements_elements;
2616 if (!gen_function_code(irfun)) {
2617 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
2623 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2627 prog_section_def def;
2629 def.type = global->vtype;
2630 def.offset = code_globals_elements;
2631 def.name = global->code.name = code_genstring(global->name);
2633 switch (global->vtype)
2636 if (code_defs_add(def) < 0)
2638 return gen_global_pointer(global);
2640 if (code_defs_add(def) < 0)
2642 return gen_global_field(global);
2647 if (code_defs_add(def) < 0)
2650 if (global->isconst) {
2651 iptr = (int32_t*)&global->constval.vfloat;
2652 ir_value_code_setaddr(global, code_globals_add(*iptr));
2654 ir_value_code_setaddr(global, code_globals_add(0));
2656 return global->code.globaladdr >= 0;
2660 if (code_defs_add(def) < 0)
2662 if (global->isconst)
2663 ir_value_code_setaddr(global, code_globals_add(code_cachedstring(global->constval.vstring)));
2665 ir_value_code_setaddr(global, code_globals_add(0));
2666 return global->code.globaladdr >= 0;
2671 if (code_defs_add(def) < 0)
2674 if (global->isconst) {
2675 iptr = (int32_t*)&global->constval.vvec;
2676 ir_value_code_setaddr(global, code_globals_add(iptr[0]));
2677 if (global->code.globaladdr < 0)
2679 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2681 if (code_globals_add(iptr[d]) < 0)
2685 ir_value_code_setaddr(global, code_globals_add(0));
2686 if (global->code.globaladdr < 0)
2688 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2690 if (code_globals_add(0) < 0)
2694 return global->code.globaladdr >= 0;
2697 if (code_defs_add(def) < 0)
2699 ir_value_code_setaddr(global, code_globals_elements);
2700 code_globals_add(code_functions_elements);
2701 return gen_global_function(self, global);
2703 /* assume biggest type */
2704 ir_value_code_setaddr(global, code_globals_add(0));
2705 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2706 code_globals_add(0);
2709 /* refuse to create 'void' type or any other fancy business. */
2710 irerror(global->context, "Invalid type for global variable `%s`: %s",
2711 global->name, type_name[global->vtype]);
2716 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2718 prog_section_def def;
2719 prog_section_field fld;
2721 def.type = field->vtype;
2722 def.offset = code_globals_elements;
2724 /* create a global named the same as the field */
2725 if (opts_standard == COMPILER_GMQCC) {
2726 /* in our standard, the global gets a dot prefix */
2727 size_t len = strlen(field->name);
2730 /* we really don't want to have to allocate this, and 1024
2731 * bytes is more than enough for a variable/field name
2733 if (len+2 >= sizeof(name)) {
2734 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
2739 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
2742 def.name = code_genstring(name);
2743 fld.name = def.name + 1; /* we reuse that string table entry */
2745 /* in plain QC, there cannot be a global with the same name,
2746 * and so we also name the global the same.
2747 * FIXME: fteqcc should create a global as well
2748 * check if it actually uses the same name. Probably does
2750 def.name = code_genstring(field->name);
2751 fld.name = def.name;
2754 field->code.name = def.name;
2756 if (code_defs_add(def) < 0)
2759 fld.type = field->fieldtype;
2761 if (fld.type == TYPE_VOID) {
2762 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
2766 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2768 if (code_fields_add(fld) < 0)
2771 ir_value_code_setaddr(field, code_globals_elements);
2772 if (!code_globals_add(fld.offset))
2774 if (fld.type == TYPE_VECTOR) {
2775 if (!code_globals_add(fld.offset+1))
2777 if (!code_globals_add(fld.offset+2))
2781 return field->code.globaladdr >= 0;
2784 bool ir_builder_generate(ir_builder *self, const char *filename)
2790 for (i = 0; i < self->fields_count; ++i)
2792 if (!ir_builder_gen_field(self, self->fields[i])) {
2797 for (i = 0; i < self->globals_count; ++i)
2799 if (!ir_builder_gen_global(self, self->globals[i])) {
2804 /* generate function code */
2805 for (i = 0; i < self->globals_count; ++i)
2807 if (self->globals[i]->vtype == TYPE_FUNCTION) {
2808 if (!gen_global_function_code(self, self->globals[i])) {
2814 printf("writing '%s'...\n", filename);
2815 return code_write(filename);
2818 /***********************************************************************
2819 *IR DEBUG Dump functions...
2822 #define IND_BUFSZ 1024
2825 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
2827 # define strncat strncat
2830 const char *qc_opname(int op)
2832 if (op < 0) return "<INVALID>";
2833 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2834 return asm_instr[op].m;
2836 case VINSTR_PHI: return "PHI";
2837 case VINSTR_JUMP: return "JUMP";
2838 case VINSTR_COND: return "COND";
2839 default: return "<UNK>";
2843 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2846 char indent[IND_BUFSZ];
2850 oprintf("module %s\n", b->name);
2851 for (i = 0; i < b->globals_count; ++i)
2854 if (b->globals[i]->isconst)
2855 oprintf("%s = ", b->globals[i]->name);
2856 ir_value_dump(b->globals[i], oprintf);
2859 for (i = 0; i < b->functions_count; ++i)
2860 ir_function_dump(b->functions[i], indent, oprintf);
2861 oprintf("endmodule %s\n", b->name);
2864 void ir_function_dump(ir_function *f, char *ind,
2865 int (*oprintf)(const char*, ...))
2868 if (f->builtin != 0) {
2869 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2872 oprintf("%sfunction %s\n", ind, f->name);
2873 strncat(ind, "\t", IND_BUFSZ);
2874 if (f->locals_count)
2876 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2877 for (i = 0; i < f->locals_count; ++i) {
2878 oprintf("%s\t", ind);
2879 ir_value_dump(f->locals[i], oprintf);
2883 if (f->blocks_count)
2885 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2886 for (i = 0; i < f->blocks_count; ++i) {
2887 if (f->blocks[i]->run_id != f->run_id) {
2888 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2890 ir_block_dump(f->blocks[i], ind, oprintf);
2894 ind[strlen(ind)-1] = 0;
2895 oprintf("%sendfunction %s\n", ind, f->name);
2898 void ir_block_dump(ir_block* b, char *ind,
2899 int (*oprintf)(const char*, ...))
2902 oprintf("%s:%s\n", ind, b->label);
2903 strncat(ind, "\t", IND_BUFSZ);
2905 for (i = 0; i < b->instr_count; ++i)
2906 ir_instr_dump(b->instr[i], ind, oprintf);
2907 ind[strlen(ind)-1] = 0;
2910 void dump_phi(ir_instr *in, char *ind,
2911 int (*oprintf)(const char*, ...))
2914 oprintf("%s <- phi ", in->_ops[0]->name);
2915 for (i = 0; i < in->phi_count; ++i)
2917 oprintf("([%s] : %s) ", in->phi[i].from->label,
2918 in->phi[i].value->name);
2923 void ir_instr_dump(ir_instr *in, char *ind,
2924 int (*oprintf)(const char*, ...))
2927 const char *comma = NULL;
2929 oprintf("%s (%i) ", ind, (int)in->eid);
2931 if (in->opcode == VINSTR_PHI) {
2932 dump_phi(in, ind, oprintf);
2936 strncat(ind, "\t", IND_BUFSZ);
2938 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2939 ir_value_dump(in->_ops[0], oprintf);
2940 if (in->_ops[1] || in->_ops[2])
2943 if (in->opcode == INSTR_CALL0) {
2944 oprintf("CALL%i\t", in->params_count);
2946 oprintf("%s\t", qc_opname(in->opcode));
2948 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2949 ir_value_dump(in->_ops[0], oprintf);
2954 for (i = 1; i != 3; ++i) {
2958 ir_value_dump(in->_ops[i], oprintf);
2966 oprintf("[%s]", in->bops[0]->label);
2970 oprintf("%s[%s]", comma, in->bops[1]->label);
2972 ind[strlen(ind)-1] = 0;
2975 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
2984 oprintf("(function)");
2987 oprintf("%g", v->constval.vfloat);
2990 oprintf("'%g %g %g'",
2993 v->constval.vvec.z);
2996 oprintf("(entity)");
2999 oprintf("\"%s\"", v->constval.vstring);
3003 oprintf("%i", v->constval.vint);
3008 v->constval.vpointer->name);
3012 oprintf("%s", v->name);
3016 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
3019 oprintf("Life of %s:\n", self->name);
3020 for (i = 0; i < self->life_count; ++i)
3022 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);