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 */
197 static void ir_gen_extparam(ir_builder *ir);
199 /* error functions */
201 static void irerror(lex_ctx ctx, const char *msg, ...)
205 con_cvprintmsg((void*)&ctx, LVL_ERROR, "internal error", msg, ap);
209 static bool irwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
212 int lvl = LVL_WARNING;
214 if (warntype && !OPTS_WARN(warntype))
221 con_vprintmsg(lvl, ctx.file, ctx.line, (opts_werror ? "error" : "warning"), fmt, ap);
227 /***********************************************************************
228 * Vector utility functions
231 bool GMQCC_WARN vec_ir_value_find(ir_value **vec, ir_value *what, size_t *idx)
234 size_t len = vec_size(vec);
235 for (i = 0; i < len; ++i) {
236 if (vec[i] == what) {
244 bool GMQCC_WARN vec_ir_block_find(ir_block **vec, ir_block *what, size_t *idx)
247 size_t len = vec_size(vec);
248 for (i = 0; i < len; ++i) {
249 if (vec[i] == what) {
257 bool GMQCC_WARN vec_ir_instr_find(ir_instr **vec, ir_instr *what, size_t *idx)
260 size_t len = vec_size(vec);
261 for (i = 0; i < len; ++i) {
262 if (vec[i] == what) {
270 /***********************************************************************
274 static void ir_block_delete_quick(ir_block* self);
275 static void ir_instr_delete_quick(ir_instr *self);
276 static void ir_function_delete_quick(ir_function *self);
278 ir_builder* ir_builder_new(const char *modulename)
282 self = (ir_builder*)mem_a(sizeof(*self));
286 self->functions = NULL;
287 self->globals = NULL;
289 self->extparams = NULL;
290 self->filenames = NULL;
291 self->filestrings = NULL;
292 self->htglobals = util_htnew(IR_HT_SIZE);
293 self->htfields = util_htnew(IR_HT_SIZE);
294 self->htfunctions = util_htnew(IR_HT_SIZE);
296 self->str_immediate = 0;
298 if (!ir_builder_set_name(self, modulename)) {
306 void ir_builder_delete(ir_builder* self)
309 util_htdel(self->htglobals);
310 util_htdel(self->htfields);
311 util_htdel(self->htfunctions);
312 mem_d((void*)self->name);
313 for (i = 0; i != vec_size(self->functions); ++i) {
314 ir_function_delete_quick(self->functions[i]);
316 vec_free(self->functions);
317 for (i = 0; i != vec_size(self->extparams); ++i) {
318 ir_value_delete(self->extparams[i]);
320 vec_free(self->extparams);
321 for (i = 0; i != vec_size(self->globals); ++i) {
322 ir_value_delete(self->globals[i]);
324 vec_free(self->globals);
325 for (i = 0; i != vec_size(self->fields); ++i) {
326 ir_value_delete(self->fields[i]);
328 vec_free(self->fields);
329 vec_free(self->filenames);
330 vec_free(self->filestrings);
334 bool ir_builder_set_name(ir_builder *self, const char *name)
337 mem_d((void*)self->name);
338 self->name = util_strdup(name);
342 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
344 return (ir_function*)util_htget(self->htfunctions, name);
347 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
349 ir_function *fn = ir_builder_get_function(self, name);
354 fn = ir_function_new(self, outtype);
355 if (!ir_function_set_name(fn, name))
357 ir_function_delete(fn);
360 vec_push(self->functions, fn);
361 util_htset(self->htfunctions, name, fn);
363 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
365 ir_function_delete(fn);
369 fn->value->hasvalue = true;
370 fn->value->outtype = outtype;
371 fn->value->constval.vfunc = fn;
372 fn->value->context = fn->context;
377 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
379 return (ir_value*)util_htget(self->htglobals, name);
382 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
386 if (name && name[0] != '#')
388 ve = ir_builder_get_global(self, name);
394 ve = ir_value_var(name, store_global, vtype);
395 vec_push(self->globals, ve);
396 util_htset(self->htglobals, name, ve);
400 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
402 return (ir_value*)util_htget(self->htfields, name);
406 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
408 ir_value *ve = ir_builder_get_field(self, name);
413 ve = ir_value_var(name, store_global, TYPE_FIELD);
414 ve->fieldtype = vtype;
415 vec_push(self->fields, ve);
416 util_htset(self->htfields, name, ve);
420 /***********************************************************************
424 bool ir_function_naive_phi(ir_function*);
425 void ir_function_enumerate(ir_function*);
426 bool ir_function_calculate_liferanges(ir_function*);
427 bool ir_function_allocate_locals(ir_function*);
429 ir_function* ir_function_new(ir_builder* owner, int outtype)
432 self = (ir_function*)mem_a(sizeof(*self));
437 memset(self, 0, sizeof(*self));
440 if (!ir_function_set_name(self, "<@unnamed>")) {
445 self->context.file = "<@no context>";
446 self->context.line = 0;
447 self->outtype = outtype;
456 self->code_function_def = -1;
457 self->allocated_locals = 0;
463 bool ir_function_set_name(ir_function *self, const char *name)
466 mem_d((void*)self->name);
467 self->name = util_strdup(name);
471 static void ir_function_delete_quick(ir_function *self)
474 mem_d((void*)self->name);
476 for (i = 0; i != vec_size(self->blocks); ++i)
477 ir_block_delete_quick(self->blocks[i]);
478 vec_free(self->blocks);
480 vec_free(self->params);
482 for (i = 0; i != vec_size(self->values); ++i)
483 ir_value_delete(self->values[i]);
484 vec_free(self->values);
486 for (i = 0; i != vec_size(self->locals); ++i)
487 ir_value_delete(self->locals[i]);
488 vec_free(self->locals);
490 /* self->value is deleted by the builder */
495 void ir_function_delete(ir_function *self)
498 mem_d((void*)self->name);
500 for (i = 0; i != vec_size(self->blocks); ++i)
501 ir_block_delete(self->blocks[i]);
502 vec_free(self->blocks);
504 vec_free(self->params);
506 for (i = 0; i != vec_size(self->values); ++i)
507 ir_value_delete(self->values[i]);
508 vec_free(self->values);
510 for (i = 0; i != vec_size(self->locals); ++i)
511 ir_value_delete(self->locals[i]);
512 vec_free(self->locals);
514 /* self->value is deleted by the builder */
519 void ir_function_collect_value(ir_function *self, ir_value *v)
521 vec_push(self->values, v);
524 ir_block* ir_function_create_block(lex_ctx ctx, ir_function *self, const char *label)
526 ir_block* bn = ir_block_new(self, label);
528 vec_push(self->blocks, bn);
532 static bool instr_is_operation(uint16_t op)
534 return ( (op >= INSTR_MUL_F && op <= INSTR_GT) ||
535 (op >= INSTR_LOAD_F && op <= INSTR_LOAD_FNC) ||
536 (op == INSTR_ADDRESS) ||
537 (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) ||
538 (op >= INSTR_AND && op <= INSTR_BITOR) );
541 bool ir_function_pass_minor(ir_function *self)
545 for (b = 0; b < vec_size(self->blocks); ++b) {
547 ir_block *block = self->blocks[b];
549 if (vec_size(block->instr) < 2)
552 for (i = 1; i < vec_size(block->instr); ++i) {
557 store = block->instr[i];
558 if (store->opcode < INSTR_STORE_F ||
559 store->opcode > INSTR_STORE_FNC)
564 oper = block->instr[i-1];
565 if (!instr_is_operation(oper->opcode))
568 value = oper->_ops[0];
570 /* only do it for SSA values */
571 if (value->store != store_value)
574 /* don't optimize out the temp if it's used later again */
575 if (vec_size(value->reads) != 1)
578 /* The very next store must use this value */
579 if (value->reads[0] != store)
582 /* And of course the store must _read_ from it, so it's in
584 if (store->_ops[1] != value)
587 ++optimization_count[OPTIM_PEEPHOLE];
588 oper->_ops[0] = store->_ops[0];
590 vec_remove(block->instr, i, 1);
591 ir_instr_delete(store);
598 bool ir_function_pass_tailcall(ir_function *self)
602 for (b = 0; b < vec_size(self->blocks); ++b) {
604 ir_instr *ret, *call, *store = NULL;
605 ir_block *block = self->blocks[b];
607 if (!block->final || vec_size(block->instr) < 2)
610 ret = block->instr[vec_size(block->instr)-1];
611 if (ret->opcode != INSTR_DONE && ret->opcode != INSTR_RETURN)
614 call = block->instr[vec_size(block->instr)-2];
615 if (call->opcode >= INSTR_STORE_F && call->opcode <= INSTR_STORE_FNC) {
616 /* account for the unoptimized
618 * STORE %return, %tmp
622 if (vec_size(block->instr) < 3)
626 call = block->instr[vec_size(block->instr)-3];
629 if (call->opcode < INSTR_CALL0 || call->opcode > INSTR_CALL8)
633 /* optimize out the STORE */
635 ret->_ops[0] == store->_ops[0] &&
636 store->_ops[1] == call->_ops[0])
638 ++optimization_count[OPTIM_PEEPHOLE];
639 call->_ops[0] = store->_ops[0];
640 vec_remove(block->instr, vec_size(block->instr) - 2, 1);
641 ir_instr_delete(store);
650 funcval = call->_ops[1];
653 if (funcval->vtype != TYPE_FUNCTION || funcval->constval.vfunc != self)
656 /* now we have a CALL and a RET, check if it's a tailcall */
657 if (ret->_ops[0] && call->_ops[0] != ret->_ops[0])
660 ++optimization_count[OPTIM_TAIL_RECURSION];
661 vec_shrinkby(block->instr, 2);
663 block->final = false; /* open it back up */
665 /* emite parameter-stores */
666 for (p = 0; p < vec_size(call->params); ++p) {
667 /* assert(call->params_count <= self->locals_count); */
668 if (!ir_block_create_store(block, call->context, self->locals[p], call->params[p])) {
669 irerror(call->context, "failed to create tailcall store instruction for parameter %i", (int)p);
673 if (!ir_block_create_jump(block, call->context, self->blocks[0])) {
674 irerror(call->context, "failed to create tailcall jump");
678 ir_instr_delete(call);
679 ir_instr_delete(ret);
685 bool ir_function_finalize(ir_function *self)
690 if (OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
691 if (!ir_function_pass_minor(self)) {
692 irerror(self->context, "generic optimization pass broke something in `%s`", self->name);
697 if (OPTS_OPTIMIZATION(OPTIM_TAIL_RECURSION)) {
698 if (!ir_function_pass_tailcall(self)) {
699 irerror(self->context, "tailcall optimization pass broke something in `%s`", self->name);
704 if (!ir_function_naive_phi(self))
707 ir_function_enumerate(self);
709 if (!ir_function_calculate_liferanges(self))
711 if (!ir_function_allocate_locals(self))
716 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
721 vec_size(self->locals) &&
722 self->locals[vec_size(self->locals)-1]->store != store_param) {
723 irerror(self->context, "cannot add parameters after adding locals");
727 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
728 vec_push(self->locals, ve);
732 /***********************************************************************
736 ir_block* ir_block_new(ir_function* owner, const char *name)
739 self = (ir_block*)mem_a(sizeof(*self));
743 memset(self, 0, sizeof(*self));
746 if (name && !ir_block_set_label(self, name)) {
751 self->context.file = "<@no context>";
752 self->context.line = 0;
756 self->entries = NULL;
760 self->is_return = false;
765 self->generated = false;
770 static void ir_block_delete_quick(ir_block* self)
773 if (self->label) mem_d(self->label);
774 for (i = 0; i != vec_size(self->instr); ++i)
775 ir_instr_delete_quick(self->instr[i]);
776 vec_free(self->instr);
777 vec_free(self->entries);
778 vec_free(self->exits);
779 vec_free(self->living);
783 void ir_block_delete(ir_block* self)
786 if (self->label) mem_d(self->label);
787 for (i = 0; i != vec_size(self->instr); ++i)
788 ir_instr_delete(self->instr[i]);
789 vec_free(self->instr);
790 vec_free(self->entries);
791 vec_free(self->exits);
792 vec_free(self->living);
796 bool ir_block_set_label(ir_block *self, const char *name)
799 mem_d((void*)self->label);
800 self->label = util_strdup(name);
801 return !!self->label;
804 /***********************************************************************
808 ir_instr* ir_instr_new(lex_ctx ctx, ir_block* owner, int op)
811 self = (ir_instr*)mem_a(sizeof(*self));
818 self->_ops[0] = NULL;
819 self->_ops[1] = NULL;
820 self->_ops[2] = NULL;
821 self->bops[0] = NULL;
822 self->bops[1] = NULL;
833 static void ir_instr_delete_quick(ir_instr *self)
836 vec_free(self->params);
840 void ir_instr_delete(ir_instr *self)
843 /* The following calls can only delete from
844 * vectors, we still want to delete this instruction
845 * so ignore the return value. Since with the warn_unused_result attribute
846 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
847 * I have to improvise here and use if(foo());
849 for (i = 0; i < vec_size(self->phi); ++i) {
851 if (vec_ir_instr_find(self->phi[i].value->writes, self, &idx))
852 vec_remove(self->phi[i].value->writes, idx, 1);
853 if (vec_ir_instr_find(self->phi[i].value->reads, self, &idx))
854 vec_remove(self->phi[i].value->reads, idx, 1);
857 for (i = 0; i < vec_size(self->params); ++i) {
859 if (vec_ir_instr_find(self->params[i]->writes, self, &idx))
860 vec_remove(self->params[i]->writes, idx, 1);
861 if (vec_ir_instr_find(self->params[i]->reads, self, &idx))
862 vec_remove(self->params[i]->reads, idx, 1);
864 vec_free(self->params);
865 (void)!ir_instr_op(self, 0, NULL, false);
866 (void)!ir_instr_op(self, 1, NULL, false);
867 (void)!ir_instr_op(self, 2, NULL, false);
871 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
873 if (self->_ops[op]) {
875 if (writing && vec_ir_instr_find(self->_ops[op]->writes, self, &idx))
876 vec_remove(self->_ops[op]->writes, idx, 1);
877 else if (vec_ir_instr_find(self->_ops[op]->reads, self, &idx))
878 vec_remove(self->_ops[op]->reads, idx, 1);
882 vec_push(v->writes, self);
884 vec_push(v->reads, self);
890 /***********************************************************************
894 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
896 self->code.globaladdr = gaddr;
897 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
898 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
899 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
902 int32_t ir_value_code_addr(const ir_value *self)
904 if (self->store == store_return)
905 return OFS_RETURN + self->code.addroffset;
906 return self->code.globaladdr + self->code.addroffset;
909 ir_value* ir_value_var(const char *name, int storetype, int vtype)
912 self = (ir_value*)mem_a(sizeof(*self));
914 self->fieldtype = TYPE_VOID;
915 self->outtype = TYPE_VOID;
916 self->store = storetype;
922 self->hasvalue = false;
923 self->context.file = "<@no context>";
924 self->context.line = 0;
926 if (name && !ir_value_set_name(self, name)) {
927 irerror(self->context, "out of memory");
932 memset(&self->constval, 0, sizeof(self->constval));
933 memset(&self->code, 0, sizeof(self->code));
935 self->members[0] = NULL;
936 self->members[1] = NULL;
937 self->members[2] = NULL;
938 self->memberof = NULL;
940 self->unique_life = false;
946 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
952 if (self->members[member])
953 return self->members[member];
955 if (self->vtype == TYPE_VECTOR)
957 m = ir_value_var(self->name, self->store, TYPE_FLOAT);
960 m->context = self->context;
962 self->members[member] = m;
963 m->code.addroffset = member;
965 else if (self->vtype == TYPE_FIELD)
967 if (self->fieldtype != TYPE_VECTOR)
969 m = ir_value_var(self->name, self->store, TYPE_FIELD);
972 m->fieldtype = TYPE_FLOAT;
973 m->context = self->context;
975 self->members[member] = m;
976 m->code.addroffset = member;
980 irerror(self->context, "invalid member access on %s", self->name);
988 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
990 ir_value *v = ir_value_var(name, storetype, vtype);
993 ir_function_collect_value(owner, v);
997 void ir_value_delete(ir_value* self)
1001 mem_d((void*)self->name);
1004 if (self->vtype == TYPE_STRING)
1005 mem_d((void*)self->constval.vstring);
1007 for (i = 0; i < 3; ++i) {
1008 if (self->members[i])
1009 ir_value_delete(self->members[i]);
1011 vec_free(self->reads);
1012 vec_free(self->writes);
1013 vec_free(self->life);
1017 bool ir_value_set_name(ir_value *self, const char *name)
1020 mem_d((void*)self->name);
1021 self->name = util_strdup(name);
1022 return !!self->name;
1025 bool ir_value_set_float(ir_value *self, float f)
1027 if (self->vtype != TYPE_FLOAT)
1029 self->constval.vfloat = f;
1030 self->hasvalue = true;
1034 bool ir_value_set_func(ir_value *self, int f)
1036 if (self->vtype != TYPE_FUNCTION)
1038 self->constval.vint = f;
1039 self->hasvalue = true;
1043 bool ir_value_set_vector(ir_value *self, vector v)
1045 if (self->vtype != TYPE_VECTOR)
1047 self->constval.vvec = v;
1048 self->hasvalue = true;
1052 bool ir_value_set_field(ir_value *self, ir_value *fld)
1054 if (self->vtype != TYPE_FIELD)
1056 self->constval.vpointer = fld;
1057 self->hasvalue = true;
1061 static char *ir_strdup(const char *str)
1064 /* actually dup empty strings */
1065 char *out = mem_a(1);
1069 return util_strdup(str);
1072 bool ir_value_set_string(ir_value *self, const char *str)
1074 if (self->vtype != TYPE_STRING)
1076 self->constval.vstring = ir_strdup(str);
1077 self->hasvalue = true;
1082 bool ir_value_set_int(ir_value *self, int i)
1084 if (self->vtype != TYPE_INTEGER)
1086 self->constval.vint = i;
1087 self->hasvalue = true;
1092 bool ir_value_lives(ir_value *self, size_t at)
1095 for (i = 0; i < vec_size(self->life); ++i)
1097 ir_life_entry_t *life = &self->life[i];
1098 if (life->start <= at && at <= life->end)
1100 if (life->start > at) /* since it's ordered */
1106 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
1109 vec_push(self->life, e);
1110 for (k = vec_size(self->life)-1; k > idx; --k)
1111 self->life[k] = self->life[k-1];
1112 self->life[idx] = e;
1116 bool ir_value_life_merge(ir_value *self, size_t s)
1119 ir_life_entry_t *life = NULL;
1120 ir_life_entry_t *before = NULL;
1121 ir_life_entry_t new_entry;
1123 /* Find the first range >= s */
1124 for (i = 0; i < vec_size(self->life); ++i)
1127 life = &self->life[i];
1128 if (life->start > s)
1131 /* nothing found? append */
1132 if (i == vec_size(self->life)) {
1134 if (life && life->end+1 == s)
1136 /* previous life range can be merged in */
1140 if (life && life->end >= s)
1142 e.start = e.end = s;
1143 vec_push(self->life, e);
1149 if (before->end + 1 == s &&
1150 life->start - 1 == s)
1153 before->end = life->end;
1154 vec_remove(self->life, i, 1);
1157 if (before->end + 1 == s)
1163 /* already contained */
1164 if (before->end >= s)
1168 if (life->start - 1 == s)
1173 /* insert a new entry */
1174 new_entry.start = new_entry.end = s;
1175 return ir_value_life_insert(self, i, new_entry);
1178 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1182 if (!vec_size(other->life))
1185 if (!vec_size(self->life)) {
1186 size_t count = vec_size(other->life);
1187 ir_life_entry_t *life = vec_add(self->life, count);
1188 memcpy(life, other->life, count * sizeof(*life));
1193 for (i = 0; i < vec_size(other->life); ++i)
1195 const ir_life_entry_t *life = &other->life[i];
1198 ir_life_entry_t *entry = &self->life[myi];
1200 if (life->end+1 < entry->start)
1202 /* adding an interval before entry */
1203 if (!ir_value_life_insert(self, myi, *life))
1209 if (life->start < entry->start &&
1210 life->end+1 >= entry->start)
1212 /* starts earlier and overlaps */
1213 entry->start = life->start;
1216 if (life->end > entry->end &&
1217 life->start <= entry->end+1)
1219 /* ends later and overlaps */
1220 entry->end = life->end;
1223 /* see if our change combines it with the next ranges */
1224 while (myi+1 < vec_size(self->life) &&
1225 entry->end+1 >= self->life[1+myi].start)
1227 /* overlaps with (myi+1) */
1228 if (entry->end < self->life[1+myi].end)
1229 entry->end = self->life[1+myi].end;
1230 vec_remove(self->life, myi+1, 1);
1231 entry = &self->life[myi];
1234 /* see if we're after the entry */
1235 if (life->start > entry->end)
1238 /* append if we're at the end */
1239 if (myi >= vec_size(self->life)) {
1240 vec_push(self->life, *life);
1243 /* otherweise check the next range */
1252 bool ir_values_overlap(const ir_value *a, const ir_value *b)
1254 /* For any life entry in A see if it overlaps with
1255 * any life entry in B.
1256 * Note that the life entries are orderes, so we can make a
1257 * more efficient algorithm there than naively translating the
1261 ir_life_entry_t *la, *lb, *enda, *endb;
1263 /* first of all, if either has no life range, they cannot clash */
1264 if (!vec_size(a->life) || !vec_size(b->life))
1269 enda = la + vec_size(a->life);
1270 endb = lb + vec_size(b->life);
1273 /* check if the entries overlap, for that,
1274 * both must start before the other one ends.
1276 if (la->start < lb->end &&
1277 lb->start < la->end)
1282 /* entries are ordered
1283 * one entry is earlier than the other
1284 * that earlier entry will be moved forward
1286 if (la->start < lb->start)
1288 /* order: A B, move A forward
1289 * check if we hit the end with A
1294 else /* if (lb->start < la->start) actually <= */
1296 /* order: B A, move B forward
1297 * check if we hit the end with B
1306 /***********************************************************************
1310 bool ir_block_create_store_op(ir_block *self, lex_ctx ctx, int op, ir_value *target, ir_value *what)
1314 irerror(self->context, "unreachable statement (%s)", self->label);
1317 in = ir_instr_new(ctx, self, op);
1321 if (target->store == store_value &&
1322 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1324 irerror(self->context, "cannot store to an SSA value");
1325 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1326 irerror(self->context, "instruction: %s", asm_instr[op].m);
1330 if (!ir_instr_op(in, 0, target, true) ||
1331 !ir_instr_op(in, 1, what, false))
1335 vec_push(self->instr, in);
1339 bool ir_block_create_store(ir_block *self, lex_ctx ctx, ir_value *target, ir_value *what)
1343 if (target->vtype == TYPE_VARIANT)
1344 vtype = what->vtype;
1346 vtype = target->vtype;
1349 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1350 op = INSTR_CONV_ITOF;
1351 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1352 op = INSTR_CONV_FTOI;
1354 op = type_store_instr[vtype];
1356 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1357 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1361 return ir_block_create_store_op(self, ctx, op, target, what);
1364 bool ir_block_create_storep(ir_block *self, lex_ctx ctx, ir_value *target, ir_value *what)
1369 if (target->vtype != TYPE_POINTER)
1372 /* storing using pointer - target is a pointer, type must be
1373 * inferred from source
1375 vtype = what->vtype;
1377 op = type_storep_instr[vtype];
1378 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1379 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1380 op = INSTR_STOREP_V;
1383 return ir_block_create_store_op(self, ctx, op, target, what);
1386 bool ir_block_create_return(ir_block *self, lex_ctx ctx, ir_value *v)
1390 irerror(self->context, "unreachable statement (%s)", self->label);
1394 self->is_return = true;
1395 in = ir_instr_new(ctx, self, INSTR_RETURN);
1399 if (v && !ir_instr_op(in, 0, v, false))
1402 vec_push(self->instr, in);
1406 bool ir_block_create_if(ir_block *self, lex_ctx ctx, ir_value *v,
1407 ir_block *ontrue, ir_block *onfalse)
1411 irerror(self->context, "unreachable statement (%s)", self->label);
1415 /*in = ir_instr_new(ctx, self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1416 in = ir_instr_new(ctx, self, VINSTR_COND);
1420 if (!ir_instr_op(in, 0, v, false)) {
1421 ir_instr_delete(in);
1425 in->bops[0] = ontrue;
1426 in->bops[1] = onfalse;
1428 vec_push(self->instr, in);
1430 vec_push(self->exits, ontrue);
1431 vec_push(self->exits, onfalse);
1432 vec_push(ontrue->entries, self);
1433 vec_push(onfalse->entries, self);
1437 bool ir_block_create_jump(ir_block *self, lex_ctx ctx, ir_block *to)
1441 irerror(self->context, "unreachable statement (%s)", self->label);
1445 in = ir_instr_new(ctx, self, VINSTR_JUMP);
1450 vec_push(self->instr, in);
1452 vec_push(self->exits, to);
1453 vec_push(to->entries, self);
1457 bool ir_block_create_goto(ir_block *self, lex_ctx ctx, ir_block *to)
1461 irerror(self->context, "unreachable statement (%s)", self->label);
1465 in = ir_instr_new(ctx, self, INSTR_GOTO);
1470 vec_push(self->instr, in);
1472 vec_push(self->exits, to);
1473 vec_push(to->entries, self);
1477 ir_instr* ir_block_create_phi(ir_block *self, lex_ctx ctx, const char *label, int ot)
1481 in = ir_instr_new(ctx, self, VINSTR_PHI);
1484 out = ir_value_out(self->owner, label, store_value, ot);
1486 ir_instr_delete(in);
1489 if (!ir_instr_op(in, 0, out, true)) {
1490 ir_instr_delete(in);
1491 ir_value_delete(out);
1494 vec_push(self->instr, in);
1498 ir_value* ir_phi_value(ir_instr *self)
1500 return self->_ops[0];
1503 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1507 if (!vec_ir_block_find(self->owner->entries, b, NULL)) {
1508 /* Must not be possible to cause this, otherwise the AST
1509 * is doing something wrong.
1511 irerror(self->context, "Invalid entry block for PHI");
1517 vec_push(v->reads, self);
1518 vec_push(self->phi, pe);
1521 /* call related code */
1522 ir_instr* ir_block_create_call(ir_block *self, lex_ctx ctx, const char *label, ir_value *func)
1526 in = ir_instr_new(ctx, self, INSTR_CALL0);
1529 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1531 ir_instr_delete(in);
1534 if (!ir_instr_op(in, 0, out, true) ||
1535 !ir_instr_op(in, 1, func, false))
1537 ir_instr_delete(in);
1538 ir_value_delete(out);
1541 vec_push(self->instr, in);
1545 ir_value* ir_call_value(ir_instr *self)
1547 return self->_ops[0];
1550 void ir_call_param(ir_instr* self, ir_value *v)
1552 vec_push(self->params, v);
1553 vec_push(v->reads, self);
1556 /* binary op related code */
1558 ir_value* ir_block_create_binop(ir_block *self, lex_ctx ctx,
1559 const char *label, int opcode,
1560 ir_value *left, ir_value *right)
1582 case INSTR_SUB_S: /* -- offset of string as float */
1587 case INSTR_BITOR_IF:
1588 case INSTR_BITOR_FI:
1589 case INSTR_BITAND_FI:
1590 case INSTR_BITAND_IF:
1605 case INSTR_BITAND_I:
1608 case INSTR_RSHIFT_I:
1609 case INSTR_LSHIFT_I:
1631 /* boolean operations result in floats */
1632 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1634 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1637 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1642 if (ot == TYPE_VOID) {
1643 /* The AST or parser were supposed to check this! */
1647 return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1650 ir_value* ir_block_create_unary(ir_block *self, lex_ctx ctx,
1651 const char *label, int opcode,
1654 int ot = TYPE_FLOAT;
1666 /* QC doesn't have other unary operations. We expect extensions to fill
1667 * the above list, otherwise we assume out-type = in-type, eg for an
1671 ot = operand->vtype;
1674 if (ot == TYPE_VOID) {
1675 /* The AST or parser were supposed to check this! */
1679 /* let's use the general instruction creator and pass NULL for OPB */
1680 return ir_block_create_general_instr(self, ctx, label, opcode, operand, NULL, ot);
1683 ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx ctx, const char *label,
1684 int op, ir_value *a, ir_value *b, int outype)
1689 out = ir_value_out(self->owner, label, store_value, outype);
1693 instr = ir_instr_new(ctx, self, op);
1695 ir_value_delete(out);
1699 if (!ir_instr_op(instr, 0, out, true) ||
1700 !ir_instr_op(instr, 1, a, false) ||
1701 !ir_instr_op(instr, 2, b, false) )
1706 vec_push(self->instr, instr);
1710 ir_instr_delete(instr);
1711 ir_value_delete(out);
1715 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx ctx, const char *label, ir_value *ent, ir_value *field)
1719 /* Support for various pointer types todo if so desired */
1720 if (ent->vtype != TYPE_ENTITY)
1723 if (field->vtype != TYPE_FIELD)
1726 v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1727 v->fieldtype = field->fieldtype;
1731 ir_value* ir_block_create_load_from_ent(ir_block *self, lex_ctx ctx, const char *label, ir_value *ent, ir_value *field, int outype)
1734 if (ent->vtype != TYPE_ENTITY)
1737 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1738 if (field->vtype != TYPE_FIELD)
1743 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1744 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1745 case TYPE_STRING: op = INSTR_LOAD_S; break;
1746 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1747 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1748 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1750 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1751 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1754 irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1758 return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
1761 ir_value* ir_block_create_add(ir_block *self, lex_ctx ctx,
1763 ir_value *left, ir_value *right)
1766 int l = left->vtype;
1767 int r = right->vtype;
1771 irerror(self->context, "invalid type for ir_block_create_add: %s", type_name[l]);
1787 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1789 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1794 irerror(self->context, "invalid type for ir_block_create_add: %s", type_name[l]);
1798 return ir_block_create_binop(self, ctx, label, op, left, right);
1801 ir_value* ir_block_create_sub(ir_block *self, lex_ctx ctx,
1803 ir_value *left, ir_value *right)
1806 int l = left->vtype;
1807 int r = right->vtype;
1812 irerror(self->context, "invalid type for ir_block_create_sub: %s", type_name[l]);
1828 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1830 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1835 irerror(self->context, "invalid type for ir_block_create_sub: %s", type_name[l]);
1839 return ir_block_create_binop(self, ctx, label, op, left, right);
1842 ir_value* ir_block_create_mul(ir_block *self, lex_ctx ctx,
1844 ir_value *left, ir_value *right)
1847 int l = left->vtype;
1848 int r = right->vtype;
1853 irerror(self->context, "invalid type for ir_block_create_mul: %s", type_name[l]);
1868 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1870 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1873 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1875 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1877 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1879 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1883 irerror(self->context, "invalid type for ir_block_create_mul: %s", type_name[l]);
1887 return ir_block_create_binop(self, ctx, label, op, left, right);
1890 ir_value* ir_block_create_div(ir_block *self, lex_ctx ctx,
1892 ir_value *left, ir_value *right)
1895 int l = left->vtype;
1896 int r = right->vtype;
1901 irerror(self->context, "invalid type for ir_block_create_div: %s", type_name[l]);
1914 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1916 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1918 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1923 irerror(self->context, "invalid type for ir_block_create_div: %s", type_name[l]);
1927 return ir_block_create_binop(self, ctx, label, op, left, right);
1930 /* PHI resolving breaks the SSA, and must thus be the last
1931 * step before life-range calculation.
1934 static bool ir_block_naive_phi(ir_block *self);
1935 bool ir_function_naive_phi(ir_function *self)
1939 for (i = 0; i < vec_size(self->blocks); ++i)
1941 if (!ir_block_naive_phi(self->blocks[i]))
1948 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1953 /* create a store */
1954 if (!ir_block_create_store(block, old, what))
1957 /* we now move it up */
1958 instr = vec_last(block->instr);
1959 for (i = vec_size(block->instr)-1; i > iid; --i)
1960 block->instr[i] = block->instr[i-1];
1961 block->instr[i] = instr;
1967 static bool ir_block_naive_phi(ir_block *self)
1969 size_t i, p; /*, w;*/
1970 /* FIXME: optionally, create_phi can add the phis
1971 * to a list so we don't need to loop through blocks
1972 * - anyway: "don't optimize YET"
1974 for (i = 0; i < vec_size(self->instr); ++i)
1976 ir_instr *instr = self->instr[i];
1977 if (instr->opcode != VINSTR_PHI)
1980 vec_remove(self->instr, i, 1);
1981 --i; /* NOTE: i+1 below */
1983 for (p = 0; p < vec_size(instr->phi); ++p)
1985 ir_value *v = instr->phi[p].value;
1986 ir_block *b = instr->phi[p].from;
1988 if (v->store == store_value &&
1989 vec_size(v->reads) == 1 &&
1990 vec_size(v->writes) == 1)
1992 /* replace the value */
1993 if (!ir_instr_op(v->writes[0], 0, instr->_ops[0], true))
1998 /* force a move instruction */
1999 ir_instr *prevjump = vec_last(b->instr);
2002 instr->_ops[0]->store = store_global;
2003 if (!ir_block_create_store(b, instr->context, instr->_ops[0], v))
2005 instr->_ops[0]->store = store_value;
2006 vec_push(b->instr, prevjump);
2011 ir_value *v = instr->phi[p].value;
2012 for (w = 0; w < vec_size(v->writes); ++w) {
2015 if (!v->writes[w]->_ops[0])
2018 /* When the write was to a global, we have to emit a mov */
2019 old = v->writes[w]->_ops[0];
2021 /* The original instruction now writes to the PHI target local */
2022 if (v->writes[w]->_ops[0] == v)
2023 v->writes[w]->_ops[0] = instr->_ops[0];
2025 if (old->store != store_value && old->store != store_local && old->store != store_param)
2027 /* If it originally wrote to a global we need to store the value
2030 if (!ir_naive_phi_emit_store(self, i+1, old, v))
2032 if (i+1 < vec_size(self->instr))
2033 instr = self->instr[i+1];
2036 /* In case I forget and access instr later, it'll be NULL
2037 * when it's a problem, to make sure we crash, rather than accessing
2043 /* If it didn't, we can replace all reads by the phi target now. */
2045 for (r = 0; r < vec_size(old->reads); ++r)
2048 ir_instr *ri = old->reads[r];
2049 for (op = 0; op < vec_size(ri->phi); ++op) {
2050 if (ri->phi[op].value == old)
2051 ri->phi[op].value = v;
2053 for (op = 0; op < 3; ++op) {
2054 if (ri->_ops[op] == old)
2062 ir_instr_delete(instr);
2067 /***********************************************************************
2068 *IR Temp allocation code
2069 * Propagating value life ranges by walking through the function backwards
2070 * until no more changes are made.
2071 * In theory this should happen once more than once for every nested loop
2073 * Though this implementation might run an additional time for if nests.
2076 /* Enumerate instructions used by value's life-ranges
2078 static void ir_block_enumerate(ir_block *self, size_t *_eid)
2082 for (i = 0; i < vec_size(self->instr); ++i)
2084 self->instr[i]->eid = eid++;
2089 /* Enumerate blocks and instructions.
2090 * The block-enumeration is unordered!
2091 * We do not really use the block enumreation, however
2092 * the instruction enumeration is important for life-ranges.
2094 void ir_function_enumerate(ir_function *self)
2097 size_t instruction_id = 0;
2098 for (i = 0; i < vec_size(self->blocks); ++i)
2100 self->blocks[i]->eid = i;
2101 self->blocks[i]->run_id = 0;
2102 ir_block_enumerate(self->blocks[i], &instruction_id);
2106 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
2107 bool ir_function_calculate_liferanges(ir_function *self)
2115 for (i = 0; i != vec_size(self->blocks); ++i)
2117 if (self->blocks[i]->is_return)
2119 vec_free(self->blocks[i]->living);
2120 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
2125 if (vec_size(self->blocks)) {
2126 ir_block *block = self->blocks[0];
2127 for (i = 0; i < vec_size(block->living); ++i) {
2128 ir_value *v = block->living[i];
2129 if (v->memberof || v->store != store_local)
2131 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2132 "variable `%s` may be used uninitialized in this function", v->name))
2141 /* Local-value allocator
2142 * After finishing creating the liferange of all values used in a function
2143 * we can allocate their global-positions.
2144 * This is the counterpart to register-allocation in register machines.
2151 } function_allocator;
2153 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
2156 size_t vsize = type_sizeof[var->vtype];
2158 slot = ir_value_var("reg", store_global, var->vtype);
2162 if (!ir_value_life_merge_into(slot, var))
2165 vec_push(alloc->locals, slot);
2166 vec_push(alloc->sizes, vsize);
2167 vec_push(alloc->unique, var->unique_life);
2172 ir_value_delete(slot);
2176 bool ir_function_allocate_locals(ir_function *self)
2185 function_allocator alloc;
2187 if (!vec_size(self->locals) && !vec_size(self->values))
2190 alloc.locals = NULL;
2192 alloc.positions = NULL;
2193 alloc.unique = NULL;
2195 for (i = 0; i < vec_size(self->locals); ++i)
2197 if (!OPTS_OPTIMIZATION(OPTIM_LOCALTEMPS))
2198 self->locals[i]->unique_life = true;
2199 if (!function_allocator_alloc(&alloc, self->locals[i]))
2203 /* Allocate a slot for any value that still exists */
2204 for (i = 0; i < vec_size(self->values); ++i)
2206 v = self->values[i];
2208 if (!vec_size(v->life))
2211 for (a = 0; a < vec_size(alloc.locals); ++a)
2213 /* if it's reserved for a unique liferange: skip */
2214 if (alloc.unique[a])
2217 slot = alloc.locals[a];
2219 /* never resize parameters
2220 * will be required later when overlapping temps + locals
2222 if (a < vec_size(self->params) &&
2223 alloc.sizes[a] < type_sizeof[v->vtype])
2228 if (ir_values_overlap(v, slot))
2231 if (!ir_value_life_merge_into(slot, v))
2234 /* adjust size for this slot */
2235 if (alloc.sizes[a] < type_sizeof[v->vtype])
2236 alloc.sizes[a] = type_sizeof[v->vtype];
2238 self->values[i]->code.local = a;
2241 if (a >= vec_size(alloc.locals)) {
2242 self->values[i]->code.local = vec_size(alloc.locals);
2243 if (!function_allocator_alloc(&alloc, v))
2252 /* Adjust slot positions based on sizes */
2253 vec_push(alloc.positions, 0);
2255 if (vec_size(alloc.sizes))
2256 pos = alloc.positions[0] + alloc.sizes[0];
2259 for (i = 1; i < vec_size(alloc.sizes); ++i)
2261 pos = alloc.positions[i-1] + alloc.sizes[i-1];
2262 vec_push(alloc.positions, pos);
2265 self->allocated_locals = pos + vec_last(alloc.sizes);
2267 /* Locals need to know their new position */
2268 for (i = 0; i < vec_size(self->locals); ++i) {
2269 self->locals[i]->code.local = alloc.positions[i];
2271 /* Take over the actual slot positions on values */
2272 for (i = 0; i < vec_size(self->values); ++i) {
2273 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
2281 for (i = 0; i < vec_size(alloc.locals); ++i)
2282 ir_value_delete(alloc.locals[i]);
2283 vec_free(alloc.locals);
2284 vec_free(alloc.sizes);
2285 vec_free(alloc.positions);
2289 /* Get information about which operand
2290 * is read from, or written to.
2292 static void ir_op_read_write(int op, size_t *read, size_t *write)
2312 case INSTR_STOREP_F:
2313 case INSTR_STOREP_V:
2314 case INSTR_STOREP_S:
2315 case INSTR_STOREP_ENT:
2316 case INSTR_STOREP_FLD:
2317 case INSTR_STOREP_FNC:
2328 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2331 bool changed = false;
2333 for (i = 0; i != vec_size(self->living); ++i)
2335 tempbool = ir_value_life_merge(self->living[i], eid);
2338 irerror(self->context, "block_living_add_instr() value instruction added %s: %i", self->living[i]->_name, (int)eid);
2340 changed = changed || tempbool;
2345 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
2351 /* values which have been read in a previous iteration are now
2352 * in the "living" array even if the previous block doesn't use them.
2353 * So we have to remove whatever does not exist in the previous block.
2354 * They will be re-added on-read, but the liferange merge won't cause
2356 for (i = 0; i < vec_size(self->living); ++i)
2358 if (!vec_ir_value_find(prev->living, self->living[i], NULL)) {
2359 vec_remove(self->living, i, 1);
2365 /* Whatever the previous block still has in its living set
2366 * must now be added to ours as well.
2368 for (i = 0; i < vec_size(prev->living); ++i)
2370 if (vec_ir_value_find(self->living, prev->living[i], NULL))
2372 vec_push(self->living, prev->living[i]);
2374 irerror(self->contextt from prev: %s", self->label, prev->living[i]->_name);
2380 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2386 /* bitmasks which operands are read from or written to */
2388 char dbg_ind[16] = { '#', '0' };
2393 if (!ir_block_life_prop_previous(self, prev, changed))
2397 i = vec_size(self->instr);
2400 instr = self->instr[i];
2402 /* PHI operands are always read operands */
2403 for (p = 0; p < vec_size(instr->phi); ++p)
2405 value = instr->phi[p].value;
2406 if (value->memberof)
2407 value = value->memberof;
2408 if (!vec_ir_value_find(self->living, value, NULL))
2409 vec_push(self->living, value);
2412 /* call params are read operands too */
2413 for (p = 0; p < vec_size(instr->params); ++p)
2415 value = instr->params[p];
2416 if (value->memberof)
2417 value = value->memberof;
2418 if (!vec_ir_value_find(self->living, value, NULL))
2419 vec_push(self->living, value);
2422 /* See which operands are read and write operands */
2423 ir_op_read_write(instr->opcode, &read, &write);
2425 if (instr->opcode == INSTR_MUL_VF)
2427 /* the float source will get an additional lifetime */
2428 tempbool = ir_value_life_merge(instr->_ops[2], instr->eid+1);
2429 *changed = *changed || tempbool;
2431 else if (instr->opcode == INSTR_MUL_FV)
2433 /* the float source will get an additional lifetime */
2434 tempbool = ir_value_life_merge(instr->_ops[1], instr->eid+1);
2435 *changed = *changed || tempbool;
2438 /* Go through the 3 main operands */
2439 for (o = 0; o < 3; ++o)
2441 if (!instr->_ops[o]) /* no such operand */
2444 value = instr->_ops[o];
2445 if (value->memberof)
2446 value = value->memberof;
2448 /* We only care about locals */
2449 /* we also calculate parameter liferanges so that locals
2450 * can take up parameter slots */
2451 if (value->store != store_value &&
2452 value->store != store_local &&
2453 value->store != store_param)
2459 if (!vec_ir_value_find(self->living, value, NULL))
2460 vec_push(self->living, value);
2463 /* write operands */
2464 /* When we write to a local, we consider it "dead" for the
2465 * remaining upper part of the function, since in SSA a value
2466 * can only be written once (== created)
2471 bool in_living = vec_ir_value_find(self->living, value, &idx);
2474 /* If the value isn't alive it hasn't been read before... */
2475 /* TODO: See if the warning can be emitted during parsing or AST processing
2476 * otherwise have warning printed here.
2477 * IF printing a warning here: include filecontext_t,
2478 * and make sure it's only printed once
2479 * since this function is run multiple times.
2481 /* For now: debug info: */
2482 /* con_err( "Value only written %s\n", value->name); */
2483 tempbool = ir_value_life_merge(value, instr->eid);
2484 *changed = *changed || tempbool;
2486 ir_instr_dump(instr, dbg_ind, printf);
2490 /* since 'living' won't contain it
2491 * anymore, merge the value, since
2494 tempbool = ir_value_life_merge(value, instr->eid);
2497 con_err( "value added id %s %i\n", value->name, (int)instr->eid);
2499 *changed = *changed || tempbool;
2501 vec_remove(self->living, idx, 1);
2506 tempbool = ir_block_living_add_instr(self, instr->eid);
2507 /*con_err( "living added values\n");*/
2508 *changed = *changed || tempbool;
2512 if (self->run_id == self->owner->run_id)
2515 self->run_id = self->owner->run_id;
2517 for (i = 0; i < vec_size(self->entries); ++i)
2519 ir_block *entry = self->entries[i];
2520 ir_block_life_propagate(entry, self, changed);
2526 /***********************************************************************
2529 * Since the IR has the convention of putting 'write' operands
2530 * at the beginning, we have to rotate the operands of instructions
2531 * properly in order to generate valid QCVM code.
2533 * Having destinations at a fixed position is more convenient. In QC
2534 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2535 * read from from OPA, and store to OPB rather than OPC. Which is
2536 * partially the reason why the implementation of these instructions
2537 * in darkplaces has been delayed for so long.
2539 * Breaking conventions is annoying...
2541 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2543 static bool gen_global_field(ir_value *global)
2545 if (global->hasvalue)
2547 ir_value *fld = global->constval.vpointer;
2549 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2553 /* copy the field's value */
2554 ir_value_code_setaddr(global, vec_size(code_globals));
2555 vec_push(code_globals, fld->code.fieldaddr);
2556 if (global->fieldtype == TYPE_VECTOR) {
2557 vec_push(code_globals, fld->code.fieldaddr+1);
2558 vec_push(code_globals, fld->code.fieldaddr+2);
2563 ir_value_code_setaddr(global, vec_size(code_globals));
2564 vec_push(code_globals, 0);
2565 if (global->fieldtype == TYPE_VECTOR) {
2566 vec_push(code_globals, 0);
2567 vec_push(code_globals, 0);
2570 if (global->code.globaladdr < 0)
2575 static bool gen_global_pointer(ir_value *global)
2577 if (global->hasvalue)
2579 ir_value *target = global->constval.vpointer;
2581 irerror(global->context, "Invalid pointer constant: %s", global->name);
2582 /* NULL pointers are pointing to the NULL constant, which also
2583 * sits at address 0, but still has an ir_value for itself.
2588 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2589 * void() foo; <- proto
2590 * void() *fooptr = &foo;
2591 * void() foo = { code }
2593 if (!target->code.globaladdr) {
2594 /* FIXME: Check for the constant nullptr ir_value!
2595 * because then code.globaladdr being 0 is valid.
2597 irerror(global->context, "FIXME: Relocation support");
2601 ir_value_code_setaddr(global, vec_size(code_globals));
2602 vec_push(code_globals, target->code.globaladdr);
2606 ir_value_code_setaddr(global, vec_size(code_globals));
2607 vec_push(code_globals, 0);
2609 if (global->code.globaladdr < 0)
2614 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2616 prog_section_statement stmt;
2625 block->generated = true;
2626 block->code_start = vec_size(code_statements);
2627 for (i = 0; i < vec_size(block->instr); ++i)
2629 instr = block->instr[i];
2631 if (instr->opcode == VINSTR_PHI) {
2632 irerror(block->context, "cannot generate virtual instruction (phi)");
2636 if (instr->opcode == VINSTR_JUMP) {
2637 target = instr->bops[0];
2638 /* for uncoditional jumps, if the target hasn't been generated
2639 * yet, we generate them right here.
2641 if (!target->generated) {
2646 /* otherwise we generate a jump instruction */
2647 stmt.opcode = INSTR_GOTO;
2648 stmt.o1.s1 = (target->code_start) - vec_size(code_statements);
2651 code_push_statement(&stmt, instr->context.line);
2653 /* no further instructions can be in this block */
2657 if (instr->opcode == VINSTR_COND) {
2658 ontrue = instr->bops[0];
2659 onfalse = instr->bops[1];
2660 /* TODO: have the AST signal which block should
2661 * come first: eg. optimize IFs without ELSE...
2664 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2668 if (ontrue->generated) {
2669 stmt.opcode = INSTR_IF;
2670 stmt.o2.s1 = (ontrue->code_start) - vec_size(code_statements);
2671 code_push_statement(&stmt, instr->context.line);
2673 if (onfalse->generated) {
2674 stmt.opcode = INSTR_IFNOT;
2675 stmt.o2.s1 = (onfalse->code_start) - vec_size(code_statements);
2676 code_push_statement(&stmt, instr->context.line);
2678 if (!ontrue->generated) {
2679 if (onfalse->generated) {
2684 if (!onfalse->generated) {
2685 if (ontrue->generated) {
2690 /* neither ontrue nor onfalse exist */
2691 stmt.opcode = INSTR_IFNOT;
2692 if (!instr->likely) {
2693 /* Honor the likelyhood hint */
2694 ir_block *tmp = onfalse;
2695 stmt.opcode = INSTR_IF;
2699 stidx = vec_size(code_statements);
2700 code_push_statement(&stmt, instr->context.line);
2701 /* on false we jump, so add ontrue-path */
2702 if (!gen_blocks_recursive(func, ontrue))
2704 /* fixup the jump address */
2705 code_statements[stidx].o2.s1 = vec_size(code_statements) - stidx;
2706 /* generate onfalse path */
2707 if (onfalse->generated) {
2708 /* fixup the jump address */
2709 code_statements[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2710 stmt.opcode = vec_last(code_statements).opcode;
2711 if (stmt.opcode == INSTR_GOTO ||
2712 stmt.opcode == INSTR_IF ||
2713 stmt.opcode == INSTR_IFNOT ||
2714 stmt.opcode == INSTR_RETURN ||
2715 stmt.opcode == INSTR_DONE)
2717 /* no use jumping from here */
2720 /* may have been generated in the previous recursive call */
2721 stmt.opcode = INSTR_GOTO;
2722 stmt.o1.s1 = (onfalse->code_start) - vec_size(code_statements);
2725 code_push_statement(&stmt, instr->context.line);
2728 /* if not, generate now */
2733 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2734 /* Trivial call translation:
2735 * copy all params to OFS_PARM*
2736 * if the output's storetype is not store_return,
2737 * add append a STORE instruction!
2739 * NOTES on how to do it better without much trouble:
2740 * -) The liferanges!
2741 * Simply check the liferange of all parameters for
2742 * other CALLs. For each param with no CALL in its
2743 * liferange, we can store it in an OFS_PARM at
2744 * generation already. This would even include later
2745 * reuse.... probably... :)
2750 first = vec_size(instr->params);
2753 for (p = 0; p < first; ++p)
2755 ir_value *param = instr->params[p];
2757 stmt.opcode = INSTR_STORE_F;
2760 if (param->vtype == TYPE_FIELD)
2761 stmt.opcode = field_store_instr[param->fieldtype];
2763 stmt.opcode = type_store_instr[param->vtype];
2764 stmt.o1.u1 = ir_value_code_addr(param);
2765 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2766 code_push_statement(&stmt, instr->context.line);
2768 /* Now handle extparams */
2769 first = vec_size(instr->params);
2770 for (; p < first; ++p)
2772 ir_builder *ir = func->owner;
2773 ir_value *param = instr->params[p];
2774 ir_value *targetparam;
2776 if (p-8 >= vec_size(ir->extparams))
2777 ir_gen_extparam(ir);
2779 targetparam = ir->extparams[p-8];
2781 stmt.opcode = INSTR_STORE_F;
2784 if (param->vtype == TYPE_FIELD)
2785 stmt.opcode = field_store_instr[param->fieldtype];
2787 stmt.opcode = type_store_instr[param->vtype];
2788 stmt.o1.u1 = ir_value_code_addr(param);
2789 stmt.o2.u1 = ir_value_code_addr(targetparam);
2790 code_push_statement(&stmt, instr->context.line);
2793 stmt.opcode = INSTR_CALL0 + vec_size(instr->params);
2794 if (stmt.opcode > INSTR_CALL8)
2795 stmt.opcode = INSTR_CALL8;
2796 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2799 code_push_statement(&stmt, instr->context.line);
2801 retvalue = instr->_ops[0];
2802 if (retvalue && retvalue->store != store_return && vec_size(retvalue->life))
2804 /* not to be kept in OFS_RETURN */
2805 if (retvalue->vtype == TYPE_FIELD)
2806 stmt.opcode = field_store_instr[retvalue->vtype];
2808 stmt.opcode = type_store_instr[retvalue->vtype];
2809 stmt.o1.u1 = OFS_RETURN;
2810 stmt.o2.u1 = ir_value_code_addr(retvalue);
2812 code_push_statement(&stmt, instr->context.line);
2817 if (instr->opcode == INSTR_STATE) {
2818 irerror(block->context, "TODO: state instruction");
2822 stmt.opcode = instr->opcode;
2827 /* This is the general order of operands */
2829 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2832 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2835 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2837 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2839 stmt.o1.u1 = stmt.o3.u1;
2842 else if ((stmt.opcode >= INSTR_STORE_F &&
2843 stmt.opcode <= INSTR_STORE_FNC) ||
2844 (stmt.opcode >= INSTR_STOREP_F &&
2845 stmt.opcode <= INSTR_STOREP_FNC))
2847 /* 2-operand instructions with A -> B */
2848 stmt.o2.u1 = stmt.o3.u1;
2851 /* tiny optimization, don't output
2854 if (stmt.o2.u1 == stmt.o1.u1 &&
2855 OPTS_OPTIMIZATION(OPTIM_PEEPHOLE))
2857 ++optimization_count[OPTIM_PEEPHOLE];
2862 code_push_statement(&stmt, instr->context.line);
2867 static bool gen_function_code(ir_function *self)
2870 prog_section_statement stmt;
2872 /* Starting from entry point, we generate blocks "as they come"
2873 * for now. Dead blocks will not be translated obviously.
2875 if (!vec_size(self->blocks)) {
2876 irerror(self->context, "Function '%s' declared without body.", self->name);
2880 block = self->blocks[0];
2881 if (block->generated)
2884 if (!gen_blocks_recursive(self, block)) {
2885 irerror(self->context, "failed to generate blocks for '%s'", self->name);
2889 /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2890 stmt.opcode = AINSTR_END;
2894 code_push_statement(&stmt, vec_last(code_linenums));
2898 static qcint ir_builder_filestring(ir_builder *ir, const char *filename)
2900 /* NOTE: filename pointers are copied, we never strdup them,
2901 * thus we can use pointer-comparison to find the string.
2906 for (i = 0; i < vec_size(ir->filenames); ++i) {
2907 if (ir->filenames[i] == filename)
2908 return ir->filestrings[i];
2911 str = code_genstring(filename);
2912 vec_push(ir->filenames, filename);
2913 vec_push(ir->filestrings, str);
2917 static bool gen_global_function(ir_builder *ir, ir_value *global)
2919 prog_section_function fun;
2924 size_t local_var_end;
2927 if (!global->hasvalue || (!global->constval.vfunc))
2929 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
2933 irfun = global->constval.vfunc;
2935 fun.name = global->code.name;
2936 fun.file = ir_builder_filestring(ir, global->context.file);
2937 fun.profile = 0; /* always 0 */
2938 fun.nargs = vec_size(irfun->params);
2942 for (i = 0;i < 8; ++i) {
2943 if ((int32_t)i >= fun.nargs)
2946 fun.argsize[i] = type_sizeof[irfun->params[i]];
2949 fun.firstlocal = vec_size(code_globals);
2952 local_var_end = fun.firstlocal;
2953 for (i = 0; i < vec_size(irfun->locals); ++i) {
2954 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
2955 irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
2959 if (vec_size(irfun->locals)) {
2960 ir_value *last = vec_last(irfun->locals);
2961 local_var_end = last->code.globaladdr;
2962 if (last->vtype == TYPE_FIELD && last->fieldtype == TYPE_VECTOR)
2963 local_var_end += type_sizeof[TYPE_VECTOR];
2965 local_var_end += type_sizeof[last->vtype];
2967 for (i = 0; i < vec_size(irfun->values); ++i)
2969 /* generate code.globaladdr for ssa values */
2970 ir_value *v = irfun->values[i];
2971 ir_value_code_setaddr(v, local_var_end + v->code.local);
2973 for (i = 0; i < irfun->allocated_locals; ++i) {
2974 /* fill the locals with zeros */
2975 vec_push(code_globals, 0);
2978 fun.locals = vec_size(code_globals) - fun.firstlocal;
2980 fun.locals = irfun->allocated_locals;
2981 for (i = 0; i < vec_size(irfun->locals); ++i) {
2982 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
2983 irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
2986 ir_value_code_setaddr(irfun->locals[i], fun.firstlocal + irfun->locals[i]->code.local);
2988 for (i = vec_size(code_globals) - fun.firstlocal; i < fun.locals; ++i) {
2989 vec_push(code_globals, 0);
2991 for (i = 0; i < vec_size(irfun->values); ++i)
2993 /* generate code.globaladdr for ssa values */
2994 ir_value *v = irfun->values[i];
2995 ir_value_code_setaddr(v, fun.firstlocal + v->code.local);
3000 fun.entry = irfun->builtin+1;
3002 irfun->code_function_def = vec_size(code_functions);
3003 fun.entry = vec_size(code_statements);
3006 vec_push(code_functions, fun);
3010 static void ir_gen_extparam(ir_builder *ir)
3012 prog_section_def def;
3016 snprintf(name, sizeof(name), "EXTPARM#%i", (int)(vec_size(ir->extparams)+8));
3017 global = ir_value_var(name, store_global, TYPE_VECTOR);
3019 def.name = code_genstring(name);
3020 def.type = TYPE_VECTOR;
3021 def.offset = vec_size(code_globals);
3023 vec_push(code_defs, def);
3024 ir_value_code_setaddr(global, def.offset);
3025 vec_push(code_globals, 0);
3026 vec_push(code_globals, 0);
3027 vec_push(code_globals, 0);
3029 vec_push(ir->extparams, global);
3032 static bool gen_function_extparam_copy(ir_function *self)
3034 size_t i, ext, numparams;
3036 ir_builder *ir = self->owner;
3038 prog_section_statement stmt;
3040 numparams = vec_size(self->params);
3044 stmt.opcode = INSTR_STORE_F;
3046 for (i = 8; i < numparams; ++i) {
3048 if (ext >= vec_size(ir->extparams))
3049 ir_gen_extparam(ir);
3051 ep = ir->extparams[ext];
3053 stmt.opcode = type_store_instr[self->locals[i]->vtype];
3054 if (self->locals[i]->vtype == TYPE_FIELD &&
3055 self->locals[i]->fieldtype == TYPE_VECTOR)
3057 stmt.opcode = INSTR_STORE_V;
3059 stmt.o1.u1 = ir_value_code_addr(ep);
3060 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3061 code_push_statement(&stmt, self->context.line);
3067 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
3069 prog_section_function *fundef;
3074 irfun = global->constval.vfunc;
3076 if (global->cvq == CV_NONE) {
3077 irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
3078 "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
3080 /* this was a function pointer, don't generate code for those */
3087 if (irfun->code_function_def < 0) {
3088 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
3091 fundef = &code_functions[irfun->code_function_def];
3093 fundef->entry = vec_size(code_statements);
3094 if (!gen_function_extparam_copy(irfun)) {
3095 irerror(irfun->context, "Failed to generate extparam-copy code for function %s", irfun->name);
3098 if (!gen_function_code(irfun)) {
3099 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
3105 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
3109 prog_section_def def;
3111 def.type = global->vtype;
3112 def.offset = vec_size(code_globals);
3115 if (global->name[0] == '#') {
3116 if (!self->str_immediate)
3117 self->str_immediate = code_genstring("IMMEDIATE");
3118 def.name = global->code.name = self->str_immediate;
3121 def.name = global->code.name = code_genstring(global->name);
3126 switch (global->vtype)
3129 if (!strcmp(global->name, "end_sys_globals")) {
3130 /* TODO: remember this point... all the defs before this one
3131 * should be checksummed and added to progdefs.h when we generate it.
3134 else if (!strcmp(global->name, "end_sys_fields")) {
3135 /* TODO: same as above but for entity-fields rather than globsl
3139 irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3141 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3142 * the system fields actually go? Though the engine knows this anyway...
3143 * Maybe this could be an -foption
3144 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3146 ir_value_code_setaddr(global, vec_size(code_globals));
3147 vec_push(code_globals, 0);
3149 vec_push(code_defs, def);
3152 vec_push(code_defs, def);
3153 return gen_global_pointer(global);
3155 vec_push(code_defs, def);
3156 return gen_global_field(global);
3161 ir_value_code_setaddr(global, vec_size(code_globals));
3162 if (global->hasvalue) {
3163 iptr = (int32_t*)&global->constval.ivec[0];
3164 vec_push(code_globals, *iptr);
3166 vec_push(code_globals, 0);
3168 def.type |= DEF_SAVEGLOBAL;
3170 vec_push(code_defs, def);
3172 return global->code.globaladdr >= 0;
3176 ir_value_code_setaddr(global, vec_size(code_globals));
3177 if (global->hasvalue) {
3178 vec_push(code_globals, code_genstring(global->constval.vstring));
3180 vec_push(code_globals, 0);
3182 def.type |= DEF_SAVEGLOBAL;
3184 vec_push(code_defs, def);
3185 return global->code.globaladdr >= 0;
3190 ir_value_code_setaddr(global, vec_size(code_globals));
3191 if (global->hasvalue) {
3192 iptr = (int32_t*)&global->constval.ivec[0];
3193 vec_push(code_globals, iptr[0]);
3194 if (global->code.globaladdr < 0)
3196 for (d = 1; d < type_sizeof[global->vtype]; ++d)
3198 vec_push(code_globals, iptr[d]);
3201 vec_push(code_globals, 0);
3202 if (global->code.globaladdr < 0)
3204 for (d = 1; d < type_sizeof[global->vtype]; ++d)
3206 vec_push(code_globals, 0);
3209 def.type |= DEF_SAVEGLOBAL;
3212 vec_push(code_defs, def);
3213 return global->code.globaladdr >= 0;
3216 ir_value_code_setaddr(global, vec_size(code_globals));
3217 if (!global->hasvalue) {
3218 vec_push(code_globals, 0);
3219 if (global->code.globaladdr < 0)
3222 vec_push(code_globals, vec_size(code_functions));
3223 if (!gen_global_function(self, global))
3226 def.type |= DEF_SAVEGLOBAL;
3228 vec_push(code_defs, def);
3231 /* assume biggest type */
3232 ir_value_code_setaddr(global, vec_size(code_globals));
3233 vec_push(code_globals, 0);
3234 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
3235 vec_push(code_globals, 0);
3238 /* refuse to create 'void' type or any other fancy business. */
3239 irerror(global->context, "Invalid type for global variable `%s`: %s",
3240 global->name, type_name[global->vtype]);
3245 static void ir_builder_prepare_field(ir_value *field)
3247 field->code.fieldaddr = code_alloc_field(type_sizeof[field->fieldtype]);
3250 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3252 prog_section_def def;
3253 prog_section_field fld;
3257 def.type = (uint16_t)field->vtype;
3258 def.offset = (uint16_t)vec_size(code_globals);
3260 /* create a global named the same as the field */
3261 if (opts_standard == COMPILER_GMQCC) {
3262 /* in our standard, the global gets a dot prefix */
3263 size_t len = strlen(field->name);
3266 /* we really don't want to have to allocate this, and 1024
3267 * bytes is more than enough for a variable/field name
3269 if (len+2 >= sizeof(name)) {
3270 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
3275 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
3278 def.name = code_genstring(name);
3279 fld.name = def.name + 1; /* we reuse that string table entry */
3281 /* in plain QC, there cannot be a global with the same name,
3282 * and so we also name the global the same.
3283 * FIXME: fteqcc should create a global as well
3284 * check if it actually uses the same name. Probably does
3286 def.name = code_genstring(field->name);
3287 fld.name = def.name;
3290 field->code.name = def.name;
3292 vec_push(code_defs, def);
3294 fld.type = field->fieldtype;
3296 if (fld.type == TYPE_VOID) {
3297 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
3301 fld.offset = field->code.fieldaddr;
3303 vec_push(code_fields, fld);
3305 ir_value_code_setaddr(field, vec_size(code_globals));
3306 vec_push(code_globals, fld.offset);
3307 if (fld.type == TYPE_VECTOR) {
3308 vec_push(code_globals, fld.offset+1);
3309 vec_push(code_globals, fld.offset+2);
3312 return field->code.globaladdr >= 0;
3315 bool ir_builder_generate(ir_builder *self, const char *filename)
3317 prog_section_statement stmt;
3319 char *lnofile = NULL;
3323 for (i = 0; i < vec_size(self->fields); ++i)
3325 ir_builder_prepare_field(self->fields[i]);
3328 for (i = 0; i < vec_size(self->globals); ++i)
3330 if (!ir_builder_gen_global(self, self->globals[i], false)) {
3335 for (i = 0; i < vec_size(self->fields); ++i)
3337 if (!ir_builder_gen_field(self, self->fields[i])) {
3342 /* generate function code */
3343 for (i = 0; i < vec_size(self->globals); ++i)
3345 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3346 if (!gen_global_function_code(self, self->globals[i])) {
3352 if (vec_size(code_globals) >= 65536) {
3353 irerror(vec_last(self->globals)->context, "This progs file would require more globals than the metadata can handle. Bailing out.");
3357 /* DP errors if the last instruction is not an INSTR_DONE
3358 * and for debugging purposes we add an additional AINSTR_END
3359 * to the end of functions, so here it goes:
3361 stmt.opcode = INSTR_DONE;
3365 code_push_statement(&stmt, vec_last(code_linenums));
3370 if (vec_size(code_statements) != vec_size(code_linenums)) {
3371 con_err("Linecounter wrong: %lu != %lu\n",
3372 (unsigned long)vec_size(code_statements),
3373 (unsigned long)vec_size(code_linenums));
3374 } else if (OPTS_FLAG(LNO)) {
3376 size_t filelen = strlen(filename);
3378 memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
3379 dot = strrchr(lnofile, '.');
3383 vec_shrinkto(lnofile, dot - lnofile);
3385 memcpy(vec_add(lnofile, 5), ".lno", 5);
3389 con_out("writing '%s' and '%s'...\n", filename, lnofile);
3391 con_out("writing '%s'\n", filename);
3392 if (!code_write(filename, lnofile)) {
3400 /***********************************************************************
3401 *IR DEBUG Dump functions...
3404 #define IND_BUFSZ 1024
3407 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
3410 const char *qc_opname(int op)
3412 if (op < 0) return "<INVALID>";
3413 if (op < (int)( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
3414 return asm_instr[op].m;
3416 case VINSTR_PHI: return "PHI";
3417 case VINSTR_JUMP: return "JUMP";
3418 case VINSTR_COND: return "COND";
3419 default: return "<UNK>";
3423 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
3426 char indent[IND_BUFSZ];
3430 oprintf("module %s\n", b->name);
3431 for (i = 0; i < vec_size(b->globals); ++i)
3434 if (b->globals[i]->hasvalue)
3435 oprintf("%s = ", b->globals[i]->name);
3436 ir_value_dump(b->globals[i], oprintf);
3439 for (i = 0; i < vec_size(b->functions); ++i)
3440 ir_function_dump(b->functions[i], indent, oprintf);
3441 oprintf("endmodule %s\n", b->name);
3444 void ir_function_dump(ir_function *f, char *ind,
3445 int (*oprintf)(const char*, ...))
3448 if (f->builtin != 0) {
3449 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
3452 oprintf("%sfunction %s\n", ind, f->name);
3453 strncat(ind, "\t", IND_BUFSZ);
3454 if (vec_size(f->locals))
3456 oprintf("%s%i locals:\n", ind, (int)vec_size(f->locals));
3457 for (i = 0; i < vec_size(f->locals); ++i) {
3458 oprintf("%s\t", ind);
3459 ir_value_dump(f->locals[i], oprintf);
3463 oprintf("%sliferanges:\n", ind);
3464 for (i = 0; i < vec_size(f->locals); ++i) {
3466 ir_value *v = f->locals[i];
3467 oprintf("%s\t%s: %s@%i ", ind, v->name, (v->unique_life ? "unique " : ""), (int)v->code.local);
3468 for (l = 0; l < vec_size(v->life); ++l) {
3469 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3473 for (i = 0; i < vec_size(f->values); ++i) {
3475 ir_value *v = f->values[i];
3476 oprintf("%s\t%s: @%i ", ind, v->name, (int)v->code.local);
3477 for (l = 0; l < vec_size(v->life); ++l) {
3478 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3482 if (vec_size(f->blocks))
3484 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
3485 for (i = 0; i < vec_size(f->blocks); ++i) {
3486 if (f->blocks[i]->run_id != f->run_id) {
3487 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
3489 ir_block_dump(f->blocks[i], ind, oprintf);
3493 ind[strlen(ind)-1] = 0;
3494 oprintf("%sendfunction %s\n", ind, f->name);
3497 void ir_block_dump(ir_block* b, char *ind,
3498 int (*oprintf)(const char*, ...))
3501 oprintf("%s:%s\n", ind, b->label);
3502 strncat(ind, "\t", IND_BUFSZ);
3504 for (i = 0; i < vec_size(b->instr); ++i)
3505 ir_instr_dump(b->instr[i], ind, oprintf);
3506 ind[strlen(ind)-1] = 0;
3509 void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
3512 oprintf("%s <- phi ", in->_ops[0]->name);
3513 for (i = 0; i < vec_size(in->phi); ++i)
3515 oprintf("([%s] : %s) ", in->phi[i].from->label,
3516 in->phi[i].value->name);
3521 void ir_instr_dump(ir_instr *in, char *ind,
3522 int (*oprintf)(const char*, ...))
3525 const char *comma = NULL;
3527 oprintf("%s (%i) ", ind, (int)in->eid);
3529 if (in->opcode == VINSTR_PHI) {
3530 dump_phi(in, oprintf);
3534 strncat(ind, "\t", IND_BUFSZ);
3536 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3537 ir_value_dump(in->_ops[0], oprintf);
3538 if (in->_ops[1] || in->_ops[2])
3541 if (in->opcode == INSTR_CALL0) {
3542 oprintf("CALL%i\t", vec_size(in->params));
3544 oprintf("%s\t", qc_opname(in->opcode));
3546 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3547 ir_value_dump(in->_ops[0], oprintf);
3552 for (i = 1; i != 3; ++i) {
3556 ir_value_dump(in->_ops[i], oprintf);
3564 oprintf("[%s]", in->bops[0]->label);
3568 oprintf("%s[%s]", comma, in->bops[1]->label);
3569 if (vec_size(in->params)) {
3570 oprintf("\tparams: ");
3571 for (i = 0; i != vec_size(in->params); ++i) {
3572 oprintf("%s, ", in->params[i]->name);
3576 ind[strlen(ind)-1] = 0;
3579 void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
3582 for (; *str; ++str) {
3584 case '\n': oprintf("\\n"); break;
3585 case '\r': oprintf("\\r"); break;
3586 case '\t': oprintf("\\t"); break;
3587 case '\v': oprintf("\\v"); break;
3588 case '\f': oprintf("\\f"); break;
3589 case '\b': oprintf("\\b"); break;
3590 case '\a': oprintf("\\a"); break;
3591 case '\\': oprintf("\\\\"); break;
3592 case '"': oprintf("\\\""); break;
3593 default: oprintf("%c", *str); break;
3599 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3608 oprintf("fn:%s", v->name);
3611 oprintf("%g", v->constval.vfloat);
3614 oprintf("'%g %g %g'",
3617 v->constval.vvec.z);
3620 oprintf("(entity)");
3623 ir_value_dump_string(v->constval.vstring, oprintf);
3627 oprintf("%i", v->constval.vint);
3632 v->constval.vpointer->name);
3636 oprintf("%s", v->name);
3640 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
3643 oprintf("Life of %12s:", self->name);
3644 for (i = 0; i < vec_size(self->life); ++i)
3646 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);