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, ...)
214 r = vcompile_warning(ctx, warntype, fmt, ap);
219 /***********************************************************************
220 * Vector utility functions
223 bool GMQCC_WARN vec_ir_value_find(ir_value **vec, ir_value *what, size_t *idx)
226 size_t len = vec_size(vec);
227 for (i = 0; i < len; ++i) {
228 if (vec[i] == what) {
236 bool GMQCC_WARN vec_ir_block_find(ir_block **vec, ir_block *what, size_t *idx)
239 size_t len = vec_size(vec);
240 for (i = 0; i < len; ++i) {
241 if (vec[i] == what) {
249 bool GMQCC_WARN vec_ir_instr_find(ir_instr **vec, ir_instr *what, size_t *idx)
252 size_t len = vec_size(vec);
253 for (i = 0; i < len; ++i) {
254 if (vec[i] == what) {
262 /***********************************************************************
266 static void ir_block_delete_quick(ir_block* self);
267 static void ir_instr_delete_quick(ir_instr *self);
268 static void ir_function_delete_quick(ir_function *self);
270 ir_builder* ir_builder_new(const char *modulename)
274 self = (ir_builder*)mem_a(sizeof(*self));
278 self->functions = NULL;
279 self->globals = NULL;
281 self->extparams = 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->str_immediate = 0;
290 if (!ir_builder_set_name(self, modulename)) {
298 void ir_builder_delete(ir_builder* self)
301 util_htdel(self->htglobals);
302 util_htdel(self->htfields);
303 util_htdel(self->htfunctions);
304 mem_d((void*)self->name);
305 for (i = 0; i != vec_size(self->functions); ++i) {
306 ir_function_delete_quick(self->functions[i]);
308 vec_free(self->functions);
309 for (i = 0; i != vec_size(self->extparams); ++i) {
310 ir_value_delete(self->extparams[i]);
312 vec_free(self->extparams);
313 for (i = 0; i != vec_size(self->globals); ++i) {
314 ir_value_delete(self->globals[i]);
316 vec_free(self->globals);
317 for (i = 0; i != vec_size(self->fields); ++i) {
318 ir_value_delete(self->fields[i]);
320 vec_free(self->fields);
321 vec_free(self->filenames);
322 vec_free(self->filestrings);
326 bool ir_builder_set_name(ir_builder *self, const char *name)
329 mem_d((void*)self->name);
330 self->name = util_strdup(name);
334 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
336 return (ir_function*)util_htget(self->htfunctions, name);
339 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
341 ir_function *fn = ir_builder_get_function(self, name);
346 fn = ir_function_new(self, outtype);
347 if (!ir_function_set_name(fn, name))
349 ir_function_delete(fn);
352 vec_push(self->functions, fn);
353 util_htset(self->htfunctions, name, fn);
355 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
357 ir_function_delete(fn);
361 fn->value->hasvalue = true;
362 fn->value->outtype = outtype;
363 fn->value->constval.vfunc = fn;
364 fn->value->context = fn->context;
369 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
371 return (ir_value*)util_htget(self->htglobals, name);
374 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
378 if (name && name[0] != '#')
380 ve = ir_builder_get_global(self, name);
386 ve = ir_value_var(name, store_global, vtype);
387 vec_push(self->globals, ve);
388 util_htset(self->htglobals, name, ve);
392 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
394 return (ir_value*)util_htget(self->htfields, name);
398 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
400 ir_value *ve = ir_builder_get_field(self, name);
405 ve = ir_value_var(name, store_global, TYPE_FIELD);
406 ve->fieldtype = vtype;
407 vec_push(self->fields, ve);
408 util_htset(self->htfields, name, ve);
412 /***********************************************************************
416 bool ir_function_naive_phi(ir_function*);
417 void ir_function_enumerate(ir_function*);
418 bool ir_function_calculate_liferanges(ir_function*);
419 bool ir_function_allocate_locals(ir_function*);
421 ir_function* ir_function_new(ir_builder* owner, int outtype)
424 self = (ir_function*)mem_a(sizeof(*self));
429 memset(self, 0, sizeof(*self));
432 if (!ir_function_set_name(self, "<@unnamed>")) {
437 self->context.file = "<@no context>";
438 self->context.line = 0;
439 self->outtype = outtype;
448 self->code_function_def = -1;
449 self->allocated_locals = 0;
455 bool ir_function_set_name(ir_function *self, const char *name)
458 mem_d((void*)self->name);
459 self->name = util_strdup(name);
463 static void ir_function_delete_quick(ir_function *self)
466 mem_d((void*)self->name);
468 for (i = 0; i != vec_size(self->blocks); ++i)
469 ir_block_delete_quick(self->blocks[i]);
470 vec_free(self->blocks);
472 vec_free(self->params);
474 for (i = 0; i != vec_size(self->values); ++i)
475 ir_value_delete(self->values[i]);
476 vec_free(self->values);
478 for (i = 0; i != vec_size(self->locals); ++i)
479 ir_value_delete(self->locals[i]);
480 vec_free(self->locals);
482 /* self->value is deleted by the builder */
487 void ir_function_delete(ir_function *self)
490 mem_d((void*)self->name);
492 for (i = 0; i != vec_size(self->blocks); ++i)
493 ir_block_delete(self->blocks[i]);
494 vec_free(self->blocks);
496 vec_free(self->params);
498 for (i = 0; i != vec_size(self->values); ++i)
499 ir_value_delete(self->values[i]);
500 vec_free(self->values);
502 for (i = 0; i != vec_size(self->locals); ++i)
503 ir_value_delete(self->locals[i]);
504 vec_free(self->locals);
506 /* self->value is deleted by the builder */
511 void ir_function_collect_value(ir_function *self, ir_value *v)
513 vec_push(self->values, v);
516 ir_block* ir_function_create_block(lex_ctx ctx, ir_function *self, const char *label)
518 ir_block* bn = ir_block_new(self, label);
520 vec_push(self->blocks, bn);
524 static bool instr_is_operation(uint16_t op)
526 return ( (op >= INSTR_MUL_F && op <= INSTR_GT) ||
527 (op >= INSTR_LOAD_F && op <= INSTR_LOAD_FNC) ||
528 (op == INSTR_ADDRESS) ||
529 (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) ||
530 (op >= INSTR_AND && op <= INSTR_BITOR) );
533 bool ir_function_pass_peephole(ir_function *self)
537 for (b = 0; b < vec_size(self->blocks); ++b) {
539 ir_block *block = self->blocks[b];
541 for (i = 0; i < vec_size(block->instr); ++i) {
543 inst = block->instr[i];
546 (inst->opcode >= INSTR_STORE_F &&
547 inst->opcode <= INSTR_STORE_FNC))
555 oper = block->instr[i-1];
556 if (!instr_is_operation(oper->opcode))
559 value = oper->_ops[0];
561 /* only do it for SSA values */
562 if (value->store != store_value)
565 /* don't optimize out the temp if it's used later again */
566 if (vec_size(value->reads) != 1)
569 /* The very next store must use this value */
570 if (value->reads[0] != store)
573 /* And of course the store must _read_ from it, so it's in
575 if (store->_ops[1] != value)
578 ++opts_optimizationcount[OPTIM_PEEPHOLE];
579 (void)!ir_instr_op(oper, 0, store->_ops[0], true);
581 vec_remove(block->instr, i, 1);
582 ir_instr_delete(store);
584 else if (inst->opcode == VINSTR_COND)
586 /* COND on a value resulting from a NOT could
587 * remove the NOT and swap its operands
594 value = inst->_ops[0];
596 if (value->store != store_value ||
597 vec_size(value->reads) != 1 ||
598 value->reads[0] != inst)
603 inot = value->writes[0];
604 if (inot->_ops[0] != value ||
605 inot->opcode < INSTR_NOT_F ||
606 inot->opcode > INSTR_NOT_FNC ||
607 inot->opcode == INSTR_NOT_V) /* can't do this one */
613 ++opts_optimizationcount[OPTIM_PEEPHOLE];
615 (void)!ir_instr_op(inst, 0, inot->_ops[1], false);
618 for (inotid = 0; inotid < vec_size(tmp->instr); ++inotid) {
619 if (tmp->instr[inotid] == inot)
622 if (inotid >= vec_size(tmp->instr)) {
623 compile_error(inst->context, "sanity-check failed: failed to find instruction to optimize out");
626 vec_remove(tmp->instr, inotid, 1);
627 ir_instr_delete(inot);
628 /* swap ontrue/onfalse */
630 inst->bops[0] = inst->bops[1];
641 bool ir_function_pass_tailcall(ir_function *self)
645 for (b = 0; b < vec_size(self->blocks); ++b) {
647 ir_instr *ret, *call, *store = NULL;
648 ir_block *block = self->blocks[b];
650 if (!block->final || vec_size(block->instr) < 2)
653 ret = block->instr[vec_size(block->instr)-1];
654 if (ret->opcode != INSTR_DONE && ret->opcode != INSTR_RETURN)
657 call = block->instr[vec_size(block->instr)-2];
658 if (call->opcode >= INSTR_STORE_F && call->opcode <= INSTR_STORE_FNC) {
659 /* account for the unoptimized
661 * STORE %return, %tmp
665 if (vec_size(block->instr) < 3)
669 call = block->instr[vec_size(block->instr)-3];
672 if (call->opcode < INSTR_CALL0 || call->opcode > INSTR_CALL8)
676 /* optimize out the STORE */
678 ret->_ops[0] == store->_ops[0] &&
679 store->_ops[1] == call->_ops[0])
681 ++opts_optimizationcount[OPTIM_PEEPHOLE];
682 call->_ops[0] = store->_ops[0];
683 vec_remove(block->instr, vec_size(block->instr) - 2, 1);
684 ir_instr_delete(store);
693 funcval = call->_ops[1];
696 if (funcval->vtype != TYPE_FUNCTION || funcval->constval.vfunc != self)
699 /* now we have a CALL and a RET, check if it's a tailcall */
700 if (ret->_ops[0] && call->_ops[0] != ret->_ops[0])
703 ++opts_optimizationcount[OPTIM_TAIL_RECURSION];
704 vec_shrinkby(block->instr, 2);
706 block->final = false; /* open it back up */
708 /* emite parameter-stores */
709 for (p = 0; p < vec_size(call->params); ++p) {
710 /* assert(call->params_count <= self->locals_count); */
711 if (!ir_block_create_store(block, call->context, self->locals[p], call->params[p])) {
712 irerror(call->context, "failed to create tailcall store instruction for parameter %i", (int)p);
716 if (!ir_block_create_jump(block, call->context, self->blocks[0])) {
717 irerror(call->context, "failed to create tailcall jump");
721 ir_instr_delete(call);
722 ir_instr_delete(ret);
728 bool ir_function_finalize(ir_function *self)
733 if (OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
734 if (!ir_function_pass_peephole(self)) {
735 irerror(self->context, "generic optimization pass broke something in `%s`", self->name);
740 if (OPTS_OPTIMIZATION(OPTIM_TAIL_RECURSION)) {
741 if (!ir_function_pass_tailcall(self)) {
742 irerror(self->context, "tailcall optimization pass broke something in `%s`", self->name);
747 if (!ir_function_naive_phi(self))
750 ir_function_enumerate(self);
752 if (!ir_function_calculate_liferanges(self))
754 if (!ir_function_allocate_locals(self))
759 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
764 vec_size(self->locals) &&
765 self->locals[vec_size(self->locals)-1]->store != store_param) {
766 irerror(self->context, "cannot add parameters after adding locals");
770 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
771 vec_push(self->locals, ve);
775 /***********************************************************************
779 ir_block* ir_block_new(ir_function* owner, const char *name)
782 self = (ir_block*)mem_a(sizeof(*self));
786 memset(self, 0, sizeof(*self));
789 if (name && !ir_block_set_label(self, name)) {
794 self->context.file = "<@no context>";
795 self->context.line = 0;
799 self->entries = NULL;
803 self->is_return = false;
808 self->generated = false;
813 static void ir_block_delete_quick(ir_block* self)
816 if (self->label) mem_d(self->label);
817 for (i = 0; i != vec_size(self->instr); ++i)
818 ir_instr_delete_quick(self->instr[i]);
819 vec_free(self->instr);
820 vec_free(self->entries);
821 vec_free(self->exits);
822 vec_free(self->living);
826 void ir_block_delete(ir_block* self)
829 if (self->label) mem_d(self->label);
830 for (i = 0; i != vec_size(self->instr); ++i)
831 ir_instr_delete(self->instr[i]);
832 vec_free(self->instr);
833 vec_free(self->entries);
834 vec_free(self->exits);
835 vec_free(self->living);
839 bool ir_block_set_label(ir_block *self, const char *name)
842 mem_d((void*)self->label);
843 self->label = util_strdup(name);
844 return !!self->label;
847 /***********************************************************************
851 ir_instr* ir_instr_new(lex_ctx ctx, ir_block* owner, int op)
854 self = (ir_instr*)mem_a(sizeof(*self));
861 self->_ops[0] = NULL;
862 self->_ops[1] = NULL;
863 self->_ops[2] = NULL;
864 self->bops[0] = NULL;
865 self->bops[1] = NULL;
876 static void ir_instr_delete_quick(ir_instr *self)
879 vec_free(self->params);
883 void ir_instr_delete(ir_instr *self)
886 /* The following calls can only delete from
887 * vectors, we still want to delete this instruction
888 * so ignore the return value. Since with the warn_unused_result attribute
889 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
890 * I have to improvise here and use if(foo());
892 for (i = 0; i < vec_size(self->phi); ++i) {
894 if (vec_ir_instr_find(self->phi[i].value->writes, self, &idx))
895 vec_remove(self->phi[i].value->writes, idx, 1);
896 if (vec_ir_instr_find(self->phi[i].value->reads, self, &idx))
897 vec_remove(self->phi[i].value->reads, idx, 1);
900 for (i = 0; i < vec_size(self->params); ++i) {
902 if (vec_ir_instr_find(self->params[i]->writes, self, &idx))
903 vec_remove(self->params[i]->writes, idx, 1);
904 if (vec_ir_instr_find(self->params[i]->reads, self, &idx))
905 vec_remove(self->params[i]->reads, idx, 1);
907 vec_free(self->params);
908 (void)!ir_instr_op(self, 0, NULL, false);
909 (void)!ir_instr_op(self, 1, NULL, false);
910 (void)!ir_instr_op(self, 2, NULL, false);
914 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
916 if (self->_ops[op]) {
918 if (writing && vec_ir_instr_find(self->_ops[op]->writes, self, &idx))
919 vec_remove(self->_ops[op]->writes, idx, 1);
920 else if (vec_ir_instr_find(self->_ops[op]->reads, self, &idx))
921 vec_remove(self->_ops[op]->reads, idx, 1);
925 vec_push(v->writes, self);
927 vec_push(v->reads, self);
933 /***********************************************************************
937 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
939 self->code.globaladdr = gaddr;
940 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
941 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
942 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
945 int32_t ir_value_code_addr(const ir_value *self)
947 if (self->store == store_return)
948 return OFS_RETURN + self->code.addroffset;
949 return self->code.globaladdr + self->code.addroffset;
952 ir_value* ir_value_var(const char *name, int storetype, int vtype)
955 self = (ir_value*)mem_a(sizeof(*self));
957 self->fieldtype = TYPE_VOID;
958 self->outtype = TYPE_VOID;
959 self->store = storetype;
965 self->hasvalue = false;
966 self->context.file = "<@no context>";
967 self->context.line = 0;
969 if (name && !ir_value_set_name(self, name)) {
970 irerror(self->context, "out of memory");
975 memset(&self->constval, 0, sizeof(self->constval));
976 memset(&self->code, 0, sizeof(self->code));
978 self->members[0] = NULL;
979 self->members[1] = NULL;
980 self->members[2] = NULL;
981 self->memberof = NULL;
983 self->unique_life = false;
989 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
997 if (self->members[member])
998 return self->members[member];
1000 len = strlen(self->name);
1001 name = (char*)mem_a(len + 3);
1002 memcpy(name, self->name, len);
1004 name[len+1] = 'x' + member;
1006 if (self->vtype == TYPE_VECTOR)
1008 m = ir_value_var(name, self->store, TYPE_FLOAT);
1012 m->context = self->context;
1014 self->members[member] = m;
1015 m->code.addroffset = member;
1017 else if (self->vtype == TYPE_FIELD)
1019 if (self->fieldtype != TYPE_VECTOR)
1021 m = ir_value_var(name, self->store, TYPE_FIELD);
1025 m->fieldtype = TYPE_FLOAT;
1026 m->context = self->context;
1028 self->members[member] = m;
1029 m->code.addroffset = member;
1033 irerror(self->context, "invalid member access on %s", self->name);
1041 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
1043 ir_value *v = ir_value_var(name, storetype, vtype);
1046 ir_function_collect_value(owner, v);
1050 void ir_value_delete(ir_value* self)
1054 mem_d((void*)self->name);
1057 if (self->vtype == TYPE_STRING)
1058 mem_d((void*)self->constval.vstring);
1060 for (i = 0; i < 3; ++i) {
1061 if (self->members[i])
1062 ir_value_delete(self->members[i]);
1064 vec_free(self->reads);
1065 vec_free(self->writes);
1066 vec_free(self->life);
1070 bool ir_value_set_name(ir_value *self, const char *name)
1073 mem_d((void*)self->name);
1074 self->name = util_strdup(name);
1075 return !!self->name;
1078 bool ir_value_set_float(ir_value *self, float f)
1080 if (self->vtype != TYPE_FLOAT)
1082 self->constval.vfloat = f;
1083 self->hasvalue = true;
1087 bool ir_value_set_func(ir_value *self, int f)
1089 if (self->vtype != TYPE_FUNCTION)
1091 self->constval.vint = f;
1092 self->hasvalue = true;
1096 bool ir_value_set_vector(ir_value *self, vector v)
1098 if (self->vtype != TYPE_VECTOR)
1100 self->constval.vvec = v;
1101 self->hasvalue = true;
1105 bool ir_value_set_field(ir_value *self, ir_value *fld)
1107 if (self->vtype != TYPE_FIELD)
1109 self->constval.vpointer = fld;
1110 self->hasvalue = true;
1114 static char *ir_strdup(const char *str)
1117 /* actually dup empty strings */
1118 char *out = mem_a(1);
1122 return util_strdup(str);
1125 bool ir_value_set_string(ir_value *self, const char *str)
1127 if (self->vtype != TYPE_STRING)
1129 self->constval.vstring = ir_strdup(str);
1130 self->hasvalue = true;
1135 bool ir_value_set_int(ir_value *self, int i)
1137 if (self->vtype != TYPE_INTEGER)
1139 self->constval.vint = i;
1140 self->hasvalue = true;
1145 bool ir_value_lives(ir_value *self, size_t at)
1148 for (i = 0; i < vec_size(self->life); ++i)
1150 ir_life_entry_t *life = &self->life[i];
1151 if (life->start <= at && at <= life->end)
1153 if (life->start > at) /* since it's ordered */
1159 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
1162 vec_push(self->life, e);
1163 for (k = vec_size(self->life)-1; k > idx; --k)
1164 self->life[k] = self->life[k-1];
1165 self->life[idx] = e;
1169 bool ir_value_life_merge(ir_value *self, size_t s)
1172 ir_life_entry_t *life = NULL;
1173 ir_life_entry_t *before = NULL;
1174 ir_life_entry_t new_entry;
1176 /* Find the first range >= s */
1177 for (i = 0; i < vec_size(self->life); ++i)
1180 life = &self->life[i];
1181 if (life->start > s)
1184 /* nothing found? append */
1185 if (i == vec_size(self->life)) {
1187 if (life && life->end+1 == s)
1189 /* previous life range can be merged in */
1193 if (life && life->end >= s)
1195 e.start = e.end = s;
1196 vec_push(self->life, e);
1202 if (before->end + 1 == s &&
1203 life->start - 1 == s)
1206 before->end = life->end;
1207 vec_remove(self->life, i, 1);
1210 if (before->end + 1 == s)
1216 /* already contained */
1217 if (before->end >= s)
1221 if (life->start - 1 == s)
1226 /* insert a new entry */
1227 new_entry.start = new_entry.end = s;
1228 return ir_value_life_insert(self, i, new_entry);
1231 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1235 if (!vec_size(other->life))
1238 if (!vec_size(self->life)) {
1239 size_t count = vec_size(other->life);
1240 ir_life_entry_t *life = vec_add(self->life, count);
1241 memcpy(life, other->life, count * sizeof(*life));
1246 for (i = 0; i < vec_size(other->life); ++i)
1248 const ir_life_entry_t *life = &other->life[i];
1251 ir_life_entry_t *entry = &self->life[myi];
1253 if (life->end+1 < entry->start)
1255 /* adding an interval before entry */
1256 if (!ir_value_life_insert(self, myi, *life))
1262 if (life->start < entry->start &&
1263 life->end+1 >= entry->start)
1265 /* starts earlier and overlaps */
1266 entry->start = life->start;
1269 if (life->end > entry->end &&
1270 life->start <= entry->end+1)
1272 /* ends later and overlaps */
1273 entry->end = life->end;
1276 /* see if our change combines it with the next ranges */
1277 while (myi+1 < vec_size(self->life) &&
1278 entry->end+1 >= self->life[1+myi].start)
1280 /* overlaps with (myi+1) */
1281 if (entry->end < self->life[1+myi].end)
1282 entry->end = self->life[1+myi].end;
1283 vec_remove(self->life, myi+1, 1);
1284 entry = &self->life[myi];
1287 /* see if we're after the entry */
1288 if (life->start > entry->end)
1291 /* append if we're at the end */
1292 if (myi >= vec_size(self->life)) {
1293 vec_push(self->life, *life);
1296 /* otherweise check the next range */
1305 bool ir_values_overlap(const ir_value *a, const ir_value *b)
1307 /* For any life entry in A see if it overlaps with
1308 * any life entry in B.
1309 * Note that the life entries are orderes, so we can make a
1310 * more efficient algorithm there than naively translating the
1314 ir_life_entry_t *la, *lb, *enda, *endb;
1316 /* first of all, if either has no life range, they cannot clash */
1317 if (!vec_size(a->life) || !vec_size(b->life))
1322 enda = la + vec_size(a->life);
1323 endb = lb + vec_size(b->life);
1326 /* check if the entries overlap, for that,
1327 * both must start before the other one ends.
1329 if (la->start < lb->end &&
1330 lb->start < la->end)
1335 /* entries are ordered
1336 * one entry is earlier than the other
1337 * that earlier entry will be moved forward
1339 if (la->start < lb->start)
1341 /* order: A B, move A forward
1342 * check if we hit the end with A
1347 else /* if (lb->start < la->start) actually <= */
1349 /* order: B A, move B forward
1350 * check if we hit the end with B
1359 /***********************************************************************
1363 static bool ir_check_unreachable(ir_block *self)
1365 /* The IR should never have to deal with unreachable code */
1366 if (!self->final/* || OPTS_FLAG(ALLOW_UNREACHABLE_CODE)*/)
1368 irerror(self->context, "unreachable statement (%s)", self->label);
1372 bool ir_block_create_store_op(ir_block *self, lex_ctx ctx, int op, ir_value *target, ir_value *what)
1375 if (!ir_check_unreachable(self))
1378 if (target->store == store_value &&
1379 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1381 irerror(self->context, "cannot store to an SSA value");
1382 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1383 irerror(self->context, "instruction: %s", asm_instr[op].m);
1387 in = ir_instr_new(ctx, self, op);
1391 if (!ir_instr_op(in, 0, target, true) ||
1392 !ir_instr_op(in, 1, what, false))
1394 ir_instr_delete(in);
1397 vec_push(self->instr, in);
1401 bool ir_block_create_store(ir_block *self, lex_ctx ctx, ir_value *target, ir_value *what)
1405 if (target->vtype == TYPE_VARIANT)
1406 vtype = what->vtype;
1408 vtype = target->vtype;
1411 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1412 op = INSTR_CONV_ITOF;
1413 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1414 op = INSTR_CONV_FTOI;
1416 op = type_store_instr[vtype];
1418 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1419 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1423 return ir_block_create_store_op(self, ctx, op, target, what);
1426 bool ir_block_create_storep(ir_block *self, lex_ctx ctx, ir_value *target, ir_value *what)
1431 if (target->vtype != TYPE_POINTER)
1434 /* storing using pointer - target is a pointer, type must be
1435 * inferred from source
1437 vtype = what->vtype;
1439 op = type_storep_instr[vtype];
1440 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1441 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1442 op = INSTR_STOREP_V;
1445 return ir_block_create_store_op(self, ctx, op, target, what);
1448 bool ir_block_create_return(ir_block *self, lex_ctx ctx, ir_value *v)
1451 if (!ir_check_unreachable(self))
1454 self->is_return = true;
1455 in = ir_instr_new(ctx, self, INSTR_RETURN);
1459 if (v && !ir_instr_op(in, 0, v, false)) {
1460 ir_instr_delete(in);
1464 vec_push(self->instr, in);
1468 bool ir_block_create_if(ir_block *self, lex_ctx ctx, ir_value *v,
1469 ir_block *ontrue, ir_block *onfalse)
1472 if (!ir_check_unreachable(self))
1475 /*in = ir_instr_new(ctx, self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1476 in = ir_instr_new(ctx, self, VINSTR_COND);
1480 if (!ir_instr_op(in, 0, v, false)) {
1481 ir_instr_delete(in);
1485 in->bops[0] = ontrue;
1486 in->bops[1] = onfalse;
1488 vec_push(self->instr, in);
1490 vec_push(self->exits, ontrue);
1491 vec_push(self->exits, onfalse);
1492 vec_push(ontrue->entries, self);
1493 vec_push(onfalse->entries, self);
1497 bool ir_block_create_jump(ir_block *self, lex_ctx ctx, ir_block *to)
1500 if (!ir_check_unreachable(self))
1503 in = ir_instr_new(ctx, self, VINSTR_JUMP);
1508 vec_push(self->instr, in);
1510 vec_push(self->exits, to);
1511 vec_push(to->entries, self);
1515 bool ir_block_create_goto(ir_block *self, lex_ctx ctx, ir_block *to)
1518 if (!ir_check_unreachable(self))
1521 in = ir_instr_new(ctx, self, INSTR_GOTO);
1526 vec_push(self->instr, in);
1528 vec_push(self->exits, to);
1529 vec_push(to->entries, self);
1533 ir_instr* ir_block_create_phi(ir_block *self, lex_ctx ctx, const char *label, int ot)
1537 if (!ir_check_unreachable(self))
1539 in = ir_instr_new(ctx, self, VINSTR_PHI);
1542 out = ir_value_out(self->owner, label, store_value, ot);
1544 ir_instr_delete(in);
1547 if (!ir_instr_op(in, 0, out, true)) {
1548 ir_instr_delete(in);
1549 ir_value_delete(out);
1552 vec_push(self->instr, in);
1556 ir_value* ir_phi_value(ir_instr *self)
1558 return self->_ops[0];
1561 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1565 if (!vec_ir_block_find(self->owner->entries, b, NULL)) {
1566 /* Must not be possible to cause this, otherwise the AST
1567 * is doing something wrong.
1569 irerror(self->context, "Invalid entry block for PHI");
1575 vec_push(v->reads, self);
1576 vec_push(self->phi, pe);
1579 /* call related code */
1580 ir_instr* ir_block_create_call(ir_block *self, lex_ctx ctx, const char *label, ir_value *func, bool noreturn)
1584 if (!ir_check_unreachable(self))
1586 in = ir_instr_new(ctx, self, (noreturn ? VINSTR_NRCALL : INSTR_CALL0));
1592 self->is_return = true;
1595 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1597 ir_instr_delete(in);
1600 if (!ir_instr_op(in, 0, out, true) ||
1601 !ir_instr_op(in, 1, func, false))
1603 ir_instr_delete(in);
1604 ir_value_delete(out);
1607 vec_push(self->instr, in);
1609 if (!ir_block_create_return(self, ctx, NULL)) {
1610 compile_error(ctx, "internal error: failed to generate dummy-return instruction");
1611 ir_instr_delete(in);
1618 ir_value* ir_call_value(ir_instr *self)
1620 return self->_ops[0];
1623 void ir_call_param(ir_instr* self, ir_value *v)
1625 vec_push(self->params, v);
1626 vec_push(v->reads, self);
1629 /* binary op related code */
1631 ir_value* ir_block_create_binop(ir_block *self, lex_ctx ctx,
1632 const char *label, int opcode,
1633 ir_value *left, ir_value *right)
1655 case INSTR_SUB_S: /* -- offset of string as float */
1660 case INSTR_BITOR_IF:
1661 case INSTR_BITOR_FI:
1662 case INSTR_BITAND_FI:
1663 case INSTR_BITAND_IF:
1678 case INSTR_BITAND_I:
1681 case INSTR_RSHIFT_I:
1682 case INSTR_LSHIFT_I:
1704 /* boolean operations result in floats */
1705 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1707 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1710 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1715 if (ot == TYPE_VOID) {
1716 /* The AST or parser were supposed to check this! */
1720 return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1723 ir_value* ir_block_create_unary(ir_block *self, lex_ctx ctx,
1724 const char *label, int opcode,
1727 int ot = TYPE_FLOAT;
1739 /* QC doesn't have other unary operations. We expect extensions to fill
1740 * the above list, otherwise we assume out-type = in-type, eg for an
1744 ot = operand->vtype;
1747 if (ot == TYPE_VOID) {
1748 /* The AST or parser were supposed to check this! */
1752 /* let's use the general instruction creator and pass NULL for OPB */
1753 return ir_block_create_general_instr(self, ctx, label, opcode, operand, NULL, ot);
1756 ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx ctx, const char *label,
1757 int op, ir_value *a, ir_value *b, int outype)
1762 out = ir_value_out(self->owner, label, store_value, outype);
1766 instr = ir_instr_new(ctx, self, op);
1768 ir_value_delete(out);
1772 if (!ir_instr_op(instr, 0, out, true) ||
1773 !ir_instr_op(instr, 1, a, false) ||
1774 !ir_instr_op(instr, 2, b, false) )
1779 vec_push(self->instr, instr);
1783 ir_instr_delete(instr);
1784 ir_value_delete(out);
1788 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx ctx, const char *label, ir_value *ent, ir_value *field)
1792 /* Support for various pointer types todo if so desired */
1793 if (ent->vtype != TYPE_ENTITY)
1796 if (field->vtype != TYPE_FIELD)
1799 v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1800 v->fieldtype = field->fieldtype;
1804 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)
1807 if (ent->vtype != TYPE_ENTITY)
1810 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1811 if (field->vtype != TYPE_FIELD)
1816 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1817 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1818 case TYPE_STRING: op = INSTR_LOAD_S; break;
1819 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1820 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1821 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1823 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1824 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1827 irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1831 return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
1834 ir_value* ir_block_create_add(ir_block *self, lex_ctx ctx,
1836 ir_value *left, ir_value *right)
1839 int l = left->vtype;
1840 int r = right->vtype;
1844 irerror(self->context, "invalid type for ir_block_create_add: %s", type_name[l]);
1860 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1862 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1867 irerror(self->context, "invalid type for ir_block_create_add: %s", type_name[l]);
1871 return ir_block_create_binop(self, ctx, label, op, left, right);
1874 ir_value* ir_block_create_sub(ir_block *self, lex_ctx ctx,
1876 ir_value *left, ir_value *right)
1879 int l = left->vtype;
1880 int r = right->vtype;
1885 irerror(self->context, "invalid type for ir_block_create_sub: %s", type_name[l]);
1901 if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1903 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1908 irerror(self->context, "invalid type for ir_block_create_sub: %s", type_name[l]);
1912 return ir_block_create_binop(self, ctx, label, op, left, right);
1915 ir_value* ir_block_create_mul(ir_block *self, lex_ctx ctx,
1917 ir_value *left, ir_value *right)
1920 int l = left->vtype;
1921 int r = right->vtype;
1926 irerror(self->context, "invalid type for ir_block_create_mul: %s", type_name[l]);
1941 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1943 else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1946 else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1948 else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1950 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1952 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1956 irerror(self->context, "invalid type for ir_block_create_mul: %s", type_name[l]);
1960 return ir_block_create_binop(self, ctx, label, op, left, right);
1963 ir_value* ir_block_create_div(ir_block *self, lex_ctx ctx,
1965 ir_value *left, ir_value *right)
1968 int l = left->vtype;
1969 int r = right->vtype;
1974 irerror(self->context, "invalid type for ir_block_create_div: %s", type_name[l]);
1987 if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1989 else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1991 else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1996 irerror(self->context, "invalid type for ir_block_create_div: %s", type_name[l]);
2000 return ir_block_create_binop(self, ctx, label, op, left, right);
2003 /* PHI resolving breaks the SSA, and must thus be the last
2004 * step before life-range calculation.
2007 static bool ir_block_naive_phi(ir_block *self);
2008 bool ir_function_naive_phi(ir_function *self)
2012 for (i = 0; i < vec_size(self->blocks); ++i)
2014 if (!ir_block_naive_phi(self->blocks[i]))
2021 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
2026 /* create a store */
2027 if (!ir_block_create_store(block, old, what))
2030 /* we now move it up */
2031 instr = vec_last(block->instr);
2032 for (i = vec_size(block->instr)-1; i > iid; --i)
2033 block->instr[i] = block->instr[i-1];
2034 block->instr[i] = instr;
2040 static bool ir_block_naive_phi(ir_block *self)
2042 size_t i, p; /*, w;*/
2043 /* FIXME: optionally, create_phi can add the phis
2044 * to a list so we don't need to loop through blocks
2045 * - anyway: "don't optimize YET"
2047 for (i = 0; i < vec_size(self->instr); ++i)
2049 ir_instr *instr = self->instr[i];
2050 if (instr->opcode != VINSTR_PHI)
2053 vec_remove(self->instr, i, 1);
2054 --i; /* NOTE: i+1 below */
2056 for (p = 0; p < vec_size(instr->phi); ++p)
2058 ir_value *v = instr->phi[p].value;
2059 ir_block *b = instr->phi[p].from;
2061 if (v->store == store_value &&
2062 vec_size(v->reads) == 1 &&
2063 vec_size(v->writes) == 1)
2065 /* replace the value */
2066 if (!ir_instr_op(v->writes[0], 0, instr->_ops[0], true))
2071 /* force a move instruction */
2072 ir_instr *prevjump = vec_last(b->instr);
2075 instr->_ops[0]->store = store_global;
2076 if (!ir_block_create_store(b, instr->context, instr->_ops[0], v))
2078 instr->_ops[0]->store = store_value;
2079 vec_push(b->instr, prevjump);
2084 ir_value *v = instr->phi[p].value;
2085 for (w = 0; w < vec_size(v->writes); ++w) {
2088 if (!v->writes[w]->_ops[0])
2091 /* When the write was to a global, we have to emit a mov */
2092 old = v->writes[w]->_ops[0];
2094 /* The original instruction now writes to the PHI target local */
2095 if (v->writes[w]->_ops[0] == v)
2096 v->writes[w]->_ops[0] = instr->_ops[0];
2098 if (old->store != store_value && old->store != store_local && old->store != store_param)
2100 /* If it originally wrote to a global we need to store the value
2103 if (!ir_naive_phi_emit_store(self, i+1, old, v))
2105 if (i+1 < vec_size(self->instr))
2106 instr = self->instr[i+1];
2109 /* In case I forget and access instr later, it'll be NULL
2110 * when it's a problem, to make sure we crash, rather than accessing
2116 /* If it didn't, we can replace all reads by the phi target now. */
2118 for (r = 0; r < vec_size(old->reads); ++r)
2121 ir_instr *ri = old->reads[r];
2122 for (op = 0; op < vec_size(ri->phi); ++op) {
2123 if (ri->phi[op].value == old)
2124 ri->phi[op].value = v;
2126 for (op = 0; op < 3; ++op) {
2127 if (ri->_ops[op] == old)
2135 ir_instr_delete(instr);
2140 /***********************************************************************
2141 *IR Temp allocation code
2142 * Propagating value life ranges by walking through the function backwards
2143 * until no more changes are made.
2144 * In theory this should happen once more than once for every nested loop
2146 * Though this implementation might run an additional time for if nests.
2149 /* Enumerate instructions used by value's life-ranges
2151 static void ir_block_enumerate(ir_block *self, size_t *_eid)
2155 for (i = 0; i < vec_size(self->instr); ++i)
2157 self->instr[i]->eid = eid++;
2162 /* Enumerate blocks and instructions.
2163 * The block-enumeration is unordered!
2164 * We do not really use the block enumreation, however
2165 * the instruction enumeration is important for life-ranges.
2167 void ir_function_enumerate(ir_function *self)
2170 size_t instruction_id = 0;
2171 for (i = 0; i < vec_size(self->blocks); ++i)
2173 self->blocks[i]->eid = i;
2174 self->blocks[i]->run_id = 0;
2175 ir_block_enumerate(self->blocks[i], &instruction_id);
2179 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
2180 bool ir_function_calculate_liferanges(ir_function *self)
2188 for (i = 0; i != vec_size(self->blocks); ++i)
2190 if (self->blocks[i]->is_return)
2192 vec_free(self->blocks[i]->living);
2193 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
2198 if (vec_size(self->blocks)) {
2199 ir_block *block = self->blocks[0];
2200 for (i = 0; i < vec_size(block->living); ++i) {
2201 ir_value *v = block->living[i];
2202 if (v->store != store_local)
2204 if ((v->members[0] && v->members[1] && v->members[2])) {
2205 /* all vector members have been accessed - only treat this as uninitialized
2206 * if any of them is also uninitialized.
2208 if (!vec_ir_value_find(block->living, v->members[0], NULL) &&
2209 !vec_ir_value_find(block->living, v->members[1], NULL) &&
2210 !vec_ir_value_find(block->living, v->members[2], NULL))
2216 /* A member is only uninitialized if the whole vector is also uninitialized */
2217 if (!vec_ir_value_find(block->living, v->memberof, NULL))
2220 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2221 "variable `%s` may be used uninitialized in this function", v->name))
2230 /* Local-value allocator
2231 * After finishing creating the liferange of all values used in a function
2232 * we can allocate their global-positions.
2233 * This is the counterpart to register-allocation in register machines.
2240 } function_allocator;
2242 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
2245 size_t vsize = type_sizeof[var->vtype];
2247 slot = ir_value_var("reg", store_global, var->vtype);
2251 if (!ir_value_life_merge_into(slot, var))
2254 vec_push(alloc->locals, slot);
2255 vec_push(alloc->sizes, vsize);
2256 vec_push(alloc->unique, var->unique_life);
2261 ir_value_delete(slot);
2265 bool ir_function_allocate_locals(ir_function *self)
2274 function_allocator alloc;
2276 if (!vec_size(self->locals) && !vec_size(self->values))
2279 alloc.locals = NULL;
2281 alloc.positions = NULL;
2282 alloc.unique = NULL;
2284 for (i = 0; i < vec_size(self->locals); ++i)
2286 if (!OPTS_OPTIMIZATION(OPTIM_LOCALTEMPS))
2287 self->locals[i]->unique_life = true;
2288 if (!function_allocator_alloc(&alloc, self->locals[i]))
2292 /* Allocate a slot for any value that still exists */
2293 for (i = 0; i < vec_size(self->values); ++i)
2295 v = self->values[i];
2297 if (!vec_size(v->life))
2300 for (a = 0; a < vec_size(alloc.locals); ++a)
2302 /* if it's reserved for a unique liferange: skip */
2303 if (alloc.unique[a])
2306 slot = alloc.locals[a];
2308 /* never resize parameters
2309 * will be required later when overlapping temps + locals
2311 if (a < vec_size(self->params) &&
2312 alloc.sizes[a] < type_sizeof[v->vtype])
2317 if (ir_values_overlap(v, slot))
2320 if (!ir_value_life_merge_into(slot, v))
2323 /* adjust size for this slot */
2324 if (alloc.sizes[a] < type_sizeof[v->vtype])
2325 alloc.sizes[a] = type_sizeof[v->vtype];
2327 self->values[i]->code.local = a;
2330 if (a >= vec_size(alloc.locals)) {
2331 self->values[i]->code.local = vec_size(alloc.locals);
2332 if (!function_allocator_alloc(&alloc, v))
2341 /* Adjust slot positions based on sizes */
2342 vec_push(alloc.positions, 0);
2344 if (vec_size(alloc.sizes))
2345 pos = alloc.positions[0] + alloc.sizes[0];
2348 for (i = 1; i < vec_size(alloc.sizes); ++i)
2350 pos = alloc.positions[i-1] + alloc.sizes[i-1];
2351 vec_push(alloc.positions, pos);
2354 self->allocated_locals = pos + vec_last(alloc.sizes);
2356 /* Locals need to know their new position */
2357 for (i = 0; i < vec_size(self->locals); ++i) {
2358 self->locals[i]->code.local = alloc.positions[i];
2360 /* Take over the actual slot positions on values */
2361 for (i = 0; i < vec_size(self->values); ++i) {
2362 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
2370 for (i = 0; i < vec_size(alloc.locals); ++i)
2371 ir_value_delete(alloc.locals[i]);
2372 vec_free(alloc.locals);
2373 vec_free(alloc.sizes);
2374 vec_free(alloc.positions);
2378 /* Get information about which operand
2379 * is read from, or written to.
2381 static void ir_op_read_write(int op, size_t *read, size_t *write)
2401 case INSTR_STOREP_F:
2402 case INSTR_STOREP_V:
2403 case INSTR_STOREP_S:
2404 case INSTR_STOREP_ENT:
2405 case INSTR_STOREP_FLD:
2406 case INSTR_STOREP_FNC:
2417 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2420 bool changed = false;
2422 for (i = 0; i != vec_size(self->living); ++i)
2424 tempbool = ir_value_life_merge(self->living[i], eid);
2427 irerror(self->context, "block_living_add_instr() value instruction added %s: %i", self->living[i]->_name, (int)eid);
2429 changed = changed || tempbool;
2434 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
2440 /* values which have been read in a previous iteration are now
2441 * in the "living" array even if the previous block doesn't use them.
2442 * So we have to remove whatever does not exist in the previous block.
2443 * They will be re-added on-read, but the liferange merge won't cause
2445 for (i = 0; i < vec_size(self->living); ++i)
2447 if (!vec_ir_value_find(prev->living, self->living[i], NULL)) {
2448 vec_remove(self->living, i, 1);
2454 /* Whatever the previous block still has in its living set
2455 * must now be added to ours as well.
2457 for (i = 0; i < vec_size(prev->living); ++i)
2459 if (vec_ir_value_find(self->living, prev->living[i], NULL))
2461 vec_push(self->living, prev->living[i]);
2463 irerror(self->contextt from prev: %s", self->label, prev->living[i]->_name);
2469 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2475 /* bitmasks which operands are read from or written to */
2477 char dbg_ind[16] = { '#', '0' };
2482 if (!ir_block_life_prop_previous(self, prev, changed))
2486 i = vec_size(self->instr);
2489 instr = self->instr[i];
2491 /* PHI operands are always read operands */
2492 for (p = 0; p < vec_size(instr->phi); ++p)
2494 value = instr->phi[p].value;
2495 if (!vec_ir_value_find(self->living, value, NULL))
2496 vec_push(self->living, value);
2499 /* call params are read operands too */
2500 for (p = 0; p < vec_size(instr->params); ++p)
2502 value = instr->params[p];
2503 if (!vec_ir_value_find(self->living, value, NULL))
2504 vec_push(self->living, value);
2507 /* See which operands are read and write operands */
2508 ir_op_read_write(instr->opcode, &read, &write);
2510 if (instr->opcode == INSTR_MUL_VF)
2512 /* the float source will get an additional lifetime */
2513 tempbool = ir_value_life_merge(instr->_ops[2], instr->eid+1);
2514 *changed = *changed || tempbool;
2516 else if (instr->opcode == INSTR_MUL_FV)
2518 /* the float source will get an additional lifetime */
2519 tempbool = ir_value_life_merge(instr->_ops[1], instr->eid+1);
2520 *changed = *changed || tempbool;
2523 /* Go through the 3 main operands */
2524 for (o = 0; o < 3; ++o)
2526 if (!instr->_ops[o]) /* no such operand */
2529 value = instr->_ops[o];
2531 /* We only care about locals */
2532 /* we also calculate parameter liferanges so that locals
2533 * can take up parameter slots */
2534 if (value->store != store_value &&
2535 value->store != store_local &&
2536 value->store != store_param)
2542 if (!vec_ir_value_find(self->living, value, NULL))
2543 vec_push(self->living, value);
2546 /* write operands */
2547 /* When we write to a local, we consider it "dead" for the
2548 * remaining upper part of the function, since in SSA a value
2549 * can only be written once (== created)
2554 bool in_living = vec_ir_value_find(self->living, value, &idx);
2557 /* If the value isn't alive it hasn't been read before... */
2558 /* TODO: See if the warning can be emitted during parsing or AST processing
2559 * otherwise have warning printed here.
2560 * IF printing a warning here: include filecontext_t,
2561 * and make sure it's only printed once
2562 * since this function is run multiple times.
2564 /* For now: debug info: */
2565 /* con_err( "Value only written %s\n", value->name); */
2566 tempbool = ir_value_life_merge(value, instr->eid);
2567 *changed = *changed || tempbool;
2569 ir_instr_dump(instr, dbg_ind, printf);
2573 /* since 'living' won't contain it
2574 * anymore, merge the value, since
2577 tempbool = ir_value_life_merge(value, instr->eid);
2580 con_err( "value added id %s %i\n", value->name, (int)instr->eid);
2582 *changed = *changed || tempbool;
2584 vec_remove(self->living, idx, 1);
2589 tempbool = ir_block_living_add_instr(self, instr->eid);
2590 /*con_err( "living added values\n");*/
2591 *changed = *changed || tempbool;
2595 if (self->run_id == self->owner->run_id)
2598 self->run_id = self->owner->run_id;
2600 for (i = 0; i < vec_size(self->entries); ++i)
2602 ir_block *entry = self->entries[i];
2603 ir_block_life_propagate(entry, self, changed);
2609 /***********************************************************************
2612 * Since the IR has the convention of putting 'write' operands
2613 * at the beginning, we have to rotate the operands of instructions
2614 * properly in order to generate valid QCVM code.
2616 * Having destinations at a fixed position is more convenient. In QC
2617 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2618 * read from from OPA, and store to OPB rather than OPC. Which is
2619 * partially the reason why the implementation of these instructions
2620 * in darkplaces has been delayed for so long.
2622 * Breaking conventions is annoying...
2624 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2626 static bool gen_global_field(ir_value *global)
2628 if (global->hasvalue)
2630 ir_value *fld = global->constval.vpointer;
2632 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2636 /* copy the field's value */
2637 ir_value_code_setaddr(global, vec_size(code_globals));
2638 vec_push(code_globals, fld->code.fieldaddr);
2639 if (global->fieldtype == TYPE_VECTOR) {
2640 vec_push(code_globals, fld->code.fieldaddr+1);
2641 vec_push(code_globals, fld->code.fieldaddr+2);
2646 ir_value_code_setaddr(global, vec_size(code_globals));
2647 vec_push(code_globals, 0);
2648 if (global->fieldtype == TYPE_VECTOR) {
2649 vec_push(code_globals, 0);
2650 vec_push(code_globals, 0);
2653 if (global->code.globaladdr < 0)
2658 static bool gen_global_pointer(ir_value *global)
2660 if (global->hasvalue)
2662 ir_value *target = global->constval.vpointer;
2664 irerror(global->context, "Invalid pointer constant: %s", global->name);
2665 /* NULL pointers are pointing to the NULL constant, which also
2666 * sits at address 0, but still has an ir_value for itself.
2671 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2672 * void() foo; <- proto
2673 * void() *fooptr = &foo;
2674 * void() foo = { code }
2676 if (!target->code.globaladdr) {
2677 /* FIXME: Check for the constant nullptr ir_value!
2678 * because then code.globaladdr being 0 is valid.
2680 irerror(global->context, "FIXME: Relocation support");
2684 ir_value_code_setaddr(global, vec_size(code_globals));
2685 vec_push(code_globals, target->code.globaladdr);
2689 ir_value_code_setaddr(global, vec_size(code_globals));
2690 vec_push(code_globals, 0);
2692 if (global->code.globaladdr < 0)
2697 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2699 prog_section_statement stmt;
2708 block->generated = true;
2709 block->code_start = vec_size(code_statements);
2710 for (i = 0; i < vec_size(block->instr); ++i)
2712 instr = block->instr[i];
2714 if (instr->opcode == VINSTR_PHI) {
2715 irerror(block->context, "cannot generate virtual instruction (phi)");
2719 if (instr->opcode == VINSTR_JUMP) {
2720 target = instr->bops[0];
2721 /* for uncoditional jumps, if the target hasn't been generated
2722 * yet, we generate them right here.
2724 if (!target->generated) {
2729 /* otherwise we generate a jump instruction */
2730 stmt.opcode = INSTR_GOTO;
2731 stmt.o1.s1 = (target->code_start) - vec_size(code_statements);
2734 if (stmt.o1.s1 != 1)
2735 code_push_statement(&stmt, instr->context.line);
2737 /* no further instructions can be in this block */
2741 if (instr->opcode == VINSTR_COND) {
2742 ontrue = instr->bops[0];
2743 onfalse = instr->bops[1];
2744 /* TODO: have the AST signal which block should
2745 * come first: eg. optimize IFs without ELSE...
2748 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2752 if (ontrue->generated) {
2753 stmt.opcode = INSTR_IF;
2754 stmt.o2.s1 = (ontrue->code_start) - vec_size(code_statements);
2755 if (stmt.o2.s1 != 1)
2756 code_push_statement(&stmt, instr->context.line);
2758 if (onfalse->generated) {
2759 stmt.opcode = INSTR_IFNOT;
2760 stmt.o2.s1 = (onfalse->code_start) - vec_size(code_statements);
2761 if (stmt.o2.s1 != 1)
2762 code_push_statement(&stmt, instr->context.line);
2764 if (!ontrue->generated) {
2765 if (onfalse->generated) {
2770 if (!onfalse->generated) {
2771 if (ontrue->generated) {
2776 /* neither ontrue nor onfalse exist */
2777 stmt.opcode = INSTR_IFNOT;
2778 if (!instr->likely) {
2779 /* Honor the likelyhood hint */
2780 ir_block *tmp = onfalse;
2781 stmt.opcode = INSTR_IF;
2785 stidx = vec_size(code_statements);
2786 code_push_statement(&stmt, instr->context.line);
2787 /* on false we jump, so add ontrue-path */
2788 if (!gen_blocks_recursive(func, ontrue))
2790 /* fixup the jump address */
2791 code_statements[stidx].o2.s1 = vec_size(code_statements) - stidx;
2792 /* generate onfalse path */
2793 if (onfalse->generated) {
2794 /* fixup the jump address */
2795 code_statements[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2796 if (code_statements[stidx].o2.s1 == 1) {
2797 code_statements[stidx] = code_statements[stidx+1];
2798 if (code_statements[stidx].o1.s1 < 0)
2799 code_statements[stidx].o1.s1++;
2800 code_pop_statement();
2802 stmt.opcode = vec_last(code_statements).opcode;
2803 if (stmt.opcode == INSTR_GOTO ||
2804 stmt.opcode == INSTR_IF ||
2805 stmt.opcode == INSTR_IFNOT ||
2806 stmt.opcode == INSTR_RETURN ||
2807 stmt.opcode == INSTR_DONE)
2809 /* no use jumping from here */
2812 /* may have been generated in the previous recursive call */
2813 stmt.opcode = INSTR_GOTO;
2814 stmt.o1.s1 = (onfalse->code_start) - vec_size(code_statements);
2817 if (stmt.o1.s1 != 1)
2818 code_push_statement(&stmt, instr->context.line);
2821 else if (code_statements[stidx].o2.s1 == 1) {
2822 code_statements[stidx] = code_statements[stidx+1];
2823 if (code_statements[stidx].o1.s1 < 0)
2824 code_statements[stidx].o1.s1++;
2825 code_pop_statement();
2827 /* if not, generate now */
2832 if ( (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8)
2833 || instr->opcode == VINSTR_NRCALL)
2835 /* Trivial call translation:
2836 * copy all params to OFS_PARM*
2837 * if the output's storetype is not store_return,
2838 * add append a STORE instruction!
2840 * NOTES on how to do it better without much trouble:
2841 * -) The liferanges!
2842 * Simply check the liferange of all parameters for
2843 * other CALLs. For each param with no CALL in its
2844 * liferange, we can store it in an OFS_PARM at
2845 * generation already. This would even include later
2846 * reuse.... probably... :)
2851 first = vec_size(instr->params);
2854 for (p = 0; p < first; ++p)
2856 ir_value *param = instr->params[p];
2858 stmt.opcode = INSTR_STORE_F;
2861 if (param->vtype == TYPE_FIELD)
2862 stmt.opcode = field_store_instr[param->fieldtype];
2864 stmt.opcode = type_store_instr[param->vtype];
2865 stmt.o1.u1 = ir_value_code_addr(param);
2866 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2867 code_push_statement(&stmt, instr->context.line);
2869 /* Now handle extparams */
2870 first = vec_size(instr->params);
2871 for (; p < first; ++p)
2873 ir_builder *ir = func->owner;
2874 ir_value *param = instr->params[p];
2875 ir_value *targetparam;
2877 if (p-8 >= vec_size(ir->extparams))
2878 ir_gen_extparam(ir);
2880 targetparam = ir->extparams[p-8];
2882 stmt.opcode = INSTR_STORE_F;
2885 if (param->vtype == TYPE_FIELD)
2886 stmt.opcode = field_store_instr[param->fieldtype];
2888 stmt.opcode = type_store_instr[param->vtype];
2889 stmt.o1.u1 = ir_value_code_addr(param);
2890 stmt.o2.u1 = ir_value_code_addr(targetparam);
2891 code_push_statement(&stmt, instr->context.line);
2894 stmt.opcode = INSTR_CALL0 + vec_size(instr->params);
2895 if (stmt.opcode > INSTR_CALL8)
2896 stmt.opcode = INSTR_CALL8;
2897 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2900 code_push_statement(&stmt, instr->context.line);
2902 retvalue = instr->_ops[0];
2903 if (retvalue && retvalue->store != store_return && vec_size(retvalue->life))
2905 /* not to be kept in OFS_RETURN */
2906 if (retvalue->vtype == TYPE_FIELD)
2907 stmt.opcode = field_store_instr[retvalue->vtype];
2909 stmt.opcode = type_store_instr[retvalue->vtype];
2910 stmt.o1.u1 = OFS_RETURN;
2911 stmt.o2.u1 = ir_value_code_addr(retvalue);
2913 code_push_statement(&stmt, instr->context.line);
2918 if (instr->opcode == INSTR_STATE) {
2919 irerror(block->context, "TODO: state instruction");
2923 stmt.opcode = instr->opcode;
2928 /* This is the general order of operands */
2930 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2933 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2936 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2938 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2940 stmt.o1.u1 = stmt.o3.u1;
2943 else if ((stmt.opcode >= INSTR_STORE_F &&
2944 stmt.opcode <= INSTR_STORE_FNC) ||
2945 (stmt.opcode >= INSTR_STOREP_F &&
2946 stmt.opcode <= INSTR_STOREP_FNC))
2948 /* 2-operand instructions with A -> B */
2949 stmt.o2.u1 = stmt.o3.u1;
2952 /* tiny optimization, don't output
2955 if (stmt.o2.u1 == stmt.o1.u1 &&
2956 OPTS_OPTIMIZATION(OPTIM_PEEPHOLE))
2958 ++opts_optimizationcount[OPTIM_PEEPHOLE];
2963 code_push_statement(&stmt, instr->context.line);
2968 static bool gen_function_code(ir_function *self)
2971 prog_section_statement stmt;
2973 /* Starting from entry point, we generate blocks "as they come"
2974 * for now. Dead blocks will not be translated obviously.
2976 if (!vec_size(self->blocks)) {
2977 irerror(self->context, "Function '%s' declared without body.", self->name);
2981 block = self->blocks[0];
2982 if (block->generated)
2985 if (!gen_blocks_recursive(self, block)) {
2986 irerror(self->context, "failed to generate blocks for '%s'", self->name);
2990 /* code_write and qcvm -disasm need to know that the function ends here */
2991 stmt.opcode = INSTR_DONE;
2995 code_push_statement(&stmt, vec_last(code_linenums));
2999 static qcint ir_builder_filestring(ir_builder *ir, const char *filename)
3001 /* NOTE: filename pointers are copied, we never strdup them,
3002 * thus we can use pointer-comparison to find the string.
3007 for (i = 0; i < vec_size(ir->filenames); ++i) {
3008 if (ir->filenames[i] == filename)
3009 return ir->filestrings[i];
3012 str = code_genstring(filename);
3013 vec_push(ir->filenames, filename);
3014 vec_push(ir->filestrings, str);
3018 static bool gen_global_function(ir_builder *ir, ir_value *global)
3020 prog_section_function fun;
3024 #ifndef NEW_ALLOC_STRAT
3025 size_t local_var_end;
3028 if (!global->hasvalue || (!global->constval.vfunc))
3030 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
3034 irfun = global->constval.vfunc;
3036 fun.name = global->code.name;
3037 fun.file = ir_builder_filestring(ir, global->context.file);
3038 fun.profile = 0; /* always 0 */
3039 fun.nargs = vec_size(irfun->params);
3043 for (i = 0;i < 8; ++i) {
3044 if ((int32_t)i >= fun.nargs)
3047 fun.argsize[i] = type_sizeof[irfun->params[i]];
3050 fun.firstlocal = vec_size(code_globals);
3052 #ifndef NEW_ALLOC_STRAT
3053 local_var_end = fun.firstlocal;
3054 for (i = 0; i < vec_size(irfun->locals); ++i) {
3055 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
3056 irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
3060 if (vec_size(irfun->locals)) {
3061 ir_value *last = vec_last(irfun->locals);
3062 local_var_end = last->code.globaladdr;
3063 if (last->vtype == TYPE_FIELD && last->fieldtype == TYPE_VECTOR)
3064 local_var_end += type_sizeof[TYPE_VECTOR];
3066 local_var_end += type_sizeof[last->vtype];
3068 for (i = 0; i < vec_size(irfun->values); ++i)
3070 /* generate code.globaladdr for ssa values */
3071 ir_value *v = irfun->values[i];
3072 ir_value_code_setaddr(v, local_var_end + v->code.local);
3074 for (i = 0; i < irfun->allocated_locals; ++i) {
3075 /* fill the locals with zeros */
3076 vec_push(code_globals, 0);
3079 fun.locals = vec_size(code_globals) - fun.firstlocal;
3081 fun.locals = irfun->allocated_locals;
3082 for (i = 0; i < vec_size(irfun->locals); ++i) {
3083 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
3084 irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
3087 ir_value_code_setaddr(irfun->locals[i], fun.firstlocal + irfun->locals[i]->code.local);
3089 for (i = vec_size(code_globals) - fun.firstlocal; i < fun.locals; ++i) {
3090 vec_push(code_globals, 0);
3092 for (i = 0; i < vec_size(irfun->values); ++i)
3094 /* generate code.globaladdr for ssa values */
3095 ir_value *v = irfun->values[i];
3096 ir_value_code_setaddr(v, fun.firstlocal + v->code.local);
3101 fun.entry = irfun->builtin+1;
3103 irfun->code_function_def = vec_size(code_functions);
3104 fun.entry = vec_size(code_statements);
3107 vec_push(code_functions, fun);
3111 static void ir_gen_extparam(ir_builder *ir)
3113 prog_section_def def;
3117 snprintf(name, sizeof(name), "EXTPARM#%i", (int)(vec_size(ir->extparams)+8));
3118 global = ir_value_var(name, store_global, TYPE_VECTOR);
3120 def.name = code_genstring(name);
3121 def.type = TYPE_VECTOR;
3122 def.offset = vec_size(code_globals);
3124 vec_push(code_defs, def);
3125 ir_value_code_setaddr(global, def.offset);
3126 vec_push(code_globals, 0);
3127 vec_push(code_globals, 0);
3128 vec_push(code_globals, 0);
3130 vec_push(ir->extparams, global);
3133 static bool gen_function_extparam_copy(ir_function *self)
3135 size_t i, ext, numparams;
3137 ir_builder *ir = self->owner;
3139 prog_section_statement stmt;
3141 numparams = vec_size(self->params);
3145 stmt.opcode = INSTR_STORE_F;
3147 for (i = 8; i < numparams; ++i) {
3149 if (ext >= vec_size(ir->extparams))
3150 ir_gen_extparam(ir);
3152 ep = ir->extparams[ext];
3154 stmt.opcode = type_store_instr[self->locals[i]->vtype];
3155 if (self->locals[i]->vtype == TYPE_FIELD &&
3156 self->locals[i]->fieldtype == TYPE_VECTOR)
3158 stmt.opcode = INSTR_STORE_V;
3160 stmt.o1.u1 = ir_value_code_addr(ep);
3161 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3162 code_push_statement(&stmt, self->context.line);
3168 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
3170 prog_section_function *fundef;
3175 irfun = global->constval.vfunc;
3177 if (global->cvq == CV_NONE) {
3178 irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
3179 "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
3181 /* this was a function pointer, don't generate code for those */
3188 if (irfun->code_function_def < 0) {
3189 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
3192 fundef = &code_functions[irfun->code_function_def];
3194 fundef->entry = vec_size(code_statements);
3195 if (!gen_function_extparam_copy(irfun)) {
3196 irerror(irfun->context, "Failed to generate extparam-copy code for function %s", irfun->name);
3199 if (!gen_function_code(irfun)) {
3200 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
3206 static void gen_vector_defs(prog_section_def def, const char *name)
3211 if (!name || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3214 def.type = TYPE_FLOAT;
3218 component = (char*)mem_a(len+3);
3219 memcpy(component, name, len);
3221 component[len-0] = 0;
3222 component[len-2] = '_';
3224 component[len-1] = 'x';
3226 for (i = 0; i < 3; ++i) {
3227 def.name = code_genstring(component);
3228 vec_push(code_defs, def);
3234 static void gen_vector_fields(prog_section_field fld, const char *name)
3239 if (!name || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3242 fld.type = TYPE_FLOAT;
3246 component = (char*)mem_a(len+3);
3247 memcpy(component, name, len);
3249 component[len-0] = 0;
3250 component[len-2] = '_';
3252 component[len-1] = 'x';
3254 for (i = 0; i < 3; ++i) {
3255 fld.name = code_genstring(component);
3256 vec_push(code_fields, fld);
3262 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
3266 prog_section_def def;
3268 def.type = global->vtype;
3269 def.offset = vec_size(code_globals);
3272 if (global->name[0] == '#') {
3273 if (!self->str_immediate)
3274 self->str_immediate = code_genstring("IMMEDIATE");
3275 def.name = global->code.name = self->str_immediate;
3278 def.name = global->code.name = code_genstring(global->name);
3283 switch (global->vtype)
3286 if (!strcmp(global->name, "end_sys_globals")) {
3287 /* TODO: remember this point... all the defs before this one
3288 * should be checksummed and added to progdefs.h when we generate it.
3291 else if (!strcmp(global->name, "end_sys_fields")) {
3292 /* TODO: same as above but for entity-fields rather than globsl
3296 irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3298 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3299 * the system fields actually go? Though the engine knows this anyway...
3300 * Maybe this could be an -foption
3301 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3303 ir_value_code_setaddr(global, vec_size(code_globals));
3304 vec_push(code_globals, 0);
3306 vec_push(code_defs, def);
3309 vec_push(code_defs, def);
3310 return gen_global_pointer(global);
3312 vec_push(code_defs, def);
3313 gen_vector_defs(def, global->name);
3314 return gen_global_field(global);
3319 ir_value_code_setaddr(global, vec_size(code_globals));
3320 if (global->hasvalue) {
3321 iptr = (int32_t*)&global->constval.ivec[0];
3322 vec_push(code_globals, *iptr);
3324 vec_push(code_globals, 0);
3326 if (!islocal && global->cvq != CV_CONST)
3327 def.type |= DEF_SAVEGLOBAL;
3328 vec_push(code_defs, def);
3330 return global->code.globaladdr >= 0;
3334 ir_value_code_setaddr(global, vec_size(code_globals));
3335 if (global->hasvalue) {
3336 vec_push(code_globals, code_genstring(global->constval.vstring));
3338 vec_push(code_globals, 0);
3340 if (!islocal && global->cvq != CV_CONST)
3341 def.type |= DEF_SAVEGLOBAL;
3342 vec_push(code_defs, def);
3343 return global->code.globaladdr >= 0;
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;
3368 vec_push(code_defs, def);
3369 def.type &= ~DEF_SAVEGLOBAL;
3370 gen_vector_defs(def, global->name);
3371 return global->code.globaladdr >= 0;
3374 ir_value_code_setaddr(global, vec_size(code_globals));
3375 if (!global->hasvalue) {
3376 vec_push(code_globals, 0);
3377 if (global->code.globaladdr < 0)
3380 vec_push(code_globals, vec_size(code_functions));
3381 if (!gen_global_function(self, global))
3384 if (!islocal && global->cvq != CV_CONST)
3385 def.type |= DEF_SAVEGLOBAL;
3386 vec_push(code_defs, def);
3389 /* assume biggest type */
3390 ir_value_code_setaddr(global, vec_size(code_globals));
3391 vec_push(code_globals, 0);
3392 for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
3393 vec_push(code_globals, 0);
3396 /* refuse to create 'void' type or any other fancy business. */
3397 irerror(global->context, "Invalid type for global variable `%s`: %s",
3398 global->name, type_name[global->vtype]);
3403 static void ir_builder_prepare_field(ir_value *field)
3405 field->code.fieldaddr = code_alloc_field(type_sizeof[field->fieldtype]);
3408 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3410 prog_section_def def;
3411 prog_section_field fld;
3415 def.type = (uint16_t)field->vtype;
3416 def.offset = (uint16_t)vec_size(code_globals);
3418 /* create a global named the same as the field */
3419 if (opts.standard == COMPILER_GMQCC) {
3420 /* in our standard, the global gets a dot prefix */
3421 size_t len = strlen(field->name);
3424 /* we really don't want to have to allocate this, and 1024
3425 * bytes is more than enough for a variable/field name
3427 if (len+2 >= sizeof(name)) {
3428 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
3433 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
3436 def.name = code_genstring(name);
3437 fld.name = def.name + 1; /* we reuse that string table entry */
3439 /* in plain QC, there cannot be a global with the same name,
3440 * and so we also name the global the same.
3441 * FIXME: fteqcc should create a global as well
3442 * check if it actually uses the same name. Probably does
3444 def.name = code_genstring(field->name);
3445 fld.name = def.name;
3448 field->code.name = def.name;
3450 vec_push(code_defs, def);
3452 fld.type = field->fieldtype;
3454 if (fld.type == TYPE_VOID) {
3455 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
3459 fld.offset = field->code.fieldaddr;
3461 vec_push(code_fields, fld);
3463 ir_value_code_setaddr(field, vec_size(code_globals));
3464 vec_push(code_globals, fld.offset);
3465 if (fld.type == TYPE_VECTOR) {
3466 vec_push(code_globals, fld.offset+1);
3467 vec_push(code_globals, fld.offset+2);
3470 if (field->fieldtype == TYPE_VECTOR) {
3471 gen_vector_defs(def, field->name);
3472 gen_vector_fields(fld, field->name);
3475 return field->code.globaladdr >= 0;
3478 bool ir_builder_generate(ir_builder *self, const char *filename)
3480 prog_section_statement stmt;
3482 char *lnofile = NULL;
3486 for (i = 0; i < vec_size(self->fields); ++i)
3488 ir_builder_prepare_field(self->fields[i]);
3491 for (i = 0; i < vec_size(self->globals); ++i)
3493 if (!ir_builder_gen_global(self, self->globals[i], false)) {
3498 for (i = 0; i < vec_size(self->fields); ++i)
3500 if (!ir_builder_gen_field(self, self->fields[i])) {
3505 /* generate function code */
3506 for (i = 0; i < vec_size(self->globals); ++i)
3508 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3509 if (!gen_global_function_code(self, self->globals[i])) {
3515 if (vec_size(code_globals) >= 65536) {
3516 irerror(vec_last(self->globals)->context, "This progs file would require more globals than the metadata can handle. Bailing out.");
3520 /* DP errors if the last instruction is not an INSTR_DONE. */
3521 if (vec_last(code_statements).opcode != INSTR_DONE)
3523 stmt.opcode = INSTR_DONE;
3527 code_push_statement(&stmt, vec_last(code_linenums));
3533 if (vec_size(code_statements) != vec_size(code_linenums)) {
3534 con_err("Linecounter wrong: %lu != %lu\n",
3535 (unsigned long)vec_size(code_statements),
3536 (unsigned long)vec_size(code_linenums));
3537 } else if (OPTS_FLAG(LNO)) {
3539 size_t filelen = strlen(filename);
3541 memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
3542 dot = strrchr(lnofile, '.');
3546 vec_shrinkto(lnofile, dot - lnofile);
3548 memcpy(vec_add(lnofile, 5), ".lno", 5);
3552 con_out("writing '%s' and '%s'...\n", filename, lnofile);
3554 con_out("writing '%s'\n", filename);
3555 if (!code_write(filename, lnofile)) {
3563 /***********************************************************************
3564 *IR DEBUG Dump functions...
3567 #define IND_BUFSZ 1024
3570 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
3573 const char *qc_opname(int op)
3575 if (op < 0) return "<INVALID>";
3576 if (op < (int)( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
3577 return asm_instr[op].m;
3579 case VINSTR_PHI: return "PHI";
3580 case VINSTR_JUMP: return "JUMP";
3581 case VINSTR_COND: return "COND";
3582 default: return "<UNK>";
3586 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
3589 char indent[IND_BUFSZ];
3593 oprintf("module %s\n", b->name);
3594 for (i = 0; i < vec_size(b->globals); ++i)
3597 if (b->globals[i]->hasvalue)
3598 oprintf("%s = ", b->globals[i]->name);
3599 ir_value_dump(b->globals[i], oprintf);
3602 for (i = 0; i < vec_size(b->functions); ++i)
3603 ir_function_dump(b->functions[i], indent, oprintf);
3604 oprintf("endmodule %s\n", b->name);
3607 void ir_function_dump(ir_function *f, char *ind,
3608 int (*oprintf)(const char*, ...))
3611 if (f->builtin != 0) {
3612 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
3615 oprintf("%sfunction %s\n", ind, f->name);
3616 strncat(ind, "\t", IND_BUFSZ);
3617 if (vec_size(f->locals))
3619 oprintf("%s%i locals:\n", ind, (int)vec_size(f->locals));
3620 for (i = 0; i < vec_size(f->locals); ++i) {
3621 oprintf("%s\t", ind);
3622 ir_value_dump(f->locals[i], oprintf);
3626 oprintf("%sliferanges:\n", ind);
3627 for (i = 0; i < vec_size(f->locals); ++i) {
3629 ir_value *v = f->locals[i];
3630 oprintf("%s\t%s: %s@%i ", ind, v->name, (v->unique_life ? "unique " : ""), (int)v->code.local);
3631 for (l = 0; l < vec_size(v->life); ++l) {
3632 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3636 for (i = 0; i < vec_size(f->values); ++i) {
3638 ir_value *v = f->values[i];
3639 oprintf("%s\t%s: @%i ", ind, v->name, (int)v->code.local);
3640 for (l = 0; l < vec_size(v->life); ++l) {
3641 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3645 if (vec_size(f->blocks))
3647 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
3648 for (i = 0; i < vec_size(f->blocks); ++i) {
3649 if (f->blocks[i]->run_id != f->run_id) {
3650 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
3652 ir_block_dump(f->blocks[i], ind, oprintf);
3656 ind[strlen(ind)-1] = 0;
3657 oprintf("%sendfunction %s\n", ind, f->name);
3660 void ir_block_dump(ir_block* b, char *ind,
3661 int (*oprintf)(const char*, ...))
3664 oprintf("%s:%s\n", ind, b->label);
3665 strncat(ind, "\t", IND_BUFSZ);
3667 for (i = 0; i < vec_size(b->instr); ++i)
3668 ir_instr_dump(b->instr[i], ind, oprintf);
3669 ind[strlen(ind)-1] = 0;
3672 void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
3675 oprintf("%s <- phi ", in->_ops[0]->name);
3676 for (i = 0; i < vec_size(in->phi); ++i)
3678 oprintf("([%s] : %s) ", in->phi[i].from->label,
3679 in->phi[i].value->name);
3684 void ir_instr_dump(ir_instr *in, char *ind,
3685 int (*oprintf)(const char*, ...))
3688 const char *comma = NULL;
3690 oprintf("%s (%i) ", ind, (int)in->eid);
3692 if (in->opcode == VINSTR_PHI) {
3693 dump_phi(in, oprintf);
3697 strncat(ind, "\t", IND_BUFSZ);
3699 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3700 ir_value_dump(in->_ops[0], oprintf);
3701 if (in->_ops[1] || in->_ops[2])
3704 if (in->opcode == INSTR_CALL0 || in->opcode == VINSTR_NRCALL) {
3705 oprintf("CALL%i\t", vec_size(in->params));
3707 oprintf("%s\t", qc_opname(in->opcode));
3709 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3710 ir_value_dump(in->_ops[0], oprintf);
3715 for (i = 1; i != 3; ++i) {
3719 ir_value_dump(in->_ops[i], oprintf);
3727 oprintf("[%s]", in->bops[0]->label);
3731 oprintf("%s[%s]", comma, in->bops[1]->label);
3732 if (vec_size(in->params)) {
3733 oprintf("\tparams: ");
3734 for (i = 0; i != vec_size(in->params); ++i) {
3735 oprintf("%s, ", in->params[i]->name);
3739 ind[strlen(ind)-1] = 0;
3742 void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
3745 for (; *str; ++str) {
3747 case '\n': oprintf("\\n"); break;
3748 case '\r': oprintf("\\r"); break;
3749 case '\t': oprintf("\\t"); break;
3750 case '\v': oprintf("\\v"); break;
3751 case '\f': oprintf("\\f"); break;
3752 case '\b': oprintf("\\b"); break;
3753 case '\a': oprintf("\\a"); break;
3754 case '\\': oprintf("\\\\"); break;
3755 case '"': oprintf("\\\""); break;
3756 default: oprintf("%c", *str); break;
3762 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3771 oprintf("fn:%s", v->name);
3774 oprintf("%g", v->constval.vfloat);
3777 oprintf("'%g %g %g'",
3780 v->constval.vvec.z);
3783 oprintf("(entity)");
3786 ir_value_dump_string(v->constval.vstring, oprintf);
3790 oprintf("%i", v->constval.vint);
3795 v->constval.vpointer->name);
3799 oprintf("%s", v->name);
3803 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
3806 oprintf("Life of %12s:", self->name);
3807 for (i = 0; i < vec_size(self->life); ++i)
3809 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);