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] = {
48 size_t type_sizeof[TYPE_COUNT] = {
55 1, /* TYPE_FUNCTION */
64 uint16_t type_store_instr[TYPE_COUNT] = {
65 INSTR_STORE_F, /* should use I when having integer support */
72 INSTR_STORE_ENT, /* should use I */
74 INSTR_STORE_I, /* integer type */
79 INSTR_STORE_V, /* variant, should never be accessed */
81 AINSTR_END, /* struct */
82 AINSTR_END, /* union */
83 AINSTR_END, /* array */
86 uint16_t field_store_instr[TYPE_COUNT] = {
96 INSTR_STORE_FLD, /* integer type */
101 INSTR_STORE_V, /* variant, should never be accessed */
103 AINSTR_END, /* struct */
104 AINSTR_END, /* union */
105 AINSTR_END, /* array */
108 uint16_t type_storep_instr[TYPE_COUNT] = {
109 INSTR_STOREP_F, /* should use I when having integer support */
116 INSTR_STOREP_ENT, /* should use I */
118 INSTR_STOREP_ENT, /* integer type */
123 INSTR_STOREP_V, /* variant, should never be accessed */
125 AINSTR_END, /* struct */
126 AINSTR_END, /* union */
127 AINSTR_END, /* array */
130 uint16_t type_eq_instr[TYPE_COUNT] = {
131 INSTR_EQ_F, /* should use I when having integer support */
136 INSTR_EQ_E, /* FLD has no comparison */
138 INSTR_EQ_E, /* should use I */
145 INSTR_EQ_V, /* variant, should never be accessed */
147 AINSTR_END, /* struct */
148 AINSTR_END, /* union */
149 AINSTR_END, /* array */
152 uint16_t type_ne_instr[TYPE_COUNT] = {
153 INSTR_NE_F, /* should use I when having integer support */
158 INSTR_NE_E, /* FLD has no comparison */
160 INSTR_NE_E, /* should use I */
167 INSTR_NE_V, /* variant, should never be accessed */
169 AINSTR_END, /* struct */
170 AINSTR_END, /* union */
171 AINSTR_END, /* array */
174 static void irerror(lex_ctx ctx, const char *msg, ...)
178 con_cvprintmsg((void*)&ctx, LVL_ERROR, "internal error", msg, ap);
182 static bool irwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
185 int lvl = LVL_WARNING;
187 if (warntype && !OPTS_WARN(warntype))
194 con_vprintmsg(lvl, ctx.file, ctx.line, "warning", fmt, ap);
200 /***********************************************************************
201 * Vector utility functions
204 bool GMQCC_WARN vec_ir_value_find(ir_value **vec, ir_value *what, size_t *idx)
207 size_t len = vec_size(vec);
208 for (i = 0; i < len; ++i) {
209 if (vec[i] == what) {
217 bool GMQCC_WARN vec_ir_block_find(ir_block **vec, ir_block *what, size_t *idx)
220 size_t len = vec_size(vec);
221 for (i = 0; i < len; ++i) {
222 if (vec[i] == what) {
230 bool GMQCC_WARN vec_ir_instr_find(ir_instr **vec, ir_instr *what, size_t *idx)
233 size_t len = vec_size(vec);
234 for (i = 0; i < len; ++i) {
235 if (vec[i] == what) {
243 /***********************************************************************
247 static void ir_block_delete_quick(ir_block* self);
248 static void ir_instr_delete_quick(ir_instr *self);
249 static void ir_function_delete_quick(ir_function *self);
251 ir_builder* ir_builder_new(const char *modulename)
255 self = (ir_builder*)mem_a(sizeof(*self));
259 self->functions = NULL;
260 self->globals = NULL;
262 self->filenames = NULL;
263 self->filestrings = NULL;
265 self->str_immediate = 0;
267 if (!ir_builder_set_name(self, modulename)) {
275 void ir_builder_delete(ir_builder* self)
278 mem_d((void*)self->name);
279 for (i = 0; i != vec_size(self->functions); ++i) {
280 ir_function_delete_quick(self->functions[i]);
282 vec_free(self->functions);
283 for (i = 0; i != vec_size(self->globals); ++i) {
284 ir_value_delete(self->globals[i]);
286 vec_free(self->globals);
287 for (i = 0; i != vec_size(self->fields); ++i) {
288 ir_value_delete(self->fields[i]);
290 vec_free(self->fields);
291 vec_free(self->filenames);
292 vec_free(self->filestrings);
296 bool ir_builder_set_name(ir_builder *self, const char *name)
299 mem_d((void*)self->name);
300 self->name = util_strdup(name);
304 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
307 for (i = 0; i < vec_size(self->functions); ++i) {
308 if (!strcmp(name, self->functions[i]->name))
309 return self->functions[i];
314 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
316 ir_function *fn = ir_builder_get_function(self, name);
321 fn = ir_function_new(self, outtype);
322 if (!ir_function_set_name(fn, name))
324 ir_function_delete(fn);
327 vec_push(self->functions, fn);
329 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
331 ir_function_delete(fn);
335 fn->value->isconst = true;
336 fn->value->outtype = outtype;
337 fn->value->constval.vfunc = fn;
338 fn->value->context = fn->context;
343 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
346 for (i = 0; i < vec_size(self->globals); ++i) {
347 if (!strcmp(self->globals[i]->name, name))
348 return self->globals[i];
353 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
357 if (name && name[0] != '#')
359 ve = ir_builder_get_global(self, name);
365 ve = ir_value_var(name, store_global, vtype);
366 vec_push(self->globals, ve);
370 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
373 for (i = 0; i < vec_size(self->fields); ++i) {
374 if (!strcmp(self->fields[i]->name, name))
375 return self->fields[i];
381 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
383 ir_value *ve = ir_builder_get_field(self, name);
388 ve = ir_value_var(name, store_global, TYPE_FIELD);
389 ve->fieldtype = vtype;
390 vec_push(self->fields, ve);
394 /***********************************************************************
398 bool ir_function_naive_phi(ir_function*);
399 void ir_function_enumerate(ir_function*);
400 bool ir_function_calculate_liferanges(ir_function*);
401 bool ir_function_allocate_locals(ir_function*);
403 ir_function* ir_function_new(ir_builder* owner, int outtype)
406 self = (ir_function*)mem_a(sizeof(*self));
411 memset(self, 0, sizeof(*self));
414 if (!ir_function_set_name(self, "<@unnamed>")) {
419 self->context.file = "<@no context>";
420 self->context.line = 0;
421 self->outtype = outtype;
430 self->code_function_def = -1;
431 self->allocated_locals = 0;
437 bool ir_function_set_name(ir_function *self, const char *name)
440 mem_d((void*)self->name);
441 self->name = util_strdup(name);
445 static void ir_function_delete_quick(ir_function *self)
448 mem_d((void*)self->name);
450 for (i = 0; i != vec_size(self->blocks); ++i)
451 ir_block_delete_quick(self->blocks[i]);
452 vec_free(self->blocks);
454 vec_free(self->params);
456 for (i = 0; i != vec_size(self->values); ++i)
457 ir_value_delete(self->values[i]);
458 vec_free(self->values);
460 for (i = 0; i != vec_size(self->locals); ++i)
461 ir_value_delete(self->locals[i]);
462 vec_free(self->locals);
464 /* self->value is deleted by the builder */
469 void ir_function_delete(ir_function *self)
472 mem_d((void*)self->name);
474 for (i = 0; i != vec_size(self->blocks); ++i)
475 ir_block_delete(self->blocks[i]);
476 vec_free(self->blocks);
478 vec_free(self->params);
480 for (i = 0; i != vec_size(self->values); ++i)
481 ir_value_delete(self->values[i]);
482 vec_free(self->values);
484 for (i = 0; i != vec_size(self->locals); ++i)
485 ir_value_delete(self->locals[i]);
486 vec_free(self->locals);
488 /* self->value is deleted by the builder */
493 void ir_function_collect_value(ir_function *self, ir_value *v)
495 vec_push(self->values, v);
498 ir_block* ir_function_create_block(ir_function *self, const char *label)
500 ir_block* bn = ir_block_new(self, label);
501 memcpy(&bn->context, &self->context, sizeof(self->context));
502 vec_push(self->blocks, bn);
506 bool ir_function_finalize(ir_function *self)
511 if (!ir_function_naive_phi(self))
514 ir_function_enumerate(self);
516 if (!ir_function_calculate_liferanges(self))
519 if (!ir_function_allocate_locals(self))
524 ir_value* ir_function_get_local(ir_function *self, const char *name)
527 for (i = 0; i < vec_size(self->locals); ++i) {
528 if (!strcmp(self->locals[i]->name, name))
529 return self->locals[i];
534 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
539 if (ir_function_get_local(self, name))
544 vec_size(self->locals) &&
545 self->locals[vec_size(self->locals)-1]->store != store_param) {
546 irerror(self->context, "cannot add parameters after adding locals");
550 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
551 vec_push(self->locals, ve);
555 /***********************************************************************
559 ir_block* ir_block_new(ir_function* owner, const char *name)
562 self = (ir_block*)mem_a(sizeof(*self));
566 memset(self, 0, sizeof(*self));
569 if (name && !ir_block_set_label(self, name)) {
574 self->context.file = "<@no context>";
575 self->context.line = 0;
579 self->entries = NULL;
583 self->is_return = false;
588 self->generated = false;
593 static void ir_block_delete_quick(ir_block* self)
596 if (self->label) mem_d(self->label);
597 for (i = 0; i != vec_size(self->instr); ++i)
598 ir_instr_delete_quick(self->instr[i]);
599 vec_free(self->instr);
600 vec_free(self->entries);
601 vec_free(self->exits);
602 vec_free(self->living);
606 void ir_block_delete(ir_block* self)
609 if (self->label) mem_d(self->label);
610 for (i = 0; i != vec_size(self->instr); ++i)
611 ir_instr_delete(self->instr[i]);
612 vec_free(self->instr);
613 vec_free(self->entries);
614 vec_free(self->exits);
615 vec_free(self->living);
619 bool ir_block_set_label(ir_block *self, const char *name)
622 mem_d((void*)self->label);
623 self->label = util_strdup(name);
624 return !!self->label;
627 /***********************************************************************
631 ir_instr* ir_instr_new(ir_block* owner, int op)
634 self = (ir_instr*)mem_a(sizeof(*self));
639 self->context.file = "<@no context>";
640 self->context.line = 0;
642 self->_ops[0] = NULL;
643 self->_ops[1] = NULL;
644 self->_ops[2] = NULL;
645 self->bops[0] = NULL;
646 self->bops[1] = NULL;
655 static void ir_instr_delete_quick(ir_instr *self)
658 vec_free(self->params);
662 void ir_instr_delete(ir_instr *self)
665 /* The following calls can only delete from
666 * vectors, we still want to delete this instruction
667 * so ignore the return value. Since with the warn_unused_result attribute
668 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
669 * I have to improvise here and use if(foo());
671 for (i = 0; i < vec_size(self->phi); ++i) {
673 if (vec_ir_instr_find(self->phi[i].value->writes, self, &idx))
674 vec_remove(self->phi[i].value->writes, idx, 1);
675 if (vec_ir_instr_find(self->phi[i].value->reads, self, &idx))
676 vec_remove(self->phi[i].value->reads, idx, 1);
679 for (i = 0; i < vec_size(self->params); ++i) {
681 if (vec_ir_instr_find(self->params[i]->writes, self, &idx))
682 vec_remove(self->params[i]->writes, idx, 1);
683 if (vec_ir_instr_find(self->params[i]->reads, self, &idx))
684 vec_remove(self->params[i]->reads, idx, 1);
686 vec_free(self->params);
687 (void)!ir_instr_op(self, 0, NULL, false);
688 (void)!ir_instr_op(self, 1, NULL, false);
689 (void)!ir_instr_op(self, 2, NULL, false);
693 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
695 if (self->_ops[op]) {
697 if (writing && vec_ir_instr_find(self->_ops[op]->writes, self, &idx))
698 vec_remove(self->_ops[op]->writes, idx, 1);
699 else if (vec_ir_instr_find(self->_ops[op]->reads, self, &idx))
700 vec_remove(self->_ops[op]->reads, idx, 1);
704 vec_push(v->writes, self);
706 vec_push(v->reads, self);
712 /***********************************************************************
716 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
718 self->code.globaladdr = gaddr;
719 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
720 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
721 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
724 int32_t ir_value_code_addr(const ir_value *self)
726 if (self->store == store_return)
727 return OFS_RETURN + self->code.addroffset;
728 return self->code.globaladdr + self->code.addroffset;
731 ir_value* ir_value_var(const char *name, int storetype, int vtype)
734 self = (ir_value*)mem_a(sizeof(*self));
736 self->fieldtype = TYPE_VOID;
737 self->outtype = TYPE_VOID;
738 self->store = storetype;
743 self->isconst = false;
744 self->context.file = "<@no context>";
745 self->context.line = 0;
747 if (name && !ir_value_set_name(self, name)) {
748 irerror(self->context, "out of memory");
753 memset(&self->constval, 0, sizeof(self->constval));
754 memset(&self->code, 0, sizeof(self->code));
756 self->members[0] = NULL;
757 self->members[1] = NULL;
758 self->members[2] = NULL;
759 self->memberof = NULL;
765 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
771 if (self->members[member])
772 return self->members[member];
774 if (self->vtype == TYPE_VECTOR)
776 m = ir_value_var(self->name, self->store, TYPE_FLOAT);
779 m->context = self->context;
781 self->members[member] = m;
782 m->code.addroffset = member;
784 else if (self->vtype == TYPE_FIELD)
786 if (self->fieldtype != TYPE_VECTOR)
788 m = ir_value_var(self->name, self->store, TYPE_FIELD);
791 m->fieldtype = TYPE_FLOAT;
792 m->context = self->context;
794 self->members[member] = m;
795 m->code.addroffset = member;
799 irerror(self->context, "invalid member access on %s", self->name);
807 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
809 ir_value *v = ir_value_var(name, storetype, vtype);
812 ir_function_collect_value(owner, v);
816 void ir_value_delete(ir_value* self)
820 mem_d((void*)self->name);
823 if (self->vtype == TYPE_STRING)
824 mem_d((void*)self->constval.vstring);
826 for (i = 0; i < 3; ++i) {
827 if (self->members[i])
828 ir_value_delete(self->members[i]);
830 vec_free(self->reads);
831 vec_free(self->writes);
832 vec_free(self->life);
836 bool ir_value_set_name(ir_value *self, const char *name)
839 mem_d((void*)self->name);
840 self->name = util_strdup(name);
844 bool ir_value_set_float(ir_value *self, float f)
846 if (self->vtype != TYPE_FLOAT)
848 self->constval.vfloat = f;
849 self->isconst = true;
853 bool ir_value_set_func(ir_value *self, int f)
855 if (self->vtype != TYPE_FUNCTION)
857 self->constval.vint = f;
858 self->isconst = true;
862 bool ir_value_set_vector(ir_value *self, vector v)
864 if (self->vtype != TYPE_VECTOR)
866 self->constval.vvec = v;
867 self->isconst = true;
871 bool ir_value_set_field(ir_value *self, ir_value *fld)
873 if (self->vtype != TYPE_FIELD)
875 self->constval.vpointer = fld;
876 self->isconst = true;
880 static char *ir_strdup(const char *str)
883 /* actually dup empty strings */
884 char *out = mem_a(1);
888 return util_strdup(str);
891 bool ir_value_set_string(ir_value *self, const char *str)
893 if (self->vtype != TYPE_STRING)
895 self->constval.vstring = ir_strdup(str);
896 self->isconst = true;
901 bool ir_value_set_int(ir_value *self, int i)
903 if (self->vtype != TYPE_INTEGER)
905 self->constval.vint = i;
906 self->isconst = true;
911 bool ir_value_lives(ir_value *self, size_t at)
914 for (i = 0; i < vec_size(self->life); ++i)
916 ir_life_entry_t *life = &self->life[i];
917 if (life->start <= at && at <= life->end)
919 if (life->start > at) /* since it's ordered */
925 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
928 vec_push(self->life, e);
929 for (k = vec_size(self->life)-1; k > idx; --k)
930 self->life[k] = self->life[k-1];
935 bool ir_value_life_merge(ir_value *self, size_t s)
938 ir_life_entry_t *life = NULL;
939 ir_life_entry_t *before = NULL;
940 ir_life_entry_t new_entry;
942 /* Find the first range >= s */
943 for (i = 0; i < vec_size(self->life); ++i)
946 life = &self->life[i];
950 /* nothing found? append */
951 if (i == vec_size(self->life)) {
953 if (life && life->end+1 == s)
955 /* previous life range can be merged in */
959 if (life && life->end >= s)
962 vec_push(self->life, e);
968 if (before->end + 1 == s &&
969 life->start - 1 == s)
972 before->end = life->end;
973 vec_remove(self->life, i, 1);
976 if (before->end + 1 == s)
982 /* already contained */
983 if (before->end >= s)
987 if (life->start - 1 == s)
992 /* insert a new entry */
993 new_entry.start = new_entry.end = s;
994 return ir_value_life_insert(self, i, new_entry);
997 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1001 if (!vec_size(other->life))
1004 if (!vec_size(self->life)) {
1005 size_t count = vec_size(other->life);
1006 ir_life_entry_t *life = vec_add(self->life, count);
1007 memcpy(life, other->life, count * sizeof(*life));
1012 for (i = 0; i < vec_size(other->life); ++i)
1014 const ir_life_entry_t *life = &other->life[i];
1017 ir_life_entry_t *entry = &self->life[myi];
1019 if (life->end+1 < entry->start)
1021 /* adding an interval before entry */
1022 if (!ir_value_life_insert(self, myi, *life))
1028 if (life->start < entry->start &&
1029 life->end+1 >= entry->start)
1031 /* starts earlier and overlaps */
1032 entry->start = life->start;
1035 if (life->end > entry->end &&
1036 life->start <= entry->end+1)
1038 /* ends later and overlaps */
1039 entry->end = life->end;
1042 /* see if our change combines it with the next ranges */
1043 while (myi+1 < vec_size(self->life) &&
1044 entry->end+1 >= self->life[1+myi].start)
1046 /* overlaps with (myi+1) */
1047 if (entry->end < self->life[1+myi].end)
1048 entry->end = self->life[1+myi].end;
1049 vec_remove(self->life, myi+1, 1);
1050 entry = &self->life[myi];
1053 /* see if we're after the entry */
1054 if (life->start > entry->end)
1057 /* append if we're at the end */
1058 if (myi >= vec_size(self->life)) {
1059 vec_push(self->life, *life);
1062 /* otherweise check the next range */
1071 bool ir_values_overlap(const ir_value *a, const ir_value *b)
1073 /* For any life entry in A see if it overlaps with
1074 * any life entry in B.
1075 * Note that the life entries are orderes, so we can make a
1076 * more efficient algorithm there than naively translating the
1080 ir_life_entry_t *la, *lb, *enda, *endb;
1082 /* first of all, if either has no life range, they cannot clash */
1083 if (!vec_size(a->life) || !vec_size(b->life))
1088 enda = la + vec_size(a->life);
1089 endb = lb + vec_size(b->life);
1092 /* check if the entries overlap, for that,
1093 * both must start before the other one ends.
1095 if (la->start < lb->end &&
1096 lb->start < la->end)
1101 /* entries are ordered
1102 * one entry is earlier than the other
1103 * that earlier entry will be moved forward
1105 if (la->start < lb->start)
1107 /* order: A B, move A forward
1108 * check if we hit the end with A
1113 else /* if (lb->start < la->start) actually <= */
1115 /* order: B A, move B forward
1116 * check if we hit the end with B
1125 /***********************************************************************
1129 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
1131 ir_instr *in = ir_instr_new(self, op);
1135 if (target->store == store_value &&
1136 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1138 irerror(self->context, "cannot store to an SSA value");
1139 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1140 irerror(self->context, "instruction: %s", asm_instr[op].m);
1144 if (!ir_instr_op(in, 0, target, true) ||
1145 !ir_instr_op(in, 1, what, false))
1149 vec_push(self->instr, in);
1153 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
1157 if (target->vtype == TYPE_VARIANT)
1158 vtype = what->vtype;
1160 vtype = target->vtype;
1163 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1164 op = INSTR_CONV_ITOF;
1165 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1166 op = INSTR_CONV_FTOI;
1168 op = type_store_instr[vtype];
1170 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1171 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1175 return ir_block_create_store_op(self, op, target, what);
1178 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
1183 if (target->vtype != TYPE_POINTER)
1186 /* storing using pointer - target is a pointer, type must be
1187 * inferred from source
1189 vtype = what->vtype;
1191 op = type_storep_instr[vtype];
1192 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1193 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1194 op = INSTR_STOREP_V;
1197 return ir_block_create_store_op(self, op, target, what);
1200 bool ir_block_create_return(ir_block *self, ir_value *v)
1204 irerror(self->context, "block already ended (%s)", self->label);
1208 self->is_return = true;
1209 in = ir_instr_new(self, INSTR_RETURN);
1213 if (v && !ir_instr_op(in, 0, v, false))
1216 vec_push(self->instr, in);
1220 bool ir_block_create_if(ir_block *self, ir_value *v,
1221 ir_block *ontrue, ir_block *onfalse)
1225 irerror(self->context, "block already ended (%s)", self->label);
1229 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1230 in = ir_instr_new(self, VINSTR_COND);
1234 if (!ir_instr_op(in, 0, v, false)) {
1235 ir_instr_delete(in);
1239 in->bops[0] = ontrue;
1240 in->bops[1] = onfalse;
1242 vec_push(self->instr, in);
1244 vec_push(self->exits, ontrue);
1245 vec_push(self->exits, onfalse);
1246 vec_push(ontrue->entries, self);
1247 vec_push(onfalse->entries, self);
1251 bool ir_block_create_jump(ir_block *self, ir_block *to)
1255 irerror(self->context, "block already ended (%s)", self->label);
1259 in = ir_instr_new(self, VINSTR_JUMP);
1264 vec_push(self->instr, in);
1266 vec_push(self->exits, to);
1267 vec_push(to->entries, self);
1271 bool ir_block_create_goto(ir_block *self, ir_block *to)
1275 irerror(self->context, "block already ended (%s)", self->label);
1279 in = ir_instr_new(self, INSTR_GOTO);
1284 vec_push(self->instr, in);
1286 vec_push(self->exits, to);
1287 vec_push(to->entries, self);
1291 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1295 in = ir_instr_new(self, VINSTR_PHI);
1298 out = ir_value_out(self->owner, label, store_value, ot);
1300 ir_instr_delete(in);
1303 if (!ir_instr_op(in, 0, out, true)) {
1304 ir_instr_delete(in);
1305 ir_value_delete(out);
1308 vec_push(self->instr, in);
1312 ir_value* ir_phi_value(ir_instr *self)
1314 return self->_ops[0];
1317 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1321 if (!vec_ir_block_find(self->owner->entries, b, NULL)) {
1322 /* Must not be possible to cause this, otherwise the AST
1323 * is doing something wrong.
1325 irerror(self->context, "Invalid entry block for PHI");
1331 vec_push(v->reads, self);
1332 vec_push(self->phi, pe);
1335 /* call related code */
1336 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1340 in = ir_instr_new(self, INSTR_CALL0);
1343 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1345 ir_instr_delete(in);
1348 if (!ir_instr_op(in, 0, out, true) ||
1349 !ir_instr_op(in, 1, func, false))
1351 ir_instr_delete(in);
1352 ir_value_delete(out);
1355 vec_push(self->instr, in);
1359 ir_value* ir_call_value(ir_instr *self)
1361 return self->_ops[0];
1364 void ir_call_param(ir_instr* self, ir_value *v)
1366 vec_push(self->params, v);
1367 vec_push(v->reads, self);
1370 /* binary op related code */
1372 ir_value* ir_block_create_binop(ir_block *self,
1373 const char *label, int opcode,
1374 ir_value *left, ir_value *right)
1396 case INSTR_SUB_S: /* -- offset of string as float */
1401 case INSTR_BITOR_IF:
1402 case INSTR_BITOR_FI:
1403 case INSTR_BITAND_FI:
1404 case INSTR_BITAND_IF:
1419 case INSTR_BITAND_I:
1422 case INSTR_RSHIFT_I:
1423 case INSTR_LSHIFT_I:
1445 /* boolean operations result in floats */
1446 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1448 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1451 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1456 if (ot == TYPE_VOID) {
1457 /* The AST or parser were supposed to check this! */
1461 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1464 ir_value* ir_block_create_unary(ir_block *self,
1465 const char *label, int opcode,
1468 int ot = TYPE_FLOAT;
1480 /* QC doesn't have other unary operations. We expect extensions to fill
1481 * the above list, otherwise we assume out-type = in-type, eg for an
1485 ot = operand->vtype;
1488 if (ot == TYPE_VOID) {
1489 /* The AST or parser were supposed to check this! */
1493 /* let's use the general instruction creator and pass NULL for OPB */
1494 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1497 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1498 int op, ir_value *a, ir_value *b, int outype)
1503 out = ir_value_out(self->owner, label, store_value, outype);
1507 instr = ir_instr_new(self, op);
1509 ir_value_delete(out);
1513 if (!ir_instr_op(instr, 0, out, true) ||
1514 !ir_instr_op(instr, 1, a, false) ||
1515 !ir_instr_op(instr, 2, b, false) )
1520 vec_push(self->instr, instr);
1524 ir_instr_delete(instr);
1525 ir_value_delete(out);
1529 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1533 /* Support for various pointer types todo if so desired */
1534 if (ent->vtype != TYPE_ENTITY)
1537 if (field->vtype != TYPE_FIELD)
1540 v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1541 v->fieldtype = field->fieldtype;
1545 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1548 if (ent->vtype != TYPE_ENTITY)
1551 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1552 if (field->vtype != TYPE_FIELD)
1557 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1558 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1559 case TYPE_STRING: op = INSTR_LOAD_S; break;
1560 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1561 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1562 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1564 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1565 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1568 irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1572 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1575 ir_value* ir_block_create_add(ir_block *self,
1577 ir_value *left, ir_value *right)
1580 int l = left->vtype;
1581 int r = right->vtype;
1585 irerror(self->context, "invalid type for ir_block_create_add: %s", type_name[l]);
1601 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1603 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1608 irerror(self->context, "invalid type for ir_block_create_add: %s", type_name[l]);
1612 return ir_block_create_binop(self, label, op, left, right);
1615 ir_value* ir_block_create_sub(ir_block *self,
1617 ir_value *left, ir_value *right)
1620 int l = left->vtype;
1621 int r = right->vtype;
1626 irerror(self->context, "invalid type for ir_block_create_sub: %s", type_name[l]);
1642 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1644 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1649 irerror(self->context, "invalid type for ir_block_create_sub: %s", type_name[l]);
1653 return ir_block_create_binop(self, label, op, left, right);
1656 ir_value* ir_block_create_mul(ir_block *self,
1658 ir_value *left, ir_value *right)
1661 int l = left->vtype;
1662 int r = right->vtype;
1667 irerror(self->context, "invalid type for ir_block_create_mul: %s", type_name[l]);
1682 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1684 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1687 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1689 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1691 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1693 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1697 irerror(self->context, "invalid type for ir_block_create_mul: %s", type_name[l]);
1701 return ir_block_create_binop(self, label, op, left, right);
1704 ir_value* ir_block_create_div(ir_block *self,
1706 ir_value *left, ir_value *right)
1709 int l = left->vtype;
1710 int r = right->vtype;
1715 irerror(self->context, "invalid type for ir_block_create_div: %s", type_name[l]);
1728 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1730 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1732 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1737 irerror(self->context, "invalid type for ir_block_create_div: %s", type_name[l]);
1741 return ir_block_create_binop(self, label, op, left, right);
1744 /* PHI resolving breaks the SSA, and must thus be the last
1745 * step before life-range calculation.
1748 static bool ir_block_naive_phi(ir_block *self);
1749 bool ir_function_naive_phi(ir_function *self)
1753 for (i = 0; i < vec_size(self->blocks); ++i)
1755 if (!ir_block_naive_phi(self->blocks[i]))
1761 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1766 /* create a store */
1767 if (!ir_block_create_store(block, old, what))
1770 /* we now move it up */
1771 instr = vec_last(block->instr);
1772 for (i = vec_size(block->instr)-1; i > iid; --i)
1773 block->instr[i] = block->instr[i-1];
1774 block->instr[i] = instr;
1779 static bool ir_block_naive_phi(ir_block *self)
1782 /* FIXME: optionally, create_phi can add the phis
1783 * to a list so we don't need to loop through blocks
1784 * - anyway: "don't optimize YET"
1786 for (i = 0; i < vec_size(self->instr); ++i)
1788 ir_instr *instr = self->instr[i];
1789 if (instr->opcode != VINSTR_PHI)
1792 vec_remove(self->instr, i, 1);
1793 --i; /* NOTE: i+1 below */
1795 for (p = 0; p < vec_size(instr->phi); ++p)
1797 ir_value *v = instr->phi[p].value;
1798 for (w = 0; w < vec_size(v->writes); ++w) {
1801 if (!v->writes[w]->_ops[0])
1804 /* When the write was to a global, we have to emit a mov */
1805 old = v->writes[w]->_ops[0];
1807 /* The original instruction now writes to the PHI target local */
1808 if (v->writes[w]->_ops[0] == v)
1809 v->writes[w]->_ops[0] = instr->_ops[0];
1811 if (old->store != store_value && old->store != store_local && old->store != store_param)
1813 /* If it originally wrote to a global we need to store the value
1816 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1818 if (i+1 < vec_size(self->instr))
1819 instr = self->instr[i+1];
1822 /* In case I forget and access instr later, it'll be NULL
1823 * when it's a problem, to make sure we crash, rather than accessing
1829 /* If it didn't, we can replace all reads by the phi target now. */
1831 for (r = 0; r < vec_size(old->reads); ++r)
1834 ir_instr *ri = old->reads[r];
1835 for (op = 0; op < vec_size(ri->phi); ++op) {
1836 if (ri->phi[op].value == old)
1837 ri->phi[op].value = v;
1839 for (op = 0; op < 3; ++op) {
1840 if (ri->_ops[op] == old)
1847 ir_instr_delete(instr);
1852 /***********************************************************************
1853 *IR Temp allocation code
1854 * Propagating value life ranges by walking through the function backwards
1855 * until no more changes are made.
1856 * In theory this should happen once more than once for every nested loop
1858 * Though this implementation might run an additional time for if nests.
1861 /* Enumerate instructions used by value's life-ranges
1863 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1867 for (i = 0; i < vec_size(self->instr); ++i)
1869 self->instr[i]->eid = eid++;
1874 /* Enumerate blocks and instructions.
1875 * The block-enumeration is unordered!
1876 * We do not really use the block enumreation, however
1877 * the instruction enumeration is important for life-ranges.
1879 void ir_function_enumerate(ir_function *self)
1882 size_t instruction_id = 0;
1883 for (i = 0; i < vec_size(self->blocks); ++i)
1885 self->blocks[i]->eid = i;
1886 self->blocks[i]->run_id = 0;
1887 ir_block_enumerate(self->blocks[i], &instruction_id);
1891 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1892 bool ir_function_calculate_liferanges(ir_function *self)
1900 for (i = 0; i != vec_size(self->blocks); ++i)
1902 if (self->blocks[i]->is_return)
1904 vec_free(self->blocks[i]->living);
1905 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1910 if (vec_size(self->blocks)) {
1911 ir_block *block = self->blocks[0];
1912 for (i = 0; i < vec_size(block->living); ++i) {
1913 ir_value *v = block->living[i];
1914 if (v->memberof || v->store != store_local)
1916 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
1917 "variable `%s` may be used uninitialized in this function", v->name))
1926 /* Local-value allocator
1927 * After finishing creating the liferange of all values used in a function
1928 * we can allocate their global-positions.
1929 * This is the counterpart to register-allocation in register machines.
1935 } function_allocator;
1937 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1940 size_t vsize = type_sizeof[var->vtype];
1942 slot = ir_value_var("reg", store_global, var->vtype);
1946 if (!ir_value_life_merge_into(slot, var))
1949 vec_push(alloc->locals, slot);
1950 vec_push(alloc->sizes, vsize);
1955 ir_value_delete(slot);
1959 bool ir_function_allocate_locals(ir_function *self)
1968 function_allocator alloc;
1970 if (!vec_size(self->locals) && !vec_size(self->values))
1973 alloc.locals = NULL;
1975 alloc.positions = NULL;
1977 for (i = 0; i < vec_size(self->locals); ++i)
1979 if (!function_allocator_alloc(&alloc, self->locals[i]))
1983 /* Allocate a slot for any value that still exists */
1984 for (i = 0; i < vec_size(self->values); ++i)
1986 v = self->values[i];
1988 if (!vec_size(v->life))
1991 for (a = 0; a < vec_size(alloc.locals); ++a)
1993 slot = alloc.locals[a];
1995 if (ir_values_overlap(v, slot))
1998 if (!ir_value_life_merge_into(slot, v))
2001 /* adjust size for this slot */
2002 if (alloc.sizes[a] < type_sizeof[v->vtype])
2003 alloc.sizes[a] = type_sizeof[v->vtype];
2005 self->values[i]->code.local = a;
2008 if (a >= vec_size(alloc.locals)) {
2009 self->values[i]->code.local = vec_size(alloc.locals);
2010 if (!function_allocator_alloc(&alloc, v))
2019 /* Adjust slot positions based on sizes */
2020 vec_push(alloc.positions, 0);
2022 if (vec_size(alloc.sizes))
2023 pos = alloc.positions[0] + alloc.sizes[0];
2026 for (i = 1; i < vec_size(alloc.sizes); ++i)
2028 pos = alloc.positions[i-1] + alloc.sizes[i-1];
2029 vec_push(alloc.positions, pos);
2032 self->allocated_locals = pos + vec_last(alloc.sizes);
2034 /* Take over the actual slot positions */
2035 for (i = 0; i < vec_size(self->values); ++i) {
2036 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
2044 for (i = 0; i < vec_size(alloc.locals); ++i)
2045 ir_value_delete(alloc.locals[i]);
2046 vec_free(alloc.locals);
2047 vec_free(alloc.sizes);
2048 vec_free(alloc.positions);
2052 /* Get information about which operand
2053 * is read from, or written to.
2055 static void ir_op_read_write(int op, size_t *read, size_t *write)
2075 case INSTR_STOREP_F:
2076 case INSTR_STOREP_V:
2077 case INSTR_STOREP_S:
2078 case INSTR_STOREP_ENT:
2079 case INSTR_STOREP_FLD:
2080 case INSTR_STOREP_FNC:
2091 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2094 bool changed = false;
2096 for (i = 0; i != vec_size(self->living); ++i)
2098 tempbool = ir_value_life_merge(self->living[i], eid);
2101 irerror(self->context, "block_living_add_instr() value instruction added %s: %i", self->living[i]->_name, (int)eid);
2103 changed = changed || tempbool;
2108 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
2111 /* values which have been read in a previous iteration are now
2112 * in the "living" array even if the previous block doesn't use them.
2113 * So we have to remove whatever does not exist in the previous block.
2114 * They will be re-added on-read, but the liferange merge won't cause
2117 for (i = 0; i < vec_size(self->living); ++i)
2119 if (!vec_ir_value_find(prev->living, self->living[i], NULL)) {
2120 vec_remove(self->living, i, 1);
2125 /* Whatever the previous block still has in its living set
2126 * must now be added to ours as well.
2128 for (i = 0; i < vec_size(prev->living); ++i)
2130 if (vec_ir_value_find(self->living, prev->living[i], NULL))
2132 vec_push(self->living, prev->living[i]);
2134 irerror(self->contextt from prev: %s", self->label, prev->living[i]->_name);
2140 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2146 /* bitmasks which operands are read from or written to */
2148 char dbg_ind[16] = { '#', '0' };
2153 if (!ir_block_life_prop_previous(self, prev, changed))
2157 i = vec_size(self->instr);
2160 instr = self->instr[i];
2162 /* PHI operands are always read operands */
2163 for (p = 0; p < vec_size(instr->phi); ++p)
2165 value = instr->phi[p].value;
2166 if (value->memberof)
2167 value = value->memberof;
2168 if (!vec_ir_value_find(self->living, value, NULL))
2169 vec_push(self->living, value);
2172 /* call params are read operands too */
2173 for (p = 0; p < vec_size(instr->params); ++p)
2175 value = instr->params[p];
2176 if (value->memberof)
2177 value = value->memberof;
2178 if (!vec_ir_value_find(self->living, value, NULL))
2179 vec_push(self->living, value);
2182 /* See which operands are read and write operands */
2183 ir_op_read_write(instr->opcode, &read, &write);
2185 if (instr->opcode == INSTR_MUL_VF)
2187 /* the float source will get an additional lifetime */
2188 tempbool = ir_value_life_merge(instr->_ops[2], instr->eid+1);
2189 *changed = *changed || tempbool;
2191 else if (instr->opcode == INSTR_MUL_FV)
2193 /* the float source will get an additional lifetime */
2194 tempbool = ir_value_life_merge(instr->_ops[1], instr->eid+1);
2195 *changed = *changed || tempbool;
2198 /* Go through the 3 main operands */
2199 for (o = 0; o < 3; ++o)
2201 if (!instr->_ops[o]) /* no such operand */
2204 value = instr->_ops[o];
2205 if (value->memberof)
2206 value = value->memberof;
2208 /* We only care about locals */
2209 /* we also calculate parameter liferanges so that locals
2210 * can take up parameter slots */
2211 if (value->store != store_value &&
2212 value->store != store_local &&
2213 value->store != store_param)
2219 if (!vec_ir_value_find(self->living, value, NULL))
2220 vec_push(self->living, value);
2223 /* write operands */
2224 /* When we write to a local, we consider it "dead" for the
2225 * remaining upper part of the function, since in SSA a value
2226 * can only be written once (== created)
2231 bool in_living = vec_ir_value_find(self->living, value, &idx);
2234 /* If the value isn't alive it hasn't been read before... */
2235 /* TODO: See if the warning can be emitted during parsing or AST processing
2236 * otherwise have warning printed here.
2237 * IF printing a warning here: include filecontext_t,
2238 * and make sure it's only printed once
2239 * since this function is run multiple times.
2241 /* For now: debug info: */
2242 /* con_err( "Value only written %s\n", value->name); */
2243 tempbool = ir_value_life_merge(value, instr->eid);
2244 *changed = *changed || tempbool;
2246 ir_instr_dump(instr, dbg_ind, printf);
2250 /* since 'living' won't contain it
2251 * anymore, merge the value, since
2254 tempbool = ir_value_life_merge(value, instr->eid);
2257 con_err( "value added id %s %i\n", value->name, (int)instr->eid);
2259 *changed = *changed || tempbool;
2261 vec_remove(self->living, idx, 1);
2266 tempbool = ir_block_living_add_instr(self, instr->eid);
2267 /*con_err( "living added values\n");*/
2268 *changed = *changed || tempbool;
2272 if (self->run_id == self->owner->run_id)
2275 self->run_id = self->owner->run_id;
2277 for (i = 0; i < vec_size(self->entries); ++i)
2279 ir_block *entry = self->entries[i];
2280 ir_block_life_propagate(entry, self, changed);
2286 /***********************************************************************
2289 * Since the IR has the convention of putting 'write' operands
2290 * at the beginning, we have to rotate the operands of instructions
2291 * properly in order to generate valid QCVM code.
2293 * Having destinations at a fixed position is more convenient. In QC
2294 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2295 * read from from OPA, and store to OPB rather than OPC. Which is
2296 * partially the reason why the implementation of these instructions
2297 * in darkplaces has been delayed for so long.
2299 * Breaking conventions is annoying...
2301 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2303 static bool gen_global_field(ir_value *global)
2305 if (global->isconst)
2307 ir_value *fld = global->constval.vpointer;
2309 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2313 /* Now, in this case, a relocation would be impossible to code
2314 * since it looks like this:
2315 * .vector v = origin; <- parse error, wtf is 'origin'?
2318 * But we will need a general relocation support later anyway
2319 * for functions... might as well support that here.
2321 if (!fld->code.globaladdr) {
2322 irerror(global->context, "FIXME: Relocation support");
2326 /* copy the field's value */
2327 ir_value_code_setaddr(global, vec_size(code_globals));
2328 vec_push(code_globals, code_globals[fld->code.globaladdr]);
2329 if (global->fieldtype == TYPE_VECTOR) {
2330 vec_push(code_globals, code_globals[fld->code.globaladdr]+1);
2331 vec_push(code_globals, code_globals[fld->code.globaladdr]+2);
2336 ir_value_code_setaddr(global, vec_size(code_globals));
2337 vec_push(code_globals, 0);
2338 if (global->fieldtype == TYPE_VECTOR) {
2339 vec_push(code_globals, 0);
2340 vec_push(code_globals, 0);
2343 if (global->code.globaladdr < 0)
2348 static bool gen_global_pointer(ir_value *global)
2350 if (global->isconst)
2352 ir_value *target = global->constval.vpointer;
2354 irerror(global->context, "Invalid pointer constant: %s", global->name);
2355 /* NULL pointers are pointing to the NULL constant, which also
2356 * sits at address 0, but still has an ir_value for itself.
2361 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2362 * void() foo; <- proto
2363 * void() *fooptr = &foo;
2364 * void() foo = { code }
2366 if (!target->code.globaladdr) {
2367 /* FIXME: Check for the constant nullptr ir_value!
2368 * because then code.globaladdr being 0 is valid.
2370 irerror(global->context, "FIXME: Relocation support");
2374 ir_value_code_setaddr(global, vec_size(code_globals));
2375 vec_push(code_globals, target->code.globaladdr);
2379 ir_value_code_setaddr(global, vec_size(code_globals));
2380 vec_push(code_globals, 0);
2382 if (global->code.globaladdr < 0)
2387 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2389 prog_section_statement stmt;
2398 block->generated = true;
2399 block->code_start = vec_size(code_statements);
2400 for (i = 0; i < vec_size(block->instr); ++i)
2402 instr = block->instr[i];
2404 if (instr->opcode == VINSTR_PHI) {
2405 irerror(block->context, "cannot generate virtual instruction (phi)");
2409 if (instr->opcode == VINSTR_JUMP) {
2410 target = instr->bops[0];
2411 /* for uncoditional jumps, if the target hasn't been generated
2412 * yet, we generate them right here.
2414 if (!target->generated) {
2419 /* otherwise we generate a jump instruction */
2420 stmt.opcode = INSTR_GOTO;
2421 stmt.o1.s1 = (target->code_start) - vec_size(code_statements);
2424 vec_push(code_statements, stmt);
2426 /* no further instructions can be in this block */
2430 if (instr->opcode == VINSTR_COND) {
2431 ontrue = instr->bops[0];
2432 onfalse = instr->bops[1];
2433 /* TODO: have the AST signal which block should
2434 * come first: eg. optimize IFs without ELSE...
2437 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2441 if (ontrue->generated) {
2442 stmt.opcode = INSTR_IF;
2443 stmt.o2.s1 = (ontrue->code_start) - vec_size(code_statements);
2444 vec_push(code_statements, stmt);
2446 if (onfalse->generated) {
2447 stmt.opcode = INSTR_IFNOT;
2448 stmt.o2.s1 = (onfalse->code_start) - vec_size(code_statements);
2449 vec_push(code_statements, stmt);
2451 if (!ontrue->generated) {
2452 if (onfalse->generated) {
2457 if (!onfalse->generated) {
2458 if (ontrue->generated) {
2463 /* neither ontrue nor onfalse exist */
2464 stmt.opcode = INSTR_IFNOT;
2465 stidx = vec_size(code_statements);
2466 vec_push(code_statements, stmt);
2467 /* on false we jump, so add ontrue-path */
2468 if (!gen_blocks_recursive(func, ontrue))
2470 /* fixup the jump address */
2471 code_statements[stidx].o2.s1 = vec_size(code_statements) - stidx;
2472 /* generate onfalse path */
2473 if (onfalse->generated) {
2474 /* fixup the jump address */
2475 code_statements[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2476 /* may have been generated in the previous recursive call */
2477 stmt.opcode = INSTR_GOTO;
2478 stmt.o1.s1 = (onfalse->code_start) - vec_size(code_statements);
2481 vec_push(code_statements, stmt);
2484 /* if not, generate now */
2489 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2490 /* Trivial call translation:
2491 * copy all params to OFS_PARM*
2492 * if the output's storetype is not store_return,
2493 * add append a STORE instruction!
2495 * NOTES on how to do it better without much trouble:
2496 * -) The liferanges!
2497 * Simply check the liferange of all parameters for
2498 * other CALLs. For each param with no CALL in its
2499 * liferange, we can store it in an OFS_PARM at
2500 * generation already. This would even include later
2501 * reuse.... probably... :)
2506 for (p = 0; p < vec_size(instr->params); ++p)
2508 ir_value *param = instr->params[p];
2510 stmt.opcode = INSTR_STORE_F;
2513 if (param->vtype == TYPE_FIELD)
2514 stmt.opcode = field_store_instr[param->fieldtype];
2516 stmt.opcode = type_store_instr[param->vtype];
2517 stmt.o1.u1 = ir_value_code_addr(param);
2518 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2519 vec_push(code_statements, stmt);
2521 stmt.opcode = INSTR_CALL0 + vec_size(instr->params);
2522 if (stmt.opcode > INSTR_CALL8)
2523 stmt.opcode = INSTR_CALL8;
2524 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2527 vec_push(code_statements, stmt);
2529 retvalue = instr->_ops[0];
2530 if (retvalue && retvalue->store != store_return && vec_size(retvalue->life))
2532 /* not to be kept in OFS_RETURN */
2533 if (retvalue->vtype == TYPE_FIELD)
2534 stmt.opcode = field_store_instr[retvalue->vtype];
2536 stmt.opcode = type_store_instr[retvalue->vtype];
2537 stmt.o1.u1 = OFS_RETURN;
2538 stmt.o2.u1 = ir_value_code_addr(retvalue);
2540 vec_push(code_statements, stmt);
2545 if (instr->opcode == INSTR_STATE) {
2546 irerror(block->context, "TODO: state instruction");
2550 stmt.opcode = instr->opcode;
2555 /* This is the general order of operands */
2557 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2560 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2563 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2565 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2567 stmt.o1.u1 = stmt.o3.u1;
2570 else if ((stmt.opcode >= INSTR_STORE_F &&
2571 stmt.opcode <= INSTR_STORE_FNC) ||
2572 (stmt.opcode >= INSTR_STOREP_F &&
2573 stmt.opcode <= INSTR_STOREP_FNC))
2575 /* 2-operand instructions with A -> B */
2576 stmt.o2.u1 = stmt.o3.u1;
2580 vec_push(code_statements, stmt);
2585 static bool gen_function_code(ir_function *self)
2588 prog_section_statement stmt;
2590 /* Starting from entry point, we generate blocks "as they come"
2591 * for now. Dead blocks will not be translated obviously.
2593 if (!vec_size(self->blocks)) {
2594 irerror(self->context, "Function '%s' declared without body.", self->name);
2598 block = self->blocks[0];
2599 if (block->generated)
2602 if (!gen_blocks_recursive(self, block)) {
2603 irerror(self->context, "failed to generate blocks for '%s'", self->name);
2607 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2608 stmt.opcode = AINSTR_END;
2612 vec_push(code_statements, stmt);
2616 static qcint ir_builder_filestring(ir_builder *ir, const char *filename)
2618 /* NOTE: filename pointers are copied, we never strdup them,
2619 * thus we can use pointer-comparison to find the string.
2624 for (i = 0; i < vec_size(ir->filenames); ++i) {
2625 if (ir->filenames[i] == filename)
2626 return ir->filestrings[i];
2629 str = code_genstring(filename);
2630 vec_push(ir->filenames, filename);
2631 vec_push(ir->filestrings, str);
2635 static bool gen_global_function(ir_builder *ir, ir_value *global)
2637 prog_section_function fun;
2641 size_t local_var_end;
2643 if (!global->isconst || (!global->constval.vfunc))
2645 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
2649 irfun = global->constval.vfunc;
2651 fun.name = global->code.name;
2652 fun.file = ir_builder_filestring(ir, global->context.file);
2653 fun.profile = 0; /* always 0 */
2654 fun.nargs = vec_size(irfun->params);
2656 for (i = 0;i < 8; ++i) {
2660 fun.argsize[i] = type_sizeof[irfun->params[i]];
2663 fun.firstlocal = vec_size(code_globals);
2665 local_var_end = fun.firstlocal;
2666 for (i = 0; i < vec_size(irfun->locals); ++i) {
2667 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
2668 irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
2672 if (vec_size(irfun->locals)) {
2673 ir_value *last = vec_last(irfun->locals);
2674 local_var_end = last->code.globaladdr;
2675 local_var_end += type_sizeof[last->vtype];
2677 for (i = 0; i < vec_size(irfun->values); ++i)
2679 /* generate code.globaladdr for ssa values */
2680 ir_value *v = irfun->values[i];
2681 ir_value_code_setaddr(v, local_var_end + v->code.local);
2683 for (i = 0; i < irfun->allocated_locals; ++i) {
2684 /* fill the locals with zeros */
2685 vec_push(code_globals, 0);
2688 fun.locals = vec_size(code_globals) - fun.firstlocal;
2691 fun.entry = irfun->builtin;
2693 irfun->code_function_def = vec_size(code_functions);
2694 fun.entry = vec_size(code_statements);
2697 vec_push(code_functions, fun);
2701 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
2703 prog_section_function *fundef;
2706 irfun = global->constval.vfunc;
2708 irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
2709 "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
2710 /* this was a function pointer, don't generate code for those */
2717 if (irfun->code_function_def < 0) {
2718 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
2721 fundef = &code_functions[irfun->code_function_def];
2723 fundef->entry = vec_size(code_statements);
2724 if (!gen_function_code(irfun)) {
2725 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
2731 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
2735 prog_section_def def;
2737 def.type = global->vtype;
2738 def.offset = vec_size(code_globals);
2741 if (global->name[0] == '#') {
2742 if (!self->str_immediate)
2743 self->str_immediate = code_genstring("IMMEDIATE");
2744 def.name = global->code.name = self->str_immediate;
2747 def.name = global->code.name = code_genstring(global->name);
2752 switch (global->vtype)
2755 if (!strcmp(global->name, "end_sys_globals")) {
2756 /* TODO: remember this point... all the defs before this one
2757 * should be checksummed and added to progdefs.h when we generate it.
2760 else if (!strcmp(global->name, "end_sys_fields")) {
2761 /* TODO: same as above but for entity-fields rather than globsl
2765 irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
2767 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
2768 * the system fields actually go? Though the engine knows this anyway...
2769 * Maybe this could be an -foption
2770 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
2772 ir_value_code_setaddr(global, vec_size(code_globals));
2773 vec_push(code_globals, 0);
2775 vec_push(code_defs, def);
2778 vec_push(code_defs, def);
2779 return gen_global_pointer(global);
2781 vec_push(code_defs, def);
2782 return gen_global_field(global);
2787 ir_value_code_setaddr(global, vec_size(code_globals));
2788 if (global->isconst) {
2789 iptr = (int32_t*)&global->constval.ivec[0];
2790 vec_push(code_globals, *iptr);
2792 vec_push(code_globals, 0);
2794 def.type |= DEF_SAVEGLOBAL;
2796 vec_push(code_defs, def);
2798 return global->code.globaladdr >= 0;
2802 ir_value_code_setaddr(global, vec_size(code_globals));
2803 if (global->isconst) {
2804 vec_push(code_globals, code_genstring(global->constval.vstring));
2806 vec_push(code_globals, 0);
2808 def.type |= DEF_SAVEGLOBAL;
2810 vec_push(code_defs, def);
2811 return global->code.globaladdr >= 0;
2816 ir_value_code_setaddr(global, vec_size(code_globals));
2817 if (global->isconst) {
2818 iptr = (int32_t*)&global->constval.ivec[0];
2819 vec_push(code_globals, iptr[0]);
2820 if (global->code.globaladdr < 0)
2822 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2824 vec_push(code_globals, iptr[d]);
2827 vec_push(code_globals, 0);
2828 if (global->code.globaladdr < 0)
2830 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2832 vec_push(code_globals, 0);
2835 def.type |= DEF_SAVEGLOBAL;
2838 vec_push(code_defs, def);
2839 return global->code.globaladdr >= 0;
2842 ir_value_code_setaddr(global, vec_size(code_globals));
2843 if (!global->isconst) {
2844 vec_push(code_globals, 0);
2845 if (global->code.globaladdr < 0)
2848 vec_push(code_globals, vec_size(code_functions));
2849 if (!gen_global_function(self, global))
2852 def.type |= DEF_SAVEGLOBAL;
2854 vec_push(code_defs, def);
2857 /* assume biggest type */
2858 ir_value_code_setaddr(global, vec_size(code_globals));
2859 vec_push(code_globals, 0);
2860 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2861 vec_push(code_globals, 0);
2864 /* refuse to create 'void' type or any other fancy business. */
2865 irerror(global->context, "Invalid type for global variable `%s`: %s",
2866 global->name, type_name[global->vtype]);
2871 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2873 prog_section_def def;
2874 prog_section_field fld;
2876 def.type = field->vtype;
2877 def.offset = vec_size(code_globals);
2879 /* create a global named the same as the field */
2880 if (opts_standard == COMPILER_GMQCC) {
2881 /* in our standard, the global gets a dot prefix */
2882 size_t len = strlen(field->name);
2885 /* we really don't want to have to allocate this, and 1024
2886 * bytes is more than enough for a variable/field name
2888 if (len+2 >= sizeof(name)) {
2889 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
2894 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
2897 def.name = code_genstring(name);
2898 fld.name = def.name + 1; /* we reuse that string table entry */
2900 /* in plain QC, there cannot be a global with the same name,
2901 * and so we also name the global the same.
2902 * FIXME: fteqcc should create a global as well
2903 * check if it actually uses the same name. Probably does
2905 def.name = code_genstring(field->name);
2906 fld.name = def.name;
2909 field->code.name = def.name;
2911 vec_push(code_defs, def);
2913 fld.type = field->fieldtype;
2915 if (fld.type == TYPE_VOID) {
2916 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
2920 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2922 vec_push(code_fields, fld);
2924 ir_value_code_setaddr(field, vec_size(code_globals));
2925 vec_push(code_globals, fld.offset);
2926 if (fld.type == TYPE_VECTOR) {
2927 vec_push(code_globals, fld.offset+1);
2928 vec_push(code_globals, fld.offset+2);
2931 return field->code.globaladdr >= 0;
2934 bool ir_builder_generate(ir_builder *self, const char *filename)
2936 prog_section_statement stmt;
2941 for (i = 0; i < vec_size(self->globals); ++i)
2943 if (!ir_builder_gen_global(self, self->globals[i], false)) {
2948 for (i = 0; i < vec_size(self->fields); ++i)
2950 if (!ir_builder_gen_field(self, self->fields[i])) {
2955 /* generate function code */
2956 for (i = 0; i < vec_size(self->globals); ++i)
2958 if (self->globals[i]->vtype == TYPE_FUNCTION) {
2959 if (!gen_global_function_code(self, self->globals[i])) {
2965 /* DP errors if the last instruction is not an INSTR_DONE
2966 * and for debugging purposes we add an additional AINSTR_END
2967 * to the end of functions, so here it goes:
2969 stmt.opcode = INSTR_DONE;
2973 vec_push(code_statements, stmt);
2975 printf("writing '%s'...\n", filename);
2976 return code_write(filename);
2979 /***********************************************************************
2980 *IR DEBUG Dump functions...
2983 #define IND_BUFSZ 1024
2986 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
2989 const char *qc_opname(int op)
2991 if (op < 0) return "<INVALID>";
2992 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2993 return asm_instr[op].m;
2995 case VINSTR_PHI: return "PHI";
2996 case VINSTR_JUMP: return "JUMP";
2997 case VINSTR_COND: return "COND";
2998 default: return "<UNK>";
3002 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
3005 char indent[IND_BUFSZ];
3009 oprintf("module %s\n", b->name);
3010 for (i = 0; i < vec_size(b->globals); ++i)
3013 if (b->globals[i]->isconst)
3014 oprintf("%s = ", b->globals[i]->name);
3015 ir_value_dump(b->globals[i], oprintf);
3018 for (i = 0; i < vec_size(b->functions); ++i)
3019 ir_function_dump(b->functions[i], indent, oprintf);
3020 oprintf("endmodule %s\n", b->name);
3023 void ir_function_dump(ir_function *f, char *ind,
3024 int (*oprintf)(const char*, ...))
3027 if (f->builtin != 0) {
3028 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
3031 oprintf("%sfunction %s\n", ind, f->name);
3032 strncat(ind, "\t", IND_BUFSZ);
3033 if (vec_size(f->locals))
3035 oprintf("%s%i locals:\n", ind, (int)vec_size(f->locals));
3036 for (i = 0; i < vec_size(f->locals); ++i) {
3037 oprintf("%s\t", ind);
3038 ir_value_dump(f->locals[i], oprintf);
3042 oprintf("%sliferanges:\n", ind);
3043 for (i = 0; i < vec_size(f->locals); ++i) {
3045 ir_value *v = f->locals[i];
3046 oprintf("%s\t%s: unique ", ind, v->name);
3047 for (l = 0; l < vec_size(v->life); ++l) {
3048 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3052 for (i = 0; i < vec_size(f->values); ++i) {
3054 ir_value *v = f->values[i];
3055 oprintf("%s\t%s: @%i ", ind, v->name, (int)v->code.local);
3056 for (l = 0; l < vec_size(v->life); ++l) {
3057 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3061 if (vec_size(f->blocks))
3063 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
3064 for (i = 0; i < vec_size(f->blocks); ++i) {
3065 if (f->blocks[i]->run_id != f->run_id) {
3066 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
3068 ir_block_dump(f->blocks[i], ind, oprintf);
3072 ind[strlen(ind)-1] = 0;
3073 oprintf("%sendfunction %s\n", ind, f->name);
3076 void ir_block_dump(ir_block* b, char *ind,
3077 int (*oprintf)(const char*, ...))
3080 oprintf("%s:%s\n", ind, b->label);
3081 strncat(ind, "\t", IND_BUFSZ);
3083 for (i = 0; i < vec_size(b->instr); ++i)
3084 ir_instr_dump(b->instr[i], ind, oprintf);
3085 ind[strlen(ind)-1] = 0;
3088 void dump_phi(ir_instr *in, char *ind,
3089 int (*oprintf)(const char*, ...))
3092 oprintf("%s <- phi ", in->_ops[0]->name);
3093 for (i = 0; i < vec_size(in->phi); ++i)
3095 oprintf("([%s] : %s) ", in->phi[i].from->label,
3096 in->phi[i].value->name);
3101 void ir_instr_dump(ir_instr *in, char *ind,
3102 int (*oprintf)(const char*, ...))
3105 const char *comma = NULL;
3107 oprintf("%s (%i) ", ind, (int)in->eid);
3109 if (in->opcode == VINSTR_PHI) {
3110 dump_phi(in, ind, oprintf);
3114 strncat(ind, "\t", IND_BUFSZ);
3116 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3117 ir_value_dump(in->_ops[0], oprintf);
3118 if (in->_ops[1] || in->_ops[2])
3121 if (in->opcode == INSTR_CALL0) {
3122 oprintf("CALL%i\t", vec_size(in->params));
3124 oprintf("%s\t", qc_opname(in->opcode));
3126 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3127 ir_value_dump(in->_ops[0], oprintf);
3132 for (i = 1; i != 3; ++i) {
3136 ir_value_dump(in->_ops[i], oprintf);
3144 oprintf("[%s]", in->bops[0]->label);
3148 oprintf("%s[%s]", comma, in->bops[1]->label);
3149 if (vec_size(in->params)) {
3150 oprintf("\tparams: ");
3151 for (i = 0; i != vec_size(in->params); ++i) {
3152 oprintf("%s, ", in->params[i]->name);
3156 ind[strlen(ind)-1] = 0;
3159 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3168 oprintf("fn:%s", v->name);
3171 oprintf("%g", v->constval.vfloat);
3174 oprintf("'%g %g %g'",
3177 v->constval.vvec.z);
3180 oprintf("(entity)");
3183 oprintf("\"%s\"", v->constval.vstring);
3187 oprintf("%i", v->constval.vint);
3192 v->constval.vpointer->name);
3196 oprintf("%s", v->name);
3200 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
3203 oprintf("Life of %12s:", self->name);
3204 for (i = 0; i < vec_size(self->life); ++i)
3206 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);