7 /***********************************************************************
8 * Type sizes used at multiple points in the IR codegen
11 const char *type_name[TYPE_COUNT] = {
30 static size_t type_sizeof_[TYPE_COUNT] = {
37 1, /* TYPE_FUNCTION */
48 const uint16_t type_store_instr[TYPE_COUNT] = {
49 INSTR_STORE_F, /* should use I when having integer support */
56 INSTR_STORE_ENT, /* should use I */
58 INSTR_STORE_I, /* integer type */
63 INSTR_STORE_V, /* variant, should never be accessed */
65 VINSTR_END, /* struct */
66 VINSTR_END, /* union */
67 VINSTR_END, /* array */
69 VINSTR_END, /* noexpr */
72 const uint16_t field_store_instr[TYPE_COUNT] = {
82 INSTR_STORE_FLD, /* integer type */
87 INSTR_STORE_V, /* variant, should never be accessed */
89 VINSTR_END, /* struct */
90 VINSTR_END, /* union */
91 VINSTR_END, /* array */
93 VINSTR_END, /* noexpr */
96 const uint16_t type_storep_instr[TYPE_COUNT] = {
97 INSTR_STOREP_F, /* should use I when having integer support */
104 INSTR_STOREP_ENT, /* should use I */
106 INSTR_STOREP_ENT, /* integer type */
111 INSTR_STOREP_V, /* variant, should never be accessed */
113 VINSTR_END, /* struct */
114 VINSTR_END, /* union */
115 VINSTR_END, /* array */
116 VINSTR_END, /* nil */
117 VINSTR_END, /* noexpr */
120 const uint16_t type_eq_instr[TYPE_COUNT] = {
121 INSTR_EQ_F, /* should use I when having integer support */
126 INSTR_EQ_E, /* FLD has no comparison */
128 INSTR_EQ_E, /* should use I */
135 INSTR_EQ_V, /* variant, should never be accessed */
137 VINSTR_END, /* struct */
138 VINSTR_END, /* union */
139 VINSTR_END, /* array */
140 VINSTR_END, /* nil */
141 VINSTR_END, /* noexpr */
144 const uint16_t type_ne_instr[TYPE_COUNT] = {
145 INSTR_NE_F, /* should use I when having integer support */
150 INSTR_NE_E, /* FLD has no comparison */
152 INSTR_NE_E, /* should use I */
159 INSTR_NE_V, /* variant, should never be accessed */
161 VINSTR_END, /* struct */
162 VINSTR_END, /* union */
163 VINSTR_END, /* array */
164 VINSTR_END, /* nil */
165 VINSTR_END, /* noexpr */
168 const uint16_t type_not_instr[TYPE_COUNT] = {
169 INSTR_NOT_F, /* should use I when having integer support */
170 VINSTR_END, /* not to be used, depends on string related -f flags */
176 INSTR_NOT_ENT, /* should use I */
178 INSTR_NOT_I, /* integer type */
183 INSTR_NOT_V, /* variant, should never be accessed */
185 VINSTR_END, /* struct */
186 VINSTR_END, /* union */
187 VINSTR_END, /* array */
188 VINSTR_END, /* nil */
189 VINSTR_END, /* noexpr */
193 static ir_value* ir_value_var(const char *name, int st, int vtype);
194 static bool ir_value_set_name(ir_value*, const char *name);
195 static void ir_value_dump(ir_value*, int (*oprintf)(const char*,...));
197 static ir_value* ir_gen_extparam_proto(ir_builder *ir);
198 static void ir_gen_extparam (ir_builder *ir);
200 static bool ir_builder_set_name(ir_builder *self, const char *name);
202 static ir_function* ir_function_new(ir_builder *owner, int returntype);
203 static bool ir_function_set_name(ir_function*, const char *name);
204 static void ir_function_delete(ir_function*);
205 static void ir_function_dump(ir_function*, char *ind, int (*oprintf)(const char*,...));
207 static ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx_t, const char *label,
208 int op, ir_value *a, ir_value *b, int outype);
209 static void ir_block_delete(ir_block*);
210 static ir_block* ir_block_new(ir_function *owner, const char *label);
211 static bool GMQCC_WARN ir_block_create_store(ir_block*, lex_ctx_t, ir_value *target, ir_value *what);
212 static bool ir_block_set_label(ir_block*, const char *label);
213 static void ir_block_dump(ir_block*, char *ind, int (*oprintf)(const char*,...));
215 static bool ir_instr_op(ir_instr*, int op, ir_value *value, bool writing);
216 static void ir_instr_delete(ir_instr*);
217 static void ir_instr_dump(ir_instr* in, char *ind, int (*oprintf)(const char*,...));
218 /* error functions */
220 static void irerror(lex_ctx_t ctx, const char *msg, ...)
224 con_cvprintmsg(ctx, LVL_ERROR, "internal error", msg, ap);
228 static bool GMQCC_WARN irwarning(lex_ctx_t ctx, int warntype, const char *fmt, ...)
233 r = vcompile_warning(ctx, warntype, fmt, ap);
238 /***********************************************************************
239 * Vector utility functions
242 static bool GMQCC_WARN vec_ir_value_find(ir_value **vec, const ir_value *what, size_t *idx)
245 size_t len = vec_size(vec);
246 for (i = 0; i < len; ++i) {
247 if (vec[i] == what) {
255 static bool GMQCC_WARN vec_ir_block_find(ir_block **vec, ir_block *what, size_t *idx)
258 size_t len = vec_size(vec);
259 for (i = 0; i < len; ++i) {
260 if (vec[i] == what) {
268 static bool GMQCC_WARN vec_ir_instr_find(ir_instr **vec, ir_instr *what, size_t *idx)
271 size_t len = vec_size(vec);
272 for (i = 0; i < len; ++i) {
273 if (vec[i] == what) {
281 /***********************************************************************
285 static void ir_block_delete_quick(ir_block* self);
286 static void ir_instr_delete_quick(ir_instr *self);
287 static void ir_function_delete_quick(ir_function *self);
289 ir_builder* ir_builder_new(const char *modulename)
294 self = (ir_builder*)mem_a(sizeof(*self));
298 self->functions = NULL;
299 self->globals = NULL;
301 self->filenames = NULL;
302 self->filestrings = NULL;
303 self->htglobals = util_htnew(IR_HT_SIZE);
304 self->htfields = util_htnew(IR_HT_SIZE);
305 self->htfunctions = util_htnew(IR_HT_SIZE);
307 self->extparams = NULL;
308 self->extparam_protos = NULL;
310 self->first_common_globaltemp = 0;
311 self->max_globaltemps = 0;
312 self->first_common_local = 0;
313 self->max_locals = 0;
315 self->str_immediate = 0;
317 if (!ir_builder_set_name(self, modulename)) {
322 self->nil = ir_value_var("nil", store_value, TYPE_NIL);
323 self->nil->cvq = CV_CONST;
325 for (i = 0; i != IR_MAX_VINSTR_TEMPS; ++i) {
326 /* we write to them, but they're not supposed to be used outside the IR, so
327 * let's not allow the generation of ir_instrs which use these.
328 * So it's a constant noexpr.
330 self->vinstr_temp[i] = ir_value_var("vinstr_temp", store_value, TYPE_NOEXPR);
331 self->vinstr_temp[i]->cvq = CV_CONST;
334 self->reserved_va_count = NULL;
335 self->coverage_func = NULL;
337 self->code = code_init();
342 void ir_builder_delete(ir_builder* self)
345 util_htdel(self->htglobals);
346 util_htdel(self->htfields);
347 util_htdel(self->htfunctions);
348 mem_d((void*)self->name);
349 for (i = 0; i != vec_size(self->functions); ++i) {
350 ir_function_delete_quick(self->functions[i]);
352 vec_free(self->functions);
353 for (i = 0; i != vec_size(self->extparams); ++i) {
354 ir_value_delete(self->extparams[i]);
356 vec_free(self->extparams);
357 vec_free(self->extparam_protos);
358 for (i = 0; i != vec_size(self->globals); ++i) {
359 ir_value_delete(self->globals[i]);
361 vec_free(self->globals);
362 for (i = 0; i != vec_size(self->fields); ++i) {
363 ir_value_delete(self->fields[i]);
365 ir_value_delete(self->nil);
366 for (i = 0; i != IR_MAX_VINSTR_TEMPS; ++i) {
367 ir_value_delete(self->vinstr_temp[i]);
369 vec_free(self->fields);
370 vec_free(self->filenames);
371 vec_free(self->filestrings);
373 code_cleanup(self->code);
377 bool ir_builder_set_name(ir_builder *self, const char *name)
380 mem_d((void*)self->name);
381 self->name = util_strdup(name);
385 static ir_function* ir_builder_get_function(ir_builder *self, const char *name)
387 return (ir_function*)util_htget(self->htfunctions, name);
390 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
392 ir_function *fn = ir_builder_get_function(self, name);
397 fn = ir_function_new(self, outtype);
398 if (!ir_function_set_name(fn, name))
400 ir_function_delete(fn);
403 vec_push(self->functions, fn);
404 util_htset(self->htfunctions, name, fn);
406 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
408 ir_function_delete(fn);
412 fn->value->hasvalue = true;
413 fn->value->outtype = outtype;
414 fn->value->constval.vfunc = fn;
415 fn->value->context = fn->context;
420 static ir_value* ir_builder_get_global(ir_builder *self, const char *name)
422 return (ir_value*)util_htget(self->htglobals, name);
425 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
431 ve = ir_builder_get_global(self, name);
437 ve = ir_value_var(name, store_global, vtype);
438 vec_push(self->globals, ve);
439 util_htset(self->htglobals, name, ve);
443 ir_value* ir_builder_get_va_count(ir_builder *self)
445 if (self->reserved_va_count)
446 return self->reserved_va_count;
447 return (self->reserved_va_count = ir_builder_create_global(self, "reserved:va_count", TYPE_FLOAT));
450 static ir_value* ir_builder_get_field(ir_builder *self, const char *name)
452 return (ir_value*)util_htget(self->htfields, name);
456 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
458 ir_value *ve = ir_builder_get_field(self, name);
463 ve = ir_value_var(name, store_global, TYPE_FIELD);
464 ve->fieldtype = vtype;
465 vec_push(self->fields, ve);
466 util_htset(self->htfields, name, ve);
470 /***********************************************************************
474 static bool ir_function_naive_phi(ir_function*);
475 static void ir_function_enumerate(ir_function*);
476 static bool ir_function_calculate_liferanges(ir_function*);
477 static bool ir_function_allocate_locals(ir_function*);
479 ir_function* ir_function_new(ir_builder* owner, int outtype)
482 self = (ir_function*)mem_a(sizeof(*self));
487 memset(self, 0, sizeof(*self));
490 if (!ir_function_set_name(self, "<@unnamed>")) {
497 self->context.file = "<@no context>";
498 self->context.line = 0;
499 self->outtype = outtype;
508 self->max_varargs = 0;
510 self->code_function_def = -1;
511 self->allocated_locals = 0;
512 self->globaltemps = 0;
518 bool ir_function_set_name(ir_function *self, const char *name)
521 mem_d((void*)self->name);
522 self->name = util_strdup(name);
526 static void ir_function_delete_quick(ir_function *self)
529 mem_d((void*)self->name);
531 for (i = 0; i != vec_size(self->blocks); ++i)
532 ir_block_delete_quick(self->blocks[i]);
533 vec_free(self->blocks);
535 vec_free(self->params);
537 for (i = 0; i != vec_size(self->values); ++i)
538 ir_value_delete(self->values[i]);
539 vec_free(self->values);
541 for (i = 0; i != vec_size(self->locals); ++i)
542 ir_value_delete(self->locals[i]);
543 vec_free(self->locals);
545 /* self->value is deleted by the builder */
550 void ir_function_delete(ir_function *self)
553 mem_d((void*)self->name);
555 for (i = 0; i != vec_size(self->blocks); ++i)
556 ir_block_delete(self->blocks[i]);
557 vec_free(self->blocks);
559 vec_free(self->params);
561 for (i = 0; i != vec_size(self->values); ++i)
562 ir_value_delete(self->values[i]);
563 vec_free(self->values);
565 for (i = 0; i != vec_size(self->locals); ++i)
566 ir_value_delete(self->locals[i]);
567 vec_free(self->locals);
569 /* self->value is deleted by the builder */
574 static void ir_function_collect_value(ir_function *self, ir_value *v)
576 vec_push(self->values, v);
579 ir_block* ir_function_create_block(lex_ctx_t ctx, ir_function *self, const char *label)
581 ir_block* bn = ir_block_new(self, label);
583 vec_push(self->blocks, bn);
585 if ((self->flags & IR_FLAG_BLOCK_COVERAGE) && self->owner->coverage_func)
586 (void)ir_block_create_call(bn, ctx, NULL, self->owner->coverage_func, false);
591 static bool instr_is_operation(uint16_t op)
593 return ( (op >= INSTR_MUL_F && op <= INSTR_GT) ||
594 (op >= INSTR_LOAD_F && op <= INSTR_LOAD_FNC) ||
595 (op == INSTR_ADDRESS) ||
596 (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) ||
597 (op >= INSTR_AND && op <= INSTR_BITOR) ||
598 (op >= INSTR_CALL0 && op <= INSTR_CALL8) ||
599 (op >= VINSTR_BITAND_V && op <= VINSTR_NEG_V) );
602 static bool ir_function_pass_peephole(ir_function *self)
606 for (b = 0; b < vec_size(self->blocks); ++b) {
608 ir_block *block = self->blocks[b];
610 for (i = 0; i < vec_size(block->instr); ++i) {
612 inst = block->instr[i];
615 (inst->opcode >= INSTR_STORE_F &&
616 inst->opcode <= INSTR_STORE_FNC))
624 oper = block->instr[i-1];
625 if (!instr_is_operation(oper->opcode))
628 /* Don't change semantics of MUL_VF in engines where these may not alias. */
629 if (OPTS_FLAG(LEGACY_VECTOR_MATHS)) {
630 if (oper->opcode == INSTR_MUL_VF && oper->_ops[2]->memberof == oper->_ops[1])
632 if (oper->opcode == INSTR_MUL_FV && oper->_ops[1]->memberof == oper->_ops[2])
636 value = oper->_ops[0];
638 /* only do it for SSA values */
639 if (value->store != store_value)
642 /* don't optimize out the temp if it's used later again */
643 if (vec_size(value->reads) != 1)
646 /* The very next store must use this value */
647 if (value->reads[0] != store)
650 /* And of course the store must _read_ from it, so it's in
652 if (store->_ops[1] != value)
655 ++opts_optimizationcount[OPTIM_PEEPHOLE];
656 (void)!ir_instr_op(oper, 0, store->_ops[0], true);
658 vec_remove(block->instr, i, 1);
659 ir_instr_delete(store);
661 else if (inst->opcode == VINSTR_COND)
663 /* COND on a value resulting from a NOT could
664 * remove the NOT and swap its operands
671 value = inst->_ops[0];
673 if (value->store != store_value ||
674 vec_size(value->reads) != 1 ||
675 value->reads[0] != inst)
680 inot = value->writes[0];
681 if (inot->_ops[0] != value ||
682 inot->opcode < INSTR_NOT_F ||
683 inot->opcode > INSTR_NOT_FNC ||
684 inot->opcode == INSTR_NOT_V || /* can't do these */
685 inot->opcode == INSTR_NOT_S)
691 ++opts_optimizationcount[OPTIM_PEEPHOLE];
693 (void)!ir_instr_op(inst, 0, inot->_ops[1], false);
696 for (inotid = 0; inotid < vec_size(tmp->instr); ++inotid) {
697 if (tmp->instr[inotid] == inot)
700 if (inotid >= vec_size(tmp->instr)) {
701 compile_error(inst->context, "sanity-check failed: failed to find instruction to optimize out");
704 vec_remove(tmp->instr, inotid, 1);
705 ir_instr_delete(inot);
706 /* swap ontrue/onfalse */
708 inst->bops[0] = inst->bops[1];
719 static bool ir_function_pass_tailrecursion(ir_function *self)
723 for (b = 0; b < vec_size(self->blocks); ++b) {
725 ir_instr *ret, *call, *store = NULL;
726 ir_block *block = self->blocks[b];
728 if (!block->final || vec_size(block->instr) < 2)
731 ret = block->instr[vec_size(block->instr)-1];
732 if (ret->opcode != INSTR_DONE && ret->opcode != INSTR_RETURN)
735 call = block->instr[vec_size(block->instr)-2];
736 if (call->opcode >= INSTR_STORE_F && call->opcode <= INSTR_STORE_FNC) {
737 /* account for the unoptimized
739 * STORE %return, %tmp
743 if (vec_size(block->instr) < 3)
747 call = block->instr[vec_size(block->instr)-3];
750 if (call->opcode < INSTR_CALL0 || call->opcode > INSTR_CALL8)
754 /* optimize out the STORE */
756 ret->_ops[0] == store->_ops[0] &&
757 store->_ops[1] == call->_ops[0])
759 ++opts_optimizationcount[OPTIM_PEEPHOLE];
760 call->_ops[0] = store->_ops[0];
761 vec_remove(block->instr, vec_size(block->instr) - 2, 1);
762 ir_instr_delete(store);
771 funcval = call->_ops[1];
774 if (funcval->vtype != TYPE_FUNCTION || funcval->constval.vfunc != self)
777 /* now we have a CALL and a RET, check if it's a tailcall */
778 if (ret->_ops[0] && call->_ops[0] != ret->_ops[0])
781 ++opts_optimizationcount[OPTIM_TAIL_RECURSION];
782 vec_shrinkby(block->instr, 2);
784 block->final = false; /* open it back up */
786 /* emite parameter-stores */
787 for (p = 0; p < vec_size(call->params); ++p) {
788 /* assert(call->params_count <= self->locals_count); */
789 if (!ir_block_create_store(block, call->context, self->locals[p], call->params[p])) {
790 irerror(call->context, "failed to create tailcall store instruction for parameter %i", (int)p);
794 if (!ir_block_create_jump(block, call->context, self->blocks[0])) {
795 irerror(call->context, "failed to create tailcall jump");
799 ir_instr_delete(call);
800 ir_instr_delete(ret);
806 bool ir_function_finalize(ir_function *self)
813 if (OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
814 if (!ir_function_pass_peephole(self)) {
815 irerror(self->context, "generic optimization pass broke something in `%s`", self->name);
820 if (OPTS_OPTIMIZATION(OPTIM_TAIL_RECURSION)) {
821 if (!ir_function_pass_tailrecursion(self)) {
822 irerror(self->context, "tail-recursion optimization pass broke something in `%s`", self->name);
827 if (!ir_function_naive_phi(self)) {
828 irerror(self->context, "internal error: ir_function_naive_phi failed");
832 for (i = 0; i < vec_size(self->locals); ++i) {
833 ir_value *v = self->locals[i];
834 if (v->vtype == TYPE_VECTOR ||
835 (v->vtype == TYPE_FIELD && v->outtype == TYPE_VECTOR))
837 ir_value_vector_member(v, 0);
838 ir_value_vector_member(v, 1);
839 ir_value_vector_member(v, 2);
842 for (i = 0; i < vec_size(self->values); ++i) {
843 ir_value *v = self->values[i];
844 if (v->vtype == TYPE_VECTOR ||
845 (v->vtype == TYPE_FIELD && v->outtype == TYPE_VECTOR))
847 ir_value_vector_member(v, 0);
848 ir_value_vector_member(v, 1);
849 ir_value_vector_member(v, 2);
853 ir_function_enumerate(self);
855 if (!ir_function_calculate_liferanges(self))
857 if (!ir_function_allocate_locals(self))
862 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
867 vec_size(self->locals) &&
868 self->locals[vec_size(self->locals)-1]->store != store_param) {
869 irerror(self->context, "cannot add parameters after adding locals");
873 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
876 vec_push(self->locals, ve);
880 /***********************************************************************
884 ir_block* ir_block_new(ir_function* owner, const char *name)
887 self = (ir_block*)mem_a(sizeof(*self));
891 memset(self, 0, sizeof(*self));
894 if (name && !ir_block_set_label(self, name)) {
899 self->context.file = "<@no context>";
900 self->context.line = 0;
904 self->entries = NULL;
908 self->is_return = false;
912 self->generated = false;
917 static void ir_block_delete_quick(ir_block* self)
920 if (self->label) mem_d(self->label);
921 for (i = 0; i != vec_size(self->instr); ++i)
922 ir_instr_delete_quick(self->instr[i]);
923 vec_free(self->instr);
924 vec_free(self->entries);
925 vec_free(self->exits);
926 vec_free(self->living);
930 void ir_block_delete(ir_block* self)
933 if (self->label) mem_d(self->label);
934 for (i = 0; i != vec_size(self->instr); ++i)
935 ir_instr_delete(self->instr[i]);
936 vec_free(self->instr);
937 vec_free(self->entries);
938 vec_free(self->exits);
939 vec_free(self->living);
943 bool ir_block_set_label(ir_block *self, const char *name)
946 mem_d((void*)self->label);
947 self->label = util_strdup(name);
948 return !!self->label;
951 /***********************************************************************
955 static ir_instr* ir_instr_new(lex_ctx_t ctx, ir_block* owner, int op)
958 self = (ir_instr*)mem_a(sizeof(*self));
965 self->_ops[0] = NULL;
966 self->_ops[1] = NULL;
967 self->_ops[2] = NULL;
968 self->bops[0] = NULL;
969 self->bops[1] = NULL;
980 static void ir_instr_delete_quick(ir_instr *self)
983 vec_free(self->params);
987 static void ir_instr_delete(ir_instr *self)
990 /* The following calls can only delete from
991 * vectors, we still want to delete this instruction
992 * so ignore the return value. Since with the warn_unused_result attribute
993 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
994 * I have to improvise here and use if(foo());
996 for (i = 0; i < vec_size(self->phi); ++i) {
998 if (vec_ir_instr_find(self->phi[i].value->writes, self, &idx))
999 vec_remove(self->phi[i].value->writes, idx, 1);
1000 if (vec_ir_instr_find(self->phi[i].value->reads, self, &idx))
1001 vec_remove(self->phi[i].value->reads, idx, 1);
1003 vec_free(self->phi);
1004 for (i = 0; i < vec_size(self->params); ++i) {
1006 if (vec_ir_instr_find(self->params[i]->writes, self, &idx))
1007 vec_remove(self->params[i]->writes, idx, 1);
1008 if (vec_ir_instr_find(self->params[i]->reads, self, &idx))
1009 vec_remove(self->params[i]->reads, idx, 1);
1011 vec_free(self->params);
1012 (void)!ir_instr_op(self, 0, NULL, false);
1013 (void)!ir_instr_op(self, 1, NULL, false);
1014 (void)!ir_instr_op(self, 2, NULL, false);
1018 static bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
1020 if (v && v->vtype == TYPE_NOEXPR) {
1021 irerror(self->context, "tried to use a NOEXPR value");
1025 if (self->_ops[op]) {
1027 if (writing && vec_ir_instr_find(self->_ops[op]->writes, self, &idx))
1028 vec_remove(self->_ops[op]->writes, idx, 1);
1029 else if (vec_ir_instr_find(self->_ops[op]->reads, self, &idx))
1030 vec_remove(self->_ops[op]->reads, idx, 1);
1034 vec_push(v->writes, self);
1036 vec_push(v->reads, self);
1042 /***********************************************************************
1046 static void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
1048 self->code.globaladdr = gaddr;
1049 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
1050 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
1051 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
1054 static int32_t ir_value_code_addr(const ir_value *self)
1056 if (self->store == store_return)
1057 return OFS_RETURN + self->code.addroffset;
1058 return self->code.globaladdr + self->code.addroffset;
1061 ir_value* ir_value_var(const char *name, int storetype, int vtype)
1064 self = (ir_value*)mem_a(sizeof(*self));
1065 self->vtype = vtype;
1066 self->fieldtype = TYPE_VOID;
1067 self->outtype = TYPE_VOID;
1068 self->store = storetype;
1072 self->writes = NULL;
1074 self->cvq = CV_NONE;
1075 self->hasvalue = false;
1076 self->context.file = "<@no context>";
1077 self->context.line = 0;
1079 if (name && !ir_value_set_name(self, name)) {
1080 irerror(self->context, "out of memory");
1085 memset(&self->constval, 0, sizeof(self->constval));
1086 memset(&self->code, 0, sizeof(self->code));
1088 self->members[0] = NULL;
1089 self->members[1] = NULL;
1090 self->members[2] = NULL;
1091 self->memberof = NULL;
1093 self->unique_life = false;
1094 self->locked = false;
1095 self->callparam = false;
1101 /* helper function */
1102 static ir_value* ir_builder_imm_float(ir_builder *self, float value, bool add_to_list) {
1103 ir_value *v = ir_value_var("#IMMEDIATE", store_global, TYPE_FLOAT);
1104 v->flags |= IR_FLAG_ERASABLE;
1107 v->constval.vfloat = value;
1109 vec_push(self->globals, v);
1111 vec_push(self->const_floats, v);
1115 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
1123 if (self->members[member])
1124 return self->members[member];
1127 len = strlen(self->name);
1128 name = (char*)mem_a(len + 3);
1129 memcpy(name, self->name, len);
1131 name[len+1] = 'x' + member;
1137 if (self->vtype == TYPE_VECTOR)
1139 m = ir_value_var(name, self->store, TYPE_FLOAT);
1144 m->context = self->context;
1146 self->members[member] = m;
1147 m->code.addroffset = member;
1149 else if (self->vtype == TYPE_FIELD)
1151 if (self->fieldtype != TYPE_VECTOR)
1153 m = ir_value_var(name, self->store, TYPE_FIELD);
1158 m->fieldtype = TYPE_FLOAT;
1159 m->context = self->context;
1161 self->members[member] = m;
1162 m->code.addroffset = member;
1166 irerror(self->context, "invalid member access on %s", self->name);
1174 static GMQCC_INLINE size_t ir_value_sizeof(const ir_value *self)
1176 if (self->vtype == TYPE_FIELD && self->fieldtype == TYPE_VECTOR)
1177 return type_sizeof_[TYPE_VECTOR];
1178 return type_sizeof_[self->vtype];
1181 static ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
1183 ir_value *v = ir_value_var(name, storetype, vtype);
1186 ir_function_collect_value(owner, v);
1190 void ir_value_delete(ir_value* self)
1194 mem_d((void*)self->name);
1197 if (self->vtype == TYPE_STRING)
1198 mem_d((void*)self->constval.vstring);
1200 if (!(self->flags & IR_FLAG_SPLIT_VECTOR)) {
1201 for (i = 0; i < 3; ++i) {
1202 if (self->members[i])
1203 ir_value_delete(self->members[i]);
1206 vec_free(self->reads);
1207 vec_free(self->writes);
1208 vec_free(self->life);
1212 bool ir_value_set_name(ir_value *self, const char *name)
1215 mem_d((void*)self->name);
1216 self->name = util_strdup(name);
1217 return !!self->name;
1220 bool ir_value_set_float(ir_value *self, float f)
1222 if (self->vtype != TYPE_FLOAT)
1224 self->constval.vfloat = f;
1225 self->hasvalue = true;
1229 bool ir_value_set_func(ir_value *self, int f)
1231 if (self->vtype != TYPE_FUNCTION)
1233 self->constval.vint = f;
1234 self->hasvalue = true;
1238 bool ir_value_set_vector(ir_value *self, vec3_t v)
1240 if (self->vtype != TYPE_VECTOR)
1242 self->constval.vvec = v;
1243 self->hasvalue = true;
1247 bool ir_value_set_field(ir_value *self, ir_value *fld)
1249 if (self->vtype != TYPE_FIELD)
1251 self->constval.vpointer = fld;
1252 self->hasvalue = true;
1256 bool ir_value_set_string(ir_value *self, const char *str)
1258 if (self->vtype != TYPE_STRING)
1260 self->constval.vstring = util_strdupe(str);
1261 self->hasvalue = true;
1266 bool ir_value_set_int(ir_value *self, int i)
1268 if (self->vtype != TYPE_INTEGER)
1270 self->constval.vint = i;
1271 self->hasvalue = true;
1276 bool ir_value_lives(ir_value *self, size_t at)
1279 for (i = 0; i < vec_size(self->life); ++i)
1281 ir_life_entry_t *life = &self->life[i];
1282 if (life->start <= at && at <= life->end)
1284 if (life->start > at) /* since it's ordered */
1290 static bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
1293 vec_push(self->life, e);
1294 for (k = vec_size(self->life)-1; k > idx; --k)
1295 self->life[k] = self->life[k-1];
1296 self->life[idx] = e;
1300 static bool ir_value_life_merge(ir_value *self, size_t s)
1303 const size_t vs = vec_size(self->life);
1304 ir_life_entry_t *life = NULL;
1305 ir_life_entry_t *before = NULL;
1306 ir_life_entry_t new_entry;
1308 /* Find the first range >= s */
1309 for (i = 0; i < vs; ++i)
1312 life = &self->life[i];
1313 if (life->start > s)
1316 /* nothing found? append */
1319 if (life && life->end+1 == s)
1321 /* previous life range can be merged in */
1325 if (life && life->end >= s)
1327 e.start = e.end = s;
1328 vec_push(self->life, e);
1334 if (before->end + 1 == s &&
1335 life->start - 1 == s)
1338 before->end = life->end;
1339 vec_remove(self->life, i, 1);
1342 if (before->end + 1 == s)
1348 /* already contained */
1349 if (before->end >= s)
1353 if (life->start - 1 == s)
1358 /* insert a new entry */
1359 new_entry.start = new_entry.end = s;
1360 return ir_value_life_insert(self, i, new_entry);
1363 static bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1367 if (!vec_size(other->life))
1370 if (!vec_size(self->life)) {
1371 size_t count = vec_size(other->life);
1372 ir_life_entry_t *life = vec_add(self->life, count);
1373 memcpy(life, other->life, count * sizeof(*life));
1378 for (i = 0; i < vec_size(other->life); ++i)
1380 const ir_life_entry_t *life = &other->life[i];
1383 ir_life_entry_t *entry = &self->life[myi];
1385 if (life->end+1 < entry->start)
1387 /* adding an interval before entry */
1388 if (!ir_value_life_insert(self, myi, *life))
1394 if (life->start < entry->start &&
1395 life->end+1 >= entry->start)
1397 /* starts earlier and overlaps */
1398 entry->start = life->start;
1401 if (life->end > entry->end &&
1402 life->start <= entry->end+1)
1404 /* ends later and overlaps */
1405 entry->end = life->end;
1408 /* see if our change combines it with the next ranges */
1409 while (myi+1 < vec_size(self->life) &&
1410 entry->end+1 >= self->life[1+myi].start)
1412 /* overlaps with (myi+1) */
1413 if (entry->end < self->life[1+myi].end)
1414 entry->end = self->life[1+myi].end;
1415 vec_remove(self->life, myi+1, 1);
1416 entry = &self->life[myi];
1419 /* see if we're after the entry */
1420 if (life->start > entry->end)
1423 /* append if we're at the end */
1424 if (myi >= vec_size(self->life)) {
1425 vec_push(self->life, *life);
1428 /* otherweise check the next range */
1437 static bool ir_values_overlap(const ir_value *a, const ir_value *b)
1439 /* For any life entry in A see if it overlaps with
1440 * any life entry in B.
1441 * Note that the life entries are orderes, so we can make a
1442 * more efficient algorithm there than naively translating the
1446 ir_life_entry_t *la, *lb, *enda, *endb;
1448 /* first of all, if either has no life range, they cannot clash */
1449 if (!vec_size(a->life) || !vec_size(b->life))
1454 enda = la + vec_size(a->life);
1455 endb = lb + vec_size(b->life);
1458 /* check if the entries overlap, for that,
1459 * both must start before the other one ends.
1461 if (la->start < lb->end &&
1462 lb->start < la->end)
1467 /* entries are ordered
1468 * one entry is earlier than the other
1469 * that earlier entry will be moved forward
1471 if (la->start < lb->start)
1473 /* order: A B, move A forward
1474 * check if we hit the end with A
1479 else /* if (lb->start < la->start) actually <= */
1481 /* order: B A, move B forward
1482 * check if we hit the end with B
1491 /***********************************************************************
1495 static bool ir_check_unreachable(ir_block *self)
1497 /* The IR should never have to deal with unreachable code */
1498 if (!self->final/* || OPTS_FLAG(ALLOW_UNREACHABLE_CODE)*/)
1500 irerror(self->context, "unreachable statement (%s)", self->label);
1504 bool ir_block_create_store_op(ir_block *self, lex_ctx_t ctx, int op, ir_value *target, ir_value *what)
1507 if (!ir_check_unreachable(self))
1510 if (target->store == store_value &&
1511 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1513 irerror(self->context, "cannot store to an SSA value");
1514 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1515 irerror(self->context, "instruction: %s", util_instr_str[op]);
1519 in = ir_instr_new(ctx, self, op);
1523 if (!ir_instr_op(in, 0, target, (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC)) ||
1524 !ir_instr_op(in, 1, what, false))
1526 ir_instr_delete(in);
1529 vec_push(self->instr, in);
1533 bool ir_block_create_state_op(ir_block *self, lex_ctx_t ctx, ir_value *frame, ir_value *think)
1536 if (!ir_check_unreachable(self))
1539 in = ir_instr_new(ctx, self, INSTR_STATE);
1543 if (!ir_instr_op(in, 0, frame, false) ||
1544 !ir_instr_op(in, 1, think, false))
1546 ir_instr_delete(in);
1549 vec_push(self->instr, in);
1553 static bool ir_block_create_store(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1557 if (target->vtype == TYPE_VARIANT)
1558 vtype = what->vtype;
1560 vtype = target->vtype;
1563 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1564 op = INSTR_CONV_ITOF;
1565 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1566 op = INSTR_CONV_FTOI;
1568 op = type_store_instr[vtype];
1570 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1571 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1575 return ir_block_create_store_op(self, ctx, op, target, what);
1578 bool ir_block_create_storep(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1583 if (target->vtype != TYPE_POINTER)
1586 /* storing using pointer - target is a pointer, type must be
1587 * inferred from source
1589 vtype = what->vtype;
1591 op = type_storep_instr[vtype];
1592 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1593 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1594 op = INSTR_STOREP_V;
1597 return ir_block_create_store_op(self, ctx, op, target, what);
1600 bool ir_block_create_return(ir_block *self, lex_ctx_t ctx, ir_value *v)
1603 if (!ir_check_unreachable(self))
1608 self->is_return = true;
1609 in = ir_instr_new(ctx, self, INSTR_RETURN);
1613 if (v && !ir_instr_op(in, 0, v, false)) {
1614 ir_instr_delete(in);
1618 vec_push(self->instr, in);
1622 bool ir_block_create_if(ir_block *self, lex_ctx_t ctx, ir_value *v,
1623 ir_block *ontrue, ir_block *onfalse)
1626 if (!ir_check_unreachable(self))
1629 /*in = ir_instr_new(ctx, self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1630 in = ir_instr_new(ctx, self, VINSTR_COND);
1634 if (!ir_instr_op(in, 0, v, false)) {
1635 ir_instr_delete(in);
1639 in->bops[0] = ontrue;
1640 in->bops[1] = onfalse;
1642 vec_push(self->instr, in);
1644 vec_push(self->exits, ontrue);
1645 vec_push(self->exits, onfalse);
1646 vec_push(ontrue->entries, self);
1647 vec_push(onfalse->entries, self);
1651 bool ir_block_create_jump(ir_block *self, lex_ctx_t ctx, ir_block *to)
1654 if (!ir_check_unreachable(self))
1657 in = ir_instr_new(ctx, self, VINSTR_JUMP);
1662 vec_push(self->instr, in);
1664 vec_push(self->exits, to);
1665 vec_push(to->entries, self);
1669 bool ir_block_create_goto(ir_block *self, lex_ctx_t ctx, ir_block *to)
1671 self->owner->flags |= IR_FLAG_HAS_GOTO;
1672 return ir_block_create_jump(self, ctx, to);
1675 ir_instr* ir_block_create_phi(ir_block *self, lex_ctx_t ctx, const char *label, int ot)
1679 if (!ir_check_unreachable(self))
1681 in = ir_instr_new(ctx, self, VINSTR_PHI);
1684 out = ir_value_out(self->owner, label, store_value, ot);
1686 ir_instr_delete(in);
1689 if (!ir_instr_op(in, 0, out, true)) {
1690 ir_instr_delete(in);
1691 ir_value_delete(out);
1694 vec_push(self->instr, in);
1698 ir_value* ir_phi_value(ir_instr *self)
1700 return self->_ops[0];
1703 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1707 if (!vec_ir_block_find(self->owner->entries, b, NULL)) {
1708 /* Must not be possible to cause this, otherwise the AST
1709 * is doing something wrong.
1711 irerror(self->context, "Invalid entry block for PHI");
1717 vec_push(v->reads, self);
1718 vec_push(self->phi, pe);
1721 /* call related code */
1722 ir_instr* ir_block_create_call(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *func, bool noreturn)
1726 if (!ir_check_unreachable(self))
1728 in = ir_instr_new(ctx, self, (noreturn ? VINSTR_NRCALL : INSTR_CALL0));
1733 self->is_return = true;
1735 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1737 ir_instr_delete(in);
1740 if (!ir_instr_op(in, 0, out, true) ||
1741 !ir_instr_op(in, 1, func, false))
1743 ir_instr_delete(in);
1744 ir_value_delete(out);
1747 vec_push(self->instr, in);
1750 if (!ir_block_create_return(self, ctx, NULL)) {
1751 compile_error(ctx, "internal error: failed to generate dummy-return instruction");
1752 ir_instr_delete(in);
1760 ir_value* ir_call_value(ir_instr *self)
1762 return self->_ops[0];
1765 void ir_call_param(ir_instr* self, ir_value *v)
1767 vec_push(self->params, v);
1768 vec_push(v->reads, self);
1771 /* binary op related code */
1773 ir_value* ir_block_create_binop(ir_block *self, lex_ctx_t ctx,
1774 const char *label, int opcode,
1775 ir_value *left, ir_value *right)
1798 case INSTR_SUB_S: /* -- offset of string as float */
1803 case INSTR_BITOR_IF:
1804 case INSTR_BITOR_FI:
1805 case INSTR_BITAND_FI:
1806 case INSTR_BITAND_IF:
1821 case INSTR_BITAND_I:
1824 case INSTR_RSHIFT_I:
1825 case INSTR_LSHIFT_I:
1833 case VINSTR_BITAND_V:
1834 case VINSTR_BITOR_V:
1835 case VINSTR_BITXOR_V:
1836 case VINSTR_BITAND_VF:
1837 case VINSTR_BITOR_VF:
1838 case VINSTR_BITXOR_VF:
1853 * after the following default case, the value of opcode can never
1854 * be 1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65
1858 /* boolean operations result in floats */
1861 * opcode >= 10 takes true branch opcode is at least 10
1862 * opcode <= 23 takes false branch opcode is at least 24
1864 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1868 * At condition "opcode <= 23", the value of "opcode" must be
1870 * At condition "opcode <= 23", the value of "opcode" cannot be
1871 * equal to any of {1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65}.
1872 * The condition "opcode <= 23" cannot be true.
1874 * Thus ot=2 (TYPE_FLOAT) can never be true
1877 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1879 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1884 if (ot == TYPE_VOID) {
1885 /* The AST or parser were supposed to check this! */
1889 return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1892 ir_value* ir_block_create_unary(ir_block *self, lex_ctx_t ctx,
1893 const char *label, int opcode,
1896 int ot = TYPE_FLOAT;
1902 case INSTR_NOT_FNC: /*
1903 case INSTR_NOT_I: */
1908 * Negation for virtual instructions is emulated with 0-value. Thankfully
1909 * the operand for 0 already exists so we just source it from here.
1912 return ir_block_create_general_instr(self, ctx, label, INSTR_SUB_F, NULL, operand, ot);
1914 return ir_block_create_general_instr(self, ctx, label, INSTR_SUB_V, NULL, operand, TYPE_VECTOR);
1917 ot = operand->vtype;
1920 if (ot == TYPE_VOID) {
1921 /* The AST or parser were supposed to check this! */
1925 /* let's use the general instruction creator and pass NULL for OPB */
1926 return ir_block_create_general_instr(self, ctx, label, opcode, operand, NULL, ot);
1929 static ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx_t ctx, const char *label,
1930 int op, ir_value *a, ir_value *b, int outype)
1935 out = ir_value_out(self->owner, label, store_value, outype);
1939 instr = ir_instr_new(ctx, self, op);
1941 ir_value_delete(out);
1945 if (!ir_instr_op(instr, 0, out, true) ||
1946 !ir_instr_op(instr, 1, a, false) ||
1947 !ir_instr_op(instr, 2, b, false) )
1952 vec_push(self->instr, instr);
1956 ir_instr_delete(instr);
1957 ir_value_delete(out);
1961 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *ent, ir_value *field)
1965 /* Support for various pointer types todo if so desired */
1966 if (ent->vtype != TYPE_ENTITY)
1969 if (field->vtype != TYPE_FIELD)
1972 v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1973 v->fieldtype = field->fieldtype;
1977 ir_value* ir_block_create_load_from_ent(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *ent, ir_value *field, int outype)
1980 if (ent->vtype != TYPE_ENTITY)
1983 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1984 if (field->vtype != TYPE_FIELD)
1989 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1990 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1991 case TYPE_STRING: op = INSTR_LOAD_S; break;
1992 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1993 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1994 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1996 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1997 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
2000 irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
2004 return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
2007 /* PHI resolving breaks the SSA, and must thus be the last
2008 * step before life-range calculation.
2011 static bool ir_block_naive_phi(ir_block *self);
2012 bool ir_function_naive_phi(ir_function *self)
2016 for (i = 0; i < vec_size(self->blocks); ++i)
2018 if (!ir_block_naive_phi(self->blocks[i]))
2024 static bool ir_block_naive_phi(ir_block *self)
2026 size_t i, p; /*, w;*/
2027 /* FIXME: optionally, create_phi can add the phis
2028 * to a list so we don't need to loop through blocks
2029 * - anyway: "don't optimize YET"
2031 for (i = 0; i < vec_size(self->instr); ++i)
2033 ir_instr *instr = self->instr[i];
2034 if (instr->opcode != VINSTR_PHI)
2037 vec_remove(self->instr, i, 1);
2038 --i; /* NOTE: i+1 below */
2040 for (p = 0; p < vec_size(instr->phi); ++p)
2042 ir_value *v = instr->phi[p].value;
2043 ir_block *b = instr->phi[p].from;
2045 if (v->store == store_value &&
2046 vec_size(v->reads) == 1 &&
2047 vec_size(v->writes) == 1)
2049 /* replace the value */
2050 if (!ir_instr_op(v->writes[0], 0, instr->_ops[0], true))
2055 /* force a move instruction */
2056 ir_instr *prevjump = vec_last(b->instr);
2059 instr->_ops[0]->store = store_global;
2060 if (!ir_block_create_store(b, instr->context, instr->_ops[0], v))
2062 instr->_ops[0]->store = store_value;
2063 vec_push(b->instr, prevjump);
2067 ir_instr_delete(instr);
2072 /***********************************************************************
2073 *IR Temp allocation code
2074 * Propagating value life ranges by walking through the function backwards
2075 * until no more changes are made.
2076 * In theory this should happen once more than once for every nested loop
2078 * Though this implementation might run an additional time for if nests.
2081 /* Enumerate instructions used by value's life-ranges
2083 static void ir_block_enumerate(ir_block *self, size_t *_eid)
2087 for (i = 0; i < vec_size(self->instr); ++i)
2089 self->instr[i]->eid = eid++;
2094 /* Enumerate blocks and instructions.
2095 * The block-enumeration is unordered!
2096 * We do not really use the block enumreation, however
2097 * the instruction enumeration is important for life-ranges.
2099 void ir_function_enumerate(ir_function *self)
2102 size_t instruction_id = 0;
2103 for (i = 0; i < vec_size(self->blocks); ++i)
2105 /* each block now gets an additional "entry" instruction id
2106 * we can use to avoid point-life issues
2108 self->blocks[i]->entry_id = instruction_id;
2111 self->blocks[i]->eid = i;
2112 ir_block_enumerate(self->blocks[i], &instruction_id);
2116 /* Local-value allocator
2117 * After finishing creating the liferange of all values used in a function
2118 * we can allocate their global-positions.
2119 * This is the counterpart to register-allocation in register machines.
2126 } function_allocator;
2128 static bool function_allocator_alloc(function_allocator *alloc, ir_value *var)
2131 size_t vsize = ir_value_sizeof(var);
2133 var->code.local = vec_size(alloc->locals);
2135 slot = ir_value_var("reg", store_global, var->vtype);
2139 if (!ir_value_life_merge_into(slot, var))
2142 vec_push(alloc->locals, slot);
2143 vec_push(alloc->sizes, vsize);
2144 vec_push(alloc->unique, var->unique_life);
2149 ir_value_delete(slot);
2153 static bool ir_function_allocator_assign(ir_function *self, function_allocator *alloc, ir_value *v)
2159 return function_allocator_alloc(alloc, v);
2161 for (a = 0; a < vec_size(alloc->locals); ++a)
2163 /* if it's reserved for a unique liferange: skip */
2164 if (alloc->unique[a])
2167 slot = alloc->locals[a];
2169 /* never resize parameters
2170 * will be required later when overlapping temps + locals
2172 if (a < vec_size(self->params) &&
2173 alloc->sizes[a] < ir_value_sizeof(v))
2178 if (ir_values_overlap(v, slot))
2181 if (!ir_value_life_merge_into(slot, v))
2184 /* adjust size for this slot */
2185 if (alloc->sizes[a] < ir_value_sizeof(v))
2186 alloc->sizes[a] = ir_value_sizeof(v);
2191 if (a >= vec_size(alloc->locals)) {
2192 if (!function_allocator_alloc(alloc, v))
2198 bool ir_function_allocate_locals(ir_function *self)
2203 bool opt_gt = OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS);
2207 function_allocator lockalloc, globalloc;
2209 if (!vec_size(self->locals) && !vec_size(self->values))
2212 globalloc.locals = NULL;
2213 globalloc.sizes = NULL;
2214 globalloc.positions = NULL;
2215 globalloc.unique = NULL;
2216 lockalloc.locals = NULL;
2217 lockalloc.sizes = NULL;
2218 lockalloc.positions = NULL;
2219 lockalloc.unique = NULL;
2221 for (i = 0; i < vec_size(self->locals); ++i)
2223 v = self->locals[i];
2224 if ((self->flags & IR_FLAG_MASK_NO_LOCAL_TEMPS) || !OPTS_OPTIMIZATION(OPTIM_LOCAL_TEMPS)) {
2226 v->unique_life = true;
2228 else if (i >= vec_size(self->params))
2231 v->locked = true; /* lock parameters locals */
2232 if (!function_allocator_alloc((v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2235 for (; i < vec_size(self->locals); ++i)
2237 v = self->locals[i];
2238 if (!vec_size(v->life))
2240 if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2244 /* Allocate a slot for any value that still exists */
2245 for (i = 0; i < vec_size(self->values); ++i)
2247 v = self->values[i];
2249 if (!vec_size(v->life))
2252 /* CALL optimization:
2253 * If the value is a parameter-temp: 1 write, 1 read from a CALL
2254 * and it's not "locked", write it to the OFS_PARM directly.
2256 if (OPTS_OPTIMIZATION(OPTIM_CALL_STORES) && !v->locked && !v->unique_life) {
2257 if (vec_size(v->reads) == 1 && vec_size(v->writes) == 1 &&
2258 (v->reads[0]->opcode == VINSTR_NRCALL ||
2259 (v->reads[0]->opcode >= INSTR_CALL0 && v->reads[0]->opcode <= INSTR_CALL8)
2264 ir_instr *call = v->reads[0];
2265 if (!vec_ir_value_find(call->params, v, ¶m)) {
2266 irerror(call->context, "internal error: unlocked parameter %s not found", v->name);
2269 ++opts_optimizationcount[OPTIM_CALL_STORES];
2270 v->callparam = true;
2272 ir_value_code_setaddr(v, OFS_PARM0 + 3*param);
2274 size_t nprotos = vec_size(self->owner->extparam_protos);
2277 if (nprotos > param)
2278 ep = self->owner->extparam_protos[param];
2281 ep = ir_gen_extparam_proto(self->owner);
2282 while (++nprotos <= param)
2283 ep = ir_gen_extparam_proto(self->owner);
2285 ir_instr_op(v->writes[0], 0, ep, true);
2286 call->params[param+8] = ep;
2290 if (vec_size(v->writes) == 1 && v->writes[0]->opcode == INSTR_CALL0)
2292 v->store = store_return;
2293 if (v->members[0]) v->members[0]->store = store_return;
2294 if (v->members[1]) v->members[1]->store = store_return;
2295 if (v->members[2]) v->members[2]->store = store_return;
2296 ++opts_optimizationcount[OPTIM_CALL_STORES];
2301 if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2305 if (!lockalloc.sizes && !globalloc.sizes) {
2308 vec_push(lockalloc.positions, 0);
2309 vec_push(globalloc.positions, 0);
2311 /* Adjust slot positions based on sizes */
2312 if (lockalloc.sizes) {
2313 pos = (vec_size(lockalloc.sizes) ? lockalloc.positions[0] : 0);
2314 for (i = 1; i < vec_size(lockalloc.sizes); ++i)
2316 pos = lockalloc.positions[i-1] + lockalloc.sizes[i-1];
2317 vec_push(lockalloc.positions, pos);
2319 self->allocated_locals = pos + vec_last(lockalloc.sizes);
2321 if (globalloc.sizes) {
2322 pos = (vec_size(globalloc.sizes) ? globalloc.positions[0] : 0);
2323 for (i = 1; i < vec_size(globalloc.sizes); ++i)
2325 pos = globalloc.positions[i-1] + globalloc.sizes[i-1];
2326 vec_push(globalloc.positions, pos);
2328 self->globaltemps = pos + vec_last(globalloc.sizes);
2331 /* Locals need to know their new position */
2332 for (i = 0; i < vec_size(self->locals); ++i) {
2333 v = self->locals[i];
2334 if (v->locked || !opt_gt)
2335 v->code.local = lockalloc.positions[v->code.local];
2337 v->code.local = globalloc.positions[v->code.local];
2339 /* Take over the actual slot positions on values */
2340 for (i = 0; i < vec_size(self->values); ++i) {
2341 v = self->values[i];
2342 if (v->locked || !opt_gt)
2343 v->code.local = lockalloc.positions[v->code.local];
2345 v->code.local = globalloc.positions[v->code.local];
2353 for (i = 0; i < vec_size(lockalloc.locals); ++i)
2354 ir_value_delete(lockalloc.locals[i]);
2355 for (i = 0; i < vec_size(globalloc.locals); ++i)
2356 ir_value_delete(globalloc.locals[i]);
2357 vec_free(globalloc.unique);
2358 vec_free(globalloc.locals);
2359 vec_free(globalloc.sizes);
2360 vec_free(globalloc.positions);
2361 vec_free(lockalloc.unique);
2362 vec_free(lockalloc.locals);
2363 vec_free(lockalloc.sizes);
2364 vec_free(lockalloc.positions);
2368 /* Get information about which operand
2369 * is read from, or written to.
2371 static void ir_op_read_write(int op, size_t *read, size_t *write)
2391 case INSTR_STOREP_F:
2392 case INSTR_STOREP_V:
2393 case INSTR_STOREP_S:
2394 case INSTR_STOREP_ENT:
2395 case INSTR_STOREP_FLD:
2396 case INSTR_STOREP_FNC:
2407 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2410 const size_t vs = vec_size(self->living);
2411 bool changed = false;
2412 for (i = 0; i != vs; ++i)
2414 if (ir_value_life_merge(self->living[i], eid))
2420 static bool ir_block_living_lock(ir_block *self)
2423 bool changed = false;
2424 for (i = 0; i != vec_size(self->living); ++i)
2426 if (!self->living[i]->locked) {
2427 self->living[i]->locked = true;
2434 static bool ir_block_life_propagate(ir_block *self, bool *changed)
2438 size_t i, o, p, mem, cnt;
2439 /* bitmasks which operands are read from or written to */
2446 vec_free(self->living);
2448 p = vec_size(self->exits);
2449 for (i = 0; i < p; ++i) {
2450 ir_block *prev = self->exits[i];
2451 cnt = vec_size(prev->living);
2452 for (o = 0; o < cnt; ++o) {
2453 if (!vec_ir_value_find(self->living, prev->living[o], NULL))
2454 vec_push(self->living, prev->living[o]);
2458 i = vec_size(self->instr);
2461 instr = self->instr[i];
2463 /* See which operands are read and write operands */
2464 ir_op_read_write(instr->opcode, &read, &write);
2466 /* Go through the 3 main operands
2467 * writes first, then reads
2469 for (o = 0; o < 3; ++o)
2471 if (!instr->_ops[o]) /* no such operand */
2474 value = instr->_ops[o];
2476 /* We only care about locals */
2477 /* we also calculate parameter liferanges so that locals
2478 * can take up parameter slots */
2479 if (value->store != store_value &&
2480 value->store != store_local &&
2481 value->store != store_param)
2484 /* write operands */
2485 /* When we write to a local, we consider it "dead" for the
2486 * remaining upper part of the function, since in SSA a value
2487 * can only be written once (== created)
2492 bool in_living = vec_ir_value_find(self->living, value, &idx);
2495 /* If the value isn't alive it hasn't been read before... */
2496 /* TODO: See if the warning can be emitted during parsing or AST processing
2497 * otherwise have warning printed here.
2498 * IF printing a warning here: include filecontext_t,
2499 * and make sure it's only printed once
2500 * since this function is run multiple times.
2502 /* con_err( "Value only written %s\n", value->name); */
2503 if (ir_value_life_merge(value, instr->eid))
2506 /* since 'living' won't contain it
2507 * anymore, merge the value, since
2510 if (ir_value_life_merge(value, instr->eid))
2513 vec_remove(self->living, idx, 1);
2515 /* Removing a vector removes all members */
2516 for (mem = 0; mem < 3; ++mem) {
2517 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], &idx)) {
2518 if (ir_value_life_merge(value->members[mem], instr->eid))
2520 vec_remove(self->living, idx, 1);
2523 /* Removing the last member removes the vector */
2524 if (value->memberof) {
2525 value = value->memberof;
2526 for (mem = 0; mem < 3; ++mem) {
2527 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], NULL))
2530 if (mem == 3 && vec_ir_value_find(self->living, value, &idx)) {
2531 if (ir_value_life_merge(value, instr->eid))
2533 vec_remove(self->living, idx, 1);
2539 /* These operations need a special case as they can break when using
2540 * same source and destination operand otherwise, as the engine may
2541 * read the source multiple times. */
2542 if (instr->opcode == INSTR_MUL_VF ||
2543 instr->opcode == VINSTR_BITAND_VF ||
2544 instr->opcode == VINSTR_BITOR_VF ||
2545 instr->opcode == VINSTR_BITXOR ||
2546 instr->opcode == VINSTR_BITXOR_VF ||
2547 instr->opcode == VINSTR_BITXOR_V ||
2548 instr->opcode == VINSTR_CROSS)
2550 value = instr->_ops[2];
2551 /* the float source will get an additional lifetime */
2552 if (ir_value_life_merge(value, instr->eid+1))
2554 if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2558 if (instr->opcode == INSTR_MUL_FV ||
2559 instr->opcode == INSTR_LOAD_V ||
2560 instr->opcode == VINSTR_BITXOR ||
2561 instr->opcode == VINSTR_BITXOR_VF ||
2562 instr->opcode == VINSTR_BITXOR_V ||
2563 instr->opcode == VINSTR_CROSS)
2565 value = instr->_ops[1];
2566 /* the float source will get an additional lifetime */
2567 if (ir_value_life_merge(value, instr->eid+1))
2569 if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2573 for (o = 0; o < 3; ++o)
2575 if (!instr->_ops[o]) /* no such operand */
2578 value = instr->_ops[o];
2580 /* We only care about locals */
2581 /* we also calculate parameter liferanges so that locals
2582 * can take up parameter slots */
2583 if (value->store != store_value &&
2584 value->store != store_local &&
2585 value->store != store_param)
2591 if (!vec_ir_value_find(self->living, value, NULL))
2592 vec_push(self->living, value);
2593 /* reading adds the full vector */
2594 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2595 vec_push(self->living, value->memberof);
2596 for (mem = 0; mem < 3; ++mem) {
2597 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2598 vec_push(self->living, value->members[mem]);
2602 /* PHI operands are always read operands */
2603 for (p = 0; p < vec_size(instr->phi); ++p)
2605 value = instr->phi[p].value;
2606 if (!vec_ir_value_find(self->living, value, NULL))
2607 vec_push(self->living, value);
2608 /* reading adds the full vector */
2609 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2610 vec_push(self->living, value->memberof);
2611 for (mem = 0; mem < 3; ++mem) {
2612 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2613 vec_push(self->living, value->members[mem]);
2617 /* on a call, all these values must be "locked" */
2618 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2619 if (ir_block_living_lock(self))
2622 /* call params are read operands too */
2623 for (p = 0; p < vec_size(instr->params); ++p)
2625 value = instr->params[p];
2626 if (!vec_ir_value_find(self->living, value, NULL))
2627 vec_push(self->living, value);
2628 /* reading adds the full vector */
2629 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2630 vec_push(self->living, value->memberof);
2631 for (mem = 0; mem < 3; ++mem) {
2632 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2633 vec_push(self->living, value->members[mem]);
2638 if (ir_block_living_add_instr(self, instr->eid))
2641 /* the "entry" instruction ID */
2642 if (ir_block_living_add_instr(self, self->entry_id))
2648 bool ir_function_calculate_liferanges(ir_function *self)
2653 /* parameters live at 0 */
2654 for (i = 0; i < vec_size(self->params); ++i)
2655 if (!ir_value_life_merge(self->locals[i], 0))
2656 compile_error(self->context, "internal error: failed value-life merging");
2661 i = vec_size(self->blocks);
2663 ir_block_life_propagate(self->blocks[i], &changed);
2667 if (vec_size(self->blocks)) {
2668 ir_block *block = self->blocks[0];
2669 for (i = 0; i < vec_size(block->living); ++i) {
2670 ir_value *v = block->living[i];
2671 if (v->store != store_local)
2673 if (v->vtype == TYPE_VECTOR)
2675 self->flags |= IR_FLAG_HAS_UNINITIALIZED;
2676 /* find the instruction reading from it */
2677 for (s = 0; s < vec_size(v->reads); ++s) {
2678 if (v->reads[s]->eid == v->life[0].end)
2681 if (s < vec_size(v->reads)) {
2682 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2683 "variable `%s` may be used uninitialized in this function\n"
2686 v->reads[s]->context.file, v->reads[s]->context.line)
2694 ir_value *vec = v->memberof;
2695 for (s = 0; s < vec_size(vec->reads); ++s) {
2696 if (vec->reads[s]->eid == v->life[0].end)
2699 if (s < vec_size(vec->reads)) {
2700 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2701 "variable `%s` may be used uninitialized in this function\n"
2704 vec->reads[s]->context.file, vec->reads[s]->context.line)
2712 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2713 "variable `%s` may be used uninitialized in this function", v->name))
2722 /***********************************************************************
2725 * Since the IR has the convention of putting 'write' operands
2726 * at the beginning, we have to rotate the operands of instructions
2727 * properly in order to generate valid QCVM code.
2729 * Having destinations at a fixed position is more convenient. In QC
2730 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2731 * read from from OPA, and store to OPB rather than OPC. Which is
2732 * partially the reason why the implementation of these instructions
2733 * in darkplaces has been delayed for so long.
2735 * Breaking conventions is annoying...
2737 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2739 static bool gen_global_field(code_t *code, ir_value *global)
2741 if (global->hasvalue)
2743 ir_value *fld = global->constval.vpointer;
2745 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2749 /* copy the field's value */
2750 ir_value_code_setaddr(global, vec_size(code->globals));
2751 vec_push(code->globals, fld->code.fieldaddr);
2752 if (global->fieldtype == TYPE_VECTOR) {
2753 vec_push(code->globals, fld->code.fieldaddr+1);
2754 vec_push(code->globals, fld->code.fieldaddr+2);
2759 ir_value_code_setaddr(global, vec_size(code->globals));
2760 vec_push(code->globals, 0);
2761 if (global->fieldtype == TYPE_VECTOR) {
2762 vec_push(code->globals, 0);
2763 vec_push(code->globals, 0);
2766 if (global->code.globaladdr < 0)
2771 static bool gen_global_pointer(code_t *code, ir_value *global)
2773 if (global->hasvalue)
2775 ir_value *target = global->constval.vpointer;
2777 irerror(global->context, "Invalid pointer constant: %s", global->name);
2778 /* NULL pointers are pointing to the NULL constant, which also
2779 * sits at address 0, but still has an ir_value for itself.
2784 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2785 * void() foo; <- proto
2786 * void() *fooptr = &foo;
2787 * void() foo = { code }
2789 if (!target->code.globaladdr) {
2790 /* FIXME: Check for the constant nullptr ir_value!
2791 * because then code.globaladdr being 0 is valid.
2793 irerror(global->context, "FIXME: Relocation support");
2797 ir_value_code_setaddr(global, vec_size(code->globals));
2798 vec_push(code->globals, target->code.globaladdr);
2802 ir_value_code_setaddr(global, vec_size(code->globals));
2803 vec_push(code->globals, 0);
2805 if (global->code.globaladdr < 0)
2810 static bool gen_blocks_recursive(code_t *code, ir_function *func, ir_block *block)
2812 prog_section_statement_t stmt;
2821 block->generated = true;
2822 block->code_start = vec_size(code->statements);
2823 for (i = 0; i < vec_size(block->instr); ++i)
2825 instr = block->instr[i];
2827 if (instr->opcode == VINSTR_PHI) {
2828 irerror(block->context, "cannot generate virtual instruction (phi)");
2832 if (instr->opcode == VINSTR_JUMP) {
2833 target = instr->bops[0];
2834 /* for uncoditional jumps, if the target hasn't been generated
2835 * yet, we generate them right here.
2837 if (!target->generated)
2838 return gen_blocks_recursive(code, func, target);
2840 /* otherwise we generate a jump instruction */
2841 stmt.opcode = INSTR_GOTO;
2842 stmt.o1.s1 = (target->code_start) - vec_size(code->statements);
2845 if (stmt.o1.s1 != 1)
2846 code_push_statement(code, &stmt, instr->context);
2848 /* no further instructions can be in this block */
2852 if (instr->opcode == VINSTR_BITXOR) {
2853 stmt.opcode = INSTR_BITOR;
2854 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2855 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2856 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2857 code_push_statement(code, &stmt, instr->context);
2858 stmt.opcode = INSTR_BITAND;
2859 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2860 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2861 stmt.o3.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2862 code_push_statement(code, &stmt, instr->context);
2863 stmt.opcode = INSTR_SUB_F;
2864 stmt.o1.s1 = ir_value_code_addr(instr->_ops[0]);
2865 stmt.o2.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2866 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2867 code_push_statement(code, &stmt, instr->context);
2869 /* instruction generated */
2873 if (instr->opcode == VINSTR_BITAND_V) {
2874 stmt.opcode = INSTR_BITAND;
2875 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2876 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2877 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2878 code_push_statement(code, &stmt, instr->context);
2882 code_push_statement(code, &stmt, instr->context);
2886 code_push_statement(code, &stmt, instr->context);
2888 /* instruction generated */
2892 if (instr->opcode == VINSTR_BITOR_V) {
2893 stmt.opcode = INSTR_BITOR;
2894 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2895 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2896 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2897 code_push_statement(code, &stmt, instr->context);
2901 code_push_statement(code, &stmt, instr->context);
2905 code_push_statement(code, &stmt, instr->context);
2907 /* instruction generated */
2911 if (instr->opcode == VINSTR_BITXOR_V) {
2912 for (j = 0; j < 3; ++j) {
2913 stmt.opcode = INSTR_BITOR;
2914 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + j;
2915 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]) + j;
2916 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]) + j;
2917 code_push_statement(code, &stmt, instr->context);
2918 stmt.opcode = INSTR_BITAND;
2919 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + j;
2920 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]) + j;
2921 stmt.o3.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]) + j;
2922 code_push_statement(code, &stmt, instr->context);
2924 stmt.opcode = INSTR_SUB_V;
2925 stmt.o1.s1 = ir_value_code_addr(instr->_ops[0]);
2926 stmt.o2.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2927 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2928 code_push_statement(code, &stmt, instr->context);
2930 /* instruction generated */
2934 if (instr->opcode == VINSTR_BITAND_VF) {
2935 stmt.opcode = INSTR_BITAND;
2936 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2937 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2938 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2939 code_push_statement(code, &stmt, instr->context);
2942 code_push_statement(code, &stmt, instr->context);
2945 code_push_statement(code, &stmt, instr->context);
2947 /* instruction generated */
2951 if (instr->opcode == VINSTR_BITOR_VF) {
2952 stmt.opcode = INSTR_BITOR;
2953 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2954 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2955 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2956 code_push_statement(code, &stmt, instr->context);
2959 code_push_statement(code, &stmt, instr->context);
2962 code_push_statement(code, &stmt, instr->context);
2964 /* instruction generated */
2968 if (instr->opcode == VINSTR_BITXOR_VF) {
2969 for (j = 0; j < 3; ++j) {
2970 stmt.opcode = INSTR_BITOR;
2971 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + j;
2972 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2973 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]) + j;
2974 code_push_statement(code, &stmt, instr->context);
2975 stmt.opcode = INSTR_BITAND;
2976 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + j;
2977 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2978 stmt.o3.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]) + j;
2979 code_push_statement(code, &stmt, instr->context);
2981 stmt.opcode = INSTR_SUB_V;
2982 stmt.o1.s1 = ir_value_code_addr(instr->_ops[0]);
2983 stmt.o2.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2984 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2985 code_push_statement(code, &stmt, instr->context);
2987 /* instruction generated */
2991 if (instr->opcode == VINSTR_CROSS) {
2992 stmt.opcode = INSTR_MUL_F;
2993 for (j = 0; j < 3; ++j) {
2994 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + (j + 1) % 3;
2995 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]) + (j + 2) % 3;
2996 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]) + j;
2997 code_push_statement(code, &stmt, instr->context);
2998 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + (j + 2) % 3;
2999 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]) + (j + 1) % 3;
3000 stmt.o3.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]) + j;
3001 code_push_statement(code, &stmt, instr->context);
3003 stmt.opcode = INSTR_SUB_V;
3004 stmt.o1.s1 = ir_value_code_addr(instr->_ops[0]);
3005 stmt.o2.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
3006 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
3007 code_push_statement(code, &stmt, instr->context);
3009 /* instruction generated */
3013 if (instr->opcode == VINSTR_COND) {
3014 ontrue = instr->bops[0];
3015 onfalse = instr->bops[1];
3016 /* TODO: have the AST signal which block should
3017 * come first: eg. optimize IFs without ELSE...
3020 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
3024 if (ontrue->generated) {
3025 stmt.opcode = INSTR_IF;
3026 stmt.o2.s1 = (ontrue->code_start) - vec_size(code->statements);
3027 if (stmt.o2.s1 != 1)
3028 code_push_statement(code, &stmt, instr->context);
3030 if (onfalse->generated) {
3031 stmt.opcode = INSTR_IFNOT;
3032 stmt.o2.s1 = (onfalse->code_start) - vec_size(code->statements);
3033 if (stmt.o2.s1 != 1)
3034 code_push_statement(code, &stmt, instr->context);
3036 if (!ontrue->generated) {
3037 if (onfalse->generated)
3038 return gen_blocks_recursive(code, func, ontrue);
3040 if (!onfalse->generated) {
3041 if (ontrue->generated)
3042 return gen_blocks_recursive(code, func, onfalse);
3044 /* neither ontrue nor onfalse exist */
3045 stmt.opcode = INSTR_IFNOT;
3046 if (!instr->likely) {
3047 /* Honor the likelyhood hint */
3048 ir_block *tmp = onfalse;
3049 stmt.opcode = INSTR_IF;
3053 stidx = vec_size(code->statements);
3054 code_push_statement(code, &stmt, instr->context);
3055 /* on false we jump, so add ontrue-path */
3056 if (!gen_blocks_recursive(code, func, ontrue))
3058 /* fixup the jump address */
3059 code->statements[stidx].o2.s1 = vec_size(code->statements) - stidx;
3060 /* generate onfalse path */
3061 if (onfalse->generated) {
3062 /* fixup the jump address */
3063 code->statements[stidx].o2.s1 = (onfalse->code_start) - (stidx);
3064 if (stidx+2 == vec_size(code->statements) && code->statements[stidx].o2.s1 == 1) {
3065 code->statements[stidx] = code->statements[stidx+1];
3066 if (code->statements[stidx].o1.s1 < 0)
3067 code->statements[stidx].o1.s1++;
3068 code_pop_statement(code);
3070 stmt.opcode = vec_last(code->statements).opcode;
3071 if (stmt.opcode == INSTR_GOTO ||
3072 stmt.opcode == INSTR_IF ||
3073 stmt.opcode == INSTR_IFNOT ||
3074 stmt.opcode == INSTR_RETURN ||
3075 stmt.opcode == INSTR_DONE)
3077 /* no use jumping from here */
3080 /* may have been generated in the previous recursive call */
3081 stmt.opcode = INSTR_GOTO;
3082 stmt.o1.s1 = (onfalse->code_start) - vec_size(code->statements);
3085 if (stmt.o1.s1 != 1)
3086 code_push_statement(code, &stmt, instr->context);
3089 else if (stidx+2 == vec_size(code->statements) && code->statements[stidx].o2.s1 == 1) {
3090 code->statements[stidx] = code->statements[stidx+1];
3091 if (code->statements[stidx].o1.s1 < 0)
3092 code->statements[stidx].o1.s1++;
3093 code_pop_statement(code);
3095 /* if not, generate now */
3096 return gen_blocks_recursive(code, func, onfalse);
3099 if ( (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8)
3100 || instr->opcode == VINSTR_NRCALL)
3105 first = vec_size(instr->params);
3108 for (p = 0; p < first; ++p)
3110 ir_value *param = instr->params[p];
3111 if (param->callparam)
3114 stmt.opcode = INSTR_STORE_F;
3117 if (param->vtype == TYPE_FIELD)
3118 stmt.opcode = field_store_instr[param->fieldtype];
3119 else if (param->vtype == TYPE_NIL)
3120 stmt.opcode = INSTR_STORE_V;
3122 stmt.opcode = type_store_instr[param->vtype];
3123 stmt.o1.u1 = ir_value_code_addr(param);
3124 stmt.o2.u1 = OFS_PARM0 + 3 * p;
3126 if (param->vtype == TYPE_VECTOR && (param->flags & IR_FLAG_SPLIT_VECTOR)) {
3127 /* fetch 3 separate floats */
3128 stmt.opcode = INSTR_STORE_F;
3129 stmt.o1.u1 = ir_value_code_addr(param->members[0]);
3130 code_push_statement(code, &stmt, instr->context);
3132 stmt.o1.u1 = ir_value_code_addr(param->members[1]);
3133 code_push_statement(code, &stmt, instr->context);
3135 stmt.o1.u1 = ir_value_code_addr(param->members[2]);
3136 code_push_statement(code, &stmt, instr->context);
3139 code_push_statement(code, &stmt, instr->context);
3141 /* Now handle extparams */
3142 first = vec_size(instr->params);
3143 for (; p < first; ++p)
3145 ir_builder *ir = func->owner;
3146 ir_value *param = instr->params[p];
3147 ir_value *targetparam;
3149 if (param->callparam)
3152 if (p-8 >= vec_size(ir->extparams))
3153 ir_gen_extparam(ir);
3155 targetparam = ir->extparams[p-8];
3157 stmt.opcode = INSTR_STORE_F;
3160 if (param->vtype == TYPE_FIELD)
3161 stmt.opcode = field_store_instr[param->fieldtype];
3162 else if (param->vtype == TYPE_NIL)
3163 stmt.opcode = INSTR_STORE_V;
3165 stmt.opcode = type_store_instr[param->vtype];
3166 stmt.o1.u1 = ir_value_code_addr(param);
3167 stmt.o2.u1 = ir_value_code_addr(targetparam);
3168 if (param->vtype == TYPE_VECTOR && (param->flags & IR_FLAG_SPLIT_VECTOR)) {
3169 /* fetch 3 separate floats */
3170 stmt.opcode = INSTR_STORE_F;
3171 stmt.o1.u1 = ir_value_code_addr(param->members[0]);
3172 code_push_statement(code, &stmt, instr->context);
3174 stmt.o1.u1 = ir_value_code_addr(param->members[1]);
3175 code_push_statement(code, &stmt, instr->context);
3177 stmt.o1.u1 = ir_value_code_addr(param->members[2]);
3178 code_push_statement(code, &stmt, instr->context);
3181 code_push_statement(code, &stmt, instr->context);
3184 stmt.opcode = INSTR_CALL0 + vec_size(instr->params);
3185 if (stmt.opcode > INSTR_CALL8)
3186 stmt.opcode = INSTR_CALL8;
3187 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
3190 code_push_statement(code, &stmt, instr->context);
3192 retvalue = instr->_ops[0];
3193 if (retvalue && retvalue->store != store_return &&
3194 (retvalue->store == store_global || vec_size(retvalue->life)))
3196 /* not to be kept in OFS_RETURN */
3197 if (retvalue->vtype == TYPE_FIELD && OPTS_FLAG(ADJUST_VECTOR_FIELDS))
3198 stmt.opcode = field_store_instr[retvalue->fieldtype];
3200 stmt.opcode = type_store_instr[retvalue->vtype];
3201 stmt.o1.u1 = OFS_RETURN;
3202 stmt.o2.u1 = ir_value_code_addr(retvalue);
3204 code_push_statement(code, &stmt, instr->context);
3209 if (instr->opcode == INSTR_STATE) {
3210 stmt.opcode = instr->opcode;
3212 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
3214 stmt.o2.u1 = ir_value_code_addr(instr->_ops[1]);
3216 code_push_statement(code, &stmt, instr->context);
3220 stmt.opcode = instr->opcode;
3225 /* This is the general order of operands */
3227 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
3230 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
3233 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
3235 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
3237 stmt.o1.u1 = stmt.o3.u1;
3240 else if ((stmt.opcode >= INSTR_STORE_F &&
3241 stmt.opcode <= INSTR_STORE_FNC) ||
3242 (stmt.opcode >= INSTR_STOREP_F &&
3243 stmt.opcode <= INSTR_STOREP_FNC))
3245 /* 2-operand instructions with A -> B */
3246 stmt.o2.u1 = stmt.o3.u1;
3249 /* tiny optimization, don't output
3252 if (stmt.o2.u1 == stmt.o1.u1 &&
3253 OPTS_OPTIMIZATION(OPTIM_PEEPHOLE))
3255 ++opts_optimizationcount[OPTIM_PEEPHOLE];
3259 code_push_statement(code, &stmt, instr->context);
3264 static bool gen_function_code(code_t *code, ir_function *self)
3267 prog_section_statement_t stmt, *retst;
3269 /* Starting from entry point, we generate blocks "as they come"
3270 * for now. Dead blocks will not be translated obviously.
3272 if (!vec_size(self->blocks)) {
3273 irerror(self->context, "Function '%s' declared without body.", self->name);
3277 block = self->blocks[0];
3278 if (block->generated)
3281 if (!gen_blocks_recursive(code, self, block)) {
3282 irerror(self->context, "failed to generate blocks for '%s'", self->name);
3286 /* code_write and qcvm -disasm need to know that the function ends here */
3287 retst = &vec_last(code->statements);
3288 if (OPTS_OPTIMIZATION(OPTIM_VOID_RETURN) &&
3289 self->outtype == TYPE_VOID &&
3290 retst->opcode == INSTR_RETURN &&
3291 !retst->o1.u1 && !retst->o2.u1 && !retst->o3.u1)
3293 retst->opcode = INSTR_DONE;
3294 ++opts_optimizationcount[OPTIM_VOID_RETURN];
3298 stmt.opcode = INSTR_DONE;
3302 last.line = vec_last(code->linenums);
3303 last.column = vec_last(code->columnnums);
3305 code_push_statement(code, &stmt, last);
3310 static qcint_t ir_builder_filestring(ir_builder *ir, const char *filename)
3312 /* NOTE: filename pointers are copied, we never strdup them,
3313 * thus we can use pointer-comparison to find the string.
3318 for (i = 0; i < vec_size(ir->filenames); ++i) {
3319 if (ir->filenames[i] == filename)
3320 return ir->filestrings[i];
3323 str = code_genstring(ir->code, filename);
3324 vec_push(ir->filenames, filename);
3325 vec_push(ir->filestrings, str);
3329 static bool gen_global_function(ir_builder *ir, ir_value *global)
3331 prog_section_function_t fun;
3336 if (!global->hasvalue || (!global->constval.vfunc))
3338 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
3342 irfun = global->constval.vfunc;
3344 fun.name = global->code.name;
3345 fun.file = ir_builder_filestring(ir, global->context.file);
3346 fun.profile = 0; /* always 0 */
3347 fun.nargs = vec_size(irfun->params);
3351 for (i = 0;i < 8; ++i) {
3352 if ((int32_t)i >= fun.nargs)
3355 fun.argsize[i] = type_sizeof_[irfun->params[i]];
3359 fun.locals = irfun->allocated_locals;
3362 fun.entry = irfun->builtin+1;
3364 irfun->code_function_def = vec_size(ir->code->functions);
3365 fun.entry = vec_size(ir->code->statements);
3368 vec_push(ir->code->functions, fun);
3372 static ir_value* ir_gen_extparam_proto(ir_builder *ir)
3377 util_snprintf(name, sizeof(name), "EXTPARM#%i", (int)(vec_size(ir->extparam_protos)));
3378 global = ir_value_var(name, store_global, TYPE_VECTOR);
3380 vec_push(ir->extparam_protos, global);
3384 static void ir_gen_extparam(ir_builder *ir)
3386 prog_section_def_t def;
3389 if (vec_size(ir->extparam_protos) < vec_size(ir->extparams)+1)
3390 global = ir_gen_extparam_proto(ir);
3392 global = ir->extparam_protos[vec_size(ir->extparams)];
3394 def.name = code_genstring(ir->code, global->name);
3395 def.type = TYPE_VECTOR;
3396 def.offset = vec_size(ir->code->globals);
3398 vec_push(ir->code->defs, def);
3400 ir_value_code_setaddr(global, def.offset);
3402 vec_push(ir->code->globals, 0);
3403 vec_push(ir->code->globals, 0);
3404 vec_push(ir->code->globals, 0);
3406 vec_push(ir->extparams, global);
3409 static bool gen_function_extparam_copy(code_t *code, ir_function *self)
3411 size_t i, ext, numparams;
3413 ir_builder *ir = self->owner;
3415 prog_section_statement_t stmt;
3417 numparams = vec_size(self->params);
3421 stmt.opcode = INSTR_STORE_F;
3423 for (i = 8; i < numparams; ++i) {
3425 if (ext >= vec_size(ir->extparams))
3426 ir_gen_extparam(ir);
3428 ep = ir->extparams[ext];
3430 stmt.opcode = type_store_instr[self->locals[i]->vtype];
3431 if (self->locals[i]->vtype == TYPE_FIELD &&
3432 self->locals[i]->fieldtype == TYPE_VECTOR)
3434 stmt.opcode = INSTR_STORE_V;
3436 stmt.o1.u1 = ir_value_code_addr(ep);
3437 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3438 code_push_statement(code, &stmt, self->context);
3444 static bool gen_function_varargs_copy(code_t *code, ir_function *self)
3446 size_t i, ext, numparams, maxparams;
3448 ir_builder *ir = self->owner;
3450 prog_section_statement_t stmt;
3452 numparams = vec_size(self->params);
3456 stmt.opcode = INSTR_STORE_V;
3458 maxparams = numparams + self->max_varargs;
3459 for (i = numparams; i < maxparams; ++i) {
3461 stmt.o1.u1 = OFS_PARM0 + 3*i;
3462 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3463 code_push_statement(code, &stmt, self->context);
3467 while (ext >= vec_size(ir->extparams))
3468 ir_gen_extparam(ir);
3470 ep = ir->extparams[ext];
3472 stmt.o1.u1 = ir_value_code_addr(ep);
3473 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3474 code_push_statement(code, &stmt, self->context);
3480 static bool gen_function_locals(ir_builder *ir, ir_value *global)
3482 prog_section_function_t *def;
3485 uint32_t firstlocal, firstglobal;
3487 irfun = global->constval.vfunc;
3488 def = ir->code->functions + irfun->code_function_def;
3490 if (OPTS_OPTION_BOOL(OPTION_G) ||
3491 !OPTS_OPTIMIZATION(OPTIM_OVERLAP_LOCALS) ||
3492 (irfun->flags & IR_FLAG_MASK_NO_OVERLAP))
3494 firstlocal = def->firstlocal = vec_size(ir->code->globals);
3496 firstlocal = def->firstlocal = ir->first_common_local;
3497 ++opts_optimizationcount[OPTIM_OVERLAP_LOCALS];
3500 firstglobal = (OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS) ? ir->first_common_globaltemp : firstlocal);
3502 for (i = vec_size(ir->code->globals); i < firstlocal + irfun->allocated_locals; ++i)
3503 vec_push(ir->code->globals, 0);
3504 for (i = 0; i < vec_size(irfun->locals); ++i) {
3505 ir_value *v = irfun->locals[i];
3506 if (v->locked || !OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS)) {
3507 ir_value_code_setaddr(v, firstlocal + v->code.local);
3508 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
3509 irerror(irfun->locals[i]->context, "failed to generate local %s", irfun->locals[i]->name);
3514 ir_value_code_setaddr(v, firstglobal + v->code.local);
3516 for (i = 0; i < vec_size(irfun->values); ++i)
3518 ir_value *v = irfun->values[i];
3522 ir_value_code_setaddr(v, firstlocal + v->code.local);
3524 ir_value_code_setaddr(v, firstglobal + v->code.local);
3529 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
3531 prog_section_function_t *fundef;
3536 irfun = global->constval.vfunc;
3538 if (global->cvq == CV_NONE) {
3539 if (irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
3540 "function `%s` has no body and in QC implicitly becomes a function-pointer",
3543 /* Not bailing out just now. If this happens a lot you don't want to have
3544 * to rerun gmqcc for each such function.
3550 /* this was a function pointer, don't generate code for those */
3558 * If there is no definition and the thing is eraseable, we can ignore
3559 * outputting the function to begin with.
3561 if (global->flags & IR_FLAG_ERASABLE && irfun->code_function_def < 0) {
3565 if (irfun->code_function_def < 0) {
3566 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
3569 fundef = &ir->code->functions[irfun->code_function_def];
3571 fundef->entry = vec_size(ir->code->statements);
3572 if (!gen_function_locals(ir, global)) {
3573 irerror(irfun->context, "Failed to generate locals for function %s", irfun->name);
3576 if (!gen_function_extparam_copy(ir->code, irfun)) {
3577 irerror(irfun->context, "Failed to generate extparam-copy code for function %s", irfun->name);
3580 if (irfun->max_varargs && !gen_function_varargs_copy(ir->code, irfun)) {
3581 irerror(irfun->context, "Failed to generate vararg-copy code for function %s", irfun->name);
3584 if (!gen_function_code(ir->code, irfun)) {
3585 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
3591 static void gen_vector_defs(code_t *code, prog_section_def_t def, const char *name)
3596 if (!name || name[0] == '#' || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3599 def.type = TYPE_FLOAT;
3603 component = (char*)mem_a(len+3);
3604 memcpy(component, name, len);
3606 component[len-0] = 0;
3607 component[len-2] = '_';
3609 component[len-1] = 'x';
3611 for (i = 0; i < 3; ++i) {
3612 def.name = code_genstring(code, component);
3613 vec_push(code->defs, def);
3621 static void gen_vector_fields(code_t *code, prog_section_field_t fld, const char *name)
3626 if (!name || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3629 fld.type = TYPE_FLOAT;
3633 component = (char*)mem_a(len+3);
3634 memcpy(component, name, len);
3636 component[len-0] = 0;
3637 component[len-2] = '_';
3639 component[len-1] = 'x';
3641 for (i = 0; i < 3; ++i) {
3642 fld.name = code_genstring(code, component);
3643 vec_push(code->fields, fld);
3651 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
3655 prog_section_def_t def;
3656 bool pushdef = opts.optimizeoff;
3658 /* we don't generate split-vectors */
3659 if (global->vtype == TYPE_VECTOR && (global->flags & IR_FLAG_SPLIT_VECTOR))
3662 def.type = global->vtype;
3663 def.offset = vec_size(self->code->globals);
3665 if (OPTS_OPTION_BOOL(OPTION_G) || !islocal)
3670 * if we're eraseable and the function isn't referenced ignore outputting
3673 if (global->flags & IR_FLAG_ERASABLE && vec_size(global->reads) == 0) {
3677 if (OPTS_OPTIMIZATION(OPTIM_STRIP_CONSTANT_NAMES) &&
3678 !(global->flags & IR_FLAG_INCLUDE_DEF) &&
3679 (global->name[0] == '#' || global->cvq == CV_CONST))
3685 if (global->name[0] == '#') {
3686 if (!self->str_immediate)
3687 self->str_immediate = code_genstring(self->code, "IMMEDIATE");
3688 def.name = global->code.name = self->str_immediate;
3691 def.name = global->code.name = code_genstring(self->code, global->name);
3696 def.offset = ir_value_code_addr(global);
3697 vec_push(self->code->defs, def);
3698 if (global->vtype == TYPE_VECTOR)
3699 gen_vector_defs(self->code, def, global->name);
3700 else if (global->vtype == TYPE_FIELD && global->fieldtype == TYPE_VECTOR)
3701 gen_vector_defs(self->code, def, global->name);
3708 switch (global->vtype)
3711 if (!strcmp(global->name, "end_sys_globals")) {
3712 /* TODO: remember this point... all the defs before this one
3713 * should be checksummed and added to progdefs.h when we generate it.
3716 else if (!strcmp(global->name, "end_sys_fields")) {
3717 /* TODO: same as above but for entity-fields rather than globsl
3720 else if(irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3723 /* Not bailing out */
3726 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3727 * the system fields actually go? Though the engine knows this anyway...
3728 * Maybe this could be an -foption
3729 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3731 ir_value_code_setaddr(global, vec_size(self->code->globals));
3732 vec_push(self->code->globals, 0);
3734 if (pushdef) vec_push(self->code->defs, def);
3737 if (pushdef) vec_push(self->code->defs, def);
3738 return gen_global_pointer(self->code, global);
3741 vec_push(self->code->defs, def);
3742 if (global->fieldtype == TYPE_VECTOR)
3743 gen_vector_defs(self->code, def, global->name);
3745 return gen_global_field(self->code, global);
3750 ir_value_code_setaddr(global, vec_size(self->code->globals));
3751 if (global->hasvalue) {
3752 iptr = (int32_t*)&global->constval.ivec[0];
3753 vec_push(self->code->globals, *iptr);
3755 vec_push(self->code->globals, 0);
3757 if (!islocal && global->cvq != CV_CONST)
3758 def.type |= DEF_SAVEGLOBAL;
3759 if (pushdef) vec_push(self->code->defs, def);
3761 return global->code.globaladdr >= 0;
3765 ir_value_code_setaddr(global, vec_size(self->code->globals));
3766 if (global->hasvalue) {
3767 uint32_t load = code_genstring(self->code, global->constval.vstring);
3768 vec_push(self->code->globals, load);
3770 vec_push(self->code->globals, 0);
3772 if (!islocal && global->cvq != CV_CONST)
3773 def.type |= DEF_SAVEGLOBAL;
3774 if (pushdef) vec_push(self->code->defs, def);
3775 return global->code.globaladdr >= 0;
3780 ir_value_code_setaddr(global, vec_size(self->code->globals));
3781 if (global->hasvalue) {
3782 iptr = (int32_t*)&global->constval.ivec[0];
3783 vec_push(self->code->globals, iptr[0]);
3784 if (global->code.globaladdr < 0)
3786 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3787 vec_push(self->code->globals, iptr[d]);
3790 vec_push(self->code->globals, 0);
3791 if (global->code.globaladdr < 0)
3793 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3794 vec_push(self->code->globals, 0);
3797 if (!islocal && global->cvq != CV_CONST)
3798 def.type |= DEF_SAVEGLOBAL;
3801 vec_push(self->code->defs, def);
3802 def.type &= ~DEF_SAVEGLOBAL;
3803 gen_vector_defs(self->code, def, global->name);
3805 return global->code.globaladdr >= 0;
3808 ir_value_code_setaddr(global, vec_size(self->code->globals));
3809 if (!global->hasvalue) {
3810 vec_push(self->code->globals, 0);
3811 if (global->code.globaladdr < 0)
3814 vec_push(self->code->globals, vec_size(self->code->functions));
3815 if (!gen_global_function(self, global))
3818 if (!islocal && global->cvq != CV_CONST)
3819 def.type |= DEF_SAVEGLOBAL;
3820 if (pushdef) vec_push(self->code->defs, def);
3823 /* assume biggest type */
3824 ir_value_code_setaddr(global, vec_size(self->code->globals));
3825 vec_push(self->code->globals, 0);
3826 for (i = 1; i < type_sizeof_[TYPE_VARIANT]; ++i)
3827 vec_push(self->code->globals, 0);
3830 /* refuse to create 'void' type or any other fancy business. */
3831 irerror(global->context, "Invalid type for global variable `%s`: %s",
3832 global->name, type_name[global->vtype]);
3837 static GMQCC_INLINE void ir_builder_prepare_field(code_t *code, ir_value *field)
3839 field->code.fieldaddr = code_alloc_field(code, type_sizeof_[field->fieldtype]);
3842 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3844 prog_section_def_t def;
3845 prog_section_field_t fld;
3849 def.type = (uint16_t)field->vtype;
3850 def.offset = (uint16_t)vec_size(self->code->globals);
3852 /* create a global named the same as the field */
3853 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
3854 /* in our standard, the global gets a dot prefix */
3855 size_t len = strlen(field->name);
3858 /* we really don't want to have to allocate this, and 1024
3859 * bytes is more than enough for a variable/field name
3861 if (len+2 >= sizeof(name)) {
3862 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
3867 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
3870 def.name = code_genstring(self->code, name);
3871 fld.name = def.name + 1; /* we reuse that string table entry */
3873 /* in plain QC, there cannot be a global with the same name,
3874 * and so we also name the global the same.
3875 * FIXME: fteqcc should create a global as well
3876 * check if it actually uses the same name. Probably does
3878 def.name = code_genstring(self->code, field->name);
3879 fld.name = def.name;
3882 field->code.name = def.name;
3884 vec_push(self->code->defs, def);
3886 fld.type = field->fieldtype;
3888 if (fld.type == TYPE_VOID) {
3889 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
3893 fld.offset = field->code.fieldaddr;
3895 vec_push(self->code->fields, fld);
3897 ir_value_code_setaddr(field, vec_size(self->code->globals));
3898 vec_push(self->code->globals, fld.offset);
3899 if (fld.type == TYPE_VECTOR) {
3900 vec_push(self->code->globals, fld.offset+1);
3901 vec_push(self->code->globals, fld.offset+2);
3904 if (field->fieldtype == TYPE_VECTOR) {
3905 gen_vector_defs (self->code, def, field->name);
3906 gen_vector_fields(self->code, fld, field->name);
3909 return field->code.globaladdr >= 0;
3912 static void ir_builder_collect_reusables(ir_builder *builder) {
3914 ir_value **reusables = NULL;
3915 for (i = 0; i < vec_size(builder->globals); ++i) {
3916 ir_value *value = builder->globals[i];
3917 if (value->vtype != TYPE_FLOAT || !value->hasvalue)
3919 if (value->cvq == CV_CONST || (value->name && value->name[0] == '#')) {
3920 vec_push(reusables, value);
3923 builder->const_floats = reusables;
3926 static void ir_builder_split_vector(ir_builder *self, ir_value *vec) {
3928 ir_value* found[3] = { NULL, NULL, NULL };
3930 /* must not be written to */
3931 if (vec_size(vec->writes))
3933 /* must not be trying to access individual members */
3934 if (vec->members[0] || vec->members[1] || vec->members[2])
3936 /* should be actually used otherwise it won't be generated anyway */
3937 count = vec_size(vec->reads);
3941 /* may only be used directly as function parameters, so if we find some other instruction cancel */
3942 for (i = 0; i != count; ++i) {
3943 /* we only split vectors if they're used directly as parameter to a call only! */
3944 ir_instr *user = vec->reads[i];
3945 if ((user->opcode < INSTR_CALL0 || user->opcode > INSTR_CALL8) && user->opcode != VINSTR_NRCALL)
3949 vec->flags |= IR_FLAG_SPLIT_VECTOR;
3951 /* find existing floats making up the split */
3952 count = vec_size(self->const_floats);
3953 for (i = 0; i != count; ++i) {
3954 ir_value *c = self->const_floats[i];
3955 if (!found[0] && c->constval.vfloat == vec->constval.vvec.x)
3957 if (!found[1] && c->constval.vfloat == vec->constval.vvec.y)
3959 if (!found[2] && c->constval.vfloat == vec->constval.vvec.z)
3961 if (found[0] && found[1] && found[2])
3965 /* generate floats for not yet found components */
3967 found[0] = ir_builder_imm_float(self, vec->constval.vvec.x, true);
3969 if (vec->constval.vvec.y == vec->constval.vvec.x)
3970 found[1] = found[0];
3972 found[1] = ir_builder_imm_float(self, vec->constval.vvec.y, true);
3975 if (vec->constval.vvec.z == vec->constval.vvec.x)
3976 found[2] = found[0];
3977 else if (vec->constval.vvec.z == vec->constval.vvec.y)
3978 found[2] = found[1];
3980 found[2] = ir_builder_imm_float(self, vec->constval.vvec.z, true);
3983 /* the .members array should be safe to use here. */
3984 vec->members[0] = found[0];
3985 vec->members[1] = found[1];
3986 vec->members[2] = found[2];
3988 /* register the readers for these floats */
3989 count = vec_size(vec->reads);
3990 for (i = 0; i != count; ++i) {
3991 vec_push(found[0]->reads, vec->reads[i]);
3992 vec_push(found[1]->reads, vec->reads[i]);
3993 vec_push(found[2]->reads, vec->reads[i]);
3997 static void ir_builder_split_vectors(ir_builder *self) {
3998 size_t i, count = vec_size(self->globals);
3999 for (i = 0; i != count; ++i) {
4000 ir_value *v = self->globals[i];
4001 if (v->vtype != TYPE_VECTOR || !v->name || v->name[0] != '#')
4003 ir_builder_split_vector(self, self->globals[i]);
4007 bool ir_builder_generate(ir_builder *self, const char *filename)
4009 prog_section_statement_t stmt;
4011 char *lnofile = NULL;
4013 if (OPTS_FLAG(SPLIT_VECTOR_PARAMETERS)) {
4014 ir_builder_collect_reusables(self);
4015 if (vec_size(self->const_floats) > 0)
4016 ir_builder_split_vectors(self);
4019 for (i = 0; i < vec_size(self->fields); ++i)
4021 ir_builder_prepare_field(self->code, self->fields[i]);
4024 for (i = 0; i < vec_size(self->globals); ++i)
4026 if (!ir_builder_gen_global(self, self->globals[i], false)) {
4029 if (self->globals[i]->vtype == TYPE_FUNCTION) {
4030 ir_function *func = self->globals[i]->constval.vfunc;
4031 if (func && self->max_locals < func->allocated_locals &&
4032 !(func->flags & IR_FLAG_MASK_NO_OVERLAP))
4034 self->max_locals = func->allocated_locals;
4036 if (func && self->max_globaltemps < func->globaltemps)
4037 self->max_globaltemps = func->globaltemps;
4041 for (i = 0; i < vec_size(self->fields); ++i)
4043 if (!ir_builder_gen_field(self, self->fields[i])) {
4049 ir_value_code_setaddr(self->nil, vec_size(self->code->globals));
4050 vec_push(self->code->globals, 0);
4051 vec_push(self->code->globals, 0);
4052 vec_push(self->code->globals, 0);
4054 /* generate virtual-instruction temps */
4055 for (i = 0; i < IR_MAX_VINSTR_TEMPS; ++i) {
4056 ir_value_code_setaddr(self->vinstr_temp[i], vec_size(self->code->globals));
4057 vec_push(self->code->globals, 0);
4058 vec_push(self->code->globals, 0);
4059 vec_push(self->code->globals, 0);
4062 /* generate global temps */
4063 self->first_common_globaltemp = vec_size(self->code->globals);
4064 for (i = 0; i < self->max_globaltemps; ++i) {
4065 vec_push(self->code->globals, 0);
4067 /* generate common locals */
4068 self->first_common_local = vec_size(self->code->globals);
4069 for (i = 0; i < self->max_locals; ++i) {
4070 vec_push(self->code->globals, 0);
4073 /* generate function code */
4074 for (i = 0; i < vec_size(self->globals); ++i)
4076 if (self->globals[i]->vtype == TYPE_FUNCTION) {
4077 if (!gen_global_function_code(self, self->globals[i])) {
4083 if (vec_size(self->code->globals) >= 65536) {
4084 irerror(vec_last(self->globals)->context, "This progs file would require more globals than the metadata can handle (%u). Bailing out.", (unsigned int)vec_size(self->code->globals));
4088 /* DP errors if the last instruction is not an INSTR_DONE. */
4089 if (vec_last(self->code->statements).opcode != INSTR_DONE)
4093 stmt.opcode = INSTR_DONE;
4097 last.line = vec_last(self->code->linenums);
4098 last.column = vec_last(self->code->columnnums);
4100 code_push_statement(self->code, &stmt, last);
4103 if (OPTS_OPTION_BOOL(OPTION_PP_ONLY))
4106 if (vec_size(self->code->statements) != vec_size(self->code->linenums)) {
4107 con_err("Linecounter wrong: %lu != %lu\n",
4108 (unsigned long)vec_size(self->code->statements),
4109 (unsigned long)vec_size(self->code->linenums));
4110 } else if (OPTS_FLAG(LNO)) {
4112 size_t filelen = strlen(filename);
4114 memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
4115 dot = strrchr(lnofile, '.');
4119 vec_shrinkto(lnofile, dot - lnofile);
4121 memcpy(vec_add(lnofile, 5), ".lno", 5);
4124 if (!code_write(self->code, filename, lnofile)) {
4133 /***********************************************************************
4134 *IR DEBUG Dump functions...
4137 #define IND_BUFSZ 1024
4139 static const char *qc_opname(int op)
4141 if (op < 0) return "<INVALID>";
4142 if (op < VINSTR_END)
4143 return util_instr_str[op];
4145 case VINSTR_END: return "END";
4146 case VINSTR_PHI: return "PHI";
4147 case VINSTR_JUMP: return "JUMP";
4148 case VINSTR_COND: return "COND";
4149 case VINSTR_BITXOR: return "BITXOR";
4150 case VINSTR_BITAND_V: return "BITAND_V";
4151 case VINSTR_BITOR_V: return "BITOR_V";
4152 case VINSTR_BITXOR_V: return "BITXOR_V";
4153 case VINSTR_BITAND_VF: return "BITAND_VF";
4154 case VINSTR_BITOR_VF: return "BITOR_VF";
4155 case VINSTR_BITXOR_VF: return "BITXOR_VF";
4156 case VINSTR_CROSS: return "CROSS";
4157 case VINSTR_NEG_F: return "NEG_F";
4158 case VINSTR_NEG_V: return "NEG_V";
4159 default: return "<UNK>";
4163 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
4166 char indent[IND_BUFSZ];
4170 oprintf("module %s\n", b->name);
4171 for (i = 0; i < vec_size(b->globals); ++i)
4174 if (b->globals[i]->hasvalue)
4175 oprintf("%s = ", b->globals[i]->name);
4176 ir_value_dump(b->globals[i], oprintf);
4179 for (i = 0; i < vec_size(b->functions); ++i)
4180 ir_function_dump(b->functions[i], indent, oprintf);
4181 oprintf("endmodule %s\n", b->name);
4184 static const char *storenames[] = {
4185 "[global]", "[local]", "[param]", "[value]", "[return]"
4188 void ir_function_dump(ir_function *f, char *ind,
4189 int (*oprintf)(const char*, ...))
4192 if (f->builtin != 0) {
4193 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
4196 oprintf("%sfunction %s\n", ind, f->name);
4197 util_strncat(ind, "\t", IND_BUFSZ-1);
4198 if (vec_size(f->locals))
4200 oprintf("%s%i locals:\n", ind, (int)vec_size(f->locals));
4201 for (i = 0; i < vec_size(f->locals); ++i) {
4202 oprintf("%s\t", ind);
4203 ir_value_dump(f->locals[i], oprintf);
4207 oprintf("%sliferanges:\n", ind);
4208 for (i = 0; i < vec_size(f->locals); ++i) {
4209 const char *attr = "";
4211 ir_value *v = f->locals[i];
4212 if (v->unique_life && v->locked)
4213 attr = "unique,locked ";
4214 else if (v->unique_life)
4218 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
4219 storenames[v->store],
4220 attr, (v->callparam ? "callparam " : ""),
4221 (int)v->code.local);
4224 for (l = 0; l < vec_size(v->life); ++l) {
4225 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
4228 for (m = 0; m < 3; ++m) {
4229 ir_value *vm = v->members[m];
4232 oprintf("%s\t%s: @%i ", ind, vm->name, (int)vm->code.local);
4233 for (l = 0; l < vec_size(vm->life); ++l) {
4234 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
4239 for (i = 0; i < vec_size(f->values); ++i) {
4240 const char *attr = "";
4242 ir_value *v = f->values[i];
4243 if (v->unique_life && v->locked)
4244 attr = "unique,locked ";
4245 else if (v->unique_life)
4249 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
4250 storenames[v->store],
4251 attr, (v->callparam ? "callparam " : ""),
4252 (int)v->code.local);
4255 for (l = 0; l < vec_size(v->life); ++l) {
4256 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
4259 for (m = 0; m < 3; ++m) {
4260 ir_value *vm = v->members[m];
4263 if (vm->unique_life && vm->locked)
4264 attr = "unique,locked ";
4265 else if (vm->unique_life)
4267 else if (vm->locked)
4269 oprintf("%s\t%s: %s@%i ", ind, vm->name, attr, (int)vm->code.local);
4270 for (l = 0; l < vec_size(vm->life); ++l) {
4271 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
4276 if (vec_size(f->blocks))
4278 oprintf("%slife passes: %i\n", ind, (int)f->run_id);
4279 for (i = 0; i < vec_size(f->blocks); ++i) {
4280 ir_block_dump(f->blocks[i], ind, oprintf);
4284 ind[strlen(ind)-1] = 0;
4285 oprintf("%sendfunction %s\n", ind, f->name);
4288 void ir_block_dump(ir_block* b, char *ind,
4289 int (*oprintf)(const char*, ...))
4292 oprintf("%s:%s\n", ind, b->label);
4293 util_strncat(ind, "\t", IND_BUFSZ-1);
4295 if (b->instr && b->instr[0])
4296 oprintf("%s (%i) [entry]\n", ind, (int)(b->instr[0]->eid-1));
4297 for (i = 0; i < vec_size(b->instr); ++i)
4298 ir_instr_dump(b->instr[i], ind, oprintf);
4299 ind[strlen(ind)-1] = 0;
4302 static void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
4305 oprintf("%s <- phi ", in->_ops[0]->name);
4306 for (i = 0; i < vec_size(in->phi); ++i)
4308 oprintf("([%s] : %s) ", in->phi[i].from->label,
4309 in->phi[i].value->name);
4314 void ir_instr_dump(ir_instr *in, char *ind,
4315 int (*oprintf)(const char*, ...))
4318 const char *comma = NULL;
4320 oprintf("%s (%i) ", ind, (int)in->eid);
4322 if (in->opcode == VINSTR_PHI) {
4323 dump_phi(in, oprintf);
4327 util_strncat(ind, "\t", IND_BUFSZ-1);
4329 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
4330 ir_value_dump(in->_ops[0], oprintf);
4331 if (in->_ops[1] || in->_ops[2])
4334 if (in->opcode == INSTR_CALL0 || in->opcode == VINSTR_NRCALL) {
4335 oprintf("CALL%i\t", vec_size(in->params));
4337 oprintf("%s\t", qc_opname(in->opcode));
4339 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
4340 ir_value_dump(in->_ops[0], oprintf);
4345 for (i = 1; i != 3; ++i) {
4349 ir_value_dump(in->_ops[i], oprintf);
4357 oprintf("[%s]", in->bops[0]->label);
4361 oprintf("%s[%s]", comma, in->bops[1]->label);
4362 if (vec_size(in->params)) {
4363 oprintf("\tparams: ");
4364 for (i = 0; i != vec_size(in->params); ++i) {
4365 oprintf("%s, ", in->params[i]->name);
4369 ind[strlen(ind)-1] = 0;
4372 static void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
4375 for (; *str; ++str) {
4377 case '\n': oprintf("\\n"); break;
4378 case '\r': oprintf("\\r"); break;
4379 case '\t': oprintf("\\t"); break;
4380 case '\v': oprintf("\\v"); break;
4381 case '\f': oprintf("\\f"); break;
4382 case '\b': oprintf("\\b"); break;
4383 case '\a': oprintf("\\a"); break;
4384 case '\\': oprintf("\\\\"); break;
4385 case '"': oprintf("\\\""); break;
4386 default: oprintf("%c", *str); break;
4392 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
4401 oprintf("fn:%s", v->name);
4404 oprintf("%g", v->constval.vfloat);
4407 oprintf("'%g %g %g'",
4410 v->constval.vvec.z);
4413 oprintf("(entity)");
4416 ir_value_dump_string(v->constval.vstring, oprintf);
4420 oprintf("%i", v->constval.vint);
4425 v->constval.vpointer->name);
4429 oprintf("%s", v->name);
4433 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
4436 oprintf("Life of %12s:", self->name);
4437 for (i = 0; i < vec_size(self->life); ++i)
4439 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);