5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 * this software and associated documentation files (the "Software"), to deal in
7 * the Software without restriction, including without limitation the rights to
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9 * of the Software, and to permit persons to whom the Software is furnished to do
10 * so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 /***********************************************************************
29 * Type sizes used at multiple points in the IR codegen
32 const char *type_name[TYPE_COUNT] = {
48 size_t type_sizeof[TYPE_COUNT] = {
55 1, /* TYPE_FUNCTION */
64 uint16_t type_store_instr[TYPE_COUNT] = {
65 INSTR_STORE_F, /* should use I when having integer support */
72 INSTR_STORE_ENT, /* should use I */
74 INSTR_STORE_I, /* integer type */
79 INSTR_STORE_V, /* variant, should never be accessed */
81 AINSTR_END, /* struct */
82 AINSTR_END, /* union */
83 AINSTR_END, /* array */
86 uint16_t field_store_instr[TYPE_COUNT] = {
96 INSTR_STORE_FLD, /* integer type */
101 INSTR_STORE_V, /* variant, should never be accessed */
103 AINSTR_END, /* struct */
104 AINSTR_END, /* union */
105 AINSTR_END, /* array */
108 uint16_t type_storep_instr[TYPE_COUNT] = {
109 INSTR_STOREP_F, /* should use I when having integer support */
116 INSTR_STOREP_ENT, /* should use I */
118 INSTR_STOREP_ENT, /* integer type */
123 INSTR_STOREP_V, /* variant, should never be accessed */
125 AINSTR_END, /* struct */
126 AINSTR_END, /* union */
127 AINSTR_END, /* array */
130 uint16_t type_eq_instr[TYPE_COUNT] = {
131 INSTR_EQ_F, /* should use I when having integer support */
136 INSTR_EQ_E, /* FLD has no comparison */
138 INSTR_EQ_E, /* should use I */
145 INSTR_EQ_V, /* variant, should never be accessed */
147 AINSTR_END, /* struct */
148 AINSTR_END, /* union */
149 AINSTR_END, /* array */
152 uint16_t type_ne_instr[TYPE_COUNT] = {
153 INSTR_NE_F, /* should use I when having integer support */
158 INSTR_NE_E, /* FLD has no comparison */
160 INSTR_NE_E, /* should use I */
167 INSTR_NE_V, /* variant, should never be accessed */
169 AINSTR_END, /* struct */
170 AINSTR_END, /* union */
171 AINSTR_END, /* array */
174 uint16_t type_not_instr[TYPE_COUNT] = {
175 INSTR_NOT_F, /* should use I when having integer support */
182 INSTR_NOT_ENT, /* should use I */
184 INSTR_NOT_I, /* integer type */
189 INSTR_NOT_V, /* variant, should never be accessed */
191 AINSTR_END, /* struct */
192 AINSTR_END, /* union */
193 AINSTR_END, /* array */
196 static void irerror(lex_ctx ctx, const char *msg, ...)
200 con_cvprintmsg((void*)&ctx, LVL_ERROR, "internal error", msg, ap);
204 static bool irwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
207 int lvl = LVL_WARNING;
209 if (warntype && !OPTS_WARN(warntype))
216 con_vprintmsg(lvl, ctx.file, ctx.line, "warning", fmt, ap);
222 /***********************************************************************
223 * Vector utility functions
226 bool GMQCC_WARN vec_ir_value_find(ir_value **vec, ir_value *what, size_t *idx)
229 size_t len = vec_size(vec);
230 for (i = 0; i < len; ++i) {
231 if (vec[i] == what) {
239 bool GMQCC_WARN vec_ir_block_find(ir_block **vec, ir_block *what, size_t *idx)
242 size_t len = vec_size(vec);
243 for (i = 0; i < len; ++i) {
244 if (vec[i] == what) {
252 bool GMQCC_WARN vec_ir_instr_find(ir_instr **vec, ir_instr *what, size_t *idx)
255 size_t len = vec_size(vec);
256 for (i = 0; i < len; ++i) {
257 if (vec[i] == what) {
265 /***********************************************************************
269 static void ir_block_delete_quick(ir_block* self);
270 static void ir_instr_delete_quick(ir_instr *self);
271 static void ir_function_delete_quick(ir_function *self);
273 ir_builder* ir_builder_new(const char *modulename)
277 self = (ir_builder*)mem_a(sizeof(*self));
281 self->functions = NULL;
282 self->globals = NULL;
284 self->extparams = NULL;
285 self->filenames = NULL;
286 self->filestrings = NULL;
287 self->htglobals = util_htnew(IR_HT_SIZE);
288 self->htfields = util_htnew(IR_HT_SIZE);
289 self->htfunctions = util_htnew(IR_HT_SIZE);
291 self->str_immediate = 0;
293 if (!ir_builder_set_name(self, modulename)) {
301 void ir_builder_delete(ir_builder* self)
304 util_htdel(self->htglobals);
305 util_htdel(self->htfields);
306 util_htdel(self->htfunctions);
307 mem_d((void*)self->name);
308 for (i = 0; i != vec_size(self->functions); ++i) {
309 ir_function_delete_quick(self->functions[i]);
311 vec_free(self->functions);
312 for (i = 0; i != vec_size(self->extparams); ++i) {
313 ir_value_delete(self->extparams[i]);
315 vec_free(self->extparams);
316 for (i = 0; i != vec_size(self->globals); ++i) {
317 ir_value_delete(self->globals[i]);
319 vec_free(self->globals);
320 for (i = 0; i != vec_size(self->fields); ++i) {
321 ir_value_delete(self->fields[i]);
323 vec_free(self->fields);
324 vec_free(self->filenames);
325 vec_free(self->filestrings);
329 bool ir_builder_set_name(ir_builder *self, const char *name)
332 mem_d((void*)self->name);
333 self->name = util_strdup(name);
337 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
339 return (ir_function*)util_htget(self->htfunctions, name);
342 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
344 ir_function *fn = ir_builder_get_function(self, name);
349 fn = ir_function_new(self, outtype);
350 if (!ir_function_set_name(fn, name))
352 ir_function_delete(fn);
355 vec_push(self->functions, fn);
356 util_htset(self->htfunctions, name, fn);
358 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
360 ir_function_delete(fn);
364 fn->value->isconst = true;
365 fn->value->outtype = outtype;
366 fn->value->constval.vfunc = fn;
367 fn->value->context = fn->context;
372 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
374 return (ir_value*)util_htget(self->htglobals, name);
377 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
381 if (name && name[0] != '#')
383 ve = ir_builder_get_global(self, name);
389 ve = ir_value_var(name, store_global, vtype);
390 vec_push(self->globals, ve);
391 util_htset(self->htglobals, name, ve);
395 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
397 return (ir_value*)util_htget(self->htfields, name);
401 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
403 ir_value *ve = ir_builder_get_field(self, name);
408 ve = ir_value_var(name, store_global, TYPE_FIELD);
409 ve->fieldtype = vtype;
410 vec_push(self->fields, ve);
411 util_htset(self->htfields, name, ve);
415 /***********************************************************************
419 bool ir_function_naive_phi(ir_function*);
420 void ir_function_enumerate(ir_function*);
421 bool ir_function_calculate_liferanges(ir_function*);
422 bool ir_function_allocate_locals(ir_function*);
424 ir_function* ir_function_new(ir_builder* owner, int outtype)
427 self = (ir_function*)mem_a(sizeof(*self));
432 memset(self, 0, sizeof(*self));
435 if (!ir_function_set_name(self, "<@unnamed>")) {
440 self->context.file = "<@no context>";
441 self->context.line = 0;
442 self->outtype = outtype;
451 self->code_function_def = -1;
452 self->allocated_locals = 0;
458 bool ir_function_set_name(ir_function *self, const char *name)
461 mem_d((void*)self->name);
462 self->name = util_strdup(name);
466 static void ir_function_delete_quick(ir_function *self)
469 mem_d((void*)self->name);
471 for (i = 0; i != vec_size(self->blocks); ++i)
472 ir_block_delete_quick(self->blocks[i]);
473 vec_free(self->blocks);
475 vec_free(self->params);
477 for (i = 0; i != vec_size(self->values); ++i)
478 ir_value_delete(self->values[i]);
479 vec_free(self->values);
481 for (i = 0; i != vec_size(self->locals); ++i)
482 ir_value_delete(self->locals[i]);
483 vec_free(self->locals);
485 /* self->value is deleted by the builder */
490 void ir_function_delete(ir_function *self)
493 mem_d((void*)self->name);
495 for (i = 0; i != vec_size(self->blocks); ++i)
496 ir_block_delete(self->blocks[i]);
497 vec_free(self->blocks);
499 vec_free(self->params);
501 for (i = 0; i != vec_size(self->values); ++i)
502 ir_value_delete(self->values[i]);
503 vec_free(self->values);
505 for (i = 0; i != vec_size(self->locals); ++i)
506 ir_value_delete(self->locals[i]);
507 vec_free(self->locals);
509 /* self->value is deleted by the builder */
514 void ir_function_collect_value(ir_function *self, ir_value *v)
516 vec_push(self->values, v);
519 ir_block* ir_function_create_block(lex_ctx ctx, ir_function *self, const char *label)
521 ir_block* bn = ir_block_new(self, label);
523 vec_push(self->blocks, bn);
527 bool ir_function_pass_tailcall(ir_function *self)
531 for (b = 0; b < vec_size(self->blocks); ++b) {
533 ir_instr *ret, *call, *store = NULL;
534 ir_block *block = self->blocks[b];
536 if (!block->final || vec_size(block->instr) < 2)
539 ret = block->instr[vec_size(block->instr)-1];
540 if (ret->opcode != INSTR_DONE && ret->opcode != INSTR_RETURN)
543 call = block->instr[vec_size(block->instr)-2];
544 if (call->opcode >= INSTR_STORE_F && call->opcode <= INSTR_STORE_FNC) {
545 /* account for the unoptimized
547 * STORE %return, %tmp
551 if (vec_size(block->instr) < 3)
555 call = block->instr[vec_size(block->instr)-3];
558 if (call->opcode < INSTR_CALL0 || call->opcode > INSTR_CALL8)
562 /* optimize out the STORE */
564 ret->_ops[0] == store->_ops[0] &&
565 store->_ops[1] == call->_ops[0])
567 ++optimization_count[OPTIM_MINOR];
568 call->_ops[0] = store->_ops[0];
569 vec_remove(block, vec_size(block->instr) - 2, 1);
570 ir_instr_delete(store);
579 funcval = call->_ops[1];
582 if (funcval->vtype != TYPE_FUNCTION || funcval->constval.vfunc != self)
585 /* now we have a CALL and a RET, check if it's a tailcall */
586 if (ret->_ops[0] && call->_ops[0] != ret->_ops[0])
589 ++optimization_count[OPTIM_TAIL_RECURSION];
590 vec_shrinkby(block->instr, 2);
592 block->final = false; /* open it back up */
594 /* emite parameter-stores */
595 for (p = 0; p < vec_size(call->params); ++p) {
596 /* assert(call->params_count <= self->locals_count); */
597 if (!ir_block_create_store(block, self->locals[p], call->params[p])) {
598 irerror(call->context, "failed to create tailcall store instruction for parameter %i", (int)p);
602 if (!ir_block_create_jump(block, self->blocks[0])) {
603 irerror(call->context, "failed to create tailcall jump");
607 ir_instr_delete(call);
608 ir_instr_delete(ret);
614 bool ir_function_finalize(ir_function *self)
619 if (OPTS_OPTIMIZATION(OPTIM_TAIL_RECURSION)) {
620 if (!ir_function_pass_tailcall(self)) {
621 irerror(self->context, "tailcall optimization pass broke something in `%s`", self->name);
626 if (!ir_function_naive_phi(self))
629 ir_function_enumerate(self);
631 if (!ir_function_calculate_liferanges(self))
633 if (!ir_function_allocate_locals(self))
638 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
643 vec_size(self->locals) &&
644 self->locals[vec_size(self->locals)-1]->store != store_param) {
645 irerror(self->context, "cannot add parameters after adding locals");
649 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
650 vec_push(self->locals, ve);
654 /***********************************************************************
658 ir_block* ir_block_new(ir_function* owner, const char *name)
661 self = (ir_block*)mem_a(sizeof(*self));
665 memset(self, 0, sizeof(*self));
668 if (name && !ir_block_set_label(self, name)) {
673 self->context.file = "<@no context>";
674 self->context.line = 0;
678 self->entries = NULL;
682 self->is_return = false;
687 self->generated = false;
692 static void ir_block_delete_quick(ir_block* self)
695 if (self->label) mem_d(self->label);
696 for (i = 0; i != vec_size(self->instr); ++i)
697 ir_instr_delete_quick(self->instr[i]);
698 vec_free(self->instr);
699 vec_free(self->entries);
700 vec_free(self->exits);
701 vec_free(self->living);
705 void ir_block_delete(ir_block* self)
708 if (self->label) mem_d(self->label);
709 for (i = 0; i != vec_size(self->instr); ++i)
710 ir_instr_delete(self->instr[i]);
711 vec_free(self->instr);
712 vec_free(self->entries);
713 vec_free(self->exits);
714 vec_free(self->living);
718 bool ir_block_set_label(ir_block *self, const char *name)
721 mem_d((void*)self->label);
722 self->label = util_strdup(name);
723 return !!self->label;
726 /***********************************************************************
730 ir_instr* ir_instr_new(ir_block* owner, int op)
733 self = (ir_instr*)mem_a(sizeof(*self));
738 self->context.file = "<@no context>";
739 self->context.line = 0;
741 self->_ops[0] = NULL;
742 self->_ops[1] = NULL;
743 self->_ops[2] = NULL;
744 self->bops[0] = NULL;
745 self->bops[1] = NULL;
756 static void ir_instr_delete_quick(ir_instr *self)
759 vec_free(self->params);
763 void ir_instr_delete(ir_instr *self)
766 /* The following calls can only delete from
767 * vectors, we still want to delete this instruction
768 * so ignore the return value. Since with the warn_unused_result attribute
769 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
770 * I have to improvise here and use if(foo());
772 for (i = 0; i < vec_size(self->phi); ++i) {
774 if (vec_ir_instr_find(self->phi[i].value->writes, self, &idx))
775 vec_remove(self->phi[i].value->writes, idx, 1);
776 if (vec_ir_instr_find(self->phi[i].value->reads, self, &idx))
777 vec_remove(self->phi[i].value->reads, idx, 1);
780 for (i = 0; i < vec_size(self->params); ++i) {
782 if (vec_ir_instr_find(self->params[i]->writes, self, &idx))
783 vec_remove(self->params[i]->writes, idx, 1);
784 if (vec_ir_instr_find(self->params[i]->reads, self, &idx))
785 vec_remove(self->params[i]->reads, idx, 1);
787 vec_free(self->params);
788 (void)!ir_instr_op(self, 0, NULL, false);
789 (void)!ir_instr_op(self, 1, NULL, false);
790 (void)!ir_instr_op(self, 2, NULL, false);
794 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
796 if (self->_ops[op]) {
798 if (writing && vec_ir_instr_find(self->_ops[op]->writes, self, &idx))
799 vec_remove(self->_ops[op]->writes, idx, 1);
800 else if (vec_ir_instr_find(self->_ops[op]->reads, self, &idx))
801 vec_remove(self->_ops[op]->reads, idx, 1);
805 vec_push(v->writes, self);
807 vec_push(v->reads, self);
813 /***********************************************************************
817 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
819 self->code.globaladdr = gaddr;
820 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
821 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
822 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
825 int32_t ir_value_code_addr(const ir_value *self)
827 if (self->store == store_return)
828 return OFS_RETURN + self->code.addroffset;
829 return self->code.globaladdr + self->code.addroffset;
832 ir_value* ir_value_var(const char *name, int storetype, int vtype)
835 self = (ir_value*)mem_a(sizeof(*self));
837 self->fieldtype = TYPE_VOID;
838 self->outtype = TYPE_VOID;
839 self->store = storetype;
844 self->isconst = false;
845 self->context.file = "<@no context>";
846 self->context.line = 0;
848 if (name && !ir_value_set_name(self, name)) {
849 irerror(self->context, "out of memory");
854 memset(&self->constval, 0, sizeof(self->constval));
855 memset(&self->code, 0, sizeof(self->code));
857 self->members[0] = NULL;
858 self->members[1] = NULL;
859 self->members[2] = NULL;
860 self->memberof = NULL;
866 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
872 if (self->members[member])
873 return self->members[member];
875 if (self->vtype == TYPE_VECTOR)
877 m = ir_value_var(self->name, self->store, TYPE_FLOAT);
880 m->context = self->context;
882 self->members[member] = m;
883 m->code.addroffset = member;
885 else if (self->vtype == TYPE_FIELD)
887 if (self->fieldtype != TYPE_VECTOR)
889 m = ir_value_var(self->name, self->store, TYPE_FIELD);
892 m->fieldtype = TYPE_FLOAT;
893 m->context = self->context;
895 self->members[member] = m;
896 m->code.addroffset = member;
900 irerror(self->context, "invalid member access on %s", self->name);
908 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
910 ir_value *v = ir_value_var(name, storetype, vtype);
913 ir_function_collect_value(owner, v);
917 void ir_value_delete(ir_value* self)
921 mem_d((void*)self->name);
924 if (self->vtype == TYPE_STRING)
925 mem_d((void*)self->constval.vstring);
927 for (i = 0; i < 3; ++i) {
928 if (self->members[i])
929 ir_value_delete(self->members[i]);
931 vec_free(self->reads);
932 vec_free(self->writes);
933 vec_free(self->life);
937 bool ir_value_set_name(ir_value *self, const char *name)
940 mem_d((void*)self->name);
941 self->name = util_strdup(name);
945 bool ir_value_set_float(ir_value *self, float f)
947 if (self->vtype != TYPE_FLOAT)
949 self->constval.vfloat = f;
950 self->isconst = true;
954 bool ir_value_set_func(ir_value *self, int f)
956 if (self->vtype != TYPE_FUNCTION)
958 self->constval.vint = f;
959 self->isconst = true;
963 bool ir_value_set_vector(ir_value *self, vector v)
965 if (self->vtype != TYPE_VECTOR)
967 self->constval.vvec = v;
968 self->isconst = true;
972 bool ir_value_set_field(ir_value *self, ir_value *fld)
974 if (self->vtype != TYPE_FIELD)
976 self->constval.vpointer = fld;
977 self->isconst = true;
981 static char *ir_strdup(const char *str)
984 /* actually dup empty strings */
985 char *out = mem_a(1);
989 return util_strdup(str);
992 bool ir_value_set_string(ir_value *self, const char *str)
994 if (self->vtype != TYPE_STRING)
996 self->constval.vstring = ir_strdup(str);
997 self->isconst = true;
1002 bool ir_value_set_int(ir_value *self, int i)
1004 if (self->vtype != TYPE_INTEGER)
1006 self->constval.vint = i;
1007 self->isconst = true;
1012 bool ir_value_lives(ir_value *self, size_t at)
1015 for (i = 0; i < vec_size(self->life); ++i)
1017 ir_life_entry_t *life = &self->life[i];
1018 if (life->start <= at && at <= life->end)
1020 if (life->start > at) /* since it's ordered */
1026 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
1029 vec_push(self->life, e);
1030 for (k = vec_size(self->life)-1; k > idx; --k)
1031 self->life[k] = self->life[k-1];
1032 self->life[idx] = e;
1036 bool ir_value_life_merge(ir_value *self, size_t s)
1039 ir_life_entry_t *life = NULL;
1040 ir_life_entry_t *before = NULL;
1041 ir_life_entry_t new_entry;
1043 /* Find the first range >= s */
1044 for (i = 0; i < vec_size(self->life); ++i)
1047 life = &self->life[i];
1048 if (life->start > s)
1051 /* nothing found? append */
1052 if (i == vec_size(self->life)) {
1054 if (life && life->end+1 == s)
1056 /* previous life range can be merged in */
1060 if (life && life->end >= s)
1062 e.start = e.end = s;
1063 vec_push(self->life, e);
1069 if (before->end + 1 == s &&
1070 life->start - 1 == s)
1073 before->end = life->end;
1074 vec_remove(self->life, i, 1);
1077 if (before->end + 1 == s)
1083 /* already contained */
1084 if (before->end >= s)
1088 if (life->start - 1 == s)
1093 /* insert a new entry */
1094 new_entry.start = new_entry.end = s;
1095 return ir_value_life_insert(self, i, new_entry);
1098 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1102 if (!vec_size(other->life))
1105 if (!vec_size(self->life)) {
1106 size_t count = vec_size(other->life);
1107 ir_life_entry_t *life = vec_add(self->life, count);
1108 memcpy(life, other->life, count * sizeof(*life));
1113 for (i = 0; i < vec_size(other->life); ++i)
1115 const ir_life_entry_t *life = &other->life[i];
1118 ir_life_entry_t *entry = &self->life[myi];
1120 if (life->end+1 < entry->start)
1122 /* adding an interval before entry */
1123 if (!ir_value_life_insert(self, myi, *life))
1129 if (life->start < entry->start &&
1130 life->end+1 >= entry->start)
1132 /* starts earlier and overlaps */
1133 entry->start = life->start;
1136 if (life->end > entry->end &&
1137 life->start <= entry->end+1)
1139 /* ends later and overlaps */
1140 entry->end = life->end;
1143 /* see if our change combines it with the next ranges */
1144 while (myi+1 < vec_size(self->life) &&
1145 entry->end+1 >= self->life[1+myi].start)
1147 /* overlaps with (myi+1) */
1148 if (entry->end < self->life[1+myi].end)
1149 entry->end = self->life[1+myi].end;
1150 vec_remove(self->life, myi+1, 1);
1151 entry = &self->life[myi];
1154 /* see if we're after the entry */
1155 if (life->start > entry->end)
1158 /* append if we're at the end */
1159 if (myi >= vec_size(self->life)) {
1160 vec_push(self->life, *life);
1163 /* otherweise check the next range */
1172 bool ir_values_overlap(const ir_value *a, const ir_value *b)
1174 /* For any life entry in A see if it overlaps with
1175 * any life entry in B.
1176 * Note that the life entries are orderes, so we can make a
1177 * more efficient algorithm there than naively translating the
1181 ir_life_entry_t *la, *lb, *enda, *endb;
1183 /* first of all, if either has no life range, they cannot clash */
1184 if (!vec_size(a->life) || !vec_size(b->life))
1189 enda = la + vec_size(a->life);
1190 endb = lb + vec_size(b->life);
1193 /* check if the entries overlap, for that,
1194 * both must start before the other one ends.
1196 if (la->start < lb->end &&
1197 lb->start < la->end)
1202 /* entries are ordered
1203 * one entry is earlier than the other
1204 * that earlier entry will be moved forward
1206 if (la->start < lb->start)
1208 /* order: A B, move A forward
1209 * check if we hit the end with A
1214 else /* if (lb->start < la->start) actually <= */
1216 /* order: B A, move B forward
1217 * check if we hit the end with B
1226 /***********************************************************************
1230 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
1234 irerror(self->context, "unreachable statement (%s)", self->label);
1237 in = ir_instr_new(self, op);
1241 if (target->store == store_value &&
1242 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1244 irerror(self->context, "cannot store to an SSA value");
1245 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1246 irerror(self->context, "instruction: %s", asm_instr[op].m);
1250 if (!ir_instr_op(in, 0, target, true) ||
1251 !ir_instr_op(in, 1, what, false))
1255 vec_push(self->instr, in);
1259 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
1263 if (target->vtype == TYPE_VARIANT)
1264 vtype = what->vtype;
1266 vtype = target->vtype;
1269 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1270 op = INSTR_CONV_ITOF;
1271 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1272 op = INSTR_CONV_FTOI;
1274 op = type_store_instr[vtype];
1276 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1277 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1281 return ir_block_create_store_op(self, op, target, what);
1284 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
1289 if (target->vtype != TYPE_POINTER)
1292 /* storing using pointer - target is a pointer, type must be
1293 * inferred from source
1295 vtype = what->vtype;
1297 op = type_storep_instr[vtype];
1298 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1299 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1300 op = INSTR_STOREP_V;
1303 return ir_block_create_store_op(self, op, target, what);
1306 bool ir_block_create_return(ir_block *self, ir_value *v)
1310 irerror(self->context, "unreachable statement (%s)", self->label);
1314 self->is_return = true;
1315 in = ir_instr_new(self, INSTR_RETURN);
1319 if (v && !ir_instr_op(in, 0, v, false))
1322 vec_push(self->instr, in);
1326 bool ir_block_create_if(ir_block *self, ir_value *v,
1327 ir_block *ontrue, ir_block *onfalse)
1331 irerror(self->context, "unreachable statement (%s)", self->label);
1335 /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1336 in = ir_instr_new(self, VINSTR_COND);
1340 if (!ir_instr_op(in, 0, v, false)) {
1341 ir_instr_delete(in);
1345 in->bops[0] = ontrue;
1346 in->bops[1] = onfalse;
1348 vec_push(self->instr, in);
1350 vec_push(self->exits, ontrue);
1351 vec_push(self->exits, onfalse);
1352 vec_push(ontrue->entries, self);
1353 vec_push(onfalse->entries, self);
1357 bool ir_block_create_jump(ir_block *self, ir_block *to)
1361 irerror(self->context, "unreachable statement (%s)", self->label);
1365 in = ir_instr_new(self, VINSTR_JUMP);
1370 vec_push(self->instr, in);
1372 vec_push(self->exits, to);
1373 vec_push(to->entries, self);
1377 bool ir_block_create_goto(ir_block *self, ir_block *to)
1381 irerror(self->context, "unreachable statement (%s)", self->label);
1385 in = ir_instr_new(self, INSTR_GOTO);
1390 vec_push(self->instr, in);
1392 vec_push(self->exits, to);
1393 vec_push(to->entries, self);
1397 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1401 in = ir_instr_new(self, VINSTR_PHI);
1404 out = ir_value_out(self->owner, label, store_value, ot);
1406 ir_instr_delete(in);
1409 if (!ir_instr_op(in, 0, out, true)) {
1410 ir_instr_delete(in);
1411 ir_value_delete(out);
1414 vec_push(self->instr, in);
1418 ir_value* ir_phi_value(ir_instr *self)
1420 return self->_ops[0];
1423 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1427 if (!vec_ir_block_find(self->owner->entries, b, NULL)) {
1428 /* Must not be possible to cause this, otherwise the AST
1429 * is doing something wrong.
1431 irerror(self->context, "Invalid entry block for PHI");
1437 vec_push(v->reads, self);
1438 vec_push(self->phi, pe);
1441 /* call related code */
1442 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1446 in = ir_instr_new(self, INSTR_CALL0);
1449 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1451 ir_instr_delete(in);
1454 if (!ir_instr_op(in, 0, out, true) ||
1455 !ir_instr_op(in, 1, func, false))
1457 ir_instr_delete(in);
1458 ir_value_delete(out);
1461 vec_push(self->instr, in);
1465 ir_value* ir_call_value(ir_instr *self)
1467 return self->_ops[0];
1470 void ir_call_param(ir_instr* self, ir_value *v)
1472 vec_push(self->params, v);
1473 vec_push(v->reads, self);
1476 /* binary op related code */
1478 ir_value* ir_block_create_binop(ir_block *self,
1479 const char *label, int opcode,
1480 ir_value *left, ir_value *right)
1502 case INSTR_SUB_S: /* -- offset of string as float */
1507 case INSTR_BITOR_IF:
1508 case INSTR_BITOR_FI:
1509 case INSTR_BITAND_FI:
1510 case INSTR_BITAND_IF:
1525 case INSTR_BITAND_I:
1528 case INSTR_RSHIFT_I:
1529 case INSTR_LSHIFT_I:
1551 /* boolean operations result in floats */
1552 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1554 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1557 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1562 if (ot == TYPE_VOID) {
1563 /* The AST or parser were supposed to check this! */
1567 return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1570 ir_value* ir_block_create_unary(ir_block *self,
1571 const char *label, int opcode,
1574 int ot = TYPE_FLOAT;
1586 /* QC doesn't have other unary operations. We expect extensions to fill
1587 * the above list, otherwise we assume out-type = in-type, eg for an
1591 ot = operand->vtype;
1594 if (ot == TYPE_VOID) {
1595 /* The AST or parser were supposed to check this! */
1599 /* let's use the general instruction creator and pass NULL for OPB */
1600 return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1603 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1604 int op, ir_value *a, ir_value *b, int outype)
1609 out = ir_value_out(self->owner, label, store_value, outype);
1613 instr = ir_instr_new(self, op);
1615 ir_value_delete(out);
1619 if (!ir_instr_op(instr, 0, out, true) ||
1620 !ir_instr_op(instr, 1, a, false) ||
1621 !ir_instr_op(instr, 2, b, false) )
1626 vec_push(self->instr, instr);
1630 ir_instr_delete(instr);
1631 ir_value_delete(out);
1635 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1639 /* Support for various pointer types todo if so desired */
1640 if (ent->vtype != TYPE_ENTITY)
1643 if (field->vtype != TYPE_FIELD)
1646 v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1647 v->fieldtype = field->fieldtype;
1651 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1654 if (ent->vtype != TYPE_ENTITY)
1657 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1658 if (field->vtype != TYPE_FIELD)
1663 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1664 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1665 case TYPE_STRING: op = INSTR_LOAD_S; break;
1666 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1667 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1668 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1670 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1671 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1674 irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1678 return ir_block_create_general_instr(self, label, op, ent, field, outype);
1681 ir_value* ir_block_create_add(ir_block *self,
1683 ir_value *left, ir_value *right)
1686 int l = left->vtype;
1687 int r = right->vtype;
1691 irerror(self->context, "invalid type for ir_block_create_add: %s", type_name[l]);
1707 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1709 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1714 irerror(self->context, "invalid type for ir_block_create_add: %s", type_name[l]);
1718 return ir_block_create_binop(self, label, op, left, right);
1721 ir_value* ir_block_create_sub(ir_block *self,
1723 ir_value *left, ir_value *right)
1726 int l = left->vtype;
1727 int r = right->vtype;
1732 irerror(self->context, "invalid type for ir_block_create_sub: %s", type_name[l]);
1748 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1750 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1755 irerror(self->context, "invalid type for ir_block_create_sub: %s", type_name[l]);
1759 return ir_block_create_binop(self, label, op, left, right);
1762 ir_value* ir_block_create_mul(ir_block *self,
1764 ir_value *left, ir_value *right)
1767 int l = left->vtype;
1768 int r = right->vtype;
1773 irerror(self->context, "invalid type for ir_block_create_mul: %s", type_name[l]);
1788 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1790 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1793 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1795 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1797 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1799 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1803 irerror(self->context, "invalid type for ir_block_create_mul: %s", type_name[l]);
1807 return ir_block_create_binop(self, label, op, left, right);
1810 ir_value* ir_block_create_div(ir_block *self,
1812 ir_value *left, ir_value *right)
1815 int l = left->vtype;
1816 int r = right->vtype;
1821 irerror(self->context, "invalid type for ir_block_create_div: %s", type_name[l]);
1834 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1836 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1838 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1843 irerror(self->context, "invalid type for ir_block_create_div: %s", type_name[l]);
1847 return ir_block_create_binop(self, label, op, left, right);
1850 /* PHI resolving breaks the SSA, and must thus be the last
1851 * step before life-range calculation.
1854 static bool ir_block_naive_phi(ir_block *self);
1855 bool ir_function_naive_phi(ir_function *self)
1859 for (i = 0; i < vec_size(self->blocks); ++i)
1861 if (!ir_block_naive_phi(self->blocks[i]))
1868 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1873 /* create a store */
1874 if (!ir_block_create_store(block, old, what))
1877 /* we now move it up */
1878 instr = vec_last(block->instr);
1879 for (i = vec_size(block->instr)-1; i > iid; --i)
1880 block->instr[i] = block->instr[i-1];
1881 block->instr[i] = instr;
1887 static bool ir_block_naive_phi(ir_block *self)
1889 size_t i, p; /*, w;*/
1890 /* FIXME: optionally, create_phi can add the phis
1891 * to a list so we don't need to loop through blocks
1892 * - anyway: "don't optimize YET"
1894 for (i = 0; i < vec_size(self->instr); ++i)
1896 ir_instr *instr = self->instr[i];
1897 if (instr->opcode != VINSTR_PHI)
1900 vec_remove(self->instr, i, 1);
1901 --i; /* NOTE: i+1 below */
1903 for (p = 0; p < vec_size(instr->phi); ++p)
1905 ir_value *v = instr->phi[p].value;
1906 ir_block *b = instr->phi[p].from;
1908 if (v->store == store_value &&
1909 vec_size(v->reads) == 1 &&
1910 vec_size(v->writes) == 1)
1912 /* replace the value */
1913 if (!ir_instr_op(v->writes[0], 0, instr->_ops[0], true))
1918 /* force a move instruction */
1919 ir_instr *prevjump = vec_last(b->instr);
1922 instr->_ops[0]->store = store_global;
1923 if (!ir_block_create_store(b, instr->_ops[0], v))
1925 instr->_ops[0]->store = store_value;
1926 vec_push(b->instr, prevjump);
1931 ir_value *v = instr->phi[p].value;
1932 for (w = 0; w < vec_size(v->writes); ++w) {
1935 if (!v->writes[w]->_ops[0])
1938 /* When the write was to a global, we have to emit a mov */
1939 old = v->writes[w]->_ops[0];
1941 /* The original instruction now writes to the PHI target local */
1942 if (v->writes[w]->_ops[0] == v)
1943 v->writes[w]->_ops[0] = instr->_ops[0];
1945 if (old->store != store_value && old->store != store_local && old->store != store_param)
1947 /* If it originally wrote to a global we need to store the value
1950 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1952 if (i+1 < vec_size(self->instr))
1953 instr = self->instr[i+1];
1956 /* In case I forget and access instr later, it'll be NULL
1957 * when it's a problem, to make sure we crash, rather than accessing
1963 /* If it didn't, we can replace all reads by the phi target now. */
1965 for (r = 0; r < vec_size(old->reads); ++r)
1968 ir_instr *ri = old->reads[r];
1969 for (op = 0; op < vec_size(ri->phi); ++op) {
1970 if (ri->phi[op].value == old)
1971 ri->phi[op].value = v;
1973 for (op = 0; op < 3; ++op) {
1974 if (ri->_ops[op] == old)
1982 ir_instr_delete(instr);
1987 /***********************************************************************
1988 *IR Temp allocation code
1989 * Propagating value life ranges by walking through the function backwards
1990 * until no more changes are made.
1991 * In theory this should happen once more than once for every nested loop
1993 * Though this implementation might run an additional time for if nests.
1996 /* Enumerate instructions used by value's life-ranges
1998 static void ir_block_enumerate(ir_block *self, size_t *_eid)
2002 for (i = 0; i < vec_size(self->instr); ++i)
2004 self->instr[i]->eid = eid++;
2009 /* Enumerate blocks and instructions.
2010 * The block-enumeration is unordered!
2011 * We do not really use the block enumreation, however
2012 * the instruction enumeration is important for life-ranges.
2014 void ir_function_enumerate(ir_function *self)
2017 size_t instruction_id = 0;
2018 for (i = 0; i < vec_size(self->blocks); ++i)
2020 self->blocks[i]->eid = i;
2021 self->blocks[i]->run_id = 0;
2022 ir_block_enumerate(self->blocks[i], &instruction_id);
2026 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
2027 bool ir_function_calculate_liferanges(ir_function *self)
2035 for (i = 0; i != vec_size(self->blocks); ++i)
2037 if (self->blocks[i]->is_return)
2039 vec_free(self->blocks[i]->living);
2040 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
2045 if (vec_size(self->blocks)) {
2046 ir_block *block = self->blocks[0];
2047 for (i = 0; i < vec_size(block->living); ++i) {
2048 ir_value *v = block->living[i];
2049 if (v->memberof || v->store != store_local)
2051 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2052 "variable `%s` may be used uninitialized in this function", v->name))
2061 /* Local-value allocator
2062 * After finishing creating the liferange of all values used in a function
2063 * we can allocate their global-positions.
2064 * This is the counterpart to register-allocation in register machines.
2070 } function_allocator;
2072 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
2075 size_t vsize = type_sizeof[var->vtype];
2077 slot = ir_value_var("reg", store_global, var->vtype);
2081 if (!ir_value_life_merge_into(slot, var))
2084 vec_push(alloc->locals, slot);
2085 vec_push(alloc->sizes, vsize);
2090 ir_value_delete(slot);
2094 bool ir_function_allocate_locals(ir_function *self)
2103 function_allocator alloc;
2105 if (!vec_size(self->locals) && !vec_size(self->values))
2108 alloc.locals = NULL;
2110 alloc.positions = NULL;
2112 for (i = 0; i < vec_size(self->locals); ++i)
2114 if (!function_allocator_alloc(&alloc, self->locals[i]))
2118 /* Allocate a slot for any value that still exists */
2119 for (i = 0; i < vec_size(self->values); ++i)
2121 v = self->values[i];
2123 if (!vec_size(v->life))
2126 for (a = 0; a < vec_size(alloc.locals); ++a)
2128 slot = alloc.locals[a];
2130 if (ir_values_overlap(v, slot))
2133 if (!ir_value_life_merge_into(slot, v))
2136 /* adjust size for this slot */
2137 if (alloc.sizes[a] < type_sizeof[v->vtype])
2138 alloc.sizes[a] = type_sizeof[v->vtype];
2140 self->values[i]->code.local = a;
2143 if (a >= vec_size(alloc.locals)) {
2144 self->values[i]->code.local = vec_size(alloc.locals);
2145 if (!function_allocator_alloc(&alloc, v))
2154 /* Adjust slot positions based on sizes */
2155 vec_push(alloc.positions, 0);
2157 if (vec_size(alloc.sizes))
2158 pos = alloc.positions[0] + alloc.sizes[0];
2161 for (i = 1; i < vec_size(alloc.sizes); ++i)
2163 pos = alloc.positions[i-1] + alloc.sizes[i-1];
2164 vec_push(alloc.positions, pos);
2167 self->allocated_locals = pos + vec_last(alloc.sizes);
2169 /* Take over the actual slot positions */
2170 for (i = 0; i < vec_size(self->values); ++i) {
2171 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
2179 for (i = 0; i < vec_size(alloc.locals); ++i)
2180 ir_value_delete(alloc.locals[i]);
2181 vec_free(alloc.locals);
2182 vec_free(alloc.sizes);
2183 vec_free(alloc.positions);
2187 /* Get information about which operand
2188 * is read from, or written to.
2190 static void ir_op_read_write(int op, size_t *read, size_t *write)
2210 case INSTR_STOREP_F:
2211 case INSTR_STOREP_V:
2212 case INSTR_STOREP_S:
2213 case INSTR_STOREP_ENT:
2214 case INSTR_STOREP_FLD:
2215 case INSTR_STOREP_FNC:
2226 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2229 bool changed = false;
2231 for (i = 0; i != vec_size(self->living); ++i)
2233 tempbool = ir_value_life_merge(self->living[i], eid);
2236 irerror(self->context, "block_living_add_instr() value instruction added %s: %i", self->living[i]->_name, (int)eid);
2238 changed = changed || tempbool;
2243 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
2249 /* values which have been read in a previous iteration are now
2250 * in the "living" array even if the previous block doesn't use them.
2251 * So we have to remove whatever does not exist in the previous block.
2252 * They will be re-added on-read, but the liferange merge won't cause
2255 for (i = 0; i < vec_size(self->living); ++i)
2257 if (!vec_ir_value_find(prev->living, self->living[i], NULL)) {
2258 vec_remove(self->living, i, 1);
2263 /* Whatever the previous block still has in its living set
2264 * must now be added to ours as well.
2266 for (i = 0; i < vec_size(prev->living); ++i)
2268 if (vec_ir_value_find(self->living, prev->living[i], NULL))
2270 vec_push(self->living, prev->living[i]);
2272 irerror(self->contextt from prev: %s", self->label, prev->living[i]->_name);
2278 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2284 /* bitmasks which operands are read from or written to */
2286 char dbg_ind[16] = { '#', '0' };
2291 if (!ir_block_life_prop_previous(self, prev, changed))
2295 i = vec_size(self->instr);
2298 instr = self->instr[i];
2300 /* PHI operands are always read operands */
2301 for (p = 0; p < vec_size(instr->phi); ++p)
2303 value = instr->phi[p].value;
2304 if (value->memberof)
2305 value = value->memberof;
2306 if (!vec_ir_value_find(self->living, value, NULL))
2307 vec_push(self->living, value);
2310 /* call params are read operands too */
2311 for (p = 0; p < vec_size(instr->params); ++p)
2313 value = instr->params[p];
2314 if (value->memberof)
2315 value = value->memberof;
2316 if (!vec_ir_value_find(self->living, value, NULL))
2317 vec_push(self->living, value);
2320 /* See which operands are read and write operands */
2321 ir_op_read_write(instr->opcode, &read, &write);
2323 if (instr->opcode == INSTR_MUL_VF)
2325 /* the float source will get an additional lifetime */
2326 tempbool = ir_value_life_merge(instr->_ops[2], instr->eid+1);
2327 *changed = *changed || tempbool;
2329 else if (instr->opcode == INSTR_MUL_FV)
2331 /* the float source will get an additional lifetime */
2332 tempbool = ir_value_life_merge(instr->_ops[1], instr->eid+1);
2333 *changed = *changed || tempbool;
2336 /* Go through the 3 main operands */
2337 for (o = 0; o < 3; ++o)
2339 if (!instr->_ops[o]) /* no such operand */
2342 value = instr->_ops[o];
2343 if (value->memberof)
2344 value = value->memberof;
2346 /* We only care about locals */
2347 /* we also calculate parameter liferanges so that locals
2348 * can take up parameter slots */
2349 if (value->store != store_value &&
2350 value->store != store_local &&
2351 value->store != store_param)
2357 if (!vec_ir_value_find(self->living, value, NULL))
2358 vec_push(self->living, value);
2361 /* write operands */
2362 /* When we write to a local, we consider it "dead" for the
2363 * remaining upper part of the function, since in SSA a value
2364 * can only be written once (== created)
2369 bool in_living = vec_ir_value_find(self->living, value, &idx);
2372 /* If the value isn't alive it hasn't been read before... */
2373 /* TODO: See if the warning can be emitted during parsing or AST processing
2374 * otherwise have warning printed here.
2375 * IF printing a warning here: include filecontext_t,
2376 * and make sure it's only printed once
2377 * since this function is run multiple times.
2379 /* For now: debug info: */
2380 /* con_err( "Value only written %s\n", value->name); */
2381 tempbool = ir_value_life_merge(value, instr->eid);
2382 *changed = *changed || tempbool;
2384 ir_instr_dump(instr, dbg_ind, printf);
2388 /* since 'living' won't contain it
2389 * anymore, merge the value, since
2392 tempbool = ir_value_life_merge(value, instr->eid);
2395 con_err( "value added id %s %i\n", value->name, (int)instr->eid);
2397 *changed = *changed || tempbool;
2399 vec_remove(self->living, idx, 1);
2404 tempbool = ir_block_living_add_instr(self, instr->eid);
2405 /*con_err( "living added values\n");*/
2406 *changed = *changed || tempbool;
2410 if (self->run_id == self->owner->run_id)
2413 self->run_id = self->owner->run_id;
2415 for (i = 0; i < vec_size(self->entries); ++i)
2417 ir_block *entry = self->entries[i];
2418 ir_block_life_propagate(entry, self, changed);
2424 /***********************************************************************
2427 * Since the IR has the convention of putting 'write' operands
2428 * at the beginning, we have to rotate the operands of instructions
2429 * properly in order to generate valid QCVM code.
2431 * Having destinations at a fixed position is more convenient. In QC
2432 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2433 * read from from OPA, and store to OPB rather than OPC. Which is
2434 * partially the reason why the implementation of these instructions
2435 * in darkplaces has been delayed for so long.
2437 * Breaking conventions is annoying...
2439 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2441 static bool gen_global_field(ir_value *global)
2443 if (global->isconst)
2445 ir_value *fld = global->constval.vpointer;
2447 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2451 /* Now, in this case, a relocation would be impossible to code
2452 * since it looks like this:
2453 * .vector v = origin; <- parse error, wtf is 'origin'?
2456 * But we will need a general relocation support later anyway
2457 * for functions... might as well support that here.
2459 if (!fld->code.globaladdr) {
2460 irerror(global->context, "FIXME: Relocation support");
2464 /* copy the field's value */
2465 ir_value_code_setaddr(global, vec_size(code_globals));
2466 vec_push(code_globals, code_globals[fld->code.globaladdr]);
2467 if (global->fieldtype == TYPE_VECTOR) {
2468 vec_push(code_globals, code_globals[fld->code.globaladdr]+1);
2469 vec_push(code_globals, code_globals[fld->code.globaladdr]+2);
2474 ir_value_code_setaddr(global, vec_size(code_globals));
2475 vec_push(code_globals, 0);
2476 if (global->fieldtype == TYPE_VECTOR) {
2477 vec_push(code_globals, 0);
2478 vec_push(code_globals, 0);
2481 if (global->code.globaladdr < 0)
2486 static bool gen_global_pointer(ir_value *global)
2488 if (global->isconst)
2490 ir_value *target = global->constval.vpointer;
2492 irerror(global->context, "Invalid pointer constant: %s", global->name);
2493 /* NULL pointers are pointing to the NULL constant, which also
2494 * sits at address 0, but still has an ir_value for itself.
2499 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2500 * void() foo; <- proto
2501 * void() *fooptr = &foo;
2502 * void() foo = { code }
2504 if (!target->code.globaladdr) {
2505 /* FIXME: Check for the constant nullptr ir_value!
2506 * because then code.globaladdr being 0 is valid.
2508 irerror(global->context, "FIXME: Relocation support");
2512 ir_value_code_setaddr(global, vec_size(code_globals));
2513 vec_push(code_globals, target->code.globaladdr);
2517 ir_value_code_setaddr(global, vec_size(code_globals));
2518 vec_push(code_globals, 0);
2520 if (global->code.globaladdr < 0)
2525 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2527 prog_section_statement stmt;
2536 block->generated = true;
2537 block->code_start = vec_size(code_statements);
2538 for (i = 0; i < vec_size(block->instr); ++i)
2540 instr = block->instr[i];
2542 if (instr->opcode == VINSTR_PHI) {
2543 irerror(block->context, "cannot generate virtual instruction (phi)");
2547 if (instr->opcode == VINSTR_JUMP) {
2548 target = instr->bops[0];
2549 /* for uncoditional jumps, if the target hasn't been generated
2550 * yet, we generate them right here.
2552 if (!target->generated) {
2557 /* otherwise we generate a jump instruction */
2558 stmt.opcode = INSTR_GOTO;
2559 stmt.o1.s1 = (target->code_start) - vec_size(code_statements);
2562 vec_push(code_statements, stmt);
2564 /* no further instructions can be in this block */
2568 if (instr->opcode == VINSTR_COND) {
2569 ontrue = instr->bops[0];
2570 onfalse = instr->bops[1];
2571 /* TODO: have the AST signal which block should
2572 * come first: eg. optimize IFs without ELSE...
2575 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2579 if (ontrue->generated) {
2580 stmt.opcode = INSTR_IF;
2581 stmt.o2.s1 = (ontrue->code_start) - vec_size(code_statements);
2582 vec_push(code_statements, stmt);
2584 if (onfalse->generated) {
2585 stmt.opcode = INSTR_IFNOT;
2586 stmt.o2.s1 = (onfalse->code_start) - vec_size(code_statements);
2587 vec_push(code_statements, stmt);
2589 if (!ontrue->generated) {
2590 if (onfalse->generated) {
2595 if (!onfalse->generated) {
2596 if (ontrue->generated) {
2601 /* neither ontrue nor onfalse exist */
2602 stmt.opcode = INSTR_IFNOT;
2603 if (!instr->likely) {
2604 /* Honor the likelyhood hint */
2605 ir_block *tmp = onfalse;
2606 stmt.opcode = INSTR_IF;
2610 stidx = vec_size(code_statements);
2611 vec_push(code_statements, stmt);
2612 /* on false we jump, so add ontrue-path */
2613 if (!gen_blocks_recursive(func, ontrue))
2615 /* fixup the jump address */
2616 code_statements[stidx].o2.s1 = vec_size(code_statements) - stidx;
2617 /* generate onfalse path */
2618 if (onfalse->generated) {
2619 /* fixup the jump address */
2620 code_statements[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2621 stmt.opcode = vec_last(code_statements).opcode;
2622 if (stmt.opcode == INSTR_GOTO ||
2623 stmt.opcode == INSTR_IF ||
2624 stmt.opcode == INSTR_IFNOT ||
2625 stmt.opcode == INSTR_RETURN ||
2626 stmt.opcode == INSTR_DONE)
2628 /* no use jumping from here */
2631 /* may have been generated in the previous recursive call */
2632 stmt.opcode = INSTR_GOTO;
2633 stmt.o1.s1 = (onfalse->code_start) - vec_size(code_statements);
2636 vec_push(code_statements, stmt);
2639 /* if not, generate now */
2644 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2645 /* Trivial call translation:
2646 * copy all params to OFS_PARM*
2647 * if the output's storetype is not store_return,
2648 * add append a STORE instruction!
2650 * NOTES on how to do it better without much trouble:
2651 * -) The liferanges!
2652 * Simply check the liferange of all parameters for
2653 * other CALLs. For each param with no CALL in its
2654 * liferange, we can store it in an OFS_PARM at
2655 * generation already. This would even include later
2656 * reuse.... probably... :)
2661 first = vec_size(instr->params);
2664 for (p = 0; p < first; ++p)
2666 ir_value *param = instr->params[p];
2668 stmt.opcode = INSTR_STORE_F;
2671 if (param->vtype == TYPE_FIELD)
2672 stmt.opcode = field_store_instr[param->fieldtype];
2674 stmt.opcode = type_store_instr[param->vtype];
2675 stmt.o1.u1 = ir_value_code_addr(param);
2676 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2677 vec_push(code_statements, stmt);
2679 /* Now handle extparams */
2680 first = vec_size(instr->params);
2681 for (; p < first; ++p)
2683 ir_builder *ir = func->owner;
2684 ir_value *param = instr->params[p];
2685 ir_value *targetparam;
2687 if (p-8 >= vec_size(ir->extparams)) {
2688 irerror(instr->context, "Not enough extparam-globals have been created");
2692 targetparam = ir->extparams[p-8];
2694 stmt.opcode = INSTR_STORE_F;
2697 if (param->vtype == TYPE_FIELD)
2698 stmt.opcode = field_store_instr[param->fieldtype];
2700 stmt.opcode = type_store_instr[param->vtype];
2701 stmt.o1.u1 = ir_value_code_addr(param);
2702 stmt.o2.u1 = ir_value_code_addr(targetparam);
2703 vec_push(code_statements, stmt);
2706 stmt.opcode = INSTR_CALL0 + vec_size(instr->params);
2707 if (stmt.opcode > INSTR_CALL8)
2708 stmt.opcode = INSTR_CALL8;
2709 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2712 vec_push(code_statements, stmt);
2714 retvalue = instr->_ops[0];
2715 if (retvalue && retvalue->store != store_return && vec_size(retvalue->life))
2717 /* not to be kept in OFS_RETURN */
2718 if (retvalue->vtype == TYPE_FIELD)
2719 stmt.opcode = field_store_instr[retvalue->vtype];
2721 stmt.opcode = type_store_instr[retvalue->vtype];
2722 stmt.o1.u1 = OFS_RETURN;
2723 stmt.o2.u1 = ir_value_code_addr(retvalue);
2725 vec_push(code_statements, stmt);
2730 if (instr->opcode == INSTR_STATE) {
2731 irerror(block->context, "TODO: state instruction");
2735 stmt.opcode = instr->opcode;
2740 /* This is the general order of operands */
2742 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2745 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2748 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2750 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2752 stmt.o1.u1 = stmt.o3.u1;
2755 else if ((stmt.opcode >= INSTR_STORE_F &&
2756 stmt.opcode <= INSTR_STORE_FNC) ||
2757 (stmt.opcode >= INSTR_STOREP_F &&
2758 stmt.opcode <= INSTR_STOREP_FNC))
2760 /* 2-operand instructions with A -> B */
2761 stmt.o2.u1 = stmt.o3.u1;
2765 vec_push(code_statements, stmt);
2770 static bool gen_function_code(ir_function *self)
2773 prog_section_statement stmt;
2775 /* Starting from entry point, we generate blocks "as they come"
2776 * for now. Dead blocks will not be translated obviously.
2778 if (!vec_size(self->blocks)) {
2779 irerror(self->context, "Function '%s' declared without body.", self->name);
2783 block = self->blocks[0];
2784 if (block->generated)
2787 if (!gen_blocks_recursive(self, block)) {
2788 irerror(self->context, "failed to generate blocks for '%s'", self->name);
2792 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2793 stmt.opcode = AINSTR_END;
2797 vec_push(code_statements, stmt);
2801 static qcint ir_builder_filestring(ir_builder *ir, const char *filename)
2803 /* NOTE: filename pointers are copied, we never strdup them,
2804 * thus we can use pointer-comparison to find the string.
2809 for (i = 0; i < vec_size(ir->filenames); ++i) {
2810 if (ir->filenames[i] == filename)
2811 return ir->filestrings[i];
2814 str = code_genstring(filename);
2815 vec_push(ir->filenames, filename);
2816 vec_push(ir->filestrings, str);
2820 static bool gen_global_function(ir_builder *ir, ir_value *global)
2822 prog_section_function fun;
2826 size_t local_var_end;
2828 if (!global->isconst || (!global->constval.vfunc))
2830 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
2834 irfun = global->constval.vfunc;
2836 fun.name = global->code.name;
2837 fun.file = ir_builder_filestring(ir, global->context.file);
2838 fun.profile = 0; /* always 0 */
2839 fun.nargs = vec_size(irfun->params);
2843 for (i = 0;i < 8; ++i) {
2847 fun.argsize[i] = type_sizeof[irfun->params[i]];
2850 fun.firstlocal = vec_size(code_globals);
2852 local_var_end = fun.firstlocal;
2853 for (i = 0; i < vec_size(irfun->locals); ++i) {
2854 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
2855 irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
2859 if (vec_size(irfun->locals)) {
2860 ir_value *last = vec_last(irfun->locals);
2861 local_var_end = last->code.globaladdr;
2862 local_var_end += type_sizeof[last->vtype];
2864 for (i = 0; i < vec_size(irfun->values); ++i)
2866 /* generate code.globaladdr for ssa values */
2867 ir_value *v = irfun->values[i];
2868 ir_value_code_setaddr(v, local_var_end + v->code.local);
2870 for (i = 0; i < irfun->allocated_locals; ++i) {
2871 /* fill the locals with zeros */
2872 vec_push(code_globals, 0);
2875 fun.locals = vec_size(code_globals) - fun.firstlocal;
2878 fun.entry = irfun->builtin;
2880 irfun->code_function_def = vec_size(code_functions);
2881 fun.entry = vec_size(code_statements);
2884 vec_push(code_functions, fun);
2888 static void ir_gen_extparam(ir_builder *ir)
2890 prog_section_def def;
2894 snprintf(name, sizeof(name), "EXTPARM#%i", (int)(vec_size(ir->extparams)+8));
2895 global = ir_value_var(name, store_global, TYPE_VECTOR);
2897 def.name = code_genstring(name);
2898 def.type = TYPE_VECTOR;
2899 def.offset = vec_size(code_globals);
2901 vec_push(code_defs, def);
2902 ir_value_code_setaddr(global, def.offset);
2903 vec_push(code_globals, 0);
2904 vec_push(code_globals, 0);
2905 vec_push(code_globals, 0);
2907 vec_push(ir->extparams, global);
2910 static bool gen_function_extparam_copy(ir_function *self)
2912 size_t i, ext, numparams;
2914 ir_builder *ir = self->owner;
2916 prog_section_statement stmt;
2918 numparams = vec_size(self->params);
2922 stmt.opcode = INSTR_STORE_F;
2924 for (i = 8; i < numparams; ++i) {
2926 if (ext >= vec_size(ir->extparams))
2927 ir_gen_extparam(ir);
2929 ep = ir->extparams[ext];
2931 stmt.opcode = type_store_instr[self->locals[i]->vtype];
2932 if (self->locals[i]->vtype == TYPE_FIELD &&
2933 self->locals[i]->fieldtype == TYPE_VECTOR)
2935 stmt.opcode = INSTR_STORE_V;
2937 stmt.o1.u1 = ir_value_code_addr(ep);
2938 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
2939 vec_push(code_statements, stmt);
2945 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
2947 prog_section_function *fundef;
2952 irfun = global->constval.vfunc;
2954 irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
2955 "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
2956 /* this was a function pointer, don't generate code for those */
2963 if (irfun->code_function_def < 0) {
2964 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
2967 fundef = &code_functions[irfun->code_function_def];
2969 fundef->entry = vec_size(code_statements);
2970 if (!gen_function_extparam_copy(irfun)) {
2971 irerror(irfun->context, "Failed to generate extparam-copy code for function %s", irfun->name);
2974 if (!gen_function_code(irfun)) {
2975 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
2981 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
2985 prog_section_def def;
2987 def.type = global->vtype;
2988 def.offset = vec_size(code_globals);
2991 if (global->name[0] == '#') {
2992 if (!self->str_immediate)
2993 self->str_immediate = code_genstring("IMMEDIATE");
2994 def.name = global->code.name = self->str_immediate;
2997 def.name = global->code.name = code_genstring(global->name);
3002 switch (global->vtype)
3005 if (!strcmp(global->name, "end_sys_globals")) {
3006 /* TODO: remember this point... all the defs before this one
3007 * should be checksummed and added to progdefs.h when we generate it.
3010 else if (!strcmp(global->name, "end_sys_fields")) {
3011 /* TODO: same as above but for entity-fields rather than globsl
3015 irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3017 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3018 * the system fields actually go? Though the engine knows this anyway...
3019 * Maybe this could be an -foption
3020 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3022 ir_value_code_setaddr(global, vec_size(code_globals));
3023 vec_push(code_globals, 0);
3025 vec_push(code_defs, def);
3028 vec_push(code_defs, def);
3029 return gen_global_pointer(global);
3031 vec_push(code_defs, def);
3032 return gen_global_field(global);
3037 ir_value_code_setaddr(global, vec_size(code_globals));
3038 if (global->isconst) {
3039 iptr = (int32_t*)&global->constval.ivec[0];
3040 vec_push(code_globals, *iptr);
3042 vec_push(code_globals, 0);
3044 def.type |= DEF_SAVEGLOBAL;
3046 vec_push(code_defs, def);
3048 return global->code.globaladdr >= 0;
3052 ir_value_code_setaddr(global, vec_size(code_globals));
3053 if (global->isconst) {
3054 vec_push(code_globals, code_genstring(global->constval.vstring));
3056 vec_push(code_globals, 0);
3058 def.type |= DEF_SAVEGLOBAL;
3060 vec_push(code_defs, def);
3061 return global->code.globaladdr >= 0;
3066 ir_value_code_setaddr(global, vec_size(code_globals));
3067 if (global->isconst) {
3068 iptr = (int32_t*)&global->constval.ivec[0];
3069 vec_push(code_globals, iptr[0]);
3070 if (global->code.globaladdr < 0)
3072 for (d = 1; d < type_sizeof[global->vtype]; ++d)
3074 vec_push(code_globals, iptr[d]);
3077 vec_push(code_globals, 0);
3078 if (global->code.globaladdr < 0)
3080 for (d = 1; d < type_sizeof[global->vtype]; ++d)
3082 vec_push(code_globals, 0);
3085 def.type |= DEF_SAVEGLOBAL;
3088 vec_push(code_defs, def);
3089 return global->code.globaladdr >= 0;
3092 ir_value_code_setaddr(global, vec_size(code_globals));
3093 if (!global->isconst) {
3094 vec_push(code_globals, 0);
3095 if (global->code.globaladdr < 0)
3098 vec_push(code_globals, vec_size(code_functions));
3099 if (!gen_global_function(self, global))
3102 def.type |= DEF_SAVEGLOBAL;
3104 vec_push(code_defs, def);
3107 /* assume biggest type */
3108 ir_value_code_setaddr(global, vec_size(code_globals));
3109 vec_push(code_globals, 0);
3110 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
3111 vec_push(code_globals, 0);
3114 /* refuse to create 'void' type or any other fancy business. */
3115 irerror(global->context, "Invalid type for global variable `%s`: %s",
3116 global->name, type_name[global->vtype]);
3121 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3123 prog_section_def def;
3124 prog_section_field fld;
3128 def.type = (uint16_t)field->vtype;
3129 def.offset = (uint16_t)vec_size(code_globals);
3131 /* create a global named the same as the field */
3132 if (opts_standard == COMPILER_GMQCC) {
3133 /* in our standard, the global gets a dot prefix */
3134 size_t len = strlen(field->name);
3137 /* we really don't want to have to allocate this, and 1024
3138 * bytes is more than enough for a variable/field name
3140 if (len+2 >= sizeof(name)) {
3141 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
3146 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
3149 def.name = code_genstring(name);
3150 fld.name = def.name + 1; /* we reuse that string table entry */
3152 /* in plain QC, there cannot be a global with the same name,
3153 * and so we also name the global the same.
3154 * FIXME: fteqcc should create a global as well
3155 * check if it actually uses the same name. Probably does
3157 def.name = code_genstring(field->name);
3158 fld.name = def.name;
3161 field->code.name = def.name;
3163 vec_push(code_defs, def);
3165 fld.type = field->fieldtype;
3167 if (fld.type == TYPE_VOID) {
3168 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
3172 fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
3174 vec_push(code_fields, fld);
3176 ir_value_code_setaddr(field, vec_size(code_globals));
3177 vec_push(code_globals, fld.offset);
3178 if (fld.type == TYPE_VECTOR) {
3179 vec_push(code_globals, fld.offset+1);
3180 vec_push(code_globals, fld.offset+2);
3183 return field->code.globaladdr >= 0;
3186 bool ir_builder_generate(ir_builder *self, const char *filename)
3188 prog_section_statement stmt;
3193 for (i = 0; i < vec_size(self->globals); ++i)
3195 if (!ir_builder_gen_global(self, self->globals[i], false)) {
3200 for (i = 0; i < vec_size(self->fields); ++i)
3202 if (!ir_builder_gen_field(self, self->fields[i])) {
3207 /* generate function code */
3208 for (i = 0; i < vec_size(self->globals); ++i)
3210 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3211 if (!gen_global_function_code(self, self->globals[i])) {
3217 if (vec_size(code_globals) >= 65536) {
3218 irerror(vec_last(self->globals)->context, "This progs file would require more globals than the metadata can handle. Bailing out.");
3222 /* DP errors if the last instruction is not an INSTR_DONE
3223 * and for debugging purposes we add an additional AINSTR_END
3224 * to the end of functions, so here it goes:
3226 stmt.opcode = INSTR_DONE;
3230 vec_push(code_statements, stmt);
3233 con_out("writing '%s'...\n", filename);
3234 return code_write(filename);
3237 /***********************************************************************
3238 *IR DEBUG Dump functions...
3241 #define IND_BUFSZ 1024
3244 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
3247 const char *qc_opname(int op)
3249 if (op < 0) return "<INVALID>";
3250 if (op < (int)( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
3251 return asm_instr[op].m;
3253 case VINSTR_PHI: return "PHI";
3254 case VINSTR_JUMP: return "JUMP";
3255 case VINSTR_COND: return "COND";
3256 default: return "<UNK>";
3260 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
3263 char indent[IND_BUFSZ];
3267 oprintf("module %s\n", b->name);
3268 for (i = 0; i < vec_size(b->globals); ++i)
3271 if (b->globals[i]->isconst)
3272 oprintf("%s = ", b->globals[i]->name);
3273 ir_value_dump(b->globals[i], oprintf);
3276 for (i = 0; i < vec_size(b->functions); ++i)
3277 ir_function_dump(b->functions[i], indent, oprintf);
3278 oprintf("endmodule %s\n", b->name);
3281 void ir_function_dump(ir_function *f, char *ind,
3282 int (*oprintf)(const char*, ...))
3285 if (f->builtin != 0) {
3286 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
3289 oprintf("%sfunction %s\n", ind, f->name);
3290 strncat(ind, "\t", IND_BUFSZ);
3291 if (vec_size(f->locals))
3293 oprintf("%s%i locals:\n", ind, (int)vec_size(f->locals));
3294 for (i = 0; i < vec_size(f->locals); ++i) {
3295 oprintf("%s\t", ind);
3296 ir_value_dump(f->locals[i], oprintf);
3300 oprintf("%sliferanges:\n", ind);
3301 for (i = 0; i < vec_size(f->locals); ++i) {
3303 ir_value *v = f->locals[i];
3304 oprintf("%s\t%s: unique ", ind, v->name);
3305 for (l = 0; l < vec_size(v->life); ++l) {
3306 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3310 for (i = 0; i < vec_size(f->values); ++i) {
3312 ir_value *v = f->values[i];
3313 oprintf("%s\t%s: @%i ", ind, v->name, (int)v->code.local);
3314 for (l = 0; l < vec_size(v->life); ++l) {
3315 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3319 if (vec_size(f->blocks))
3321 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
3322 for (i = 0; i < vec_size(f->blocks); ++i) {
3323 if (f->blocks[i]->run_id != f->run_id) {
3324 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
3326 ir_block_dump(f->blocks[i], ind, oprintf);
3330 ind[strlen(ind)-1] = 0;
3331 oprintf("%sendfunction %s\n", ind, f->name);
3334 void ir_block_dump(ir_block* b, char *ind,
3335 int (*oprintf)(const char*, ...))
3338 oprintf("%s:%s\n", ind, b->label);
3339 strncat(ind, "\t", IND_BUFSZ);
3341 for (i = 0; i < vec_size(b->instr); ++i)
3342 ir_instr_dump(b->instr[i], ind, oprintf);
3343 ind[strlen(ind)-1] = 0;
3346 void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
3349 oprintf("%s <- phi ", in->_ops[0]->name);
3350 for (i = 0; i < vec_size(in->phi); ++i)
3352 oprintf("([%s] : %s) ", in->phi[i].from->label,
3353 in->phi[i].value->name);
3358 void ir_instr_dump(ir_instr *in, char *ind,
3359 int (*oprintf)(const char*, ...))
3362 const char *comma = NULL;
3364 oprintf("%s (%i) ", ind, (int)in->eid);
3366 if (in->opcode == VINSTR_PHI) {
3367 dump_phi(in, oprintf);
3371 strncat(ind, "\t", IND_BUFSZ);
3373 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3374 ir_value_dump(in->_ops[0], oprintf);
3375 if (in->_ops[1] || in->_ops[2])
3378 if (in->opcode == INSTR_CALL0) {
3379 oprintf("CALL%i\t", vec_size(in->params));
3381 oprintf("%s\t", qc_opname(in->opcode));
3383 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3384 ir_value_dump(in->_ops[0], oprintf);
3389 for (i = 1; i != 3; ++i) {
3393 ir_value_dump(in->_ops[i], oprintf);
3401 oprintf("[%s]", in->bops[0]->label);
3405 oprintf("%s[%s]", comma, in->bops[1]->label);
3406 if (vec_size(in->params)) {
3407 oprintf("\tparams: ");
3408 for (i = 0; i != vec_size(in->params); ++i) {
3409 oprintf("%s, ", in->params[i]->name);
3413 ind[strlen(ind)-1] = 0;
3416 void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
3419 for (; *str; ++str) {
3421 case '\n': oprintf("\\n"); break;
3422 case '\r': oprintf("\\r"); break;
3423 case '\t': oprintf("\\t"); break;
3424 case '\v': oprintf("\\v"); break;
3425 case '\f': oprintf("\\f"); break;
3426 case '\b': oprintf("\\b"); break;
3427 case '\a': oprintf("\\a"); break;
3428 case '\\': oprintf("\\\\"); break;
3429 case '"': oprintf("\\\""); break;
3430 default: oprintf("%c", *str); break;
3436 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3445 oprintf("fn:%s", v->name);
3448 oprintf("%g", v->constval.vfloat);
3451 oprintf("'%g %g %g'",
3454 v->constval.vvec.z);
3457 oprintf("(entity)");
3460 ir_value_dump_string(v->constval.vstring, oprintf);
3464 oprintf("%i", v->constval.vint);
3469 v->constval.vpointer->name);
3473 oprintf("%s", v->name);
3477 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
3480 oprintf("Life of %12s:", self->name);
3481 for (i = 0; i < vec_size(self->life); ++i)
3483 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);