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->max_locals = 0;
290 self->str_immediate = 0;
292 if (!ir_builder_set_name(self, modulename)) {
300 void ir_builder_delete(ir_builder* self)
303 util_htdel(self->htglobals);
304 util_htdel(self->htfields);
305 util_htdel(self->htfunctions);
306 mem_d((void*)self->name);
307 for (i = 0; i != vec_size(self->functions); ++i) {
308 ir_function_delete_quick(self->functions[i]);
310 vec_free(self->functions);
311 for (i = 0; i != vec_size(self->extparams); ++i) {
312 ir_value_delete(self->extparams[i]);
314 vec_free(self->extparams);
315 for (i = 0; i != vec_size(self->globals); ++i) {
316 ir_value_delete(self->globals[i]);
318 vec_free(self->globals);
319 for (i = 0; i != vec_size(self->fields); ++i) {
320 ir_value_delete(self->fields[i]);
322 vec_free(self->fields);
323 vec_free(self->filenames);
324 vec_free(self->filestrings);
328 bool ir_builder_set_name(ir_builder *self, const char *name)
331 mem_d((void*)self->name);
332 self->name = util_strdup(name);
336 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
338 return (ir_function*)util_htget(self->htfunctions, name);
341 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
343 ir_function *fn = ir_builder_get_function(self, name);
348 fn = ir_function_new(self, outtype);
349 if (!ir_function_set_name(fn, name))
351 ir_function_delete(fn);
354 vec_push(self->functions, fn);
355 util_htset(self->htfunctions, name, fn);
357 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
359 ir_function_delete(fn);
363 fn->value->hasvalue = true;
364 fn->value->outtype = outtype;
365 fn->value->constval.vfunc = fn;
366 fn->value->context = fn->context;
371 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
373 return (ir_value*)util_htget(self->htglobals, name);
376 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
380 if (name && name[0] != '#')
382 ve = ir_builder_get_global(self, name);
388 ve = ir_value_var(name, store_global, vtype);
389 vec_push(self->globals, ve);
390 util_htset(self->htglobals, name, ve);
394 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
396 return (ir_value*)util_htget(self->htfields, name);
400 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
402 ir_value *ve = ir_builder_get_field(self, name);
407 ve = ir_value_var(name, store_global, TYPE_FIELD);
408 ve->fieldtype = vtype;
409 vec_push(self->fields, ve);
410 util_htset(self->htfields, name, ve);
414 /***********************************************************************
418 bool ir_function_naive_phi(ir_function*);
419 void ir_function_enumerate(ir_function*);
420 bool ir_function_calculate_liferanges(ir_function*);
421 bool ir_function_allocate_locals(ir_function*);
423 ir_function* ir_function_new(ir_builder* owner, int outtype)
426 self = (ir_function*)mem_a(sizeof(*self));
431 memset(self, 0, sizeof(*self));
434 if (!ir_function_set_name(self, "<@unnamed>")) {
441 self->context.file = "<@no context>";
442 self->context.line = 0;
443 self->outtype = outtype;
452 self->code_function_def = -1;
453 self->allocated_locals = 0;
459 bool ir_function_set_name(ir_function *self, const char *name)
462 mem_d((void*)self->name);
463 self->name = util_strdup(name);
467 static void ir_function_delete_quick(ir_function *self)
470 mem_d((void*)self->name);
472 for (i = 0; i != vec_size(self->blocks); ++i)
473 ir_block_delete_quick(self->blocks[i]);
474 vec_free(self->blocks);
476 vec_free(self->params);
478 for (i = 0; i != vec_size(self->values); ++i)
479 ir_value_delete(self->values[i]);
480 vec_free(self->values);
482 for (i = 0; i != vec_size(self->locals); ++i)
483 ir_value_delete(self->locals[i]);
484 vec_free(self->locals);
486 /* self->value is deleted by the builder */
491 void ir_function_delete(ir_function *self)
494 mem_d((void*)self->name);
496 for (i = 0; i != vec_size(self->blocks); ++i)
497 ir_block_delete(self->blocks[i]);
498 vec_free(self->blocks);
500 vec_free(self->params);
502 for (i = 0; i != vec_size(self->values); ++i)
503 ir_value_delete(self->values[i]);
504 vec_free(self->values);
506 for (i = 0; i != vec_size(self->locals); ++i)
507 ir_value_delete(self->locals[i]);
508 vec_free(self->locals);
510 /* self->value is deleted by the builder */
515 void ir_function_collect_value(ir_function *self, ir_value *v)
517 vec_push(self->values, v);
520 ir_block* ir_function_create_block(lex_ctx ctx, ir_function *self, const char *label)
522 ir_block* bn = ir_block_new(self, label);
524 vec_push(self->blocks, bn);
528 static bool instr_is_operation(uint16_t op)
530 return ( (op >= INSTR_MUL_F && op <= INSTR_GT) ||
531 (op >= INSTR_LOAD_F && op <= INSTR_LOAD_FNC) ||
532 (op == INSTR_ADDRESS) ||
533 (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) ||
534 (op >= INSTR_AND && op <= INSTR_BITOR) ||
535 (op >= INSTR_CALL0 && op <= INSTR_CALL8) );
538 bool ir_function_pass_peephole(ir_function *self)
542 for (b = 0; b < vec_size(self->blocks); ++b) {
544 ir_block *block = self->blocks[b];
546 for (i = 0; i < vec_size(block->instr); ++i) {
548 inst = block->instr[i];
551 (inst->opcode >= INSTR_STORE_F &&
552 inst->opcode <= INSTR_STORE_FNC))
560 oper = block->instr[i-1];
561 if (!instr_is_operation(oper->opcode))
564 value = oper->_ops[0];
566 /* only do it for SSA values */
567 if (value->store != store_value)
570 /* don't optimize out the temp if it's used later again */
571 if (vec_size(value->reads) != 1)
574 /* The very next store must use this value */
575 if (value->reads[0] != store)
578 /* And of course the store must _read_ from it, so it's in
580 if (store->_ops[1] != value)
583 ++opts_optimizationcount[OPTIM_PEEPHOLE];
584 (void)!ir_instr_op(oper, 0, store->_ops[0], true);
586 vec_remove(block->instr, i, 1);
587 ir_instr_delete(store);
589 else if (inst->opcode == VINSTR_COND)
591 /* COND on a value resulting from a NOT could
592 * remove the NOT and swap its operands
599 value = inst->_ops[0];
601 if (value->store != store_value ||
602 vec_size(value->reads) != 1 ||
603 value->reads[0] != inst)
608 inot = value->writes[0];
609 if (inot->_ops[0] != value ||
610 inot->opcode < INSTR_NOT_F ||
611 inot->opcode > INSTR_NOT_FNC ||
612 inot->opcode == INSTR_NOT_V || /* can't do these */
613 inot->opcode == INSTR_NOT_S)
619 ++opts_optimizationcount[OPTIM_PEEPHOLE];
621 (void)!ir_instr_op(inst, 0, inot->_ops[1], false);
624 for (inotid = 0; inotid < vec_size(tmp->instr); ++inotid) {
625 if (tmp->instr[inotid] == inot)
628 if (inotid >= vec_size(tmp->instr)) {
629 compile_error(inst->context, "sanity-check failed: failed to find instruction to optimize out");
632 vec_remove(tmp->instr, inotid, 1);
633 ir_instr_delete(inot);
634 /* swap ontrue/onfalse */
636 inst->bops[0] = inst->bops[1];
647 bool ir_function_pass_tailrecursion(ir_function *self)
651 for (b = 0; b < vec_size(self->blocks); ++b) {
653 ir_instr *ret, *call, *store = NULL;
654 ir_block *block = self->blocks[b];
656 if (!block->final || vec_size(block->instr) < 2)
659 ret = block->instr[vec_size(block->instr)-1];
660 if (ret->opcode != INSTR_DONE && ret->opcode != INSTR_RETURN)
663 call = block->instr[vec_size(block->instr)-2];
664 if (call->opcode >= INSTR_STORE_F && call->opcode <= INSTR_STORE_FNC) {
665 /* account for the unoptimized
667 * STORE %return, %tmp
671 if (vec_size(block->instr) < 3)
675 call = block->instr[vec_size(block->instr)-3];
678 if (call->opcode < INSTR_CALL0 || call->opcode > INSTR_CALL8)
682 /* optimize out the STORE */
684 ret->_ops[0] == store->_ops[0] &&
685 store->_ops[1] == call->_ops[0])
687 ++opts_optimizationcount[OPTIM_PEEPHOLE];
688 call->_ops[0] = store->_ops[0];
689 vec_remove(block->instr, vec_size(block->instr) - 2, 1);
690 ir_instr_delete(store);
699 funcval = call->_ops[1];
702 if (funcval->vtype != TYPE_FUNCTION || funcval->constval.vfunc != self)
705 /* now we have a CALL and a RET, check if it's a tailcall */
706 if (ret->_ops[0] && call->_ops[0] != ret->_ops[0])
709 ++opts_optimizationcount[OPTIM_TAIL_RECURSION];
710 vec_shrinkby(block->instr, 2);
712 block->final = false; /* open it back up */
714 /* emite parameter-stores */
715 for (p = 0; p < vec_size(call->params); ++p) {
716 /* assert(call->params_count <= self->locals_count); */
717 if (!ir_block_create_store(block, call->context, self->locals[p], call->params[p])) {
718 irerror(call->context, "failed to create tailcall store instruction for parameter %i", (int)p);
722 if (!ir_block_create_jump(block, call->context, self->blocks[0])) {
723 irerror(call->context, "failed to create tailcall jump");
727 ir_instr_delete(call);
728 ir_instr_delete(ret);
734 bool ir_function_finalize(ir_function *self)
739 if (OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
740 if (!ir_function_pass_peephole(self)) {
741 irerror(self->context, "generic optimization pass broke something in `%s`", self->name);
746 if (OPTS_OPTIMIZATION(OPTIM_TAIL_RECURSION)) {
747 if (!ir_function_pass_tailrecursion(self)) {
748 irerror(self->context, "tail-recursion optimization pass broke something in `%s`", self->name);
753 if (!ir_function_naive_phi(self))
756 ir_function_enumerate(self);
758 if (!ir_function_calculate_liferanges(self))
760 if (!ir_function_allocate_locals(self))
765 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
770 vec_size(self->locals) &&
771 self->locals[vec_size(self->locals)-1]->store != store_param) {
772 irerror(self->context, "cannot add parameters after adding locals");
776 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
777 vec_push(self->locals, ve);
781 /***********************************************************************
785 ir_block* ir_block_new(ir_function* owner, const char *name)
788 self = (ir_block*)mem_a(sizeof(*self));
792 memset(self, 0, sizeof(*self));
795 if (name && !ir_block_set_label(self, name)) {
800 self->context.file = "<@no context>";
801 self->context.line = 0;
805 self->entries = NULL;
809 self->is_return = false;
814 self->generated = false;
819 static void ir_block_delete_quick(ir_block* self)
822 if (self->label) mem_d(self->label);
823 for (i = 0; i != vec_size(self->instr); ++i)
824 ir_instr_delete_quick(self->instr[i]);
825 vec_free(self->instr);
826 vec_free(self->entries);
827 vec_free(self->exits);
828 vec_free(self->living);
832 void ir_block_delete(ir_block* self)
835 if (self->label) mem_d(self->label);
836 for (i = 0; i != vec_size(self->instr); ++i)
837 ir_instr_delete(self->instr[i]);
838 vec_free(self->instr);
839 vec_free(self->entries);
840 vec_free(self->exits);
841 vec_free(self->living);
845 bool ir_block_set_label(ir_block *self, const char *name)
848 mem_d((void*)self->label);
849 self->label = util_strdup(name);
850 return !!self->label;
853 /***********************************************************************
857 ir_instr* ir_instr_new(lex_ctx ctx, ir_block* owner, int op)
860 self = (ir_instr*)mem_a(sizeof(*self));
867 self->_ops[0] = NULL;
868 self->_ops[1] = NULL;
869 self->_ops[2] = NULL;
870 self->bops[0] = NULL;
871 self->bops[1] = NULL;
882 static void ir_instr_delete_quick(ir_instr *self)
885 vec_free(self->params);
889 void ir_instr_delete(ir_instr *self)
892 /* The following calls can only delete from
893 * vectors, we still want to delete this instruction
894 * so ignore the return value. Since with the warn_unused_result attribute
895 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
896 * I have to improvise here and use if(foo());
898 for (i = 0; i < vec_size(self->phi); ++i) {
900 if (vec_ir_instr_find(self->phi[i].value->writes, self, &idx))
901 vec_remove(self->phi[i].value->writes, idx, 1);
902 if (vec_ir_instr_find(self->phi[i].value->reads, self, &idx))
903 vec_remove(self->phi[i].value->reads, idx, 1);
906 for (i = 0; i < vec_size(self->params); ++i) {
908 if (vec_ir_instr_find(self->params[i]->writes, self, &idx))
909 vec_remove(self->params[i]->writes, idx, 1);
910 if (vec_ir_instr_find(self->params[i]->reads, self, &idx))
911 vec_remove(self->params[i]->reads, idx, 1);
913 vec_free(self->params);
914 (void)!ir_instr_op(self, 0, NULL, false);
915 (void)!ir_instr_op(self, 1, NULL, false);
916 (void)!ir_instr_op(self, 2, NULL, false);
920 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
922 if (self->_ops[op]) {
924 if (writing && vec_ir_instr_find(self->_ops[op]->writes, self, &idx))
925 vec_remove(self->_ops[op]->writes, idx, 1);
926 else if (vec_ir_instr_find(self->_ops[op]->reads, self, &idx))
927 vec_remove(self->_ops[op]->reads, idx, 1);
931 vec_push(v->writes, self);
933 vec_push(v->reads, self);
939 /***********************************************************************
943 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
945 self->code.globaladdr = gaddr;
946 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
947 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
948 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
951 int32_t ir_value_code_addr(const ir_value *self)
953 if (self->store == store_return)
954 return OFS_RETURN + self->code.addroffset;
955 return self->code.globaladdr + self->code.addroffset;
958 ir_value* ir_value_var(const char *name, int storetype, int vtype)
961 self = (ir_value*)mem_a(sizeof(*self));
963 self->fieldtype = TYPE_VOID;
964 self->outtype = TYPE_VOID;
965 self->store = storetype;
971 self->hasvalue = false;
972 self->context.file = "<@no context>";
973 self->context.line = 0;
975 if (name && !ir_value_set_name(self, name)) {
976 irerror(self->context, "out of memory");
981 memset(&self->constval, 0, sizeof(self->constval));
982 memset(&self->code, 0, sizeof(self->code));
984 self->members[0] = NULL;
985 self->members[1] = NULL;
986 self->members[2] = NULL;
987 self->memberof = NULL;
989 self->unique_life = false;
995 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
1003 if (self->members[member])
1004 return self->members[member];
1007 len = strlen(self->name);
1008 name = (char*)mem_a(len + 3);
1009 memcpy(name, self->name, len);
1011 name[len+1] = 'x' + member;
1017 if (self->vtype == TYPE_VECTOR)
1019 m = ir_value_var(name, self->store, TYPE_FLOAT);
1024 m->context = self->context;
1026 self->members[member] = m;
1027 m->code.addroffset = member;
1029 else if (self->vtype == TYPE_FIELD)
1031 if (self->fieldtype != TYPE_VECTOR)
1033 m = ir_value_var(name, self->store, TYPE_FIELD);
1038 m->fieldtype = TYPE_FLOAT;
1039 m->context = self->context;
1041 self->members[member] = m;
1042 m->code.addroffset = member;
1046 irerror(self->context, "invalid member access on %s", self->name);
1054 static GMQCC_INLINE size_t ir_value_sizeof(const ir_value *self)
1056 if (self->vtype == TYPE_FIELD && self->fieldtype == TYPE_VECTOR)
1057 return type_sizeof_[TYPE_VECTOR];
1058 return type_sizeof_[self->vtype];
1061 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
1063 ir_value *v = ir_value_var(name, storetype, vtype);
1066 ir_function_collect_value(owner, v);
1070 void ir_value_delete(ir_value* self)
1074 mem_d((void*)self->name);
1077 if (self->vtype == TYPE_STRING)
1078 mem_d((void*)self->constval.vstring);
1080 for (i = 0; i < 3; ++i) {
1081 if (self->members[i])
1082 ir_value_delete(self->members[i]);
1084 vec_free(self->reads);
1085 vec_free(self->writes);
1086 vec_free(self->life);
1090 bool ir_value_set_name(ir_value *self, const char *name)
1093 mem_d((void*)self->name);
1094 self->name = util_strdup(name);
1095 return !!self->name;
1098 bool ir_value_set_float(ir_value *self, float f)
1100 if (self->vtype != TYPE_FLOAT)
1102 self->constval.vfloat = f;
1103 self->hasvalue = true;
1107 bool ir_value_set_func(ir_value *self, int f)
1109 if (self->vtype != TYPE_FUNCTION)
1111 self->constval.vint = f;
1112 self->hasvalue = true;
1116 bool ir_value_set_vector(ir_value *self, vector v)
1118 if (self->vtype != TYPE_VECTOR)
1120 self->constval.vvec = v;
1121 self->hasvalue = true;
1125 bool ir_value_set_field(ir_value *self, ir_value *fld)
1127 if (self->vtype != TYPE_FIELD)
1129 self->constval.vpointer = fld;
1130 self->hasvalue = true;
1134 static char *ir_strdup(const char *str)
1137 /* actually dup empty strings */
1138 char *out = (char*)mem_a(1);
1142 return util_strdup(str);
1145 bool ir_value_set_string(ir_value *self, const char *str)
1147 if (self->vtype != TYPE_STRING)
1149 self->constval.vstring = ir_strdup(str);
1150 self->hasvalue = true;
1155 bool ir_value_set_int(ir_value *self, int i)
1157 if (self->vtype != TYPE_INTEGER)
1159 self->constval.vint = i;
1160 self->hasvalue = true;
1165 bool ir_value_lives(ir_value *self, size_t at)
1168 for (i = 0; i < vec_size(self->life); ++i)
1170 ir_life_entry_t *life = &self->life[i];
1171 if (life->start <= at && at <= life->end)
1173 if (life->start > at) /* since it's ordered */
1179 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
1182 vec_push(self->life, e);
1183 for (k = vec_size(self->life)-1; k > idx; --k)
1184 self->life[k] = self->life[k-1];
1185 self->life[idx] = e;
1189 bool ir_value_life_merge(ir_value *self, size_t s)
1192 ir_life_entry_t *life = NULL;
1193 ir_life_entry_t *before = NULL;
1194 ir_life_entry_t new_entry;
1196 /* Find the first range >= s */
1197 for (i = 0; i < vec_size(self->life); ++i)
1200 life = &self->life[i];
1201 if (life->start > s)
1204 /* nothing found? append */
1205 if (i == vec_size(self->life)) {
1207 if (life && life->end+1 == s)
1209 /* previous life range can be merged in */
1213 if (life && life->end >= s)
1215 e.start = e.end = s;
1216 vec_push(self->life, e);
1222 if (before->end + 1 == s &&
1223 life->start - 1 == s)
1226 before->end = life->end;
1227 vec_remove(self->life, i, 1);
1230 if (before->end + 1 == s)
1236 /* already contained */
1237 if (before->end >= s)
1241 if (life->start - 1 == s)
1246 /* insert a new entry */
1247 new_entry.start = new_entry.end = s;
1248 return ir_value_life_insert(self, i, new_entry);
1251 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1255 if (!vec_size(other->life))
1258 if (!vec_size(self->life)) {
1259 size_t count = vec_size(other->life);
1260 ir_life_entry_t *life = vec_add(self->life, count);
1261 memcpy(life, other->life, count * sizeof(*life));
1266 for (i = 0; i < vec_size(other->life); ++i)
1268 const ir_life_entry_t *life = &other->life[i];
1271 ir_life_entry_t *entry = &self->life[myi];
1273 if (life->end+1 < entry->start)
1275 /* adding an interval before entry */
1276 if (!ir_value_life_insert(self, myi, *life))
1282 if (life->start < entry->start &&
1283 life->end+1 >= entry->start)
1285 /* starts earlier and overlaps */
1286 entry->start = life->start;
1289 if (life->end > entry->end &&
1290 life->start <= entry->end+1)
1292 /* ends later and overlaps */
1293 entry->end = life->end;
1296 /* see if our change combines it with the next ranges */
1297 while (myi+1 < vec_size(self->life) &&
1298 entry->end+1 >= self->life[1+myi].start)
1300 /* overlaps with (myi+1) */
1301 if (entry->end < self->life[1+myi].end)
1302 entry->end = self->life[1+myi].end;
1303 vec_remove(self->life, myi+1, 1);
1304 entry = &self->life[myi];
1307 /* see if we're after the entry */
1308 if (life->start > entry->end)
1311 /* append if we're at the end */
1312 if (myi >= vec_size(self->life)) {
1313 vec_push(self->life, *life);
1316 /* otherweise check the next range */
1325 bool ir_values_overlap(const ir_value *a, const ir_value *b)
1327 /* For any life entry in A see if it overlaps with
1328 * any life entry in B.
1329 * Note that the life entries are orderes, so we can make a
1330 * more efficient algorithm there than naively translating the
1334 ir_life_entry_t *la, *lb, *enda, *endb;
1336 /* first of all, if either has no life range, they cannot clash */
1337 if (!vec_size(a->life) || !vec_size(b->life))
1342 enda = la + vec_size(a->life);
1343 endb = lb + vec_size(b->life);
1346 /* check if the entries overlap, for that,
1347 * both must start before the other one ends.
1349 if (la->start < lb->end &&
1350 lb->start < la->end)
1355 /* entries are ordered
1356 * one entry is earlier than the other
1357 * that earlier entry will be moved forward
1359 if (la->start < lb->start)
1361 /* order: A B, move A forward
1362 * check if we hit the end with A
1367 else /* if (lb->start < la->start) actually <= */
1369 /* order: B A, move B forward
1370 * check if we hit the end with B
1379 /***********************************************************************
1383 static bool ir_check_unreachable(ir_block *self)
1385 /* The IR should never have to deal with unreachable code */
1386 if (!self->final/* || OPTS_FLAG(ALLOW_UNREACHABLE_CODE)*/)
1388 irerror(self->context, "unreachable statement (%s)", self->label);
1392 bool ir_block_create_store_op(ir_block *self, lex_ctx ctx, int op, ir_value *target, ir_value *what)
1395 if (!ir_check_unreachable(self))
1398 if (target->store == store_value &&
1399 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1401 irerror(self->context, "cannot store to an SSA value");
1402 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1403 irerror(self->context, "instruction: %s", asm_instr[op].m);
1407 in = ir_instr_new(ctx, self, op);
1411 if (!ir_instr_op(in, 0, target, (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC)) ||
1412 !ir_instr_op(in, 1, what, false))
1414 ir_instr_delete(in);
1417 vec_push(self->instr, in);
1421 bool ir_block_create_store(ir_block *self, lex_ctx ctx, ir_value *target, ir_value *what)
1425 if (target->vtype == TYPE_VARIANT)
1426 vtype = what->vtype;
1428 vtype = target->vtype;
1431 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1432 op = INSTR_CONV_ITOF;
1433 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1434 op = INSTR_CONV_FTOI;
1436 op = type_store_instr[vtype];
1438 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1439 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1443 return ir_block_create_store_op(self, ctx, op, target, what);
1446 bool ir_block_create_storep(ir_block *self, lex_ctx ctx, ir_value *target, ir_value *what)
1451 if (target->vtype != TYPE_POINTER)
1454 /* storing using pointer - target is a pointer, type must be
1455 * inferred from source
1457 vtype = what->vtype;
1459 op = type_storep_instr[vtype];
1460 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1461 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1462 op = INSTR_STOREP_V;
1465 return ir_block_create_store_op(self, ctx, op, target, what);
1468 bool ir_block_create_return(ir_block *self, lex_ctx ctx, ir_value *v)
1471 if (!ir_check_unreachable(self))
1474 self->is_return = true;
1475 in = ir_instr_new(ctx, self, INSTR_RETURN);
1479 if (v && !ir_instr_op(in, 0, v, false)) {
1480 ir_instr_delete(in);
1484 vec_push(self->instr, in);
1488 bool ir_block_create_if(ir_block *self, lex_ctx ctx, ir_value *v,
1489 ir_block *ontrue, ir_block *onfalse)
1492 if (!ir_check_unreachable(self))
1495 /*in = ir_instr_new(ctx, self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1496 in = ir_instr_new(ctx, self, VINSTR_COND);
1500 if (!ir_instr_op(in, 0, v, false)) {
1501 ir_instr_delete(in);
1505 in->bops[0] = ontrue;
1506 in->bops[1] = onfalse;
1508 vec_push(self->instr, in);
1510 vec_push(self->exits, ontrue);
1511 vec_push(self->exits, onfalse);
1512 vec_push(ontrue->entries, self);
1513 vec_push(onfalse->entries, self);
1517 bool ir_block_create_jump(ir_block *self, lex_ctx ctx, ir_block *to)
1520 if (!ir_check_unreachable(self))
1523 in = ir_instr_new(ctx, self, VINSTR_JUMP);
1528 vec_push(self->instr, in);
1530 vec_push(self->exits, to);
1531 vec_push(to->entries, self);
1535 bool ir_block_create_goto(ir_block *self, lex_ctx ctx, ir_block *to)
1537 self->owner->flags |= IR_FLAG_HAS_GOTO;
1538 return ir_block_create_jump(self, ctx, to);
1541 ir_instr* ir_block_create_phi(ir_block *self, lex_ctx ctx, const char *label, int ot)
1545 if (!ir_check_unreachable(self))
1547 in = ir_instr_new(ctx, self, VINSTR_PHI);
1550 out = ir_value_out(self->owner, label, store_value, ot);
1552 ir_instr_delete(in);
1555 if (!ir_instr_op(in, 0, out, true)) {
1556 ir_instr_delete(in);
1557 ir_value_delete(out);
1560 vec_push(self->instr, in);
1564 ir_value* ir_phi_value(ir_instr *self)
1566 return self->_ops[0];
1569 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1573 if (!vec_ir_block_find(self->owner->entries, b, NULL)) {
1574 /* Must not be possible to cause this, otherwise the AST
1575 * is doing something wrong.
1577 irerror(self->context, "Invalid entry block for PHI");
1583 vec_push(v->reads, self);
1584 vec_push(self->phi, pe);
1587 /* call related code */
1588 ir_instr* ir_block_create_call(ir_block *self, lex_ctx ctx, const char *label, ir_value *func, bool noreturn)
1592 if (!ir_check_unreachable(self))
1594 in = ir_instr_new(ctx, self, (noreturn ? VINSTR_NRCALL : INSTR_CALL0));
1599 self->is_return = true;
1601 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1603 ir_instr_delete(in);
1606 if (!ir_instr_op(in, 0, out, true) ||
1607 !ir_instr_op(in, 1, func, false))
1609 ir_instr_delete(in);
1610 ir_value_delete(out);
1613 vec_push(self->instr, in);
1616 if (!ir_block_create_return(self, ctx, NULL)) {
1617 compile_error(ctx, "internal error: failed to generate dummy-return instruction");
1618 ir_instr_delete(in);
1626 ir_value* ir_call_value(ir_instr *self)
1628 return self->_ops[0];
1631 void ir_call_param(ir_instr* self, ir_value *v)
1633 vec_push(self->params, v);
1634 vec_push(v->reads, self);
1637 /* binary op related code */
1639 ir_value* ir_block_create_binop(ir_block *self, lex_ctx ctx,
1640 const char *label, int opcode,
1641 ir_value *left, ir_value *right)
1663 case INSTR_SUB_S: /* -- offset of string as float */
1668 case INSTR_BITOR_IF:
1669 case INSTR_BITOR_FI:
1670 case INSTR_BITAND_FI:
1671 case INSTR_BITAND_IF:
1686 case INSTR_BITAND_I:
1689 case INSTR_RSHIFT_I:
1690 case INSTR_LSHIFT_I:
1712 /* boolean operations result in floats */
1713 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1715 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1718 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1723 if (ot == TYPE_VOID) {
1724 /* The AST or parser were supposed to check this! */
1728 return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1731 ir_value* ir_block_create_unary(ir_block *self, lex_ctx ctx,
1732 const char *label, int opcode,
1735 int ot = TYPE_FLOAT;
1747 /* QC doesn't have other unary operations. We expect extensions to fill
1748 * the above list, otherwise we assume out-type = in-type, eg for an
1752 ot = operand->vtype;
1755 if (ot == TYPE_VOID) {
1756 /* The AST or parser were supposed to check this! */
1760 /* let's use the general instruction creator and pass NULL for OPB */
1761 return ir_block_create_general_instr(self, ctx, label, opcode, operand, NULL, ot);
1764 ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx ctx, const char *label,
1765 int op, ir_value *a, ir_value *b, int outype)
1770 out = ir_value_out(self->owner, label, store_value, outype);
1774 instr = ir_instr_new(ctx, self, op);
1776 ir_value_delete(out);
1780 if (!ir_instr_op(instr, 0, out, true) ||
1781 !ir_instr_op(instr, 1, a, false) ||
1782 !ir_instr_op(instr, 2, b, false) )
1787 vec_push(self->instr, instr);
1791 ir_instr_delete(instr);
1792 ir_value_delete(out);
1796 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx ctx, const char *label, ir_value *ent, ir_value *field)
1800 /* Support for various pointer types todo if so desired */
1801 if (ent->vtype != TYPE_ENTITY)
1804 if (field->vtype != TYPE_FIELD)
1807 v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1808 v->fieldtype = field->fieldtype;
1812 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)
1815 if (ent->vtype != TYPE_ENTITY)
1818 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1819 if (field->vtype != TYPE_FIELD)
1824 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1825 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1826 case TYPE_STRING: op = INSTR_LOAD_S; break;
1827 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1828 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1829 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1831 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1832 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1835 irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1839 return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
1842 /* PHI resolving breaks the SSA, and must thus be the last
1843 * step before life-range calculation.
1846 static bool ir_block_naive_phi(ir_block *self);
1847 bool ir_function_naive_phi(ir_function *self)
1851 for (i = 0; i < vec_size(self->blocks); ++i)
1853 if (!ir_block_naive_phi(self->blocks[i]))
1860 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1865 /* create a store */
1866 if (!ir_block_create_store(block, old, what))
1869 /* we now move it up */
1870 instr = vec_last(block->instr);
1871 for (i = vec_size(block->instr)-1; i > iid; --i)
1872 block->instr[i] = block->instr[i-1];
1873 block->instr[i] = instr;
1879 static bool ir_block_naive_phi(ir_block *self)
1881 size_t i, p; /*, w;*/
1882 /* FIXME: optionally, create_phi can add the phis
1883 * to a list so we don't need to loop through blocks
1884 * - anyway: "don't optimize YET"
1886 for (i = 0; i < vec_size(self->instr); ++i)
1888 ir_instr *instr = self->instr[i];
1889 if (instr->opcode != VINSTR_PHI)
1892 vec_remove(self->instr, i, 1);
1893 --i; /* NOTE: i+1 below */
1895 for (p = 0; p < vec_size(instr->phi); ++p)
1897 ir_value *v = instr->phi[p].value;
1898 ir_block *b = instr->phi[p].from;
1900 if (v->store == store_value &&
1901 vec_size(v->reads) == 1 &&
1902 vec_size(v->writes) == 1)
1904 /* replace the value */
1905 if (!ir_instr_op(v->writes[0], 0, instr->_ops[0], true))
1910 /* force a move instruction */
1911 ir_instr *prevjump = vec_last(b->instr);
1914 instr->_ops[0]->store = store_global;
1915 if (!ir_block_create_store(b, instr->context, instr->_ops[0], v))
1917 instr->_ops[0]->store = store_value;
1918 vec_push(b->instr, prevjump);
1923 ir_value *v = instr->phi[p].value;
1924 for (w = 0; w < vec_size(v->writes); ++w) {
1927 if (!v->writes[w]->_ops[0])
1930 /* When the write was to a global, we have to emit a mov */
1931 old = v->writes[w]->_ops[0];
1933 /* The original instruction now writes to the PHI target local */
1934 if (v->writes[w]->_ops[0] == v)
1935 v->writes[w]->_ops[0] = instr->_ops[0];
1937 if (old->store != store_value && old->store != store_local && old->store != store_param)
1939 /* If it originally wrote to a global we need to store the value
1942 if (!ir_naive_phi_emit_store(self, i+1, old, v))
1944 if (i+1 < vec_size(self->instr))
1945 instr = self->instr[i+1];
1948 /* In case I forget and access instr later, it'll be NULL
1949 * when it's a problem, to make sure we crash, rather than accessing
1955 /* If it didn't, we can replace all reads by the phi target now. */
1957 for (r = 0; r < vec_size(old->reads); ++r)
1960 ir_instr *ri = old->reads[r];
1961 for (op = 0; op < vec_size(ri->phi); ++op) {
1962 if (ri->phi[op].value == old)
1963 ri->phi[op].value = v;
1965 for (op = 0; op < 3; ++op) {
1966 if (ri->_ops[op] == old)
1974 ir_instr_delete(instr);
1979 /***********************************************************************
1980 *IR Temp allocation code
1981 * Propagating value life ranges by walking through the function backwards
1982 * until no more changes are made.
1983 * In theory this should happen once more than once for every nested loop
1985 * Though this implementation might run an additional time for if nests.
1988 /* Enumerate instructions used by value's life-ranges
1990 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1994 for (i = 0; i < vec_size(self->instr); ++i)
1996 self->instr[i]->eid = eid++;
2001 /* Enumerate blocks and instructions.
2002 * The block-enumeration is unordered!
2003 * We do not really use the block enumreation, however
2004 * the instruction enumeration is important for life-ranges.
2006 void ir_function_enumerate(ir_function *self)
2009 size_t instruction_id = 1;
2010 for (i = 0; i < vec_size(self->blocks); ++i)
2012 self->blocks[i]->eid = i;
2013 self->blocks[i]->run_id = 0;
2014 ir_block_enumerate(self->blocks[i], &instruction_id);
2018 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
2019 bool ir_function_calculate_liferanges(ir_function *self)
2024 /* parameters live at 0 */
2025 for (i = 0; i < vec_size(self->params); ++i)
2026 ir_value_life_merge(self->locals[i], 0);
2031 for (i = 0; i != vec_size(self->blocks); ++i)
2033 if (self->blocks[i]->is_return)
2035 vec_free(self->blocks[i]->living);
2036 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
2041 if (vec_size(self->blocks)) {
2042 ir_block *block = self->blocks[0];
2043 for (i = 0; i < vec_size(block->living); ++i) {
2044 ir_value *v = block->living[i];
2045 if (v->store != store_local)
2047 if ((v->members[0] && v->members[1] && v->members[2])) {
2048 /* all vector members have been accessed - only treat this as uninitialized
2049 * if any of them is also uninitialized.
2051 if (!vec_ir_value_find(block->living, v->members[0], NULL) &&
2052 !vec_ir_value_find(block->living, v->members[1], NULL) &&
2053 !vec_ir_value_find(block->living, v->members[2], NULL))
2059 /* A member is only uninitialized if the whole vector is also uninitialized */
2060 if (!vec_ir_value_find(block->living, v->memberof, NULL))
2063 self->flags |= IR_FLAG_HAS_UNINITIALIZED;
2064 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2065 "variable `%s` may be used uninitialized in this function", v->name))
2074 /* Local-value allocator
2075 * After finishing creating the liferange of all values used in a function
2076 * we can allocate their global-positions.
2077 * This is the counterpart to register-allocation in register machines.
2084 } function_allocator;
2086 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
2089 size_t vsize = ir_value_sizeof(var);
2091 slot = ir_value_var("reg", store_global, var->vtype);
2095 if (!ir_value_life_merge_into(slot, var))
2098 vec_push(alloc->locals, slot);
2099 vec_push(alloc->sizes, vsize);
2100 vec_push(alloc->unique, var->unique_life);
2105 ir_value_delete(slot);
2109 bool ir_function_allocate_locals(ir_function *self)
2118 function_allocator alloc;
2120 if (!vec_size(self->locals) && !vec_size(self->values))
2123 alloc.locals = NULL;
2125 alloc.positions = NULL;
2126 alloc.unique = NULL;
2128 for (i = 0; i < vec_size(self->locals); ++i)
2130 if (!OPTS_OPTIMIZATION(OPTIM_LOCAL_TEMPS))
2131 self->locals[i]->unique_life = true;
2132 if (!function_allocator_alloc(&alloc, self->locals[i]))
2136 /* Allocate a slot for any value that still exists */
2137 for (i = 0; i < vec_size(self->values); ++i)
2139 v = self->values[i];
2141 if (!vec_size(v->life))
2144 for (a = 0; a < vec_size(alloc.locals); ++a)
2146 /* if it's reserved for a unique liferange: skip */
2147 if (alloc.unique[a])
2150 slot = alloc.locals[a];
2152 /* never resize parameters
2153 * will be required later when overlapping temps + locals
2155 if (a < vec_size(self->params) &&
2156 alloc.sizes[a] < ir_value_sizeof(v))
2161 if (ir_values_overlap(v, slot))
2164 if (!ir_value_life_merge_into(slot, v))
2167 /* adjust size for this slot */
2168 if (alloc.sizes[a] < ir_value_sizeof(v))
2169 alloc.sizes[a] = ir_value_sizeof(v);
2171 self->values[i]->code.local = a;
2174 if (a >= vec_size(alloc.locals)) {
2175 self->values[i]->code.local = vec_size(alloc.locals);
2176 if (!function_allocator_alloc(&alloc, v))
2185 /* Adjust slot positions based on sizes */
2186 vec_push(alloc.positions, 0);
2188 if (vec_size(alloc.sizes))
2189 pos = alloc.positions[0] + alloc.sizes[0];
2192 for (i = 1; i < vec_size(alloc.sizes); ++i)
2194 pos = alloc.positions[i-1] + alloc.sizes[i-1];
2195 vec_push(alloc.positions, pos);
2198 self->allocated_locals = pos + vec_last(alloc.sizes);
2200 /* Locals need to know their new position */
2201 for (i = 0; i < vec_size(self->locals); ++i) {
2202 self->locals[i]->code.local = alloc.positions[i];
2204 /* Take over the actual slot positions on values */
2205 for (i = 0; i < vec_size(self->values); ++i) {
2206 self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
2214 for (i = 0; i < vec_size(alloc.locals); ++i)
2215 ir_value_delete(alloc.locals[i]);
2216 vec_free(alloc.unique);
2217 vec_free(alloc.locals);
2218 vec_free(alloc.sizes);
2219 vec_free(alloc.positions);
2223 /* Get information about which operand
2224 * is read from, or written to.
2226 static void ir_op_read_write(int op, size_t *read, size_t *write)
2246 case INSTR_STOREP_F:
2247 case INSTR_STOREP_V:
2248 case INSTR_STOREP_S:
2249 case INSTR_STOREP_ENT:
2250 case INSTR_STOREP_FLD:
2251 case INSTR_STOREP_FNC:
2262 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2265 bool changed = false;
2267 for (i = 0; i != vec_size(self->living); ++i)
2269 tempbool = ir_value_life_merge(self->living[i], eid);
2272 irerror(self->context, "block_living_add_instr() value instruction added %s: %i", self->living[i]->_name, (int)eid);
2274 changed = changed || tempbool;
2279 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
2285 /* values which have been read in a previous iteration are now
2286 * in the "living" array even if the previous block doesn't use them.
2287 * So we have to remove whatever does not exist in the previous block.
2288 * They will be re-added on-read, but the liferange merge won't cause
2290 for (i = 0; i < vec_size(self->living); ++i)
2292 if (!vec_ir_value_find(prev->living, self->living[i], NULL)) {
2293 vec_remove(self->living, i, 1);
2299 /* Whatever the previous block still has in its living set
2300 * must now be added to ours as well.
2302 for (i = 0; i < vec_size(prev->living); ++i)
2304 if (vec_ir_value_find(self->living, prev->living[i], NULL))
2306 vec_push(self->living, prev->living[i]);
2308 irerror(self->contextt from prev: %s", self->label, prev->living[i]->_name);
2314 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2320 /* bitmasks which operands are read from or written to */
2322 char dbg_ind[16] = { '#', '0' };
2327 if (!ir_block_life_prop_previous(self, prev, changed))
2331 i = vec_size(self->instr);
2334 instr = self->instr[i];
2336 /* See which operands are read and write operands */
2337 ir_op_read_write(instr->opcode, &read, &write);
2339 if (instr->opcode == INSTR_MUL_VF)
2341 /* the float source will get an additional lifetime */
2342 tempbool = ir_value_life_merge(instr->_ops[2], instr->eid+1);
2343 *changed = *changed || tempbool;
2345 else if (instr->opcode == INSTR_MUL_FV)
2347 /* the float source will get an additional lifetime */
2348 tempbool = ir_value_life_merge(instr->_ops[1], instr->eid+1);
2349 *changed = *changed || tempbool;
2352 /* Go through the 3 main operands
2353 * writes first, then reads
2355 for (o = 0; o < 3; ++o)
2357 if (!instr->_ops[o]) /* no such operand */
2360 value = instr->_ops[o];
2362 /* We only care about locals */
2363 /* we also calculate parameter liferanges so that locals
2364 * can take up parameter slots */
2365 if (value->store != store_value &&
2366 value->store != store_local &&
2367 value->store != store_param)
2370 /* write operands */
2371 /* When we write to a local, we consider it "dead" for the
2372 * remaining upper part of the function, since in SSA a value
2373 * can only be written once (== created)
2378 bool in_living = vec_ir_value_find(self->living, value, &idx);
2381 /* If the value isn't alive it hasn't been read before... */
2382 /* TODO: See if the warning can be emitted during parsing or AST processing
2383 * otherwise have warning printed here.
2384 * IF printing a warning here: include filecontext_t,
2385 * and make sure it's only printed once
2386 * since this function is run multiple times.
2388 /* For now: debug info: */
2389 /* con_err( "Value only written %s\n", value->name); */
2390 tempbool = ir_value_life_merge(value, instr->eid);
2391 *changed = *changed || tempbool;
2393 ir_instr_dump(instr, dbg_ind, printf);
2397 /* since 'living' won't contain it
2398 * anymore, merge the value, since
2401 tempbool = ir_value_life_merge(value, instr->eid);
2402 *changed = *changed || tempbool;
2404 vec_remove(self->living, idx, 1);
2409 for (o = 0; o < 3; ++o)
2411 if (!instr->_ops[o]) /* no such operand */
2414 value = instr->_ops[o];
2416 /* We only care about locals */
2417 /* we also calculate parameter liferanges so that locals
2418 * can take up parameter slots */
2419 if (value->store != store_value &&
2420 value->store != store_local &&
2421 value->store != store_param)
2427 if (!vec_ir_value_find(self->living, value, NULL))
2428 vec_push(self->living, value);
2431 /* PHI operands are always read operands */
2432 for (p = 0; p < vec_size(instr->phi); ++p)
2434 value = instr->phi[p].value;
2435 if (!vec_ir_value_find(self->living, value, NULL))
2436 vec_push(self->living, value);
2439 /* call params are read operands too */
2440 for (p = 0; p < vec_size(instr->params); ++p)
2442 value = instr->params[p];
2443 if (!vec_ir_value_find(self->living, value, NULL))
2444 vec_push(self->living, value);
2448 tempbool = ir_block_living_add_instr(self, instr->eid);
2449 /*con_err( "living added values\n");*/
2450 *changed = *changed || tempbool;
2454 if (self->run_id == self->owner->run_id)
2457 self->run_id = self->owner->run_id;
2459 for (i = 0; i < vec_size(self->entries); ++i)
2461 ir_block *entry = self->entries[i];
2462 ir_block_life_propagate(entry, self, changed);
2468 /***********************************************************************
2471 * Since the IR has the convention of putting 'write' operands
2472 * at the beginning, we have to rotate the operands of instructions
2473 * properly in order to generate valid QCVM code.
2475 * Having destinations at a fixed position is more convenient. In QC
2476 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2477 * read from from OPA, and store to OPB rather than OPC. Which is
2478 * partially the reason why the implementation of these instructions
2479 * in darkplaces has been delayed for so long.
2481 * Breaking conventions is annoying...
2483 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal, bool defs_only);
2485 static bool gen_global_field(ir_value *global)
2487 if (global->hasvalue)
2489 ir_value *fld = global->constval.vpointer;
2491 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2495 /* copy the field's value */
2496 ir_value_code_setaddr(global, vec_size(code_globals));
2497 vec_push(code_globals, fld->code.fieldaddr);
2498 if (global->fieldtype == TYPE_VECTOR) {
2499 vec_push(code_globals, fld->code.fieldaddr+1);
2500 vec_push(code_globals, fld->code.fieldaddr+2);
2505 ir_value_code_setaddr(global, vec_size(code_globals));
2506 vec_push(code_globals, 0);
2507 if (global->fieldtype == TYPE_VECTOR) {
2508 vec_push(code_globals, 0);
2509 vec_push(code_globals, 0);
2512 if (global->code.globaladdr < 0)
2517 static bool gen_global_pointer(ir_value *global)
2519 if (global->hasvalue)
2521 ir_value *target = global->constval.vpointer;
2523 irerror(global->context, "Invalid pointer constant: %s", global->name);
2524 /* NULL pointers are pointing to the NULL constant, which also
2525 * sits at address 0, but still has an ir_value for itself.
2530 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2531 * void() foo; <- proto
2532 * void() *fooptr = &foo;
2533 * void() foo = { code }
2535 if (!target->code.globaladdr) {
2536 /* FIXME: Check for the constant nullptr ir_value!
2537 * because then code.globaladdr being 0 is valid.
2539 irerror(global->context, "FIXME: Relocation support");
2543 ir_value_code_setaddr(global, vec_size(code_globals));
2544 vec_push(code_globals, target->code.globaladdr);
2548 ir_value_code_setaddr(global, vec_size(code_globals));
2549 vec_push(code_globals, 0);
2551 if (global->code.globaladdr < 0)
2556 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2558 prog_section_statement stmt;
2567 block->generated = true;
2568 block->code_start = vec_size(code_statements);
2569 for (i = 0; i < vec_size(block->instr); ++i)
2571 instr = block->instr[i];
2573 if (instr->opcode == VINSTR_PHI) {
2574 irerror(block->context, "cannot generate virtual instruction (phi)");
2578 if (instr->opcode == VINSTR_JUMP) {
2579 target = instr->bops[0];
2580 /* for uncoditional jumps, if the target hasn't been generated
2581 * yet, we generate them right here.
2583 if (!target->generated) {
2588 /* otherwise we generate a jump instruction */
2589 stmt.opcode = INSTR_GOTO;
2590 stmt.o1.s1 = (target->code_start) - vec_size(code_statements);
2593 if (stmt.o1.s1 != 1)
2594 code_push_statement(&stmt, instr->context.line);
2596 /* no further instructions can be in this block */
2600 if (instr->opcode == VINSTR_COND) {
2601 ontrue = instr->bops[0];
2602 onfalse = instr->bops[1];
2603 /* TODO: have the AST signal which block should
2604 * come first: eg. optimize IFs without ELSE...
2607 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2611 if (ontrue->generated) {
2612 stmt.opcode = INSTR_IF;
2613 stmt.o2.s1 = (ontrue->code_start) - vec_size(code_statements);
2614 if (stmt.o2.s1 != 1)
2615 code_push_statement(&stmt, instr->context.line);
2617 if (onfalse->generated) {
2618 stmt.opcode = INSTR_IFNOT;
2619 stmt.o2.s1 = (onfalse->code_start) - vec_size(code_statements);
2620 if (stmt.o2.s1 != 1)
2621 code_push_statement(&stmt, instr->context.line);
2623 if (!ontrue->generated) {
2624 if (onfalse->generated) {
2629 if (!onfalse->generated) {
2630 if (ontrue->generated) {
2635 /* neither ontrue nor onfalse exist */
2636 stmt.opcode = INSTR_IFNOT;
2637 if (!instr->likely) {
2638 /* Honor the likelyhood hint */
2639 ir_block *tmp = onfalse;
2640 stmt.opcode = INSTR_IF;
2644 stidx = vec_size(code_statements);
2645 code_push_statement(&stmt, instr->context.line);
2646 /* on false we jump, so add ontrue-path */
2647 if (!gen_blocks_recursive(func, ontrue))
2649 /* fixup the jump address */
2650 code_statements[stidx].o2.s1 = vec_size(code_statements) - stidx;
2651 /* generate onfalse path */
2652 if (onfalse->generated) {
2653 /* fixup the jump address */
2654 code_statements[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2655 if (code_statements[stidx].o2.s1 == 1) {
2656 code_statements[stidx] = code_statements[stidx+1];
2657 if (code_statements[stidx].o1.s1 < 0)
2658 code_statements[stidx].o1.s1++;
2659 code_pop_statement();
2661 stmt.opcode = vec_last(code_statements).opcode;
2662 if (stmt.opcode == INSTR_GOTO ||
2663 stmt.opcode == INSTR_IF ||
2664 stmt.opcode == INSTR_IFNOT ||
2665 stmt.opcode == INSTR_RETURN ||
2666 stmt.opcode == INSTR_DONE)
2668 /* no use jumping from here */
2671 /* may have been generated in the previous recursive call */
2672 stmt.opcode = INSTR_GOTO;
2673 stmt.o1.s1 = (onfalse->code_start) - vec_size(code_statements);
2676 if (stmt.o1.s1 != 1)
2677 code_push_statement(&stmt, instr->context.line);
2680 else if (code_statements[stidx].o2.s1 == 1) {
2681 code_statements[stidx] = code_statements[stidx+1];
2682 if (code_statements[stidx].o1.s1 < 0)
2683 code_statements[stidx].o1.s1++;
2684 code_pop_statement();
2686 /* if not, generate now */
2691 if ( (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8)
2692 || instr->opcode == VINSTR_NRCALL)
2694 /* Trivial call translation:
2695 * copy all params to OFS_PARM*
2696 * if the output's storetype is not store_return,
2697 * add append a STORE instruction!
2699 * NOTES on how to do it better without much trouble:
2700 * -) The liferanges!
2701 * Simply check the liferange of all parameters for
2702 * other CALLs. For each param with no CALL in its
2703 * liferange, we can store it in an OFS_PARM at
2704 * generation already. This would even include later
2705 * reuse.... probably... :)
2710 first = vec_size(instr->params);
2713 for (p = 0; p < first; ++p)
2715 ir_value *param = instr->params[p];
2717 stmt.opcode = INSTR_STORE_F;
2720 if (param->vtype == TYPE_FIELD)
2721 stmt.opcode = field_store_instr[param->fieldtype];
2723 stmt.opcode = type_store_instr[param->vtype];
2724 stmt.o1.u1 = ir_value_code_addr(param);
2725 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2726 code_push_statement(&stmt, instr->context.line);
2728 /* Now handle extparams */
2729 first = vec_size(instr->params);
2730 for (; p < first; ++p)
2732 ir_builder *ir = func->owner;
2733 ir_value *param = instr->params[p];
2734 ir_value *targetparam;
2736 if (p-8 >= vec_size(ir->extparams))
2737 ir_gen_extparam(ir);
2739 targetparam = ir->extparams[p-8];
2741 stmt.opcode = INSTR_STORE_F;
2744 if (param->vtype == TYPE_FIELD)
2745 stmt.opcode = field_store_instr[param->fieldtype];
2747 stmt.opcode = type_store_instr[param->vtype];
2748 stmt.o1.u1 = ir_value_code_addr(param);
2749 stmt.o2.u1 = ir_value_code_addr(targetparam);
2750 code_push_statement(&stmt, instr->context.line);
2753 stmt.opcode = INSTR_CALL0 + vec_size(instr->params);
2754 if (stmt.opcode > INSTR_CALL8)
2755 stmt.opcode = INSTR_CALL8;
2756 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2759 code_push_statement(&stmt, instr->context.line);
2761 retvalue = instr->_ops[0];
2762 if (retvalue && retvalue->store != store_return &&
2763 (retvalue->store == store_global || vec_size(retvalue->life)))
2765 /* not to be kept in OFS_RETURN */
2766 if (retvalue->vtype == TYPE_FIELD && OPTS_FLAG(ADJUST_VECTOR_FIELDS))
2767 stmt.opcode = field_store_instr[retvalue->fieldtype];
2769 stmt.opcode = type_store_instr[retvalue->vtype];
2770 stmt.o1.u1 = OFS_RETURN;
2771 stmt.o2.u1 = ir_value_code_addr(retvalue);
2773 code_push_statement(&stmt, instr->context.line);
2778 if (instr->opcode == INSTR_STATE) {
2779 irerror(block->context, "TODO: state instruction");
2783 stmt.opcode = instr->opcode;
2788 /* This is the general order of operands */
2790 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2793 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2796 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2798 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2800 stmt.o1.u1 = stmt.o3.u1;
2803 else if ((stmt.opcode >= INSTR_STORE_F &&
2804 stmt.opcode <= INSTR_STORE_FNC) ||
2805 (stmt.opcode >= INSTR_STOREP_F &&
2806 stmt.opcode <= INSTR_STOREP_FNC))
2808 /* 2-operand instructions with A -> B */
2809 stmt.o2.u1 = stmt.o3.u1;
2812 /* tiny optimization, don't output
2815 if (stmt.o2.u1 == stmt.o1.u1 &&
2816 OPTS_OPTIMIZATION(OPTIM_PEEPHOLE))
2818 ++opts_optimizationcount[OPTIM_PEEPHOLE];
2823 code_push_statement(&stmt, instr->context.line);
2828 static bool gen_function_code(ir_function *self)
2831 prog_section_statement stmt;
2833 /* Starting from entry point, we generate blocks "as they come"
2834 * for now. Dead blocks will not be translated obviously.
2836 if (!vec_size(self->blocks)) {
2837 irerror(self->context, "Function '%s' declared without body.", self->name);
2841 block = self->blocks[0];
2842 if (block->generated)
2845 if (!gen_blocks_recursive(self, block)) {
2846 irerror(self->context, "failed to generate blocks for '%s'", self->name);
2850 /* code_write and qcvm -disasm need to know that the function ends here */
2851 stmt.opcode = INSTR_DONE;
2855 code_push_statement(&stmt, vec_last(code_linenums));
2859 static qcint ir_builder_filestring(ir_builder *ir, const char *filename)
2861 /* NOTE: filename pointers are copied, we never strdup them,
2862 * thus we can use pointer-comparison to find the string.
2867 for (i = 0; i < vec_size(ir->filenames); ++i) {
2868 if (ir->filenames[i] == filename)
2869 return ir->filestrings[i];
2872 str = code_genstring(filename);
2873 vec_push(ir->filenames, filename);
2874 vec_push(ir->filestrings, str);
2878 static bool gen_global_function(ir_builder *ir, ir_value *global)
2880 prog_section_function fun;
2885 if (!global->hasvalue || (!global->constval.vfunc))
2887 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
2891 irfun = global->constval.vfunc;
2893 fun.name = global->code.name;
2894 fun.file = ir_builder_filestring(ir, global->context.file);
2895 fun.profile = 0; /* always 0 */
2896 fun.nargs = vec_size(irfun->params);
2900 for (i = 0;i < 8; ++i) {
2901 if ((int32_t)i >= fun.nargs)
2904 fun.argsize[i] = type_sizeof_[irfun->params[i]];
2908 fun.locals = irfun->allocated_locals;
2911 fun.entry = irfun->builtin+1;
2913 irfun->code_function_def = vec_size(code_functions);
2914 fun.entry = vec_size(code_statements);
2917 vec_push(code_functions, fun);
2921 static void ir_gen_extparam(ir_builder *ir)
2923 prog_section_def def;
2927 snprintf(name, sizeof(name), "EXTPARM#%i", (int)(vec_size(ir->extparams)+8));
2928 global = ir_value_var(name, store_global, TYPE_VECTOR);
2930 def.name = code_genstring(name);
2931 def.type = TYPE_VECTOR;
2932 def.offset = vec_size(code_globals);
2934 vec_push(code_defs, def);
2935 ir_value_code_setaddr(global, def.offset);
2936 vec_push(code_globals, 0);
2937 vec_push(code_globals, 0);
2938 vec_push(code_globals, 0);
2940 vec_push(ir->extparams, global);
2943 static bool gen_function_extparam_copy(ir_function *self)
2945 size_t i, ext, numparams;
2947 ir_builder *ir = self->owner;
2949 prog_section_statement stmt;
2951 numparams = vec_size(self->params);
2955 stmt.opcode = INSTR_STORE_F;
2957 for (i = 8; i < numparams; ++i) {
2959 if (ext >= vec_size(ir->extparams))
2960 ir_gen_extparam(ir);
2962 ep = ir->extparams[ext];
2964 stmt.opcode = type_store_instr[self->locals[i]->vtype];
2965 if (self->locals[i]->vtype == TYPE_FIELD &&
2966 self->locals[i]->fieldtype == TYPE_VECTOR)
2968 stmt.opcode = INSTR_STORE_V;
2970 stmt.o1.u1 = ir_value_code_addr(ep);
2971 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
2972 code_push_statement(&stmt, self->context.line);
2978 static bool gen_function_locals(ir_builder *ir, ir_value *global)
2980 prog_section_function *def;
2983 uint32_t firstlocal;
2985 irfun = global->constval.vfunc;
2986 def = code_functions + irfun->code_function_def;
2988 if (opts.g || !OPTS_OPTIMIZATION(OPTIM_OVERLAP_LOCALS) || (irfun->flags & IR_FLAG_MASK_NO_OVERLAP))
2989 firstlocal = def->firstlocal = vec_size(code_globals);
2991 firstlocal = def->firstlocal = ir->first_common_local;
2992 ++opts_optimizationcount[OPTIM_OVERLAP_LOCALS];
2995 for (i = vec_size(code_globals); i < firstlocal + irfun->allocated_locals; ++i)
2996 vec_push(code_globals, 0);
2997 for (i = 0; i < vec_size(irfun->locals); ++i) {
2998 ir_value_code_setaddr(irfun->locals[i], firstlocal + irfun->locals[i]->code.local);
2999 if (!ir_builder_gen_global(ir, irfun->locals[i], true, true)) {
3000 irerror(irfun->locals[i]->context, "failed to generate local %s", irfun->locals[i]->name);
3004 for (i = 0; i < vec_size(irfun->values); ++i)
3006 ir_value *v = irfun->values[i];
3007 ir_value_code_setaddr(v, firstlocal + v->code.local);
3012 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
3014 prog_section_function *fundef;
3019 irfun = global->constval.vfunc;
3021 if (global->cvq == CV_NONE) {
3022 irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
3023 "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
3025 /* this was a function pointer, don't generate code for those */
3032 if (irfun->code_function_def < 0) {
3033 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
3036 fundef = &code_functions[irfun->code_function_def];
3038 fundef->entry = vec_size(code_statements);
3039 if (!gen_function_locals(ir, global)) {
3040 irerror(irfun->context, "Failed to generate locals for function %s", irfun->name);
3043 if (!gen_function_extparam_copy(irfun)) {
3044 irerror(irfun->context, "Failed to generate extparam-copy code for function %s", irfun->name);
3047 if (!gen_function_code(irfun)) {
3048 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
3054 static void gen_vector_defs(prog_section_def def, const char *name)
3059 if (!name || name[0] == '#' || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3062 def.type = TYPE_FLOAT;
3066 component = (char*)mem_a(len+3);
3067 memcpy(component, name, len);
3069 component[len-0] = 0;
3070 component[len-2] = '_';
3072 component[len-1] = 'x';
3074 for (i = 0; i < 3; ++i) {
3075 def.name = code_genstring(component);
3076 vec_push(code_defs, def);
3082 static void gen_vector_fields(prog_section_field fld, const char *name)
3087 if (!name || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3090 fld.type = TYPE_FLOAT;
3094 component = (char*)mem_a(len+3);
3095 memcpy(component, name, len);
3097 component[len-0] = 0;
3098 component[len-2] = '_';
3100 component[len-1] = 'x';
3102 for (i = 0; i < 3; ++i) {
3103 fld.name = code_genstring(component);
3104 vec_push(code_fields, fld);
3110 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal, bool defs_only)
3114 prog_section_def def;
3115 bool pushdef = false;
3117 if (opts.g || !islocal)
3120 def.type = global->vtype;
3121 def.offset = vec_size(code_globals);
3123 if (OPTS_OPTIMIZATION(OPTIM_STRIP_CONSTANT_NAMES) &&
3124 (global->name[0] == '#' || global->cvq == CV_CONST))
3129 if (pushdef && global->name) {
3130 if (global->name[0] == '#') {
3131 if (!self->str_immediate)
3132 self->str_immediate = code_genstring("IMMEDIATE");
3133 def.name = global->code.name = self->str_immediate;
3136 def.name = global->code.name = code_genstring(global->name);
3141 def.offset = ir_value_code_addr(global);
3142 vec_push(code_defs, def);
3143 if (global->vtype == TYPE_VECTOR)
3144 gen_vector_defs(def, global->name);
3145 else if (global->vtype == TYPE_FIELD && global->fieldtype == TYPE_VECTOR)
3146 gen_vector_defs(def, global->name);
3153 switch (global->vtype)
3156 if (!strcmp(global->name, "end_sys_globals")) {
3157 /* TODO: remember this point... all the defs before this one
3158 * should be checksummed and added to progdefs.h when we generate it.
3161 else if (!strcmp(global->name, "end_sys_fields")) {
3162 /* TODO: same as above but for entity-fields rather than globsl
3166 irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3168 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3169 * the system fields actually go? Though the engine knows this anyway...
3170 * Maybe this could be an -foption
3171 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3173 ir_value_code_setaddr(global, vec_size(code_globals));
3174 vec_push(code_globals, 0);
3176 if (pushdef) vec_push(code_defs, def);
3179 if (pushdef) vec_push(code_defs, def);
3180 return gen_global_pointer(global);
3183 vec_push(code_defs, def);
3184 if (global->fieldtype == TYPE_VECTOR)
3185 gen_vector_defs(def, global->name);
3187 return gen_global_field(global);
3192 ir_value_code_setaddr(global, vec_size(code_globals));
3193 if (global->hasvalue) {
3194 iptr = (int32_t*)&global->constval.ivec[0];
3195 vec_push(code_globals, *iptr);
3197 vec_push(code_globals, 0);
3199 if (!islocal && global->cvq != CV_CONST)
3200 def.type |= DEF_SAVEGLOBAL;
3201 if (pushdef) vec_push(code_defs, def);
3203 return global->code.globaladdr >= 0;
3207 ir_value_code_setaddr(global, vec_size(code_globals));
3208 if (global->hasvalue) {
3209 vec_push(code_globals, code_genstring(global->constval.vstring));
3211 vec_push(code_globals, 0);
3213 if (!islocal && global->cvq != CV_CONST)
3214 def.type |= DEF_SAVEGLOBAL;
3215 if (pushdef) vec_push(code_defs, def);
3216 return global->code.globaladdr >= 0;
3221 ir_value_code_setaddr(global, vec_size(code_globals));
3222 if (global->hasvalue) {
3223 iptr = (int32_t*)&global->constval.ivec[0];
3224 vec_push(code_globals, iptr[0]);
3225 if (global->code.globaladdr < 0)
3227 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3228 vec_push(code_globals, iptr[d]);
3231 vec_push(code_globals, 0);
3232 if (global->code.globaladdr < 0)
3234 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3235 vec_push(code_globals, 0);
3238 if (!islocal && global->cvq != CV_CONST)
3239 def.type |= DEF_SAVEGLOBAL;
3242 vec_push(code_defs, def);
3243 def.type &= ~DEF_SAVEGLOBAL;
3244 gen_vector_defs(def, global->name);
3246 return global->code.globaladdr >= 0;
3249 ir_value_code_setaddr(global, vec_size(code_globals));
3250 if (!global->hasvalue) {
3251 vec_push(code_globals, 0);
3252 if (global->code.globaladdr < 0)
3255 vec_push(code_globals, vec_size(code_functions));
3256 if (!gen_global_function(self, global))
3259 if (!islocal && global->cvq != CV_CONST)
3260 def.type |= DEF_SAVEGLOBAL;
3261 if (pushdef) vec_push(code_defs, def);
3264 /* assume biggest type */
3265 ir_value_code_setaddr(global, vec_size(code_globals));
3266 vec_push(code_globals, 0);
3267 for (i = 1; i < type_sizeof_[TYPE_VARIANT]; ++i)
3268 vec_push(code_globals, 0);
3271 /* refuse to create 'void' type or any other fancy business. */
3272 irerror(global->context, "Invalid type for global variable `%s`: %s",
3273 global->name, type_name[global->vtype]);
3278 static void ir_builder_prepare_field(ir_value *field)
3280 field->code.fieldaddr = code_alloc_field(type_sizeof_[field->fieldtype]);
3283 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3285 prog_section_def def;
3286 prog_section_field fld;
3290 def.type = (uint16_t)field->vtype;
3291 def.offset = (uint16_t)vec_size(code_globals);
3293 /* create a global named the same as the field */
3294 if (opts.standard == COMPILER_GMQCC) {
3295 /* in our standard, the global gets a dot prefix */
3296 size_t len = strlen(field->name);
3299 /* we really don't want to have to allocate this, and 1024
3300 * bytes is more than enough for a variable/field name
3302 if (len+2 >= sizeof(name)) {
3303 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
3308 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
3311 def.name = code_genstring(name);
3312 fld.name = def.name + 1; /* we reuse that string table entry */
3314 /* in plain QC, there cannot be a global with the same name,
3315 * and so we also name the global the same.
3316 * FIXME: fteqcc should create a global as well
3317 * check if it actually uses the same name. Probably does
3319 def.name = code_genstring(field->name);
3320 fld.name = def.name;
3323 field->code.name = def.name;
3325 vec_push(code_defs, def);
3327 fld.type = field->fieldtype;
3329 if (fld.type == TYPE_VOID) {
3330 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
3334 fld.offset = field->code.fieldaddr;
3336 vec_push(code_fields, fld);
3338 ir_value_code_setaddr(field, vec_size(code_globals));
3339 vec_push(code_globals, fld.offset);
3340 if (fld.type == TYPE_VECTOR) {
3341 vec_push(code_globals, fld.offset+1);
3342 vec_push(code_globals, fld.offset+2);
3345 if (field->fieldtype == TYPE_VECTOR) {
3346 gen_vector_defs(def, field->name);
3347 gen_vector_fields(fld, field->name);
3350 return field->code.globaladdr >= 0;
3353 bool ir_builder_generate(ir_builder *self, const char *filename)
3355 prog_section_statement stmt;
3357 char *lnofile = NULL;
3361 for (i = 0; i < vec_size(self->fields); ++i)
3363 ir_builder_prepare_field(self->fields[i]);
3366 for (i = 0; i < vec_size(self->globals); ++i)
3368 if (!ir_builder_gen_global(self, self->globals[i], false, false)) {
3371 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3372 ir_function *func = self->globals[i]->constval.vfunc;
3373 if (func && self->max_locals < func->allocated_locals &&
3374 !(func->flags & IR_FLAG_MASK_NO_OVERLAP))
3376 self->max_locals = func->allocated_locals;
3381 for (i = 0; i < vec_size(self->fields); ++i)
3383 if (!ir_builder_gen_field(self, self->fields[i])) {
3388 /* generate common locals */
3389 self->first_common_local = vec_size(code_globals);
3390 for (i = 0; i < self->max_locals; ++i) {
3391 vec_push(code_globals, 0);
3394 /* generate function code */
3395 for (i = 0; i < vec_size(self->globals); ++i)
3397 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3398 if (!gen_global_function_code(self, self->globals[i])) {
3404 if (vec_size(code_globals) >= 65536) {
3405 irerror(vec_last(self->globals)->context, "This progs file would require more globals than the metadata can handle. Bailing out.");
3409 /* DP errors if the last instruction is not an INSTR_DONE. */
3410 if (vec_last(code_statements).opcode != INSTR_DONE)
3412 stmt.opcode = INSTR_DONE;
3416 code_push_statement(&stmt, vec_last(code_linenums));
3422 if (vec_size(code_statements) != vec_size(code_linenums)) {
3423 con_err("Linecounter wrong: %lu != %lu\n",
3424 (unsigned long)vec_size(code_statements),
3425 (unsigned long)vec_size(code_linenums));
3426 } else if (OPTS_FLAG(LNO)) {
3428 size_t filelen = strlen(filename);
3430 memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
3431 dot = strrchr(lnofile, '.');
3435 vec_shrinkto(lnofile, dot - lnofile);
3437 memcpy(vec_add(lnofile, 5), ".lno", 5);
3442 con_out("writing '%s' and '%s'...\n", filename, lnofile);
3444 con_out("writing '%s'\n", filename);
3446 if (!code_write(filename, lnofile)) {
3454 /***********************************************************************
3455 *IR DEBUG Dump functions...
3458 #define IND_BUFSZ 1024
3461 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
3464 const char *qc_opname(int op)
3466 if (op < 0) return "<INVALID>";
3467 if (op < (int)( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
3468 return asm_instr[op].m;
3470 case VINSTR_PHI: return "PHI";
3471 case VINSTR_JUMP: return "JUMP";
3472 case VINSTR_COND: return "COND";
3473 default: return "<UNK>";
3477 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
3480 char indent[IND_BUFSZ];
3484 oprintf("module %s\n", b->name);
3485 for (i = 0; i < vec_size(b->globals); ++i)
3488 if (b->globals[i]->hasvalue)
3489 oprintf("%s = ", b->globals[i]->name);
3490 ir_value_dump(b->globals[i], oprintf);
3493 for (i = 0; i < vec_size(b->functions); ++i)
3494 ir_function_dump(b->functions[i], indent, oprintf);
3495 oprintf("endmodule %s\n", b->name);
3498 void ir_function_dump(ir_function *f, char *ind,
3499 int (*oprintf)(const char*, ...))
3502 if (f->builtin != 0) {
3503 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
3506 oprintf("%sfunction %s\n", ind, f->name);
3507 strncat(ind, "\t", IND_BUFSZ);
3508 if (vec_size(f->locals))
3510 oprintf("%s%i locals:\n", ind, (int)vec_size(f->locals));
3511 for (i = 0; i < vec_size(f->locals); ++i) {
3512 oprintf("%s\t", ind);
3513 ir_value_dump(f->locals[i], oprintf);
3517 oprintf("%sliferanges:\n", ind);
3518 for (i = 0; i < vec_size(f->locals); ++i) {
3520 ir_value *v = f->locals[i];
3521 oprintf("%s\t%s: %s@%i ", ind, v->name, (v->unique_life ? "unique " : ""), (int)v->code.local);
3522 for (l = 0; l < vec_size(v->life); ++l) {
3523 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3527 for (i = 0; i < vec_size(f->values); ++i) {
3529 ir_value *v = f->values[i];
3530 oprintf("%s\t%s: @%i ", ind, v->name, (int)v->code.local);
3531 for (l = 0; l < vec_size(v->life); ++l) {
3532 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3536 if (vec_size(f->blocks))
3538 oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
3539 for (i = 0; i < vec_size(f->blocks); ++i) {
3540 if (f->blocks[i]->run_id != f->run_id) {
3541 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
3543 ir_block_dump(f->blocks[i], ind, oprintf);
3547 ind[strlen(ind)-1] = 0;
3548 oprintf("%sendfunction %s\n", ind, f->name);
3551 void ir_block_dump(ir_block* b, char *ind,
3552 int (*oprintf)(const char*, ...))
3555 oprintf("%s:%s\n", ind, b->label);
3556 strncat(ind, "\t", IND_BUFSZ);
3558 for (i = 0; i < vec_size(b->instr); ++i)
3559 ir_instr_dump(b->instr[i], ind, oprintf);
3560 ind[strlen(ind)-1] = 0;
3563 void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
3566 oprintf("%s <- phi ", in->_ops[0]->name);
3567 for (i = 0; i < vec_size(in->phi); ++i)
3569 oprintf("([%s] : %s) ", in->phi[i].from->label,
3570 in->phi[i].value->name);
3575 void ir_instr_dump(ir_instr *in, char *ind,
3576 int (*oprintf)(const char*, ...))
3579 const char *comma = NULL;
3581 oprintf("%s (%i) ", ind, (int)in->eid);
3583 if (in->opcode == VINSTR_PHI) {
3584 dump_phi(in, oprintf);
3588 strncat(ind, "\t", IND_BUFSZ);
3590 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3591 ir_value_dump(in->_ops[0], oprintf);
3592 if (in->_ops[1] || in->_ops[2])
3595 if (in->opcode == INSTR_CALL0 || in->opcode == VINSTR_NRCALL) {
3596 oprintf("CALL%i\t", vec_size(in->params));
3598 oprintf("%s\t", qc_opname(in->opcode));
3600 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3601 ir_value_dump(in->_ops[0], oprintf);
3606 for (i = 1; i != 3; ++i) {
3610 ir_value_dump(in->_ops[i], oprintf);
3618 oprintf("[%s]", in->bops[0]->label);
3622 oprintf("%s[%s]", comma, in->bops[1]->label);
3623 if (vec_size(in->params)) {
3624 oprintf("\tparams: ");
3625 for (i = 0; i != vec_size(in->params); ++i) {
3626 oprintf("%s, ", in->params[i]->name);
3630 ind[strlen(ind)-1] = 0;
3633 void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
3636 for (; *str; ++str) {
3638 case '\n': oprintf("\\n"); break;
3639 case '\r': oprintf("\\r"); break;
3640 case '\t': oprintf("\\t"); break;
3641 case '\v': oprintf("\\v"); break;
3642 case '\f': oprintf("\\f"); break;
3643 case '\b': oprintf("\\b"); break;
3644 case '\a': oprintf("\\a"); break;
3645 case '\\': oprintf("\\\\"); break;
3646 case '"': oprintf("\\\""); break;
3647 default: oprintf("%c", *str); break;
3653 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3662 oprintf("fn:%s", v->name);
3665 oprintf("%g", v->constval.vfloat);
3668 oprintf("'%g %g %g'",
3671 v->constval.vvec.z);
3674 oprintf("(entity)");
3677 ir_value_dump_string(v->constval.vstring, oprintf);
3681 oprintf("%i", v->constval.vint);
3686 v->constval.vpointer->name);
3690 oprintf("%s", v->name);
3694 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
3697 oprintf("Life of %12s:", self->name);
3698 for (i = 0; i < vec_size(self->life); ++i)
3700 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);