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 /***********************************************************************
32 ir_builder* ir_builder_new(const char *modulename)
36 self = (ir_builder*)mem_a(sizeof(*self));
40 MEM_VECTOR_INIT(self, functions);
41 MEM_VECTOR_INIT(self, globals);
43 if (!ir_builder_set_name(self, modulename)) {
48 /* globals which always exist */
50 /* for now we give it a vector size */
51 ir_builder_create_global(self, "OFS_RETURN", TYPE_VARIANT);
56 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
57 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
59 void ir_builder_delete(ir_builder* self)
62 mem_d((void*)self->name);
63 for (i = 0; i != self->functions_count; ++i) {
64 ir_function_delete(self->functions[i]);
66 MEM_VECTOR_CLEAR(self, functions);
67 for (i = 0; i != self->globals_count; ++i) {
68 ir_value_delete(self->globals[i]);
70 MEM_VECTOR_CLEAR(self, globals);
74 bool ir_builder_set_name(ir_builder *self, const char *name)
77 mem_d((void*)self->name);
78 self->name = util_strdup(name);
82 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
85 for (i = 0; i < self->functions_count; ++i) {
86 if (!strcmp(name, self->functions[i]->name))
87 return self->functions[i];
92 ir_function* ir_builder_create_function(ir_builder *self, const char *name)
94 ir_function *fn = ir_builder_get_function(self, name);
99 fn = ir_function_new(self);
100 if (!ir_function_set_name(fn, name) ||
101 !ir_builder_functions_add(self, fn) )
103 ir_function_delete(fn);
109 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
112 for (i = 0; i < self->globals_count; ++i) {
113 if (!strcmp(self->globals[i]->name, name))
114 return self->globals[i];
119 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
121 ir_value *ve = ir_builder_get_global(self, name);
126 ve = ir_value_var(name, store_global, vtype);
127 if (!ir_builder_globals_add(self, ve)) {
134 /***********************************************************************
138 bool ir_function_naive_phi(ir_function*);
139 void ir_function_enumerate(ir_function*);
140 bool ir_function_calculate_liferanges(ir_function*);
142 ir_function* ir_function_new(ir_builder* owner)
145 self = (ir_function*)mem_a(sizeof(*self));
151 if (!ir_function_set_name(self, "<@unnamed>")) {
156 self->context.file = "<@no context>";
157 self->context.line = 0;
158 self->retype = TYPE_VOID;
159 MEM_VECTOR_INIT(self, params);
160 MEM_VECTOR_INIT(self, blocks);
161 MEM_VECTOR_INIT(self, values);
162 MEM_VECTOR_INIT(self, locals);
167 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
168 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
169 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
171 bool ir_function_set_name(ir_function *self, const char *name)
174 mem_d((void*)self->name);
175 self->name = util_strdup(name);
179 void ir_function_delete(ir_function *self)
182 mem_d((void*)self->name);
184 for (i = 0; i != self->blocks_count; ++i)
185 ir_block_delete(self->blocks[i]);
186 MEM_VECTOR_CLEAR(self, blocks);
188 MEM_VECTOR_CLEAR(self, params);
190 for (i = 0; i != self->values_count; ++i)
191 ir_value_delete(self->values[i]);
192 MEM_VECTOR_CLEAR(self, values);
194 for (i = 0; i != self->locals_count; ++i)
195 ir_value_delete(self->locals[i]);
196 MEM_VECTOR_CLEAR(self, locals);
201 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
203 return ir_function_values_add(self, v);
206 ir_block* ir_function_create_block(ir_function *self, const char *label)
208 ir_block* bn = ir_block_new(self, label);
209 memcpy(&bn->context, &self->context, sizeof(self->context));
210 if (!ir_function_blocks_add(self, bn)) {
217 bool ir_function_finalize(ir_function *self)
219 if (!ir_function_naive_phi(self))
222 ir_function_enumerate(self);
224 if (!ir_function_calculate_liferanges(self))
229 ir_value* ir_function_get_local(ir_function *self, const char *name)
232 for (i = 0; i < self->locals_count; ++i) {
233 if (!strcmp(self->locals[i]->name, name))
234 return self->locals[i];
239 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype)
241 ir_value *ve = ir_function_get_local(self, name);
246 ve = ir_value_var(name, store_local, vtype);
247 if (!ir_function_locals_add(self, ve)) {
254 /***********************************************************************
258 ir_block* ir_block_new(ir_function* owner, const char *name)
261 self = (ir_block*)mem_a(sizeof(*self));
265 memset(self, 0, sizeof(*self));
268 if (!ir_block_set_label(self, name)) {
273 self->context.file = "<@no context>";
274 self->context.line = 0;
276 MEM_VECTOR_INIT(self, instr);
277 MEM_VECTOR_INIT(self, entries);
278 MEM_VECTOR_INIT(self, exits);
281 self->is_return = false;
283 MEM_VECTOR_INIT(self, living);
285 self->generated = false;
289 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
290 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
291 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
292 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
294 void ir_block_delete(ir_block* self)
298 for (i = 0; i != self->instr_count; ++i)
299 ir_instr_delete(self->instr[i]);
300 MEM_VECTOR_CLEAR(self, instr);
301 MEM_VECTOR_CLEAR(self, entries);
302 MEM_VECTOR_CLEAR(self, exits);
303 MEM_VECTOR_CLEAR(self, living);
307 bool ir_block_set_label(ir_block *self, const char *name)
310 mem_d((void*)self->label);
311 self->label = util_strdup(name);
312 return !!self->label;
315 /***********************************************************************
319 ir_instr* ir_instr_new(ir_block* owner, int op)
322 self = (ir_instr*)mem_a(sizeof(*self));
327 self->context.file = "<@no context>";
328 self->context.line = 0;
330 self->_ops[0] = NULL;
331 self->_ops[1] = NULL;
332 self->_ops[2] = NULL;
333 self->bops[0] = NULL;
334 self->bops[1] = NULL;
335 MEM_VECTOR_INIT(self, phi);
340 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
342 void ir_instr_delete(ir_instr *self)
345 /* The following calls can only delete from
346 * vectors, we still want to delete this instruction
347 * so ignore the return value. Since with the warn_unused_result attribute
348 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
349 * I have to improvise here and use if(foo());
351 for (i = 0; i < self->phi_count; ++i) {
353 if (ir_value_writes_find(self->phi[i].value, self, &idx))
354 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPRESS_EMPTY_BODY;
355 if (ir_value_reads_find(self->phi[i].value, self, &idx))
356 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPRESS_EMPTY_BODY;
358 MEM_VECTOR_CLEAR(self, phi);
359 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPRESS_EMPTY_BODY;
360 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPRESS_EMPTY_BODY;
361 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPRESS_EMPTY_BODY;
365 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
367 if (self->_ops[op]) {
369 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
371 if (!ir_value_writes_remove(self->_ops[op], idx))
374 else if (ir_value_reads_find(self->_ops[op], self, &idx))
376 if (!ir_value_reads_remove(self->_ops[op], idx))
382 if (!ir_value_writes_add(v, self))
385 if (!ir_value_reads_add(v, self))
393 /***********************************************************************
397 ir_value* ir_value_var(const char *name, int storetype, int vtype)
400 self = (ir_value*)mem_a(sizeof(*self));
402 self->fieldtype = TYPE_VOID;
403 self->store = storetype;
404 MEM_VECTOR_INIT(self, reads);
405 MEM_VECTOR_INIT(self, writes);
406 self->isconst = false;
407 self->context.file = "<@no context>";
408 self->context.line = 0;
410 ir_value_set_name(self, name);
412 memset(&self->constval, 0, sizeof(self->constval));
413 memset(&self->code, 0, sizeof(self->code));
415 MEM_VECTOR_INIT(self, life);
418 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
419 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
420 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
422 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
424 ir_value *v = ir_value_var(name, storetype, vtype);
427 if (!ir_function_collect_value(owner, v))
435 void ir_value_delete(ir_value* self)
437 mem_d((void*)self->name);
440 if (self->vtype == TYPE_STRING)
441 mem_d((void*)self->constval.vstring);
443 MEM_VECTOR_CLEAR(self, reads);
444 MEM_VECTOR_CLEAR(self, writes);
445 MEM_VECTOR_CLEAR(self, life);
449 void ir_value_set_name(ir_value *self, const char *name)
452 mem_d((void*)self->name);
453 self->name = util_strdup(name);
456 bool ir_value_set_float(ir_value *self, float f)
458 if (self->vtype != TYPE_FLOAT)
460 self->constval.vfloat = f;
461 self->isconst = true;
465 bool ir_value_set_vector(ir_value *self, vector v)
467 if (self->vtype != TYPE_VECTOR)
469 self->constval.vvec = v;
470 self->isconst = true;
474 bool ir_value_set_string(ir_value *self, const char *str)
476 if (self->vtype != TYPE_STRING)
478 self->constval.vstring = util_strdup(str);
479 self->isconst = true;
484 bool ir_value_set_int(ir_value *self, int i)
486 if (self->vtype != TYPE_INTEGER)
488 self->constval.vint = i;
489 self->isconst = true;
494 bool ir_value_lives(ir_value *self, size_t at)
497 for (i = 0; i < self->life_count; ++i)
499 ir_life_entry_t *life = &self->life[i];
500 if (life->start <= at && at <= life->end)
502 if (life->start > at) /* since it's ordered */
508 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
511 if (!ir_value_life_add(self, e)) /* naive... */
513 for (k = self->life_count-1; k > idx; --k)
514 self->life[k] = self->life[k-1];
519 bool ir_value_life_merge(ir_value *self, size_t s)
522 ir_life_entry_t *life = NULL;
523 ir_life_entry_t *before = NULL;
524 ir_life_entry_t new_entry;
526 /* Find the first range >= s */
527 for (i = 0; i < self->life_count; ++i)
530 life = &self->life[i];
534 /* nothing found? append */
535 if (i == self->life_count) {
537 if (life && life->end+1 == s)
539 /* previous life range can be merged in */
543 if (life && life->end >= s)
546 if (!ir_value_life_add(self, e))
547 return false; /* failing */
553 if (before->end + 1 == s &&
554 life->start - 1 == s)
557 before->end = life->end;
558 if (!ir_value_life_remove(self, i))
559 return false; /* failing */
562 if (before->end + 1 == s)
568 /* already contained */
569 if (before->end >= s)
573 if (life->start - 1 == s)
578 /* insert a new entry */
579 new_entry.start = new_entry.end = s;
580 return ir_value_life_insert(self, i, new_entry);
583 bool ir_values_overlap(ir_value *a, ir_value *b)
585 /* For any life entry in A see if it overlaps with
586 * any life entry in B.
587 * Note that the life entries are orderes, so we can make a
588 * more efficient algorithm there than naively translating the
592 ir_life_entry_t *la, *lb, *enda, *endb;
594 /* first of all, if either has no life range, they cannot clash */
595 if (!a->life_count || !b->life_count)
600 enda = la + a->life_count;
601 endb = lb + b->life_count;
604 /* check if the entries overlap, for that,
605 * both must start before the other one ends.
607 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
608 if (la->start <= lb->end &&
609 lb->start <= la->end)
611 if (la->start < lb->end &&
618 /* entries are ordered
619 * one entry is earlier than the other
620 * that earlier entry will be moved forward
622 if (la->end < lb->end)
624 /* order: A B, move A forward
625 * check if we hit the end with A
630 else if (lb->end < la->end)
632 /* order: B A, move B forward
633 * check if we hit the end with B
642 /***********************************************************************
646 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
648 if (target->store == store_value) {
649 fprintf(stderr, "cannot store to an SSA value\n");
650 fprintf(stderr, "trying to store: %s <- %s\n", target->name, what->name);
653 ir_instr *in = ir_instr_new(self, op);
656 if (!ir_instr_op(in, 0, target, true) ||
657 !ir_instr_op(in, 1, what, false) ||
658 !ir_block_instr_add(self, in) )
666 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
670 if (target->vtype == TYPE_VARIANT)
673 vtype = target->vtype;
678 if (what->vtype == TYPE_INTEGER)
679 op = INSTR_CONV_ITOF;
688 op = INSTR_STORE_ENT;
694 op = INSTR_STORE_FLD;
698 if (what->vtype == TYPE_INTEGER)
699 op = INSTR_CONV_FTOI;
708 op = INSTR_STORE_ENT;
715 return ir_block_create_store_op(self, op, target, what);
718 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
723 if (target->vtype != TYPE_POINTER)
726 /* storing using pointer - target is a pointer, type must be
727 * inferred from source
739 op = INSTR_STOREP_ENT;
745 op = INSTR_STOREP_FLD;
756 op = INSTR_STOREP_ENT;
763 return ir_block_create_store_op(self, op, target, what);
766 bool ir_block_create_return(ir_block *self, ir_value *v)
770 fprintf(stderr, "block already ended (%s)\n", self->label);
774 self->is_return = true;
775 in = ir_instr_new(self, INSTR_RETURN);
779 if (!ir_instr_op(in, 0, v, false) ||
780 !ir_block_instr_add(self, in) )
787 bool ir_block_create_if(ir_block *self, ir_value *v,
788 ir_block *ontrue, ir_block *onfalse)
792 fprintf(stderr, "block already ended (%s)\n", self->label);
796 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
797 in = ir_instr_new(self, VINSTR_COND);
801 if (!ir_instr_op(in, 0, v, false)) {
806 in->bops[0] = ontrue;
807 in->bops[1] = onfalse;
809 if (!ir_block_instr_add(self, in))
812 if (!ir_block_exits_add(self, ontrue) ||
813 !ir_block_exits_add(self, onfalse) ||
814 !ir_block_entries_add(ontrue, self) ||
815 !ir_block_entries_add(onfalse, self) )
822 bool ir_block_create_jump(ir_block *self, ir_block *to)
826 fprintf(stderr, "block already ended (%s)\n", self->label);
830 in = ir_instr_new(self, VINSTR_JUMP);
835 if (!ir_block_instr_add(self, in))
838 if (!ir_block_exits_add(self, to) ||
839 !ir_block_entries_add(to, self) )
846 bool ir_block_create_goto(ir_block *self, ir_block *to)
850 fprintf(stderr, "block already ended (%s)\n", self->label);
854 in = ir_instr_new(self, INSTR_GOTO);
859 if (!ir_block_instr_add(self, in))
862 if (!ir_block_exits_add(self, to) ||
863 !ir_block_entries_add(to, self) )
870 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
874 in = ir_instr_new(self, VINSTR_PHI);
877 out = ir_value_out(self->owner, label, store_value, ot);
882 if (!ir_instr_op(in, 0, out, true)) {
884 ir_value_delete(out);
887 if (!ir_block_instr_add(self, in)) {
889 ir_value_delete(out);
895 ir_value* ir_phi_value(ir_instr *self)
897 return self->_ops[0];
900 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
904 if (!ir_block_entries_find(self->owner, b, NULL)) {
905 /* Must not be possible to cause this, otherwise the AST
906 * is doing something wrong.
908 fprintf(stderr, "Invalid entry block for PHI\n");
914 if (!ir_value_reads_add(v, self))
916 return ir_instr_phi_add(self, pe);
919 /* binary op related code */
921 ir_value* ir_block_create_binop(ir_block *self,
922 const char *label, int opcode,
923 ir_value *left, ir_value *right)
945 case INSTR_SUB_S: /* -- offset of string as float */
952 case INSTR_BITAND_FI:
953 case INSTR_BITAND_IF:
994 /* boolean operations result in floats */
995 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
997 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1000 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1005 if (ot == TYPE_VOID) {
1006 /* The AST or parser were supposed to check this! */
1010 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1013 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1014 int op, ir_value *a, ir_value *b, int outype)
1019 out = ir_value_out(self->owner, label, store_value, outype);
1023 instr = ir_instr_new(self, op);
1025 ir_value_delete(out);
1029 if (!ir_instr_op(instr, 0, out, true) ||
1030 !ir_instr_op(instr, 1, a, false) ||
1031 !ir_instr_op(instr, 2, b, false) )
1036 if (!ir_block_instr_add(self, instr))
1041 ir_instr_delete(instr);
1042 ir_value_delete(out);
1046 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1048 /* Support for various pointer types todo if so desired */
1049 if (ent->vtype != TYPE_ENTITY)
1052 if (field->vtype != TYPE_FIELD)
1055 return ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1058 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1061 if (ent->vtype != TYPE_ENTITY)
1064 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1065 if (field->vtype != TYPE_FIELD)
1070 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1071 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1072 case TYPE_STRING: op = INSTR_LOAD_S; break;
1073 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1074 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1076 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1077 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1083 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1086 ir_value* ir_block_create_add(ir_block *self,
1088 ir_value *left, ir_value *right)
1091 int l = left->vtype;
1092 int r = right->vtype;
1111 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1113 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1119 return ir_block_create_binop(self, label, op, left, right);
1122 ir_value* ir_block_create_sub(ir_block *self,
1124 ir_value *left, ir_value *right)
1127 int l = left->vtype;
1128 int r = right->vtype;
1148 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1150 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1156 return ir_block_create_binop(self, label, op, left, right);
1159 ir_value* ir_block_create_mul(ir_block *self,
1161 ir_value *left, ir_value *right)
1164 int l = left->vtype;
1165 int r = right->vtype;
1184 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1186 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1189 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1191 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1193 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1195 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1201 return ir_block_create_binop(self, label, op, left, right);
1204 ir_value* ir_block_create_div(ir_block *self,
1206 ir_value *left, ir_value *right)
1209 int l = left->vtype;
1210 int r = right->vtype;
1227 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1229 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1231 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1237 return ir_block_create_binop(self, label, op, left, right);
1240 /* PHI resolving breaks the SSA, and must thus be the last
1241 * step before life-range calculation.
1244 static bool ir_block_naive_phi(ir_block *self);
1245 bool ir_function_naive_phi(ir_function *self)
1249 for (i = 0; i < self->blocks_count; ++i)
1251 if (!ir_block_naive_phi(self->blocks[i]))
1257 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1262 /* create a store */
1263 if (!ir_block_create_store(block, old, what))
1266 /* we now move it up */
1267 instr = block->instr[block->instr_count-1];
1268 for (i = block->instr_count; i > iid; --i)
1269 block->instr[i] = block->instr[i-1];
1270 block->instr[i] = instr;
1275 static bool ir_block_naive_phi(ir_block *self)
1278 /* FIXME: optionally, create_phi can add the phis
1279 * to a list so we don't need to loop through blocks
1280 * - anyway: "don't optimize YET"
1282 for (i = 0; i < self->instr_count; ++i)
1284 ir_instr *instr = self->instr[i];
1285 if (instr->opcode != VINSTR_PHI)
1288 if (!ir_block_instr_remove(self, i))
1290 --i; /* NOTE: i+1 below */
1292 for (p = 0; p < instr->phi_count; ++p)
1294 ir_value *v = instr->phi[p].value;
1295 for (w = 0; w < v->writes_count; ++w) {
1298 if (!v->writes[w]->_ops[0])
1301 /* When the write was to a global, we have to emit a mov */
1302 old = v->writes[w]->_ops[0];
1304 /* The original instruction now writes to the PHI target local */
1305 if (v->writes[w]->_ops[0] == v)
1306 v->writes[w]->_ops[0] = instr->_ops[0];
1308 if (old->store != store_value && old->store != store_local)
1310 /* If it originally wrote to a global we need to store the value
1313 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1315 if (i+1 < self->instr_count)
1316 instr = self->instr[i+1];
1319 /* In case I forget and access instr later, it'll be NULL
1320 * when it's a problem, to make sure we crash, rather than accessing
1326 /* If it didn't, we can replace all reads by the phi target now. */
1328 for (r = 0; r < old->reads_count; ++r)
1331 ir_instr *ri = old->reads[r];
1332 for (op = 0; op < ri->phi_count; ++op) {
1333 if (ri->phi[op].value == old)
1334 ri->phi[op].value = v;
1336 for (op = 0; op < 3; ++op) {
1337 if (ri->_ops[op] == old)
1344 ir_instr_delete(instr);
1349 /***********************************************************************
1350 *IR Temp allocation code
1351 * Propagating value life ranges by walking through the function backwards
1352 * until no more changes are made.
1353 * In theory this should happen once more than once for every nested loop
1355 * Though this implementation might run an additional time for if nests.
1364 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1366 /* Enumerate instructions used by value's life-ranges
1368 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1372 for (i = 0; i < self->instr_count; ++i)
1374 self->instr[i]->eid = eid++;
1379 /* Enumerate blocks and instructions.
1380 * The block-enumeration is unordered!
1381 * We do not really use the block enumreation, however
1382 * the instruction enumeration is important for life-ranges.
1384 void ir_function_enumerate(ir_function *self)
1387 size_t instruction_id = 0;
1388 for (i = 0; i < self->blocks_count; ++i)
1390 self->blocks[i]->eid = i;
1391 self->blocks[i]->run_id = 0;
1392 ir_block_enumerate(self->blocks[i], &instruction_id);
1396 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1397 bool ir_function_calculate_liferanges(ir_function *self)
1405 for (i = 0; i != self->blocks_count; ++i)
1407 if (self->blocks[i]->is_return)
1409 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1417 /* Get information about which operand
1418 * is read from, or written to.
1420 static void ir_op_read_write(int op, size_t *read, size_t *write)
1447 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1450 bool changed = false;
1452 for (i = 0; i != self->living_count; ++i)
1454 tempbool = ir_value_life_merge(self->living[i], eid);
1457 fprintf(stderr, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1459 changed = changed || tempbool;
1464 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1467 /* values which have been read in a previous iteration are now
1468 * in the "living" array even if the previous block doesn't use them.
1469 * So we have to remove whatever does not exist in the previous block.
1470 * They will be re-added on-read, but the liferange merge won't cause
1473 for (i = 0; i < self->living_count; ++i)
1475 if (!ir_block_living_find(prev, self->living[i], NULL)) {
1476 if (!ir_block_living_remove(self, i))
1482 /* Whatever the previous block still has in its living set
1483 * must now be added to ours as well.
1485 for (i = 0; i < prev->living_count; ++i)
1487 if (ir_block_living_find(self, prev->living[i], NULL))
1489 if (!ir_block_living_add(self, prev->living[i]))
1492 printf("%s got from prev: %s\n", self->label, prev->living[i]->_name);
1498 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
1504 /* bitmasks which operands are read from or written to */
1506 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1508 new_reads_t new_reads;
1510 char dbg_ind[16] = { '#', '0' };
1513 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1514 MEM_VECTOR_INIT(&new_reads, v);
1519 if (!ir_block_life_prop_previous(self, prev, changed))
1523 i = self->instr_count;
1526 instr = self->instr[i];
1528 /* PHI operands are always read operands */
1529 for (p = 0; p < instr->phi_count; ++p)
1531 value = instr->phi[p].value;
1532 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1533 if (!ir_block_living_find(self, value, NULL) &&
1534 !ir_block_living_add(self, value))
1539 if (!new_reads_t_v_find(&new_reads, value, NULL))
1541 if (!new_reads_t_v_add(&new_reads, value))
1547 /* See which operands are read and write operands */
1548 ir_op_read_write(instr->opcode, &read, &write);
1550 /* Go through the 3 main operands */
1551 for (o = 0; o < 3; ++o)
1553 if (!instr->_ops[o]) /* no such operand */
1556 value = instr->_ops[o];
1558 /* We only care about locals */
1559 if (value->store != store_value &&
1560 value->store != store_local)
1566 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1567 if (!ir_block_living_find(self, value, NULL) &&
1568 !ir_block_living_add(self, value))
1573 /* fprintf(stderr, "read: %s\n", value->_name); */
1574 if (!new_reads_t_v_find(&new_reads, value, NULL))
1576 if (!new_reads_t_v_add(&new_reads, value))
1582 /* write operands */
1583 /* When we write to a local, we consider it "dead" for the
1584 * remaining upper part of the function, since in SSA a value
1585 * can only be written once (== created)
1590 bool in_living = ir_block_living_find(self, value, &idx);
1591 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1593 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
1594 if (!in_living && !in_reads)
1599 /* If the value isn't alive it hasn't been read before... */
1600 /* TODO: See if the warning can be emitted during parsing or AST processing
1601 * otherwise have warning printed here.
1602 * IF printing a warning here: include filecontext_t,
1603 * and make sure it's only printed once
1604 * since this function is run multiple times.
1606 /* For now: debug info: */
1607 fprintf(stderr, "Value only written %s\n", value->name);
1608 tempbool = ir_value_life_merge(value, instr->eid);
1609 *changed = *changed || tempbool;
1611 ir_instr_dump(instr, dbg_ind, printf);
1615 /* since 'living' won't contain it
1616 * anymore, merge the value, since
1619 tempbool = ir_value_life_merge(value, instr->eid);
1622 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
1624 *changed = *changed || tempbool;
1626 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1627 if (!ir_block_living_remove(self, idx))
1632 if (!new_reads_t_v_remove(&new_reads, readidx))
1640 tempbool = ir_block_living_add_instr(self, instr->eid);
1641 /*fprintf(stderr, "living added values\n");*/
1642 *changed = *changed || tempbool;
1644 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1646 for (rd = 0; rd < new_reads.v_count; ++rd)
1648 if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
1649 if (!ir_block_living_add(self, new_reads.v[rd]))
1652 if (!i && !self->entries_count) {
1654 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
1657 MEM_VECTOR_CLEAR(&new_reads, v);
1661 if (self->run_id == self->owner->run_id)
1664 self->run_id = self->owner->run_id;
1666 for (i = 0; i < self->entries_count; ++i)
1668 ir_block *entry = self->entries[i];
1669 ir_block_life_propagate(entry, self, changed);
1674 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1675 MEM_VECTOR_CLEAR(&new_reads, v);
1680 /***********************************************************************
1683 * Since the IR has the convention of putting 'write' operands
1684 * at the beginning, we have to rotate the operands of instructions
1685 * properly in order to generate valid QCVM code.
1687 * Having destinations at a fixed position is more convenient. In QC
1688 * this is *mostly* OPC, but FTE adds at least 2 instructions which
1689 * read from from OPA, and store to OPB rather than OPC. Which is
1690 * partially the reason why the implementation of these instructions
1691 * in darkplaces has been delayed for so long.
1693 * Breaking conventions is annoying...
1695 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
1697 static bool gen_global_field(ir_value *global)
1699 if (global->isconst)
1701 ir_value *fld = global->constval.vpointer;
1703 printf("Invalid field constant with no field: %s\n", global->name);
1707 /* Now, in this case, a relocation would be impossible to code
1708 * since it looks like this:
1709 * .vector v = origin; <- parse error, wtf is 'origin'?
1712 * But we will need a general relocation support later anyway
1713 * for functions... might as well support that here.
1715 if (!fld->code.globaladdr) {
1716 printf("FIXME: Relocation support\n");
1720 /* copy the field's value */
1721 global->code.globaladdr = code_globals_add(code_globals_data[fld->code.globaladdr]);
1725 prog_section_field fld;
1727 fld.name = global->code.name;
1728 fld.offset = code_fields_elements;
1729 fld.type = global->fieldtype;
1731 if (fld.type == TYPE_VOID) {
1732 printf("Field is missing a type: %s\n", global->name);
1736 if (code_fields_add(fld) < 0)
1739 global->code.globaladdr = code_globals_add(fld.offset);
1741 if (global->code.globaladdr < 0)
1746 static bool gen_global_pointer(ir_value *global)
1748 if (global->isconst)
1750 ir_value *target = global->constval.vpointer;
1752 printf("Invalid pointer constant: %s\n", global->name);
1753 /* NULL pointers are pointing to the NULL constant, which also
1754 * sits at address 0, but still has an ir_value for itself.
1759 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
1760 * void() foo; <- proto
1761 * void() *fooptr = &foo;
1762 * void() foo = { code }
1764 if (!target->code.globaladdr) {
1765 /* FIXME: Check for the constant nullptr ir_value!
1766 * because then code.globaladdr being 0 is valid.
1768 printf("FIXME: Relocation support\n");
1772 global->code.globaladdr = code_globals_add(target->code.globaladdr);
1776 global->code.globaladdr = code_globals_add(0);
1778 if (global->code.globaladdr < 0)
1783 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
1785 prog_section_statement stmt;
1786 prog_section_statement *stptr;
1795 block->generated = true;
1796 block->code_start = code_statements_elements;
1797 for (i = 0; i < block->instr_count; ++i)
1799 instr = block->instr[i];
1801 if (instr->opcode == VINSTR_PHI) {
1802 printf("cannot generate virtual instruction (phi)\n");
1806 if (instr->opcode == VINSTR_JUMP) {
1807 target = instr->bops[0];
1808 /* for uncoditional jumps, if the target hasn't been generated
1809 * yet, we generate them right here.
1811 if (!target->generated) {
1816 /* otherwise we generate a jump instruction */
1817 stmt.opcode = INSTR_GOTO;
1818 stmt.o1.s1 = (target->code_start-1) - code_statements_elements;
1821 if (code_statements_add(stmt) < 0)
1824 /* no further instructions can be in this block */
1828 if (instr->opcode == VINSTR_COND) {
1829 ontrue = instr->bops[0];
1830 onfalse = instr->bops[1];
1831 /* TODO: have the AST signal which block should
1832 * come first: eg. optimize IFs without ELSE...
1835 stmt.o1.u1 = instr->_ops[0]->code.globaladdr;
1838 if (ontrue->generated) {
1839 stmt.opcode = INSTR_IF;
1840 stmt.o2.s1 = (ontrue->code_start-1) - code_statements_elements;
1841 if (code_statements_add(stmt) < 0)
1844 if (onfalse->generated) {
1845 stmt.opcode = INSTR_IFNOT;
1846 stmt.o2.s1 = (onfalse->code_start-1) - code_statements_elements;
1847 if (code_statements_add(stmt) < 0)
1850 if (!ontrue->generated) {
1851 if (onfalse->generated) {
1856 if (!onfalse->generated) {
1857 if (ontrue->generated) {
1862 /* neither ontrue nor onfalse exist */
1863 stmt.opcode = INSTR_IFNOT;
1864 stidx = code_statements_elements - 1;
1865 if (code_statements_add(stmt) < 0)
1867 stptr = &code_statements_data[stidx];
1868 /* on false we jump, so add ontrue-path */
1869 if (!gen_blocks_recursive(func, ontrue))
1871 /* fixup the jump address */
1872 stptr->o2.s1 = (ontrue->code_start-1) - (stidx+1);
1873 /* generate onfalse path */
1874 if (onfalse->generated) {
1875 /* may have been generated in the previous recursive call */
1876 stmt.opcode = INSTR_GOTO;
1879 stmt.o1.s1 = (onfalse->code_start-1) - code_statements_elements;
1880 return (code_statements_add(stmt) >= 0);
1882 /* if not, generate now */
1887 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
1888 printf("TODO: call instruction\n");
1892 if (instr->opcode == INSTR_STATE) {
1893 printf("TODO: state instruction\n");
1897 stmt.opcode = instr->opcode;
1902 /* This is the general order of operands */
1904 stmt.o3.u1 = instr->_ops[0]->code.globaladdr;
1907 stmt.o1.u1 = instr->_ops[1]->code.globaladdr;
1910 stmt.o2.u1 = instr->_ops[2]->code.globaladdr;
1912 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
1914 stmt.o1.u1 = stmt.o3.u1;
1917 else if ((stmt.opcode >= INSTR_STORE_F &&
1918 stmt.opcode <= INSTR_STORE_FNC) ||
1919 (stmt.opcode >= INSTR_NOT_F &&
1920 stmt.opcode <= INSTR_NOT_FNC))
1922 /* 2-operand instructions with A -> B */
1923 stmt.o2.u1 = stmt.o3.u1;
1927 if (code_statements_add(stmt) < 0)
1933 static bool gen_function_code(ir_function *self)
1937 /* Starting from entry point, we generate blocks "as they come"
1938 * for now. Dead blocks will not be translated obviously.
1940 if (!self->blocks_count) {
1941 printf("Function '%s' declared without body.\n", self->name);
1945 block = self->blocks[0];
1946 if (block->generated)
1949 if (!gen_blocks_recursive(self, block)) {
1950 printf("failed to generate blocks for '%s'\n", self->name);
1956 static bool gen_global_function(ir_builder *ir, ir_value *global)
1958 prog_section_function fun;
1963 if (!global->isconst ||
1964 !global->constval.vfunc)
1966 printf("Invalid state of function-global: not constant: %s\n", global->name);
1970 irfun = global->constval.vfunc;
1972 fun.name = global->code.name;
1973 fun.file = code_cachedstring(global->context.file);
1974 fun.profile = 0; /* always 0 */
1975 fun.nargs = irfun->params_count;
1977 for (i = 0;i < 8; ++i) {
1980 else if (irfun->params[i] == TYPE_VECTOR)
1986 fun.locals = irfun->locals_count;
1987 fun.firstlocal = code_globals_elements;
1988 for (i = 0; i < irfun->locals_count; ++i) {
1989 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
1990 printf("Failed to generate global %s\n", irfun->locals[i]->name);
1995 fun.entry = code_statements_elements;
1996 if (!gen_function_code(irfun)) {
1997 printf("Failed to generate code for function %s\n", irfun->name);
2001 return (code_functions_add(fun) >= 0);
2004 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2007 prog_section_def def;
2009 def.type = global->vtype;
2010 def.offset = code_globals_elements;
2011 def.name = global->code.name = code_genstring(global->name);
2013 switch (global->vtype)
2016 if (code_defs_add(def) < 0)
2018 return gen_global_pointer(global);
2020 if (code_defs_add(def) < 0)
2022 return gen_global_field(global);
2027 if (code_defs_add(def) < 0)
2030 if (global->isconst) {
2031 iptr = (int32_t*)&global->constval.vfloat;
2032 global->code.globaladdr = code_globals_add(*iptr);
2034 global->code.globaladdr = code_globals_add(0);
2036 return global->code.globaladdr >= 0;
2040 if (code_defs_add(def) < 0)
2042 if (global->isconst)
2043 global->code.globaladdr = code_globals_add(code_cachedstring(global->constval.vstring));
2045 global->code.globaladdr = code_globals_add(0);
2046 return global->code.globaladdr >= 0;
2050 if (code_defs_add(def) < 0)
2053 if (global->isconst) {
2054 iptr = (int32_t*)&global->constval.vvec;
2055 global->code.globaladdr = code_globals_add(iptr[0]);
2056 if (code_globals_add(iptr[1]) < 0 || code_globals_add(iptr[2]) < 0)
2059 global->code.globaladdr = code_globals_add(0);
2060 if (code_globals_add(0) < 0 || code_globals_add(0) < 0)
2063 return global->code.globaladdr >= 0;
2066 if (code_defs_add(def) < 0)
2068 code_globals_add(code_functions_elements);
2069 return gen_global_function(self, global);
2071 /* assume biggest type */
2072 global->code.globaladdr = code_globals_add(0);
2073 code_globals_add(0);
2074 code_globals_add(0);
2077 /* refuse to create 'void' type or any other fancy business. */
2078 printf("Invalid type for global variable %s\n", global->name);
2083 bool ir_builder_generate(ir_builder *self, const char *filename)
2089 /* FIXME: generate TYPE_FUNCTION globals and link them
2090 * to their ir_function.
2093 for (i = 0; i < self->functions_count; ++i)
2096 ir_function *fun = self->functions[i];
2098 funval = ir_builder_create_global(self, fun->name, TYPE_FUNCTION);
2099 funval->isconst = true;
2100 funval->constval.vfunc = fun;
2101 funval->context = fun->context;
2104 for (i = 0; i < self->globals_count; ++i)
2106 if (!ir_builder_gen_global(self, self->globals[i])) {
2111 printf("writing '%s'...\n", filename);
2112 return code_write(filename);
2115 /***********************************************************************
2116 *IR DEBUG Dump functions...
2119 #define IND_BUFSZ 1024
2121 const char *qc_opname(int op)
2123 if (op < 0) return "<INVALID>";
2124 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2125 return asm_instr[op].m;
2127 case VINSTR_PHI: return "PHI";
2128 case VINSTR_JUMP: return "JUMP";
2129 case VINSTR_COND: return "COND";
2130 default: return "<UNK>";
2134 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2137 char indent[IND_BUFSZ];
2141 oprintf("module %s\n", b->name);
2142 for (i = 0; i < b->globals_count; ++i)
2145 if (b->globals[i]->isconst)
2146 oprintf("%s = ", b->globals[i]->name);
2147 ir_value_dump(b->globals[i], oprintf);
2150 for (i = 0; i < b->functions_count; ++i)
2151 ir_function_dump(b->functions[i], indent, oprintf);
2152 oprintf("endmodule %s\n", b->name);
2155 void ir_function_dump(ir_function *f, char *ind,
2156 int (*oprintf)(const char*, ...))
2159 oprintf("%sfunction %s\n", ind, f->name);
2160 strncat(ind, "\t", IND_BUFSZ);
2161 if (f->locals_count)
2163 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2164 for (i = 0; i < f->locals_count; ++i) {
2165 oprintf("%s\t", ind);
2166 ir_value_dump(f->locals[i], oprintf);
2170 if (f->blocks_count)
2172 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2173 for (i = 0; i < f->blocks_count; ++i) {
2174 if (f->blocks[i]->run_id != f->run_id) {
2175 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2177 ir_block_dump(f->blocks[i], ind, oprintf);
2181 ind[strlen(ind)-1] = 0;
2182 oprintf("%sendfunction %s\n", ind, f->name);
2185 void ir_block_dump(ir_block* b, char *ind,
2186 int (*oprintf)(const char*, ...))
2189 oprintf("%s:%s\n", ind, b->label);
2190 strncat(ind, "\t", IND_BUFSZ);
2192 for (i = 0; i < b->instr_count; ++i)
2193 ir_instr_dump(b->instr[i], ind, oprintf);
2194 ind[strlen(ind)-1] = 0;
2197 void dump_phi(ir_instr *in, char *ind,
2198 int (*oprintf)(const char*, ...))
2201 oprintf("%s <- phi ", in->_ops[0]->name);
2202 for (i = 0; i < in->phi_count; ++i)
2204 oprintf("([%s] : %s) ", in->phi[i].from->label,
2205 in->phi[i].value->name);
2210 void ir_instr_dump(ir_instr *in, char *ind,
2211 int (*oprintf)(const char*, ...))
2214 const char *comma = NULL;
2216 oprintf("%s (%i) ", ind, (int)in->eid);
2218 if (in->opcode == VINSTR_PHI) {
2219 dump_phi(in, ind, oprintf);
2223 strncat(ind, "\t", IND_BUFSZ);
2225 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2226 ir_value_dump(in->_ops[0], oprintf);
2227 if (in->_ops[1] || in->_ops[2])
2230 oprintf("%s\t", qc_opname(in->opcode));
2231 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2232 ir_value_dump(in->_ops[0], oprintf);
2237 for (i = 1; i != 3; ++i) {
2241 ir_value_dump(in->_ops[i], oprintf);
2249 oprintf("[%s]", in->bops[0]->label);
2253 oprintf("%s[%s]", comma, in->bops[1]->label);
2255 ind[strlen(ind)-1] = 0;
2258 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
2266 oprintf("%g", v->constval.vfloat);
2269 oprintf("'%g %g %g'",
2272 v->constval.vvec.z);
2275 oprintf("(entity)");
2278 oprintf("\"%s\"", v->constval.vstring);
2282 oprintf("%i", v->constval.vint);
2287 v->constval.vpointer->name);
2291 oprintf("%s", v->name);
2295 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
2298 oprintf("Life of %s:\n", self->name);
2299 for (i = 0; i < self->life_count; ++i)
2301 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);