5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 * this software and associated documentation files (the "Software"), to deal in
7 * the Software without restriction, including without limitation the rights to
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9 * of the Software, and to permit persons to whom the Software is furnished to do
10 * so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 /***********************************************************************
29 * Type sizes used at multiple points in the IR codegen
32 size_t type_sizeof[TYPE_COUNT] = {
39 1, /* TYPE_FUNCTION */
47 MEM_VEC_FUNCTIONS(ir_value_vector, ir_value*, v)
49 /***********************************************************************
53 ir_builder* ir_builder_new(const char *modulename)
57 self = (ir_builder*)mem_a(sizeof(*self));
61 MEM_VECTOR_INIT(self, functions);
62 MEM_VECTOR_INIT(self, globals);
64 if (!ir_builder_set_name(self, modulename)) {
69 /* globals which always exist */
71 /* for now we give it a vector size */
72 ir_builder_create_global(self, "OFS_RETURN", TYPE_VARIANT);
77 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
78 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
80 void ir_builder_delete(ir_builder* self)
83 mem_d((void*)self->name);
84 for (i = 0; i != self->functions_count; ++i) {
85 ir_function_delete(self->functions[i]);
87 MEM_VECTOR_CLEAR(self, functions);
88 for (i = 0; i != self->globals_count; ++i) {
89 ir_value_delete(self->globals[i]);
91 MEM_VECTOR_CLEAR(self, globals);
95 bool ir_builder_set_name(ir_builder *self, const char *name)
98 mem_d((void*)self->name);
99 self->name = util_strdup(name);
103 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
106 for (i = 0; i < self->functions_count; ++i) {
107 if (!strcmp(name, self->functions[i]->name))
108 return self->functions[i];
113 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
115 ir_function *fn = ir_builder_get_function(self, name);
120 fn = ir_function_new(self, outtype);
121 if (!ir_function_set_name(fn, name) ||
122 !ir_builder_functions_add(self, fn) )
124 ir_function_delete(fn);
128 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
130 ir_function_delete(fn);
134 fn->value->isconst = true;
135 fn->value->outtype = outtype;
136 fn->value->constval.vfunc = fn;
137 fn->value->context = fn->context;
142 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
145 for (i = 0; i < self->globals_count; ++i) {
146 if (!strcmp(self->globals[i]->name, name))
147 return self->globals[i];
152 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
154 ir_value *ve = ir_builder_get_global(self, name);
159 ve = ir_value_var(name, store_global, vtype);
160 if (!ir_builder_globals_add(self, ve)) {
167 /***********************************************************************
171 bool ir_function_naive_phi(ir_function*);
172 void ir_function_enumerate(ir_function*);
173 bool ir_function_calculate_liferanges(ir_function*);
174 bool ir_function_allocate_locals(ir_function*);
176 ir_function* ir_function_new(ir_builder* owner, int outtype)
179 self = (ir_function*)mem_a(sizeof(*self));
185 if (!ir_function_set_name(self, "<@unnamed>")) {
190 self->context.file = "<@no context>";
191 self->context.line = 0;
192 self->outtype = outtype;
194 MEM_VECTOR_INIT(self, params);
195 MEM_VECTOR_INIT(self, blocks);
196 MEM_VECTOR_INIT(self, values);
197 MEM_VECTOR_INIT(self, locals);
202 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
203 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
204 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
206 bool ir_function_set_name(ir_function *self, const char *name)
209 mem_d((void*)self->name);
210 self->name = util_strdup(name);
214 void ir_function_delete(ir_function *self)
217 mem_d((void*)self->name);
219 for (i = 0; i != self->blocks_count; ++i)
220 ir_block_delete(self->blocks[i]);
221 MEM_VECTOR_CLEAR(self, blocks);
223 MEM_VECTOR_CLEAR(self, params);
225 for (i = 0; i != self->values_count; ++i)
226 ir_value_delete(self->values[i]);
227 MEM_VECTOR_CLEAR(self, values);
229 for (i = 0; i != self->locals_count; ++i)
230 ir_value_delete(self->locals[i]);
231 MEM_VECTOR_CLEAR(self, locals);
233 /* self->value is deleted by the builder */
238 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
240 return ir_function_values_add(self, v);
243 ir_block* ir_function_create_block(ir_function *self, const char *label)
245 ir_block* bn = ir_block_new(self, label);
246 memcpy(&bn->context, &self->context, sizeof(self->context));
247 if (!ir_function_blocks_add(self, bn)) {
254 bool ir_function_finalize(ir_function *self)
256 if (!ir_function_naive_phi(self))
259 ir_function_enumerate(self);
261 if (!ir_function_calculate_liferanges(self))
264 if (!ir_function_allocate_locals(self))
269 ir_value* ir_function_get_local(ir_function *self, const char *name)
272 for (i = 0; i < self->locals_count; ++i) {
273 if (!strcmp(self->locals[i]->name, name))
274 return self->locals[i];
279 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype)
281 ir_value *ve = ir_function_get_local(self, name);
286 ve = ir_value_var(name, store_local, vtype);
287 if (!ir_function_locals_add(self, ve)) {
294 /***********************************************************************
298 ir_block* ir_block_new(ir_function* owner, const char *name)
301 self = (ir_block*)mem_a(sizeof(*self));
305 memset(self, 0, sizeof(*self));
308 if (!ir_block_set_label(self, name)) {
313 self->context.file = "<@no context>";
314 self->context.line = 0;
316 MEM_VECTOR_INIT(self, instr);
317 MEM_VECTOR_INIT(self, entries);
318 MEM_VECTOR_INIT(self, exits);
321 self->is_return = false;
323 MEM_VECTOR_INIT(self, living);
325 self->generated = false;
329 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
330 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
331 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
332 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
334 void ir_block_delete(ir_block* self)
338 for (i = 0; i != self->instr_count; ++i)
339 ir_instr_delete(self->instr[i]);
340 MEM_VECTOR_CLEAR(self, instr);
341 MEM_VECTOR_CLEAR(self, entries);
342 MEM_VECTOR_CLEAR(self, exits);
343 MEM_VECTOR_CLEAR(self, living);
347 bool ir_block_set_label(ir_block *self, const char *name)
350 mem_d((void*)self->label);
351 self->label = util_strdup(name);
352 return !!self->label;
355 /***********************************************************************
359 ir_instr* ir_instr_new(ir_block* owner, int op)
362 self = (ir_instr*)mem_a(sizeof(*self));
367 self->context.file = "<@no context>";
368 self->context.line = 0;
370 self->_ops[0] = NULL;
371 self->_ops[1] = NULL;
372 self->_ops[2] = NULL;
373 self->bops[0] = NULL;
374 self->bops[1] = NULL;
375 MEM_VECTOR_INIT(self, phi);
376 MEM_VECTOR_INIT(self, params);
381 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
382 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
384 void ir_instr_delete(ir_instr *self)
387 /* The following calls can only delete from
388 * vectors, we still want to delete this instruction
389 * so ignore the return value. Since with the warn_unused_result attribute
390 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
391 * I have to improvise here and use if(foo());
393 for (i = 0; i < self->phi_count; ++i) {
395 if (ir_value_writes_find(self->phi[i].value, self, &idx))
396 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
397 if (ir_value_reads_find(self->phi[i].value, self, &idx))
398 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
400 MEM_VECTOR_CLEAR(self, phi);
401 for (i = 0; i < self->params_count; ++i) {
403 if (ir_value_writes_find(self->params[i], self, &idx))
404 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
405 if (ir_value_reads_find(self->params[i], self, &idx))
406 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
408 MEM_VECTOR_CLEAR(self, params);
409 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
410 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
411 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
415 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
417 if (self->_ops[op]) {
419 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
421 if (!ir_value_writes_remove(self->_ops[op], idx))
424 else if (ir_value_reads_find(self->_ops[op], self, &idx))
426 if (!ir_value_reads_remove(self->_ops[op], idx))
432 if (!ir_value_writes_add(v, self))
435 if (!ir_value_reads_add(v, self))
443 /***********************************************************************
447 ir_value* ir_value_var(const char *name, int storetype, int vtype)
450 self = (ir_value*)mem_a(sizeof(*self));
452 self->fieldtype = TYPE_VOID;
453 self->outtype = TYPE_VOID;
454 self->store = storetype;
455 MEM_VECTOR_INIT(self, reads);
456 MEM_VECTOR_INIT(self, writes);
457 self->isconst = false;
458 self->context.file = "<@no context>";
459 self->context.line = 0;
461 ir_value_set_name(self, name);
463 memset(&self->constval, 0, sizeof(self->constval));
464 memset(&self->code, 0, sizeof(self->code));
466 MEM_VECTOR_INIT(self, life);
469 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
470 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
471 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
473 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
475 ir_value *v = ir_value_var(name, storetype, vtype);
478 if (!ir_function_collect_value(owner, v))
486 void ir_value_delete(ir_value* self)
489 mem_d((void*)self->name);
492 if (self->vtype == TYPE_STRING)
493 mem_d((void*)self->constval.vstring);
495 MEM_VECTOR_CLEAR(self, reads);
496 MEM_VECTOR_CLEAR(self, writes);
497 MEM_VECTOR_CLEAR(self, life);
501 void ir_value_set_name(ir_value *self, const char *name)
504 mem_d((void*)self->name);
505 self->name = util_strdup(name);
508 bool ir_value_set_float(ir_value *self, float f)
510 if (self->vtype != TYPE_FLOAT)
512 self->constval.vfloat = f;
513 self->isconst = true;
517 bool ir_value_set_vector(ir_value *self, vector v)
519 if (self->vtype != TYPE_VECTOR)
521 self->constval.vvec = v;
522 self->isconst = true;
526 bool ir_value_set_string(ir_value *self, const char *str)
528 if (self->vtype != TYPE_STRING)
530 self->constval.vstring = util_strdup(str);
531 self->isconst = true;
536 bool ir_value_set_int(ir_value *self, int i)
538 if (self->vtype != TYPE_INTEGER)
540 self->constval.vint = i;
541 self->isconst = true;
546 bool ir_value_lives(ir_value *self, size_t at)
549 for (i = 0; i < self->life_count; ++i)
551 ir_life_entry_t *life = &self->life[i];
552 if (life->start <= at && at <= life->end)
554 if (life->start > at) /* since it's ordered */
560 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
563 if (!ir_value_life_add(self, e)) /* naive... */
565 for (k = self->life_count-1; k > idx; --k)
566 self->life[k] = self->life[k-1];
571 bool ir_value_life_merge(ir_value *self, size_t s)
574 ir_life_entry_t *life = NULL;
575 ir_life_entry_t *before = NULL;
576 ir_life_entry_t new_entry;
578 /* Find the first range >= s */
579 for (i = 0; i < self->life_count; ++i)
582 life = &self->life[i];
586 /* nothing found? append */
587 if (i == self->life_count) {
589 if (life && life->end+1 == s)
591 /* previous life range can be merged in */
595 if (life && life->end >= s)
598 if (!ir_value_life_add(self, e))
599 return false; /* failing */
605 if (before->end + 1 == s &&
606 life->start - 1 == s)
609 before->end = life->end;
610 if (!ir_value_life_remove(self, i))
611 return false; /* failing */
614 if (before->end + 1 == s)
620 /* already contained */
621 if (before->end >= s)
625 if (life->start - 1 == s)
630 /* insert a new entry */
631 new_entry.start = new_entry.end = s;
632 return ir_value_life_insert(self, i, new_entry);
635 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
639 if (!other->life_count)
642 if (!self->life_count) {
643 for (i = 0; i < other->life_count; ++i) {
644 if (!ir_value_life_add(self, other->life[i]))
651 for (i = 0; i < other->life_count; ++i)
653 const ir_life_entry_t *life = &other->life[i];
656 ir_life_entry_t *entry = &self->life[myi];
658 if (life->end+1 < entry->start)
660 /* adding an interval before entry */
661 if (!ir_value_life_insert(self, myi, *life))
667 if (life->start < entry->start &&
668 life->end >= entry->start)
670 /* starts earlier and overlaps */
671 entry->start = life->start;
674 if (life->end > entry->end &&
675 life->start-1 <= entry->end)
677 /* ends later and overlaps */
678 entry->end = life->end;
681 /* see if our change combines it with the next ranges */
682 while (myi+1 < self->life_count &&
683 entry->end+1 >= self->life[1+myi].start)
685 /* overlaps with (myi+1) */
686 if (entry->end < self->life[1+myi].end)
687 entry->end = self->life[1+myi].end;
688 if (!ir_value_life_remove(self, myi+1))
690 entry = &self->life[myi];
693 /* see if we're after the entry */
694 if (life->start > entry->end)
697 /* append if we're at the end */
698 if (myi >= self->life_count) {
699 if (!ir_value_life_add(self, *life))
703 /* otherweise check the next range */
712 bool ir_values_overlap(const ir_value *a, const ir_value *b)
714 /* For any life entry in A see if it overlaps with
715 * any life entry in B.
716 * Note that the life entries are orderes, so we can make a
717 * more efficient algorithm there than naively translating the
721 ir_life_entry_t *la, *lb, *enda, *endb;
723 /* first of all, if either has no life range, they cannot clash */
724 if (!a->life_count || !b->life_count)
729 enda = la + a->life_count;
730 endb = lb + b->life_count;
733 /* check if the entries overlap, for that,
734 * both must start before the other one ends.
736 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
737 if (la->start <= lb->end &&
738 lb->start <= la->end)
740 if (la->start < lb->end &&
747 /* entries are ordered
748 * one entry is earlier than the other
749 * that earlier entry will be moved forward
751 if (la->start < lb->start)
753 /* order: A B, move A forward
754 * check if we hit the end with A
759 else if (lb->start < la->start)
761 /* order: B A, move B forward
762 * check if we hit the end with B
771 /***********************************************************************
775 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
777 if (target->store == store_value) {
778 fprintf(stderr, "cannot store to an SSA value\n");
779 fprintf(stderr, "trying to store: %s <- %s\n", target->name, what->name);
782 ir_instr *in = ir_instr_new(self, op);
785 if (!ir_instr_op(in, 0, target, true) ||
786 !ir_instr_op(in, 1, what, false) ||
787 !ir_block_instr_add(self, in) )
795 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
799 if (target->vtype == TYPE_VARIANT)
802 vtype = target->vtype;
807 if (what->vtype == TYPE_INTEGER)
808 op = INSTR_CONV_ITOF;
817 op = INSTR_STORE_ENT;
823 op = INSTR_STORE_FLD;
827 if (what->vtype == TYPE_INTEGER)
828 op = INSTR_CONV_FTOI;
837 op = INSTR_STORE_ENT;
844 return ir_block_create_store_op(self, op, target, what);
847 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
852 if (target->vtype != TYPE_POINTER)
855 /* storing using pointer - target is a pointer, type must be
856 * inferred from source
868 op = INSTR_STOREP_ENT;
874 op = INSTR_STOREP_FLD;
885 op = INSTR_STOREP_ENT;
892 return ir_block_create_store_op(self, op, target, what);
895 bool ir_block_create_return(ir_block *self, ir_value *v)
899 fprintf(stderr, "block already ended (%s)\n", self->label);
903 self->is_return = true;
904 in = ir_instr_new(self, INSTR_RETURN);
908 if (!ir_instr_op(in, 0, v, false) ||
909 !ir_block_instr_add(self, in) )
916 bool ir_block_create_if(ir_block *self, ir_value *v,
917 ir_block *ontrue, ir_block *onfalse)
921 fprintf(stderr, "block already ended (%s)\n", self->label);
925 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
926 in = ir_instr_new(self, VINSTR_COND);
930 if (!ir_instr_op(in, 0, v, false)) {
935 in->bops[0] = ontrue;
936 in->bops[1] = onfalse;
938 if (!ir_block_instr_add(self, in))
941 if (!ir_block_exits_add(self, ontrue) ||
942 !ir_block_exits_add(self, onfalse) ||
943 !ir_block_entries_add(ontrue, self) ||
944 !ir_block_entries_add(onfalse, self) )
951 bool ir_block_create_jump(ir_block *self, ir_block *to)
955 fprintf(stderr, "block already ended (%s)\n", self->label);
959 in = ir_instr_new(self, VINSTR_JUMP);
964 if (!ir_block_instr_add(self, in))
967 if (!ir_block_exits_add(self, to) ||
968 !ir_block_entries_add(to, self) )
975 bool ir_block_create_goto(ir_block *self, ir_block *to)
979 fprintf(stderr, "block already ended (%s)\n", self->label);
983 in = ir_instr_new(self, INSTR_GOTO);
988 if (!ir_block_instr_add(self, in))
991 if (!ir_block_exits_add(self, to) ||
992 !ir_block_entries_add(to, self) )
999 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1003 in = ir_instr_new(self, VINSTR_PHI);
1006 out = ir_value_out(self->owner, label, store_value, ot);
1008 ir_instr_delete(in);
1011 if (!ir_instr_op(in, 0, out, true)) {
1012 ir_instr_delete(in);
1013 ir_value_delete(out);
1016 if (!ir_block_instr_add(self, in)) {
1017 ir_instr_delete(in);
1018 ir_value_delete(out);
1024 ir_value* ir_phi_value(ir_instr *self)
1026 return self->_ops[0];
1029 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1033 if (!ir_block_entries_find(self->owner, b, NULL)) {
1034 /* Must not be possible to cause this, otherwise the AST
1035 * is doing something wrong.
1037 fprintf(stderr, "Invalid entry block for PHI\n");
1043 if (!ir_value_reads_add(v, self))
1045 return ir_instr_phi_add(self, pe);
1048 /* call related code */
1049 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1053 in = ir_instr_new(self, INSTR_CALL0);
1056 out = ir_value_out(self->owner, label, store_value, func->outtype);
1058 ir_instr_delete(in);
1061 if (!ir_instr_op(in, 0, out, true) ||
1062 !ir_instr_op(in, 1, func, false) ||
1063 !ir_block_instr_add(self, in))
1065 ir_instr_delete(in);
1066 ir_value_delete(out);
1072 ir_value* ir_call_value(ir_instr *self)
1074 return self->_ops[0];
1077 bool ir_call_param(ir_instr* self, ir_value *v)
1079 if (!ir_instr_params_add(self, v))
1081 if (!ir_value_reads_add(v, self)) {
1082 if (!ir_instr_params_remove(self, self->params_count-1))
1083 GMQCC_SUPPRESS_EMPTY_BODY;
1089 /* binary op related code */
1091 ir_value* ir_block_create_binop(ir_block *self,
1092 const char *label, int opcode,
1093 ir_value *left, ir_value *right)
1115 case INSTR_SUB_S: /* -- offset of string as float */
1120 case INSTR_BITOR_IF:
1121 case INSTR_BITOR_FI:
1122 case INSTR_BITAND_FI:
1123 case INSTR_BITAND_IF:
1138 case INSTR_BITAND_I:
1141 case INSTR_RSHIFT_I:
1142 case INSTR_LSHIFT_I:
1164 /* boolean operations result in floats */
1165 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1167 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1170 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1175 if (ot == TYPE_VOID) {
1176 /* The AST or parser were supposed to check this! */
1180 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1183 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1184 int op, ir_value *a, ir_value *b, int outype)
1189 out = ir_value_out(self->owner, label, store_value, outype);
1193 instr = ir_instr_new(self, op);
1195 ir_value_delete(out);
1199 if (!ir_instr_op(instr, 0, out, true) ||
1200 !ir_instr_op(instr, 1, a, false) ||
1201 !ir_instr_op(instr, 2, b, false) )
1206 if (!ir_block_instr_add(self, instr))
1211 ir_instr_delete(instr);
1212 ir_value_delete(out);
1216 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1218 /* Support for various pointer types todo if so desired */
1219 if (ent->vtype != TYPE_ENTITY)
1222 if (field->vtype != TYPE_FIELD)
1225 return ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1228 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1231 if (ent->vtype != TYPE_ENTITY)
1234 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1235 if (field->vtype != TYPE_FIELD)
1240 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1241 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1242 case TYPE_STRING: op = INSTR_LOAD_S; break;
1243 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1244 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1246 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1247 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1253 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1256 ir_value* ir_block_create_add(ir_block *self,
1258 ir_value *left, ir_value *right)
1261 int l = left->vtype;
1262 int r = right->vtype;
1281 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1283 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1289 return ir_block_create_binop(self, label, op, left, right);
1292 ir_value* ir_block_create_sub(ir_block *self,
1294 ir_value *left, ir_value *right)
1297 int l = left->vtype;
1298 int r = right->vtype;
1318 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1320 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1326 return ir_block_create_binop(self, label, op, left, right);
1329 ir_value* ir_block_create_mul(ir_block *self,
1331 ir_value *left, ir_value *right)
1334 int l = left->vtype;
1335 int r = right->vtype;
1354 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1356 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1359 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1361 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1363 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1365 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1371 return ir_block_create_binop(self, label, op, left, right);
1374 ir_value* ir_block_create_div(ir_block *self,
1376 ir_value *left, ir_value *right)
1379 int l = left->vtype;
1380 int r = right->vtype;
1397 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1399 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1401 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1407 return ir_block_create_binop(self, label, op, left, right);
1410 /* PHI resolving breaks the SSA, and must thus be the last
1411 * step before life-range calculation.
1414 static bool ir_block_naive_phi(ir_block *self);
1415 bool ir_function_naive_phi(ir_function *self)
1419 for (i = 0; i < self->blocks_count; ++i)
1421 if (!ir_block_naive_phi(self->blocks[i]))
1427 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1432 /* create a store */
1433 if (!ir_block_create_store(block, old, what))
1436 /* we now move it up */
1437 instr = block->instr[block->instr_count-1];
1438 for (i = block->instr_count; i > iid; --i)
1439 block->instr[i] = block->instr[i-1];
1440 block->instr[i] = instr;
1445 static bool ir_block_naive_phi(ir_block *self)
1448 /* FIXME: optionally, create_phi can add the phis
1449 * to a list so we don't need to loop through blocks
1450 * - anyway: "don't optimize YET"
1452 for (i = 0; i < self->instr_count; ++i)
1454 ir_instr *instr = self->instr[i];
1455 if (instr->opcode != VINSTR_PHI)
1458 if (!ir_block_instr_remove(self, i))
1460 --i; /* NOTE: i+1 below */
1462 for (p = 0; p < instr->phi_count; ++p)
1464 ir_value *v = instr->phi[p].value;
1465 for (w = 0; w < v->writes_count; ++w) {
1468 if (!v->writes[w]->_ops[0])
1471 /* When the write was to a global, we have to emit a mov */
1472 old = v->writes[w]->_ops[0];
1474 /* The original instruction now writes to the PHI target local */
1475 if (v->writes[w]->_ops[0] == v)
1476 v->writes[w]->_ops[0] = instr->_ops[0];
1478 if (old->store != store_value && old->store != store_local)
1480 /* If it originally wrote to a global we need to store the value
1483 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1485 if (i+1 < self->instr_count)
1486 instr = self->instr[i+1];
1489 /* In case I forget and access instr later, it'll be NULL
1490 * when it's a problem, to make sure we crash, rather than accessing
1496 /* If it didn't, we can replace all reads by the phi target now. */
1498 for (r = 0; r < old->reads_count; ++r)
1501 ir_instr *ri = old->reads[r];
1502 for (op = 0; op < ri->phi_count; ++op) {
1503 if (ri->phi[op].value == old)
1504 ri->phi[op].value = v;
1506 for (op = 0; op < 3; ++op) {
1507 if (ri->_ops[op] == old)
1514 ir_instr_delete(instr);
1519 /***********************************************************************
1520 *IR Temp allocation code
1521 * Propagating value life ranges by walking through the function backwards
1522 * until no more changes are made.
1523 * In theory this should happen once more than once for every nested loop
1525 * Though this implementation might run an additional time for if nests.
1534 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1536 /* Enumerate instructions used by value's life-ranges
1538 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1542 for (i = 0; i < self->instr_count; ++i)
1544 self->instr[i]->eid = eid++;
1549 /* Enumerate blocks and instructions.
1550 * The block-enumeration is unordered!
1551 * We do not really use the block enumreation, however
1552 * the instruction enumeration is important for life-ranges.
1554 void ir_function_enumerate(ir_function *self)
1557 size_t instruction_id = 0;
1558 for (i = 0; i < self->blocks_count; ++i)
1560 self->blocks[i]->eid = i;
1561 self->blocks[i]->run_id = 0;
1562 ir_block_enumerate(self->blocks[i], &instruction_id);
1566 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1567 bool ir_function_calculate_liferanges(ir_function *self)
1575 for (i = 0; i != self->blocks_count; ++i)
1577 if (self->blocks[i]->is_return)
1579 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1587 /* Local-value allocator
1588 * After finishing creating the liferange of all values used in a function
1589 * we can allocate their global-positions.
1590 * This is the counterpart to register-allocation in register machines.
1593 MEM_VECTOR_MAKE(ir_value*, locals);
1594 MEM_VECTOR_MAKE(size_t, sizes);
1595 MEM_VECTOR_MAKE(size_t, positions);
1596 } function_allocator;
1597 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1598 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1599 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1601 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1604 size_t vsize = type_sizeof[var->vtype];
1606 slot = ir_value_var("reg", store_global, var->vtype);
1610 if (!ir_value_life_merge_into(slot, var))
1613 if (!function_allocator_locals_add(alloc, slot))
1616 if (!function_allocator_sizes_add(alloc, vsize))
1622 ir_value_delete(slot);
1626 bool ir_function_allocate_locals(ir_function *self)
1635 function_allocator alloc;
1637 MEM_VECTOR_INIT(&alloc, locals);
1638 MEM_VECTOR_INIT(&alloc, sizes);
1639 MEM_VECTOR_INIT(&alloc, positions);
1641 for (i = 0; i < self->locals_count; ++i)
1643 if (!function_allocator_alloc(&alloc, self->locals[i]))
1647 /* Allocate a slot for any value that still exists */
1648 for (i = 0; i < self->values_count; ++i)
1650 v = self->values[i];
1655 for (a = 0; a < alloc.locals_count; ++a)
1657 slot = alloc.locals[a];
1659 if (ir_values_overlap(v, slot))
1662 if (!ir_value_life_merge_into(slot, v))
1665 /* adjust size for this slot */
1666 if (alloc.sizes[a] < type_sizeof[v->vtype])
1667 alloc.sizes[a] = type_sizeof[v->vtype];
1669 self->values[i]->code.local = a;
1672 if (a >= alloc.locals_count) {
1673 self->values[i]->code.local = alloc.locals_count;
1674 if (!function_allocator_alloc(&alloc, v))
1679 /* Adjust slot positions based on sizes */
1680 if (!function_allocator_positions_add(&alloc, 0))
1683 if (alloc.sizes_count)
1684 pos = alloc.positions[0] + alloc.sizes[0];
1687 for (i = 1; i < alloc.sizes_count; ++i)
1689 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1690 if (!function_allocator_positions_add(&alloc, pos))
1694 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1696 /* Take over the actual slot positions */
1697 for (i = 0; i < self->values_count; ++i)
1698 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1705 for (i = 0; i < alloc.locals_count; ++i)
1706 ir_value_delete(alloc.locals[i]);
1707 MEM_VECTOR_CLEAR(&alloc, locals);
1708 MEM_VECTOR_CLEAR(&alloc, sizes);
1709 MEM_VECTOR_CLEAR(&alloc, positions);
1713 /* Get information about which operand
1714 * is read from, or written to.
1716 static void ir_op_read_write(int op, size_t *read, size_t *write)
1743 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1746 bool changed = false;
1748 for (i = 0; i != self->living_count; ++i)
1750 tempbool = ir_value_life_merge(self->living[i], eid);
1753 fprintf(stderr, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1755 changed = changed || tempbool;
1760 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1763 /* values which have been read in a previous iteration are now
1764 * in the "living" array even if the previous block doesn't use them.
1765 * So we have to remove whatever does not exist in the previous block.
1766 * They will be re-added on-read, but the liferange merge won't cause
1769 for (i = 0; i < self->living_count; ++i)
1771 if (!ir_block_living_find(prev, self->living[i], NULL)) {
1772 if (!ir_block_living_remove(self, i))
1778 /* Whatever the previous block still has in its living set
1779 * must now be added to ours as well.
1781 for (i = 0; i < prev->living_count; ++i)
1783 if (ir_block_living_find(self, prev->living[i], NULL))
1785 if (!ir_block_living_add(self, prev->living[i]))
1788 printf("%s got from prev: %s\n", self->label, prev->living[i]->_name);
1794 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
1800 /* bitmasks which operands are read from or written to */
1802 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1804 new_reads_t new_reads;
1806 char dbg_ind[16] = { '#', '0' };
1809 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1810 MEM_VECTOR_INIT(&new_reads, v);
1815 if (!ir_block_life_prop_previous(self, prev, changed))
1819 i = self->instr_count;
1822 instr = self->instr[i];
1824 /* PHI operands are always read operands */
1825 for (p = 0; p < instr->phi_count; ++p)
1827 value = instr->phi[p].value;
1828 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1829 if (!ir_block_living_find(self, value, NULL) &&
1830 !ir_block_living_add(self, value))
1835 if (!new_reads_t_v_find(&new_reads, value, NULL))
1837 if (!new_reads_t_v_add(&new_reads, value))
1843 /* See which operands are read and write operands */
1844 ir_op_read_write(instr->opcode, &read, &write);
1846 /* Go through the 3 main operands */
1847 for (o = 0; o < 3; ++o)
1849 if (!instr->_ops[o]) /* no such operand */
1852 value = instr->_ops[o];
1854 /* We only care about locals */
1855 if (value->store != store_value &&
1856 value->store != store_local)
1862 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1863 if (!ir_block_living_find(self, value, NULL) &&
1864 !ir_block_living_add(self, value))
1869 /* fprintf(stderr, "read: %s\n", value->_name); */
1870 if (!new_reads_t_v_find(&new_reads, value, NULL))
1872 if (!new_reads_t_v_add(&new_reads, value))
1878 /* write operands */
1879 /* When we write to a local, we consider it "dead" for the
1880 * remaining upper part of the function, since in SSA a value
1881 * can only be written once (== created)
1886 bool in_living = ir_block_living_find(self, value, &idx);
1887 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1889 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
1890 if (!in_living && !in_reads)
1895 /* If the value isn't alive it hasn't been read before... */
1896 /* TODO: See if the warning can be emitted during parsing or AST processing
1897 * otherwise have warning printed here.
1898 * IF printing a warning here: include filecontext_t,
1899 * and make sure it's only printed once
1900 * since this function is run multiple times.
1902 /* For now: debug info: */
1903 fprintf(stderr, "Value only written %s\n", value->name);
1904 tempbool = ir_value_life_merge(value, instr->eid);
1905 *changed = *changed || tempbool;
1907 ir_instr_dump(instr, dbg_ind, printf);
1911 /* since 'living' won't contain it
1912 * anymore, merge the value, since
1915 tempbool = ir_value_life_merge(value, instr->eid);
1918 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
1920 *changed = *changed || tempbool;
1922 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1923 if (!ir_block_living_remove(self, idx))
1928 if (!new_reads_t_v_remove(&new_reads, readidx))
1936 tempbool = ir_block_living_add_instr(self, instr->eid);
1937 /*fprintf(stderr, "living added values\n");*/
1938 *changed = *changed || tempbool;
1940 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1942 for (rd = 0; rd < new_reads.v_count; ++rd)
1944 if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
1945 if (!ir_block_living_add(self, new_reads.v[rd]))
1948 if (!i && !self->entries_count) {
1950 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
1953 MEM_VECTOR_CLEAR(&new_reads, v);
1957 if (self->run_id == self->owner->run_id)
1960 self->run_id = self->owner->run_id;
1962 for (i = 0; i < self->entries_count; ++i)
1964 ir_block *entry = self->entries[i];
1965 ir_block_life_propagate(entry, self, changed);
1970 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1971 MEM_VECTOR_CLEAR(&new_reads, v);
1976 /***********************************************************************
1979 * Since the IR has the convention of putting 'write' operands
1980 * at the beginning, we have to rotate the operands of instructions
1981 * properly in order to generate valid QCVM code.
1983 * Having destinations at a fixed position is more convenient. In QC
1984 * this is *mostly* OPC, but FTE adds at least 2 instructions which
1985 * read from from OPA, and store to OPB rather than OPC. Which is
1986 * partially the reason why the implementation of these instructions
1987 * in darkplaces has been delayed for so long.
1989 * Breaking conventions is annoying...
1991 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
1993 static bool gen_global_field(ir_value *global)
1995 if (global->isconst)
1997 ir_value *fld = global->constval.vpointer;
1999 printf("Invalid field constant with no field: %s\n", global->name);
2003 /* Now, in this case, a relocation would be impossible to code
2004 * since it looks like this:
2005 * .vector v = origin; <- parse error, wtf is 'origin'?
2008 * But we will need a general relocation support later anyway
2009 * for functions... might as well support that here.
2011 if (!fld->code.globaladdr) {
2012 printf("FIXME: Relocation support\n");
2016 /* copy the field's value */
2017 global->code.globaladdr = code_globals_add(code_globals_data[fld->code.globaladdr]);
2021 prog_section_field fld;
2023 fld.name = global->code.name;
2024 fld.offset = code_fields_elements;
2025 fld.type = global->fieldtype;
2027 if (fld.type == TYPE_VOID) {
2028 printf("Field is missing a type: %s\n", global->name);
2032 if (code_fields_add(fld) < 0)
2035 global->code.globaladdr = code_globals_add(fld.offset);
2037 if (global->code.globaladdr < 0)
2042 static bool gen_global_pointer(ir_value *global)
2044 if (global->isconst)
2046 ir_value *target = global->constval.vpointer;
2048 printf("Invalid pointer constant: %s\n", global->name);
2049 /* NULL pointers are pointing to the NULL constant, which also
2050 * sits at address 0, but still has an ir_value for itself.
2055 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2056 * void() foo; <- proto
2057 * void() *fooptr = &foo;
2058 * void() foo = { code }
2060 if (!target->code.globaladdr) {
2061 /* FIXME: Check for the constant nullptr ir_value!
2062 * because then code.globaladdr being 0 is valid.
2064 printf("FIXME: Relocation support\n");
2068 global->code.globaladdr = code_globals_add(target->code.globaladdr);
2072 global->code.globaladdr = code_globals_add(0);
2074 if (global->code.globaladdr < 0)
2079 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2081 prog_section_statement stmt;
2090 block->generated = true;
2091 block->code_start = code_statements_elements;
2092 for (i = 0; i < block->instr_count; ++i)
2094 instr = block->instr[i];
2096 if (instr->opcode == VINSTR_PHI) {
2097 printf("cannot generate virtual instruction (phi)\n");
2101 if (instr->opcode == VINSTR_JUMP) {
2102 target = instr->bops[0];
2103 /* for uncoditional jumps, if the target hasn't been generated
2104 * yet, we generate them right here.
2106 if (!target->generated) {
2111 /* otherwise we generate a jump instruction */
2112 stmt.opcode = INSTR_GOTO;
2113 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2116 if (code_statements_add(stmt) < 0)
2119 /* no further instructions can be in this block */
2123 if (instr->opcode == VINSTR_COND) {
2124 ontrue = instr->bops[0];
2125 onfalse = instr->bops[1];
2126 /* TODO: have the AST signal which block should
2127 * come first: eg. optimize IFs without ELSE...
2130 stmt.o1.u1 = instr->_ops[0]->code.globaladdr;
2134 if (ontrue->generated) {
2135 stmt.opcode = INSTR_IF;
2136 stmt.o2.s1 = (ontrue->code_start-1) - code_statements_elements;
2137 if (code_statements_add(stmt) < 0)
2140 if (onfalse->generated) {
2141 stmt.opcode = INSTR_IFNOT;
2142 stmt.o2.s1 = (onfalse->code_start-1) - code_statements_elements;
2143 if (code_statements_add(stmt) < 0)
2146 if (!ontrue->generated) {
2147 if (onfalse->generated) {
2152 if (!onfalse->generated) {
2153 if (ontrue->generated) {
2158 /* neither ontrue nor onfalse exist */
2159 stmt.opcode = INSTR_IFNOT;
2160 stidx = code_statements_elements;
2161 if (code_statements_add(stmt) < 0)
2163 /* on false we jump, so add ontrue-path */
2164 if (!gen_blocks_recursive(func, ontrue))
2166 /* fixup the jump address */
2167 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2168 /* generate onfalse path */
2169 if (onfalse->generated) {
2170 /* fixup the jump address */
2171 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2172 /* may have been generated in the previous recursive call */
2173 stmt.opcode = INSTR_GOTO;
2174 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2177 return (code_statements_add(stmt) >= 0);
2179 /* if not, generate now */
2184 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2185 /* Trivial call translation:
2186 * copy all params to OFS_PARM*
2188 * NOTES on how to do it better without much trouble:
2189 * -) The liferanges!
2190 * Simply check the liferange of all parameters for
2191 * other CALLs. For each param with no CALL in its
2192 * liferange, we can store it in an OFS_PARM at
2193 * generation already. This would even include later
2194 * reuse.... probably... :)
2196 printf("TODO: call instruction\n");
2200 if (instr->opcode == INSTR_STATE) {
2201 printf("TODO: state instruction\n");
2205 stmt.opcode = instr->opcode;
2210 /* This is the general order of operands */
2212 stmt.o3.u1 = instr->_ops[0]->code.globaladdr;
2215 stmt.o1.u1 = instr->_ops[1]->code.globaladdr;
2218 stmt.o2.u1 = instr->_ops[2]->code.globaladdr;
2220 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2222 stmt.o1.u1 = stmt.o3.u1;
2225 else if ((stmt.opcode >= INSTR_STORE_F &&
2226 stmt.opcode <= INSTR_STORE_FNC) ||
2227 (stmt.opcode >= INSTR_NOT_F &&
2228 stmt.opcode <= INSTR_NOT_FNC))
2230 /* 2-operand instructions with A -> B */
2231 stmt.o2.u1 = stmt.o3.u1;
2235 if (code_statements_add(stmt) < 0)
2241 static bool gen_function_code(ir_function *self)
2245 /* Starting from entry point, we generate blocks "as they come"
2246 * for now. Dead blocks will not be translated obviously.
2248 if (!self->blocks_count) {
2249 printf("Function '%s' declared without body.\n", self->name);
2253 block = self->blocks[0];
2254 if (block->generated)
2257 if (!gen_blocks_recursive(self, block)) {
2258 printf("failed to generate blocks for '%s'\n", self->name);
2264 static bool gen_global_function(ir_builder *ir, ir_value *global)
2266 prog_section_function fun;
2270 size_t local_var_end;
2272 if (!global->isconst ||
2273 !global->constval.vfunc)
2275 printf("Invalid state of function-global: not constant: %s\n", global->name);
2279 irfun = global->constval.vfunc;
2281 fun.name = global->code.name;
2282 fun.file = code_cachedstring(global->context.file);
2283 fun.profile = 0; /* always 0 */
2284 fun.nargs = irfun->params_count;
2286 for (i = 0;i < 8; ++i) {
2289 else if (irfun->params[i] == TYPE_VECTOR)
2295 fun.firstlocal = code_globals_elements;
2296 fun.locals = irfun->allocated_locals + irfun->locals_count;
2299 for (i = 0; i < irfun->locals_count; ++i) {
2300 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2301 printf("Failed to generate global %s\n", irfun->locals[i]->name);
2305 if (irfun->locals_count) {
2306 ir_value *last = irfun->locals[irfun->locals_count-1];
2307 local_var_end = last->code.globaladdr;
2308 local_var_end += type_sizeof[last->vtype];
2310 for (i = 0; i < irfun->values_count; ++i)
2312 /* generate code.globaladdr for ssa values */
2313 ir_value *v = irfun->values[i];
2314 v->code.globaladdr = local_var_end + v->code.local;
2316 for (i = 0; i < irfun->locals_count; ++i) {
2317 /* fill the locals with zeros */
2318 code_globals_add(0);
2321 fun.entry = code_statements_elements;
2322 if (!gen_function_code(irfun)) {
2323 printf("Failed to generate code for function %s\n", irfun->name);
2327 return (code_functions_add(fun) >= 0);
2330 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2333 prog_section_def def;
2335 def.type = global->vtype;
2336 def.offset = code_globals_elements;
2337 def.name = global->code.name = code_genstring(global->name);
2339 switch (global->vtype)
2342 if (code_defs_add(def) < 0)
2344 return gen_global_pointer(global);
2346 if (code_defs_add(def) < 0)
2348 return gen_global_field(global);
2353 if (code_defs_add(def) < 0)
2356 if (global->isconst) {
2357 iptr = (int32_t*)&global->constval.vfloat;
2358 global->code.globaladdr = code_globals_add(*iptr);
2360 global->code.globaladdr = code_globals_add(0);
2362 return global->code.globaladdr >= 0;
2366 if (code_defs_add(def) < 0)
2368 if (global->isconst)
2369 global->code.globaladdr = code_globals_add(code_cachedstring(global->constval.vstring));
2371 global->code.globaladdr = code_globals_add(0);
2372 return global->code.globaladdr >= 0;
2376 if (code_defs_add(def) < 0)
2379 if (global->isconst) {
2380 iptr = (int32_t*)&global->constval.vvec;
2381 global->code.globaladdr = code_globals_add(iptr[0]);
2382 if (code_globals_add(iptr[1]) < 0 || code_globals_add(iptr[2]) < 0)
2385 global->code.globaladdr = code_globals_add(0);
2386 if (code_globals_add(0) < 0 || code_globals_add(0) < 0)
2389 return global->code.globaladdr >= 0;
2392 if (code_defs_add(def) < 0)
2394 code_globals_add(code_functions_elements);
2395 return gen_global_function(self, global);
2397 /* assume biggest type */
2398 global->code.globaladdr = code_globals_add(0);
2399 code_globals_add(0);
2400 code_globals_add(0);
2403 /* refuse to create 'void' type or any other fancy business. */
2404 printf("Invalid type for global variable %s\n", global->name);
2409 bool ir_builder_generate(ir_builder *self, const char *filename)
2415 for (i = 0; i < self->globals_count; ++i)
2417 if (!ir_builder_gen_global(self, self->globals[i])) {
2422 printf("writing '%s'...\n", filename);
2423 return code_write(filename);
2426 /***********************************************************************
2427 *IR DEBUG Dump functions...
2430 #define IND_BUFSZ 1024
2432 const char *qc_opname(int op)
2434 if (op < 0) return "<INVALID>";
2435 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2436 return asm_instr[op].m;
2438 case VINSTR_PHI: return "PHI";
2439 case VINSTR_JUMP: return "JUMP";
2440 case VINSTR_COND: return "COND";
2441 default: return "<UNK>";
2445 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2448 char indent[IND_BUFSZ];
2452 oprintf("module %s\n", b->name);
2453 for (i = 0; i < b->globals_count; ++i)
2456 if (b->globals[i]->isconst)
2457 oprintf("%s = ", b->globals[i]->name);
2458 ir_value_dump(b->globals[i], oprintf);
2461 for (i = 0; i < b->functions_count; ++i)
2462 ir_function_dump(b->functions[i], indent, oprintf);
2463 oprintf("endmodule %s\n", b->name);
2466 void ir_function_dump(ir_function *f, char *ind,
2467 int (*oprintf)(const char*, ...))
2470 oprintf("%sfunction %s\n", ind, f->name);
2471 strncat(ind, "\t", IND_BUFSZ);
2472 if (f->locals_count)
2474 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2475 for (i = 0; i < f->locals_count; ++i) {
2476 oprintf("%s\t", ind);
2477 ir_value_dump(f->locals[i], oprintf);
2481 if (f->blocks_count)
2483 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2484 for (i = 0; i < f->blocks_count; ++i) {
2485 if (f->blocks[i]->run_id != f->run_id) {
2486 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2488 ir_block_dump(f->blocks[i], ind, oprintf);
2492 ind[strlen(ind)-1] = 0;
2493 oprintf("%sendfunction %s\n", ind, f->name);
2496 void ir_block_dump(ir_block* b, char *ind,
2497 int (*oprintf)(const char*, ...))
2500 oprintf("%s:%s\n", ind, b->label);
2501 strncat(ind, "\t", IND_BUFSZ);
2503 for (i = 0; i < b->instr_count; ++i)
2504 ir_instr_dump(b->instr[i], ind, oprintf);
2505 ind[strlen(ind)-1] = 0;
2508 void dump_phi(ir_instr *in, char *ind,
2509 int (*oprintf)(const char*, ...))
2512 oprintf("%s <- phi ", in->_ops[0]->name);
2513 for (i = 0; i < in->phi_count; ++i)
2515 oprintf("([%s] : %s) ", in->phi[i].from->label,
2516 in->phi[i].value->name);
2521 void ir_instr_dump(ir_instr *in, char *ind,
2522 int (*oprintf)(const char*, ...))
2525 const char *comma = NULL;
2527 oprintf("%s (%i) ", ind, (int)in->eid);
2529 if (in->opcode == VINSTR_PHI) {
2530 dump_phi(in, ind, oprintf);
2534 strncat(ind, "\t", IND_BUFSZ);
2536 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2537 ir_value_dump(in->_ops[0], oprintf);
2538 if (in->_ops[1] || in->_ops[2])
2541 oprintf("%s\t", qc_opname(in->opcode));
2542 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2543 ir_value_dump(in->_ops[0], oprintf);
2548 for (i = 1; i != 3; ++i) {
2552 ir_value_dump(in->_ops[i], oprintf);
2560 oprintf("[%s]", in->bops[0]->label);
2564 oprintf("%s[%s]", comma, in->bops[1]->label);
2566 ind[strlen(ind)-1] = 0;
2569 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
2577 oprintf("%g", v->constval.vfloat);
2580 oprintf("'%g %g %g'",
2583 v->constval.vvec.z);
2586 oprintf("(entity)");
2589 oprintf("\"%s\"", v->constval.vstring);
2593 oprintf("%i", v->constval.vint);
2598 v->constval.vpointer->name);
2602 oprintf("%s", v->name);
2606 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
2609 oprintf("Life of %s:\n", self->name);
2610 for (i = 0; i < self->life_count; ++i)
2612 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);