2 * Copyright (C) 2012, 2013, 2014
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of
7 * this software and associated documentation files (the "Software"), to deal in
8 * the Software without restriction, including without limitation the rights to
9 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 * of the Software, and to permit persons to whom the Software is furnished to do
11 * so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30 /***********************************************************************
31 * Type sizes used at multiple points in the IR codegen
34 const char *type_name[TYPE_COUNT] = {
53 static size_t type_sizeof_[TYPE_COUNT] = {
60 1, /* TYPE_FUNCTION */
71 const uint16_t type_store_instr[TYPE_COUNT] = {
72 INSTR_STORE_F, /* should use I when having integer support */
79 INSTR_STORE_ENT, /* should use I */
81 INSTR_STORE_I, /* integer type */
86 INSTR_STORE_V, /* variant, should never be accessed */
88 VINSTR_END, /* struct */
89 VINSTR_END, /* union */
90 VINSTR_END, /* array */
92 VINSTR_END, /* noexpr */
95 const uint16_t field_store_instr[TYPE_COUNT] = {
105 INSTR_STORE_FLD, /* integer type */
110 INSTR_STORE_V, /* variant, should never be accessed */
112 VINSTR_END, /* struct */
113 VINSTR_END, /* union */
114 VINSTR_END, /* array */
115 VINSTR_END, /* nil */
116 VINSTR_END, /* noexpr */
119 const uint16_t type_storep_instr[TYPE_COUNT] = {
120 INSTR_STOREP_F, /* should use I when having integer support */
127 INSTR_STOREP_ENT, /* should use I */
129 INSTR_STOREP_ENT, /* integer type */
134 INSTR_STOREP_V, /* variant, should never be accessed */
136 VINSTR_END, /* struct */
137 VINSTR_END, /* union */
138 VINSTR_END, /* array */
139 VINSTR_END, /* nil */
140 VINSTR_END, /* noexpr */
143 const uint16_t type_eq_instr[TYPE_COUNT] = {
144 INSTR_EQ_F, /* should use I when having integer support */
149 INSTR_EQ_E, /* FLD has no comparison */
151 INSTR_EQ_E, /* should use I */
158 INSTR_EQ_V, /* variant, should never be accessed */
160 VINSTR_END, /* struct */
161 VINSTR_END, /* union */
162 VINSTR_END, /* array */
163 VINSTR_END, /* nil */
164 VINSTR_END, /* noexpr */
167 const uint16_t type_ne_instr[TYPE_COUNT] = {
168 INSTR_NE_F, /* should use I when having integer support */
173 INSTR_NE_E, /* FLD has no comparison */
175 INSTR_NE_E, /* should use I */
182 INSTR_NE_V, /* variant, should never be accessed */
184 VINSTR_END, /* struct */
185 VINSTR_END, /* union */
186 VINSTR_END, /* array */
187 VINSTR_END, /* nil */
188 VINSTR_END, /* noexpr */
191 const uint16_t type_not_instr[TYPE_COUNT] = {
192 INSTR_NOT_F, /* should use I when having integer support */
193 VINSTR_END, /* not to be used, depends on string related -f flags */
199 INSTR_NOT_ENT, /* should use I */
201 INSTR_NOT_I, /* integer type */
206 INSTR_NOT_V, /* variant, should never be accessed */
208 VINSTR_END, /* struct */
209 VINSTR_END, /* union */
210 VINSTR_END, /* array */
211 VINSTR_END, /* nil */
212 VINSTR_END, /* noexpr */
216 static ir_value* ir_value_var(const char *name, int st, int vtype);
217 static bool ir_value_set_name(ir_value*, const char *name);
218 static void ir_value_dump(ir_value*, int (*oprintf)(const char*,...));
220 static ir_value* ir_gen_extparam_proto(ir_builder *ir);
221 static void ir_gen_extparam (ir_builder *ir);
223 static bool ir_builder_set_name(ir_builder *self, const char *name);
225 static ir_function* ir_function_new(struct ir_builder_s *owner, int returntype);
226 static bool ir_function_set_name(ir_function*, const char *name);
227 static void ir_function_delete(ir_function*);
228 static void ir_function_dump(ir_function*, char *ind, int (*oprintf)(const char*,...));
230 static ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx_t, const char *label,
231 int op, ir_value *a, ir_value *b, int outype);
232 static void ir_block_delete(ir_block*);
233 static ir_block* ir_block_new(struct ir_function_s *owner, const char *label);
234 static bool GMQCC_WARN ir_block_create_store(ir_block*, lex_ctx_t, ir_value *target, ir_value *what);
235 static bool ir_block_set_label(ir_block*, const char *label);
236 static void ir_block_dump(ir_block*, char *ind, int (*oprintf)(const char*,...));
238 static bool ir_instr_op(ir_instr*, int op, ir_value *value, bool writing);
239 static void ir_instr_delete(ir_instr*);
240 static void ir_instr_dump(ir_instr* in, char *ind, int (*oprintf)(const char*,...));
241 /* error functions */
243 static void irerror(lex_ctx_t ctx, const char *msg, ...)
247 con_cvprintmsg(ctx, LVL_ERROR, "internal error", msg, ap);
251 static bool GMQCC_WARN irwarning(lex_ctx_t ctx, int warntype, const char *fmt, ...)
256 r = vcompile_warning(ctx, warntype, fmt, ap);
261 /***********************************************************************
262 * Vector utility functions
265 static bool GMQCC_WARN vec_ir_value_find(ir_value **vec, const ir_value *what, size_t *idx)
268 size_t len = vec_size(vec);
269 for (i = 0; i < len; ++i) {
270 if (vec[i] == what) {
278 static bool GMQCC_WARN vec_ir_block_find(ir_block **vec, ir_block *what, size_t *idx)
281 size_t len = vec_size(vec);
282 for (i = 0; i < len; ++i) {
283 if (vec[i] == what) {
291 static bool GMQCC_WARN vec_ir_instr_find(ir_instr **vec, ir_instr *what, size_t *idx)
294 size_t len = vec_size(vec);
295 for (i = 0; i < len; ++i) {
296 if (vec[i] == what) {
304 /***********************************************************************
308 static void ir_block_delete_quick(ir_block* self);
309 static void ir_instr_delete_quick(ir_instr *self);
310 static void ir_function_delete_quick(ir_function *self);
312 ir_builder* ir_builder_new(const char *modulename)
317 self = (ir_builder*)mem_a(sizeof(*self));
321 self->functions = NULL;
322 self->globals = NULL;
324 self->filenames = NULL;
325 self->filestrings = NULL;
326 self->htglobals = util_htnew(IR_HT_SIZE);
327 self->htfields = util_htnew(IR_HT_SIZE);
328 self->htfunctions = util_htnew(IR_HT_SIZE);
330 self->extparams = NULL;
331 self->extparam_protos = NULL;
333 self->first_common_globaltemp = 0;
334 self->max_globaltemps = 0;
335 self->first_common_local = 0;
336 self->max_locals = 0;
338 self->str_immediate = 0;
340 if (!ir_builder_set_name(self, modulename)) {
345 self->nil = ir_value_var("nil", store_value, TYPE_NIL);
346 self->nil->cvq = CV_CONST;
348 for (i = 0; i != IR_MAX_VINSTR_TEMPS; ++i) {
349 /* we write to them, but they're not supposed to be used outside the IR, so
350 * let's not allow the generation of ir_instrs which use these.
351 * So it's a constant noexpr.
353 self->vinstr_temp[i] = ir_value_var("vinstr_temp", store_value, TYPE_NOEXPR);
354 self->vinstr_temp[i]->cvq = CV_CONST;
357 self->reserved_va_count = NULL;
358 self->coverage_func = NULL;
360 self->code = code_init();
365 void ir_builder_delete(ir_builder* self)
368 util_htdel(self->htglobals);
369 util_htdel(self->htfields);
370 util_htdel(self->htfunctions);
371 mem_d((void*)self->name);
372 for (i = 0; i != vec_size(self->functions); ++i) {
373 ir_function_delete_quick(self->functions[i]);
375 vec_free(self->functions);
376 for (i = 0; i != vec_size(self->extparams); ++i) {
377 ir_value_delete(self->extparams[i]);
379 vec_free(self->extparams);
380 vec_free(self->extparam_protos);
381 for (i = 0; i != vec_size(self->globals); ++i) {
382 ir_value_delete(self->globals[i]);
384 vec_free(self->globals);
385 for (i = 0; i != vec_size(self->fields); ++i) {
386 ir_value_delete(self->fields[i]);
388 ir_value_delete(self->nil);
389 for (i = 0; i != IR_MAX_VINSTR_TEMPS; ++i) {
390 ir_value_delete(self->vinstr_temp[i]);
392 vec_free(self->fields);
393 vec_free(self->filenames);
394 vec_free(self->filestrings);
396 code_cleanup(self->code);
400 bool ir_builder_set_name(ir_builder *self, const char *name)
403 mem_d((void*)self->name);
404 self->name = util_strdup(name);
408 static ir_function* ir_builder_get_function(ir_builder *self, const char *name)
410 return (ir_function*)util_htget(self->htfunctions, name);
413 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
415 ir_function *fn = ir_builder_get_function(self, name);
420 fn = ir_function_new(self, outtype);
421 if (!ir_function_set_name(fn, name))
423 ir_function_delete(fn);
426 vec_push(self->functions, fn);
427 util_htset(self->htfunctions, name, fn);
429 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
431 ir_function_delete(fn);
435 fn->value->hasvalue = true;
436 fn->value->outtype = outtype;
437 fn->value->constval.vfunc = fn;
438 fn->value->context = fn->context;
443 static ir_value* ir_builder_get_global(ir_builder *self, const char *name)
445 return (ir_value*)util_htget(self->htglobals, name);
448 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
454 ve = ir_builder_get_global(self, name);
460 ve = ir_value_var(name, store_global, vtype);
461 vec_push(self->globals, ve);
462 util_htset(self->htglobals, name, ve);
466 ir_value* ir_builder_get_va_count(ir_builder *self)
468 if (self->reserved_va_count)
469 return self->reserved_va_count;
470 return (self->reserved_va_count = ir_builder_create_global(self, "reserved:va_count", TYPE_FLOAT));
473 static ir_value* ir_builder_get_field(ir_builder *self, const char *name)
475 return (ir_value*)util_htget(self->htfields, name);
479 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
481 ir_value *ve = ir_builder_get_field(self, name);
486 ve = ir_value_var(name, store_global, TYPE_FIELD);
487 ve->fieldtype = vtype;
488 vec_push(self->fields, ve);
489 util_htset(self->htfields, name, ve);
493 /***********************************************************************
497 static bool ir_function_naive_phi(ir_function*);
498 static void ir_function_enumerate(ir_function*);
499 static bool ir_function_calculate_liferanges(ir_function*);
500 static bool ir_function_allocate_locals(ir_function*);
502 ir_function* ir_function_new(ir_builder* owner, int outtype)
505 self = (ir_function*)mem_a(sizeof(*self));
510 memset(self, 0, sizeof(*self));
513 if (!ir_function_set_name(self, "<@unnamed>")) {
520 self->context.file = "<@no context>";
521 self->context.line = 0;
522 self->outtype = outtype;
531 self->max_varargs = 0;
533 self->code_function_def = -1;
534 self->allocated_locals = 0;
535 self->globaltemps = 0;
541 bool ir_function_set_name(ir_function *self, const char *name)
544 mem_d((void*)self->name);
545 self->name = util_strdup(name);
549 static void ir_function_delete_quick(ir_function *self)
552 mem_d((void*)self->name);
554 for (i = 0; i != vec_size(self->blocks); ++i)
555 ir_block_delete_quick(self->blocks[i]);
556 vec_free(self->blocks);
558 vec_free(self->params);
560 for (i = 0; i != vec_size(self->values); ++i)
561 ir_value_delete(self->values[i]);
562 vec_free(self->values);
564 for (i = 0; i != vec_size(self->locals); ++i)
565 ir_value_delete(self->locals[i]);
566 vec_free(self->locals);
568 /* self->value is deleted by the builder */
573 void ir_function_delete(ir_function *self)
576 mem_d((void*)self->name);
578 for (i = 0; i != vec_size(self->blocks); ++i)
579 ir_block_delete(self->blocks[i]);
580 vec_free(self->blocks);
582 vec_free(self->params);
584 for (i = 0; i != vec_size(self->values); ++i)
585 ir_value_delete(self->values[i]);
586 vec_free(self->values);
588 for (i = 0; i != vec_size(self->locals); ++i)
589 ir_value_delete(self->locals[i]);
590 vec_free(self->locals);
592 /* self->value is deleted by the builder */
597 static void ir_function_collect_value(ir_function *self, ir_value *v)
599 vec_push(self->values, v);
602 ir_block* ir_function_create_block(lex_ctx_t ctx, ir_function *self, const char *label)
604 ir_block* bn = ir_block_new(self, label);
606 vec_push(self->blocks, bn);
608 if ((self->flags & IR_FLAG_BLOCK_COVERAGE) && self->owner->coverage_func)
609 (void)ir_block_create_call(bn, ctx, NULL, self->owner->coverage_func, false);
614 static bool instr_is_operation(uint16_t op)
616 return ( (op >= INSTR_MUL_F && op <= INSTR_GT) ||
617 (op >= INSTR_LOAD_F && op <= INSTR_LOAD_FNC) ||
618 (op == INSTR_ADDRESS) ||
619 (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) ||
620 (op >= INSTR_AND && op <= INSTR_BITOR) ||
621 (op >= INSTR_CALL0 && op <= INSTR_CALL8) ||
622 (op >= VINSTR_BITAND_V && op <= VINSTR_NEG_V) );
625 static bool ir_function_pass_peephole(ir_function *self)
629 for (b = 0; b < vec_size(self->blocks); ++b) {
631 ir_block *block = self->blocks[b];
633 for (i = 0; i < vec_size(block->instr); ++i) {
635 inst = block->instr[i];
638 (inst->opcode >= INSTR_STORE_F &&
639 inst->opcode <= INSTR_STORE_FNC))
647 oper = block->instr[i-1];
648 if (!instr_is_operation(oper->opcode))
651 /* Don't change semantics of MUL_VF in engines where these may not alias. */
652 if (OPTS_FLAG(LEGACY_VECTOR_MATHS)) {
653 if (oper->opcode == INSTR_MUL_VF && oper->_ops[2]->memberof == oper->_ops[1])
655 if (oper->opcode == INSTR_MUL_FV && oper->_ops[1]->memberof == oper->_ops[2])
659 value = oper->_ops[0];
661 /* only do it for SSA values */
662 if (value->store != store_value)
665 /* don't optimize out the temp if it's used later again */
666 if (vec_size(value->reads) != 1)
669 /* The very next store must use this value */
670 if (value->reads[0] != store)
673 /* And of course the store must _read_ from it, so it's in
675 if (store->_ops[1] != value)
678 ++opts_optimizationcount[OPTIM_PEEPHOLE];
679 (void)!ir_instr_op(oper, 0, store->_ops[0], true);
681 vec_remove(block->instr, i, 1);
682 ir_instr_delete(store);
684 else if (inst->opcode == VINSTR_COND)
686 /* COND on a value resulting from a NOT could
687 * remove the NOT and swap its operands
694 value = inst->_ops[0];
696 if (value->store != store_value ||
697 vec_size(value->reads) != 1 ||
698 value->reads[0] != inst)
703 inot = value->writes[0];
704 if (inot->_ops[0] != value ||
705 inot->opcode < INSTR_NOT_F ||
706 inot->opcode > INSTR_NOT_FNC ||
707 inot->opcode == INSTR_NOT_V || /* can't do these */
708 inot->opcode == INSTR_NOT_S)
714 ++opts_optimizationcount[OPTIM_PEEPHOLE];
716 (void)!ir_instr_op(inst, 0, inot->_ops[1], false);
719 for (inotid = 0; inotid < vec_size(tmp->instr); ++inotid) {
720 if (tmp->instr[inotid] == inot)
723 if (inotid >= vec_size(tmp->instr)) {
724 compile_error(inst->context, "sanity-check failed: failed to find instruction to optimize out");
727 vec_remove(tmp->instr, inotid, 1);
728 ir_instr_delete(inot);
729 /* swap ontrue/onfalse */
731 inst->bops[0] = inst->bops[1];
742 static bool ir_function_pass_tailrecursion(ir_function *self)
746 for (b = 0; b < vec_size(self->blocks); ++b) {
748 ir_instr *ret, *call, *store = NULL;
749 ir_block *block = self->blocks[b];
751 if (!block->final || vec_size(block->instr) < 2)
754 ret = block->instr[vec_size(block->instr)-1];
755 if (ret->opcode != INSTR_DONE && ret->opcode != INSTR_RETURN)
758 call = block->instr[vec_size(block->instr)-2];
759 if (call->opcode >= INSTR_STORE_F && call->opcode <= INSTR_STORE_FNC) {
760 /* account for the unoptimized
762 * STORE %return, %tmp
766 if (vec_size(block->instr) < 3)
770 call = block->instr[vec_size(block->instr)-3];
773 if (call->opcode < INSTR_CALL0 || call->opcode > INSTR_CALL8)
777 /* optimize out the STORE */
779 ret->_ops[0] == store->_ops[0] &&
780 store->_ops[1] == call->_ops[0])
782 ++opts_optimizationcount[OPTIM_PEEPHOLE];
783 call->_ops[0] = store->_ops[0];
784 vec_remove(block->instr, vec_size(block->instr) - 2, 1);
785 ir_instr_delete(store);
794 funcval = call->_ops[1];
797 if (funcval->vtype != TYPE_FUNCTION || funcval->constval.vfunc != self)
800 /* now we have a CALL and a RET, check if it's a tailcall */
801 if (ret->_ops[0] && call->_ops[0] != ret->_ops[0])
804 ++opts_optimizationcount[OPTIM_TAIL_RECURSION];
805 vec_shrinkby(block->instr, 2);
807 block->final = false; /* open it back up */
809 /* emite parameter-stores */
810 for (p = 0; p < vec_size(call->params); ++p) {
811 /* assert(call->params_count <= self->locals_count); */
812 if (!ir_block_create_store(block, call->context, self->locals[p], call->params[p])) {
813 irerror(call->context, "failed to create tailcall store instruction for parameter %i", (int)p);
817 if (!ir_block_create_jump(block, call->context, self->blocks[0])) {
818 irerror(call->context, "failed to create tailcall jump");
822 ir_instr_delete(call);
823 ir_instr_delete(ret);
829 bool ir_function_finalize(ir_function *self)
836 if (OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
837 if (!ir_function_pass_peephole(self)) {
838 irerror(self->context, "generic optimization pass broke something in `%s`", self->name);
843 if (OPTS_OPTIMIZATION(OPTIM_TAIL_RECURSION)) {
844 if (!ir_function_pass_tailrecursion(self)) {
845 irerror(self->context, "tail-recursion optimization pass broke something in `%s`", self->name);
850 if (!ir_function_naive_phi(self)) {
851 irerror(self->context, "internal error: ir_function_naive_phi failed");
855 for (i = 0; i < vec_size(self->locals); ++i) {
856 ir_value *v = self->locals[i];
857 if (v->vtype == TYPE_VECTOR ||
858 (v->vtype == TYPE_FIELD && v->outtype == TYPE_VECTOR))
860 ir_value_vector_member(v, 0);
861 ir_value_vector_member(v, 1);
862 ir_value_vector_member(v, 2);
865 for (i = 0; i < vec_size(self->values); ++i) {
866 ir_value *v = self->values[i];
867 if (v->vtype == TYPE_VECTOR ||
868 (v->vtype == TYPE_FIELD && v->outtype == TYPE_VECTOR))
870 ir_value_vector_member(v, 0);
871 ir_value_vector_member(v, 1);
872 ir_value_vector_member(v, 2);
876 ir_function_enumerate(self);
878 if (!ir_function_calculate_liferanges(self))
880 if (!ir_function_allocate_locals(self))
885 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
890 vec_size(self->locals) &&
891 self->locals[vec_size(self->locals)-1]->store != store_param) {
892 irerror(self->context, "cannot add parameters after adding locals");
896 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
899 vec_push(self->locals, ve);
903 /***********************************************************************
907 ir_block* ir_block_new(ir_function* owner, const char *name)
910 self = (ir_block*)mem_a(sizeof(*self));
914 memset(self, 0, sizeof(*self));
917 if (name && !ir_block_set_label(self, name)) {
922 self->context.file = "<@no context>";
923 self->context.line = 0;
927 self->entries = NULL;
931 self->is_return = false;
935 self->generated = false;
940 static void ir_block_delete_quick(ir_block* self)
943 if (self->label) mem_d(self->label);
944 for (i = 0; i != vec_size(self->instr); ++i)
945 ir_instr_delete_quick(self->instr[i]);
946 vec_free(self->instr);
947 vec_free(self->entries);
948 vec_free(self->exits);
949 vec_free(self->living);
953 void ir_block_delete(ir_block* self)
956 if (self->label) mem_d(self->label);
957 for (i = 0; i != vec_size(self->instr); ++i)
958 ir_instr_delete(self->instr[i]);
959 vec_free(self->instr);
960 vec_free(self->entries);
961 vec_free(self->exits);
962 vec_free(self->living);
966 bool ir_block_set_label(ir_block *self, const char *name)
969 mem_d((void*)self->label);
970 self->label = util_strdup(name);
971 return !!self->label;
974 /***********************************************************************
978 static ir_instr* ir_instr_new(lex_ctx_t ctx, ir_block* owner, int op)
981 self = (ir_instr*)mem_a(sizeof(*self));
988 self->_ops[0] = NULL;
989 self->_ops[1] = NULL;
990 self->_ops[2] = NULL;
991 self->bops[0] = NULL;
992 self->bops[1] = NULL;
1003 static void ir_instr_delete_quick(ir_instr *self)
1005 vec_free(self->phi);
1006 vec_free(self->params);
1010 static void ir_instr_delete(ir_instr *self)
1013 /* The following calls can only delete from
1014 * vectors, we still want to delete this instruction
1015 * so ignore the return value. Since with the warn_unused_result attribute
1016 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
1017 * I have to improvise here and use if(foo());
1019 for (i = 0; i < vec_size(self->phi); ++i) {
1021 if (vec_ir_instr_find(self->phi[i].value->writes, self, &idx))
1022 vec_remove(self->phi[i].value->writes, idx, 1);
1023 if (vec_ir_instr_find(self->phi[i].value->reads, self, &idx))
1024 vec_remove(self->phi[i].value->reads, idx, 1);
1026 vec_free(self->phi);
1027 for (i = 0; i < vec_size(self->params); ++i) {
1029 if (vec_ir_instr_find(self->params[i]->writes, self, &idx))
1030 vec_remove(self->params[i]->writes, idx, 1);
1031 if (vec_ir_instr_find(self->params[i]->reads, self, &idx))
1032 vec_remove(self->params[i]->reads, idx, 1);
1034 vec_free(self->params);
1035 (void)!ir_instr_op(self, 0, NULL, false);
1036 (void)!ir_instr_op(self, 1, NULL, false);
1037 (void)!ir_instr_op(self, 2, NULL, false);
1041 static bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
1043 if (v && v->vtype == TYPE_NOEXPR) {
1044 irerror(self->context, "tried to use a NOEXPR value");
1048 if (self->_ops[op]) {
1050 if (writing && vec_ir_instr_find(self->_ops[op]->writes, self, &idx))
1051 vec_remove(self->_ops[op]->writes, idx, 1);
1052 else if (vec_ir_instr_find(self->_ops[op]->reads, self, &idx))
1053 vec_remove(self->_ops[op]->reads, idx, 1);
1057 vec_push(v->writes, self);
1059 vec_push(v->reads, self);
1065 /***********************************************************************
1069 static void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
1071 self->code.globaladdr = gaddr;
1072 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
1073 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
1074 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
1077 static int32_t ir_value_code_addr(const ir_value *self)
1079 if (self->store == store_return)
1080 return OFS_RETURN + self->code.addroffset;
1081 return self->code.globaladdr + self->code.addroffset;
1084 ir_value* ir_value_var(const char *name, int storetype, int vtype)
1087 self = (ir_value*)mem_a(sizeof(*self));
1088 self->vtype = vtype;
1089 self->fieldtype = TYPE_VOID;
1090 self->outtype = TYPE_VOID;
1091 self->store = storetype;
1095 self->writes = NULL;
1097 self->cvq = CV_NONE;
1098 self->hasvalue = false;
1099 self->context.file = "<@no context>";
1100 self->context.line = 0;
1102 if (name && !ir_value_set_name(self, name)) {
1103 irerror(self->context, "out of memory");
1108 memset(&self->constval, 0, sizeof(self->constval));
1109 memset(&self->code, 0, sizeof(self->code));
1111 self->members[0] = NULL;
1112 self->members[1] = NULL;
1113 self->members[2] = NULL;
1114 self->memberof = NULL;
1116 self->unique_life = false;
1117 self->locked = false;
1118 self->callparam = false;
1124 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
1132 if (self->members[member])
1133 return self->members[member];
1136 len = strlen(self->name);
1137 name = (char*)mem_a(len + 3);
1138 memcpy(name, self->name, len);
1140 name[len+1] = 'x' + member;
1146 if (self->vtype == TYPE_VECTOR)
1148 m = ir_value_var(name, self->store, TYPE_FLOAT);
1153 m->context = self->context;
1155 self->members[member] = m;
1156 m->code.addroffset = member;
1158 else if (self->vtype == TYPE_FIELD)
1160 if (self->fieldtype != TYPE_VECTOR)
1162 m = ir_value_var(name, self->store, TYPE_FIELD);
1167 m->fieldtype = TYPE_FLOAT;
1168 m->context = self->context;
1170 self->members[member] = m;
1171 m->code.addroffset = member;
1175 irerror(self->context, "invalid member access on %s", self->name);
1183 static GMQCC_INLINE size_t ir_value_sizeof(const ir_value *self)
1185 if (self->vtype == TYPE_FIELD && self->fieldtype == TYPE_VECTOR)
1186 return type_sizeof_[TYPE_VECTOR];
1187 return type_sizeof_[self->vtype];
1190 static ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
1192 ir_value *v = ir_value_var(name, storetype, vtype);
1195 ir_function_collect_value(owner, v);
1199 void ir_value_delete(ir_value* self)
1203 mem_d((void*)self->name);
1206 if (self->vtype == TYPE_STRING)
1207 mem_d((void*)self->constval.vstring);
1209 for (i = 0; i < 3; ++i) {
1210 if (self->members[i])
1211 ir_value_delete(self->members[i]);
1213 vec_free(self->reads);
1214 vec_free(self->writes);
1215 vec_free(self->life);
1219 bool ir_value_set_name(ir_value *self, const char *name)
1222 mem_d((void*)self->name);
1223 self->name = util_strdup(name);
1224 return !!self->name;
1227 bool ir_value_set_float(ir_value *self, float f)
1229 if (self->vtype != TYPE_FLOAT)
1231 self->constval.vfloat = f;
1232 self->hasvalue = true;
1236 bool ir_value_set_func(ir_value *self, int f)
1238 if (self->vtype != TYPE_FUNCTION)
1240 self->constval.vint = f;
1241 self->hasvalue = true;
1245 bool ir_value_set_vector(ir_value *self, vec3_t v)
1247 if (self->vtype != TYPE_VECTOR)
1249 self->constval.vvec = v;
1250 self->hasvalue = true;
1254 bool ir_value_set_field(ir_value *self, ir_value *fld)
1256 if (self->vtype != TYPE_FIELD)
1258 self->constval.vpointer = fld;
1259 self->hasvalue = true;
1263 bool ir_value_set_string(ir_value *self, const char *str)
1265 if (self->vtype != TYPE_STRING)
1267 self->constval.vstring = util_strdupe(str);
1268 self->hasvalue = true;
1273 bool ir_value_set_int(ir_value *self, int i)
1275 if (self->vtype != TYPE_INTEGER)
1277 self->constval.vint = i;
1278 self->hasvalue = true;
1283 bool ir_value_lives(ir_value *self, size_t at)
1286 for (i = 0; i < vec_size(self->life); ++i)
1288 ir_life_entry_t *life = &self->life[i];
1289 if (life->start <= at && at <= life->end)
1291 if (life->start > at) /* since it's ordered */
1297 static bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
1300 vec_push(self->life, e);
1301 for (k = vec_size(self->life)-1; k > idx; --k)
1302 self->life[k] = self->life[k-1];
1303 self->life[idx] = e;
1307 static bool ir_value_life_merge(ir_value *self, size_t s)
1310 const size_t vs = vec_size(self->life);
1311 ir_life_entry_t *life = NULL;
1312 ir_life_entry_t *before = NULL;
1313 ir_life_entry_t new_entry;
1315 /* Find the first range >= s */
1316 for (i = 0; i < vs; ++i)
1319 life = &self->life[i];
1320 if (life->start > s)
1323 /* nothing found? append */
1326 if (life && life->end+1 == s)
1328 /* previous life range can be merged in */
1332 if (life && life->end >= s)
1334 e.start = e.end = s;
1335 vec_push(self->life, e);
1341 if (before->end + 1 == s &&
1342 life->start - 1 == s)
1345 before->end = life->end;
1346 vec_remove(self->life, i, 1);
1349 if (before->end + 1 == s)
1355 /* already contained */
1356 if (before->end >= s)
1360 if (life->start - 1 == s)
1365 /* insert a new entry */
1366 new_entry.start = new_entry.end = s;
1367 return ir_value_life_insert(self, i, new_entry);
1370 static bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1374 if (!vec_size(other->life))
1377 if (!vec_size(self->life)) {
1378 size_t count = vec_size(other->life);
1379 ir_life_entry_t *life = vec_add(self->life, count);
1380 memcpy(life, other->life, count * sizeof(*life));
1385 for (i = 0; i < vec_size(other->life); ++i)
1387 const ir_life_entry_t *life = &other->life[i];
1390 ir_life_entry_t *entry = &self->life[myi];
1392 if (life->end+1 < entry->start)
1394 /* adding an interval before entry */
1395 if (!ir_value_life_insert(self, myi, *life))
1401 if (life->start < entry->start &&
1402 life->end+1 >= entry->start)
1404 /* starts earlier and overlaps */
1405 entry->start = life->start;
1408 if (life->end > entry->end &&
1409 life->start <= entry->end+1)
1411 /* ends later and overlaps */
1412 entry->end = life->end;
1415 /* see if our change combines it with the next ranges */
1416 while (myi+1 < vec_size(self->life) &&
1417 entry->end+1 >= self->life[1+myi].start)
1419 /* overlaps with (myi+1) */
1420 if (entry->end < self->life[1+myi].end)
1421 entry->end = self->life[1+myi].end;
1422 vec_remove(self->life, myi+1, 1);
1423 entry = &self->life[myi];
1426 /* see if we're after the entry */
1427 if (life->start > entry->end)
1430 /* append if we're at the end */
1431 if (myi >= vec_size(self->life)) {
1432 vec_push(self->life, *life);
1435 /* otherweise check the next range */
1444 static bool ir_values_overlap(const ir_value *a, const ir_value *b)
1446 /* For any life entry in A see if it overlaps with
1447 * any life entry in B.
1448 * Note that the life entries are orderes, so we can make a
1449 * more efficient algorithm there than naively translating the
1453 ir_life_entry_t *la, *lb, *enda, *endb;
1455 /* first of all, if either has no life range, they cannot clash */
1456 if (!vec_size(a->life) || !vec_size(b->life))
1461 enda = la + vec_size(a->life);
1462 endb = lb + vec_size(b->life);
1465 /* check if the entries overlap, for that,
1466 * both must start before the other one ends.
1468 if (la->start < lb->end &&
1469 lb->start < la->end)
1474 /* entries are ordered
1475 * one entry is earlier than the other
1476 * that earlier entry will be moved forward
1478 if (la->start < lb->start)
1480 /* order: A B, move A forward
1481 * check if we hit the end with A
1486 else /* if (lb->start < la->start) actually <= */
1488 /* order: B A, move B forward
1489 * check if we hit the end with B
1498 /***********************************************************************
1502 static bool ir_check_unreachable(ir_block *self)
1504 /* The IR should never have to deal with unreachable code */
1505 if (!self->final/* || OPTS_FLAG(ALLOW_UNREACHABLE_CODE)*/)
1507 irerror(self->context, "unreachable statement (%s)", self->label);
1511 bool ir_block_create_store_op(ir_block *self, lex_ctx_t ctx, int op, ir_value *target, ir_value *what)
1514 if (!ir_check_unreachable(self))
1517 if (target->store == store_value &&
1518 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1520 irerror(self->context, "cannot store to an SSA value");
1521 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1522 irerror(self->context, "instruction: %s", util_instr_str[op]);
1526 in = ir_instr_new(ctx, self, op);
1530 if (!ir_instr_op(in, 0, target, (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC)) ||
1531 !ir_instr_op(in, 1, what, false))
1533 ir_instr_delete(in);
1536 vec_push(self->instr, in);
1540 static bool ir_block_create_store(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1544 if (target->vtype == TYPE_VARIANT)
1545 vtype = what->vtype;
1547 vtype = target->vtype;
1550 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1551 op = INSTR_CONV_ITOF;
1552 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1553 op = INSTR_CONV_FTOI;
1555 op = type_store_instr[vtype];
1557 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1558 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1562 return ir_block_create_store_op(self, ctx, op, target, what);
1565 bool ir_block_create_storep(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1570 if (target->vtype != TYPE_POINTER)
1573 /* storing using pointer - target is a pointer, type must be
1574 * inferred from source
1576 vtype = what->vtype;
1578 op = type_storep_instr[vtype];
1579 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1580 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1581 op = INSTR_STOREP_V;
1584 return ir_block_create_store_op(self, ctx, op, target, what);
1587 bool ir_block_create_return(ir_block *self, lex_ctx_t ctx, ir_value *v)
1590 if (!ir_check_unreachable(self))
1595 self->is_return = true;
1596 in = ir_instr_new(ctx, self, INSTR_RETURN);
1600 if (v && !ir_instr_op(in, 0, v, false)) {
1601 ir_instr_delete(in);
1605 vec_push(self->instr, in);
1609 bool ir_block_create_if(ir_block *self, lex_ctx_t ctx, ir_value *v,
1610 ir_block *ontrue, ir_block *onfalse)
1613 if (!ir_check_unreachable(self))
1616 /*in = ir_instr_new(ctx, self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1617 in = ir_instr_new(ctx, self, VINSTR_COND);
1621 if (!ir_instr_op(in, 0, v, false)) {
1622 ir_instr_delete(in);
1626 in->bops[0] = ontrue;
1627 in->bops[1] = onfalse;
1629 vec_push(self->instr, in);
1631 vec_push(self->exits, ontrue);
1632 vec_push(self->exits, onfalse);
1633 vec_push(ontrue->entries, self);
1634 vec_push(onfalse->entries, self);
1638 bool ir_block_create_jump(ir_block *self, lex_ctx_t ctx, ir_block *to)
1641 if (!ir_check_unreachable(self))
1644 in = ir_instr_new(ctx, self, VINSTR_JUMP);
1649 vec_push(self->instr, in);
1651 vec_push(self->exits, to);
1652 vec_push(to->entries, self);
1656 bool ir_block_create_goto(ir_block *self, lex_ctx_t ctx, ir_block *to)
1658 self->owner->flags |= IR_FLAG_HAS_GOTO;
1659 return ir_block_create_jump(self, ctx, to);
1662 ir_instr* ir_block_create_phi(ir_block *self, lex_ctx_t ctx, const char *label, int ot)
1666 if (!ir_check_unreachable(self))
1668 in = ir_instr_new(ctx, self, VINSTR_PHI);
1671 out = ir_value_out(self->owner, label, store_value, ot);
1673 ir_instr_delete(in);
1676 if (!ir_instr_op(in, 0, out, true)) {
1677 ir_instr_delete(in);
1678 ir_value_delete(out);
1681 vec_push(self->instr, in);
1685 ir_value* ir_phi_value(ir_instr *self)
1687 return self->_ops[0];
1690 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1694 if (!vec_ir_block_find(self->owner->entries, b, NULL)) {
1695 /* Must not be possible to cause this, otherwise the AST
1696 * is doing something wrong.
1698 irerror(self->context, "Invalid entry block for PHI");
1704 vec_push(v->reads, self);
1705 vec_push(self->phi, pe);
1708 /* call related code */
1709 ir_instr* ir_block_create_call(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *func, bool noreturn)
1713 if (!ir_check_unreachable(self))
1715 in = ir_instr_new(ctx, self, (noreturn ? VINSTR_NRCALL : INSTR_CALL0));
1720 self->is_return = true;
1722 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1724 ir_instr_delete(in);
1727 if (!ir_instr_op(in, 0, out, true) ||
1728 !ir_instr_op(in, 1, func, false))
1730 ir_instr_delete(in);
1731 ir_value_delete(out);
1734 vec_push(self->instr, in);
1737 if (!ir_block_create_return(self, ctx, NULL)) {
1738 compile_error(ctx, "internal error: failed to generate dummy-return instruction");
1739 ir_instr_delete(in);
1747 ir_value* ir_call_value(ir_instr *self)
1749 return self->_ops[0];
1752 void ir_call_param(ir_instr* self, ir_value *v)
1754 vec_push(self->params, v);
1755 vec_push(v->reads, self);
1758 /* binary op related code */
1760 ir_value* ir_block_create_binop(ir_block *self, lex_ctx_t ctx,
1761 const char *label, int opcode,
1762 ir_value *left, ir_value *right)
1785 case INSTR_SUB_S: /* -- offset of string as float */
1790 case INSTR_BITOR_IF:
1791 case INSTR_BITOR_FI:
1792 case INSTR_BITAND_FI:
1793 case INSTR_BITAND_IF:
1808 case INSTR_BITAND_I:
1811 case INSTR_RSHIFT_I:
1812 case INSTR_LSHIFT_I:
1820 case VINSTR_BITAND_V:
1821 case VINSTR_BITOR_V:
1822 case VINSTR_BITXOR_V:
1823 case VINSTR_BITAND_VF:
1824 case VINSTR_BITOR_VF:
1825 case VINSTR_BITXOR_VF:
1840 * after the following default case, the value of opcode can never
1841 * be 1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65
1845 /* boolean operations result in floats */
1848 * opcode >= 10 takes true branch opcode is at least 10
1849 * opcode <= 23 takes false branch opcode is at least 24
1851 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1855 * At condition "opcode <= 23", the value of "opcode" must be
1857 * At condition "opcode <= 23", the value of "opcode" cannot be
1858 * equal to any of {1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65}.
1859 * The condition "opcode <= 23" cannot be true.
1861 * Thus ot=2 (TYPE_FLOAT) can never be true
1864 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1866 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1871 if (ot == TYPE_VOID) {
1872 /* The AST or parser were supposed to check this! */
1876 return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1879 ir_value* ir_block_create_unary(ir_block *self, lex_ctx_t ctx,
1880 const char *label, int opcode,
1883 int ot = TYPE_FLOAT;
1889 case INSTR_NOT_FNC: /*
1890 case INSTR_NOT_I: */
1895 * Negation for virtual instructions is emulated with 0-value. Thankfully
1896 * the operand for 0 already exists so we just source it from here.
1899 return ir_block_create_general_instr(self, ctx, label, INSTR_SUB_F, NULL, operand, ot);
1901 return ir_block_create_general_instr(self, ctx, label, INSTR_SUB_V, NULL, operand, TYPE_VECTOR);
1904 ot = operand->vtype;
1907 if (ot == TYPE_VOID) {
1908 /* The AST or parser were supposed to check this! */
1912 /* let's use the general instruction creator and pass NULL for OPB */
1913 return ir_block_create_general_instr(self, ctx, label, opcode, operand, NULL, ot);
1916 static ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx_t ctx, const char *label,
1917 int op, ir_value *a, ir_value *b, int outype)
1922 out = ir_value_out(self->owner, label, store_value, outype);
1926 instr = ir_instr_new(ctx, self, op);
1928 ir_value_delete(out);
1932 if (!ir_instr_op(instr, 0, out, true) ||
1933 !ir_instr_op(instr, 1, a, false) ||
1934 !ir_instr_op(instr, 2, b, false) )
1939 vec_push(self->instr, instr);
1943 ir_instr_delete(instr);
1944 ir_value_delete(out);
1948 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *ent, ir_value *field)
1952 /* Support for various pointer types todo if so desired */
1953 if (ent->vtype != TYPE_ENTITY)
1956 if (field->vtype != TYPE_FIELD)
1959 v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1960 v->fieldtype = field->fieldtype;
1964 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)
1967 if (ent->vtype != TYPE_ENTITY)
1970 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1971 if (field->vtype != TYPE_FIELD)
1976 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1977 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1978 case TYPE_STRING: op = INSTR_LOAD_S; break;
1979 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1980 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1981 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1983 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1984 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1987 irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1991 return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
1994 /* PHI resolving breaks the SSA, and must thus be the last
1995 * step before life-range calculation.
1998 static bool ir_block_naive_phi(ir_block *self);
1999 bool ir_function_naive_phi(ir_function *self)
2003 for (i = 0; i < vec_size(self->blocks); ++i)
2005 if (!ir_block_naive_phi(self->blocks[i]))
2011 static bool ir_block_naive_phi(ir_block *self)
2013 size_t i, p; /*, w;*/
2014 /* FIXME: optionally, create_phi can add the phis
2015 * to a list so we don't need to loop through blocks
2016 * - anyway: "don't optimize YET"
2018 for (i = 0; i < vec_size(self->instr); ++i)
2020 ir_instr *instr = self->instr[i];
2021 if (instr->opcode != VINSTR_PHI)
2024 vec_remove(self->instr, i, 1);
2025 --i; /* NOTE: i+1 below */
2027 for (p = 0; p < vec_size(instr->phi); ++p)
2029 ir_value *v = instr->phi[p].value;
2030 ir_block *b = instr->phi[p].from;
2032 if (v->store == store_value &&
2033 vec_size(v->reads) == 1 &&
2034 vec_size(v->writes) == 1)
2036 /* replace the value */
2037 if (!ir_instr_op(v->writes[0], 0, instr->_ops[0], true))
2042 /* force a move instruction */
2043 ir_instr *prevjump = vec_last(b->instr);
2046 instr->_ops[0]->store = store_global;
2047 if (!ir_block_create_store(b, instr->context, instr->_ops[0], v))
2049 instr->_ops[0]->store = store_value;
2050 vec_push(b->instr, prevjump);
2054 ir_instr_delete(instr);
2059 /***********************************************************************
2060 *IR Temp allocation code
2061 * Propagating value life ranges by walking through the function backwards
2062 * until no more changes are made.
2063 * In theory this should happen once more than once for every nested loop
2065 * Though this implementation might run an additional time for if nests.
2068 /* Enumerate instructions used by value's life-ranges
2070 static void ir_block_enumerate(ir_block *self, size_t *_eid)
2074 for (i = 0; i < vec_size(self->instr); ++i)
2076 self->instr[i]->eid = eid++;
2081 /* Enumerate blocks and instructions.
2082 * The block-enumeration is unordered!
2083 * We do not really use the block enumreation, however
2084 * the instruction enumeration is important for life-ranges.
2086 void ir_function_enumerate(ir_function *self)
2089 size_t instruction_id = 0;
2090 for (i = 0; i < vec_size(self->blocks); ++i)
2092 /* each block now gets an additional "entry" instruction id
2093 * we can use to avoid point-life issues
2095 self->blocks[i]->entry_id = instruction_id;
2098 self->blocks[i]->eid = i;
2099 ir_block_enumerate(self->blocks[i], &instruction_id);
2103 /* Local-value allocator
2104 * After finishing creating the liferange of all values used in a function
2105 * we can allocate their global-positions.
2106 * This is the counterpart to register-allocation in register machines.
2113 } function_allocator;
2115 static bool function_allocator_alloc(function_allocator *alloc, ir_value *var)
2118 size_t vsize = ir_value_sizeof(var);
2120 var->code.local = vec_size(alloc->locals);
2122 slot = ir_value_var("reg", store_global, var->vtype);
2126 if (!ir_value_life_merge_into(slot, var))
2129 vec_push(alloc->locals, slot);
2130 vec_push(alloc->sizes, vsize);
2131 vec_push(alloc->unique, var->unique_life);
2136 ir_value_delete(slot);
2140 static bool ir_function_allocator_assign(ir_function *self, function_allocator *alloc, ir_value *v)
2146 return function_allocator_alloc(alloc, v);
2148 for (a = 0; a < vec_size(alloc->locals); ++a)
2150 /* if it's reserved for a unique liferange: skip */
2151 if (alloc->unique[a])
2154 slot = alloc->locals[a];
2156 /* never resize parameters
2157 * will be required later when overlapping temps + locals
2159 if (a < vec_size(self->params) &&
2160 alloc->sizes[a] < ir_value_sizeof(v))
2165 if (ir_values_overlap(v, slot))
2168 if (!ir_value_life_merge_into(slot, v))
2171 /* adjust size for this slot */
2172 if (alloc->sizes[a] < ir_value_sizeof(v))
2173 alloc->sizes[a] = ir_value_sizeof(v);
2178 if (a >= vec_size(alloc->locals)) {
2179 if (!function_allocator_alloc(alloc, v))
2185 bool ir_function_allocate_locals(ir_function *self)
2190 bool opt_gt = OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS);
2194 function_allocator lockalloc, globalloc;
2196 if (!vec_size(self->locals) && !vec_size(self->values))
2199 globalloc.locals = NULL;
2200 globalloc.sizes = NULL;
2201 globalloc.positions = NULL;
2202 globalloc.unique = NULL;
2203 lockalloc.locals = NULL;
2204 lockalloc.sizes = NULL;
2205 lockalloc.positions = NULL;
2206 lockalloc.unique = NULL;
2208 for (i = 0; i < vec_size(self->locals); ++i)
2210 v = self->locals[i];
2211 if ((self->flags & IR_FLAG_MASK_NO_LOCAL_TEMPS) || !OPTS_OPTIMIZATION(OPTIM_LOCAL_TEMPS)) {
2213 v->unique_life = true;
2215 else if (i >= vec_size(self->params))
2218 v->locked = true; /* lock parameters locals */
2219 if (!function_allocator_alloc((v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2222 for (; i < vec_size(self->locals); ++i)
2224 v = self->locals[i];
2225 if (!vec_size(v->life))
2227 if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2231 /* Allocate a slot for any value that still exists */
2232 for (i = 0; i < vec_size(self->values); ++i)
2234 v = self->values[i];
2236 if (!vec_size(v->life))
2239 /* CALL optimization:
2240 * If the value is a parameter-temp: 1 write, 1 read from a CALL
2241 * and it's not "locked", write it to the OFS_PARM directly.
2243 if (OPTS_OPTIMIZATION(OPTIM_CALL_STORES) && !v->locked && !v->unique_life) {
2244 if (vec_size(v->reads) == 1 && vec_size(v->writes) == 1 &&
2245 (v->reads[0]->opcode == VINSTR_NRCALL ||
2246 (v->reads[0]->opcode >= INSTR_CALL0 && v->reads[0]->opcode <= INSTR_CALL8)
2251 ir_instr *call = v->reads[0];
2252 if (!vec_ir_value_find(call->params, v, ¶m)) {
2253 irerror(call->context, "internal error: unlocked parameter %s not found", v->name);
2256 ++opts_optimizationcount[OPTIM_CALL_STORES];
2257 v->callparam = true;
2259 ir_value_code_setaddr(v, OFS_PARM0 + 3*param);
2261 size_t nprotos = vec_size(self->owner->extparam_protos);
2264 if (nprotos > param)
2265 ep = self->owner->extparam_protos[param];
2268 ep = ir_gen_extparam_proto(self->owner);
2269 while (++nprotos <= param)
2270 ep = ir_gen_extparam_proto(self->owner);
2272 ir_instr_op(v->writes[0], 0, ep, true);
2273 call->params[param+8] = ep;
2277 if (vec_size(v->writes) == 1 && v->writes[0]->opcode == INSTR_CALL0)
2279 v->store = store_return;
2280 if (v->members[0]) v->members[0]->store = store_return;
2281 if (v->members[1]) v->members[1]->store = store_return;
2282 if (v->members[2]) v->members[2]->store = store_return;
2283 ++opts_optimizationcount[OPTIM_CALL_STORES];
2288 if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2292 if (!lockalloc.sizes && !globalloc.sizes) {
2295 vec_push(lockalloc.positions, 0);
2296 vec_push(globalloc.positions, 0);
2298 /* Adjust slot positions based on sizes */
2299 if (lockalloc.sizes) {
2300 pos = (vec_size(lockalloc.sizes) ? lockalloc.positions[0] : 0);
2301 for (i = 1; i < vec_size(lockalloc.sizes); ++i)
2303 pos = lockalloc.positions[i-1] + lockalloc.sizes[i-1];
2304 vec_push(lockalloc.positions, pos);
2306 self->allocated_locals = pos + vec_last(lockalloc.sizes);
2308 if (globalloc.sizes) {
2309 pos = (vec_size(globalloc.sizes) ? globalloc.positions[0] : 0);
2310 for (i = 1; i < vec_size(globalloc.sizes); ++i)
2312 pos = globalloc.positions[i-1] + globalloc.sizes[i-1];
2313 vec_push(globalloc.positions, pos);
2315 self->globaltemps = pos + vec_last(globalloc.sizes);
2318 /* Locals need to know their new position */
2319 for (i = 0; i < vec_size(self->locals); ++i) {
2320 v = self->locals[i];
2321 if (v->locked || !opt_gt)
2322 v->code.local = lockalloc.positions[v->code.local];
2324 v->code.local = globalloc.positions[v->code.local];
2326 /* Take over the actual slot positions on values */
2327 for (i = 0; i < vec_size(self->values); ++i) {
2328 v = self->values[i];
2329 if (v->locked || !opt_gt)
2330 v->code.local = lockalloc.positions[v->code.local];
2332 v->code.local = globalloc.positions[v->code.local];
2340 for (i = 0; i < vec_size(lockalloc.locals); ++i)
2341 ir_value_delete(lockalloc.locals[i]);
2342 for (i = 0; i < vec_size(globalloc.locals); ++i)
2343 ir_value_delete(globalloc.locals[i]);
2344 vec_free(globalloc.unique);
2345 vec_free(globalloc.locals);
2346 vec_free(globalloc.sizes);
2347 vec_free(globalloc.positions);
2348 vec_free(lockalloc.unique);
2349 vec_free(lockalloc.locals);
2350 vec_free(lockalloc.sizes);
2351 vec_free(lockalloc.positions);
2355 /* Get information about which operand
2356 * is read from, or written to.
2358 static void ir_op_read_write(int op, size_t *read, size_t *write)
2378 case INSTR_STOREP_F:
2379 case INSTR_STOREP_V:
2380 case INSTR_STOREP_S:
2381 case INSTR_STOREP_ENT:
2382 case INSTR_STOREP_FLD:
2383 case INSTR_STOREP_FNC:
2394 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2397 const size_t vs = vec_size(self->living);
2398 bool changed = false;
2399 for (i = 0; i != vs; ++i)
2401 if (ir_value_life_merge(self->living[i], eid))
2407 static bool ir_block_living_lock(ir_block *self)
2410 bool changed = false;
2411 for (i = 0; i != vec_size(self->living); ++i)
2413 if (!self->living[i]->locked) {
2414 self->living[i]->locked = true;
2421 static bool ir_block_life_propagate(ir_block *self, bool *changed)
2425 size_t i, o, p, mem, cnt;
2426 /* bitmasks which operands are read from or written to */
2433 vec_free(self->living);
2435 p = vec_size(self->exits);
2436 for (i = 0; i < p; ++i) {
2437 ir_block *prev = self->exits[i];
2438 cnt = vec_size(prev->living);
2439 for (o = 0; o < cnt; ++o) {
2440 if (!vec_ir_value_find(self->living, prev->living[o], NULL))
2441 vec_push(self->living, prev->living[o]);
2445 i = vec_size(self->instr);
2448 instr = self->instr[i];
2450 /* See which operands are read and write operands */
2451 ir_op_read_write(instr->opcode, &read, &write);
2453 /* Go through the 3 main operands
2454 * writes first, then reads
2456 for (o = 0; o < 3; ++o)
2458 if (!instr->_ops[o]) /* no such operand */
2461 value = instr->_ops[o];
2463 /* We only care about locals */
2464 /* we also calculate parameter liferanges so that locals
2465 * can take up parameter slots */
2466 if (value->store != store_value &&
2467 value->store != store_local &&
2468 value->store != store_param)
2471 /* write operands */
2472 /* When we write to a local, we consider it "dead" for the
2473 * remaining upper part of the function, since in SSA a value
2474 * can only be written once (== created)
2479 bool in_living = vec_ir_value_find(self->living, value, &idx);
2482 /* If the value isn't alive it hasn't been read before... */
2483 /* TODO: See if the warning can be emitted during parsing or AST processing
2484 * otherwise have warning printed here.
2485 * IF printing a warning here: include filecontext_t,
2486 * and make sure it's only printed once
2487 * since this function is run multiple times.
2489 /* con_err( "Value only written %s\n", value->name); */
2490 if (ir_value_life_merge(value, instr->eid))
2493 /* since 'living' won't contain it
2494 * anymore, merge the value, since
2497 if (ir_value_life_merge(value, instr->eid))
2500 vec_remove(self->living, idx, 1);
2502 /* Removing a vector removes all members */
2503 for (mem = 0; mem < 3; ++mem) {
2504 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], &idx)) {
2505 if (ir_value_life_merge(value->members[mem], instr->eid))
2507 vec_remove(self->living, idx, 1);
2510 /* Removing the last member removes the vector */
2511 if (value->memberof) {
2512 value = value->memberof;
2513 for (mem = 0; mem < 3; ++mem) {
2514 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], NULL))
2517 if (mem == 3 && vec_ir_value_find(self->living, value, &idx)) {
2518 if (ir_value_life_merge(value, instr->eid))
2520 vec_remove(self->living, idx, 1);
2526 /* These operations need a special case as they can break when using
2527 * same source and destination operand otherwise, as the engine may
2528 * read the source multiple times. */
2529 if (instr->opcode == INSTR_MUL_VF ||
2530 instr->opcode == VINSTR_BITAND_VF ||
2531 instr->opcode == VINSTR_BITOR_VF ||
2532 instr->opcode == VINSTR_BITXOR ||
2533 instr->opcode == VINSTR_BITXOR_VF ||
2534 instr->opcode == VINSTR_BITXOR_V ||
2535 instr->opcode == VINSTR_CROSS)
2537 value = instr->_ops[2];
2538 /* the float source will get an additional lifetime */
2539 if (ir_value_life_merge(value, instr->eid+1))
2541 if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2545 if (instr->opcode == INSTR_MUL_FV ||
2546 instr->opcode == INSTR_LOAD_V ||
2547 instr->opcode == VINSTR_BITXOR ||
2548 instr->opcode == VINSTR_BITXOR_VF ||
2549 instr->opcode == VINSTR_BITXOR_V ||
2550 instr->opcode == VINSTR_CROSS)
2552 value = instr->_ops[1];
2553 /* the float source will get an additional lifetime */
2554 if (ir_value_life_merge(value, instr->eid+1))
2556 if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2560 for (o = 0; o < 3; ++o)
2562 if (!instr->_ops[o]) /* no such operand */
2565 value = instr->_ops[o];
2567 /* We only care about locals */
2568 /* we also calculate parameter liferanges so that locals
2569 * can take up parameter slots */
2570 if (value->store != store_value &&
2571 value->store != store_local &&
2572 value->store != store_param)
2578 if (!vec_ir_value_find(self->living, value, NULL))
2579 vec_push(self->living, value);
2580 /* reading adds the full vector */
2581 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2582 vec_push(self->living, value->memberof);
2583 for (mem = 0; mem < 3; ++mem) {
2584 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2585 vec_push(self->living, value->members[mem]);
2589 /* PHI operands are always read operands */
2590 for (p = 0; p < vec_size(instr->phi); ++p)
2592 value = instr->phi[p].value;
2593 if (!vec_ir_value_find(self->living, value, NULL))
2594 vec_push(self->living, value);
2595 /* reading adds the full vector */
2596 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2597 vec_push(self->living, value->memberof);
2598 for (mem = 0; mem < 3; ++mem) {
2599 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2600 vec_push(self->living, value->members[mem]);
2604 /* on a call, all these values must be "locked" */
2605 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2606 if (ir_block_living_lock(self))
2609 /* call params are read operands too */
2610 for (p = 0; p < vec_size(instr->params); ++p)
2612 value = instr->params[p];
2613 if (!vec_ir_value_find(self->living, value, NULL))
2614 vec_push(self->living, value);
2615 /* reading adds the full vector */
2616 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2617 vec_push(self->living, value->memberof);
2618 for (mem = 0; mem < 3; ++mem) {
2619 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2620 vec_push(self->living, value->members[mem]);
2625 if (ir_block_living_add_instr(self, instr->eid))
2628 /* the "entry" instruction ID */
2629 if (ir_block_living_add_instr(self, self->entry_id))
2635 bool ir_function_calculate_liferanges(ir_function *self)
2640 /* parameters live at 0 */
2641 for (i = 0; i < vec_size(self->params); ++i)
2642 if (!ir_value_life_merge(self->locals[i], 0))
2643 compile_error(self->context, "internal error: failed value-life merging");
2648 i = vec_size(self->blocks);
2650 ir_block_life_propagate(self->blocks[i], &changed);
2654 if (vec_size(self->blocks)) {
2655 ir_block *block = self->blocks[0];
2656 for (i = 0; i < vec_size(block->living); ++i) {
2657 ir_value *v = block->living[i];
2658 if (v->store != store_local)
2660 if (v->vtype == TYPE_VECTOR)
2662 self->flags |= IR_FLAG_HAS_UNINITIALIZED;
2663 /* find the instruction reading from it */
2664 for (s = 0; s < vec_size(v->reads); ++s) {
2665 if (v->reads[s]->eid == v->life[0].end)
2668 if (s < vec_size(v->reads)) {
2669 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2670 "variable `%s` may be used uninitialized in this function\n"
2673 v->reads[s]->context.file, v->reads[s]->context.line)
2681 ir_value *vec = v->memberof;
2682 for (s = 0; s < vec_size(vec->reads); ++s) {
2683 if (vec->reads[s]->eid == v->life[0].end)
2686 if (s < vec_size(vec->reads)) {
2687 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2688 "variable `%s` may be used uninitialized in this function\n"
2691 vec->reads[s]->context.file, vec->reads[s]->context.line)
2699 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2700 "variable `%s` may be used uninitialized in this function", v->name))
2709 /***********************************************************************
2712 * Since the IR has the convention of putting 'write' operands
2713 * at the beginning, we have to rotate the operands of instructions
2714 * properly in order to generate valid QCVM code.
2716 * Having destinations at a fixed position is more convenient. In QC
2717 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2718 * read from from OPA, and store to OPB rather than OPC. Which is
2719 * partially the reason why the implementation of these instructions
2720 * in darkplaces has been delayed for so long.
2722 * Breaking conventions is annoying...
2724 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2726 static bool gen_global_field(code_t *code, ir_value *global)
2728 if (global->hasvalue)
2730 ir_value *fld = global->constval.vpointer;
2732 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2736 /* copy the field's value */
2737 ir_value_code_setaddr(global, vec_size(code->globals));
2738 vec_push(code->globals, fld->code.fieldaddr);
2739 if (global->fieldtype == TYPE_VECTOR) {
2740 vec_push(code->globals, fld->code.fieldaddr+1);
2741 vec_push(code->globals, fld->code.fieldaddr+2);
2746 ir_value_code_setaddr(global, vec_size(code->globals));
2747 vec_push(code->globals, 0);
2748 if (global->fieldtype == TYPE_VECTOR) {
2749 vec_push(code->globals, 0);
2750 vec_push(code->globals, 0);
2753 if (global->code.globaladdr < 0)
2758 static bool gen_global_pointer(code_t *code, ir_value *global)
2760 if (global->hasvalue)
2762 ir_value *target = global->constval.vpointer;
2764 irerror(global->context, "Invalid pointer constant: %s", global->name);
2765 /* NULL pointers are pointing to the NULL constant, which also
2766 * sits at address 0, but still has an ir_value for itself.
2771 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2772 * void() foo; <- proto
2773 * void() *fooptr = &foo;
2774 * void() foo = { code }
2776 if (!target->code.globaladdr) {
2777 /* FIXME: Check for the constant nullptr ir_value!
2778 * because then code.globaladdr being 0 is valid.
2780 irerror(global->context, "FIXME: Relocation support");
2784 ir_value_code_setaddr(global, vec_size(code->globals));
2785 vec_push(code->globals, target->code.globaladdr);
2789 ir_value_code_setaddr(global, vec_size(code->globals));
2790 vec_push(code->globals, 0);
2792 if (global->code.globaladdr < 0)
2797 static bool gen_blocks_recursive(code_t *code, ir_function *func, ir_block *block)
2799 prog_section_statement_t stmt;
2808 block->generated = true;
2809 block->code_start = vec_size(code->statements);
2810 for (i = 0; i < vec_size(block->instr); ++i)
2812 instr = block->instr[i];
2814 if (instr->opcode == VINSTR_PHI) {
2815 irerror(block->context, "cannot generate virtual instruction (phi)");
2819 if (instr->opcode == VINSTR_JUMP) {
2820 target = instr->bops[0];
2821 /* for uncoditional jumps, if the target hasn't been generated
2822 * yet, we generate them right here.
2824 if (!target->generated)
2825 return gen_blocks_recursive(code, func, target);
2827 /* otherwise we generate a jump instruction */
2828 stmt.opcode = INSTR_GOTO;
2829 stmt.o1.s1 = (target->code_start) - vec_size(code->statements);
2832 if (stmt.o1.s1 != 1)
2833 code_push_statement(code, &stmt, instr->context);
2835 /* no further instructions can be in this block */
2839 if (instr->opcode == VINSTR_BITXOR) {
2840 stmt.opcode = INSTR_BITOR;
2841 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2842 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2843 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2844 code_push_statement(code, &stmt, instr->context);
2845 stmt.opcode = INSTR_BITAND;
2846 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2847 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2848 stmt.o3.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2849 code_push_statement(code, &stmt, instr->context);
2850 stmt.opcode = INSTR_SUB_F;
2851 stmt.o1.s1 = ir_value_code_addr(instr->_ops[0]);
2852 stmt.o2.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2853 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2854 code_push_statement(code, &stmt, instr->context);
2856 /* instruction generated */
2860 if (instr->opcode == VINSTR_BITAND_V) {
2861 stmt.opcode = INSTR_BITAND;
2862 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2863 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2864 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2865 code_push_statement(code, &stmt, instr->context);
2869 code_push_statement(code, &stmt, instr->context);
2873 code_push_statement(code, &stmt, instr->context);
2875 /* instruction generated */
2879 if (instr->opcode == VINSTR_BITOR_V) {
2880 stmt.opcode = INSTR_BITOR;
2881 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2882 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2883 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2884 code_push_statement(code, &stmt, instr->context);
2888 code_push_statement(code, &stmt, instr->context);
2892 code_push_statement(code, &stmt, instr->context);
2894 /* instruction generated */
2898 if (instr->opcode == VINSTR_BITXOR_V) {
2899 for (j = 0; j < 3; ++j) {
2900 stmt.opcode = INSTR_BITOR;
2901 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + j;
2902 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]) + j;
2903 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]) + j;
2904 code_push_statement(code, &stmt, instr->context);
2905 stmt.opcode = INSTR_BITAND;
2906 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + j;
2907 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]) + j;
2908 stmt.o3.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]) + j;
2909 code_push_statement(code, &stmt, instr->context);
2911 stmt.opcode = INSTR_SUB_V;
2912 stmt.o1.s1 = ir_value_code_addr(instr->_ops[0]);
2913 stmt.o2.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2914 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2915 code_push_statement(code, &stmt, instr->context);
2917 /* instruction generated */
2921 if (instr->opcode == VINSTR_BITAND_VF) {
2922 stmt.opcode = INSTR_BITAND;
2923 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2924 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2925 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2926 code_push_statement(code, &stmt, instr->context);
2929 code_push_statement(code, &stmt, instr->context);
2932 code_push_statement(code, &stmt, instr->context);
2934 /* instruction generated */
2938 if (instr->opcode == VINSTR_BITOR_VF) {
2939 stmt.opcode = INSTR_BITOR;
2940 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]);
2941 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2942 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2943 code_push_statement(code, &stmt, instr->context);
2946 code_push_statement(code, &stmt, instr->context);
2949 code_push_statement(code, &stmt, instr->context);
2951 /* instruction generated */
2955 if (instr->opcode == VINSTR_BITXOR_VF) {
2956 for (j = 0; j < 3; ++j) {
2957 stmt.opcode = INSTR_BITOR;
2958 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + j;
2959 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2960 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]) + j;
2961 code_push_statement(code, &stmt, instr->context);
2962 stmt.opcode = INSTR_BITAND;
2963 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + j;
2964 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]);
2965 stmt.o3.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]) + j;
2966 code_push_statement(code, &stmt, instr->context);
2968 stmt.opcode = INSTR_SUB_V;
2969 stmt.o1.s1 = ir_value_code_addr(instr->_ops[0]);
2970 stmt.o2.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2971 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2972 code_push_statement(code, &stmt, instr->context);
2974 /* instruction generated */
2978 if (instr->opcode == VINSTR_CROSS) {
2979 stmt.opcode = INSTR_MUL_F;
2980 for (j = 0; j < 3; ++j) {
2981 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + (j + 1) % 3;
2982 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]) + (j + 2) % 3;
2983 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]) + j;
2984 code_push_statement(code, &stmt, instr->context);
2985 stmt.o1.s1 = ir_value_code_addr(instr->_ops[1]) + (j + 2) % 3;
2986 stmt.o2.s1 = ir_value_code_addr(instr->_ops[2]) + (j + 1) % 3;
2987 stmt.o3.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]) + j;
2988 code_push_statement(code, &stmt, instr->context);
2990 stmt.opcode = INSTR_SUB_V;
2991 stmt.o1.s1 = ir_value_code_addr(instr->_ops[0]);
2992 stmt.o2.s1 = ir_value_code_addr(func->owner->vinstr_temp[0]);
2993 stmt.o3.s1 = ir_value_code_addr(instr->_ops[0]);
2994 code_push_statement(code, &stmt, instr->context);
2996 /* instruction generated */
3000 if (instr->opcode == VINSTR_COND) {
3001 ontrue = instr->bops[0];
3002 onfalse = instr->bops[1];
3003 /* TODO: have the AST signal which block should
3004 * come first: eg. optimize IFs without ELSE...
3007 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
3011 if (ontrue->generated) {
3012 stmt.opcode = INSTR_IF;
3013 stmt.o2.s1 = (ontrue->code_start) - vec_size(code->statements);
3014 if (stmt.o2.s1 != 1)
3015 code_push_statement(code, &stmt, instr->context);
3017 if (onfalse->generated) {
3018 stmt.opcode = INSTR_IFNOT;
3019 stmt.o2.s1 = (onfalse->code_start) - vec_size(code->statements);
3020 if (stmt.o2.s1 != 1)
3021 code_push_statement(code, &stmt, instr->context);
3023 if (!ontrue->generated) {
3024 if (onfalse->generated)
3025 return gen_blocks_recursive(code, func, ontrue);
3027 if (!onfalse->generated) {
3028 if (ontrue->generated)
3029 return gen_blocks_recursive(code, func, onfalse);
3031 /* neither ontrue nor onfalse exist */
3032 stmt.opcode = INSTR_IFNOT;
3033 if (!instr->likely) {
3034 /* Honor the likelyhood hint */
3035 ir_block *tmp = onfalse;
3036 stmt.opcode = INSTR_IF;
3040 stidx = vec_size(code->statements);
3041 code_push_statement(code, &stmt, instr->context);
3042 /* on false we jump, so add ontrue-path */
3043 if (!gen_blocks_recursive(code, func, ontrue))
3045 /* fixup the jump address */
3046 code->statements[stidx].o2.s1 = vec_size(code->statements) - stidx;
3047 /* generate onfalse path */
3048 if (onfalse->generated) {
3049 /* fixup the jump address */
3050 code->statements[stidx].o2.s1 = (onfalse->code_start) - (stidx);
3051 if (stidx+2 == vec_size(code->statements) && code->statements[stidx].o2.s1 == 1) {
3052 code->statements[stidx] = code->statements[stidx+1];
3053 if (code->statements[stidx].o1.s1 < 0)
3054 code->statements[stidx].o1.s1++;
3055 code_pop_statement(code);
3057 stmt.opcode = vec_last(code->statements).opcode;
3058 if (stmt.opcode == INSTR_GOTO ||
3059 stmt.opcode == INSTR_IF ||
3060 stmt.opcode == INSTR_IFNOT ||
3061 stmt.opcode == INSTR_RETURN ||
3062 stmt.opcode == INSTR_DONE)
3064 /* no use jumping from here */
3067 /* may have been generated in the previous recursive call */
3068 stmt.opcode = INSTR_GOTO;
3069 stmt.o1.s1 = (onfalse->code_start) - vec_size(code->statements);
3072 if (stmt.o1.s1 != 1)
3073 code_push_statement(code, &stmt, instr->context);
3076 else if (stidx+2 == vec_size(code->statements) && code->statements[stidx].o2.s1 == 1) {
3077 code->statements[stidx] = code->statements[stidx+1];
3078 if (code->statements[stidx].o1.s1 < 0)
3079 code->statements[stidx].o1.s1++;
3080 code_pop_statement(code);
3082 /* if not, generate now */
3083 return gen_blocks_recursive(code, func, onfalse);
3086 if ( (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8)
3087 || instr->opcode == VINSTR_NRCALL)
3092 first = vec_size(instr->params);
3095 for (p = 0; p < first; ++p)
3097 ir_value *param = instr->params[p];
3098 if (param->callparam)
3101 stmt.opcode = INSTR_STORE_F;
3104 if (param->vtype == TYPE_FIELD)
3105 stmt.opcode = field_store_instr[param->fieldtype];
3106 else if (param->vtype == TYPE_NIL)
3107 stmt.opcode = INSTR_STORE_V;
3109 stmt.opcode = type_store_instr[param->vtype];
3110 stmt.o1.u1 = ir_value_code_addr(param);
3111 stmt.o2.u1 = OFS_PARM0 + 3 * p;
3112 code_push_statement(code, &stmt, instr->context);
3114 /* Now handle extparams */
3115 first = vec_size(instr->params);
3116 for (; p < first; ++p)
3118 ir_builder *ir = func->owner;
3119 ir_value *param = instr->params[p];
3120 ir_value *targetparam;
3122 if (param->callparam)
3125 if (p-8 >= vec_size(ir->extparams))
3126 ir_gen_extparam(ir);
3128 targetparam = ir->extparams[p-8];
3130 stmt.opcode = INSTR_STORE_F;
3133 if (param->vtype == TYPE_FIELD)
3134 stmt.opcode = field_store_instr[param->fieldtype];
3135 else if (param->vtype == TYPE_NIL)
3136 stmt.opcode = INSTR_STORE_V;
3138 stmt.opcode = type_store_instr[param->vtype];
3139 stmt.o1.u1 = ir_value_code_addr(param);
3140 stmt.o2.u1 = ir_value_code_addr(targetparam);
3141 code_push_statement(code, &stmt, instr->context);
3144 stmt.opcode = INSTR_CALL0 + vec_size(instr->params);
3145 if (stmt.opcode > INSTR_CALL8)
3146 stmt.opcode = INSTR_CALL8;
3147 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
3150 code_push_statement(code, &stmt, instr->context);
3152 retvalue = instr->_ops[0];
3153 if (retvalue && retvalue->store != store_return &&
3154 (retvalue->store == store_global || vec_size(retvalue->life)))
3156 /* not to be kept in OFS_RETURN */
3157 if (retvalue->vtype == TYPE_FIELD && OPTS_FLAG(ADJUST_VECTOR_FIELDS))
3158 stmt.opcode = field_store_instr[retvalue->fieldtype];
3160 stmt.opcode = type_store_instr[retvalue->vtype];
3161 stmt.o1.u1 = OFS_RETURN;
3162 stmt.o2.u1 = ir_value_code_addr(retvalue);
3164 code_push_statement(code, &stmt, instr->context);
3169 if (instr->opcode == INSTR_STATE) {
3170 irerror(block->context, "TODO: state instruction");
3174 stmt.opcode = instr->opcode;
3179 /* This is the general order of operands */
3181 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
3184 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
3187 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
3189 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
3191 stmt.o1.u1 = stmt.o3.u1;
3194 else if ((stmt.opcode >= INSTR_STORE_F &&
3195 stmt.opcode <= INSTR_STORE_FNC) ||
3196 (stmt.opcode >= INSTR_STOREP_F &&
3197 stmt.opcode <= INSTR_STOREP_FNC))
3199 /* 2-operand instructions with A -> B */
3200 stmt.o2.u1 = stmt.o3.u1;
3203 /* tiny optimization, don't output
3206 if (stmt.o2.u1 == stmt.o1.u1 &&
3207 OPTS_OPTIMIZATION(OPTIM_PEEPHOLE))
3209 ++opts_optimizationcount[OPTIM_PEEPHOLE];
3213 code_push_statement(code, &stmt, instr->context);
3218 static bool gen_function_code(code_t *code, ir_function *self)
3221 prog_section_statement_t stmt, *retst;
3223 /* Starting from entry point, we generate blocks "as they come"
3224 * for now. Dead blocks will not be translated obviously.
3226 if (!vec_size(self->blocks)) {
3227 irerror(self->context, "Function '%s' declared without body.", self->name);
3231 block = self->blocks[0];
3232 if (block->generated)
3235 if (!gen_blocks_recursive(code, self, block)) {
3236 irerror(self->context, "failed to generate blocks for '%s'", self->name);
3240 /* code_write and qcvm -disasm need to know that the function ends here */
3241 retst = &vec_last(code->statements);
3242 if (OPTS_OPTIMIZATION(OPTIM_VOID_RETURN) &&
3243 self->outtype == TYPE_VOID &&
3244 retst->opcode == INSTR_RETURN &&
3245 !retst->o1.u1 && !retst->o2.u1 && !retst->o3.u1)
3247 retst->opcode = INSTR_DONE;
3248 ++opts_optimizationcount[OPTIM_VOID_RETURN];
3252 stmt.opcode = INSTR_DONE;
3256 last.line = vec_last(code->linenums);
3257 last.column = vec_last(code->columnnums);
3259 code_push_statement(code, &stmt, last);
3264 static qcint_t ir_builder_filestring(ir_builder *ir, const char *filename)
3266 /* NOTE: filename pointers are copied, we never strdup them,
3267 * thus we can use pointer-comparison to find the string.
3272 for (i = 0; i < vec_size(ir->filenames); ++i) {
3273 if (ir->filenames[i] == filename)
3274 return ir->filestrings[i];
3277 str = code_genstring(ir->code, filename);
3278 vec_push(ir->filenames, filename);
3279 vec_push(ir->filestrings, str);
3283 static bool gen_global_function(ir_builder *ir, ir_value *global)
3285 prog_section_function_t fun;
3290 if (!global->hasvalue || (!global->constval.vfunc))
3292 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
3296 irfun = global->constval.vfunc;
3298 fun.name = global->code.name;
3299 fun.file = ir_builder_filestring(ir, global->context.file);
3300 fun.profile = 0; /* always 0 */
3301 fun.nargs = vec_size(irfun->params);
3305 for (i = 0;i < 8; ++i) {
3306 if ((int32_t)i >= fun.nargs)
3309 fun.argsize[i] = type_sizeof_[irfun->params[i]];
3313 fun.locals = irfun->allocated_locals;
3316 fun.entry = irfun->builtin+1;
3318 irfun->code_function_def = vec_size(ir->code->functions);
3319 fun.entry = vec_size(ir->code->statements);
3322 vec_push(ir->code->functions, fun);
3326 static ir_value* ir_gen_extparam_proto(ir_builder *ir)
3331 util_snprintf(name, sizeof(name), "EXTPARM#%i", (int)(vec_size(ir->extparam_protos)));
3332 global = ir_value_var(name, store_global, TYPE_VECTOR);
3334 vec_push(ir->extparam_protos, global);
3338 static void ir_gen_extparam(ir_builder *ir)
3340 prog_section_def_t def;
3343 if (vec_size(ir->extparam_protos) < vec_size(ir->extparams)+1)
3344 global = ir_gen_extparam_proto(ir);
3346 global = ir->extparam_protos[vec_size(ir->extparams)];
3348 def.name = code_genstring(ir->code, global->name);
3349 def.type = TYPE_VECTOR;
3350 def.offset = vec_size(ir->code->globals);
3352 vec_push(ir->code->defs, def);
3354 ir_value_code_setaddr(global, def.offset);
3356 vec_push(ir->code->globals, 0);
3357 vec_push(ir->code->globals, 0);
3358 vec_push(ir->code->globals, 0);
3360 vec_push(ir->extparams, global);
3363 static bool gen_function_extparam_copy(code_t *code, ir_function *self)
3365 size_t i, ext, numparams;
3367 ir_builder *ir = self->owner;
3369 prog_section_statement_t stmt;
3371 numparams = vec_size(self->params);
3375 stmt.opcode = INSTR_STORE_F;
3377 for (i = 8; i < numparams; ++i) {
3379 if (ext >= vec_size(ir->extparams))
3380 ir_gen_extparam(ir);
3382 ep = ir->extparams[ext];
3384 stmt.opcode = type_store_instr[self->locals[i]->vtype];
3385 if (self->locals[i]->vtype == TYPE_FIELD &&
3386 self->locals[i]->fieldtype == TYPE_VECTOR)
3388 stmt.opcode = INSTR_STORE_V;
3390 stmt.o1.u1 = ir_value_code_addr(ep);
3391 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3392 code_push_statement(code, &stmt, self->context);
3398 static bool gen_function_varargs_copy(code_t *code, ir_function *self)
3400 size_t i, ext, numparams, maxparams;
3402 ir_builder *ir = self->owner;
3404 prog_section_statement_t stmt;
3406 numparams = vec_size(self->params);
3410 stmt.opcode = INSTR_STORE_V;
3412 maxparams = numparams + self->max_varargs;
3413 for (i = numparams; i < maxparams; ++i) {
3415 stmt.o1.u1 = OFS_PARM0 + 3*i;
3416 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3417 code_push_statement(code, &stmt, self->context);
3421 while (ext >= vec_size(ir->extparams))
3422 ir_gen_extparam(ir);
3424 ep = ir->extparams[ext];
3426 stmt.o1.u1 = ir_value_code_addr(ep);
3427 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3428 code_push_statement(code, &stmt, self->context);
3434 static bool gen_function_locals(ir_builder *ir, ir_value *global)
3436 prog_section_function_t *def;
3439 uint32_t firstlocal, firstglobal;
3441 irfun = global->constval.vfunc;
3442 def = ir->code->functions + irfun->code_function_def;
3444 if (OPTS_OPTION_BOOL(OPTION_G) ||
3445 !OPTS_OPTIMIZATION(OPTIM_OVERLAP_LOCALS) ||
3446 (irfun->flags & IR_FLAG_MASK_NO_OVERLAP))
3448 firstlocal = def->firstlocal = vec_size(ir->code->globals);
3450 firstlocal = def->firstlocal = ir->first_common_local;
3451 ++opts_optimizationcount[OPTIM_OVERLAP_LOCALS];
3454 firstglobal = (OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS) ? ir->first_common_globaltemp : firstlocal);
3456 for (i = vec_size(ir->code->globals); i < firstlocal + irfun->allocated_locals; ++i)
3457 vec_push(ir->code->globals, 0);
3458 for (i = 0; i < vec_size(irfun->locals); ++i) {
3459 ir_value *v = irfun->locals[i];
3460 if (v->locked || !OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS)) {
3461 ir_value_code_setaddr(v, firstlocal + v->code.local);
3462 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
3463 irerror(irfun->locals[i]->context, "failed to generate local %s", irfun->locals[i]->name);
3468 ir_value_code_setaddr(v, firstglobal + v->code.local);
3470 for (i = 0; i < vec_size(irfun->values); ++i)
3472 ir_value *v = irfun->values[i];
3476 ir_value_code_setaddr(v, firstlocal + v->code.local);
3478 ir_value_code_setaddr(v, firstglobal + v->code.local);
3483 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
3485 prog_section_function_t *fundef;
3490 irfun = global->constval.vfunc;
3492 if (global->cvq == CV_NONE) {
3493 if (irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
3494 "function `%s` has no body and in QC implicitly becomes a function-pointer",
3497 /* Not bailing out just now. If this happens a lot you don't want to have
3498 * to rerun gmqcc for each such function.
3504 /* this was a function pointer, don't generate code for those */
3512 * If there is no definition and the thing is eraseable, we can ignore
3513 * outputting the function to begin with.
3515 if (global->flags & IR_FLAG_ERASEABLE && irfun->code_function_def < 0) {
3519 if (irfun->code_function_def < 0) {
3520 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
3523 fundef = &ir->code->functions[irfun->code_function_def];
3525 fundef->entry = vec_size(ir->code->statements);
3526 if (!gen_function_locals(ir, global)) {
3527 irerror(irfun->context, "Failed to generate locals for function %s", irfun->name);
3530 if (!gen_function_extparam_copy(ir->code, irfun)) {
3531 irerror(irfun->context, "Failed to generate extparam-copy code for function %s", irfun->name);
3534 if (irfun->max_varargs && !gen_function_varargs_copy(ir->code, irfun)) {
3535 irerror(irfun->context, "Failed to generate vararg-copy code for function %s", irfun->name);
3538 if (!gen_function_code(ir->code, irfun)) {
3539 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
3545 static void gen_vector_defs(code_t *code, prog_section_def_t def, const char *name)
3550 if (!name || name[0] == '#' || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3553 def.type = TYPE_FLOAT;
3557 component = (char*)mem_a(len+3);
3558 memcpy(component, name, len);
3560 component[len-0] = 0;
3561 component[len-2] = '_';
3563 component[len-1] = 'x';
3565 for (i = 0; i < 3; ++i) {
3566 def.name = code_genstring(code, component);
3567 vec_push(code->defs, def);
3575 static void gen_vector_fields(code_t *code, prog_section_field_t fld, const char *name)
3580 if (!name || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3583 fld.type = TYPE_FLOAT;
3587 component = (char*)mem_a(len+3);
3588 memcpy(component, name, len);
3590 component[len-0] = 0;
3591 component[len-2] = '_';
3593 component[len-1] = 'x';
3595 for (i = 0; i < 3; ++i) {
3596 fld.name = code_genstring(code, component);
3597 vec_push(code->fields, fld);
3605 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
3609 prog_section_def_t def;
3610 bool pushdef = opts.optimizeoff;
3612 def.type = global->vtype;
3613 def.offset = vec_size(self->code->globals);
3615 if (OPTS_OPTION_BOOL(OPTION_G) || !islocal)
3620 * if we're eraseable and the function isn't referenced ignore outputting
3623 if (global->flags & IR_FLAG_ERASEABLE && vec_size(global->reads) == 0) {
3627 if (OPTS_OPTIMIZATION(OPTIM_STRIP_CONSTANT_NAMES) &&
3628 !(global->flags & IR_FLAG_INCLUDE_DEF) &&
3629 (global->name[0] == '#' || global->cvq == CV_CONST))
3635 if (global->name[0] == '#') {
3636 if (!self->str_immediate)
3637 self->str_immediate = code_genstring(self->code, "IMMEDIATE");
3638 def.name = global->code.name = self->str_immediate;
3641 def.name = global->code.name = code_genstring(self->code, global->name);
3646 def.offset = ir_value_code_addr(global);
3647 vec_push(self->code->defs, def);
3648 if (global->vtype == TYPE_VECTOR)
3649 gen_vector_defs(self->code, def, global->name);
3650 else if (global->vtype == TYPE_FIELD && global->fieldtype == TYPE_VECTOR)
3651 gen_vector_defs(self->code, def, global->name);
3658 switch (global->vtype)
3661 if (!strcmp(global->name, "end_sys_globals")) {
3662 /* TODO: remember this point... all the defs before this one
3663 * should be checksummed and added to progdefs.h when we generate it.
3666 else if (!strcmp(global->name, "end_sys_fields")) {
3667 /* TODO: same as above but for entity-fields rather than globsl
3670 else if(irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3673 /* Not bailing out */
3676 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3677 * the system fields actually go? Though the engine knows this anyway...
3678 * Maybe this could be an -foption
3679 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3681 ir_value_code_setaddr(global, vec_size(self->code->globals));
3682 vec_push(self->code->globals, 0);
3684 if (pushdef) vec_push(self->code->defs, def);
3687 if (pushdef) vec_push(self->code->defs, def);
3688 return gen_global_pointer(self->code, global);
3691 vec_push(self->code->defs, def);
3692 if (global->fieldtype == TYPE_VECTOR)
3693 gen_vector_defs(self->code, def, global->name);
3695 return gen_global_field(self->code, global);
3700 ir_value_code_setaddr(global, vec_size(self->code->globals));
3701 if (global->hasvalue) {
3702 iptr = (int32_t*)&global->constval.ivec[0];
3703 vec_push(self->code->globals, *iptr);
3705 vec_push(self->code->globals, 0);
3707 if (!islocal && global->cvq != CV_CONST)
3708 def.type |= DEF_SAVEGLOBAL;
3709 if (pushdef) vec_push(self->code->defs, def);
3711 return global->code.globaladdr >= 0;
3715 ir_value_code_setaddr(global, vec_size(self->code->globals));
3716 if (global->hasvalue) {
3717 uint32_t load = code_genstring(self->code, global->constval.vstring);
3718 vec_push(self->code->globals, load);
3720 vec_push(self->code->globals, 0);
3722 if (!islocal && global->cvq != CV_CONST)
3723 def.type |= DEF_SAVEGLOBAL;
3724 if (pushdef) vec_push(self->code->defs, def);
3725 return global->code.globaladdr >= 0;
3730 ir_value_code_setaddr(global, vec_size(self->code->globals));
3731 if (global->hasvalue) {
3732 iptr = (int32_t*)&global->constval.ivec[0];
3733 vec_push(self->code->globals, iptr[0]);
3734 if (global->code.globaladdr < 0)
3736 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3737 vec_push(self->code->globals, iptr[d]);
3740 vec_push(self->code->globals, 0);
3741 if (global->code.globaladdr < 0)
3743 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3744 vec_push(self->code->globals, 0);
3747 if (!islocal && global->cvq != CV_CONST)
3748 def.type |= DEF_SAVEGLOBAL;
3751 vec_push(self->code->defs, def);
3752 def.type &= ~DEF_SAVEGLOBAL;
3753 gen_vector_defs(self->code, def, global->name);
3755 return global->code.globaladdr >= 0;
3758 ir_value_code_setaddr(global, vec_size(self->code->globals));
3759 if (!global->hasvalue) {
3760 vec_push(self->code->globals, 0);
3761 if (global->code.globaladdr < 0)
3764 vec_push(self->code->globals, vec_size(self->code->functions));
3765 if (!gen_global_function(self, global))
3768 if (!islocal && global->cvq != CV_CONST)
3769 def.type |= DEF_SAVEGLOBAL;
3770 if (pushdef) vec_push(self->code->defs, def);
3773 /* assume biggest type */
3774 ir_value_code_setaddr(global, vec_size(self->code->globals));
3775 vec_push(self->code->globals, 0);
3776 for (i = 1; i < type_sizeof_[TYPE_VARIANT]; ++i)
3777 vec_push(self->code->globals, 0);
3780 /* refuse to create 'void' type or any other fancy business. */
3781 irerror(global->context, "Invalid type for global variable `%s`: %s",
3782 global->name, type_name[global->vtype]);
3787 static GMQCC_INLINE void ir_builder_prepare_field(code_t *code, ir_value *field)
3789 field->code.fieldaddr = code_alloc_field(code, type_sizeof_[field->fieldtype]);
3792 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3794 prog_section_def_t def;
3795 prog_section_field_t fld;
3799 def.type = (uint16_t)field->vtype;
3800 def.offset = (uint16_t)vec_size(self->code->globals);
3802 /* create a global named the same as the field */
3803 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
3804 /* in our standard, the global gets a dot prefix */
3805 size_t len = strlen(field->name);
3808 /* we really don't want to have to allocate this, and 1024
3809 * bytes is more than enough for a variable/field name
3811 if (len+2 >= sizeof(name)) {
3812 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
3817 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
3820 def.name = code_genstring(self->code, name);
3821 fld.name = def.name + 1; /* we reuse that string table entry */
3823 /* in plain QC, there cannot be a global with the same name,
3824 * and so we also name the global the same.
3825 * FIXME: fteqcc should create a global as well
3826 * check if it actually uses the same name. Probably does
3828 def.name = code_genstring(self->code, field->name);
3829 fld.name = def.name;
3832 field->code.name = def.name;
3834 vec_push(self->code->defs, def);
3836 fld.type = field->fieldtype;
3838 if (fld.type == TYPE_VOID) {
3839 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
3843 fld.offset = field->code.fieldaddr;
3845 vec_push(self->code->fields, fld);
3847 ir_value_code_setaddr(field, vec_size(self->code->globals));
3848 vec_push(self->code->globals, fld.offset);
3849 if (fld.type == TYPE_VECTOR) {
3850 vec_push(self->code->globals, fld.offset+1);
3851 vec_push(self->code->globals, fld.offset+2);
3854 if (field->fieldtype == TYPE_VECTOR) {
3855 gen_vector_defs (self->code, def, field->name);
3856 gen_vector_fields(self->code, fld, field->name);
3859 return field->code.globaladdr >= 0;
3862 bool ir_builder_generate(ir_builder *self, const char *filename)
3864 prog_section_statement_t stmt;
3866 char *lnofile = NULL;
3868 for (i = 0; i < vec_size(self->fields); ++i)
3870 ir_builder_prepare_field(self->code, self->fields[i]);
3873 for (i = 0; i < vec_size(self->globals); ++i)
3875 if (!ir_builder_gen_global(self, self->globals[i], false)) {
3878 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3879 ir_function *func = self->globals[i]->constval.vfunc;
3880 if (func && self->max_locals < func->allocated_locals &&
3881 !(func->flags & IR_FLAG_MASK_NO_OVERLAP))
3883 self->max_locals = func->allocated_locals;
3885 if (func && self->max_globaltemps < func->globaltemps)
3886 self->max_globaltemps = func->globaltemps;
3890 for (i = 0; i < vec_size(self->fields); ++i)
3892 if (!ir_builder_gen_field(self, self->fields[i])) {
3898 ir_value_code_setaddr(self->nil, vec_size(self->code->globals));
3899 vec_push(self->code->globals, 0);
3900 vec_push(self->code->globals, 0);
3901 vec_push(self->code->globals, 0);
3903 /* generate virtual-instruction temps */
3904 for (i = 0; i < IR_MAX_VINSTR_TEMPS; ++i) {
3905 ir_value_code_setaddr(self->vinstr_temp[i], vec_size(self->code->globals));
3906 vec_push(self->code->globals, 0);
3907 vec_push(self->code->globals, 0);
3908 vec_push(self->code->globals, 0);
3911 /* generate global temps */
3912 self->first_common_globaltemp = vec_size(self->code->globals);
3913 for (i = 0; i < self->max_globaltemps; ++i) {
3914 vec_push(self->code->globals, 0);
3916 /* generate common locals */
3917 self->first_common_local = vec_size(self->code->globals);
3918 for (i = 0; i < self->max_locals; ++i) {
3919 vec_push(self->code->globals, 0);
3922 /* generate function code */
3923 for (i = 0; i < vec_size(self->globals); ++i)
3925 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3926 if (!gen_global_function_code(self, self->globals[i])) {
3932 if (vec_size(self->code->globals) >= 65536) {
3933 irerror(vec_last(self->globals)->context, "This progs file would require more globals than the metadata can handle. Bailing out.");
3937 /* DP errors if the last instruction is not an INSTR_DONE. */
3938 if (vec_last(self->code->statements).opcode != INSTR_DONE)
3942 stmt.opcode = INSTR_DONE;
3946 last.line = vec_last(self->code->linenums);
3947 last.column = vec_last(self->code->columnnums);
3949 code_push_statement(self->code, &stmt, last);
3952 if (OPTS_OPTION_BOOL(OPTION_PP_ONLY))
3955 if (vec_size(self->code->statements) != vec_size(self->code->linenums)) {
3956 con_err("Linecounter wrong: %lu != %lu\n",
3957 (unsigned long)vec_size(self->code->statements),
3958 (unsigned long)vec_size(self->code->linenums));
3959 } else if (OPTS_FLAG(LNO)) {
3961 size_t filelen = strlen(filename);
3963 memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
3964 dot = strrchr(lnofile, '.');
3968 vec_shrinkto(lnofile, dot - lnofile);
3970 memcpy(vec_add(lnofile, 5), ".lno", 5);
3973 if (!code_write(self->code, filename, lnofile)) {
3982 /***********************************************************************
3983 *IR DEBUG Dump functions...
3986 #define IND_BUFSZ 1024
3988 static const char *qc_opname(int op)
3990 if (op < 0) return "<INVALID>";
3991 if (op < VINSTR_END)
3992 return util_instr_str[op];
3994 case VINSTR_END: return "END";
3995 case VINSTR_PHI: return "PHI";
3996 case VINSTR_JUMP: return "JUMP";
3997 case VINSTR_COND: return "COND";
3998 case VINSTR_BITXOR: return "BITXOR";
3999 case VINSTR_BITAND_V: return "BITAND_V";
4000 case VINSTR_BITOR_V: return "BITOR_V";
4001 case VINSTR_BITXOR_V: return "BITXOR_V";
4002 case VINSTR_BITAND_VF: return "BITAND_VF";
4003 case VINSTR_BITOR_VF: return "BITOR_VF";
4004 case VINSTR_BITXOR_VF: return "BITXOR_VF";
4005 case VINSTR_CROSS: return "CROSS";
4006 case VINSTR_NEG_F: return "NEG_F";
4007 case VINSTR_NEG_V: return "NEG_V";
4008 default: return "<UNK>";
4012 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
4015 char indent[IND_BUFSZ];
4019 oprintf("module %s\n", b->name);
4020 for (i = 0; i < vec_size(b->globals); ++i)
4023 if (b->globals[i]->hasvalue)
4024 oprintf("%s = ", b->globals[i]->name);
4025 ir_value_dump(b->globals[i], oprintf);
4028 for (i = 0; i < vec_size(b->functions); ++i)
4029 ir_function_dump(b->functions[i], indent, oprintf);
4030 oprintf("endmodule %s\n", b->name);
4033 static const char *storenames[] = {
4034 "[global]", "[local]", "[param]", "[value]", "[return]"
4037 void ir_function_dump(ir_function *f, char *ind,
4038 int (*oprintf)(const char*, ...))
4041 if (f->builtin != 0) {
4042 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
4045 oprintf("%sfunction %s\n", ind, f->name);
4046 util_strncat(ind, "\t", IND_BUFSZ-1);
4047 if (vec_size(f->locals))
4049 oprintf("%s%i locals:\n", ind, (int)vec_size(f->locals));
4050 for (i = 0; i < vec_size(f->locals); ++i) {
4051 oprintf("%s\t", ind);
4052 ir_value_dump(f->locals[i], oprintf);
4056 oprintf("%sliferanges:\n", ind);
4057 for (i = 0; i < vec_size(f->locals); ++i) {
4058 const char *attr = "";
4060 ir_value *v = f->locals[i];
4061 if (v->unique_life && v->locked)
4062 attr = "unique,locked ";
4063 else if (v->unique_life)
4067 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
4068 storenames[v->store],
4069 attr, (v->callparam ? "callparam " : ""),
4070 (int)v->code.local);
4073 for (l = 0; l < vec_size(v->life); ++l) {
4074 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
4077 for (m = 0; m < 3; ++m) {
4078 ir_value *vm = v->members[m];
4081 oprintf("%s\t%s: @%i ", ind, vm->name, (int)vm->code.local);
4082 for (l = 0; l < vec_size(vm->life); ++l) {
4083 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
4088 for (i = 0; i < vec_size(f->values); ++i) {
4089 const char *attr = "";
4091 ir_value *v = f->values[i];
4092 if (v->unique_life && v->locked)
4093 attr = "unique,locked ";
4094 else if (v->unique_life)
4098 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
4099 storenames[v->store],
4100 attr, (v->callparam ? "callparam " : ""),
4101 (int)v->code.local);
4104 for (l = 0; l < vec_size(v->life); ++l) {
4105 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
4108 for (m = 0; m < 3; ++m) {
4109 ir_value *vm = v->members[m];
4112 if (vm->unique_life && vm->locked)
4113 attr = "unique,locked ";
4114 else if (vm->unique_life)
4116 else if (vm->locked)
4118 oprintf("%s\t%s: %s@%i ", ind, vm->name, attr, (int)vm->code.local);
4119 for (l = 0; l < vec_size(vm->life); ++l) {
4120 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
4125 if (vec_size(f->blocks))
4127 oprintf("%slife passes: %i\n", ind, (int)f->run_id);
4128 for (i = 0; i < vec_size(f->blocks); ++i) {
4129 ir_block_dump(f->blocks[i], ind, oprintf);
4133 ind[strlen(ind)-1] = 0;
4134 oprintf("%sendfunction %s\n", ind, f->name);
4137 void ir_block_dump(ir_block* b, char *ind,
4138 int (*oprintf)(const char*, ...))
4141 oprintf("%s:%s\n", ind, b->label);
4142 util_strncat(ind, "\t", IND_BUFSZ-1);
4144 if (b->instr && b->instr[0])
4145 oprintf("%s (%i) [entry]\n", ind, (int)(b->instr[0]->eid-1));
4146 for (i = 0; i < vec_size(b->instr); ++i)
4147 ir_instr_dump(b->instr[i], ind, oprintf);
4148 ind[strlen(ind)-1] = 0;
4151 static void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
4154 oprintf("%s <- phi ", in->_ops[0]->name);
4155 for (i = 0; i < vec_size(in->phi); ++i)
4157 oprintf("([%s] : %s) ", in->phi[i].from->label,
4158 in->phi[i].value->name);
4163 void ir_instr_dump(ir_instr *in, char *ind,
4164 int (*oprintf)(const char*, ...))
4167 const char *comma = NULL;
4169 oprintf("%s (%i) ", ind, (int)in->eid);
4171 if (in->opcode == VINSTR_PHI) {
4172 dump_phi(in, oprintf);
4176 util_strncat(ind, "\t", IND_BUFSZ-1);
4178 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
4179 ir_value_dump(in->_ops[0], oprintf);
4180 if (in->_ops[1] || in->_ops[2])
4183 if (in->opcode == INSTR_CALL0 || in->opcode == VINSTR_NRCALL) {
4184 oprintf("CALL%i\t", vec_size(in->params));
4186 oprintf("%s\t", qc_opname(in->opcode));
4188 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
4189 ir_value_dump(in->_ops[0], oprintf);
4194 for (i = 1; i != 3; ++i) {
4198 ir_value_dump(in->_ops[i], oprintf);
4206 oprintf("[%s]", in->bops[0]->label);
4210 oprintf("%s[%s]", comma, in->bops[1]->label);
4211 if (vec_size(in->params)) {
4212 oprintf("\tparams: ");
4213 for (i = 0; i != vec_size(in->params); ++i) {
4214 oprintf("%s, ", in->params[i]->name);
4218 ind[strlen(ind)-1] = 0;
4221 static void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
4224 for (; *str; ++str) {
4226 case '\n': oprintf("\\n"); break;
4227 case '\r': oprintf("\\r"); break;
4228 case '\t': oprintf("\\t"); break;
4229 case '\v': oprintf("\\v"); break;
4230 case '\f': oprintf("\\f"); break;
4231 case '\b': oprintf("\\b"); break;
4232 case '\a': oprintf("\\a"); break;
4233 case '\\': oprintf("\\\\"); break;
4234 case '"': oprintf("\\\""); break;
4235 default: oprintf("%c", *str); break;
4241 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
4250 oprintf("fn:%s", v->name);
4253 oprintf("%g", v->constval.vfloat);
4256 oprintf("'%g %g %g'",
4259 v->constval.vvec.z);
4262 oprintf("(entity)");
4265 ir_value_dump_string(v->constval.vstring, oprintf);
4269 oprintf("%i", v->constval.vint);
4274 v->constval.vpointer->name);
4278 oprintf("%s", v->name);
4282 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
4285 oprintf("Life of %12s:", self->name);
4286 for (i = 0; i < vec_size(self->life); ++i)
4288 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);