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 ir_value* ir_gen_extparam_proto(ir_builder *ir);
198 static void ir_gen_extparam (ir_builder *ir);
200 /* error functions */
202 static void irerror(lex_ctx ctx, const char *msg, ...)
206 con_cvprintmsg((void*)&ctx, LVL_ERROR, "internal error", msg, ap);
210 static bool irwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
215 r = vcompile_warning(ctx, warntype, fmt, ap);
220 /***********************************************************************
221 * Vector utility functions
224 bool GMQCC_WARN vec_ir_value_find(ir_value **vec, const ir_value *what, size_t *idx)
227 size_t len = vec_size(vec);
228 for (i = 0; i < len; ++i) {
229 if (vec[i] == what) {
237 bool GMQCC_WARN vec_ir_block_find(ir_block **vec, ir_block *what, size_t *idx)
240 size_t len = vec_size(vec);
241 for (i = 0; i < len; ++i) {
242 if (vec[i] == what) {
250 bool GMQCC_WARN vec_ir_instr_find(ir_instr **vec, ir_instr *what, size_t *idx)
253 size_t len = vec_size(vec);
254 for (i = 0; i < len; ++i) {
255 if (vec[i] == what) {
263 /***********************************************************************
267 static void ir_block_delete_quick(ir_block* self);
268 static void ir_instr_delete_quick(ir_instr *self);
269 static void ir_function_delete_quick(ir_function *self);
271 ir_builder* ir_builder_new(const char *modulename)
275 self = (ir_builder*)mem_a(sizeof(*self));
279 self->functions = NULL;
280 self->globals = NULL;
282 self->filenames = NULL;
283 self->filestrings = NULL;
284 self->htglobals = util_htnew(IR_HT_SIZE);
285 self->htfields = util_htnew(IR_HT_SIZE);
286 self->htfunctions = util_htnew(IR_HT_SIZE);
288 self->extparams = NULL;
289 self->extparam_protos = NULL;
291 self->max_locals = 0;
293 self->str_immediate = 0;
295 if (!ir_builder_set_name(self, modulename)) {
303 void ir_builder_delete(ir_builder* self)
306 util_htdel(self->htglobals);
307 util_htdel(self->htfields);
308 util_htdel(self->htfunctions);
309 mem_d((void*)self->name);
310 for (i = 0; i != vec_size(self->functions); ++i) {
311 ir_function_delete_quick(self->functions[i]);
313 vec_free(self->functions);
314 for (i = 0; i != vec_size(self->extparams); ++i) {
315 ir_value_delete(self->extparams[i]);
317 vec_free(self->extparams);
318 for (i = 0; i != vec_size(self->globals); ++i) {
319 ir_value_delete(self->globals[i]);
321 vec_free(self->globals);
322 for (i = 0; i != vec_size(self->fields); ++i) {
323 ir_value_delete(self->fields[i]);
325 vec_free(self->fields);
326 vec_free(self->filenames);
327 vec_free(self->filestrings);
331 bool ir_builder_set_name(ir_builder *self, const char *name)
334 mem_d((void*)self->name);
335 self->name = util_strdup(name);
339 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
341 return (ir_function*)util_htget(self->htfunctions, name);
344 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
346 ir_function *fn = ir_builder_get_function(self, name);
351 fn = ir_function_new(self, outtype);
352 if (!ir_function_set_name(fn, name))
354 ir_function_delete(fn);
357 vec_push(self->functions, fn);
358 util_htset(self->htfunctions, name, fn);
360 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
362 ir_function_delete(fn);
366 fn->value->hasvalue = true;
367 fn->value->outtype = outtype;
368 fn->value->constval.vfunc = fn;
369 fn->value->context = fn->context;
374 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
376 return (ir_value*)util_htget(self->htglobals, name);
379 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
383 if (name && name[0] != '#')
385 ve = ir_builder_get_global(self, name);
391 ve = ir_value_var(name, store_global, vtype);
392 vec_push(self->globals, ve);
393 util_htset(self->htglobals, name, ve);
397 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
399 return (ir_value*)util_htget(self->htfields, name);
403 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
405 ir_value *ve = ir_builder_get_field(self, name);
410 ve = ir_value_var(name, store_global, TYPE_FIELD);
411 ve->fieldtype = vtype;
412 vec_push(self->fields, ve);
413 util_htset(self->htfields, name, ve);
417 /***********************************************************************
421 bool ir_function_naive_phi(ir_function*);
422 void ir_function_enumerate(ir_function*);
423 bool ir_function_calculate_liferanges(ir_function*);
424 bool ir_function_allocate_locals(ir_function*);
426 ir_function* ir_function_new(ir_builder* owner, int outtype)
429 self = (ir_function*)mem_a(sizeof(*self));
434 memset(self, 0, sizeof(*self));
437 if (!ir_function_set_name(self, "<@unnamed>")) {
444 self->context.file = "<@no context>";
445 self->context.line = 0;
446 self->outtype = outtype;
455 self->code_function_def = -1;
456 self->allocated_locals = 0;
462 bool ir_function_set_name(ir_function *self, const char *name)
465 mem_d((void*)self->name);
466 self->name = util_strdup(name);
470 static void ir_function_delete_quick(ir_function *self)
473 mem_d((void*)self->name);
475 for (i = 0; i != vec_size(self->blocks); ++i)
476 ir_block_delete_quick(self->blocks[i]);
477 vec_free(self->blocks);
479 vec_free(self->params);
481 for (i = 0; i != vec_size(self->values); ++i)
482 ir_value_delete(self->values[i]);
483 vec_free(self->values);
485 for (i = 0; i != vec_size(self->locals); ++i)
486 ir_value_delete(self->locals[i]);
487 vec_free(self->locals);
489 /* self->value is deleted by the builder */
494 void ir_function_delete(ir_function *self)
497 mem_d((void*)self->name);
499 for (i = 0; i != vec_size(self->blocks); ++i)
500 ir_block_delete(self->blocks[i]);
501 vec_free(self->blocks);
503 vec_free(self->params);
505 for (i = 0; i != vec_size(self->values); ++i)
506 ir_value_delete(self->values[i]);
507 vec_free(self->values);
509 for (i = 0; i != vec_size(self->locals); ++i)
510 ir_value_delete(self->locals[i]);
511 vec_free(self->locals);
513 /* self->value is deleted by the builder */
518 void ir_function_collect_value(ir_function *self, ir_value *v)
520 vec_push(self->values, v);
523 ir_block* ir_function_create_block(lex_ctx ctx, ir_function *self, const char *label)
525 ir_block* bn = ir_block_new(self, label);
527 vec_push(self->blocks, bn);
531 static bool instr_is_operation(uint16_t op)
533 return ( (op >= INSTR_MUL_F && op <= INSTR_GT) ||
534 (op >= INSTR_LOAD_F && op <= INSTR_LOAD_FNC) ||
535 (op == INSTR_ADDRESS) ||
536 (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) ||
537 (op >= INSTR_AND && op <= INSTR_BITOR) ||
538 (op >= INSTR_CALL0 && op <= INSTR_CALL8) );
541 bool ir_function_pass_peephole(ir_function *self)
545 for (b = 0; b < vec_size(self->blocks); ++b) {
547 ir_block *block = self->blocks[b];
549 for (i = 0; i < vec_size(block->instr); ++i) {
551 inst = block->instr[i];
554 (inst->opcode >= INSTR_STORE_F &&
555 inst->opcode <= INSTR_STORE_FNC))
563 oper = block->instr[i-1];
564 if (!instr_is_operation(oper->opcode))
567 value = oper->_ops[0];
569 /* only do it for SSA values */
570 if (value->store != store_value)
573 /* don't optimize out the temp if it's used later again */
574 if (vec_size(value->reads) != 1)
577 /* The very next store must use this value */
578 if (value->reads[0] != store)
581 /* And of course the store must _read_ from it, so it's in
583 if (store->_ops[1] != value)
586 ++opts_optimizationcount[OPTIM_PEEPHOLE];
587 (void)!ir_instr_op(oper, 0, store->_ops[0], true);
589 vec_remove(block->instr, i, 1);
590 ir_instr_delete(store);
592 else if (inst->opcode == VINSTR_COND)
594 /* COND on a value resulting from a NOT could
595 * remove the NOT and swap its operands
602 value = inst->_ops[0];
604 if (value->store != store_value ||
605 vec_size(value->reads) != 1 ||
606 value->reads[0] != inst)
611 inot = value->writes[0];
612 if (inot->_ops[0] != value ||
613 inot->opcode < INSTR_NOT_F ||
614 inot->opcode > INSTR_NOT_FNC ||
615 inot->opcode == INSTR_NOT_V || /* can't do these */
616 inot->opcode == INSTR_NOT_S)
622 ++opts_optimizationcount[OPTIM_PEEPHOLE];
624 (void)!ir_instr_op(inst, 0, inot->_ops[1], false);
627 for (inotid = 0; inotid < vec_size(tmp->instr); ++inotid) {
628 if (tmp->instr[inotid] == inot)
631 if (inotid >= vec_size(tmp->instr)) {
632 compile_error(inst->context, "sanity-check failed: failed to find instruction to optimize out");
635 vec_remove(tmp->instr, inotid, 1);
636 ir_instr_delete(inot);
637 /* swap ontrue/onfalse */
639 inst->bops[0] = inst->bops[1];
650 bool ir_function_pass_tailrecursion(ir_function *self)
654 for (b = 0; b < vec_size(self->blocks); ++b) {
656 ir_instr *ret, *call, *store = NULL;
657 ir_block *block = self->blocks[b];
659 if (!block->final || vec_size(block->instr) < 2)
662 ret = block->instr[vec_size(block->instr)-1];
663 if (ret->opcode != INSTR_DONE && ret->opcode != INSTR_RETURN)
666 call = block->instr[vec_size(block->instr)-2];
667 if (call->opcode >= INSTR_STORE_F && call->opcode <= INSTR_STORE_FNC) {
668 /* account for the unoptimized
670 * STORE %return, %tmp
674 if (vec_size(block->instr) < 3)
678 call = block->instr[vec_size(block->instr)-3];
681 if (call->opcode < INSTR_CALL0 || call->opcode > INSTR_CALL8)
685 /* optimize out the STORE */
687 ret->_ops[0] == store->_ops[0] &&
688 store->_ops[1] == call->_ops[0])
690 ++opts_optimizationcount[OPTIM_PEEPHOLE];
691 call->_ops[0] = store->_ops[0];
692 vec_remove(block->instr, vec_size(block->instr) - 2, 1);
693 ir_instr_delete(store);
702 funcval = call->_ops[1];
705 if (funcval->vtype != TYPE_FUNCTION || funcval->constval.vfunc != self)
708 /* now we have a CALL and a RET, check if it's a tailcall */
709 if (ret->_ops[0] && call->_ops[0] != ret->_ops[0])
712 ++opts_optimizationcount[OPTIM_TAIL_RECURSION];
713 vec_shrinkby(block->instr, 2);
715 block->final = false; /* open it back up */
717 /* emite parameter-stores */
718 for (p = 0; p < vec_size(call->params); ++p) {
719 /* assert(call->params_count <= self->locals_count); */
720 if (!ir_block_create_store(block, call->context, self->locals[p], call->params[p])) {
721 irerror(call->context, "failed to create tailcall store instruction for parameter %i", (int)p);
725 if (!ir_block_create_jump(block, call->context, self->blocks[0])) {
726 irerror(call->context, "failed to create tailcall jump");
730 ir_instr_delete(call);
731 ir_instr_delete(ret);
737 bool ir_function_finalize(ir_function *self)
742 if (OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
743 if (!ir_function_pass_peephole(self)) {
744 irerror(self->context, "generic optimization pass broke something in `%s`", self->name);
749 if (OPTS_OPTIMIZATION(OPTIM_TAIL_RECURSION)) {
750 if (!ir_function_pass_tailrecursion(self)) {
751 irerror(self->context, "tail-recursion optimization pass broke something in `%s`", self->name);
756 if (!ir_function_naive_phi(self))
759 ir_function_enumerate(self);
761 if (!ir_function_calculate_liferanges(self))
763 if (!ir_function_allocate_locals(self))
768 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
773 vec_size(self->locals) &&
774 self->locals[vec_size(self->locals)-1]->store != store_param) {
775 irerror(self->context, "cannot add parameters after adding locals");
779 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
780 vec_push(self->locals, ve);
784 /***********************************************************************
788 ir_block* ir_block_new(ir_function* owner, const char *name)
791 self = (ir_block*)mem_a(sizeof(*self));
795 memset(self, 0, sizeof(*self));
798 if (name && !ir_block_set_label(self, name)) {
803 self->context.file = "<@no context>";
804 self->context.line = 0;
808 self->entries = NULL;
812 self->is_return = false;
817 self->generated = false;
822 static void ir_block_delete_quick(ir_block* self)
825 if (self->label) mem_d(self->label);
826 for (i = 0; i != vec_size(self->instr); ++i)
827 ir_instr_delete_quick(self->instr[i]);
828 vec_free(self->instr);
829 vec_free(self->entries);
830 vec_free(self->exits);
831 vec_free(self->living);
835 void ir_block_delete(ir_block* self)
838 if (self->label) mem_d(self->label);
839 for (i = 0; i != vec_size(self->instr); ++i)
840 ir_instr_delete(self->instr[i]);
841 vec_free(self->instr);
842 vec_free(self->entries);
843 vec_free(self->exits);
844 vec_free(self->living);
848 bool ir_block_set_label(ir_block *self, const char *name)
851 mem_d((void*)self->label);
852 self->label = util_strdup(name);
853 return !!self->label;
856 /***********************************************************************
860 ir_instr* ir_instr_new(lex_ctx ctx, ir_block* owner, int op)
863 self = (ir_instr*)mem_a(sizeof(*self));
870 self->_ops[0] = NULL;
871 self->_ops[1] = NULL;
872 self->_ops[2] = NULL;
873 self->bops[0] = NULL;
874 self->bops[1] = NULL;
885 static void ir_instr_delete_quick(ir_instr *self)
888 vec_free(self->params);
892 void ir_instr_delete(ir_instr *self)
895 /* The following calls can only delete from
896 * vectors, we still want to delete this instruction
897 * so ignore the return value. Since with the warn_unused_result attribute
898 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
899 * I have to improvise here and use if(foo());
901 for (i = 0; i < vec_size(self->phi); ++i) {
903 if (vec_ir_instr_find(self->phi[i].value->writes, self, &idx))
904 vec_remove(self->phi[i].value->writes, idx, 1);
905 if (vec_ir_instr_find(self->phi[i].value->reads, self, &idx))
906 vec_remove(self->phi[i].value->reads, idx, 1);
909 for (i = 0; i < vec_size(self->params); ++i) {
911 if (vec_ir_instr_find(self->params[i]->writes, self, &idx))
912 vec_remove(self->params[i]->writes, idx, 1);
913 if (vec_ir_instr_find(self->params[i]->reads, self, &idx))
914 vec_remove(self->params[i]->reads, idx, 1);
916 vec_free(self->params);
917 (void)!ir_instr_op(self, 0, NULL, false);
918 (void)!ir_instr_op(self, 1, NULL, false);
919 (void)!ir_instr_op(self, 2, NULL, false);
923 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
925 if (self->_ops[op]) {
927 if (writing && vec_ir_instr_find(self->_ops[op]->writes, self, &idx))
928 vec_remove(self->_ops[op]->writes, idx, 1);
929 else if (vec_ir_instr_find(self->_ops[op]->reads, self, &idx))
930 vec_remove(self->_ops[op]->reads, idx, 1);
934 vec_push(v->writes, self);
936 vec_push(v->reads, self);
942 /***********************************************************************
946 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
948 self->code.globaladdr = gaddr;
949 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
950 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
951 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
954 int32_t ir_value_code_addr(const ir_value *self)
956 if (self->store == store_return)
957 return OFS_RETURN + self->code.addroffset;
958 return self->code.globaladdr + self->code.addroffset;
961 ir_value* ir_value_var(const char *name, int storetype, int vtype)
964 self = (ir_value*)mem_a(sizeof(*self));
966 self->fieldtype = TYPE_VOID;
967 self->outtype = TYPE_VOID;
968 self->store = storetype;
974 self->hasvalue = false;
975 self->context.file = "<@no context>";
976 self->context.line = 0;
978 if (name && !ir_value_set_name(self, name)) {
979 irerror(self->context, "out of memory");
984 memset(&self->constval, 0, sizeof(self->constval));
985 memset(&self->code, 0, sizeof(self->code));
987 self->members[0] = NULL;
988 self->members[1] = NULL;
989 self->members[2] = NULL;
990 self->memberof = NULL;
992 self->unique_life = false;
993 self->locked = false;
994 self->callparam = false;
1000 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
1008 if (self->members[member])
1009 return self->members[member];
1012 len = strlen(self->name);
1013 name = (char*)mem_a(len + 3);
1014 memcpy(name, self->name, len);
1016 name[len+1] = 'x' + member;
1022 if (self->vtype == TYPE_VECTOR)
1024 m = ir_value_var(name, self->store, TYPE_FLOAT);
1029 m->context = self->context;
1031 self->members[member] = m;
1032 m->code.addroffset = member;
1034 else if (self->vtype == TYPE_FIELD)
1036 if (self->fieldtype != TYPE_VECTOR)
1038 m = ir_value_var(name, self->store, TYPE_FIELD);
1043 m->fieldtype = TYPE_FLOAT;
1044 m->context = self->context;
1046 self->members[member] = m;
1047 m->code.addroffset = member;
1051 irerror(self->context, "invalid member access on %s", self->name);
1059 static GMQCC_INLINE size_t ir_value_sizeof(const ir_value *self)
1061 if (self->vtype == TYPE_FIELD && self->fieldtype == TYPE_VECTOR)
1062 return type_sizeof_[TYPE_VECTOR];
1063 return type_sizeof_[self->vtype];
1066 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
1068 ir_value *v = ir_value_var(name, storetype, vtype);
1071 ir_function_collect_value(owner, v);
1075 void ir_value_delete(ir_value* self)
1079 mem_d((void*)self->name);
1082 if (self->vtype == TYPE_STRING)
1083 mem_d((void*)self->constval.vstring);
1085 for (i = 0; i < 3; ++i) {
1086 if (self->members[i])
1087 ir_value_delete(self->members[i]);
1089 vec_free(self->reads);
1090 vec_free(self->writes);
1091 vec_free(self->life);
1095 bool ir_value_set_name(ir_value *self, const char *name)
1098 mem_d((void*)self->name);
1099 self->name = util_strdup(name);
1100 return !!self->name;
1103 bool ir_value_set_float(ir_value *self, float f)
1105 if (self->vtype != TYPE_FLOAT)
1107 self->constval.vfloat = f;
1108 self->hasvalue = true;
1112 bool ir_value_set_func(ir_value *self, int f)
1114 if (self->vtype != TYPE_FUNCTION)
1116 self->constval.vint = f;
1117 self->hasvalue = true;
1121 bool ir_value_set_vector(ir_value *self, vector v)
1123 if (self->vtype != TYPE_VECTOR)
1125 self->constval.vvec = v;
1126 self->hasvalue = true;
1130 bool ir_value_set_field(ir_value *self, ir_value *fld)
1132 if (self->vtype != TYPE_FIELD)
1134 self->constval.vpointer = fld;
1135 self->hasvalue = true;
1139 static char *ir_strdup(const char *str)
1142 /* actually dup empty strings */
1143 char *out = (char*)mem_a(1);
1147 return util_strdup(str);
1150 bool ir_value_set_string(ir_value *self, const char *str)
1152 if (self->vtype != TYPE_STRING)
1154 self->constval.vstring = ir_strdup(str);
1155 self->hasvalue = true;
1160 bool ir_value_set_int(ir_value *self, int i)
1162 if (self->vtype != TYPE_INTEGER)
1164 self->constval.vint = i;
1165 self->hasvalue = true;
1170 bool ir_value_lives(ir_value *self, size_t at)
1173 for (i = 0; i < vec_size(self->life); ++i)
1175 ir_life_entry_t *life = &self->life[i];
1176 if (life->start <= at && at <= life->end)
1178 if (life->start > at) /* since it's ordered */
1184 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
1187 vec_push(self->life, e);
1188 for (k = vec_size(self->life)-1; k > idx; --k)
1189 self->life[k] = self->life[k-1];
1190 self->life[idx] = e;
1194 bool ir_value_life_merge(ir_value *self, size_t s)
1197 ir_life_entry_t *life = NULL;
1198 ir_life_entry_t *before = NULL;
1199 ir_life_entry_t new_entry;
1201 /* Find the first range >= s */
1202 for (i = 0; i < vec_size(self->life); ++i)
1205 life = &self->life[i];
1206 if (life->start > s)
1209 /* nothing found? append */
1210 if (i == vec_size(self->life)) {
1212 if (life && life->end+1 == s)
1214 /* previous life range can be merged in */
1218 if (life && life->end >= s)
1220 e.start = e.end = s;
1221 vec_push(self->life, e);
1227 if (before->end + 1 == s &&
1228 life->start - 1 == s)
1231 before->end = life->end;
1232 vec_remove(self->life, i, 1);
1235 if (before->end + 1 == s)
1241 /* already contained */
1242 if (before->end >= s)
1246 if (life->start - 1 == s)
1251 /* insert a new entry */
1252 new_entry.start = new_entry.end = s;
1253 return ir_value_life_insert(self, i, new_entry);
1256 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1260 if (!vec_size(other->life))
1263 if (!vec_size(self->life)) {
1264 size_t count = vec_size(other->life);
1265 ir_life_entry_t *life = vec_add(self->life, count);
1266 memcpy(life, other->life, count * sizeof(*life));
1271 for (i = 0; i < vec_size(other->life); ++i)
1273 const ir_life_entry_t *life = &other->life[i];
1276 ir_life_entry_t *entry = &self->life[myi];
1278 if (life->end+1 < entry->start)
1280 /* adding an interval before entry */
1281 if (!ir_value_life_insert(self, myi, *life))
1287 if (life->start < entry->start &&
1288 life->end+1 >= entry->start)
1290 /* starts earlier and overlaps */
1291 entry->start = life->start;
1294 if (life->end > entry->end &&
1295 life->start <= entry->end+1)
1297 /* ends later and overlaps */
1298 entry->end = life->end;
1301 /* see if our change combines it with the next ranges */
1302 while (myi+1 < vec_size(self->life) &&
1303 entry->end+1 >= self->life[1+myi].start)
1305 /* overlaps with (myi+1) */
1306 if (entry->end < self->life[1+myi].end)
1307 entry->end = self->life[1+myi].end;
1308 vec_remove(self->life, myi+1, 1);
1309 entry = &self->life[myi];
1312 /* see if we're after the entry */
1313 if (life->start > entry->end)
1316 /* append if we're at the end */
1317 if (myi >= vec_size(self->life)) {
1318 vec_push(self->life, *life);
1321 /* otherweise check the next range */
1330 bool ir_values_overlap(const ir_value *a, const ir_value *b)
1332 /* For any life entry in A see if it overlaps with
1333 * any life entry in B.
1334 * Note that the life entries are orderes, so we can make a
1335 * more efficient algorithm there than naively translating the
1339 ir_life_entry_t *la, *lb, *enda, *endb;
1341 /* first of all, if either has no life range, they cannot clash */
1342 if (!vec_size(a->life) || !vec_size(b->life))
1347 enda = la + vec_size(a->life);
1348 endb = lb + vec_size(b->life);
1351 /* check if the entries overlap, for that,
1352 * both must start before the other one ends.
1354 if (la->start < lb->end &&
1355 lb->start < la->end)
1360 /* entries are ordered
1361 * one entry is earlier than the other
1362 * that earlier entry will be moved forward
1364 if (la->start < lb->start)
1366 /* order: A B, move A forward
1367 * check if we hit the end with A
1372 else /* if (lb->start < la->start) actually <= */
1374 /* order: B A, move B forward
1375 * check if we hit the end with B
1384 /***********************************************************************
1388 static bool ir_check_unreachable(ir_block *self)
1390 /* The IR should never have to deal with unreachable code */
1391 if (!self->final/* || OPTS_FLAG(ALLOW_UNREACHABLE_CODE)*/)
1393 irerror(self->context, "unreachable statement (%s)", self->label);
1397 bool ir_block_create_store_op(ir_block *self, lex_ctx ctx, int op, ir_value *target, ir_value *what)
1400 if (!ir_check_unreachable(self))
1403 if (target->store == store_value &&
1404 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1406 irerror(self->context, "cannot store to an SSA value");
1407 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1408 irerror(self->context, "instruction: %s", asm_instr[op].m);
1412 in = ir_instr_new(ctx, self, op);
1416 if (!ir_instr_op(in, 0, target, (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC)) ||
1417 !ir_instr_op(in, 1, what, false))
1419 ir_instr_delete(in);
1422 vec_push(self->instr, in);
1426 bool ir_block_create_store(ir_block *self, lex_ctx ctx, ir_value *target, ir_value *what)
1430 if (target->vtype == TYPE_VARIANT)
1431 vtype = what->vtype;
1433 vtype = target->vtype;
1436 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1437 op = INSTR_CONV_ITOF;
1438 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1439 op = INSTR_CONV_FTOI;
1441 op = type_store_instr[vtype];
1443 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1444 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1448 return ir_block_create_store_op(self, ctx, op, target, what);
1451 bool ir_block_create_storep(ir_block *self, lex_ctx ctx, ir_value *target, ir_value *what)
1456 if (target->vtype != TYPE_POINTER)
1459 /* storing using pointer - target is a pointer, type must be
1460 * inferred from source
1462 vtype = what->vtype;
1464 op = type_storep_instr[vtype];
1465 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1466 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1467 op = INSTR_STOREP_V;
1470 return ir_block_create_store_op(self, ctx, op, target, what);
1473 bool ir_block_create_return(ir_block *self, lex_ctx ctx, ir_value *v)
1476 if (!ir_check_unreachable(self))
1479 self->is_return = true;
1480 in = ir_instr_new(ctx, self, INSTR_RETURN);
1484 if (v && !ir_instr_op(in, 0, v, false)) {
1485 ir_instr_delete(in);
1489 vec_push(self->instr, in);
1493 bool ir_block_create_if(ir_block *self, lex_ctx ctx, ir_value *v,
1494 ir_block *ontrue, ir_block *onfalse)
1497 if (!ir_check_unreachable(self))
1500 /*in = ir_instr_new(ctx, self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1501 in = ir_instr_new(ctx, self, VINSTR_COND);
1505 if (!ir_instr_op(in, 0, v, false)) {
1506 ir_instr_delete(in);
1510 in->bops[0] = ontrue;
1511 in->bops[1] = onfalse;
1513 vec_push(self->instr, in);
1515 vec_push(self->exits, ontrue);
1516 vec_push(self->exits, onfalse);
1517 vec_push(ontrue->entries, self);
1518 vec_push(onfalse->entries, self);
1522 bool ir_block_create_jump(ir_block *self, lex_ctx ctx, ir_block *to)
1525 if (!ir_check_unreachable(self))
1528 in = ir_instr_new(ctx, self, VINSTR_JUMP);
1533 vec_push(self->instr, in);
1535 vec_push(self->exits, to);
1536 vec_push(to->entries, self);
1540 bool ir_block_create_goto(ir_block *self, lex_ctx ctx, ir_block *to)
1542 self->owner->flags |= IR_FLAG_HAS_GOTO;
1543 return ir_block_create_jump(self, ctx, to);
1546 ir_instr* ir_block_create_phi(ir_block *self, lex_ctx ctx, const char *label, int ot)
1550 if (!ir_check_unreachable(self))
1552 in = ir_instr_new(ctx, self, VINSTR_PHI);
1555 out = ir_value_out(self->owner, label, store_value, ot);
1557 ir_instr_delete(in);
1560 if (!ir_instr_op(in, 0, out, true)) {
1561 ir_instr_delete(in);
1562 ir_value_delete(out);
1565 vec_push(self->instr, in);
1569 ir_value* ir_phi_value(ir_instr *self)
1571 return self->_ops[0];
1574 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1578 if (!vec_ir_block_find(self->owner->entries, b, NULL)) {
1579 /* Must not be possible to cause this, otherwise the AST
1580 * is doing something wrong.
1582 irerror(self->context, "Invalid entry block for PHI");
1588 vec_push(v->reads, self);
1589 vec_push(self->phi, pe);
1592 /* call related code */
1593 ir_instr* ir_block_create_call(ir_block *self, lex_ctx ctx, const char *label, ir_value *func, bool noreturn)
1597 if (!ir_check_unreachable(self))
1599 in = ir_instr_new(ctx, self, (noreturn ? VINSTR_NRCALL : INSTR_CALL0));
1604 self->is_return = true;
1606 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1608 ir_instr_delete(in);
1611 if (!ir_instr_op(in, 0, out, true) ||
1612 !ir_instr_op(in, 1, func, false))
1614 ir_instr_delete(in);
1615 ir_value_delete(out);
1618 vec_push(self->instr, in);
1621 if (!ir_block_create_return(self, ctx, NULL)) {
1622 compile_error(ctx, "internal error: failed to generate dummy-return instruction");
1623 ir_instr_delete(in);
1631 ir_value* ir_call_value(ir_instr *self)
1633 return self->_ops[0];
1636 void ir_call_param(ir_instr* self, ir_value *v)
1638 vec_push(self->params, v);
1639 vec_push(v->reads, self);
1642 /* binary op related code */
1644 ir_value* ir_block_create_binop(ir_block *self, lex_ctx ctx,
1645 const char *label, int opcode,
1646 ir_value *left, ir_value *right)
1668 case INSTR_SUB_S: /* -- offset of string as float */
1673 case INSTR_BITOR_IF:
1674 case INSTR_BITOR_FI:
1675 case INSTR_BITAND_FI:
1676 case INSTR_BITAND_IF:
1691 case INSTR_BITAND_I:
1694 case INSTR_RSHIFT_I:
1695 case INSTR_LSHIFT_I:
1717 /* boolean operations result in floats */
1718 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1720 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1723 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1728 if (ot == TYPE_VOID) {
1729 /* The AST or parser were supposed to check this! */
1733 return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1736 ir_value* ir_block_create_unary(ir_block *self, lex_ctx ctx,
1737 const char *label, int opcode,
1740 int ot = TYPE_FLOAT;
1752 /* QC doesn't have other unary operations. We expect extensions to fill
1753 * the above list, otherwise we assume out-type = in-type, eg for an
1757 ot = operand->vtype;
1760 if (ot == TYPE_VOID) {
1761 /* The AST or parser were supposed to check this! */
1765 /* let's use the general instruction creator and pass NULL for OPB */
1766 return ir_block_create_general_instr(self, ctx, label, opcode, operand, NULL, ot);
1769 ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx ctx, const char *label,
1770 int op, ir_value *a, ir_value *b, int outype)
1775 out = ir_value_out(self->owner, label, store_value, outype);
1779 instr = ir_instr_new(ctx, self, op);
1781 ir_value_delete(out);
1785 if (!ir_instr_op(instr, 0, out, true) ||
1786 !ir_instr_op(instr, 1, a, false) ||
1787 !ir_instr_op(instr, 2, b, false) )
1792 vec_push(self->instr, instr);
1796 ir_instr_delete(instr);
1797 ir_value_delete(out);
1801 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx ctx, const char *label, ir_value *ent, ir_value *field)
1805 /* Support for various pointer types todo if so desired */
1806 if (ent->vtype != TYPE_ENTITY)
1809 if (field->vtype != TYPE_FIELD)
1812 v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1813 v->fieldtype = field->fieldtype;
1817 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)
1820 if (ent->vtype != TYPE_ENTITY)
1823 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1824 if (field->vtype != TYPE_FIELD)
1829 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1830 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1831 case TYPE_STRING: op = INSTR_LOAD_S; break;
1832 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1833 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1834 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1836 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1837 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1840 irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1844 return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
1847 /* PHI resolving breaks the SSA, and must thus be the last
1848 * step before life-range calculation.
1851 static bool ir_block_naive_phi(ir_block *self);
1852 bool ir_function_naive_phi(ir_function *self)
1856 for (i = 0; i < vec_size(self->blocks); ++i)
1858 if (!ir_block_naive_phi(self->blocks[i]))
1865 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1870 /* create a store */
1871 if (!ir_block_create_store(block, old, what))
1874 /* we now move it up */
1875 instr = vec_last(block->instr);
1876 for (i = vec_size(block->instr)-1; i > iid; --i)
1877 block->instr[i] = block->instr[i-1];
1878 block->instr[i] = instr;
1884 static bool ir_block_naive_phi(ir_block *self)
1886 size_t i, p; /*, w;*/
1887 /* FIXME: optionally, create_phi can add the phis
1888 * to a list so we don't need to loop through blocks
1889 * - anyway: "don't optimize YET"
1891 for (i = 0; i < vec_size(self->instr); ++i)
1893 ir_instr *instr = self->instr[i];
1894 if (instr->opcode != VINSTR_PHI)
1897 vec_remove(self->instr, i, 1);
1898 --i; /* NOTE: i+1 below */
1900 for (p = 0; p < vec_size(instr->phi); ++p)
1902 ir_value *v = instr->phi[p].value;
1903 ir_block *b = instr->phi[p].from;
1905 if (v->store == store_value &&
1906 vec_size(v->reads) == 1 &&
1907 vec_size(v->writes) == 1)
1909 /* replace the value */
1910 if (!ir_instr_op(v->writes[0], 0, instr->_ops[0], true))
1915 /* force a move instruction */
1916 ir_instr *prevjump = vec_last(b->instr);
1919 instr->_ops[0]->store = store_global;
1920 if (!ir_block_create_store(b, instr->context, instr->_ops[0], v))
1922 instr->_ops[0]->store = store_value;
1923 vec_push(b->instr, prevjump);
1928 ir_value *v = instr->phi[p].value;
1929 for (w = 0; w < vec_size(v->writes); ++w) {
1932 if (!v->writes[w]->_ops[0])
1935 /* When the write was to a global, we have to emit a mov */
1936 old = v->writes[w]->_ops[0];
1938 /* The original instruction now writes to the PHI target local */
1939 if (v->writes[w]->_ops[0] == v)
1940 v->writes[w]->_ops[0] = instr->_ops[0];
1942 if (old->store != store_value && old->store != store_local && old->store != store_param)
1944 /* If it originally wrote to a global we need to store the value
1947 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1949 if (i+1 < vec_size(self->instr))
1950 instr = self->instr[i+1];
1953 /* In case I forget and access instr later, it'll be NULL
1954 * when it's a problem, to make sure we crash, rather than accessing
1960 /* If it didn't, we can replace all reads by the phi target now. */
1962 for (r = 0; r < vec_size(old->reads); ++r)
1965 ir_instr *ri = old->reads[r];
1966 for (op = 0; op < vec_size(ri->phi); ++op) {
1967 if (ri->phi[op].value == old)
1968 ri->phi[op].value = v;
1970 for (op = 0; op < 3; ++op) {
1971 if (ri->_ops[op] == old)
1979 ir_instr_delete(instr);
1984 /***********************************************************************
1985 *IR Temp allocation code
1986 * Propagating value life ranges by walking through the function backwards
1987 * until no more changes are made.
1988 * In theory this should happen once more than once for every nested loop
1990 * Though this implementation might run an additional time for if nests.
1993 /* Enumerate instructions used by value's life-ranges
1995 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1999 for (i = 0; i < vec_size(self->instr); ++i)
2001 self->instr[i]->eid = eid++;
2006 /* Enumerate blocks and instructions.
2007 * The block-enumeration is unordered!
2008 * We do not really use the block enumreation, however
2009 * the instruction enumeration is important for life-ranges.
2011 void ir_function_enumerate(ir_function *self)
2014 size_t instruction_id = 1;
2015 for (i = 0; i < vec_size(self->blocks); ++i)
2017 self->blocks[i]->eid = i;
2018 self->blocks[i]->run_id = 0;
2019 ir_block_enumerate(self->blocks[i], &instruction_id);
2023 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
2024 bool ir_function_calculate_liferanges(ir_function *self)
2029 /* parameters live at 0 */
2030 for (i = 0; i < vec_size(self->params); ++i)
2031 ir_value_life_merge(self->locals[i], 0);
2036 for (i = 0; i != vec_size(self->blocks); ++i)
2038 if (self->blocks[i]->is_return)
2040 vec_free(self->blocks[i]->living);
2041 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
2046 if (vec_size(self->blocks)) {
2047 ir_block *block = self->blocks[0];
2048 for (i = 0; i < vec_size(block->living); ++i) {
2049 ir_value *v = block->living[i];
2050 if (v->store != store_local)
2052 if (v->vtype == TYPE_VECTOR)
2054 self->flags |= IR_FLAG_HAS_UNINITIALIZED;
2055 /* find the instruction reading from it */
2056 for (s = 0; s < vec_size(v->reads); ++s) {
2057 if (v->reads[s]->eid == v->life[0].end)
2060 if (s < vec_size(v->reads)) {
2061 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2062 "variable `%s` may be used uninitialized in this function\n"
2065 v->reads[s]->context.file, v->reads[s]->context.line)
2073 ir_value *vec = v->memberof;
2074 for (s = 0; s < vec_size(vec->reads); ++s) {
2075 if (vec->reads[s]->eid == v->life[0].end)
2078 if (s < vec_size(vec->reads)) {
2079 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2080 "variable `%s` may be used uninitialized in this function\n"
2083 vec->reads[s]->context.file, vec->reads[s]->context.line)
2091 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2092 "variable `%s` may be used uninitialized in this function", v->name))
2101 /* Local-value allocator
2102 * After finishing creating the liferange of all values used in a function
2103 * we can allocate their global-positions.
2104 * This is the counterpart to register-allocation in register machines.
2111 } function_allocator;
2113 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
2116 size_t vsize = ir_value_sizeof(var);
2118 slot = ir_value_var("reg", store_global, var->vtype);
2122 if (!ir_value_life_merge_into(slot, var))
2125 vec_push(alloc->locals, slot);
2126 vec_push(alloc->sizes, vsize);
2127 vec_push(alloc->unique, var->unique_life);
2132 ir_value_delete(slot);
2136 bool ir_function_allocate_locals(ir_function *self)
2145 function_allocator alloc;
2147 if (!vec_size(self->locals) && !vec_size(self->values))
2150 alloc.locals = NULL;
2152 alloc.positions = NULL;
2153 alloc.unique = NULL;
2155 for (i = 0; i < vec_size(self->locals); ++i)
2157 if (!OPTS_OPTIMIZATION(OPTIM_LOCAL_TEMPS))
2158 self->locals[i]->unique_life = true;
2159 if (!function_allocator_alloc(&alloc, self->locals[i]))
2163 /* Allocate a slot for any value that still exists */
2164 for (i = 0; i < vec_size(self->values); ++i)
2166 v = self->values[i];
2168 if (!vec_size(v->life))
2171 /* CALL optimization:
2172 * If the value is a parameter-temp: 1 write, 1 read from a CALL
2173 * and it's not "locked", write it to the OFS_PARM directly.
2175 if (OPTS_OPTIMIZATION(OPTIM_CALL_STORES)) {
2176 if (!v->locked && vec_size(v->reads) == 1 && vec_size(v->writes) == 1 &&
2177 (v->reads[0]->opcode == VINSTR_NRCALL ||
2178 (v->reads[0]->opcode >= INSTR_CALL0 && v->reads[0]->opcode <= INSTR_CALL8)
2183 ir_instr *call = v->reads[0];
2184 if (!vec_ir_value_find(call->params, v, ¶m)) {
2185 irerror(call->context, "internal error: unlocked parameter %s not found", v->name);
2189 v->callparam = true;
2191 ir_value_code_setaddr(v, OFS_PARM0 + 3*param);
2195 if (vec_size(self->owner->extparam_protos) <= param)
2196 ep = ir_gen_extparam_proto(self->owner);
2198 ep = self->owner->extparam_protos[param];
2199 ir_instr_op(v->writes[0], 0, ep, true);
2200 call->params[param+8] = ep;
2206 for (a = 0; a < vec_size(alloc.locals); ++a)
2208 /* if it's reserved for a unique liferange: skip */
2209 if (alloc.unique[a])
2212 slot = alloc.locals[a];
2214 /* never resize parameters
2215 * will be required later when overlapping temps + locals
2217 if (a < vec_size(self->params) &&
2218 alloc.sizes[a] < ir_value_sizeof(v))
2223 if (ir_values_overlap(v, slot))
2226 if (!ir_value_life_merge_into(slot, v))
2229 /* adjust size for this slot */
2230 if (alloc.sizes[a] < ir_value_sizeof(v))
2231 alloc.sizes[a] = ir_value_sizeof(v);
2233 self->values[i]->code.local = a;
2236 if (a >= vec_size(alloc.locals)) {
2237 self->values[i]->code.local = vec_size(alloc.locals);
2238 if (!function_allocator_alloc(&alloc, v))
2247 /* Adjust slot positions based on sizes */
2248 vec_push(alloc.positions, 0);
2250 if (vec_size(alloc.sizes))
2251 pos = alloc.positions[0] + alloc.sizes[0];
2254 for (i = 1; i < vec_size(alloc.sizes); ++i)
2256 pos = alloc.positions[i-1] + alloc.sizes[i-1];
2257 vec_push(alloc.positions, pos);
2260 self->allocated_locals = pos + vec_last(alloc.sizes);
2262 /* Locals need to know their new position */
2263 for (i = 0; i < vec_size(self->locals); ++i) {
2264 self->locals[i]->code.local = alloc.positions[i];
2266 /* Take over the actual slot positions on values */
2267 for (i = 0; i < vec_size(self->values); ++i) {
2268 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
2276 for (i = 0; i < vec_size(alloc.locals); ++i)
2277 ir_value_delete(alloc.locals[i]);
2278 vec_free(alloc.unique);
2279 vec_free(alloc.locals);
2280 vec_free(alloc.sizes);
2281 vec_free(alloc.positions);
2285 /* Get information about which operand
2286 * is read from, or written to.
2288 static void ir_op_read_write(int op, size_t *read, size_t *write)
2308 case INSTR_STOREP_F:
2309 case INSTR_STOREP_V:
2310 case INSTR_STOREP_S:
2311 case INSTR_STOREP_ENT:
2312 case INSTR_STOREP_FLD:
2313 case INSTR_STOREP_FNC:
2324 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2327 bool changed = false;
2329 for (i = 0; i != vec_size(self->living); ++i)
2331 tempbool = ir_value_life_merge(self->living[i], eid);
2332 changed = changed || tempbool;
2337 static bool ir_block_living_lock(ir_block *self)
2340 bool changed = false;
2341 for (i = 0; i != vec_size(self->living); ++i)
2343 if (!self->living[i]->locked)
2345 self->living[i]->locked = true;
2350 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
2356 /* values which have been read in a previous iteration are now
2357 * in the "living" array even if the previous block doesn't use them.
2358 * So we have to remove whatever does not exist in the previous block.
2359 * They will be re-added on-read, but the liferange merge won't cause
2361 for (i = 0; i < vec_size(self->living); ++i)
2363 if (!vec_ir_value_find(prev->living, self->living[i], NULL)) {
2364 vec_remove(self->living, i, 1);
2370 /* Whatever the previous block still has in its living set
2371 * must now be added to ours as well.
2373 for (i = 0; i < vec_size(prev->living); ++i)
2375 if (vec_ir_value_find(self->living, prev->living[i], NULL))
2377 vec_push(self->living, prev->living[i]);
2379 irerror(self->contextt from prev: %s", self->label, prev->living[i]->_name);
2385 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2390 size_t i, o, p, mem;
2391 /* bitmasks which operands are read from or written to */
2393 char dbg_ind[16] = { '#', '0' };
2398 if (!ir_block_life_prop_previous(self, prev, changed))
2402 i = vec_size(self->instr);
2405 instr = self->instr[i];
2407 /* See which operands are read and write operands */
2408 ir_op_read_write(instr->opcode, &read, &write);
2410 if (instr->opcode == INSTR_MUL_VF)
2412 /* the float source will get an additional lifetime */
2413 tempbool = ir_value_life_merge(instr->_ops[2], instr->eid+1);
2414 *changed = *changed || tempbool;
2416 else if (instr->opcode == INSTR_MUL_FV)
2418 /* the float source will get an additional lifetime */
2419 tempbool = ir_value_life_merge(instr->_ops[1], instr->eid+1);
2420 *changed = *changed || tempbool;
2423 /* Go through the 3 main operands
2424 * writes first, then reads
2426 for (o = 0; o < 3; ++o)
2428 if (!instr->_ops[o]) /* no such operand */
2431 value = instr->_ops[o];
2433 /* We only care about locals */
2434 /* we also calculate parameter liferanges so that locals
2435 * can take up parameter slots */
2436 if (value->store != store_value &&
2437 value->store != store_local &&
2438 value->store != store_param)
2441 /* write operands */
2442 /* When we write to a local, we consider it "dead" for the
2443 * remaining upper part of the function, since in SSA a value
2444 * can only be written once (== created)
2449 bool in_living = vec_ir_value_find(self->living, value, &idx);
2452 /* If the value isn't alive it hasn't been read before... */
2453 /* TODO: See if the warning can be emitted during parsing or AST processing
2454 * otherwise have warning printed here.
2455 * IF printing a warning here: include filecontext_t,
2456 * and make sure it's only printed once
2457 * since this function is run multiple times.
2459 /* con_err( "Value only written %s\n", value->name); */
2460 tempbool = ir_value_life_merge(value, instr->eid);
2461 *changed = *changed || tempbool;
2463 /* since 'living' won't contain it
2464 * anymore, merge the value, since
2467 tempbool = ir_value_life_merge(value, instr->eid);
2468 *changed = *changed || tempbool;
2470 vec_remove(self->living, idx, 1);
2472 /* Removing a vector removes all members */
2473 for (mem = 0; mem < 3; ++mem) {
2474 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], &idx)) {
2475 tempbool = ir_value_life_merge(value->members[mem], instr->eid);
2476 *changed = *changed || tempbool;
2477 vec_remove(self->living, idx, 1);
2480 /* Removing the last member removes the vector */
2481 if (value->memberof) {
2482 value = value->memberof;
2483 for (mem = 0; mem < 3; ++mem) {
2484 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], NULL))
2487 if (mem == 3 && vec_ir_value_find(self->living, value, &idx)) {
2488 tempbool = ir_value_life_merge(value, instr->eid);
2489 *changed = *changed || tempbool;
2490 vec_remove(self->living, idx, 1);
2496 for (o = 0; o < 3; ++o)
2498 if (!instr->_ops[o]) /* no such operand */
2501 value = instr->_ops[o];
2503 /* We only care about locals */
2504 /* we also calculate parameter liferanges so that locals
2505 * can take up parameter slots */
2506 if (value->store != store_value &&
2507 value->store != store_local &&
2508 value->store != store_param)
2514 if (!vec_ir_value_find(self->living, value, NULL))
2515 vec_push(self->living, value);
2516 /* reading adds the full vector */
2517 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2518 vec_push(self->living, value->memberof);
2519 for (mem = 0; mem < 3; ++mem) {
2520 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2521 vec_push(self->living, value->members[mem]);
2525 /* PHI operands are always read operands */
2526 for (p = 0; p < vec_size(instr->phi); ++p)
2528 value = instr->phi[p].value;
2529 if (!vec_ir_value_find(self->living, value, NULL))
2530 vec_push(self->living, value);
2531 /* reading adds the full vector */
2532 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2533 vec_push(self->living, value->memberof);
2534 for (mem = 0; mem < 3; ++mem) {
2535 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2536 vec_push(self->living, value->members[mem]);
2540 /* on a call, all these values must be "locked" */
2541 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2542 if (ir_block_living_lock(self))
2545 /* call params are read operands too */
2546 for (p = 0; p < vec_size(instr->params); ++p)
2548 value = instr->params[p];
2549 if (!vec_ir_value_find(self->living, value, NULL))
2550 vec_push(self->living, value);
2551 /* reading adds the full vector */
2552 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2553 vec_push(self->living, value->memberof);
2554 for (mem = 0; mem < 3; ++mem) {
2555 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2556 vec_push(self->living, value->members[mem]);
2561 tempbool = ir_block_living_add_instr(self, instr->eid);
2562 /*con_err( "living added values\n");*/
2563 *changed = *changed || tempbool;
2567 if (self->run_id == self->owner->run_id)
2570 self->run_id = self->owner->run_id;
2572 for (i = 0; i < vec_size(self->entries); ++i)
2574 ir_block *entry = self->entries[i];
2575 ir_block_life_propagate(entry, self, changed);
2581 /***********************************************************************
2584 * Since the IR has the convention of putting 'write' operands
2585 * at the beginning, we have to rotate the operands of instructions
2586 * properly in order to generate valid QCVM code.
2588 * Having destinations at a fixed position is more convenient. In QC
2589 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2590 * read from from OPA, and store to OPB rather than OPC. Which is
2591 * partially the reason why the implementation of these instructions
2592 * in darkplaces has been delayed for so long.
2594 * Breaking conventions is annoying...
2596 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal, bool defs_only);
2598 static bool gen_global_field(ir_value *global)
2600 if (global->hasvalue)
2602 ir_value *fld = global->constval.vpointer;
2604 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2608 /* copy the field's value */
2609 ir_value_code_setaddr(global, vec_size(code_globals));
2610 vec_push(code_globals, fld->code.fieldaddr);
2611 if (global->fieldtype == TYPE_VECTOR) {
2612 vec_push(code_globals, fld->code.fieldaddr+1);
2613 vec_push(code_globals, fld->code.fieldaddr+2);
2618 ir_value_code_setaddr(global, vec_size(code_globals));
2619 vec_push(code_globals, 0);
2620 if (global->fieldtype == TYPE_VECTOR) {
2621 vec_push(code_globals, 0);
2622 vec_push(code_globals, 0);
2625 if (global->code.globaladdr < 0)
2630 static bool gen_global_pointer(ir_value *global)
2632 if (global->hasvalue)
2634 ir_value *target = global->constval.vpointer;
2636 irerror(global->context, "Invalid pointer constant: %s", global->name);
2637 /* NULL pointers are pointing to the NULL constant, which also
2638 * sits at address 0, but still has an ir_value for itself.
2643 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2644 * void() foo; <- proto
2645 * void() *fooptr = &foo;
2646 * void() foo = { code }
2648 if (!target->code.globaladdr) {
2649 /* FIXME: Check for the constant nullptr ir_value!
2650 * because then code.globaladdr being 0 is valid.
2652 irerror(global->context, "FIXME: Relocation support");
2656 ir_value_code_setaddr(global, vec_size(code_globals));
2657 vec_push(code_globals, target->code.globaladdr);
2661 ir_value_code_setaddr(global, vec_size(code_globals));
2662 vec_push(code_globals, 0);
2664 if (global->code.globaladdr < 0)
2669 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2671 prog_section_statement stmt;
2680 block->generated = true;
2681 block->code_start = vec_size(code_statements);
2682 for (i = 0; i < vec_size(block->instr); ++i)
2684 instr = block->instr[i];
2686 if (instr->opcode == VINSTR_PHI) {
2687 irerror(block->context, "cannot generate virtual instruction (phi)");
2691 if (instr->opcode == VINSTR_JUMP) {
2692 target = instr->bops[0];
2693 /* for uncoditional jumps, if the target hasn't been generated
2694 * yet, we generate them right here.
2696 if (!target->generated) {
2701 /* otherwise we generate a jump instruction */
2702 stmt.opcode = INSTR_GOTO;
2703 stmt.o1.s1 = (target->code_start) - vec_size(code_statements);
2706 if (stmt.o1.s1 != 1)
2707 code_push_statement(&stmt, instr->context.line);
2709 /* no further instructions can be in this block */
2713 if (instr->opcode == VINSTR_COND) {
2714 ontrue = instr->bops[0];
2715 onfalse = instr->bops[1];
2716 /* TODO: have the AST signal which block should
2717 * come first: eg. optimize IFs without ELSE...
2720 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2724 if (ontrue->generated) {
2725 stmt.opcode = INSTR_IF;
2726 stmt.o2.s1 = (ontrue->code_start) - vec_size(code_statements);
2727 if (stmt.o2.s1 != 1)
2728 code_push_statement(&stmt, instr->context.line);
2730 if (onfalse->generated) {
2731 stmt.opcode = INSTR_IFNOT;
2732 stmt.o2.s1 = (onfalse->code_start) - vec_size(code_statements);
2733 if (stmt.o2.s1 != 1)
2734 code_push_statement(&stmt, instr->context.line);
2736 if (!ontrue->generated) {
2737 if (onfalse->generated) {
2742 if (!onfalse->generated) {
2743 if (ontrue->generated) {
2748 /* neither ontrue nor onfalse exist */
2749 stmt.opcode = INSTR_IFNOT;
2750 if (!instr->likely) {
2751 /* Honor the likelyhood hint */
2752 ir_block *tmp = onfalse;
2753 stmt.opcode = INSTR_IF;
2757 stidx = vec_size(code_statements);
2758 code_push_statement(&stmt, instr->context.line);
2759 /* on false we jump, so add ontrue-path */
2760 if (!gen_blocks_recursive(func, ontrue))
2762 /* fixup the jump address */
2763 code_statements[stidx].o2.s1 = vec_size(code_statements) - stidx;
2764 /* generate onfalse path */
2765 if (onfalse->generated) {
2766 /* fixup the jump address */
2767 code_statements[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2768 if (code_statements[stidx].o2.s1 == 1) {
2769 code_statements[stidx] = code_statements[stidx+1];
2770 if (code_statements[stidx].o1.s1 < 0)
2771 code_statements[stidx].o1.s1++;
2772 code_pop_statement();
2774 stmt.opcode = vec_last(code_statements).opcode;
2775 if (stmt.opcode == INSTR_GOTO ||
2776 stmt.opcode == INSTR_IF ||
2777 stmt.opcode == INSTR_IFNOT ||
2778 stmt.opcode == INSTR_RETURN ||
2779 stmt.opcode == INSTR_DONE)
2781 /* no use jumping from here */
2784 /* may have been generated in the previous recursive call */
2785 stmt.opcode = INSTR_GOTO;
2786 stmt.o1.s1 = (onfalse->code_start) - vec_size(code_statements);
2789 if (stmt.o1.s1 != 1)
2790 code_push_statement(&stmt, instr->context.line);
2793 else if (code_statements[stidx].o2.s1 == 1) {
2794 code_statements[stidx] = code_statements[stidx+1];
2795 if (code_statements[stidx].o1.s1 < 0)
2796 code_statements[stidx].o1.s1++;
2797 code_pop_statement();
2799 /* if not, generate now */
2804 if ( (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8)
2805 || instr->opcode == VINSTR_NRCALL)
2810 first = vec_size(instr->params);
2813 for (p = 0; p < first; ++p)
2815 ir_value *param = instr->params[p];
2816 if (param->callparam)
2819 stmt.opcode = INSTR_STORE_F;
2822 if (param->vtype == TYPE_FIELD)
2823 stmt.opcode = field_store_instr[param->fieldtype];
2825 stmt.opcode = type_store_instr[param->vtype];
2826 stmt.o1.u1 = ir_value_code_addr(param);
2827 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2828 code_push_statement(&stmt, instr->context.line);
2830 /* Now handle extparams */
2831 first = vec_size(instr->params);
2832 for (; p < first; ++p)
2834 ir_builder *ir = func->owner;
2835 ir_value *param = instr->params[p];
2836 ir_value *targetparam;
2838 if (param->callparam)
2841 if (p-8 >= vec_size(ir->extparams))
2842 ir_gen_extparam(ir);
2844 targetparam = ir->extparams[p-8];
2846 stmt.opcode = INSTR_STORE_F;
2849 if (param->vtype == TYPE_FIELD)
2850 stmt.opcode = field_store_instr[param->fieldtype];
2852 stmt.opcode = type_store_instr[param->vtype];
2853 stmt.o1.u1 = ir_value_code_addr(param);
2854 stmt.o2.u1 = ir_value_code_addr(targetparam);
2855 code_push_statement(&stmt, instr->context.line);
2858 stmt.opcode = INSTR_CALL0 + vec_size(instr->params);
2859 if (stmt.opcode > INSTR_CALL8)
2860 stmt.opcode = INSTR_CALL8;
2861 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2864 code_push_statement(&stmt, instr->context.line);
2866 retvalue = instr->_ops[0];
2867 if (retvalue && retvalue->store != store_return &&
2868 (retvalue->store == store_global || vec_size(retvalue->life)))
2870 /* not to be kept in OFS_RETURN */
2871 if (retvalue->vtype == TYPE_FIELD && OPTS_FLAG(ADJUST_VECTOR_FIELDS))
2872 stmt.opcode = field_store_instr[retvalue->fieldtype];
2874 stmt.opcode = type_store_instr[retvalue->vtype];
2875 stmt.o1.u1 = OFS_RETURN;
2876 stmt.o2.u1 = ir_value_code_addr(retvalue);
2878 code_push_statement(&stmt, instr->context.line);
2883 if (instr->opcode == INSTR_STATE) {
2884 irerror(block->context, "TODO: state instruction");
2888 stmt.opcode = instr->opcode;
2893 /* This is the general order of operands */
2895 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2898 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2901 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2903 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2905 stmt.o1.u1 = stmt.o3.u1;
2908 else if ((stmt.opcode >= INSTR_STORE_F &&
2909 stmt.opcode <= INSTR_STORE_FNC) ||
2910 (stmt.opcode >= INSTR_STOREP_F &&
2911 stmt.opcode <= INSTR_STOREP_FNC))
2913 /* 2-operand instructions with A -> B */
2914 stmt.o2.u1 = stmt.o3.u1;
2917 /* tiny optimization, don't output
2920 if (stmt.o2.u1 == stmt.o1.u1 &&
2921 OPTS_OPTIMIZATION(OPTIM_PEEPHOLE))
2923 ++opts_optimizationcount[OPTIM_PEEPHOLE];
2928 code_push_statement(&stmt, instr->context.line);
2933 static bool gen_function_code(ir_function *self)
2936 prog_section_statement stmt;
2938 /* Starting from entry point, we generate blocks "as they come"
2939 * for now. Dead blocks will not be translated obviously.
2941 if (!vec_size(self->blocks)) {
2942 irerror(self->context, "Function '%s' declared without body.", self->name);
2946 block = self->blocks[0];
2947 if (block->generated)
2950 if (!gen_blocks_recursive(self, block)) {
2951 irerror(self->context, "failed to generate blocks for '%s'", self->name);
2955 /* code_write and qcvm -disasm need to know that the function ends here */
2956 stmt.opcode = INSTR_DONE;
2960 code_push_statement(&stmt, vec_last(code_linenums));
2964 static qcint ir_builder_filestring(ir_builder *ir, const char *filename)
2966 /* NOTE: filename pointers are copied, we never strdup them,
2967 * thus we can use pointer-comparison to find the string.
2972 for (i = 0; i < vec_size(ir->filenames); ++i) {
2973 if (ir->filenames[i] == filename)
2974 return ir->filestrings[i];
2977 str = code_genstring(filename);
2978 vec_push(ir->filenames, filename);
2979 vec_push(ir->filestrings, str);
2983 static bool gen_global_function(ir_builder *ir, ir_value *global)
2985 prog_section_function fun;
2990 if (!global->hasvalue || (!global->constval.vfunc))
2992 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
2996 irfun = global->constval.vfunc;
2998 fun.name = global->code.name;
2999 fun.file = ir_builder_filestring(ir, global->context.file);
3000 fun.profile = 0; /* always 0 */
3001 fun.nargs = vec_size(irfun->params);
3005 for (i = 0;i < 8; ++i) {
3006 if ((int32_t)i >= fun.nargs)
3009 fun.argsize[i] = type_sizeof_[irfun->params[i]];
3013 fun.locals = irfun->allocated_locals;
3016 fun.entry = irfun->builtin+1;
3018 irfun->code_function_def = vec_size(code_functions);
3019 fun.entry = vec_size(code_statements);
3022 vec_push(code_functions, fun);
3026 static ir_value* ir_gen_extparam_proto(ir_builder *ir)
3031 snprintf(name, sizeof(name), "EXTPARM#%i", (int)(vec_size(ir->extparam_protos)+8));
3032 global = ir_value_var(name, store_global, TYPE_VECTOR);
3034 vec_push(ir->extparam_protos, global);
3038 static void ir_gen_extparam(ir_builder *ir)
3040 prog_section_def def;
3043 if (vec_size(ir->extparam_protos) < vec_size(ir->extparams)+1)
3044 global = ir_gen_extparam_proto(ir);
3046 global = ir->extparam_protos[vec_size(ir->extparams)];
3048 def.name = code_genstring(global->name);
3049 def.type = TYPE_VECTOR;
3050 def.offset = vec_size(code_globals);
3052 vec_push(code_defs, def);
3053 ir_value_code_setaddr(global, def.offset);
3054 vec_push(code_globals, 0);
3055 vec_push(code_globals, 0);
3056 vec_push(code_globals, 0);
3058 vec_push(ir->extparams, global);
3061 static bool gen_function_extparam_copy(ir_function *self)
3063 size_t i, ext, numparams;
3065 ir_builder *ir = self->owner;
3067 prog_section_statement stmt;
3069 numparams = vec_size(self->params);
3073 stmt.opcode = INSTR_STORE_F;
3075 for (i = 8; i < numparams; ++i) {
3077 if (ext >= vec_size(ir->extparams))
3078 ir_gen_extparam(ir);
3080 ep = ir->extparams[ext];
3082 stmt.opcode = type_store_instr[self->locals[i]->vtype];
3083 if (self->locals[i]->vtype == TYPE_FIELD &&
3084 self->locals[i]->fieldtype == TYPE_VECTOR)
3086 stmt.opcode = INSTR_STORE_V;
3088 stmt.o1.u1 = ir_value_code_addr(ep);
3089 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3090 code_push_statement(&stmt, self->context.line);
3096 static bool gen_function_locals(ir_builder *ir, ir_value *global)
3098 prog_section_function *def;
3101 uint32_t firstlocal;
3103 irfun = global->constval.vfunc;
3104 def = code_functions + irfun->code_function_def;
3106 if (opts.g || !OPTS_OPTIMIZATION(OPTIM_OVERLAP_LOCALS) || (irfun->flags & IR_FLAG_MASK_NO_OVERLAP))
3107 firstlocal = def->firstlocal = vec_size(code_globals);
3109 firstlocal = def->firstlocal = ir->first_common_local;
3110 ++opts_optimizationcount[OPTIM_OVERLAP_LOCALS];
3113 for (i = vec_size(code_globals); i < firstlocal + irfun->allocated_locals; ++i)
3114 vec_push(code_globals, 0);
3115 for (i = 0; i < vec_size(irfun->locals); ++i) {
3116 ir_value_code_setaddr(irfun->locals[i], firstlocal + irfun->locals[i]->code.local);
3117 if (!ir_builder_gen_global(ir, irfun->locals[i], true, true)) {
3118 irerror(irfun->locals[i]->context, "failed to generate local %s", irfun->locals[i]->name);
3122 for (i = 0; i < vec_size(irfun->values); ++i)
3124 ir_value *v = irfun->values[i];
3127 ir_value_code_setaddr(v, firstlocal + v->code.local);
3132 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
3134 prog_section_function *fundef;
3139 irfun = global->constval.vfunc;
3141 if (global->cvq == CV_NONE) {
3142 irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
3143 "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
3145 /* this was a function pointer, don't generate code for those */
3152 if (irfun->code_function_def < 0) {
3153 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
3156 fundef = &code_functions[irfun->code_function_def];
3158 fundef->entry = vec_size(code_statements);
3159 if (!gen_function_locals(ir, global)) {
3160 irerror(irfun->context, "Failed to generate locals for function %s", irfun->name);
3163 if (!gen_function_extparam_copy(irfun)) {
3164 irerror(irfun->context, "Failed to generate extparam-copy code for function %s", irfun->name);
3167 if (!gen_function_code(irfun)) {
3168 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
3174 static void gen_vector_defs(prog_section_def def, const char *name)
3179 if (!name || name[0] == '#' || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3182 def.type = TYPE_FLOAT;
3186 component = (char*)mem_a(len+3);
3187 memcpy(component, name, len);
3189 component[len-0] = 0;
3190 component[len-2] = '_';
3192 component[len-1] = 'x';
3194 for (i = 0; i < 3; ++i) {
3195 def.name = code_genstring(component);
3196 vec_push(code_defs, def);
3202 static void gen_vector_fields(prog_section_field fld, const char *name)
3207 if (!name || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3210 fld.type = TYPE_FLOAT;
3214 component = (char*)mem_a(len+3);
3215 memcpy(component, name, len);
3217 component[len-0] = 0;
3218 component[len-2] = '_';
3220 component[len-1] = 'x';
3222 for (i = 0; i < 3; ++i) {
3223 fld.name = code_genstring(component);
3224 vec_push(code_fields, fld);
3230 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal, bool defs_only)
3234 prog_section_def def;
3235 bool pushdef = false;
3237 if (opts.g || !islocal)
3240 def.type = global->vtype;
3241 def.offset = vec_size(code_globals);
3243 if (OPTS_OPTIMIZATION(OPTIM_STRIP_CONSTANT_NAMES) &&
3244 (global->name[0] == '#' || global->cvq == CV_CONST))
3249 if (pushdef && global->name) {
3250 if (global->name[0] == '#') {
3251 if (!self->str_immediate)
3252 self->str_immediate = code_genstring("IMMEDIATE");
3253 def.name = global->code.name = self->str_immediate;
3256 def.name = global->code.name = code_genstring(global->name);
3261 def.offset = ir_value_code_addr(global);
3262 vec_push(code_defs, def);
3263 if (global->vtype == TYPE_VECTOR)
3264 gen_vector_defs(def, global->name);
3265 else if (global->vtype == TYPE_FIELD && global->fieldtype == TYPE_VECTOR)
3266 gen_vector_defs(def, global->name);
3273 switch (global->vtype)
3276 if (!strcmp(global->name, "end_sys_globals")) {
3277 /* TODO: remember this point... all the defs before this one
3278 * should be checksummed and added to progdefs.h when we generate it.
3281 else if (!strcmp(global->name, "end_sys_fields")) {
3282 /* TODO: same as above but for entity-fields rather than globsl
3286 irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3288 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3289 * the system fields actually go? Though the engine knows this anyway...
3290 * Maybe this could be an -foption
3291 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3293 ir_value_code_setaddr(global, vec_size(code_globals));
3294 vec_push(code_globals, 0);
3296 if (pushdef) vec_push(code_defs, def);
3299 if (pushdef) vec_push(code_defs, def);
3300 return gen_global_pointer(global);
3303 vec_push(code_defs, def);
3304 if (global->fieldtype == TYPE_VECTOR) {
3305 gen_vector_defs(def, global->name);
3306 ir_value_vector_member(global, 0);
3307 ir_value_vector_member(global, 1);
3308 ir_value_vector_member(global, 2);
3311 return gen_global_field(global);
3316 ir_value_code_setaddr(global, vec_size(code_globals));
3317 if (global->hasvalue) {
3318 iptr = (int32_t*)&global->constval.ivec[0];
3319 vec_push(code_globals, *iptr);
3321 vec_push(code_globals, 0);
3323 if (!islocal && global->cvq != CV_CONST)
3324 def.type |= DEF_SAVEGLOBAL;
3325 if (pushdef) vec_push(code_defs, def);
3327 return global->code.globaladdr >= 0;
3331 ir_value_code_setaddr(global, vec_size(code_globals));
3332 if (global->hasvalue) {
3333 vec_push(code_globals, code_genstring(global->constval.vstring));
3335 vec_push(code_globals, 0);
3337 if (!islocal && global->cvq != CV_CONST)
3338 def.type |= DEF_SAVEGLOBAL;
3339 if (pushdef) vec_push(code_defs, def);
3340 return global->code.globaladdr >= 0;
3345 ir_value_vector_member(global, 0);
3346 ir_value_vector_member(global, 1);
3347 ir_value_vector_member(global, 2);
3348 ir_value_code_setaddr(global, vec_size(code_globals));
3349 if (global->hasvalue) {
3350 iptr = (int32_t*)&global->constval.ivec[0];
3351 vec_push(code_globals, iptr[0]);
3352 if (global->code.globaladdr < 0)
3354 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3355 vec_push(code_globals, iptr[d]);
3358 vec_push(code_globals, 0);
3359 if (global->code.globaladdr < 0)
3361 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3362 vec_push(code_globals, 0);
3365 if (!islocal && global->cvq != CV_CONST)
3366 def.type |= DEF_SAVEGLOBAL;
3369 vec_push(code_defs, def);
3370 def.type &= ~DEF_SAVEGLOBAL;
3371 gen_vector_defs(def, global->name);
3373 return global->code.globaladdr >= 0;
3376 ir_value_code_setaddr(global, vec_size(code_globals));
3377 if (!global->hasvalue) {
3378 vec_push(code_globals, 0);
3379 if (global->code.globaladdr < 0)
3382 vec_push(code_globals, vec_size(code_functions));
3383 if (!gen_global_function(self, global))
3386 if (!islocal && global->cvq != CV_CONST)
3387 def.type |= DEF_SAVEGLOBAL;
3388 if (pushdef) vec_push(code_defs, def);
3391 /* assume biggest type */
3392 ir_value_code_setaddr(global, vec_size(code_globals));
3393 vec_push(code_globals, 0);
3394 for (i = 1; i < type_sizeof_[TYPE_VARIANT]; ++i)
3395 vec_push(code_globals, 0);
3398 /* refuse to create 'void' type or any other fancy business. */
3399 irerror(global->context, "Invalid type for global variable `%s`: %s",
3400 global->name, type_name[global->vtype]);
3405 static void ir_builder_prepare_field(ir_value *field)
3407 field->code.fieldaddr = code_alloc_field(type_sizeof_[field->fieldtype]);
3410 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3412 prog_section_def def;
3413 prog_section_field fld;
3417 def.type = (uint16_t)field->vtype;
3418 def.offset = (uint16_t)vec_size(code_globals);
3420 /* create a global named the same as the field */
3421 if (opts.standard == COMPILER_GMQCC) {
3422 /* in our standard, the global gets a dot prefix */
3423 size_t len = strlen(field->name);
3426 /* we really don't want to have to allocate this, and 1024
3427 * bytes is more than enough for a variable/field name
3429 if (len+2 >= sizeof(name)) {
3430 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
3435 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
3438 def.name = code_genstring(name);
3439 fld.name = def.name + 1; /* we reuse that string table entry */
3441 /* in plain QC, there cannot be a global with the same name,
3442 * and so we also name the global the same.
3443 * FIXME: fteqcc should create a global as well
3444 * check if it actually uses the same name. Probably does
3446 def.name = code_genstring(field->name);
3447 fld.name = def.name;
3450 field->code.name = def.name;
3452 vec_push(code_defs, def);
3454 fld.type = field->fieldtype;
3456 if (fld.type == TYPE_VOID) {
3457 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
3461 fld.offset = field->code.fieldaddr;
3463 vec_push(code_fields, fld);
3465 ir_value_code_setaddr(field, vec_size(code_globals));
3466 vec_push(code_globals, fld.offset);
3467 if (fld.type == TYPE_VECTOR) {
3468 vec_push(code_globals, fld.offset+1);
3469 vec_push(code_globals, fld.offset+2);
3472 if (field->fieldtype == TYPE_VECTOR) {
3473 gen_vector_defs(def, field->name);
3474 gen_vector_fields(fld, field->name);
3477 return field->code.globaladdr >= 0;
3480 bool ir_builder_generate(ir_builder *self, const char *filename)
3482 prog_section_statement stmt;
3484 char *lnofile = NULL;
3488 for (i = 0; i < vec_size(self->fields); ++i)
3490 ir_builder_prepare_field(self->fields[i]);
3493 for (i = 0; i < vec_size(self->globals); ++i)
3495 if (!ir_builder_gen_global(self, self->globals[i], false, false)) {
3498 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3499 ir_function *func = self->globals[i]->constval.vfunc;
3500 if (func && self->max_locals < func->allocated_locals &&
3501 !(func->flags & IR_FLAG_MASK_NO_OVERLAP))
3503 self->max_locals = func->allocated_locals;
3508 for (i = 0; i < vec_size(self->fields); ++i)
3510 if (!ir_builder_gen_field(self, self->fields[i])) {
3515 /* generate common locals */
3516 self->first_common_local = vec_size(code_globals);
3517 for (i = 0; i < self->max_locals; ++i) {
3518 vec_push(code_globals, 0);
3521 /* generate function code */
3522 for (i = 0; i < vec_size(self->globals); ++i)
3524 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3525 if (!gen_global_function_code(self, self->globals[i])) {
3531 if (vec_size(code_globals) >= 65536) {
3532 irerror(vec_last(self->globals)->context, "This progs file would require more globals than the metadata can handle. Bailing out.");
3536 /* DP errors if the last instruction is not an INSTR_DONE. */
3537 if (vec_last(code_statements).opcode != INSTR_DONE)
3539 stmt.opcode = INSTR_DONE;
3543 code_push_statement(&stmt, vec_last(code_linenums));
3549 if (vec_size(code_statements) != vec_size(code_linenums)) {
3550 con_err("Linecounter wrong: %lu != %lu\n",
3551 (unsigned long)vec_size(code_statements),
3552 (unsigned long)vec_size(code_linenums));
3553 } else if (OPTS_FLAG(LNO)) {
3555 size_t filelen = strlen(filename);
3557 memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
3558 dot = strrchr(lnofile, '.');
3562 vec_shrinkto(lnofile, dot - lnofile);
3564 memcpy(vec_add(lnofile, 5), ".lno", 5);
3569 con_out("writing '%s' and '%s'...\n", filename, lnofile);
3571 con_out("writing '%s'\n", filename);
3573 if (!code_write(filename, lnofile)) {
3581 /***********************************************************************
3582 *IR DEBUG Dump functions...
3585 #define IND_BUFSZ 1024
3588 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
3591 const char *qc_opname(int op)
3593 if (op < 0) return "<INVALID>";
3594 if (op < (int)( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
3595 return asm_instr[op].m;
3597 case VINSTR_PHI: return "PHI";
3598 case VINSTR_JUMP: return "JUMP";
3599 case VINSTR_COND: return "COND";
3600 default: return "<UNK>";
3604 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
3607 char indent[IND_BUFSZ];
3611 oprintf("module %s\n", b->name);
3612 for (i = 0; i < vec_size(b->globals); ++i)
3615 if (b->globals[i]->hasvalue)
3616 oprintf("%s = ", b->globals[i]->name);
3617 ir_value_dump(b->globals[i], oprintf);
3620 for (i = 0; i < vec_size(b->functions); ++i)
3621 ir_function_dump(b->functions[i], indent, oprintf);
3622 oprintf("endmodule %s\n", b->name);
3625 void ir_function_dump(ir_function *f, char *ind,
3626 int (*oprintf)(const char*, ...))
3629 if (f->builtin != 0) {
3630 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
3633 oprintf("%sfunction %s\n", ind, f->name);
3634 strncat(ind, "\t", IND_BUFSZ);
3635 if (vec_size(f->locals))
3637 oprintf("%s%i locals:\n", ind, (int)vec_size(f->locals));
3638 for (i = 0; i < vec_size(f->locals); ++i) {
3639 oprintf("%s\t", ind);
3640 ir_value_dump(f->locals[i], oprintf);
3644 oprintf("%sliferanges:\n", ind);
3645 for (i = 0; i < vec_size(f->locals); ++i) {
3647 ir_value *v = f->locals[i];
3648 oprintf("%s\t%s: %s@%i ", ind, v->name, (v->unique_life ? "unique " : ""), (int)v->code.local);
3649 for (l = 0; l < vec_size(v->life); ++l) {
3650 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3653 for (m = 0; m < 3; ++m) {
3654 ir_value *vm = v->members[m];
3657 oprintf("%s\t%s: %s@%i ", ind, vm->name, (vm->unique_life ? "unique " : ""), (int)vm->code.local);
3658 for (l = 0; l < vec_size(vm->life); ++l) {
3659 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
3664 for (i = 0; i < vec_size(f->values); ++i) {
3666 ir_value *v = f->values[i];
3667 oprintf("%s\t%s: @%i ", ind, v->name, (int)v->code.local);
3668 for (l = 0; l < vec_size(v->life); ++l) {
3669 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3673 if (vec_size(f->blocks))
3675 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
3676 for (i = 0; i < vec_size(f->blocks); ++i) {
3677 if (f->blocks[i]->run_id != f->run_id) {
3678 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
3680 ir_block_dump(f->blocks[i], ind, oprintf);
3684 ind[strlen(ind)-1] = 0;
3685 oprintf("%sendfunction %s\n", ind, f->name);
3688 void ir_block_dump(ir_block* b, char *ind,
3689 int (*oprintf)(const char*, ...))
3692 oprintf("%s:%s\n", ind, b->label);
3693 strncat(ind, "\t", IND_BUFSZ);
3695 for (i = 0; i < vec_size(b->instr); ++i)
3696 ir_instr_dump(b->instr[i], ind, oprintf);
3697 ind[strlen(ind)-1] = 0;
3700 void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
3703 oprintf("%s <- phi ", in->_ops[0]->name);
3704 for (i = 0; i < vec_size(in->phi); ++i)
3706 oprintf("([%s] : %s) ", in->phi[i].from->label,
3707 in->phi[i].value->name);
3712 void ir_instr_dump(ir_instr *in, char *ind,
3713 int (*oprintf)(const char*, ...))
3716 const char *comma = NULL;
3718 oprintf("%s (%i) ", ind, (int)in->eid);
3720 if (in->opcode == VINSTR_PHI) {
3721 dump_phi(in, oprintf);
3725 strncat(ind, "\t", IND_BUFSZ);
3727 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3728 ir_value_dump(in->_ops[0], oprintf);
3729 if (in->_ops[1] || in->_ops[2])
3732 if (in->opcode == INSTR_CALL0 || in->opcode == VINSTR_NRCALL) {
3733 oprintf("CALL%i\t", vec_size(in->params));
3735 oprintf("%s\t", qc_opname(in->opcode));
3737 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3738 ir_value_dump(in->_ops[0], oprintf);
3743 for (i = 1; i != 3; ++i) {
3747 ir_value_dump(in->_ops[i], oprintf);
3755 oprintf("[%s]", in->bops[0]->label);
3759 oprintf("%s[%s]", comma, in->bops[1]->label);
3760 if (vec_size(in->params)) {
3761 oprintf("\tparams: ");
3762 for (i = 0; i != vec_size(in->params); ++i) {
3763 oprintf("%s, ", in->params[i]->name);
3767 ind[strlen(ind)-1] = 0;
3770 void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
3773 for (; *str; ++str) {
3775 case '\n': oprintf("\\n"); break;
3776 case '\r': oprintf("\\r"); break;
3777 case '\t': oprintf("\\t"); break;
3778 case '\v': oprintf("\\v"); break;
3779 case '\f': oprintf("\\f"); break;
3780 case '\b': oprintf("\\b"); break;
3781 case '\a': oprintf("\\a"); break;
3782 case '\\': oprintf("\\\\"); break;
3783 case '"': oprintf("\\\""); break;
3784 default: oprintf("%c", *str); break;
3790 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3799 oprintf("fn:%s", v->name);
3802 oprintf("%g", v->constval.vfloat);
3805 oprintf("'%g %g %g'",
3808 v->constval.vvec.z);
3811 oprintf("(entity)");
3814 ir_value_dump_string(v->constval.vstring, oprintf);
3818 oprintf("%i", v->constval.vint);
3823 v->constval.vpointer->name);
3827 oprintf("%s", v->name);
3831 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
3834 oprintf("Life of %12s:", self->name);
3835 for (i = 0; i < vec_size(self->life); ++i)
3837 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);