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*);
141 bool ir_function_allocate_locals(ir_function*);
143 ir_function* ir_function_new(ir_builder* owner)
146 self = (ir_function*)mem_a(sizeof(*self));
152 if (!ir_function_set_name(self, "<@unnamed>")) {
157 self->context.file = "<@no context>";
158 self->context.line = 0;
159 self->retype = TYPE_VOID;
160 MEM_VECTOR_INIT(self, params);
161 MEM_VECTOR_INIT(self, blocks);
162 MEM_VECTOR_INIT(self, values);
163 MEM_VECTOR_INIT(self, locals);
168 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
169 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
170 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
172 bool ir_function_set_name(ir_function *self, const char *name)
175 mem_d((void*)self->name);
176 self->name = util_strdup(name);
180 void ir_function_delete(ir_function *self)
183 mem_d((void*)self->name);
185 for (i = 0; i != self->blocks_count; ++i)
186 ir_block_delete(self->blocks[i]);
187 MEM_VECTOR_CLEAR(self, blocks);
189 MEM_VECTOR_CLEAR(self, params);
191 for (i = 0; i != self->values_count; ++i)
192 ir_value_delete(self->values[i]);
193 MEM_VECTOR_CLEAR(self, values);
195 for (i = 0; i != self->locals_count; ++i)
196 ir_value_delete(self->locals[i]);
197 MEM_VECTOR_CLEAR(self, locals);
202 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
204 return ir_function_values_add(self, v);
207 ir_block* ir_function_create_block(ir_function *self, const char *label)
209 ir_block* bn = ir_block_new(self, label);
210 memcpy(&bn->context, &self->context, sizeof(self->context));
211 if (!ir_function_blocks_add(self, bn)) {
218 bool ir_function_finalize(ir_function *self)
220 if (!ir_function_naive_phi(self))
223 ir_function_enumerate(self);
225 if (!ir_function_calculate_liferanges(self))
228 if (!ir_function_allocate_locals(self))
233 ir_value* ir_function_get_local(ir_function *self, const char *name)
236 for (i = 0; i < self->locals_count; ++i) {
237 if (!strcmp(self->locals[i]->name, name))
238 return self->locals[i];
243 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype)
245 ir_value *ve = ir_function_get_local(self, name);
250 ve = ir_value_var(name, store_local, vtype);
251 if (!ir_function_locals_add(self, ve)) {
258 /***********************************************************************
262 ir_block* ir_block_new(ir_function* owner, const char *name)
265 self = (ir_block*)mem_a(sizeof(*self));
269 memset(self, 0, sizeof(*self));
272 if (!ir_block_set_label(self, name)) {
277 self->context.file = "<@no context>";
278 self->context.line = 0;
280 MEM_VECTOR_INIT(self, instr);
281 MEM_VECTOR_INIT(self, entries);
282 MEM_VECTOR_INIT(self, exits);
285 self->is_return = false;
287 MEM_VECTOR_INIT(self, living);
289 self->generated = false;
293 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
294 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
295 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
296 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
298 void ir_block_delete(ir_block* self)
302 for (i = 0; i != self->instr_count; ++i)
303 ir_instr_delete(self->instr[i]);
304 MEM_VECTOR_CLEAR(self, instr);
305 MEM_VECTOR_CLEAR(self, entries);
306 MEM_VECTOR_CLEAR(self, exits);
307 MEM_VECTOR_CLEAR(self, living);
311 bool ir_block_set_label(ir_block *self, const char *name)
314 mem_d((void*)self->label);
315 self->label = util_strdup(name);
316 return !!self->label;
319 /***********************************************************************
323 ir_instr* ir_instr_new(ir_block* owner, int op)
326 self = (ir_instr*)mem_a(sizeof(*self));
331 self->context.file = "<@no context>";
332 self->context.line = 0;
334 self->_ops[0] = NULL;
335 self->_ops[1] = NULL;
336 self->_ops[2] = NULL;
337 self->bops[0] = NULL;
338 self->bops[1] = NULL;
339 MEM_VECTOR_INIT(self, phi);
344 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
346 void ir_instr_delete(ir_instr *self)
349 /* The following calls can only delete from
350 * vectors, we still want to delete this instruction
351 * so ignore the return value. Since with the warn_unused_result attribute
352 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
353 * I have to improvise here and use if(foo());
355 for (i = 0; i < self->phi_count; ++i) {
357 if (ir_value_writes_find(self->phi[i].value, self, &idx))
358 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPRESS_EMPTY_BODY;
359 if (ir_value_reads_find(self->phi[i].value, self, &idx))
360 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPRESS_EMPTY_BODY;
362 MEM_VECTOR_CLEAR(self, phi);
363 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPRESS_EMPTY_BODY;
364 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPRESS_EMPTY_BODY;
365 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPRESS_EMPTY_BODY;
369 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
371 if (self->_ops[op]) {
373 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
375 if (!ir_value_writes_remove(self->_ops[op], idx))
378 else if (ir_value_reads_find(self->_ops[op], self, &idx))
380 if (!ir_value_reads_remove(self->_ops[op], idx))
386 if (!ir_value_writes_add(v, self))
389 if (!ir_value_reads_add(v, self))
397 /***********************************************************************
401 ir_value* ir_value_var(const char *name, int storetype, int vtype)
404 self = (ir_value*)mem_a(sizeof(*self));
406 self->fieldtype = TYPE_VOID;
407 self->store = storetype;
408 MEM_VECTOR_INIT(self, reads);
409 MEM_VECTOR_INIT(self, writes);
410 self->isconst = false;
411 self->context.file = "<@no context>";
412 self->context.line = 0;
414 ir_value_set_name(self, name);
416 memset(&self->constval, 0, sizeof(self->constval));
417 memset(&self->code, 0, sizeof(self->code));
419 MEM_VECTOR_INIT(self, life);
422 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
423 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
424 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
426 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
428 ir_value *v = ir_value_var(name, storetype, vtype);
431 if (!ir_function_collect_value(owner, v))
439 void ir_value_delete(ir_value* self)
441 mem_d((void*)self->name);
444 if (self->vtype == TYPE_STRING)
445 mem_d((void*)self->constval.vstring);
447 MEM_VECTOR_CLEAR(self, reads);
448 MEM_VECTOR_CLEAR(self, writes);
449 MEM_VECTOR_CLEAR(self, life);
453 void ir_value_set_name(ir_value *self, const char *name)
456 mem_d((void*)self->name);
457 self->name = util_strdup(name);
460 bool ir_value_set_float(ir_value *self, float f)
462 if (self->vtype != TYPE_FLOAT)
464 self->constval.vfloat = f;
465 self->isconst = true;
469 bool ir_value_set_vector(ir_value *self, vector v)
471 if (self->vtype != TYPE_VECTOR)
473 self->constval.vvec = v;
474 self->isconst = true;
478 bool ir_value_set_string(ir_value *self, const char *str)
480 if (self->vtype != TYPE_STRING)
482 self->constval.vstring = util_strdup(str);
483 self->isconst = true;
488 bool ir_value_set_int(ir_value *self, int i)
490 if (self->vtype != TYPE_INTEGER)
492 self->constval.vint = i;
493 self->isconst = true;
498 bool ir_value_lives(ir_value *self, size_t at)
501 for (i = 0; i < self->life_count; ++i)
503 ir_life_entry_t *life = &self->life[i];
504 if (life->start <= at && at <= life->end)
506 if (life->start > at) /* since it's ordered */
512 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
515 if (!ir_value_life_add(self, e)) /* naive... */
517 for (k = self->life_count-1; k > idx; --k)
518 self->life[k] = self->life[k-1];
523 bool ir_value_life_merge(ir_value *self, size_t s)
526 ir_life_entry_t *life = NULL;
527 ir_life_entry_t *before = NULL;
528 ir_life_entry_t new_entry;
530 /* Find the first range >= s */
531 for (i = 0; i < self->life_count; ++i)
534 life = &self->life[i];
538 /* nothing found? append */
539 if (i == self->life_count) {
541 if (life && life->end+1 == s)
543 /* previous life range can be merged in */
547 if (life && life->end >= s)
550 if (!ir_value_life_add(self, e))
551 return false; /* failing */
557 if (before->end + 1 == s &&
558 life->start - 1 == s)
561 before->end = life->end;
562 if (!ir_value_life_remove(self, i))
563 return false; /* failing */
566 if (before->end + 1 == s)
572 /* already contained */
573 if (before->end >= s)
577 if (life->start - 1 == s)
582 /* insert a new entry */
583 new_entry.start = new_entry.end = s;
584 return ir_value_life_insert(self, i, new_entry);
587 bool ir_values_overlap(ir_value *a, ir_value *b)
589 /* For any life entry in A see if it overlaps with
590 * any life entry in B.
591 * Note that the life entries are orderes, so we can make a
592 * more efficient algorithm there than naively translating the
596 ir_life_entry_t *la, *lb, *enda, *endb;
598 /* first of all, if either has no life range, they cannot clash */
599 if (!a->life_count || !b->life_count)
604 enda = la + a->life_count;
605 endb = lb + b->life_count;
608 /* check if the entries overlap, for that,
609 * both must start before the other one ends.
611 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
612 if (la->start <= lb->end &&
613 lb->start <= la->end)
615 if (la->start < lb->end &&
622 /* entries are ordered
623 * one entry is earlier than the other
624 * that earlier entry will be moved forward
626 if (la->end < lb->end)
628 /* order: A B, move A forward
629 * check if we hit the end with A
634 else if (lb->end < la->end)
636 /* order: B A, move B forward
637 * check if we hit the end with B
646 /***********************************************************************
650 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
652 if (target->store == store_value) {
653 fprintf(stderr, "cannot store to an SSA value\n");
654 fprintf(stderr, "trying to store: %s <- %s\n", target->name, what->name);
657 ir_instr *in = ir_instr_new(self, op);
660 if (!ir_instr_op(in, 0, target, true) ||
661 !ir_instr_op(in, 1, what, false) ||
662 !ir_block_instr_add(self, in) )
670 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
674 if (target->vtype == TYPE_VARIANT)
677 vtype = target->vtype;
682 if (what->vtype == TYPE_INTEGER)
683 op = INSTR_CONV_ITOF;
692 op = INSTR_STORE_ENT;
698 op = INSTR_STORE_FLD;
702 if (what->vtype == TYPE_INTEGER)
703 op = INSTR_CONV_FTOI;
712 op = INSTR_STORE_ENT;
719 return ir_block_create_store_op(self, op, target, what);
722 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
727 if (target->vtype != TYPE_POINTER)
730 /* storing using pointer - target is a pointer, type must be
731 * inferred from source
743 op = INSTR_STOREP_ENT;
749 op = INSTR_STOREP_FLD;
760 op = INSTR_STOREP_ENT;
767 return ir_block_create_store_op(self, op, target, what);
770 bool ir_block_create_return(ir_block *self, ir_value *v)
774 fprintf(stderr, "block already ended (%s)\n", self->label);
778 self->is_return = true;
779 in = ir_instr_new(self, INSTR_RETURN);
783 if (!ir_instr_op(in, 0, v, false) ||
784 !ir_block_instr_add(self, in) )
791 bool ir_block_create_if(ir_block *self, ir_value *v,
792 ir_block *ontrue, ir_block *onfalse)
796 fprintf(stderr, "block already ended (%s)\n", self->label);
800 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
801 in = ir_instr_new(self, VINSTR_COND);
805 if (!ir_instr_op(in, 0, v, false)) {
810 in->bops[0] = ontrue;
811 in->bops[1] = onfalse;
813 if (!ir_block_instr_add(self, in))
816 if (!ir_block_exits_add(self, ontrue) ||
817 !ir_block_exits_add(self, onfalse) ||
818 !ir_block_entries_add(ontrue, self) ||
819 !ir_block_entries_add(onfalse, self) )
826 bool ir_block_create_jump(ir_block *self, ir_block *to)
830 fprintf(stderr, "block already ended (%s)\n", self->label);
834 in = ir_instr_new(self, VINSTR_JUMP);
839 if (!ir_block_instr_add(self, in))
842 if (!ir_block_exits_add(self, to) ||
843 !ir_block_entries_add(to, self) )
850 bool ir_block_create_goto(ir_block *self, ir_block *to)
854 fprintf(stderr, "block already ended (%s)\n", self->label);
858 in = ir_instr_new(self, INSTR_GOTO);
863 if (!ir_block_instr_add(self, in))
866 if (!ir_block_exits_add(self, to) ||
867 !ir_block_entries_add(to, self) )
874 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
878 in = ir_instr_new(self, VINSTR_PHI);
881 out = ir_value_out(self->owner, label, store_value, ot);
886 if (!ir_instr_op(in, 0, out, true)) {
888 ir_value_delete(out);
891 if (!ir_block_instr_add(self, in)) {
893 ir_value_delete(out);
899 ir_value* ir_phi_value(ir_instr *self)
901 return self->_ops[0];
904 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
908 if (!ir_block_entries_find(self->owner, b, NULL)) {
909 /* Must not be possible to cause this, otherwise the AST
910 * is doing something wrong.
912 fprintf(stderr, "Invalid entry block for PHI\n");
918 if (!ir_value_reads_add(v, self))
920 return ir_instr_phi_add(self, pe);
923 /* binary op related code */
925 ir_value* ir_block_create_binop(ir_block *self,
926 const char *label, int opcode,
927 ir_value *left, ir_value *right)
949 case INSTR_SUB_S: /* -- offset of string as float */
956 case INSTR_BITAND_FI:
957 case INSTR_BITAND_IF:
998 /* boolean operations result in floats */
999 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1001 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1004 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1009 if (ot == TYPE_VOID) {
1010 /* The AST or parser were supposed to check this! */
1014 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1017 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1018 int op, ir_value *a, ir_value *b, int outype)
1023 out = ir_value_out(self->owner, label, store_value, outype);
1027 instr = ir_instr_new(self, op);
1029 ir_value_delete(out);
1033 if (!ir_instr_op(instr, 0, out, true) ||
1034 !ir_instr_op(instr, 1, a, false) ||
1035 !ir_instr_op(instr, 2, b, false) )
1040 if (!ir_block_instr_add(self, instr))
1045 ir_instr_delete(instr);
1046 ir_value_delete(out);
1050 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1052 /* Support for various pointer types todo if so desired */
1053 if (ent->vtype != TYPE_ENTITY)
1056 if (field->vtype != TYPE_FIELD)
1059 return ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1062 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1065 if (ent->vtype != TYPE_ENTITY)
1068 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1069 if (field->vtype != TYPE_FIELD)
1074 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1075 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1076 case TYPE_STRING: op = INSTR_LOAD_S; break;
1077 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1078 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1080 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1081 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1087 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1090 ir_value* ir_block_create_add(ir_block *self,
1092 ir_value *left, ir_value *right)
1095 int l = left->vtype;
1096 int r = right->vtype;
1115 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1117 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1123 return ir_block_create_binop(self, label, op, left, right);
1126 ir_value* ir_block_create_sub(ir_block *self,
1128 ir_value *left, ir_value *right)
1131 int l = left->vtype;
1132 int r = right->vtype;
1152 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1154 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1160 return ir_block_create_binop(self, label, op, left, right);
1163 ir_value* ir_block_create_mul(ir_block *self,
1165 ir_value *left, ir_value *right)
1168 int l = left->vtype;
1169 int r = right->vtype;
1188 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1190 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1193 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1195 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1197 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1199 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1205 return ir_block_create_binop(self, label, op, left, right);
1208 ir_value* ir_block_create_div(ir_block *self,
1210 ir_value *left, ir_value *right)
1213 int l = left->vtype;
1214 int r = right->vtype;
1231 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1233 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1235 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1241 return ir_block_create_binop(self, label, op, left, right);
1244 /* PHI resolving breaks the SSA, and must thus be the last
1245 * step before life-range calculation.
1248 static bool ir_block_naive_phi(ir_block *self);
1249 bool ir_function_naive_phi(ir_function *self)
1253 for (i = 0; i < self->blocks_count; ++i)
1255 if (!ir_block_naive_phi(self->blocks[i]))
1261 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1266 /* create a store */
1267 if (!ir_block_create_store(block, old, what))
1270 /* we now move it up */
1271 instr = block->instr[block->instr_count-1];
1272 for (i = block->instr_count; i > iid; --i)
1273 block->instr[i] = block->instr[i-1];
1274 block->instr[i] = instr;
1279 static bool ir_block_naive_phi(ir_block *self)
1282 /* FIXME: optionally, create_phi can add the phis
1283 * to a list so we don't need to loop through blocks
1284 * - anyway: "don't optimize YET"
1286 for (i = 0; i < self->instr_count; ++i)
1288 ir_instr *instr = self->instr[i];
1289 if (instr->opcode != VINSTR_PHI)
1292 if (!ir_block_instr_remove(self, i))
1294 --i; /* NOTE: i+1 below */
1296 for (p = 0; p < instr->phi_count; ++p)
1298 ir_value *v = instr->phi[p].value;
1299 for (w = 0; w < v->writes_count; ++w) {
1302 if (!v->writes[w]->_ops[0])
1305 /* When the write was to a global, we have to emit a mov */
1306 old = v->writes[w]->_ops[0];
1308 /* The original instruction now writes to the PHI target local */
1309 if (v->writes[w]->_ops[0] == v)
1310 v->writes[w]->_ops[0] = instr->_ops[0];
1312 if (old->store != store_value && old->store != store_local)
1314 /* If it originally wrote to a global we need to store the value
1317 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1319 if (i+1 < self->instr_count)
1320 instr = self->instr[i+1];
1323 /* In case I forget and access instr later, it'll be NULL
1324 * when it's a problem, to make sure we crash, rather than accessing
1330 /* If it didn't, we can replace all reads by the phi target now. */
1332 for (r = 0; r < old->reads_count; ++r)
1335 ir_instr *ri = old->reads[r];
1336 for (op = 0; op < ri->phi_count; ++op) {
1337 if (ri->phi[op].value == old)
1338 ri->phi[op].value = v;
1340 for (op = 0; op < 3; ++op) {
1341 if (ri->_ops[op] == old)
1348 ir_instr_delete(instr);
1353 /***********************************************************************
1354 *IR Temp allocation code
1355 * Propagating value life ranges by walking through the function backwards
1356 * until no more changes are made.
1357 * In theory this should happen once more than once for every nested loop
1359 * Though this implementation might run an additional time for if nests.
1368 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1370 /* Enumerate instructions used by value's life-ranges
1372 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1376 for (i = 0; i < self->instr_count; ++i)
1378 self->instr[i]->eid = eid++;
1383 /* Enumerate blocks and instructions.
1384 * The block-enumeration is unordered!
1385 * We do not really use the block enumreation, however
1386 * the instruction enumeration is important for life-ranges.
1388 void ir_function_enumerate(ir_function *self)
1391 size_t instruction_id = 0;
1392 for (i = 0; i < self->blocks_count; ++i)
1394 self->blocks[i]->eid = i;
1395 self->blocks[i]->run_id = 0;
1396 ir_block_enumerate(self->blocks[i], &instruction_id);
1400 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1401 bool ir_function_calculate_liferanges(ir_function *self)
1409 for (i = 0; i != self->blocks_count; ++i)
1411 if (self->blocks[i]->is_return)
1413 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1421 /* Local-value allocator
1422 * After finishing creating the liferange of all values used in a function
1423 * we can allocate their global-positions.
1424 * This is the counterpart to register-allocation in register machines.
1426 bool ir_function_allocate_locals(ir_function *self)
1431 /* Get information about which operand
1432 * is read from, or written to.
1434 static void ir_op_read_write(int op, size_t *read, size_t *write)
1461 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1464 bool changed = false;
1466 for (i = 0; i != self->living_count; ++i)
1468 tempbool = ir_value_life_merge(self->living[i], eid);
1471 fprintf(stderr, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1473 changed = changed || tempbool;
1478 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1481 /* values which have been read in a previous iteration are now
1482 * in the "living" array even if the previous block doesn't use them.
1483 * So we have to remove whatever does not exist in the previous block.
1484 * They will be re-added on-read, but the liferange merge won't cause
1487 for (i = 0; i < self->living_count; ++i)
1489 if (!ir_block_living_find(prev, self->living[i], NULL)) {
1490 if (!ir_block_living_remove(self, i))
1496 /* Whatever the previous block still has in its living set
1497 * must now be added to ours as well.
1499 for (i = 0; i < prev->living_count; ++i)
1501 if (ir_block_living_find(self, prev->living[i], NULL))
1503 if (!ir_block_living_add(self, prev->living[i]))
1506 printf("%s got from prev: %s\n", self->label, prev->living[i]->_name);
1512 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
1518 /* bitmasks which operands are read from or written to */
1520 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1522 new_reads_t new_reads;
1524 char dbg_ind[16] = { '#', '0' };
1527 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1528 MEM_VECTOR_INIT(&new_reads, v);
1533 if (!ir_block_life_prop_previous(self, prev, changed))
1537 i = self->instr_count;
1540 instr = self->instr[i];
1542 /* PHI operands are always read operands */
1543 for (p = 0; p < instr->phi_count; ++p)
1545 value = instr->phi[p].value;
1546 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1547 if (!ir_block_living_find(self, value, NULL) &&
1548 !ir_block_living_add(self, value))
1553 if (!new_reads_t_v_find(&new_reads, value, NULL))
1555 if (!new_reads_t_v_add(&new_reads, value))
1561 /* See which operands are read and write operands */
1562 ir_op_read_write(instr->opcode, &read, &write);
1564 /* Go through the 3 main operands */
1565 for (o = 0; o < 3; ++o)
1567 if (!instr->_ops[o]) /* no such operand */
1570 value = instr->_ops[o];
1572 /* We only care about locals */
1573 if (value->store != store_value &&
1574 value->store != store_local)
1580 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1581 if (!ir_block_living_find(self, value, NULL) &&
1582 !ir_block_living_add(self, value))
1587 /* fprintf(stderr, "read: %s\n", value->_name); */
1588 if (!new_reads_t_v_find(&new_reads, value, NULL))
1590 if (!new_reads_t_v_add(&new_reads, value))
1596 /* write operands */
1597 /* When we write to a local, we consider it "dead" for the
1598 * remaining upper part of the function, since in SSA a value
1599 * can only be written once (== created)
1604 bool in_living = ir_block_living_find(self, value, &idx);
1605 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1607 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
1608 if (!in_living && !in_reads)
1613 /* If the value isn't alive it hasn't been read before... */
1614 /* TODO: See if the warning can be emitted during parsing or AST processing
1615 * otherwise have warning printed here.
1616 * IF printing a warning here: include filecontext_t,
1617 * and make sure it's only printed once
1618 * since this function is run multiple times.
1620 /* For now: debug info: */
1621 fprintf(stderr, "Value only written %s\n", value->name);
1622 tempbool = ir_value_life_merge(value, instr->eid);
1623 *changed = *changed || tempbool;
1625 ir_instr_dump(instr, dbg_ind, printf);
1629 /* since 'living' won't contain it
1630 * anymore, merge the value, since
1633 tempbool = ir_value_life_merge(value, instr->eid);
1636 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
1638 *changed = *changed || tempbool;
1640 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1641 if (!ir_block_living_remove(self, idx))
1646 if (!new_reads_t_v_remove(&new_reads, readidx))
1654 tempbool = ir_block_living_add_instr(self, instr->eid);
1655 /*fprintf(stderr, "living added values\n");*/
1656 *changed = *changed || tempbool;
1658 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1660 for (rd = 0; rd < new_reads.v_count; ++rd)
1662 if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
1663 if (!ir_block_living_add(self, new_reads.v[rd]))
1666 if (!i && !self->entries_count) {
1668 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
1671 MEM_VECTOR_CLEAR(&new_reads, v);
1675 if (self->run_id == self->owner->run_id)
1678 self->run_id = self->owner->run_id;
1680 for (i = 0; i < self->entries_count; ++i)
1682 ir_block *entry = self->entries[i];
1683 ir_block_life_propagate(entry, self, changed);
1688 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1689 MEM_VECTOR_CLEAR(&new_reads, v);
1694 /***********************************************************************
1697 * Since the IR has the convention of putting 'write' operands
1698 * at the beginning, we have to rotate the operands of instructions
1699 * properly in order to generate valid QCVM code.
1701 * Having destinations at a fixed position is more convenient. In QC
1702 * this is *mostly* OPC, but FTE adds at least 2 instructions which
1703 * read from from OPA, and store to OPB rather than OPC. Which is
1704 * partially the reason why the implementation of these instructions
1705 * in darkplaces has been delayed for so long.
1707 * Breaking conventions is annoying...
1709 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
1711 static bool gen_global_field(ir_value *global)
1713 if (global->isconst)
1715 ir_value *fld = global->constval.vpointer;
1717 printf("Invalid field constant with no field: %s\n", global->name);
1721 /* Now, in this case, a relocation would be impossible to code
1722 * since it looks like this:
1723 * .vector v = origin; <- parse error, wtf is 'origin'?
1726 * But we will need a general relocation support later anyway
1727 * for functions... might as well support that here.
1729 if (!fld->code.globaladdr) {
1730 printf("FIXME: Relocation support\n");
1734 /* copy the field's value */
1735 global->code.globaladdr = code_globals_add(code_globals_data[fld->code.globaladdr]);
1739 prog_section_field fld;
1741 fld.name = global->code.name;
1742 fld.offset = code_fields_elements;
1743 fld.type = global->fieldtype;
1745 if (fld.type == TYPE_VOID) {
1746 printf("Field is missing a type: %s\n", global->name);
1750 if (code_fields_add(fld) < 0)
1753 global->code.globaladdr = code_globals_add(fld.offset);
1755 if (global->code.globaladdr < 0)
1760 static bool gen_global_pointer(ir_value *global)
1762 if (global->isconst)
1764 ir_value *target = global->constval.vpointer;
1766 printf("Invalid pointer constant: %s\n", global->name);
1767 /* NULL pointers are pointing to the NULL constant, which also
1768 * sits at address 0, but still has an ir_value for itself.
1773 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
1774 * void() foo; <- proto
1775 * void() *fooptr = &foo;
1776 * void() foo = { code }
1778 if (!target->code.globaladdr) {
1779 /* FIXME: Check for the constant nullptr ir_value!
1780 * because then code.globaladdr being 0 is valid.
1782 printf("FIXME: Relocation support\n");
1786 global->code.globaladdr = code_globals_add(target->code.globaladdr);
1790 global->code.globaladdr = code_globals_add(0);
1792 if (global->code.globaladdr < 0)
1797 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
1799 prog_section_statement stmt;
1800 prog_section_statement *stptr;
1809 block->generated = true;
1810 block->code_start = code_statements_elements;
1811 for (i = 0; i < block->instr_count; ++i)
1813 instr = block->instr[i];
1815 if (instr->opcode == VINSTR_PHI) {
1816 printf("cannot generate virtual instruction (phi)\n");
1820 if (instr->opcode == VINSTR_JUMP) {
1821 target = instr->bops[0];
1822 /* for uncoditional jumps, if the target hasn't been generated
1823 * yet, we generate them right here.
1825 if (!target->generated) {
1830 /* otherwise we generate a jump instruction */
1831 stmt.opcode = INSTR_GOTO;
1832 stmt.o1.s1 = (target->code_start-1) - code_statements_elements;
1835 if (code_statements_add(stmt) < 0)
1838 /* no further instructions can be in this block */
1842 if (instr->opcode == VINSTR_COND) {
1843 ontrue = instr->bops[0];
1844 onfalse = instr->bops[1];
1845 /* TODO: have the AST signal which block should
1846 * come first: eg. optimize IFs without ELSE...
1849 stmt.o1.u1 = instr->_ops[0]->code.globaladdr;
1852 if (ontrue->generated) {
1853 stmt.opcode = INSTR_IF;
1854 stmt.o2.s1 = (ontrue->code_start-1) - code_statements_elements;
1855 if (code_statements_add(stmt) < 0)
1858 if (onfalse->generated) {
1859 stmt.opcode = INSTR_IFNOT;
1860 stmt.o2.s1 = (onfalse->code_start-1) - code_statements_elements;
1861 if (code_statements_add(stmt) < 0)
1864 if (!ontrue->generated) {
1865 if (onfalse->generated) {
1870 if (!onfalse->generated) {
1871 if (ontrue->generated) {
1876 /* neither ontrue nor onfalse exist */
1877 stmt.opcode = INSTR_IFNOT;
1878 stidx = code_statements_elements - 1;
1879 if (code_statements_add(stmt) < 0)
1881 stptr = &code_statements_data[stidx];
1882 /* on false we jump, so add ontrue-path */
1883 if (!gen_blocks_recursive(func, ontrue))
1885 /* fixup the jump address */
1886 stptr->o2.s1 = (ontrue->code_start-1) - (stidx+1);
1887 /* generate onfalse path */
1888 if (onfalse->generated) {
1889 /* may have been generated in the previous recursive call */
1890 stmt.opcode = INSTR_GOTO;
1893 stmt.o1.s1 = (onfalse->code_start-1) - code_statements_elements;
1894 return (code_statements_add(stmt) >= 0);
1896 /* if not, generate now */
1901 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
1902 printf("TODO: call instruction\n");
1906 if (instr->opcode == INSTR_STATE) {
1907 printf("TODO: state instruction\n");
1911 stmt.opcode = instr->opcode;
1916 /* This is the general order of operands */
1918 stmt.o3.u1 = instr->_ops[0]->code.globaladdr;
1921 stmt.o1.u1 = instr->_ops[1]->code.globaladdr;
1924 stmt.o2.u1 = instr->_ops[2]->code.globaladdr;
1926 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
1928 stmt.o1.u1 = stmt.o3.u1;
1931 else if ((stmt.opcode >= INSTR_STORE_F &&
1932 stmt.opcode <= INSTR_STORE_FNC) ||
1933 (stmt.opcode >= INSTR_NOT_F &&
1934 stmt.opcode <= INSTR_NOT_FNC))
1936 /* 2-operand instructions with A -> B */
1937 stmt.o2.u1 = stmt.o3.u1;
1941 if (code_statements_add(stmt) < 0)
1947 static bool gen_function_code(ir_function *self)
1951 /* Starting from entry point, we generate blocks "as they come"
1952 * for now. Dead blocks will not be translated obviously.
1954 if (!self->blocks_count) {
1955 printf("Function '%s' declared without body.\n", self->name);
1959 block = self->blocks[0];
1960 if (block->generated)
1963 if (!gen_blocks_recursive(self, block)) {
1964 printf("failed to generate blocks for '%s'\n", self->name);
1970 static bool gen_global_function(ir_builder *ir, ir_value *global)
1972 prog_section_function fun;
1977 if (!global->isconst ||
1978 !global->constval.vfunc)
1980 printf("Invalid state of function-global: not constant: %s\n", global->name);
1984 irfun = global->constval.vfunc;
1986 fun.name = global->code.name;
1987 fun.file = code_cachedstring(global->context.file);
1988 fun.profile = 0; /* always 0 */
1989 fun.nargs = irfun->params_count;
1991 for (i = 0;i < 8; ++i) {
1994 else if (irfun->params[i] == TYPE_VECTOR)
2000 fun.firstlocal = code_globals_elements;
2001 fun.locals = irfun->locals_count;
2002 for (i = 0; i < irfun->locals_count; ++i) {
2003 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2004 printf("Failed to generate global %s\n", irfun->locals[i]->name);
2009 fun.entry = code_statements_elements;
2010 if (!gen_function_code(irfun)) {
2011 printf("Failed to generate code for function %s\n", irfun->name);
2015 return (code_functions_add(fun) >= 0);
2018 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2021 prog_section_def def;
2023 def.type = global->vtype;
2024 def.offset = code_globals_elements;
2025 def.name = global->code.name = code_genstring(global->name);
2027 switch (global->vtype)
2030 if (code_defs_add(def) < 0)
2032 return gen_global_pointer(global);
2034 if (code_defs_add(def) < 0)
2036 return gen_global_field(global);
2041 if (code_defs_add(def) < 0)
2044 if (global->isconst) {
2045 iptr = (int32_t*)&global->constval.vfloat;
2046 global->code.globaladdr = code_globals_add(*iptr);
2048 global->code.globaladdr = code_globals_add(0);
2050 return global->code.globaladdr >= 0;
2054 if (code_defs_add(def) < 0)
2056 if (global->isconst)
2057 global->code.globaladdr = code_globals_add(code_cachedstring(global->constval.vstring));
2059 global->code.globaladdr = code_globals_add(0);
2060 return global->code.globaladdr >= 0;
2064 if (code_defs_add(def) < 0)
2067 if (global->isconst) {
2068 iptr = (int32_t*)&global->constval.vvec;
2069 global->code.globaladdr = code_globals_add(iptr[0]);
2070 if (code_globals_add(iptr[1]) < 0 || code_globals_add(iptr[2]) < 0)
2073 global->code.globaladdr = code_globals_add(0);
2074 if (code_globals_add(0) < 0 || code_globals_add(0) < 0)
2077 return global->code.globaladdr >= 0;
2080 if (code_defs_add(def) < 0)
2082 code_globals_add(code_functions_elements);
2083 return gen_global_function(self, global);
2085 /* assume biggest type */
2086 global->code.globaladdr = code_globals_add(0);
2087 code_globals_add(0);
2088 code_globals_add(0);
2091 /* refuse to create 'void' type or any other fancy business. */
2092 printf("Invalid type for global variable %s\n", global->name);
2097 bool ir_builder_generate(ir_builder *self, const char *filename)
2103 /* FIXME: generate TYPE_FUNCTION globals and link them
2104 * to their ir_function.
2107 for (i = 0; i < self->functions_count; ++i)
2110 ir_function *fun = self->functions[i];
2112 funval = ir_builder_create_global(self, fun->name, TYPE_FUNCTION);
2113 funval->isconst = true;
2114 funval->constval.vfunc = fun;
2115 funval->context = fun->context;
2118 for (i = 0; i < self->globals_count; ++i)
2120 if (!ir_builder_gen_global(self, self->globals[i])) {
2125 printf("writing '%s'...\n", filename);
2126 return code_write(filename);
2129 /***********************************************************************
2130 *IR DEBUG Dump functions...
2133 #define IND_BUFSZ 1024
2135 const char *qc_opname(int op)
2137 if (op < 0) return "<INVALID>";
2138 if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2139 return asm_instr[op].m;
2141 case VINSTR_PHI: return "PHI";
2142 case VINSTR_JUMP: return "JUMP";
2143 case VINSTR_COND: return "COND";
2144 default: return "<UNK>";
2148 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2151 char indent[IND_BUFSZ];
2155 oprintf("module %s\n", b->name);
2156 for (i = 0; i < b->globals_count; ++i)
2159 if (b->globals[i]->isconst)
2160 oprintf("%s = ", b->globals[i]->name);
2161 ir_value_dump(b->globals[i], oprintf);
2164 for (i = 0; i < b->functions_count; ++i)
2165 ir_function_dump(b->functions[i], indent, oprintf);
2166 oprintf("endmodule %s\n", b->name);
2169 void ir_function_dump(ir_function *f, char *ind,
2170 int (*oprintf)(const char*, ...))
2173 oprintf("%sfunction %s\n", ind, f->name);
2174 strncat(ind, "\t", IND_BUFSZ);
2175 if (f->locals_count)
2177 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2178 for (i = 0; i < f->locals_count; ++i) {
2179 oprintf("%s\t", ind);
2180 ir_value_dump(f->locals[i], oprintf);
2184 if (f->blocks_count)
2186 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
2187 for (i = 0; i < f->blocks_count; ++i) {
2188 if (f->blocks[i]->run_id != f->run_id) {
2189 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
2191 ir_block_dump(f->blocks[i], ind, oprintf);
2195 ind[strlen(ind)-1] = 0;
2196 oprintf("%sendfunction %s\n", ind, f->name);
2199 void ir_block_dump(ir_block* b, char *ind,
2200 int (*oprintf)(const char*, ...))
2203 oprintf("%s:%s\n", ind, b->label);
2204 strncat(ind, "\t", IND_BUFSZ);
2206 for (i = 0; i < b->instr_count; ++i)
2207 ir_instr_dump(b->instr[i], ind, oprintf);
2208 ind[strlen(ind)-1] = 0;
2211 void dump_phi(ir_instr *in, char *ind,
2212 int (*oprintf)(const char*, ...))
2215 oprintf("%s <- phi ", in->_ops[0]->name);
2216 for (i = 0; i < in->phi_count; ++i)
2218 oprintf("([%s] : %s) ", in->phi[i].from->label,
2219 in->phi[i].value->name);
2224 void ir_instr_dump(ir_instr *in, char *ind,
2225 int (*oprintf)(const char*, ...))
2228 const char *comma = NULL;
2230 oprintf("%s (%i) ", ind, (int)in->eid);
2232 if (in->opcode == VINSTR_PHI) {
2233 dump_phi(in, ind, oprintf);
2237 strncat(ind, "\t", IND_BUFSZ);
2239 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
2240 ir_value_dump(in->_ops[0], oprintf);
2241 if (in->_ops[1] || in->_ops[2])
2244 oprintf("%s\t", qc_opname(in->opcode));
2245 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
2246 ir_value_dump(in->_ops[0], oprintf);
2251 for (i = 1; i != 3; ++i) {
2255 ir_value_dump(in->_ops[i], oprintf);
2263 oprintf("[%s]", in->bops[0]->label);
2267 oprintf("%s[%s]", comma, in->bops[1]->label);
2269 ind[strlen(ind)-1] = 0;
2272 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
2280 oprintf("%g", v->constval.vfloat);
2283 oprintf("'%g %g %g'",
2286 v->constval.vvec.z);
2289 oprintf("(entity)");
2292 oprintf("\"%s\"", v->constval.vstring);
2296 oprintf("%i", v->constval.vint);
2301 v->constval.vpointer->name);
2305 oprintf("%s", v->name);
2309 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
2312 oprintf("Life of %s:\n", self->name);
2313 for (i = 0; i < self->life_count; ++i)
2315 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);