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 (warntype && !OPTS_WARN(warntype))
148 vprintmsg(lvl, ctx.file, ctx.line, "warning", fmt, ap);
154 /***********************************************************************
158 static void ir_block_delete_quick(ir_block* self);
159 static void ir_instr_delete_quick(ir_instr *self);
160 static void ir_function_delete_quick(ir_function *self);
162 ir_builder* ir_builder_new(const char *modulename)
166 self = (ir_builder*)mem_a(sizeof(*self));
170 MEM_VECTOR_INIT(self, functions);
171 MEM_VECTOR_INIT(self, globals);
172 MEM_VECTOR_INIT(self, fields);
173 MEM_VECTOR_INIT(self, filenames);
174 MEM_VECTOR_INIT(self, filestrings);
175 self->str_immediate = 0;
177 if (!ir_builder_set_name(self, modulename)) {
185 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
186 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, fields)
187 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
188 MEM_VEC_FUNCTIONS(ir_builder, const char*, filenames)
189 MEM_VEC_FUNCTIONS(ir_builder, qcint, filestrings)
191 void ir_builder_delete(ir_builder* self)
194 mem_d((void*)self->name);
195 for (i = 0; i != self->functions_count; ++i) {
196 ir_function_delete_quick(self->functions[i]);
198 MEM_VECTOR_CLEAR(self, functions);
199 for (i = 0; i != self->globals_count; ++i) {
200 ir_value_delete(self->globals[i]);
202 MEM_VECTOR_CLEAR(self, globals);
203 for (i = 0; i != self->fields_count; ++i) {
204 ir_value_delete(self->fields[i]);
206 MEM_VECTOR_CLEAR(self, fields);
207 MEM_VECTOR_CLEAR(self, filenames);
208 MEM_VECTOR_CLEAR(self, filestrings);
212 bool ir_builder_set_name(ir_builder *self, const char *name)
215 mem_d((void*)self->name);
216 self->name = util_strdup(name);
220 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
223 for (i = 0; i < self->functions_count; ++i) {
224 if (!strcmp(name, self->functions[i]->name))
225 return self->functions[i];
230 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
232 ir_function *fn = ir_builder_get_function(self, name);
237 fn = ir_function_new(self, outtype);
238 if (!ir_function_set_name(fn, name) ||
239 !ir_builder_functions_add(self, fn) )
241 ir_function_delete(fn);
245 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
247 ir_function_delete(fn);
251 fn->value->isconst = true;
252 fn->value->outtype = outtype;
253 fn->value->constval.vfunc = fn;
254 fn->value->context = fn->context;
259 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
262 for (i = 0; i < self->globals_count; ++i) {
263 if (!strcmp(self->globals[i]->name, name))
264 return self->globals[i];
269 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
273 if (name && name[0] != '#')
275 ve = ir_builder_get_global(self, name);
281 ve = ir_value_var(name, store_global, vtype);
282 if (!ir_builder_globals_add(self, ve)) {
289 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
292 for (i = 0; i < self->fields_count; ++i) {
293 if (!strcmp(self->fields[i]->name, name))
294 return self->fields[i];
300 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
302 ir_value *ve = ir_builder_get_field(self, name);
307 ve = ir_value_var(name, store_global, TYPE_FIELD);
308 ve->fieldtype = vtype;
309 if (!ir_builder_fields_add(self, ve)) {
316 /***********************************************************************
320 bool ir_function_naive_phi(ir_function*);
321 void ir_function_enumerate(ir_function*);
322 bool ir_function_calculate_liferanges(ir_function*);
323 bool ir_function_allocate_locals(ir_function*);
325 ir_function* ir_function_new(ir_builder* owner, int outtype)
328 self = (ir_function*)mem_a(sizeof(*self));
333 memset(self, 0, sizeof(*self));
336 if (!ir_function_set_name(self, "<@unnamed>")) {
341 self->context.file = "<@no context>";
342 self->context.line = 0;
343 self->outtype = outtype;
346 MEM_VECTOR_INIT(self, params);
347 MEM_VECTOR_INIT(self, blocks);
348 MEM_VECTOR_INIT(self, values);
349 MEM_VECTOR_INIT(self, locals);
351 self->code_function_def = -1;
352 self->allocated_locals = 0;
357 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
358 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
359 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
360 MEM_VEC_FUNCTIONS(ir_function, int, params)
362 bool ir_function_set_name(ir_function *self, const char *name)
365 mem_d((void*)self->name);
366 self->name = util_strdup(name);
370 static void ir_function_delete_quick(ir_function *self)
373 mem_d((void*)self->name);
375 for (i = 0; i != self->blocks_count; ++i)
376 ir_block_delete_quick(self->blocks[i]);
377 MEM_VECTOR_CLEAR(self, blocks);
379 MEM_VECTOR_CLEAR(self, params);
381 for (i = 0; i != self->values_count; ++i)
382 ir_value_delete(self->values[i]);
383 MEM_VECTOR_CLEAR(self, values);
385 for (i = 0; i != self->locals_count; ++i)
386 ir_value_delete(self->locals[i]);
387 MEM_VECTOR_CLEAR(self, locals);
389 /* self->value is deleted by the builder */
394 void ir_function_delete(ir_function *self)
397 mem_d((void*)self->name);
399 for (i = 0; i != self->blocks_count; ++i)
400 ir_block_delete(self->blocks[i]);
401 MEM_VECTOR_CLEAR(self, blocks);
403 MEM_VECTOR_CLEAR(self, params);
405 for (i = 0; i != self->values_count; ++i)
406 ir_value_delete(self->values[i]);
407 MEM_VECTOR_CLEAR(self, values);
409 for (i = 0; i != self->locals_count; ++i)
410 ir_value_delete(self->locals[i]);
411 MEM_VECTOR_CLEAR(self, locals);
413 /* self->value is deleted by the builder */
418 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
420 return ir_function_values_add(self, v);
423 ir_block* ir_function_create_block(ir_function *self, const char *label)
425 ir_block* bn = ir_block_new(self, label);
426 memcpy(&bn->context, &self->context, sizeof(self->context));
427 if (!ir_function_blocks_add(self, bn)) {
434 bool ir_function_finalize(ir_function *self)
439 if (!ir_function_naive_phi(self))
442 ir_function_enumerate(self);
444 if (!ir_function_calculate_liferanges(self))
447 if (!ir_function_allocate_locals(self))
452 ir_value* ir_function_get_local(ir_function *self, const char *name)
455 for (i = 0; i < self->locals_count; ++i) {
456 if (!strcmp(self->locals[i]->name, name))
457 return self->locals[i];
462 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
467 if (ir_function_get_local(self, name))
472 self->locals_count &&
473 self->locals[self->locals_count-1]->store != store_param) {
474 irerror(self->context, "cannot add parameters after adding locals");
478 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
479 if (!ir_function_locals_add(self, ve)) {
486 /***********************************************************************
490 ir_block* ir_block_new(ir_function* owner, const char *name)
493 self = (ir_block*)mem_a(sizeof(*self));
497 memset(self, 0, sizeof(*self));
500 if (name && !ir_block_set_label(self, name)) {
505 self->context.file = "<@no context>";
506 self->context.line = 0;
508 MEM_VECTOR_INIT(self, instr);
509 MEM_VECTOR_INIT(self, entries);
510 MEM_VECTOR_INIT(self, exits);
513 self->is_return = false;
515 MEM_VECTOR_INIT(self, living);
517 self->generated = false;
521 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
522 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
523 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
524 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
526 static void ir_block_delete_quick(ir_block* self)
529 if (self->label) mem_d(self->label);
530 for (i = 0; i != self->instr_count; ++i)
531 ir_instr_delete_quick(self->instr[i]);
532 MEM_VECTOR_CLEAR(self, instr);
533 MEM_VECTOR_CLEAR(self, entries);
534 MEM_VECTOR_CLEAR(self, exits);
535 MEM_VECTOR_CLEAR(self, living);
539 void ir_block_delete(ir_block* self)
542 if (self->label) mem_d(self->label);
543 for (i = 0; i != self->instr_count; ++i)
544 ir_instr_delete(self->instr[i]);
545 MEM_VECTOR_CLEAR(self, instr);
546 MEM_VECTOR_CLEAR(self, entries);
547 MEM_VECTOR_CLEAR(self, exits);
548 MEM_VECTOR_CLEAR(self, living);
552 bool ir_block_set_label(ir_block *self, const char *name)
555 mem_d((void*)self->label);
556 self->label = util_strdup(name);
557 return !!self->label;
560 /***********************************************************************
564 ir_instr* ir_instr_new(ir_block* owner, int op)
567 self = (ir_instr*)mem_a(sizeof(*self));
572 self->context.file = "<@no context>";
573 self->context.line = 0;
575 self->_ops[0] = NULL;
576 self->_ops[1] = NULL;
577 self->_ops[2] = NULL;
578 self->bops[0] = NULL;
579 self->bops[1] = NULL;
580 MEM_VECTOR_INIT(self, phi);
581 MEM_VECTOR_INIT(self, params);
586 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
587 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
589 static void ir_instr_delete_quick(ir_instr *self)
591 MEM_VECTOR_CLEAR(self, phi);
592 MEM_VECTOR_CLEAR(self, params);
596 void ir_instr_delete(ir_instr *self)
599 /* The following calls can only delete from
600 * vectors, we still want to delete this instruction
601 * so ignore the return value. Since with the warn_unused_result attribute
602 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
603 * I have to improvise here and use if(foo());
605 for (i = 0; i < self->phi_count; ++i) {
607 if (ir_value_writes_find(self->phi[i].value, self, &idx))
608 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
609 if (ir_value_reads_find(self->phi[i].value, self, &idx))
610 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
612 MEM_VECTOR_CLEAR(self, phi);
613 for (i = 0; i < self->params_count; ++i) {
615 if (ir_value_writes_find(self->params[i], self, &idx))
616 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
617 if (ir_value_reads_find(self->params[i], self, &idx))
618 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
620 MEM_VECTOR_CLEAR(self, params);
621 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
622 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
623 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
627 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
629 if (self->_ops[op]) {
631 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
633 if (!ir_value_writes_remove(self->_ops[op], idx))
636 else if (ir_value_reads_find(self->_ops[op], self, &idx))
638 if (!ir_value_reads_remove(self->_ops[op], idx))
644 if (!ir_value_writes_add(v, self))
647 if (!ir_value_reads_add(v, self))
655 /***********************************************************************
659 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
661 self->code.globaladdr = gaddr;
662 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
663 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
664 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
667 int32_t ir_value_code_addr(const ir_value *self)
669 if (self->store == store_return)
670 return OFS_RETURN + self->code.addroffset;
671 return self->code.globaladdr + self->code.addroffset;
674 ir_value* ir_value_var(const char *name, int storetype, int vtype)
677 self = (ir_value*)mem_a(sizeof(*self));
679 self->fieldtype = TYPE_VOID;
680 self->outtype = TYPE_VOID;
681 self->store = storetype;
682 MEM_VECTOR_INIT(self, reads);
683 MEM_VECTOR_INIT(self, writes);
684 self->isconst = false;
685 self->context.file = "<@no context>";
686 self->context.line = 0;
688 if (name && !ir_value_set_name(self, name)) {
689 irerror(self->context, "out of memory");
694 memset(&self->constval, 0, sizeof(self->constval));
695 memset(&self->code, 0, sizeof(self->code));
697 self->members[0] = NULL;
698 self->members[1] = NULL;
699 self->members[2] = NULL;
700 self->memberof = NULL;
702 MEM_VECTOR_INIT(self, life);
706 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
712 if (self->members[member])
713 return self->members[member];
715 if (self->vtype == TYPE_VECTOR)
717 m = ir_value_var(self->name, self->store, TYPE_FLOAT);
720 m->context = self->context;
722 self->members[member] = m;
723 m->code.addroffset = member;
725 else if (self->vtype == TYPE_FIELD)
727 if (self->fieldtype != TYPE_VECTOR)
729 m = ir_value_var(self->name, self->store, TYPE_FIELD);
732 m->fieldtype = TYPE_FLOAT;
733 m->context = self->context;
735 self->members[member] = m;
736 m->code.addroffset = member;
740 irerror(self->context, "invalid member access on %s", self->name);
748 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
749 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
750 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
752 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
754 ir_value *v = ir_value_var(name, storetype, vtype);
757 if (!ir_function_collect_value(owner, v))
765 void ir_value_delete(ir_value* self)
769 mem_d((void*)self->name);
772 if (self->vtype == TYPE_STRING)
773 mem_d((void*)self->constval.vstring);
775 for (i = 0; i < 3; ++i) {
776 if (self->members[i])
777 ir_value_delete(self->members[i]);
779 MEM_VECTOR_CLEAR(self, reads);
780 MEM_VECTOR_CLEAR(self, writes);
781 MEM_VECTOR_CLEAR(self, life);
785 bool ir_value_set_name(ir_value *self, const char *name)
788 mem_d((void*)self->name);
789 self->name = util_strdup(name);
793 bool ir_value_set_float(ir_value *self, float f)
795 if (self->vtype != TYPE_FLOAT)
797 self->constval.vfloat = f;
798 self->isconst = true;
802 bool ir_value_set_func(ir_value *self, int f)
804 if (self->vtype != TYPE_FUNCTION)
806 self->constval.vint = f;
807 self->isconst = true;
811 bool ir_value_set_vector(ir_value *self, vector v)
813 if (self->vtype != TYPE_VECTOR)
815 self->constval.vvec = v;
816 self->isconst = true;
820 bool ir_value_set_field(ir_value *self, ir_value *fld)
822 if (self->vtype != TYPE_FIELD)
824 self->constval.vpointer = fld;
825 self->isconst = true;
829 static char *ir_strdup(const char *str)
832 /* actually dup empty strings */
833 char *out = mem_a(1);
837 return util_strdup(str);
840 bool ir_value_set_string(ir_value *self, const char *str)
842 if (self->vtype != TYPE_STRING)
844 self->constval.vstring = ir_strdup(str);
845 self->isconst = true;
850 bool ir_value_set_int(ir_value *self, int i)
852 if (self->vtype != TYPE_INTEGER)
854 self->constval.vint = i;
855 self->isconst = true;
860 bool ir_value_lives(ir_value *self, size_t at)
863 for (i = 0; i < self->life_count; ++i)
865 ir_life_entry_t *life = &self->life[i];
866 if (life->start <= at && at <= life->end)
868 if (life->start > at) /* since it's ordered */
874 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
877 if (!ir_value_life_add(self, e)) /* naive... */
879 for (k = self->life_count-1; k > idx; --k)
880 self->life[k] = self->life[k-1];
885 bool ir_value_life_merge(ir_value *self, size_t s)
888 ir_life_entry_t *life = NULL;
889 ir_life_entry_t *before = NULL;
890 ir_life_entry_t new_entry;
892 /* Find the first range >= s */
893 for (i = 0; i < self->life_count; ++i)
896 life = &self->life[i];
900 /* nothing found? append */
901 if (i == self->life_count) {
903 if (life && life->end+1 == s)
905 /* previous life range can be merged in */
909 if (life && life->end >= s)
912 if (!ir_value_life_add(self, e))
913 return false; /* failing */
919 if (before->end + 1 == s &&
920 life->start - 1 == s)
923 before->end = life->end;
924 if (!ir_value_life_remove(self, i))
925 return false; /* failing */
928 if (before->end + 1 == s)
934 /* already contained */
935 if (before->end >= s)
939 if (life->start - 1 == s)
944 /* insert a new entry */
945 new_entry.start = new_entry.end = s;
946 return ir_value_life_insert(self, i, new_entry);
949 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
953 if (!other->life_count)
956 if (!self->life_count) {
957 for (i = 0; i < other->life_count; ++i) {
958 if (!ir_value_life_add(self, other->life[i]))
965 for (i = 0; i < other->life_count; ++i)
967 const ir_life_entry_t *life = &other->life[i];
970 ir_life_entry_t *entry = &self->life[myi];
972 if (life->end+1 < entry->start)
974 /* adding an interval before entry */
975 if (!ir_value_life_insert(self, myi, *life))
981 if (life->start < entry->start &&
982 life->end+1 >= entry->start)
984 /* starts earlier and overlaps */
985 entry->start = life->start;
988 if (life->end > entry->end &&
989 life->start <= entry->end+1)
991 /* ends later and overlaps */
992 entry->end = life->end;
995 /* see if our change combines it with the next ranges */
996 while (myi+1 < self->life_count &&
997 entry->end+1 >= self->life[1+myi].start)
999 /* overlaps with (myi+1) */
1000 if (entry->end < self->life[1+myi].end)
1001 entry->end = self->life[1+myi].end;
1002 if (!ir_value_life_remove(self, myi+1))
1004 entry = &self->life[myi];
1007 /* see if we're after the entry */
1008 if (life->start > entry->end)
1011 /* append if we're at the end */
1012 if (myi >= self->life_count) {
1013 if (!ir_value_life_add(self, *life))
1017 /* otherweise check the next range */
1026 bool ir_values_overlap(const ir_value *a, const ir_value *b)
1028 /* For any life entry in A see if it overlaps with
1029 * any life entry in B.
1030 * Note that the life entries are orderes, so we can make a
1031 * more efficient algorithm there than naively translating the
1035 ir_life_entry_t *la, *lb, *enda, *endb;
1037 /* first of all, if either has no life range, they cannot clash */
1038 if (!a->life_count || !b->life_count)
1043 enda = la + a->life_count;
1044 endb = lb + b->life_count;
1047 /* check if the entries overlap, for that,
1048 * both must start before the other one ends.
1050 if (la->start < lb->end &&
1051 lb->start < la->end)
1056 /* entries are ordered
1057 * one entry is earlier than the other
1058 * that earlier entry will be moved forward
1060 if (la->start < lb->start)
1062 /* order: A B, move A forward
1063 * check if we hit the end with A
1068 else /* if (lb->start < la->start) actually <= */
1070 /* order: B A, move B forward
1071 * check if we hit the end with B
1080 /***********************************************************************
1084 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
1086 ir_instr *in = ir_instr_new(self, op);
1090 if (target->store == store_value &&
1091 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1093 irerror(self->context, "cannot store to an SSA value");
1094 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1095 irerror(self->context, "instruction: %s", asm_instr[op].m);
1099 if (!ir_instr_op(in, 0, target, true) ||
1100 !ir_instr_op(in, 1, what, false) ||
1101 !ir_block_instr_add(self, in) )
1108 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
1112 if (target->vtype == TYPE_VARIANT)
1113 vtype = what->vtype;
1115 vtype = target->vtype;
1118 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1119 op = INSTR_CONV_ITOF;
1120 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1121 op = INSTR_CONV_FTOI;
1123 op = type_store_instr[vtype];
1125 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1126 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1130 return ir_block_create_store_op(self, op, target, what);
1133 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
1138 if (target->vtype != TYPE_POINTER)
1141 /* storing using pointer - target is a pointer, type must be
1142 * inferred from source
1144 vtype = what->vtype;
1146 op = type_storep_instr[vtype];
1147 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1148 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1149 op = INSTR_STOREP_V;
1152 return ir_block_create_store_op(self, op, target, what);
1155 bool ir_block_create_return(ir_block *self, ir_value *v)
1159 irerror(self->context, "block already ended (%s)", self->label);
1163 self->is_return = true;
1164 in = ir_instr_new(self, INSTR_RETURN);
1168 if (v && !ir_instr_op(in, 0, v, false))
1171 if (!ir_block_instr_add(self, in))
1176 bool ir_block_create_if(ir_block *self, ir_value *v,
1177 ir_block *ontrue, ir_block *onfalse)
1181 irerror(self->context, "block already ended (%s)", self->label);
1185 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1186 in = ir_instr_new(self, VINSTR_COND);
1190 if (!ir_instr_op(in, 0, v, false)) {
1191 ir_instr_delete(in);
1195 in->bops[0] = ontrue;
1196 in->bops[1] = onfalse;
1198 if (!ir_block_instr_add(self, in))
1201 if (!ir_block_exits_add(self, ontrue) ||
1202 !ir_block_exits_add(self, onfalse) ||
1203 !ir_block_entries_add(ontrue, self) ||
1204 !ir_block_entries_add(onfalse, self) )
1211 bool ir_block_create_jump(ir_block *self, ir_block *to)
1215 irerror(self->context, "block already ended (%s)", self->label);
1219 in = ir_instr_new(self, VINSTR_JUMP);
1224 if (!ir_block_instr_add(self, in))
1227 if (!ir_block_exits_add(self, to) ||
1228 !ir_block_entries_add(to, self) )
1235 bool ir_block_create_goto(ir_block *self, ir_block *to)
1239 irerror(self->context, "block already ended (%s)", self->label);
1243 in = ir_instr_new(self, INSTR_GOTO);
1248 if (!ir_block_instr_add(self, in))
1251 if (!ir_block_exits_add(self, to) ||
1252 !ir_block_entries_add(to, self) )
1259 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1263 in = ir_instr_new(self, VINSTR_PHI);
1266 out = ir_value_out(self->owner, label, store_value, ot);
1268 ir_instr_delete(in);
1271 if (!ir_instr_op(in, 0, out, true)) {
1272 ir_instr_delete(in);
1273 ir_value_delete(out);
1276 if (!ir_block_instr_add(self, in)) {
1277 ir_instr_delete(in);
1278 ir_value_delete(out);
1284 ir_value* ir_phi_value(ir_instr *self)
1286 return self->_ops[0];
1289 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1293 if (!ir_block_entries_find(self->owner, b, NULL)) {
1294 /* Must not be possible to cause this, otherwise the AST
1295 * is doing something wrong.
1297 irerror(self->context, "Invalid entry block for PHI");
1303 if (!ir_value_reads_add(v, self))
1305 return ir_instr_phi_add(self, pe);
1308 /* call related code */
1309 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1313 in = ir_instr_new(self, INSTR_CALL0);
1316 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1318 ir_instr_delete(in);
1321 if (!ir_instr_op(in, 0, out, true) ||
1322 !ir_instr_op(in, 1, func, false) ||
1323 !ir_block_instr_add(self, in))
1325 ir_instr_delete(in);
1326 ir_value_delete(out);
1332 ir_value* ir_call_value(ir_instr *self)
1334 return self->_ops[0];
1337 bool ir_call_param(ir_instr* self, ir_value *v)
1339 if (!ir_instr_params_add(self, v))
1341 if (!ir_value_reads_add(v, self)) {
1342 if (!ir_instr_params_remove(self, self->params_count-1))
1343 GMQCC_SUPPRESS_EMPTY_BODY;
1349 /* binary op related code */
1351 ir_value* ir_block_create_binop(ir_block *self,
1352 const char *label, int opcode,
1353 ir_value *left, ir_value *right)
1375 case INSTR_SUB_S: /* -- offset of string as float */
1380 case INSTR_BITOR_IF:
1381 case INSTR_BITOR_FI:
1382 case INSTR_BITAND_FI:
1383 case INSTR_BITAND_IF:
1398 case INSTR_BITAND_I:
1401 case INSTR_RSHIFT_I:
1402 case INSTR_LSHIFT_I:
1424 /* boolean operations result in floats */
1425 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1427 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1430 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1435 if (ot == TYPE_VOID) {
1436 /* The AST or parser were supposed to check this! */
1440 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1443 ir_value* ir_block_create_unary(ir_block *self,
1444 const char *label, int opcode,
1447 int ot = TYPE_FLOAT;
1459 /* QC doesn't have other unary operations. We expect extensions to fill
1460 * the above list, otherwise we assume out-type = in-type, eg for an
1464 ot = operand->vtype;
1467 if (ot == TYPE_VOID) {
1468 /* The AST or parser were supposed to check this! */
1472 /* let's use the general instruction creator and pass NULL for OPB */
1473 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1476 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1477 int op, ir_value *a, ir_value *b, int outype)
1482 out = ir_value_out(self->owner, label, store_value, outype);
1486 instr = ir_instr_new(self, op);
1488 ir_value_delete(out);
1492 if (!ir_instr_op(instr, 0, out, true) ||
1493 !ir_instr_op(instr, 1, a, false) ||
1494 !ir_instr_op(instr, 2, b, false) )
1499 if (!ir_block_instr_add(self, instr))
1504 ir_instr_delete(instr);
1505 ir_value_delete(out);
1509 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1513 /* Support for various pointer types todo if so desired */
1514 if (ent->vtype != TYPE_ENTITY)
1517 if (field->vtype != TYPE_FIELD)
1520 v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1521 v->fieldtype = field->fieldtype;
1525 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1528 if (ent->vtype != TYPE_ENTITY)
1531 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1532 if (field->vtype != TYPE_FIELD)
1537 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1538 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1539 case TYPE_STRING: op = INSTR_LOAD_S; break;
1540 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1541 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1542 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1544 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1545 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1551 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1554 ir_value* ir_block_create_add(ir_block *self,
1556 ir_value *left, ir_value *right)
1559 int l = left->vtype;
1560 int r = right->vtype;
1579 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1581 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1587 return ir_block_create_binop(self, label, op, left, right);
1590 ir_value* ir_block_create_sub(ir_block *self,
1592 ir_value *left, ir_value *right)
1595 int l = left->vtype;
1596 int r = right->vtype;
1616 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1618 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1624 return ir_block_create_binop(self, label, op, left, right);
1627 ir_value* ir_block_create_mul(ir_block *self,
1629 ir_value *left, ir_value *right)
1632 int l = left->vtype;
1633 int r = right->vtype;
1652 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1654 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1657 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1659 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1661 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1663 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1669 return ir_block_create_binop(self, label, op, left, right);
1672 ir_value* ir_block_create_div(ir_block *self,
1674 ir_value *left, ir_value *right)
1677 int l = left->vtype;
1678 int r = right->vtype;
1695 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1697 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1699 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1705 return ir_block_create_binop(self, label, op, left, right);
1708 /* PHI resolving breaks the SSA, and must thus be the last
1709 * step before life-range calculation.
1712 static bool ir_block_naive_phi(ir_block *self);
1713 bool ir_function_naive_phi(ir_function *self)
1717 for (i = 0; i < self->blocks_count; ++i)
1719 if (!ir_block_naive_phi(self->blocks[i]))
1725 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1730 /* create a store */
1731 if (!ir_block_create_store(block, old, what))
1734 /* we now move it up */
1735 instr = block->instr[block->instr_count-1];
1736 for (i = block->instr_count; i > iid; --i)
1737 block->instr[i] = block->instr[i-1];
1738 block->instr[i] = instr;
1743 static bool ir_block_naive_phi(ir_block *self)
1746 /* FIXME: optionally, create_phi can add the phis
1747 * to a list so we don't need to loop through blocks
1748 * - anyway: "don't optimize YET"
1750 for (i = 0; i < self->instr_count; ++i)
1752 ir_instr *instr = self->instr[i];
1753 if (instr->opcode != VINSTR_PHI)
1756 if (!ir_block_instr_remove(self, i))
1758 --i; /* NOTE: i+1 below */
1760 for (p = 0; p < instr->phi_count; ++p)
1762 ir_value *v = instr->phi[p].value;
1763 for (w = 0; w < v->writes_count; ++w) {
1766 if (!v->writes[w]->_ops[0])
1769 /* When the write was to a global, we have to emit a mov */
1770 old = v->writes[w]->_ops[0];
1772 /* The original instruction now writes to the PHI target local */
1773 if (v->writes[w]->_ops[0] == v)
1774 v->writes[w]->_ops[0] = instr->_ops[0];
1776 if (old->store != store_value && old->store != store_local && old->store != store_param)
1778 /* If it originally wrote to a global we need to store the value
1781 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1783 if (i+1 < self->instr_count)
1784 instr = self->instr[i+1];
1787 /* In case I forget and access instr later, it'll be NULL
1788 * when it's a problem, to make sure we crash, rather than accessing
1794 /* If it didn't, we can replace all reads by the phi target now. */
1796 for (r = 0; r < old->reads_count; ++r)
1799 ir_instr *ri = old->reads[r];
1800 for (op = 0; op < ri->phi_count; ++op) {
1801 if (ri->phi[op].value == old)
1802 ri->phi[op].value = v;
1804 for (op = 0; op < 3; ++op) {
1805 if (ri->_ops[op] == old)
1812 ir_instr_delete(instr);
1817 /***********************************************************************
1818 *IR Temp allocation code
1819 * Propagating value life ranges by walking through the function backwards
1820 * until no more changes are made.
1821 * In theory this should happen once more than once for every nested loop
1823 * Though this implementation might run an additional time for if nests.
1832 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1834 /* Enumerate instructions used by value's life-ranges
1836 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1840 for (i = 0; i < self->instr_count; ++i)
1842 self->instr[i]->eid = eid++;
1847 /* Enumerate blocks and instructions.
1848 * The block-enumeration is unordered!
1849 * We do not really use the block enumreation, however
1850 * the instruction enumeration is important for life-ranges.
1852 void ir_function_enumerate(ir_function *self)
1855 size_t instruction_id = 0;
1856 for (i = 0; i < self->blocks_count; ++i)
1858 self->blocks[i]->eid = i;
1859 self->blocks[i]->run_id = 0;
1860 ir_block_enumerate(self->blocks[i], &instruction_id);
1864 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1865 bool ir_function_calculate_liferanges(ir_function *self)
1873 for (i = 0; i != self->blocks_count; ++i)
1875 if (self->blocks[i]->is_return)
1877 self->blocks[i]->living_count = 0;
1878 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1883 if (self->blocks_count) {
1884 ir_block *block = self->blocks[0];
1885 for (i = 0; i < block->living_count; ++i) {
1886 ir_value *v = block->living[i];
1887 if (v->memberof || v->store != store_local)
1889 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
1890 "variable `%s` may be used uninitialized in this function", v->name))
1899 /* Local-value allocator
1900 * After finishing creating the liferange of all values used in a function
1901 * we can allocate their global-positions.
1902 * This is the counterpart to register-allocation in register machines.
1905 MEM_VECTOR_MAKE(ir_value*, locals);
1906 MEM_VECTOR_MAKE(size_t, sizes);
1907 MEM_VECTOR_MAKE(size_t, positions);
1908 } function_allocator;
1909 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1910 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1911 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1913 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1916 size_t vsize = type_sizeof[var->vtype];
1918 slot = ir_value_var("reg", store_global, var->vtype);
1922 if (!ir_value_life_merge_into(slot, var))
1925 if (!function_allocator_locals_add(alloc, slot))
1928 if (!function_allocator_sizes_add(alloc, vsize))
1934 ir_value_delete(slot);
1938 bool ir_function_allocate_locals(ir_function *self)
1947 function_allocator alloc;
1949 if (!self->locals_count && !self->values_count)
1952 MEM_VECTOR_INIT(&alloc, locals);
1953 MEM_VECTOR_INIT(&alloc, sizes);
1954 MEM_VECTOR_INIT(&alloc, positions);
1956 for (i = 0; i < self->locals_count; ++i)
1958 if (!function_allocator_alloc(&alloc, self->locals[i]))
1962 /* Allocate a slot for any value that still exists */
1963 for (i = 0; i < self->values_count; ++i)
1965 v = self->values[i];
1970 for (a = 0; a < alloc.locals_count; ++a)
1972 slot = alloc.locals[a];
1974 if (ir_values_overlap(v, slot))
1977 if (!ir_value_life_merge_into(slot, v))
1980 /* adjust size for this slot */
1981 if (alloc.sizes[a] < type_sizeof[v->vtype])
1982 alloc.sizes[a] = type_sizeof[v->vtype];
1984 self->values[i]->code.local = a;
1987 if (a >= alloc.locals_count) {
1988 self->values[i]->code.local = alloc.locals_count;
1989 if (!function_allocator_alloc(&alloc, v))
1998 /* Adjust slot positions based on sizes */
1999 if (!function_allocator_positions_add(&alloc, 0))
2002 if (alloc.sizes_count)
2003 pos = alloc.positions[0] + alloc.sizes[0];
2006 for (i = 1; i < alloc.sizes_count; ++i)
2008 pos = alloc.positions[i-1] + alloc.sizes[i-1];
2009 if (!function_allocator_positions_add(&alloc, pos))
2013 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
2015 /* Take over the actual slot positions */
2016 for (i = 0; i < self->values_count; ++i) {
2017 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
2025 for (i = 0; i < alloc.locals_count; ++i)
2026 ir_value_delete(alloc.locals[i]);
2027 MEM_VECTOR_CLEAR(&alloc, locals);
2028 MEM_VECTOR_CLEAR(&alloc, sizes);
2029 MEM_VECTOR_CLEAR(&alloc, positions);
2033 /* Get information about which operand
2034 * is read from, or written to.
2036 static void ir_op_read_write(int op, size_t *read, size_t *write)
2056 case INSTR_STOREP_F:
2057 case INSTR_STOREP_V:
2058 case INSTR_STOREP_S:
2059 case INSTR_STOREP_ENT:
2060 case INSTR_STOREP_FLD:
2061 case INSTR_STOREP_FNC:
2072 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2075 bool changed = false;
2077 for (i = 0; i != self->living_count; ++i)
2079 tempbool = ir_value_life_merge(self->living[i], eid);
2082 irerror(self->context, "block_living_add_instr() value instruction added %s: %i", self->living[i]->_name, (int)eid);
2084 changed = changed || tempbool;
2089 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
2092 /* values which have been read in a previous iteration are now
2093 * in the "living" array even if the previous block doesn't use them.
2094 * So we have to remove whatever does not exist in the previous block.
2095 * They will be re-added on-read, but the liferange merge won't cause
2098 for (i = 0; i < self->living_count; ++i)
2100 if (!ir_block_living_find(prev, self->living[i], NULL)) {
2101 if (!ir_block_living_remove(self, i))
2107 /* Whatever the previous block still has in its living set
2108 * must now be added to ours as well.
2110 for (i = 0; i < prev->living_count; ++i)
2112 if (ir_block_living_find(self, prev->living[i], NULL))
2114 if (!ir_block_living_add(self, prev->living[i]))
2117 irerror(self->contextt from prev: %s", self->label, prev->living[i]->_name);
2123 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2129 /* bitmasks which operands are read from or written to */
2131 char dbg_ind[16] = { '#', '0' };
2136 if (!ir_block_life_prop_previous(self, prev, changed))
2140 i = self->instr_count;
2143 instr = self->instr[i];
2145 /* PHI operands are always read operands */
2146 for (p = 0; p < instr->phi_count; ++p)
2148 value = instr->phi[p].value;
2149 if (value->memberof)
2150 value = value->memberof;
2151 if (!ir_block_living_find(self, value, NULL) &&
2152 !ir_block_living_add(self, value))
2158 /* call params are read operands too */
2159 for (p = 0; p < instr->params_count; ++p)
2161 value = instr->params[p];
2162 if (value->memberof)
2163 value = value->memberof;
2164 if (!ir_block_living_find(self, value, NULL) &&
2165 !ir_block_living_add(self, value))
2171 /* See which operands are read and write operands */
2172 ir_op_read_write(instr->opcode, &read, &write);
2174 if (instr->opcode == INSTR_MUL_VF)
2176 /* the float source will get an additional lifetime */
2177 tempbool = ir_value_life_merge(instr->_ops[2], instr->eid+1);
2178 *changed = *changed || tempbool;
2180 else if (instr->opcode == INSTR_MUL_FV)
2182 /* the float source will get an additional lifetime */
2183 tempbool = ir_value_life_merge(instr->_ops[1], instr->eid+1);
2184 *changed = *changed || tempbool;
2187 /* Go through the 3 main operands */
2188 for (o = 0; o < 3; ++o)
2190 if (!instr->_ops[o]) /* no such operand */
2193 value = instr->_ops[o];
2194 if (value->memberof)
2195 value = value->memberof;
2197 /* We only care about locals */
2198 /* we also calculate parameter liferanges so that locals
2199 * can take up parameter slots */
2200 if (value->store != store_value &&
2201 value->store != store_local &&
2202 value->store != store_param)
2208 if (!ir_block_living_find(self, value, NULL) &&
2209 !ir_block_living_add(self, value))
2215 /* write operands */
2216 /* When we write to a local, we consider it "dead" for the
2217 * remaining upper part of the function, since in SSA a value
2218 * can only be written once (== created)
2223 bool in_living = ir_block_living_find(self, value, &idx);
2226 /* If the value isn't alive it hasn't been read before... */
2227 /* TODO: See if the warning can be emitted during parsing or AST processing
2228 * otherwise have warning printed here.
2229 * IF printing a warning here: include filecontext_t,
2230 * and make sure it's only printed once
2231 * since this function is run multiple times.
2233 /* For now: debug info: */
2234 /* fprintf(stderr, "Value only written %s\n", value->name); */
2235 tempbool = ir_value_life_merge(value, instr->eid);
2236 *changed = *changed || tempbool;
2238 ir_instr_dump(instr, dbg_ind, printf);
2242 /* since 'living' won't contain it
2243 * anymore, merge the value, since
2246 tempbool = ir_value_life_merge(value, instr->eid);
2249 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2251 *changed = *changed || tempbool;
2253 if (!ir_block_living_remove(self, idx))
2259 tempbool = ir_block_living_add_instr(self, instr->eid);
2260 /*fprintf(stderr, "living added values\n");*/
2261 *changed = *changed || tempbool;
2265 if (self->run_id == self->owner->run_id)
2268 self->run_id = self->owner->run_id;
2270 for (i = 0; i < self->entries_count; ++i)
2272 ir_block *entry = self->entries[i];
2273 ir_block_life_propagate(entry, self, changed);
2279 /***********************************************************************
2282 * Since the IR has the convention of putting 'write' operands
2283 * at the beginning, we have to rotate the operands of instructions
2284 * properly in order to generate valid QCVM code.
2286 * Having destinations at a fixed position is more convenient. In QC
2287 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2288 * read from from OPA, and store to OPB rather than OPC. Which is
2289 * partially the reason why the implementation of these instructions
2290 * in darkplaces has been delayed for so long.
2292 * Breaking conventions is annoying...
2294 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2296 static bool gen_global_field(ir_value *global)
2298 if (global->isconst)
2300 ir_value *fld = global->constval.vpointer;
2302 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2306 /* Now, in this case, a relocation would be impossible to code
2307 * since it looks like this:
2308 * .vector v = origin; <- parse error, wtf is 'origin'?
2311 * But we will need a general relocation support later anyway
2312 * for functions... might as well support that here.
2314 if (!fld->code.globaladdr) {
2315 irerror(global->context, "FIXME: Relocation support");
2319 /* copy the field's value */
2320 ir_value_code_setaddr(global, code_globals_add(code_globals_data[fld->code.globaladdr]));
2321 if (global->fieldtype == TYPE_VECTOR) {
2322 code_globals_add(code_globals_data[fld->code.globaladdr]+1);
2323 code_globals_add(code_globals_data[fld->code.globaladdr]+2);
2328 ir_value_code_setaddr(global, code_globals_add(0));
2329 if (global->fieldtype == TYPE_VECTOR) {
2330 code_globals_add(0);
2331 code_globals_add(0);
2334 if (global->code.globaladdr < 0)
2339 static bool gen_global_pointer(ir_value *global)
2341 if (global->isconst)
2343 ir_value *target = global->constval.vpointer;
2345 irerror(global->context, "Invalid pointer constant: %s", global->name);
2346 /* NULL pointers are pointing to the NULL constant, which also
2347 * sits at address 0, but still has an ir_value for itself.
2352 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2353 * void() foo; <- proto
2354 * void() *fooptr = &foo;
2355 * void() foo = { code }
2357 if (!target->code.globaladdr) {
2358 /* FIXME: Check for the constant nullptr ir_value!
2359 * because then code.globaladdr being 0 is valid.
2361 irerror(global->context, "FIXME: Relocation support");
2365 ir_value_code_setaddr(global, code_globals_add(target->code.globaladdr));
2369 ir_value_code_setaddr(global, code_globals_add(0));
2371 if (global->code.globaladdr < 0)
2376 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2378 prog_section_statement stmt;
2387 block->generated = true;
2388 block->code_start = code_statements_elements;
2389 for (i = 0; i < block->instr_count; ++i)
2391 instr = block->instr[i];
2393 if (instr->opcode == VINSTR_PHI) {
2394 irerror(block->context, "cannot generate virtual instruction (phi)");
2398 if (instr->opcode == VINSTR_JUMP) {
2399 target = instr->bops[0];
2400 /* for uncoditional jumps, if the target hasn't been generated
2401 * yet, we generate them right here.
2403 if (!target->generated) {
2408 /* otherwise we generate a jump instruction */
2409 stmt.opcode = INSTR_GOTO;
2410 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2413 if (code_statements_add(stmt) < 0)
2416 /* no further instructions can be in this block */
2420 if (instr->opcode == VINSTR_COND) {
2421 ontrue = instr->bops[0];
2422 onfalse = instr->bops[1];
2423 /* TODO: have the AST signal which block should
2424 * come first: eg. optimize IFs without ELSE...
2427 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2431 if (ontrue->generated) {
2432 stmt.opcode = INSTR_IF;
2433 stmt.o2.s1 = (ontrue->code_start) - code_statements_elements;
2434 if (code_statements_add(stmt) < 0)
2437 if (onfalse->generated) {
2438 stmt.opcode = INSTR_IFNOT;
2439 stmt.o2.s1 = (onfalse->code_start) - code_statements_elements;
2440 if (code_statements_add(stmt) < 0)
2443 if (!ontrue->generated) {
2444 if (onfalse->generated) {
2449 if (!onfalse->generated) {
2450 if (ontrue->generated) {
2455 /* neither ontrue nor onfalse exist */
2456 stmt.opcode = INSTR_IFNOT;
2457 stidx = code_statements_elements;
2458 if (code_statements_add(stmt) < 0)
2460 /* on false we jump, so add ontrue-path */
2461 if (!gen_blocks_recursive(func, ontrue))
2463 /* fixup the jump address */
2464 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2465 /* generate onfalse path */
2466 if (onfalse->generated) {
2467 /* fixup the jump address */
2468 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2469 /* may have been generated in the previous recursive call */
2470 stmt.opcode = INSTR_GOTO;
2471 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2474 return (code_statements_add(stmt) >= 0);
2476 /* if not, generate now */
2481 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2482 /* Trivial call translation:
2483 * copy all params to OFS_PARM*
2484 * if the output's storetype is not store_return,
2485 * add append a STORE instruction!
2487 * NOTES on how to do it better without much trouble:
2488 * -) The liferanges!
2489 * Simply check the liferange of all parameters for
2490 * other CALLs. For each param with no CALL in its
2491 * liferange, we can store it in an OFS_PARM at
2492 * generation already. This would even include later
2493 * reuse.... probably... :)
2498 for (p = 0; p < instr->params_count; ++p)
2500 ir_value *param = instr->params[p];
2502 stmt.opcode = INSTR_STORE_F;
2505 stmt.opcode = type_store_instr[param->vtype];
2506 stmt.o1.u1 = ir_value_code_addr(param);
2507 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2508 if (code_statements_add(stmt) < 0)
2511 stmt.opcode = INSTR_CALL0 + instr->params_count;
2512 if (stmt.opcode > INSTR_CALL8)
2513 stmt.opcode = INSTR_CALL8;
2514 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2517 if (code_statements_add(stmt) < 0)
2520 retvalue = instr->_ops[0];
2521 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2523 /* not to be kept in OFS_RETURN */
2524 stmt.opcode = type_store_instr[retvalue->vtype];
2525 stmt.o1.u1 = OFS_RETURN;
2526 stmt.o2.u1 = ir_value_code_addr(retvalue);
2528 if (code_statements_add(stmt) < 0)
2534 if (instr->opcode == INSTR_STATE) {
2535 irerror(block->context, "TODO: state instruction");
2539 stmt.opcode = instr->opcode;
2544 /* This is the general order of operands */
2546 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2549 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2552 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2554 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2556 stmt.o1.u1 = stmt.o3.u1;
2559 else if ((stmt.opcode >= INSTR_STORE_F &&
2560 stmt.opcode <= INSTR_STORE_FNC) ||
2561 (stmt.opcode >= INSTR_STOREP_F &&
2562 stmt.opcode <= INSTR_STOREP_FNC))
2564 /* 2-operand instructions with A -> B */
2565 stmt.o2.u1 = stmt.o3.u1;
2569 if (code_statements_add(stmt) < 0)
2575 static bool gen_function_code(ir_function *self)
2578 prog_section_statement stmt;
2580 /* Starting from entry point, we generate blocks "as they come"
2581 * for now. Dead blocks will not be translated obviously.
2583 if (!self->blocks_count) {
2584 irerror(self->context, "Function '%s' declared without body.", self->name);
2588 block = self->blocks[0];
2589 if (block->generated)
2592 if (!gen_blocks_recursive(self, block)) {
2593 irerror(self->context, "failed to generate blocks for '%s'", self->name);
2597 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2598 stmt.opcode = AINSTR_END;
2602 if (code_statements_add(stmt) < 0)
2607 static qcint ir_builder_filestring(ir_builder *ir, const char *filename)
2609 /* NOTE: filename pointers are copied, we never strdup them,
2610 * thus we can use pointer-comparison to find the string.
2615 for (i = 0; i < ir->filenames_count; ++i) {
2616 if (ir->filenames[i] == filename)
2617 return ir->filestrings[i];
2620 str = code_genstring(filename);
2621 if (!ir_builder_filenames_add(ir, filename))
2623 if (!ir_builder_filestrings_add(ir, str))
2624 ir->filenames_count--;
2628 static bool gen_global_function(ir_builder *ir, ir_value *global)
2630 prog_section_function fun;
2634 size_t local_var_end;
2636 if (!global->isconst || (!global->constval.vfunc))
2638 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
2642 irfun = global->constval.vfunc;
2644 fun.name = global->code.name;
2645 fun.file = ir_builder_filestring(ir, global->context.file);
2646 fun.profile = 0; /* always 0 */
2647 fun.nargs = irfun->params_count;
2649 for (i = 0;i < 8; ++i) {
2653 fun.argsize[i] = type_sizeof[irfun->params[i]];
2656 fun.firstlocal = code_globals_elements;
2658 local_var_end = fun.firstlocal;
2659 for (i = 0; i < irfun->locals_count; ++i) {
2660 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
2661 irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
2665 if (irfun->locals_count) {
2666 ir_value *last = irfun->locals[irfun->locals_count-1];
2667 local_var_end = last->code.globaladdr;
2668 local_var_end += type_sizeof[last->vtype];
2670 for (i = 0; i < irfun->values_count; ++i)
2672 /* generate code.globaladdr for ssa values */
2673 ir_value *v = irfun->values[i];
2674 ir_value_code_setaddr(v, local_var_end + v->code.local);
2676 for (i = 0; i < irfun->allocated_locals; ++i) {
2677 /* fill the locals with zeros */
2678 code_globals_add(0);
2681 fun.locals = code_globals_elements - fun.firstlocal;
2684 fun.entry = irfun->builtin;
2686 irfun->code_function_def = code_functions_elements;
2687 fun.entry = code_statements_elements;
2690 return (code_functions_add(fun) >= 0);
2693 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
2695 prog_section_function *fundef;
2698 irfun = global->constval.vfunc;
2700 irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
2701 "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
2702 /* this was a function pointer, don't generate code for those */
2709 if (irfun->code_function_def < 0) {
2710 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
2713 fundef = &code_functions_data[irfun->code_function_def];
2715 fundef->entry = code_statements_elements;
2716 if (!gen_function_code(irfun)) {
2717 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
2723 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
2727 prog_section_def def;
2729 def.type = global->vtype;
2730 def.offset = code_globals_elements;
2733 if (global->name[0] == '#') {
2734 if (!self->str_immediate)
2735 self->str_immediate = code_genstring("IMMEDIATE");
2736 def.name = global->code.name = self->str_immediate;
2739 def.name = global->code.name = code_genstring(global->name);
2744 switch (global->vtype)
2747 if (!strcmp(global->name, "end_sys_globals")) {
2748 /* TODO: remember this point... all the defs before this one
2749 * should be checksummed and added to progdefs.h when we generate it.
2752 else if (!strcmp(global->name, "end_sys_fields")) {
2753 /* TODO: same as above but for entity-fields rather than globsl
2757 irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
2759 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
2760 * the system fields actually go? Though the engine knows this anyway...
2761 * Maybe this could be an -foption
2762 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
2764 ir_value_code_setaddr(global, code_globals_add(0));
2766 if (code_defs_add(def) < 0)
2770 if (code_defs_add(def) < 0)
2772 return gen_global_pointer(global);
2774 if (code_defs_add(def) < 0)
2776 return gen_global_field(global);
2781 if (global->isconst) {
2782 iptr = (int32_t*)&global->constval.vfloat;
2783 ir_value_code_setaddr(global, code_globals_add(*iptr));
2785 ir_value_code_setaddr(global, code_globals_add(0));
2787 def.type |= DEF_SAVEGLOBAL;
2789 if (code_defs_add(def) < 0)
2792 return global->code.globaladdr >= 0;
2796 if (global->isconst)
2797 ir_value_code_setaddr(global, code_globals_add(code_genstring(global->constval.vstring)));
2799 ir_value_code_setaddr(global, code_globals_add(0));
2801 def.type |= DEF_SAVEGLOBAL;
2803 if (code_defs_add(def) < 0)
2805 return global->code.globaladdr >= 0;
2810 if (global->isconst) {
2811 iptr = (int32_t*)&global->constval.vvec;
2812 ir_value_code_setaddr(global, code_globals_add(iptr[0]));
2813 if (global->code.globaladdr < 0)
2815 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2817 if (code_globals_add(iptr[d]) < 0)
2821 ir_value_code_setaddr(global, code_globals_add(0));
2822 if (global->code.globaladdr < 0)
2824 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2826 if (code_globals_add(0) < 0)
2830 def.type |= DEF_SAVEGLOBAL;
2833 if (code_defs_add(def) < 0)
2835 return global->code.globaladdr >= 0;
2838 if (!global->isconst) {
2839 ir_value_code_setaddr(global, code_globals_add(0));
2840 if (global->code.globaladdr < 0)
2843 ir_value_code_setaddr(global, code_globals_elements);
2844 code_globals_add(code_functions_elements);
2845 if (!gen_global_function(self, global))
2848 def.type |= DEF_SAVEGLOBAL;
2850 if (code_defs_add(def) < 0)
2854 /* assume biggest type */
2855 ir_value_code_setaddr(global, code_globals_add(0));
2856 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2857 code_globals_add(0);
2860 /* refuse to create 'void' type or any other fancy business. */
2861 irerror(global->context, "Invalid type for global variable `%s`: %s",
2862 global->name, type_name[global->vtype]);
2867 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2869 prog_section_def def;
2870 prog_section_field fld;
2872 def.type = field->vtype;
2873 def.offset = code_globals_elements;
2875 /* create a global named the same as the field */
2876 if (opts_standard == COMPILER_GMQCC) {
2877 /* in our standard, the global gets a dot prefix */
2878 size_t len = strlen(field->name);
2881 /* we really don't want to have to allocate this, and 1024
2882 * bytes is more than enough for a variable/field name
2884 if (len+2 >= sizeof(name)) {
2885 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
2890 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
2893 def.name = code_genstring(name);
2894 fld.name = def.name + 1; /* we reuse that string table entry */
2896 /* in plain QC, there cannot be a global with the same name,
2897 * and so we also name the global the same.
2898 * FIXME: fteqcc should create a global as well
2899 * check if it actually uses the same name. Probably does
2901 def.name = code_genstring(field->name);
2902 fld.name = def.name;
2905 field->code.name = def.name;
2907 if (code_defs_add(def) < 0)
2910 fld.type = field->fieldtype;
2912 if (fld.type == TYPE_VOID) {
2913 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
2917 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2919 if (code_fields_add(fld) < 0)
2922 ir_value_code_setaddr(field, code_globals_elements);
2923 if (!code_globals_add(fld.offset))
2925 if (fld.type == TYPE_VECTOR) {
2926 if (!code_globals_add(fld.offset+1))
2928 if (!code_globals_add(fld.offset+2))
2932 return field->code.globaladdr >= 0;
2935 bool ir_builder_generate(ir_builder *self, const char *filename)
2937 prog_section_statement stmt;
2942 for (i = 0; i < self->globals_count; ++i)
2944 if (!ir_builder_gen_global(self, self->globals[i], false)) {
2949 for (i = 0; i < self->fields_count; ++i)
2951 if (!ir_builder_gen_field(self, self->fields[i])) {
2956 /* generate function code */
2957 for (i = 0; i < self->globals_count; ++i)
2959 if (self->globals[i]->vtype == TYPE_FUNCTION) {
2960 if (!gen_global_function_code(self, self->globals[i])) {
2966 /* DP errors if the last instruction is not an INSTR_DONE
2967 * and for debugging purposes we add an additional AINSTR_END
2968 * to the end of functions, so here it goes:
2970 stmt.opcode = INSTR_DONE;
2974 if (code_statements_add(stmt) < 0)
2977 printf("writing '%s'...\n", filename);
2978 return code_write(filename);
2981 /***********************************************************************
2982 *IR DEBUG Dump functions...
2985 #define IND_BUFSZ 1024
2988 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
2990 # define strncat strncat
2993 const char *qc_opname(int op)
2995 if (op < 0) return "<INVALID>";
2996 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2997 return asm_instr[op].m;
2999 case VINSTR_PHI: return "PHI";
3000 case VINSTR_JUMP: return "JUMP";
3001 case VINSTR_COND: return "COND";
3002 default: return "<UNK>";
3006 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
3009 char indent[IND_BUFSZ];
3013 oprintf("module %s\n", b->name);
3014 for (i = 0; i < b->globals_count; ++i)
3017 if (b->globals[i]->isconst)
3018 oprintf("%s = ", b->globals[i]->name);
3019 ir_value_dump(b->globals[i], oprintf);
3022 for (i = 0; i < b->functions_count; ++i)
3023 ir_function_dump(b->functions[i], indent, oprintf);
3024 oprintf("endmodule %s\n", b->name);
3027 void ir_function_dump(ir_function *f, char *ind,
3028 int (*oprintf)(const char*, ...))
3031 if (f->builtin != 0) {
3032 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
3035 oprintf("%sfunction %s\n", ind, f->name);
3036 strncat(ind, "\t", IND_BUFSZ);
3037 if (f->locals_count)
3039 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
3040 for (i = 0; i < f->locals_count; ++i) {
3041 oprintf("%s\t", ind);
3042 ir_value_dump(f->locals[i], oprintf);
3046 oprintf("%sliferanges:\n", ind);
3047 for (i = 0; i < f->locals_count; ++i) {
3049 ir_value *v = f->locals[i];
3050 oprintf("%s\t%s: unique ", ind, v->name);
3051 for (l = 0; l < v->life_count; ++l) {
3052 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3056 for (i = 0; i < f->values_count; ++i) {
3058 ir_value *v = f->values[i];
3059 oprintf("%s\t%s: @%i ", ind, v->name, (int)v->code.local);
3060 for (l = 0; l < v->life_count; ++l) {
3061 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3065 if (f->blocks_count)
3067 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
3068 for (i = 0; i < f->blocks_count; ++i) {
3069 if (f->blocks[i]->run_id != f->run_id) {
3070 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
3072 ir_block_dump(f->blocks[i], ind, oprintf);
3076 ind[strlen(ind)-1] = 0;
3077 oprintf("%sendfunction %s\n", ind, f->name);
3080 void ir_block_dump(ir_block* b, char *ind,
3081 int (*oprintf)(const char*, ...))
3084 oprintf("%s:%s\n", ind, b->label);
3085 strncat(ind, "\t", IND_BUFSZ);
3087 for (i = 0; i < b->instr_count; ++i)
3088 ir_instr_dump(b->instr[i], ind, oprintf);
3089 ind[strlen(ind)-1] = 0;
3092 void dump_phi(ir_instr *in, char *ind,
3093 int (*oprintf)(const char*, ...))
3096 oprintf("%s <- phi ", in->_ops[0]->name);
3097 for (i = 0; i < in->phi_count; ++i)
3099 oprintf("([%s] : %s) ", in->phi[i].from->label,
3100 in->phi[i].value->name);
3105 void ir_instr_dump(ir_instr *in, char *ind,
3106 int (*oprintf)(const char*, ...))
3109 const char *comma = NULL;
3111 oprintf("%s (%i) ", ind, (int)in->eid);
3113 if (in->opcode == VINSTR_PHI) {
3114 dump_phi(in, ind, oprintf);
3118 strncat(ind, "\t", IND_BUFSZ);
3120 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3121 ir_value_dump(in->_ops[0], oprintf);
3122 if (in->_ops[1] || in->_ops[2])
3125 if (in->opcode == INSTR_CALL0) {
3126 oprintf("CALL%i\t", in->params_count);
3128 oprintf("%s\t", qc_opname(in->opcode));
3130 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3131 ir_value_dump(in->_ops[0], oprintf);
3136 for (i = 1; i != 3; ++i) {
3140 ir_value_dump(in->_ops[i], oprintf);
3148 oprintf("[%s]", in->bops[0]->label);
3152 oprintf("%s[%s]", comma, in->bops[1]->label);
3153 if (in->params_count) {
3154 oprintf("\tparams: ");
3155 for (i = 0; i != in->params_count; ++i) {
3156 oprintf("%s, ", in->params[i]->name);
3160 ind[strlen(ind)-1] = 0;
3163 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3172 oprintf("fn:%s", v->name);
3175 oprintf("%g", v->constval.vfloat);
3178 oprintf("'%g %g %g'",
3181 v->constval.vvec.z);
3184 oprintf("(entity)");
3187 oprintf("\"%s\"", v->constval.vstring);
3191 oprintf("%i", v->constval.vint);
3196 v->constval.vpointer->name);
3200 oprintf("%s", v->name);
3204 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
3207 oprintf("Life of %12s:", self->name);
3208 for (i = 0; i < self->life_count; ++i)
3210 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);