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);
130 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
133 for (i = 0; i < self->globals_count; ++i) {
134 if (!strcmp(self->globals[i]->name, name))
135 return self->globals[i];
140 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
142 ir_value *ve = ir_builder_get_global(self, name);
147 ve = ir_value_var(name, store_global, vtype);
148 if (!ir_builder_globals_add(self, ve)) {
155 /***********************************************************************
159 bool ir_function_naive_phi(ir_function*);
160 void ir_function_enumerate(ir_function*);
161 bool ir_function_calculate_liferanges(ir_function*);
162 bool ir_function_allocate_locals(ir_function*);
164 ir_function* ir_function_new(ir_builder* owner, int outtype)
167 self = (ir_function*)mem_a(sizeof(*self));
173 if (!ir_function_set_name(self, "<@unnamed>")) {
178 self->context.file = "<@no context>";
179 self->context.line = 0;
180 self->outtype = outtype;
181 MEM_VECTOR_INIT(self, params);
182 MEM_VECTOR_INIT(self, blocks);
183 MEM_VECTOR_INIT(self, values);
184 MEM_VECTOR_INIT(self, locals);
189 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
190 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
191 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
193 bool ir_function_set_name(ir_function *self, const char *name)
196 mem_d((void*)self->name);
197 self->name = util_strdup(name);
201 void ir_function_delete(ir_function *self)
204 mem_d((void*)self->name);
206 for (i = 0; i != self->blocks_count; ++i)
207 ir_block_delete(self->blocks[i]);
208 MEM_VECTOR_CLEAR(self, blocks);
210 MEM_VECTOR_CLEAR(self, params);
212 for (i = 0; i != self->values_count; ++i)
213 ir_value_delete(self->values[i]);
214 MEM_VECTOR_CLEAR(self, values);
216 for (i = 0; i != self->locals_count; ++i)
217 ir_value_delete(self->locals[i]);
218 MEM_VECTOR_CLEAR(self, locals);
223 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
225 return ir_function_values_add(self, v);
228 ir_block* ir_function_create_block(ir_function *self, const char *label)
230 ir_block* bn = ir_block_new(self, label);
231 memcpy(&bn->context, &self->context, sizeof(self->context));
232 if (!ir_function_blocks_add(self, bn)) {
239 bool ir_function_finalize(ir_function *self)
241 if (!ir_function_naive_phi(self))
244 ir_function_enumerate(self);
246 if (!ir_function_calculate_liferanges(self))
249 if (!ir_function_allocate_locals(self))
254 ir_value* ir_function_get_local(ir_function *self, const char *name)
257 for (i = 0; i < self->locals_count; ++i) {
258 if (!strcmp(self->locals[i]->name, name))
259 return self->locals[i];
264 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype)
266 ir_value *ve = ir_function_get_local(self, name);
271 ve = ir_value_var(name, store_local, vtype);
272 if (!ir_function_locals_add(self, ve)) {
279 /***********************************************************************
283 ir_block* ir_block_new(ir_function* owner, const char *name)
286 self = (ir_block*)mem_a(sizeof(*self));
290 memset(self, 0, sizeof(*self));
293 if (!ir_block_set_label(self, name)) {
298 self->context.file = "<@no context>";
299 self->context.line = 0;
301 MEM_VECTOR_INIT(self, instr);
302 MEM_VECTOR_INIT(self, entries);
303 MEM_VECTOR_INIT(self, exits);
306 self->is_return = false;
308 MEM_VECTOR_INIT(self, living);
310 self->generated = false;
314 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
315 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
316 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
317 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
319 void ir_block_delete(ir_block* self)
323 for (i = 0; i != self->instr_count; ++i)
324 ir_instr_delete(self->instr[i]);
325 MEM_VECTOR_CLEAR(self, instr);
326 MEM_VECTOR_CLEAR(self, entries);
327 MEM_VECTOR_CLEAR(self, exits);
328 MEM_VECTOR_CLEAR(self, living);
332 bool ir_block_set_label(ir_block *self, const char *name)
335 mem_d((void*)self->label);
336 self->label = util_strdup(name);
337 return !!self->label;
340 /***********************************************************************
344 ir_instr* ir_instr_new(ir_block* owner, int op)
347 self = (ir_instr*)mem_a(sizeof(*self));
352 self->context.file = "<@no context>";
353 self->context.line = 0;
355 self->_ops[0] = NULL;
356 self->_ops[1] = NULL;
357 self->_ops[2] = NULL;
358 self->bops[0] = NULL;
359 self->bops[1] = NULL;
360 MEM_VECTOR_INIT(self, phi);
361 MEM_VECTOR_INIT(self, params);
366 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
367 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
369 void ir_instr_delete(ir_instr *self)
372 /* The following calls can only delete from
373 * vectors, we still want to delete this instruction
374 * so ignore the return value. Since with the warn_unused_result attribute
375 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
376 * I have to improvise here and use if(foo());
378 for (i = 0; i < self->phi_count; ++i) {
380 if (ir_value_writes_find(self->phi[i].value, self, &idx))
381 if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
382 if (ir_value_reads_find(self->phi[i].value, self, &idx))
383 if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
385 MEM_VECTOR_CLEAR(self, phi);
386 for (i = 0; i < self->params_count; ++i) {
388 if (ir_value_writes_find(self->params[i], self, &idx))
389 if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
390 if (ir_value_reads_find(self->params[i], self, &idx))
391 if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
393 MEM_VECTOR_CLEAR(self, params);
394 if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
395 if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
396 if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
400 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
402 if (self->_ops[op]) {
404 if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
406 if (!ir_value_writes_remove(self->_ops[op], idx))
409 else if (ir_value_reads_find(self->_ops[op], self, &idx))
411 if (!ir_value_reads_remove(self->_ops[op], idx))
417 if (!ir_value_writes_add(v, self))
420 if (!ir_value_reads_add(v, self))
428 /***********************************************************************
432 ir_value* ir_value_var(const char *name, int storetype, int vtype)
435 self = (ir_value*)mem_a(sizeof(*self));
437 self->fieldtype = TYPE_VOID;
438 self->outtype = TYPE_VOID;
439 self->store = storetype;
440 MEM_VECTOR_INIT(self, reads);
441 MEM_VECTOR_INIT(self, writes);
442 self->isconst = false;
443 self->context.file = "<@no context>";
444 self->context.line = 0;
446 ir_value_set_name(self, name);
448 memset(&self->constval, 0, sizeof(self->constval));
449 memset(&self->code, 0, sizeof(self->code));
451 MEM_VECTOR_INIT(self, life);
454 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
455 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
456 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
458 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
460 ir_value *v = ir_value_var(name, storetype, vtype);
463 if (!ir_function_collect_value(owner, v))
471 void ir_value_delete(ir_value* self)
474 mem_d((void*)self->name);
477 if (self->vtype == TYPE_STRING)
478 mem_d((void*)self->constval.vstring);
480 MEM_VECTOR_CLEAR(self, reads);
481 MEM_VECTOR_CLEAR(self, writes);
482 MEM_VECTOR_CLEAR(self, life);
486 void ir_value_set_name(ir_value *self, const char *name)
489 mem_d((void*)self->name);
490 self->name = util_strdup(name);
493 bool ir_value_set_float(ir_value *self, float f)
495 if (self->vtype != TYPE_FLOAT)
497 self->constval.vfloat = f;
498 self->isconst = true;
502 bool ir_value_set_vector(ir_value *self, vector v)
504 if (self->vtype != TYPE_VECTOR)
506 self->constval.vvec = v;
507 self->isconst = true;
511 bool ir_value_set_string(ir_value *self, const char *str)
513 if (self->vtype != TYPE_STRING)
515 self->constval.vstring = util_strdup(str);
516 self->isconst = true;
521 bool ir_value_set_int(ir_value *self, int i)
523 if (self->vtype != TYPE_INTEGER)
525 self->constval.vint = i;
526 self->isconst = true;
531 bool ir_value_lives(ir_value *self, size_t at)
534 for (i = 0; i < self->life_count; ++i)
536 ir_life_entry_t *life = &self->life[i];
537 if (life->start <= at && at <= life->end)
539 if (life->start > at) /* since it's ordered */
545 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
548 if (!ir_value_life_add(self, e)) /* naive... */
550 for (k = self->life_count-1; k > idx; --k)
551 self->life[k] = self->life[k-1];
556 bool ir_value_life_merge(ir_value *self, size_t s)
559 ir_life_entry_t *life = NULL;
560 ir_life_entry_t *before = NULL;
561 ir_life_entry_t new_entry;
563 /* Find the first range >= s */
564 for (i = 0; i < self->life_count; ++i)
567 life = &self->life[i];
571 /* nothing found? append */
572 if (i == self->life_count) {
574 if (life && life->end+1 == s)
576 /* previous life range can be merged in */
580 if (life && life->end >= s)
583 if (!ir_value_life_add(self, e))
584 return false; /* failing */
590 if (before->end + 1 == s &&
591 life->start - 1 == s)
594 before->end = life->end;
595 if (!ir_value_life_remove(self, i))
596 return false; /* failing */
599 if (before->end + 1 == s)
605 /* already contained */
606 if (before->end >= s)
610 if (life->start - 1 == s)
615 /* insert a new entry */
616 new_entry.start = new_entry.end = s;
617 return ir_value_life_insert(self, i, new_entry);
620 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
624 if (!other->life_count)
627 if (!self->life_count) {
628 for (i = 0; i < other->life_count; ++i) {
629 if (!ir_value_life_add(self, other->life[i]))
636 for (i = 0; i < other->life_count; ++i)
638 const ir_life_entry_t *life = &other->life[i];
641 ir_life_entry_t *entry = &self->life[myi];
643 if (life->end+1 < entry->start)
645 /* adding an interval before entry */
646 if (!ir_value_life_insert(self, myi, *life))
652 if (life->start < entry->start &&
653 life->end >= entry->start)
655 /* starts earlier and overlaps */
656 entry->start = life->start;
659 if (life->end > entry->end &&
660 life->start-1 <= entry->end)
662 /* ends later and overlaps */
663 entry->end = life->end;
666 /* see if our change combines it with the next ranges */
667 while (myi+1 < self->life_count &&
668 entry->end+1 >= self->life[1+myi].start)
670 /* overlaps with (myi+1) */
671 if (entry->end < self->life[1+myi].end)
672 entry->end = self->life[1+myi].end;
673 if (!ir_value_life_remove(self, myi+1))
675 entry = &self->life[myi];
678 /* see if we're after the entry */
679 if (life->start > entry->end)
682 /* append if we're at the end */
683 if (myi >= self->life_count) {
684 if (!ir_value_life_add(self, *life))
688 /* otherweise check the next range */
697 bool ir_values_overlap(const ir_value *a, const ir_value *b)
699 /* For any life entry in A see if it overlaps with
700 * any life entry in B.
701 * Note that the life entries are orderes, so we can make a
702 * more efficient algorithm there than naively translating the
706 ir_life_entry_t *la, *lb, *enda, *endb;
708 /* first of all, if either has no life range, they cannot clash */
709 if (!a->life_count || !b->life_count)
714 enda = la + a->life_count;
715 endb = lb + b->life_count;
718 /* check if the entries overlap, for that,
719 * both must start before the other one ends.
721 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
722 if (la->start <= lb->end &&
723 lb->start <= la->end)
725 if (la->start < lb->end &&
732 /* entries are ordered
733 * one entry is earlier than the other
734 * that earlier entry will be moved forward
736 if (la->start < lb->start)
738 /* order: A B, move A forward
739 * check if we hit the end with A
744 else if (lb->start < la->start)
746 /* order: B A, move B forward
747 * check if we hit the end with B
756 /***********************************************************************
760 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
762 if (target->store == store_value) {
763 fprintf(stderr, "cannot store to an SSA value\n");
764 fprintf(stderr, "trying to store: %s <- %s\n", target->name, what->name);
767 ir_instr *in = ir_instr_new(self, op);
770 if (!ir_instr_op(in, 0, target, true) ||
771 !ir_instr_op(in, 1, what, false) ||
772 !ir_block_instr_add(self, in) )
780 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
784 if (target->vtype == TYPE_VARIANT)
787 vtype = target->vtype;
792 if (what->vtype == TYPE_INTEGER)
793 op = INSTR_CONV_ITOF;
802 op = INSTR_STORE_ENT;
808 op = INSTR_STORE_FLD;
812 if (what->vtype == TYPE_INTEGER)
813 op = INSTR_CONV_FTOI;
822 op = INSTR_STORE_ENT;
829 return ir_block_create_store_op(self, op, target, what);
832 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
837 if (target->vtype != TYPE_POINTER)
840 /* storing using pointer - target is a pointer, type must be
841 * inferred from source
853 op = INSTR_STOREP_ENT;
859 op = INSTR_STOREP_FLD;
870 op = INSTR_STOREP_ENT;
877 return ir_block_create_store_op(self, op, target, what);
880 bool ir_block_create_return(ir_block *self, ir_value *v)
884 fprintf(stderr, "block already ended (%s)\n", self->label);
888 self->is_return = true;
889 in = ir_instr_new(self, INSTR_RETURN);
893 if (!ir_instr_op(in, 0, v, false) ||
894 !ir_block_instr_add(self, in) )
901 bool ir_block_create_if(ir_block *self, ir_value *v,
902 ir_block *ontrue, ir_block *onfalse)
906 fprintf(stderr, "block already ended (%s)\n", self->label);
910 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
911 in = ir_instr_new(self, VINSTR_COND);
915 if (!ir_instr_op(in, 0, v, false)) {
920 in->bops[0] = ontrue;
921 in->bops[1] = onfalse;
923 if (!ir_block_instr_add(self, in))
926 if (!ir_block_exits_add(self, ontrue) ||
927 !ir_block_exits_add(self, onfalse) ||
928 !ir_block_entries_add(ontrue, self) ||
929 !ir_block_entries_add(onfalse, self) )
936 bool ir_block_create_jump(ir_block *self, ir_block *to)
940 fprintf(stderr, "block already ended (%s)\n", self->label);
944 in = ir_instr_new(self, VINSTR_JUMP);
949 if (!ir_block_instr_add(self, in))
952 if (!ir_block_exits_add(self, to) ||
953 !ir_block_entries_add(to, self) )
960 bool ir_block_create_goto(ir_block *self, ir_block *to)
964 fprintf(stderr, "block already ended (%s)\n", self->label);
968 in = ir_instr_new(self, INSTR_GOTO);
973 if (!ir_block_instr_add(self, in))
976 if (!ir_block_exits_add(self, to) ||
977 !ir_block_entries_add(to, self) )
984 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
988 in = ir_instr_new(self, VINSTR_PHI);
991 out = ir_value_out(self->owner, label, store_value, ot);
996 if (!ir_instr_op(in, 0, out, true)) {
998 ir_value_delete(out);
1001 if (!ir_block_instr_add(self, in)) {
1002 ir_instr_delete(in);
1003 ir_value_delete(out);
1009 ir_value* ir_phi_value(ir_instr *self)
1011 return self->_ops[0];
1014 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1018 if (!ir_block_entries_find(self->owner, b, NULL)) {
1019 /* Must not be possible to cause this, otherwise the AST
1020 * is doing something wrong.
1022 fprintf(stderr, "Invalid entry block for PHI\n");
1028 if (!ir_value_reads_add(v, self))
1030 return ir_instr_phi_add(self, pe);
1033 /* call related code */
1034 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1038 in = ir_instr_new(self, INSTR_CALL0);
1041 out = ir_value_out(self->owner, label, store_value, func->outtype);
1043 ir_instr_delete(in);
1046 if (!ir_instr_op(in, 0, out, true) ||
1047 !ir_instr_op(in, 1, func, false) ||
1048 !ir_block_instr_add(self, in))
1050 ir_instr_delete(in);
1051 ir_value_delete(out);
1057 ir_value* ir_call_value(ir_instr *self)
1059 return self->_ops[0];
1062 bool ir_call_param(ir_instr* self, ir_value *v)
1064 if (!ir_instr_params_add(self, v))
1066 if (!ir_value_reads_add(v, self)) {
1067 if (!ir_instr_params_remove(self, self->params_count-1))
1068 GMQCC_SUPPRESS_EMPTY_BODY;
1074 /* binary op related code */
1076 ir_value* ir_block_create_binop(ir_block *self,
1077 const char *label, int opcode,
1078 ir_value *left, ir_value *right)
1100 case INSTR_SUB_S: /* -- offset of string as float */
1105 case INSTR_BITOR_IF:
1106 case INSTR_BITOR_FI:
1107 case INSTR_BITAND_FI:
1108 case INSTR_BITAND_IF:
1123 case INSTR_BITAND_I:
1126 case INSTR_RSHIFT_I:
1127 case INSTR_LSHIFT_I:
1149 /* boolean operations result in floats */
1150 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1152 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1155 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1160 if (ot == TYPE_VOID) {
1161 /* The AST or parser were supposed to check this! */
1165 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1168 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1169 int op, ir_value *a, ir_value *b, int outype)
1174 out = ir_value_out(self->owner, label, store_value, outype);
1178 instr = ir_instr_new(self, op);
1180 ir_value_delete(out);
1184 if (!ir_instr_op(instr, 0, out, true) ||
1185 !ir_instr_op(instr, 1, a, false) ||
1186 !ir_instr_op(instr, 2, b, false) )
1191 if (!ir_block_instr_add(self, instr))
1196 ir_instr_delete(instr);
1197 ir_value_delete(out);
1201 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1203 /* Support for various pointer types todo if so desired */
1204 if (ent->vtype != TYPE_ENTITY)
1207 if (field->vtype != TYPE_FIELD)
1210 return ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1213 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1216 if (ent->vtype != TYPE_ENTITY)
1219 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1220 if (field->vtype != TYPE_FIELD)
1225 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1226 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1227 case TYPE_STRING: op = INSTR_LOAD_S; break;
1228 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1229 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1231 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1232 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1238 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1241 ir_value* ir_block_create_add(ir_block *self,
1243 ir_value *left, ir_value *right)
1246 int l = left->vtype;
1247 int r = right->vtype;
1266 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1268 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1274 return ir_block_create_binop(self, label, op, left, right);
1277 ir_value* ir_block_create_sub(ir_block *self,
1279 ir_value *left, ir_value *right)
1282 int l = left->vtype;
1283 int r = right->vtype;
1303 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1305 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1311 return ir_block_create_binop(self, label, op, left, right);
1314 ir_value* ir_block_create_mul(ir_block *self,
1316 ir_value *left, ir_value *right)
1319 int l = left->vtype;
1320 int r = right->vtype;
1339 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1341 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1344 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1346 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1348 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1350 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1356 return ir_block_create_binop(self, label, op, left, right);
1359 ir_value* ir_block_create_div(ir_block *self,
1361 ir_value *left, ir_value *right)
1364 int l = left->vtype;
1365 int r = right->vtype;
1382 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1384 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1386 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1392 return ir_block_create_binop(self, label, op, left, right);
1395 /* PHI resolving breaks the SSA, and must thus be the last
1396 * step before life-range calculation.
1399 static bool ir_block_naive_phi(ir_block *self);
1400 bool ir_function_naive_phi(ir_function *self)
1404 for (i = 0; i < self->blocks_count; ++i)
1406 if (!ir_block_naive_phi(self->blocks[i]))
1412 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1417 /* create a store */
1418 if (!ir_block_create_store(block, old, what))
1421 /* we now move it up */
1422 instr = block->instr[block->instr_count-1];
1423 for (i = block->instr_count; i > iid; --i)
1424 block->instr[i] = block->instr[i-1];
1425 block->instr[i] = instr;
1430 static bool ir_block_naive_phi(ir_block *self)
1433 /* FIXME: optionally, create_phi can add the phis
1434 * to a list so we don't need to loop through blocks
1435 * - anyway: "don't optimize YET"
1437 for (i = 0; i < self->instr_count; ++i)
1439 ir_instr *instr = self->instr[i];
1440 if (instr->opcode != VINSTR_PHI)
1443 if (!ir_block_instr_remove(self, i))
1445 --i; /* NOTE: i+1 below */
1447 for (p = 0; p < instr->phi_count; ++p)
1449 ir_value *v = instr->phi[p].value;
1450 for (w = 0; w < v->writes_count; ++w) {
1453 if (!v->writes[w]->_ops[0])
1456 /* When the write was to a global, we have to emit a mov */
1457 old = v->writes[w]->_ops[0];
1459 /* The original instruction now writes to the PHI target local */
1460 if (v->writes[w]->_ops[0] == v)
1461 v->writes[w]->_ops[0] = instr->_ops[0];
1463 if (old->store != store_value && old->store != store_local)
1465 /* If it originally wrote to a global we need to store the value
1468 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1470 if (i+1 < self->instr_count)
1471 instr = self->instr[i+1];
1474 /* In case I forget and access instr later, it'll be NULL
1475 * when it's a problem, to make sure we crash, rather than accessing
1481 /* If it didn't, we can replace all reads by the phi target now. */
1483 for (r = 0; r < old->reads_count; ++r)
1486 ir_instr *ri = old->reads[r];
1487 for (op = 0; op < ri->phi_count; ++op) {
1488 if (ri->phi[op].value == old)
1489 ri->phi[op].value = v;
1491 for (op = 0; op < 3; ++op) {
1492 if (ri->_ops[op] == old)
1499 ir_instr_delete(instr);
1504 /***********************************************************************
1505 *IR Temp allocation code
1506 * Propagating value life ranges by walking through the function backwards
1507 * until no more changes are made.
1508 * In theory this should happen once more than once for every nested loop
1510 * Though this implementation might run an additional time for if nests.
1519 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1521 /* Enumerate instructions used by value's life-ranges
1523 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1527 for (i = 0; i < self->instr_count; ++i)
1529 self->instr[i]->eid = eid++;
1534 /* Enumerate blocks and instructions.
1535 * The block-enumeration is unordered!
1536 * We do not really use the block enumreation, however
1537 * the instruction enumeration is important for life-ranges.
1539 void ir_function_enumerate(ir_function *self)
1542 size_t instruction_id = 0;
1543 for (i = 0; i < self->blocks_count; ++i)
1545 self->blocks[i]->eid = i;
1546 self->blocks[i]->run_id = 0;
1547 ir_block_enumerate(self->blocks[i], &instruction_id);
1551 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1552 bool ir_function_calculate_liferanges(ir_function *self)
1560 for (i = 0; i != self->blocks_count; ++i)
1562 if (self->blocks[i]->is_return)
1564 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1572 /* Local-value allocator
1573 * After finishing creating the liferange of all values used in a function
1574 * we can allocate their global-positions.
1575 * This is the counterpart to register-allocation in register machines.
1578 MEM_VECTOR_MAKE(ir_value*, locals);
1579 MEM_VECTOR_MAKE(size_t, sizes);
1580 MEM_VECTOR_MAKE(size_t, positions);
1581 } function_allocator;
1582 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1583 MEM_VEC_FUNCTIONS(function_allocator, size_t, sizes)
1584 MEM_VEC_FUNCTIONS(function_allocator, size_t, positions)
1586 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1589 size_t vsize = type_sizeof[var->vtype];
1591 slot = ir_value_var("reg", store_global, var->vtype);
1595 if (!ir_value_life_merge_into(slot, var))
1598 if (!function_allocator_locals_add(alloc, slot))
1601 if (!function_allocator_sizes_add(alloc, vsize))
1607 ir_value_delete(slot);
1611 bool ir_function_allocate_locals(ir_function *self)
1620 function_allocator alloc;
1622 MEM_VECTOR_INIT(&alloc, locals);
1623 MEM_VECTOR_INIT(&alloc, sizes);
1624 MEM_VECTOR_INIT(&alloc, positions);
1626 for (i = 0; i < self->locals_count; ++i)
1628 if (!function_allocator_alloc(&alloc, self->locals[i]))
1632 /* Allocate a slot for any value that still exists */
1633 for (i = 0; i < self->values_count; ++i)
1635 v = self->values[i];
1640 for (a = 0; a < alloc.locals_count; ++a)
1642 slot = alloc.locals[a];
1644 if (ir_values_overlap(v, slot))
1647 if (!ir_value_life_merge_into(slot, v))
1650 /* adjust size for this slot */
1651 if (alloc.sizes[a] < type_sizeof[v->vtype])
1652 alloc.sizes[a] = type_sizeof[v->vtype];
1654 self->values[i]->code.local = a;
1657 if (a >= alloc.locals_count) {
1658 self->values[i]->code.local = alloc.locals_count;
1659 if (!function_allocator_alloc(&alloc, v))
1664 /* Adjust slot positions based on sizes */
1665 if (!function_allocator_positions_add(&alloc, 0))
1668 if (alloc.sizes_count)
1669 pos = alloc.positions[0] + alloc.sizes[0];
1672 for (i = 1; i < alloc.sizes_count; ++i)
1674 pos = alloc.positions[i-1] + alloc.sizes[i-1];
1675 if (!function_allocator_positions_add(&alloc, pos))
1679 self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1681 /* Take over the actual slot positions */
1682 for (i = 0; i < self->values_count; ++i)
1683 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1690 for (i = 0; i < alloc.locals_count; ++i)
1691 ir_value_delete(alloc.locals[i]);
1692 MEM_VECTOR_CLEAR(&alloc, locals);
1693 MEM_VECTOR_CLEAR(&alloc, sizes);
1694 MEM_VECTOR_CLEAR(&alloc, positions);
1698 /* Get information about which operand
1699 * is read from, or written to.
1701 static void ir_op_read_write(int op, size_t *read, size_t *write)
1728 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1731 bool changed = false;
1733 for (i = 0; i != self->living_count; ++i)
1735 tempbool = ir_value_life_merge(self->living[i], eid);
1738 fprintf(stderr, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1740 changed = changed || tempbool;
1745 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1748 /* values which have been read in a previous iteration are now
1749 * in the "living" array even if the previous block doesn't use them.
1750 * So we have to remove whatever does not exist in the previous block.
1751 * They will be re-added on-read, but the liferange merge won't cause
1754 for (i = 0; i < self->living_count; ++i)
1756 if (!ir_block_living_find(prev, self->living[i], NULL)) {
1757 if (!ir_block_living_remove(self, i))
1763 /* Whatever the previous block still has in its living set
1764 * must now be added to ours as well.
1766 for (i = 0; i < prev->living_count; ++i)
1768 if (ir_block_living_find(self, prev->living[i], NULL))
1770 if (!ir_block_living_add(self, prev->living[i]))
1773 printf("%s got from prev: %s\n", self->label, prev->living[i]->_name);
1779 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
1785 /* bitmasks which operands are read from or written to */
1787 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1789 new_reads_t new_reads;
1791 char dbg_ind[16] = { '#', '0' };
1794 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1795 MEM_VECTOR_INIT(&new_reads, v);
1800 if (!ir_block_life_prop_previous(self, prev, changed))
1804 i = self->instr_count;
1807 instr = self->instr[i];
1809 /* PHI operands are always read operands */
1810 for (p = 0; p < instr->phi_count; ++p)
1812 value = instr->phi[p].value;
1813 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1814 if (!ir_block_living_find(self, value, NULL) &&
1815 !ir_block_living_add(self, value))
1820 if (!new_reads_t_v_find(&new_reads, value, NULL))
1822 if (!new_reads_t_v_add(&new_reads, value))
1828 /* See which operands are read and write operands */
1829 ir_op_read_write(instr->opcode, &read, &write);
1831 /* Go through the 3 main operands */
1832 for (o = 0; o < 3; ++o)
1834 if (!instr->_ops[o]) /* no such operand */
1837 value = instr->_ops[o];
1839 /* We only care about locals */
1840 if (value->store != store_value &&
1841 value->store != store_local)
1847 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1848 if (!ir_block_living_find(self, value, NULL) &&
1849 !ir_block_living_add(self, value))
1854 /* fprintf(stderr, "read: %s\n", value->_name); */
1855 if (!new_reads_t_v_find(&new_reads, value, NULL))
1857 if (!new_reads_t_v_add(&new_reads, value))
1863 /* write operands */
1864 /* When we write to a local, we consider it "dead" for the
1865 * remaining upper part of the function, since in SSA a value
1866 * can only be written once (== created)
1871 bool in_living = ir_block_living_find(self, value, &idx);
1872 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1874 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
1875 if (!in_living && !in_reads)
1880 /* If the value isn't alive it hasn't been read before... */
1881 /* TODO: See if the warning can be emitted during parsing or AST processing
1882 * otherwise have warning printed here.
1883 * IF printing a warning here: include filecontext_t,
1884 * and make sure it's only printed once
1885 * since this function is run multiple times.
1887 /* For now: debug info: */
1888 fprintf(stderr, "Value only written %s\n", value->name);
1889 tempbool = ir_value_life_merge(value, instr->eid);
1890 *changed = *changed || tempbool;
1892 ir_instr_dump(instr, dbg_ind, printf);
1896 /* since 'living' won't contain it
1897 * anymore, merge the value, since
1900 tempbool = ir_value_life_merge(value, instr->eid);
1903 fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
1905 *changed = *changed || tempbool;
1907 #if ! defined(LIFE_RANGE_WITHOUT_LAST_READ)
1908 if (!ir_block_living_remove(self, idx))
1913 if (!new_reads_t_v_remove(&new_reads, readidx))
1921 tempbool = ir_block_living_add_instr(self, instr->eid);
1922 /*fprintf(stderr, "living added values\n");*/
1923 *changed = *changed || tempbool;
1925 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1927 for (rd = 0; rd < new_reads.v_count; ++rd)
1929 if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
1930 if (!ir_block_living_add(self, new_reads.v[rd]))
1933 if (!i && !self->entries_count) {
1935 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
1938 MEM_VECTOR_CLEAR(&new_reads, v);
1942 if (self->run_id == self->owner->run_id)
1945 self->run_id = self->owner->run_id;
1947 for (i = 0; i < self->entries_count; ++i)
1949 ir_block *entry = self->entries[i];
1950 ir_block_life_propagate(entry, self, changed);
1955 #if defined(LIFE_RANGE_WITHOUT_LAST_READ)
1956 MEM_VECTOR_CLEAR(&new_reads, v);
1961 /***********************************************************************
1964 * Since the IR has the convention of putting 'write' operands
1965 * at the beginning, we have to rotate the operands of instructions
1966 * properly in order to generate valid QCVM code.
1968 * Having destinations at a fixed position is more convenient. In QC
1969 * this is *mostly* OPC, but FTE adds at least 2 instructions which
1970 * read from from OPA, and store to OPB rather than OPC. Which is
1971 * partially the reason why the implementation of these instructions
1972 * in darkplaces has been delayed for so long.
1974 * Breaking conventions is annoying...
1976 static bool ir_builder_gen_global(ir_builder *self, ir_value *global);
1978 static bool gen_global_field(ir_value *global)
1980 if (global->isconst)
1982 ir_value *fld = global->constval.vpointer;
1984 printf("Invalid field constant with no field: %s\n", global->name);
1988 /* Now, in this case, a relocation would be impossible to code
1989 * since it looks like this:
1990 * .vector v = origin; <- parse error, wtf is 'origin'?
1993 * But we will need a general relocation support later anyway
1994 * for functions... might as well support that here.
1996 if (!fld->code.globaladdr) {
1997 printf("FIXME: Relocation support\n");
2001 /* copy the field's value */
2002 global->code.globaladdr = code_globals_add(code_globals_data[fld->code.globaladdr]);
2006 prog_section_field fld;
2008 fld.name = global->code.name;
2009 fld.offset = code_fields_elements;
2010 fld.type = global->fieldtype;
2012 if (fld.type == TYPE_VOID) {
2013 printf("Field is missing a type: %s\n", global->name);
2017 if (code_fields_add(fld) < 0)
2020 global->code.globaladdr = code_globals_add(fld.offset);
2022 if (global->code.globaladdr < 0)
2027 static bool gen_global_pointer(ir_value *global)
2029 if (global->isconst)
2031 ir_value *target = global->constval.vpointer;
2033 printf("Invalid pointer constant: %s\n", global->name);
2034 /* NULL pointers are pointing to the NULL constant, which also
2035 * sits at address 0, but still has an ir_value for itself.
2040 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2041 * void() foo; <- proto
2042 * void() *fooptr = &foo;
2043 * void() foo = { code }
2045 if (!target->code.globaladdr) {
2046 /* FIXME: Check for the constant nullptr ir_value!
2047 * because then code.globaladdr being 0 is valid.
2049 printf("FIXME: Relocation support\n");
2053 global->code.globaladdr = code_globals_add(target->code.globaladdr);
2057 global->code.globaladdr = code_globals_add(0);
2059 if (global->code.globaladdr < 0)
2064 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2066 prog_section_statement stmt;
2075 block->generated = true;
2076 block->code_start = code_statements_elements;
2077 for (i = 0; i < block->instr_count; ++i)
2079 instr = block->instr[i];
2081 if (instr->opcode == VINSTR_PHI) {
2082 printf("cannot generate virtual instruction (phi)\n");
2086 if (instr->opcode == VINSTR_JUMP) {
2087 target = instr->bops[0];
2088 /* for uncoditional jumps, if the target hasn't been generated
2089 * yet, we generate them right here.
2091 if (!target->generated) {
2096 /* otherwise we generate a jump instruction */
2097 stmt.opcode = INSTR_GOTO;
2098 stmt.o1.s1 = (target->code_start) - code_statements_elements;
2101 if (code_statements_add(stmt) < 0)
2104 /* no further instructions can be in this block */
2108 if (instr->opcode == VINSTR_COND) {
2109 ontrue = instr->bops[0];
2110 onfalse = instr->bops[1];
2111 /* TODO: have the AST signal which block should
2112 * come first: eg. optimize IFs without ELSE...
2115 stmt.o1.u1 = instr->_ops[0]->code.globaladdr;
2119 if (ontrue->generated) {
2120 stmt.opcode = INSTR_IF;
2121 stmt.o2.s1 = (ontrue->code_start-1) - code_statements_elements;
2122 if (code_statements_add(stmt) < 0)
2125 if (onfalse->generated) {
2126 stmt.opcode = INSTR_IFNOT;
2127 stmt.o2.s1 = (onfalse->code_start-1) - code_statements_elements;
2128 if (code_statements_add(stmt) < 0)
2131 if (!ontrue->generated) {
2132 if (onfalse->generated) {
2137 if (!onfalse->generated) {
2138 if (ontrue->generated) {
2143 /* neither ontrue nor onfalse exist */
2144 stmt.opcode = INSTR_IFNOT;
2145 stidx = code_statements_elements;
2146 if (code_statements_add(stmt) < 0)
2148 /* on false we jump, so add ontrue-path */
2149 if (!gen_blocks_recursive(func, ontrue))
2151 /* fixup the jump address */
2152 code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2153 /* generate onfalse path */
2154 if (onfalse->generated) {
2155 /* fixup the jump address */
2156 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2157 /* may have been generated in the previous recursive call */
2158 stmt.opcode = INSTR_GOTO;
2159 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2162 return (code_statements_add(stmt) >= 0);
2164 /* if not, generate now */
2169 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2170 /* Trivial call translation:
2171 * copy all params to OFS_PARM*
2173 * NOTES on how to do it better without much trouble:
2174 * -) The liferanges!
2175 * Simply check the liferange of all parameters for
2176 * other CALLs. For each param with no CALL in its
2177 * liferange, we can store it in an OFS_PARM at
2178 * generation already. This would even include later
2179 * reuse.... probably... :)
2181 printf("TODO: call instruction\n");
2185 if (instr->opcode == INSTR_STATE) {
2186 printf("TODO: state instruction\n");
2190 stmt.opcode = instr->opcode;
2195 /* This is the general order of operands */
2197 stmt.o3.u1 = instr->_ops[0]->code.globaladdr;
2200 stmt.o1.u1 = instr->_ops[1]->code.globaladdr;
2203 stmt.o2.u1 = instr->_ops[2]->code.globaladdr;
2205 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2207 stmt.o1.u1 = stmt.o3.u1;
2210 else if ((stmt.opcode >= INSTR_STORE_F &&
2211 stmt.opcode <= INSTR_STORE_FNC) ||
2212 (stmt.opcode >= INSTR_NOT_F &&
2213 stmt.opcode <= INSTR_NOT_FNC))
2215 /* 2-operand instructions with A -> B */
2216 stmt.o2.u1 = stmt.o3.u1;
2220 if (code_statements_add(stmt) < 0)
2226 static bool gen_function_code(ir_function *self)
2230 /* Starting from entry point, we generate blocks "as they come"
2231 * for now. Dead blocks will not be translated obviously.
2233 if (!self->blocks_count) {
2234 printf("Function '%s' declared without body.\n", self->name);
2238 block = self->blocks[0];
2239 if (block->generated)
2242 if (!gen_blocks_recursive(self, block)) {
2243 printf("failed to generate blocks for '%s'\n", self->name);
2249 static bool gen_global_function(ir_builder *ir, ir_value *global)
2251 prog_section_function fun;
2255 size_t local_var_end;
2257 if (!global->isconst ||
2258 !global->constval.vfunc)
2260 printf("Invalid state of function-global: not constant: %s\n", global->name);
2264 irfun = global->constval.vfunc;
2266 fun.name = global->code.name;
2267 fun.file = code_cachedstring(global->context.file);
2268 fun.profile = 0; /* always 0 */
2269 fun.nargs = irfun->params_count;
2271 for (i = 0;i < 8; ++i) {
2274 else if (irfun->params[i] == TYPE_VECTOR)
2280 fun.firstlocal = code_globals_elements;
2281 fun.locals = irfun->allocated_locals + irfun->locals_count;
2284 for (i = 0; i < irfun->locals_count; ++i) {
2285 if (!ir_builder_gen_global(ir, irfun->locals[i])) {
2286 printf("Failed to generate global %s\n", irfun->locals[i]->name);
2290 if (irfun->locals_count) {
2291 ir_value *last = irfun->locals[irfun->locals_count-1];
2292 local_var_end = last->code.globaladdr;
2293 local_var_end += type_sizeof[last->vtype];
2295 for (i = 0; i < irfun->values_count; ++i)
2297 /* generate code.globaladdr for ssa values */
2298 ir_value *v = irfun->values[i];
2299 v->code.globaladdr = local_var_end + v->code.local;
2301 for (i = 0; i < irfun->locals_count; ++i) {
2302 /* fill the locals with zeros */
2303 code_globals_add(0);
2306 fun.entry = code_statements_elements;
2307 if (!gen_function_code(irfun)) {
2308 printf("Failed to generate code for function %s\n", irfun->name);
2312 return (code_functions_add(fun) >= 0);
2315 static bool ir_builder_gen_global(ir_builder *self, ir_value *global)
2318 prog_section_def def;
2320 def.type = global->vtype;
2321 def.offset = code_globals_elements;
2322 def.name = global->code.name = code_genstring(global->name);
2324 switch (global->vtype)
2327 if (code_defs_add(def) < 0)
2329 return gen_global_pointer(global);
2331 if (code_defs_add(def) < 0)
2333 return gen_global_field(global);
2338 if (code_defs_add(def) < 0)
2341 if (global->isconst) {
2342 iptr = (int32_t*)&global->constval.vfloat;
2343 global->code.globaladdr = code_globals_add(*iptr);
2345 global->code.globaladdr = code_globals_add(0);
2347 return global->code.globaladdr >= 0;
2351 if (code_defs_add(def) < 0)
2353 if (global->isconst)
2354 global->code.globaladdr = code_globals_add(code_cachedstring(global->constval.vstring));
2356 global->code.globaladdr = code_globals_add(0);
2357 return global->code.globaladdr >= 0;
2361 if (code_defs_add(def) < 0)
2364 if (global->isconst) {
2365 iptr = (int32_t*)&global->constval.vvec;
2366 global->code.globaladdr = code_globals_add(iptr[0]);
2367 if (code_globals_add(iptr[1]) < 0 || code_globals_add(iptr[2]) < 0)
2370 global->code.globaladdr = code_globals_add(0);
2371 if (code_globals_add(0) < 0 || code_globals_add(0) < 0)
2374 return global->code.globaladdr >= 0;
2377 if (code_defs_add(def) < 0)
2379 code_globals_add(code_functions_elements);
2380 return gen_global_function(self, global);
2382 /* assume biggest type */
2383 global->code.globaladdr = code_globals_add(0);
2384 code_globals_add(0);
2385 code_globals_add(0);
2388 /* refuse to create 'void' type or any other fancy business. */
2389 printf("Invalid type for global variable %s\n", global->name);
2394 bool ir_builder_generate(ir_builder *self, const char *filename)
2400 /* FIXME: generate TYPE_FUNCTION globals and link them
2401 * to their ir_function.
2404 for (i = 0; i < self->functions_count; ++i)
2407 ir_function *fun = self->functions[i];
2409 funval = ir_builder_create_global(self, fun->name, TYPE_FUNCTION);
2410 funval->isconst = true;
2411 funval->constval.vfunc = fun;
2412 funval->context = fun->context;
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);