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 ir_builder* ir_builder_new(const char *modulename)
162 self = (ir_builder*)mem_a(sizeof(*self));
166 MEM_VECTOR_INIT(self, functions);
167 MEM_VECTOR_INIT(self, globals);
168 MEM_VECTOR_INIT(self, fields);
170 if (!ir_builder_set_name(self, modulename)) {
178 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
179 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, fields)
180 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
182 void ir_builder_delete(ir_builder* self)
185 mem_d((void*)self->name);
186 for (i = 0; i != self->functions_count; ++i) {
187 ir_function_delete(self->functions[i]);
189 MEM_VECTOR_CLEAR(self, functions);
190 for (i = 0; i != self->globals_count; ++i) {
191 ir_value_delete(self->globals[i]);
193 MEM_VECTOR_CLEAR(self, globals);
194 for (i = 0; i != self->fields_count; ++i) {
195 ir_value_delete(self->fields[i]);
197 MEM_VECTOR_CLEAR(self, fields);
201 bool ir_builder_set_name(ir_builder *self, const char *name)
204 mem_d((void*)self->name);
205 self->name = util_strdup(name);
209 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
212 for (i = 0; i < self->functions_count; ++i) {
213 if (!strcmp(name, self->functions[i]->name))
214 return self->functions[i];
219 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
221 ir_function *fn = ir_builder_get_function(self, name);
226 fn = ir_function_new(self, outtype);
227 if (!ir_function_set_name(fn, name) ||
228 !ir_builder_functions_add(self, fn) )
230 ir_function_delete(fn);
234 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
236 ir_function_delete(fn);
240 fn->value->isconst = true;
241 fn->value->outtype = outtype;
242 fn->value->constval.vfunc = fn;
243 fn->value->context = fn->context;
248 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
251 for (i = 0; i < self->globals_count; ++i) {
252 if (!strcmp(self->globals[i]->name, name))
253 return self->globals[i];
258 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
262 if (name && name[0] != '#')
264 ve = ir_builder_get_global(self, name);
270 ve = ir_value_var(name, store_global, vtype);
271 if (!ir_builder_globals_add(self, ve)) {
278 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
281 for (i = 0; i < self->fields_count; ++i) {
282 if (!strcmp(self->fields[i]->name, name))
283 return self->fields[i];
289 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
291 ir_value *ve = ir_builder_get_field(self, name);
296 ve = ir_value_var(name, store_global, TYPE_FIELD);
297 ve->fieldtype = vtype;
298 if (!ir_builder_fields_add(self, ve)) {
305 /***********************************************************************
309 bool ir_function_naive_phi(ir_function*);
310 void ir_function_enumerate(ir_function*);
311 bool ir_function_calculate_liferanges(ir_function*);
312 bool ir_function_allocate_locals(ir_function*);
314 ir_function* ir_function_new(ir_builder* owner, int outtype)
317 self = (ir_function*)mem_a(sizeof(*self));
322 memset(self, 0, sizeof(*self));
325 if (!ir_function_set_name(self, "<@unnamed>")) {
330 self->context.file = "<@no context>";
331 self->context.line = 0;
332 self->outtype = outtype;
335 MEM_VECTOR_INIT(self, params);
336 MEM_VECTOR_INIT(self, blocks);
337 MEM_VECTOR_INIT(self, values);
338 MEM_VECTOR_INIT(self, locals);
340 self->code_function_def = -1;
341 self->allocated_locals = 0;
346 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
347 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
348 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
349 MEM_VEC_FUNCTIONS(ir_function, int, params)
351 bool ir_function_set_name(ir_function *self, const char *name)
354 mem_d((void*)self->name);
355 self->name = util_strdup(name);
359 void ir_function_delete(ir_function *self)
362 mem_d((void*)self->name);
364 for (i = 0; i != self->blocks_count; ++i)
365 ir_block_delete(self->blocks[i]);
366 MEM_VECTOR_CLEAR(self, blocks);
368 MEM_VECTOR_CLEAR(self, params);
370 for (i = 0; i != self->values_count; ++i)
371 ir_value_delete(self->values[i]);
372 MEM_VECTOR_CLEAR(self, values);
374 for (i = 0; i != self->locals_count; ++i)
375 ir_value_delete(self->locals[i]);
376 MEM_VECTOR_CLEAR(self, locals);
378 /* self->value is deleted by the builder */
383 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
385 return ir_function_values_add(self, v);
388 ir_block* ir_function_create_block(ir_function *self, const char *label)
390 ir_block* bn = ir_block_new(self, label);
391 memcpy(&bn->context, &self->context, sizeof(self->context));
392 if (!ir_function_blocks_add(self, bn)) {
399 bool ir_function_finalize(ir_function *self)
404 if (!ir_function_naive_phi(self))
407 ir_function_enumerate(self);
409 if (!ir_function_calculate_liferanges(self))
412 if (!ir_function_allocate_locals(self))
417 ir_value* ir_function_get_local(ir_function *self, const char *name)
420 for (i = 0; i < self->locals_count; ++i) {
421 if (!strcmp(self->locals[i]->name, name))
422 return self->locals[i];
427 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
432 if (ir_function_get_local(self, name))
437 self->locals_count &&
438 self->locals[self->locals_count-1]->store != store_param) {
439 irerror(self->context, "cannot add parameters after adding locals");
443 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
444 if (!ir_function_locals_add(self, ve)) {
451 /***********************************************************************
455 ir_block* ir_block_new(ir_function* owner, const char *name)
458 self = (ir_block*)mem_a(sizeof(*self));
462 memset(self, 0, sizeof(*self));
465 if (!ir_block_set_label(self, name)) {
470 self->context.file = "<@no context>";
471 self->context.line = 0;
473 MEM_VECTOR_INIT(self, instr);
474 MEM_VECTOR_INIT(self, entries);
475 MEM_VECTOR_INIT(self, exits);
478 self->is_return = false;
480 MEM_VECTOR_INIT(self, living);
482 self->generated = false;
486 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
487 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
488 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
489 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
491 void ir_block_delete(ir_block* self)
495 for (i = 0; i != self->instr_count; ++i)
496 ir_instr_delete(self->instr[i]);
497 MEM_VECTOR_CLEAR(self, instr);
498 MEM_VECTOR_CLEAR(self, entries);
499 MEM_VECTOR_CLEAR(self, exits);
500 MEM_VECTOR_CLEAR(self, living);
504 bool ir_block_set_label(ir_block *self, const char *name)
507 mem_d((void*)self->label);
508 self->label = util_strdup(name);
509 return !!self->label;
512 /***********************************************************************
516 ir_instr* ir_instr_new(ir_block* owner, int op)
519 self = (ir_instr*)mem_a(sizeof(*self));
524 self->context.file = "<@no context>";
525 self->context.line = 0;
527 self->_ops[0] = NULL;
528 self->_ops[1] = NULL;
529 self->_ops[2] = NULL;
530 self->bops[0] = NULL;
531 self->bops[1] = NULL;
532 MEM_VECTOR_INIT(self, phi);
533 MEM_VECTOR_INIT(self, params);
538 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
539 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
541 void ir_instr_delete(ir_instr *self)
544 /* The following calls can only delete from
545 * vectors, we still want to delete this instruction
546 * so ignore the return value. Since with the warn_unused_result attribute
547 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
548 * I have to improvise here and use if(foo());
550 for (i = 0; i < self->phi_count; ++i) {
552 if (ir_value_writes_find(self->phi[i].value, self, &idx))
553 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
554 if (ir_value_reads_find(self->phi[i].value, self, &idx))
555 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
557 MEM_VECTOR_CLEAR(self, phi);
558 for (i = 0; i < self->params_count; ++i) {
560 if (ir_value_writes_find(self->params[i], self, &idx))
561 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
562 if (ir_value_reads_find(self->params[i], self, &idx))
563 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
565 MEM_VECTOR_CLEAR(self, params);
566 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
567 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
568 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
572 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
574 if (self->_ops[op]) {
576 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
578 if (!ir_value_writes_remove(self->_ops[op], idx))
581 else if (ir_value_reads_find(self->_ops[op], self, &idx))
583 if (!ir_value_reads_remove(self->_ops[op], idx))
589 if (!ir_value_writes_add(v, self))
592 if (!ir_value_reads_add(v, self))
600 /***********************************************************************
604 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
606 self->code.globaladdr = gaddr;
607 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
608 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
609 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
612 int32_t ir_value_code_addr(const ir_value *self)
614 if (self->store == store_return)
615 return OFS_RETURN + self->code.addroffset;
616 return self->code.globaladdr + self->code.addroffset;
619 ir_value* ir_value_var(const char *name, int storetype, int vtype)
622 self = (ir_value*)mem_a(sizeof(*self));
624 self->fieldtype = TYPE_VOID;
625 self->outtype = TYPE_VOID;
626 self->store = storetype;
627 MEM_VECTOR_INIT(self, reads);
628 MEM_VECTOR_INIT(self, writes);
629 self->isconst = false;
630 self->context.file = "<@no context>";
631 self->context.line = 0;
633 ir_value_set_name(self, name);
635 memset(&self->constval, 0, sizeof(self->constval));
636 memset(&self->code, 0, sizeof(self->code));
638 self->members[0] = NULL;
639 self->members[1] = NULL;
640 self->members[2] = NULL;
641 self->memberof = NULL;
643 MEM_VECTOR_INIT(self, life);
647 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
653 if (self->members[member])
654 return self->members[member];
656 if (self->vtype == TYPE_VECTOR)
658 m = ir_value_var(self->name, self->store, TYPE_FLOAT);
661 m->context = self->context;
663 self->members[member] = m;
664 m->code.addroffset = member;
666 else if (self->vtype == TYPE_FIELD)
668 if (self->fieldtype != TYPE_VECTOR)
670 m = ir_value_var(self->name, self->store, TYPE_FIELD);
673 m->fieldtype = TYPE_FLOAT;
674 m->context = self->context;
676 self->members[member] = m;
677 m->code.addroffset = member;
681 irerror(self->context, "invalid member access on %s", self->name);
689 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
690 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
691 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
693 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
695 ir_value *v = ir_value_var(name, storetype, vtype);
698 if (!ir_function_collect_value(owner, v))
706 void ir_value_delete(ir_value* self)
710 mem_d((void*)self->name);
713 if (self->vtype == TYPE_STRING)
714 mem_d((void*)self->constval.vstring);
716 for (i = 0; i < 3; ++i) {
717 if (self->members[i])
718 ir_value_delete(self->members[i]);
720 MEM_VECTOR_CLEAR(self, reads);
721 MEM_VECTOR_CLEAR(self, writes);
722 MEM_VECTOR_CLEAR(self, life);
726 void ir_value_set_name(ir_value *self, const char *name)
729 mem_d((void*)self->name);
730 self->name = util_strdup(name);
733 bool ir_value_set_float(ir_value *self, float f)
735 if (self->vtype != TYPE_FLOAT)
737 self->constval.vfloat = f;
738 self->isconst = true;
742 bool ir_value_set_func(ir_value *self, int f)
744 if (self->vtype != TYPE_FUNCTION)
746 self->constval.vint = f;
747 self->isconst = true;
751 bool ir_value_set_vector(ir_value *self, vector v)
753 if (self->vtype != TYPE_VECTOR)
755 self->constval.vvec = v;
756 self->isconst = true;
760 bool ir_value_set_field(ir_value *self, ir_value *fld)
762 if (self->vtype != TYPE_FIELD)
764 self->constval.vpointer = fld;
765 self->isconst = true;
769 static char *ir_strdup(const char *str)
772 /* actually dup empty strings */
773 char *out = mem_a(1);
777 return util_strdup(str);
780 bool ir_value_set_string(ir_value *self, const char *str)
782 if (self->vtype != TYPE_STRING)
784 self->constval.vstring = ir_strdup(str);
785 self->isconst = true;
790 bool ir_value_set_int(ir_value *self, int i)
792 if (self->vtype != TYPE_INTEGER)
794 self->constval.vint = i;
795 self->isconst = true;
800 bool ir_value_lives(ir_value *self, size_t at)
803 for (i = 0; i < self->life_count; ++i)
805 ir_life_entry_t *life = &self->life[i];
806 if (life->start <= at && at <= life->end)
808 if (life->start > at) /* since it's ordered */
814 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
817 if (!ir_value_life_add(self, e)) /* naive... */
819 for (k = self->life_count-1; k > idx; --k)
820 self->life[k] = self->life[k-1];
825 bool ir_value_life_merge(ir_value *self, size_t s)
828 ir_life_entry_t *life = NULL;
829 ir_life_entry_t *before = NULL;
830 ir_life_entry_t new_entry;
832 /* Find the first range >= s */
833 for (i = 0; i < self->life_count; ++i)
836 life = &self->life[i];
840 /* nothing found? append */
841 if (i == self->life_count) {
843 if (life && life->end+1 == s)
845 /* previous life range can be merged in */
849 if (life && life->end >= s)
852 if (!ir_value_life_add(self, e))
853 return false; /* failing */
859 if (before->end + 1 == s &&
860 life->start - 1 == s)
863 before->end = life->end;
864 if (!ir_value_life_remove(self, i))
865 return false; /* failing */
868 if (before->end + 1 == s)
874 /* already contained */
875 if (before->end >= s)
879 if (life->start - 1 == s)
884 /* insert a new entry */
885 new_entry.start = new_entry.end = s;
886 return ir_value_life_insert(self, i, new_entry);
889 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
893 if (!other->life_count)
896 if (!self->life_count) {
897 for (i = 0; i < other->life_count; ++i) {
898 if (!ir_value_life_add(self, other->life[i]))
905 for (i = 0; i < other->life_count; ++i)
907 const ir_life_entry_t *life = &other->life[i];
910 ir_life_entry_t *entry = &self->life[myi];
912 if (life->end+1 < entry->start)
914 /* adding an interval before entry */
915 if (!ir_value_life_insert(self, myi, *life))
921 if (life->start < entry->start &&
922 life->end >= entry->start)
924 /* starts earlier and overlaps */
925 entry->start = life->start;
928 if (life->end > entry->end &&
929 life->start-1 <= entry->end)
931 /* ends later and overlaps */
932 entry->end = life->end;
935 /* see if our change combines it with the next ranges */
936 while (myi+1 < self->life_count &&
937 entry->end+1 >= self->life[1+myi].start)
939 /* overlaps with (myi+1) */
940 if (entry->end < self->life[1+myi].end)
941 entry->end = self->life[1+myi].end;
942 if (!ir_value_life_remove(self, myi+1))
944 entry = &self->life[myi];
947 /* see if we're after the entry */
948 if (life->start > entry->end)
951 /* append if we're at the end */
952 if (myi >= self->life_count) {
953 if (!ir_value_life_add(self, *life))
957 /* otherweise check the next range */
966 bool ir_values_overlap(const ir_value *a, const ir_value *b)
968 /* For any life entry in A see if it overlaps with
969 * any life entry in B.
970 * Note that the life entries are orderes, so we can make a
971 * more efficient algorithm there than naively translating the
975 ir_life_entry_t *la, *lb, *enda, *endb;
977 /* first of all, if either has no life range, they cannot clash */
978 if (!a->life_count || !b->life_count)
983 enda = la + a->life_count;
984 endb = lb + b->life_count;
987 /* check if the entries overlap, for that,
988 * both must start before the other one ends.
990 if (la->start < lb->end &&
996 /* entries are ordered
997 * one entry is earlier than the other
998 * that earlier entry will be moved forward
1000 if (la->start < lb->start)
1002 /* order: A B, move A forward
1003 * check if we hit the end with A
1008 else /* if (lb->start < la->start) actually <= */
1010 /* order: B A, move B forward
1011 * check if we hit the end with B
1020 /***********************************************************************
1024 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
1026 ir_instr *in = ir_instr_new(self, op);
1030 if (target->store == store_value &&
1031 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1033 irerror(self->context, "cannot store to an SSA value");
1034 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1035 irerror(self->context, "instruction: %s", asm_instr[op].m);
1039 if (!ir_instr_op(in, 0, target, true) ||
1040 !ir_instr_op(in, 1, what, false) ||
1041 !ir_block_instr_add(self, in) )
1048 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
1052 if (target->vtype == TYPE_VARIANT)
1053 vtype = what->vtype;
1055 vtype = target->vtype;
1058 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1059 op = INSTR_CONV_ITOF;
1060 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1061 op = INSTR_CONV_FTOI;
1063 op = type_store_instr[vtype];
1065 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1066 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1070 return ir_block_create_store_op(self, op, target, what);
1073 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
1078 if (target->vtype != TYPE_POINTER)
1081 /* storing using pointer - target is a pointer, type must be
1082 * inferred from source
1084 vtype = what->vtype;
1086 op = type_storep_instr[vtype];
1087 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1088 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1089 op = INSTR_STOREP_V;
1092 return ir_block_create_store_op(self, op, target, what);
1095 bool ir_block_create_return(ir_block *self, ir_value *v)
1099 irerror(self->context, "block already ended (%s)", self->label);
1103 self->is_return = true;
1104 in = ir_instr_new(self, INSTR_RETURN);
1108 if (v && !ir_instr_op(in, 0, v, false))
1111 if (!ir_block_instr_add(self, in))
1116 bool ir_block_create_if(ir_block *self, ir_value *v,
1117 ir_block *ontrue, ir_block *onfalse)
1121 irerror(self->context, "block already ended (%s)", self->label);
1125 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1126 in = ir_instr_new(self, VINSTR_COND);
1130 if (!ir_instr_op(in, 0, v, false)) {
1131 ir_instr_delete(in);
1135 in->bops[0] = ontrue;
1136 in->bops[1] = onfalse;
1138 if (!ir_block_instr_add(self, in))
1141 if (!ir_block_exits_add(self, ontrue) ||
1142 !ir_block_exits_add(self, onfalse) ||
1143 !ir_block_entries_add(ontrue, self) ||
1144 !ir_block_entries_add(onfalse, self) )
1151 bool ir_block_create_jump(ir_block *self, ir_block *to)
1155 irerror(self->context, "block already ended (%s)", self->label);
1159 in = ir_instr_new(self, VINSTR_JUMP);
1164 if (!ir_block_instr_add(self, in))
1167 if (!ir_block_exits_add(self, to) ||
1168 !ir_block_entries_add(to, self) )
1175 bool ir_block_create_goto(ir_block *self, ir_block *to)
1179 irerror(self->context, "block already ended (%s)", self->label);
1183 in = ir_instr_new(self, INSTR_GOTO);
1188 if (!ir_block_instr_add(self, in))
1191 if (!ir_block_exits_add(self, to) ||
1192 !ir_block_entries_add(to, self) )
1199 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1203 in = ir_instr_new(self, VINSTR_PHI);
1206 out = ir_value_out(self->owner, label, store_value, ot);
1208 ir_instr_delete(in);
1211 if (!ir_instr_op(in, 0, out, true)) {
1212 ir_instr_delete(in);
1213 ir_value_delete(out);
1216 if (!ir_block_instr_add(self, in)) {
1217 ir_instr_delete(in);
1218 ir_value_delete(out);
1224 ir_value* ir_phi_value(ir_instr *self)
1226 return self->_ops[0];
1229 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1233 if (!ir_block_entries_find(self->owner, b, NULL)) {
1234 /* Must not be possible to cause this, otherwise the AST
1235 * is doing something wrong.
1237 irerror(self->context, "Invalid entry block for PHI");
1243 if (!ir_value_reads_add(v, self))
1245 return ir_instr_phi_add(self, pe);
1248 /* call related code */
1249 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1253 in = ir_instr_new(self, INSTR_CALL0);
1256 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1258 ir_instr_delete(in);
1261 if (!ir_instr_op(in, 0, out, true) ||
1262 !ir_instr_op(in, 1, func, false) ||
1263 !ir_block_instr_add(self, in))
1265 ir_instr_delete(in);
1266 ir_value_delete(out);
1272 ir_value* ir_call_value(ir_instr *self)
1274 return self->_ops[0];
1277 bool ir_call_param(ir_instr* self, ir_value *v)
1279 if (!ir_instr_params_add(self, v))
1281 if (!ir_value_reads_add(v, self)) {
1282 if (!ir_instr_params_remove(self, self->params_count-1))
1283 GMQCC_SUPPRESS_EMPTY_BODY;
1289 /* binary op related code */
1291 ir_value* ir_block_create_binop(ir_block *self,
1292 const char *label, int opcode,
1293 ir_value *left, ir_value *right)
1315 case INSTR_SUB_S: /* -- offset of string as float */
1320 case INSTR_BITOR_IF:
1321 case INSTR_BITOR_FI:
1322 case INSTR_BITAND_FI:
1323 case INSTR_BITAND_IF:
1338 case INSTR_BITAND_I:
1341 case INSTR_RSHIFT_I:
1342 case INSTR_LSHIFT_I:
1364 /* boolean operations result in floats */
1365 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1367 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1370 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1375 if (ot == TYPE_VOID) {
1376 /* The AST or parser were supposed to check this! */
1380 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1383 ir_value* ir_block_create_unary(ir_block *self,
1384 const char *label, int opcode,
1387 int ot = TYPE_FLOAT;
1399 /* QC doesn't have other unary operations. We expect extensions to fill
1400 * the above list, otherwise we assume out-type = in-type, eg for an
1404 ot = operand->vtype;
1407 if (ot == TYPE_VOID) {
1408 /* The AST or parser were supposed to check this! */
1412 /* let's use the general instruction creator and pass NULL for OPB */
1413 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1416 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1417 int op, ir_value *a, ir_value *b, int outype)
1422 out = ir_value_out(self->owner, label, store_value, outype);
1426 instr = ir_instr_new(self, op);
1428 ir_value_delete(out);
1432 if (!ir_instr_op(instr, 0, out, true) ||
1433 !ir_instr_op(instr, 1, a, false) ||
1434 !ir_instr_op(instr, 2, b, false) )
1439 if (!ir_block_instr_add(self, instr))
1444 ir_instr_delete(instr);
1445 ir_value_delete(out);
1449 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1453 /* Support for various pointer types todo if so desired */
1454 if (ent->vtype != TYPE_ENTITY)
1457 if (field->vtype != TYPE_FIELD)
1460 v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1461 v->fieldtype = field->fieldtype;
1465 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1468 if (ent->vtype != TYPE_ENTITY)
1471 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1472 if (field->vtype != TYPE_FIELD)
1477 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1478 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1479 case TYPE_STRING: op = INSTR_LOAD_S; break;
1480 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1481 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1482 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1484 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1485 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1491 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1494 ir_value* ir_block_create_add(ir_block *self,
1496 ir_value *left, ir_value *right)
1499 int l = left->vtype;
1500 int r = right->vtype;
1519 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1521 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1527 return ir_block_create_binop(self, label, op, left, right);
1530 ir_value* ir_block_create_sub(ir_block *self,
1532 ir_value *left, ir_value *right)
1535 int l = left->vtype;
1536 int r = right->vtype;
1556 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1558 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1564 return ir_block_create_binop(self, label, op, left, right);
1567 ir_value* ir_block_create_mul(ir_block *self,
1569 ir_value *left, ir_value *right)
1572 int l = left->vtype;
1573 int r = right->vtype;
1592 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1594 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1597 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1599 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1601 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1603 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1609 return ir_block_create_binop(self, label, op, left, right);
1612 ir_value* ir_block_create_div(ir_block *self,
1614 ir_value *left, ir_value *right)
1617 int l = left->vtype;
1618 int r = right->vtype;
1635 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1637 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1639 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1645 return ir_block_create_binop(self, label, op, left, right);
1648 /* PHI resolving breaks the SSA, and must thus be the last
1649 * step before life-range calculation.
1652 static bool ir_block_naive_phi(ir_block *self);
1653 bool ir_function_naive_phi(ir_function *self)
1657 for (i = 0; i < self->blocks_count; ++i)
1659 if (!ir_block_naive_phi(self->blocks[i]))
1665 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1670 /* create a store */
1671 if (!ir_block_create_store(block, old, what))
1674 /* we now move it up */
1675 instr = block->instr[block->instr_count-1];
1676 for (i = block->instr_count; i > iid; --i)
1677 block->instr[i] = block->instr[i-1];
1678 block->instr[i] = instr;
1683 static bool ir_block_naive_phi(ir_block *self)
1686 /* FIXME: optionally, create_phi can add the phis
1687 * to a list so we don't need to loop through blocks
1688 * - anyway: "don't optimize YET"
1690 for (i = 0; i < self->instr_count; ++i)
1692 ir_instr *instr = self->instr[i];
1693 if (instr->opcode != VINSTR_PHI)
1696 if (!ir_block_instr_remove(self, i))
1698 --i; /* NOTE: i+1 below */
1700 for (p = 0; p < instr->phi_count; ++p)
1702 ir_value *v = instr->phi[p].value;
1703 for (w = 0; w < v->writes_count; ++w) {
1706 if (!v->writes[w]->_ops[0])
1709 /* When the write was to a global, we have to emit a mov */
1710 old = v->writes[w]->_ops[0];
1712 /* The original instruction now writes to the PHI target local */
1713 if (v->writes[w]->_ops[0] == v)
1714 v->writes[w]->_ops[0] = instr->_ops[0];
1716 if (old->store != store_value && old->store != store_local && old->store != store_param)
1718 /* If it originally wrote to a global we need to store the value
1721 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1723 if (i+1 < self->instr_count)
1724 instr = self->instr[i+1];
1727 /* In case I forget and access instr later, it'll be NULL
1728 * when it's a problem, to make sure we crash, rather than accessing
1734 /* If it didn't, we can replace all reads by the phi target now. */
1736 for (r = 0; r < old->reads_count; ++r)
1739 ir_instr *ri = old->reads[r];
1740 for (op = 0; op < ri->phi_count; ++op) {
1741 if (ri->phi[op].value == old)
1742 ri->phi[op].value = v;
1744 for (op = 0; op < 3; ++op) {
1745 if (ri->_ops[op] == old)
1752 ir_instr_delete(instr);
1757 /***********************************************************************
1758 *IR Temp allocation code
1759 * Propagating value life ranges by walking through the function backwards
1760 * until no more changes are made.
1761 * In theory this should happen once more than once for every nested loop
1763 * Though this implementation might run an additional time for if nests.
1772 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1774 /* Enumerate instructions used by value's life-ranges
1776 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1780 for (i = 0; i < self->instr_count; ++i)
1782 self->instr[i]->eid = eid++;
1787 /* Enumerate blocks and instructions.
1788 * The block-enumeration is unordered!
1789 * We do not really use the block enumreation, however
1790 * the instruction enumeration is important for life-ranges.
1792 void ir_function_enumerate(ir_function *self)
1795 size_t instruction_id = 0;
1796 for (i = 0; i < self->blocks_count; ++i)
1798 self->blocks[i]->eid = i;
1799 self->blocks[i]->run_id = 0;
1800 ir_block_enumerate(self->blocks[i], &instruction_id);
1804 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1805 bool ir_function_calculate_liferanges(ir_function *self)
1813 for (i = 0; i != self->blocks_count; ++i)
1815 if (self->blocks[i]->is_return)
1817 self->blocks[i]->living_count = 0;
1818 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1823 if (self->blocks_count) {
1824 ir_block *block = self->blocks[0];
1825 for (i = 0; i < block->living_count; ++i) {
1826 ir_value *v = block->living[i];
1827 if (v->memberof || v->store != store_local)
1829 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
1830 "variable `%s` may be used uninitialized in this function", v->name))
1839 /* Local-value allocator
1840 * After finishing creating the liferange of all values used in a function
1841 * we can allocate their global-positions.
1842 * This is the counterpart to register-allocation in register machines.
1845 MEM_VECTOR_MAKE(ir_value*, locals);
1846 MEM_VECTOR_MAKE(size_t, sizes);
1847 MEM_VECTOR_MAKE(size_t, positions);
1848 } function_allocator;
1849 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1850 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1851 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1853 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1856 size_t vsize = type_sizeof[var->vtype];
1858 slot = ir_value_var("reg", store_global, var->vtype);
1862 if (!ir_value_life_merge_into(slot, var))
1865 if (!function_allocator_locals_add(alloc, slot))
1868 if (!function_allocator_sizes_add(alloc, vsize))
1874 ir_value_delete(slot);
1878 bool ir_function_allocate_locals(ir_function *self)
1887 function_allocator alloc;
1889 if (!self->locals_count && !self->values_count)
1892 MEM_VECTOR_INIT(&alloc, locals);
1893 MEM_VECTOR_INIT(&alloc, sizes);
1894 MEM_VECTOR_INIT(&alloc, positions);
1896 for (i = 0; i < self->locals_count; ++i)
1898 if (!function_allocator_alloc(&alloc, self->locals[i]))
1902 /* Allocate a slot for any value that still exists */
1903 for (i = 0; i < self->values_count; ++i)
1905 v = self->values[i];
1910 for (a = 0; a < alloc.locals_count; ++a)
1912 slot = alloc.locals[a];
1914 if (ir_values_overlap(v, slot))
1917 if (!ir_value_life_merge_into(slot, v))
1920 /* adjust size for this slot */
1921 if (alloc.sizes[a] < type_sizeof[v->vtype])
1922 alloc.sizes[a] = type_sizeof[v->vtype];
1924 self->values[i]->code.local = a;
1927 if (a >= alloc.locals_count) {
1928 self->values[i]->code.local = alloc.locals_count;
1929 if (!function_allocator_alloc(&alloc, v))
1938 /* Adjust slot positions based on sizes */
1939 if (!function_allocator_positions_add(&alloc, 0))
1942 if (alloc.sizes_count)
1943 pos = alloc.positions[0] + alloc.sizes[0];
1946 for (i = 1; i < alloc.sizes_count; ++i)
1948 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1949 if (!function_allocator_positions_add(&alloc, pos))
1953 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1955 /* Take over the actual slot positions */
1956 for (i = 0; i < self->values_count; ++i) {
1957 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1965 for (i = 0; i < alloc.locals_count; ++i)
1966 ir_value_delete(alloc.locals[i]);
1967 MEM_VECTOR_CLEAR(&alloc, locals);
1968 MEM_VECTOR_CLEAR(&alloc, sizes);
1969 MEM_VECTOR_CLEAR(&alloc, positions);
1973 /* Get information about which operand
1974 * is read from, or written to.
1976 static void ir_op_read_write(int op, size_t *read, size_t *write)
1996 case INSTR_STOREP_F:
1997 case INSTR_STOREP_V:
1998 case INSTR_STOREP_S:
1999 case INSTR_STOREP_ENT:
2000 case INSTR_STOREP_FLD:
2001 case INSTR_STOREP_FNC:
2012 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2015 bool changed = false;
2017 for (i = 0; i != self->living_count; ++i)
2019 tempbool = ir_value_life_merge(self->living[i], eid);
2022 irerror(self->context, "block_living_add_instr() value instruction added %s: %i", self->living[i]->_name, (int)eid);
2024 changed = changed || tempbool;
2029 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
2032 /* values which have been read in a previous iteration are now
2033 * in the "living" array even if the previous block doesn't use them.
2034 * So we have to remove whatever does not exist in the previous block.
2035 * They will be re-added on-read, but the liferange merge won't cause
2038 for (i = 0; i < self->living_count; ++i)
2040 if (!ir_block_living_find(prev, self->living[i], NULL)) {
2041 if (!ir_block_living_remove(self, i))
2047 /* Whatever the previous block still has in its living set
2048 * must now be added to ours as well.
2050 for (i = 0; i < prev->living_count; ++i)
2052 if (ir_block_living_find(self, prev->living[i], NULL))
2054 if (!ir_block_living_add(self, prev->living[i]))
2057 irerror(self->contextt from prev: %s", self->label, prev->living[i]->_name);
2063 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2069 /* bitmasks which operands are read from or written to */
2071 char dbg_ind[16] = { '#', '0' };
2076 if (!ir_block_life_prop_previous(self, prev, changed))
2080 i = self->instr_count;
2083 instr = self->instr[i];
2085 /* PHI operands are always read operands */
2086 for (p = 0; p < instr->phi_count; ++p)
2088 value = instr->phi[p].value;
2089 if (value->memberof)
2090 value = value->memberof;
2091 if (!ir_block_living_find(self, value, NULL) &&
2092 !ir_block_living_add(self, value))
2098 /* call params are read operands too */
2099 for (p = 0; p < instr->params_count; ++p)
2101 value = instr->params[p];
2102 if (value->memberof)
2103 value = value->memberof;
2104 if (!ir_block_living_find(self, value, NULL) &&
2105 !ir_block_living_add(self, value))
2111 /* See which operands are read and write operands */
2112 ir_op_read_write(instr->opcode, &read, &write);
2114 if (instr->opcode == INSTR_MUL_VF)
2116 /* the float source will get an additional lifetime */
2117 tempbool = ir_value_life_merge(instr->_ops[2], instr->eid+1);
2118 *changed = *changed || tempbool;
2120 else if (instr->opcode == INSTR_MUL_FV)
2122 /* the float source will get an additional lifetime */
2123 tempbool = ir_value_life_merge(instr->_ops[1], instr->eid+1);
2124 *changed = *changed || tempbool;
2127 /* Go through the 3 main operands */
2128 for (o = 0; o < 3; ++o)
2130 if (!instr->_ops[o]) /* no such operand */
2133 value = instr->_ops[o];
2134 if (value->memberof)
2135 value = value->memberof;
2137 /* We only care about locals */
2138 /* we also calculate parameter liferanges so that locals
2139 * can take up parameter slots */
2140 if (value->store != store_value &&
2141 value->store != store_local &&
2142 value->store != store_param)
2148 if (!ir_block_living_find(self, value, NULL) &&
2149 !ir_block_living_add(self, value))
2155 /* write operands */
2156 /* When we write to a local, we consider it "dead" for the
2157 * remaining upper part of the function, since in SSA a value
2158 * can only be written once (== created)
2163 bool in_living = ir_block_living_find(self, value, &idx);
2166 /* If the value isn't alive it hasn't been read before... */
2167 /* TODO: See if the warning can be emitted during parsing or AST processing
2168 * otherwise have warning printed here.
2169 * IF printing a warning here: include filecontext_t,
2170 * and make sure it's only printed once
2171 * since this function is run multiple times.
2173 /* For now: debug info: */
2174 /* fprintf(stderr, "Value only written %s\n", value->name); */
2175 tempbool = ir_value_life_merge(value, instr->eid);
2176 *changed = *changed || tempbool;
2178 ir_instr_dump(instr, dbg_ind, printf);
2182 /* since 'living' won't contain it
2183 * anymore, merge the value, since
2186 tempbool = ir_value_life_merge(value, instr->eid);
2189 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2191 *changed = *changed || tempbool;
2193 if (!ir_block_living_remove(self, idx))
2199 tempbool = ir_block_living_add_instr(self, instr->eid);
2200 /*fprintf(stderr, "living added values\n");*/
2201 *changed = *changed || tempbool;
2205 if (self->run_id == self->owner->run_id)
2208 self->run_id = self->owner->run_id;
2210 for (i = 0; i < self->entries_count; ++i)
2212 ir_block *entry = self->entries[i];
2213 ir_block_life_propagate(entry, self, changed);
2219 /***********************************************************************
2222 * Since the IR has the convention of putting 'write' operands
2223 * at the beginning, we have to rotate the operands of instructions
2224 * properly in order to generate valid QCVM code.
2226 * Having destinations at a fixed position is more convenient. In QC
2227 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2228 * read from from OPA, and store to OPB rather than OPC. Which is
2229 * partially the reason why the implementation of these instructions
2230 * in darkplaces has been delayed for so long.
2232 * Breaking conventions is annoying...
2234 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2236 static bool gen_global_field(ir_value *global)
2238 if (global->isconst)
2240 ir_value *fld = global->constval.vpointer;
2242 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2246 /* Now, in this case, a relocation would be impossible to code
2247 * since it looks like this:
2248 * .vector v = origin; <- parse error, wtf is 'origin'?
2251 * But we will need a general relocation support later anyway
2252 * for functions... might as well support that here.
2254 if (!fld->code.globaladdr) {
2255 irerror(global->context, "FIXME: Relocation support");
2259 /* copy the field's value */
2260 ir_value_code_setaddr(global, code_globals_add(code_globals_data[fld->code.globaladdr]));
2261 if (global->fieldtype == TYPE_VECTOR) {
2262 code_globals_add(code_globals_data[fld->code.globaladdr]+1);
2263 code_globals_add(code_globals_data[fld->code.globaladdr]+2);
2268 ir_value_code_setaddr(global, code_globals_add(0));
2269 if (global->fieldtype == TYPE_VECTOR) {
2270 code_globals_add(0);
2271 code_globals_add(0);
2274 if (global->code.globaladdr < 0)
2279 static bool gen_global_pointer(ir_value *global)
2281 if (global->isconst)
2283 ir_value *target = global->constval.vpointer;
2285 irerror(global->context, "Invalid pointer constant: %s", global->name);
2286 /* NULL pointers are pointing to the NULL constant, which also
2287 * sits at address 0, but still has an ir_value for itself.
2292 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2293 * void() foo; <- proto
2294 * void() *fooptr = &foo;
2295 * void() foo = { code }
2297 if (!target->code.globaladdr) {
2298 /* FIXME: Check for the constant nullptr ir_value!
2299 * because then code.globaladdr being 0 is valid.
2301 irerror(global->context, "FIXME: Relocation support");
2305 ir_value_code_setaddr(global, code_globals_add(target->code.globaladdr));
2309 ir_value_code_setaddr(global, code_globals_add(0));
2311 if (global->code.globaladdr < 0)
2316 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2318 prog_section_statement stmt;
2327 block->generated = true;
2328 block->code_start = code_statements_elements;
2329 for (i = 0; i < block->instr_count; ++i)
2331 instr = block->instr[i];
2333 if (instr->opcode == VINSTR_PHI) {
2334 irerror(block->context, "cannot generate virtual instruction (phi)");
2338 if (instr->opcode == VINSTR_JUMP) {
2339 target = instr->bops[0];
2340 /* for uncoditional jumps, if the target hasn't been generated
2341 * yet, we generate them right here.
2343 if (!target->generated) {
2348 /* otherwise we generate a jump instruction */
2349 stmt.opcode = INSTR_GOTO;
2350 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2353 if (code_statements_add(stmt) < 0)
2356 /* no further instructions can be in this block */
2360 if (instr->opcode == VINSTR_COND) {
2361 ontrue = instr->bops[0];
2362 onfalse = instr->bops[1];
2363 /* TODO: have the AST signal which block should
2364 * come first: eg. optimize IFs without ELSE...
2367 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2371 if (ontrue->generated) {
2372 stmt.opcode = INSTR_IF;
2373 stmt.o2.s1 = (ontrue->code_start) - code_statements_elements;
2374 if (code_statements_add(stmt) < 0)
2377 if (onfalse->generated) {
2378 stmt.opcode = INSTR_IFNOT;
2379 stmt.o2.s1 = (onfalse->code_start) - code_statements_elements;
2380 if (code_statements_add(stmt) < 0)
2383 if (!ontrue->generated) {
2384 if (onfalse->generated) {
2389 if (!onfalse->generated) {
2390 if (ontrue->generated) {
2395 /* neither ontrue nor onfalse exist */
2396 stmt.opcode = INSTR_IFNOT;
2397 stidx = code_statements_elements;
2398 if (code_statements_add(stmt) < 0)
2400 /* on false we jump, so add ontrue-path */
2401 if (!gen_blocks_recursive(func, ontrue))
2403 /* fixup the jump address */
2404 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2405 /* generate onfalse path */
2406 if (onfalse->generated) {
2407 /* fixup the jump address */
2408 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2409 /* may have been generated in the previous recursive call */
2410 stmt.opcode = INSTR_GOTO;
2411 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2414 return (code_statements_add(stmt) >= 0);
2416 /* if not, generate now */
2421 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2422 /* Trivial call translation:
2423 * copy all params to OFS_PARM*
2424 * if the output's storetype is not store_return,
2425 * add append a STORE instruction!
2427 * NOTES on how to do it better without much trouble:
2428 * -) The liferanges!
2429 * Simply check the liferange of all parameters for
2430 * other CALLs. For each param with no CALL in its
2431 * liferange, we can store it in an OFS_PARM at
2432 * generation already. This would even include later
2433 * reuse.... probably... :)
2438 for (p = 0; p < instr->params_count; ++p)
2440 ir_value *param = instr->params[p];
2442 stmt.opcode = INSTR_STORE_F;
2445 stmt.opcode = type_store_instr[param->vtype];
2446 stmt.o1.u1 = ir_value_code_addr(param);
2447 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2448 if (code_statements_add(stmt) < 0)
2451 stmt.opcode = INSTR_CALL0 + instr->params_count;
2452 if (stmt.opcode > INSTR_CALL8)
2453 stmt.opcode = INSTR_CALL8;
2454 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2457 if (code_statements_add(stmt) < 0)
2460 retvalue = instr->_ops[0];
2461 if (retvalue && retvalue->store != store_return && retvalue->life_count)
2463 /* not to be kept in OFS_RETURN */
2464 stmt.opcode = type_store_instr[retvalue->vtype];
2465 stmt.o1.u1 = OFS_RETURN;
2466 stmt.o2.u1 = ir_value_code_addr(retvalue);
2468 if (code_statements_add(stmt) < 0)
2474 if (instr->opcode == INSTR_STATE) {
2475 irerror(block->context, "TODO: state instruction");
2479 stmt.opcode = instr->opcode;
2484 /* This is the general order of operands */
2486 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2489 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2492 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2494 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2496 stmt.o1.u1 = stmt.o3.u1;
2499 else if ((stmt.opcode >= INSTR_STORE_F &&
2500 stmt.opcode <= INSTR_STORE_FNC) ||
2501 (stmt.opcode >= INSTR_STOREP_F &&
2502 stmt.opcode <= INSTR_STOREP_FNC))
2504 /* 2-operand instructions with A -> B */
2505 stmt.o2.u1 = stmt.o3.u1;
2509 if (code_statements_add(stmt) < 0)
2515 static bool gen_function_code(ir_function *self)
2518 prog_section_statement stmt;
2520 /* Starting from entry point, we generate blocks "as they come"
2521 * for now. Dead blocks will not be translated obviously.
2523 if (!self->blocks_count) {
2524 irerror(self->context, "Function '%s' declared without body.", self->name);
2528 block = self->blocks[0];
2529 if (block->generated)
2532 if (!gen_blocks_recursive(self, block)) {
2533 irerror(self->context, "failed to generate blocks for '%s'", self->name);
2537 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2538 stmt.opcode = AINSTR_END;
2542 if (code_statements_add(stmt) < 0)
2547 static bool gen_global_function(ir_builder *ir, ir_value *global)
2549 prog_section_function fun;
2553 size_t local_var_end;
2555 if (!global->isconst || (!global->constval.vfunc))
2557 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
2561 irfun = global->constval.vfunc;
2563 fun.name = global->code.name;
2564 fun.file = code_cachedstring(global->context.file);
2565 fun.profile = 0; /* always 0 */
2566 fun.nargs = irfun->params_count;
2568 for (i = 0;i < 8; ++i) {
2572 fun.argsize[i] = type_sizeof[irfun->params[i]];
2575 fun.firstlocal = code_globals_elements;
2577 local_var_end = fun.firstlocal;
2578 for (i = 0; i < irfun->locals_count; ++i) {
2579 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
2580 irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
2584 if (irfun->locals_count) {
2585 ir_value *last = irfun->locals[irfun->locals_count-1];
2586 local_var_end = last->code.globaladdr;
2587 local_var_end += type_sizeof[last->vtype];
2589 for (i = 0; i < irfun->values_count; ++i)
2591 /* generate code.globaladdr for ssa values */
2592 ir_value *v = irfun->values[i];
2593 ir_value_code_setaddr(v, local_var_end + v->code.local);
2595 for (i = 0; i < irfun->allocated_locals; ++i) {
2596 /* fill the locals with zeros */
2597 code_globals_add(0);
2600 fun.locals = code_globals_elements - fun.firstlocal;
2603 fun.entry = irfun->builtin;
2605 irfun->code_function_def = code_functions_elements;
2606 fun.entry = code_statements_elements;
2609 return (code_functions_add(fun) >= 0);
2612 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
2614 prog_section_function *fundef;
2617 irfun = global->constval.vfunc;
2619 irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
2620 "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
2621 /* this was a function pointer, don't generate code for those */
2628 if (irfun->code_function_def < 0) {
2629 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
2632 fundef = &code_functions_data[irfun->code_function_def];
2634 fundef->entry = code_statements_elements;
2635 if (!gen_function_code(irfun)) {
2636 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
2642 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
2646 prog_section_def def;
2648 def.type = global->vtype;
2649 def.offset = code_globals_elements;
2650 def.name = global->code.name = code_genstring(global->name);
2652 switch (global->vtype)
2655 if (!strcmp(global->name, "end_sys_globals")) {
2656 /* TODO: remember this point... all the defs before this one
2657 * should be checksummed and added to progdefs.h when we generate it.
2660 else if (!strcmp(global->name, "end_sys_fields")) {
2661 /* TODO: same as above but for entity-fields rather than globsl
2665 irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
2667 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
2668 * the system fields actually go? Though the engine knows this anyway...
2669 * Maybe this could be an -foption
2670 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
2672 ir_value_code_setaddr(global, code_globals_add(0));
2674 if (code_defs_add(def) < 0)
2678 if (code_defs_add(def) < 0)
2680 return gen_global_pointer(global);
2682 if (code_defs_add(def) < 0)
2684 return gen_global_field(global);
2689 if (global->isconst) {
2690 iptr = (int32_t*)&global->constval.vfloat;
2691 ir_value_code_setaddr(global, code_globals_add(*iptr));
2693 ir_value_code_setaddr(global, code_globals_add(0));
2695 def.type |= DEF_SAVEGLOBAL;
2697 if (code_defs_add(def) < 0)
2700 return global->code.globaladdr >= 0;
2704 if (global->isconst)
2705 ir_value_code_setaddr(global, code_globals_add(code_cachedstring(global->constval.vstring)));
2707 ir_value_code_setaddr(global, code_globals_add(0));
2709 def.type |= DEF_SAVEGLOBAL;
2711 if (code_defs_add(def) < 0)
2713 return global->code.globaladdr >= 0;
2718 if (global->isconst) {
2719 iptr = (int32_t*)&global->constval.vvec;
2720 ir_value_code_setaddr(global, code_globals_add(iptr[0]));
2721 if (global->code.globaladdr < 0)
2723 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2725 if (code_globals_add(iptr[d]) < 0)
2729 ir_value_code_setaddr(global, code_globals_add(0));
2730 if (global->code.globaladdr < 0)
2732 for (d = 1; d < type_sizeof[global->vtype]; ++d)
2734 if (code_globals_add(0) < 0)
2738 def.type |= DEF_SAVEGLOBAL;
2741 if (code_defs_add(def) < 0)
2743 return global->code.globaladdr >= 0;
2746 if (!global->isconst) {
2747 ir_value_code_setaddr(global, code_globals_add(0));
2748 if (global->code.globaladdr < 0)
2751 ir_value_code_setaddr(global, code_globals_elements);
2752 code_globals_add(code_functions_elements);
2753 if (!gen_global_function(self, global))
2756 def.type |= DEF_SAVEGLOBAL;
2758 if (code_defs_add(def) < 0)
2762 /* assume biggest type */
2763 ir_value_code_setaddr(global, code_globals_add(0));
2764 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2765 code_globals_add(0);
2768 /* refuse to create 'void' type or any other fancy business. */
2769 irerror(global->context, "Invalid type for global variable `%s`: %s",
2770 global->name, type_name[global->vtype]);
2775 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2777 prog_section_def def;
2778 prog_section_field fld;
2780 def.type = field->vtype;
2781 def.offset = code_globals_elements;
2783 /* create a global named the same as the field */
2784 if (opts_standard == COMPILER_GMQCC) {
2785 /* in our standard, the global gets a dot prefix */
2786 size_t len = strlen(field->name);
2789 /* we really don't want to have to allocate this, and 1024
2790 * bytes is more than enough for a variable/field name
2792 if (len+2 >= sizeof(name)) {
2793 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
2798 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
2801 def.name = code_genstring(name);
2802 fld.name = def.name + 1; /* we reuse that string table entry */
2804 /* in plain QC, there cannot be a global with the same name,
2805 * and so we also name the global the same.
2806 * FIXME: fteqcc should create a global as well
2807 * check if it actually uses the same name. Probably does
2809 def.name = code_genstring(field->name);
2810 fld.name = def.name;
2813 field->code.name = def.name;
2815 if (code_defs_add(def) < 0)
2818 fld.type = field->fieldtype;
2820 if (fld.type == TYPE_VOID) {
2821 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
2825 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2827 if (code_fields_add(fld) < 0)
2830 ir_value_code_setaddr(field, code_globals_elements);
2831 if (!code_globals_add(fld.offset))
2833 if (fld.type == TYPE_VECTOR) {
2834 if (!code_globals_add(fld.offset+1))
2836 if (!code_globals_add(fld.offset+2))
2840 return field->code.globaladdr >= 0;
2843 bool ir_builder_generate(ir_builder *self, const char *filename)
2845 prog_section_statement stmt;
2850 for (i = 0; i < self->globals_count; ++i)
2852 if (!ir_builder_gen_global(self, self->globals[i], false)) {
2857 for (i = 0; i < self->fields_count; ++i)
2859 if (!ir_builder_gen_field(self, self->fields[i])) {
2864 /* generate function code */
2865 for (i = 0; i < self->globals_count; ++i)
2867 if (self->globals[i]->vtype == TYPE_FUNCTION) {
2868 if (!gen_global_function_code(self, self->globals[i])) {
2874 /* DP errors if the last instruction is not an INSTR_DONE
2875 * and for debugging purposes we add an additional AINSTR_END
2876 * to the end of functions, so here it goes:
2878 stmt.opcode = INSTR_DONE;
2882 if (code_statements_add(stmt) < 0)
2885 printf("writing '%s'...\n", filename);
2886 return code_write(filename);
2889 /***********************************************************************
2890 *IR DEBUG Dump functions...
2893 #define IND_BUFSZ 1024
2896 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
2898 # define strncat strncat
2901 const char *qc_opname(int op)
2903 if (op < 0) return "<INVALID>";
2904 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2905 return asm_instr[op].m;
2907 case VINSTR_PHI: return "PHI";
2908 case VINSTR_JUMP: return "JUMP";
2909 case VINSTR_COND: return "COND";
2910 default: return "<UNK>";
2914 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2917 char indent[IND_BUFSZ];
2921 oprintf("module %s\n", b->name);
2922 for (i = 0; i < b->globals_count; ++i)
2925 if (b->globals[i]->isconst)
2926 oprintf("%s = ", b->globals[i]->name);
2927 ir_value_dump(b->globals[i], oprintf);
2930 for (i = 0; i < b->functions_count; ++i)
2931 ir_function_dump(b->functions[i], indent, oprintf);
2932 oprintf("endmodule %s\n", b->name);
2935 void ir_function_dump(ir_function *f, char *ind,
2936 int (*oprintf)(const char*, ...))
2939 if (f->builtin != 0) {
2940 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2943 oprintf("%sfunction %s\n", ind, f->name);
2944 strncat(ind, "\t", IND_BUFSZ);
2945 if (f->locals_count)
2947 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2948 for (i = 0; i < f->locals_count; ++i) {
2949 oprintf("%s\t", ind);
2950 ir_value_dump(f->locals[i], oprintf);
2954 oprintf("%sliferanges:\n", ind);
2955 for (i = 0; i < f->locals_count; ++i) {
2957 ir_value *v = f->locals[i];
2958 oprintf("%s\t%s: unique ", ind, v->name);
2959 for (l = 0; l < v->life_count; ++l) {
2960 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
2964 for (i = 0; i < f->values_count; ++i) {
2966 ir_value *v = f->values[i];
2967 oprintf("%s\t%s: @%i ", ind, v->name, (int)v->code.local);
2968 for (l = 0; l < v->life_count; ++l) {
2969 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
2973 if (f->blocks_count)
2975 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2976 for (i = 0; i < f->blocks_count; ++i) {
2977 if (f->blocks[i]->run_id != f->run_id) {
2978 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2980 ir_block_dump(f->blocks[i], ind, oprintf);
2984 ind[strlen(ind)-1] = 0;
2985 oprintf("%sendfunction %s\n", ind, f->name);
2988 void ir_block_dump(ir_block* b, char *ind,
2989 int (*oprintf)(const char*, ...))
2992 oprintf("%s:%s\n", ind, b->label);
2993 strncat(ind, "\t", IND_BUFSZ);
2995 for (i = 0; i < b->instr_count; ++i)
2996 ir_instr_dump(b->instr[i], ind, oprintf);
2997 ind[strlen(ind)-1] = 0;
3000 void dump_phi(ir_instr *in, char *ind,
3001 int (*oprintf)(const char*, ...))
3004 oprintf("%s <- phi ", in->_ops[0]->name);
3005 for (i = 0; i < in->phi_count; ++i)
3007 oprintf("([%s] : %s) ", in->phi[i].from->label,
3008 in->phi[i].value->name);
3013 void ir_instr_dump(ir_instr *in, char *ind,
3014 int (*oprintf)(const char*, ...))
3017 const char *comma = NULL;
3019 oprintf("%s (%i) ", ind, (int)in->eid);
3021 if (in->opcode == VINSTR_PHI) {
3022 dump_phi(in, ind, oprintf);
3026 strncat(ind, "\t", IND_BUFSZ);
3028 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3029 ir_value_dump(in->_ops[0], oprintf);
3030 if (in->_ops[1] || in->_ops[2])
3033 if (in->opcode == INSTR_CALL0) {
3034 oprintf("CALL%i\t", in->params_count);
3036 oprintf("%s\t", qc_opname(in->opcode));
3038 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3039 ir_value_dump(in->_ops[0], oprintf);
3044 for (i = 1; i != 3; ++i) {
3048 ir_value_dump(in->_ops[i], oprintf);
3056 oprintf("[%s]", in->bops[0]->label);
3060 oprintf("%s[%s]", comma, in->bops[1]->label);
3061 if (in->params_count) {
3062 oprintf("\tparams: ");
3063 for (i = 0; i != in->params_count; ++i) {
3064 oprintf("%s, ", in->params[i]->name);
3068 ind[strlen(ind)-1] = 0;
3071 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3080 oprintf("fn:%s", v->name);
3083 oprintf("%g", v->constval.vfloat);
3086 oprintf("'%g %g %g'",
3089 v->constval.vvec.z);
3092 oprintf("(entity)");
3095 oprintf("\"%s\"", v->constval.vstring);
3099 oprintf("%i", v->constval.vint);
3104 v->constval.vpointer->name);
3108 oprintf("%s", v->name);
3112 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
3115 oprintf("Life of %s:\n", self->name);
3116 for (i = 0; i < self->life_count; ++i)
3118 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);