2 * Copyright (C) 2012, 2013
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 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)
316 self = (ir_builder*)mem_a(sizeof(*self));
320 self->functions = NULL;
321 self->globals = NULL;
323 self->filenames = NULL;
324 self->filestrings = NULL;
325 self->htglobals = util_htnew(IR_HT_SIZE);
326 self->htfields = util_htnew(IR_HT_SIZE);
327 self->htfunctions = util_htnew(IR_HT_SIZE);
329 self->extparams = NULL;
330 self->extparam_protos = NULL;
332 self->first_common_globaltemp = 0;
333 self->max_globaltemps = 0;
334 self->first_common_local = 0;
335 self->max_locals = 0;
337 self->str_immediate = 0;
339 if (!ir_builder_set_name(self, modulename)) {
344 self->nil = ir_value_var("nil", store_value, TYPE_NIL);
345 self->nil->cvq = CV_CONST;
347 self->reserved_va_count = NULL;
348 self->code = code_init();
353 void ir_builder_delete(ir_builder* self)
356 util_htdel(self->htglobals);
357 util_htdel(self->htfields);
358 util_htdel(self->htfunctions);
359 mem_d((void*)self->name);
360 for (i = 0; i != vec_size(self->functions); ++i) {
361 ir_function_delete_quick(self->functions[i]);
363 vec_free(self->functions);
364 for (i = 0; i != vec_size(self->extparams); ++i) {
365 ir_value_delete(self->extparams[i]);
367 vec_free(self->extparams);
368 vec_free(self->extparam_protos);
369 for (i = 0; i != vec_size(self->globals); ++i) {
370 ir_value_delete(self->globals[i]);
372 vec_free(self->globals);
373 for (i = 0; i != vec_size(self->fields); ++i) {
374 ir_value_delete(self->fields[i]);
376 ir_value_delete(self->nil);
377 vec_free(self->fields);
378 vec_free(self->filenames);
379 vec_free(self->filestrings);
381 code_cleanup(self->code);
385 bool ir_builder_set_name(ir_builder *self, const char *name)
388 mem_d((void*)self->name);
389 self->name = util_strdup(name);
393 static ir_function* ir_builder_get_function(ir_builder *self, const char *name)
395 return (ir_function*)util_htget(self->htfunctions, name);
398 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
400 ir_function *fn = ir_builder_get_function(self, name);
405 fn = ir_function_new(self, outtype);
406 if (!ir_function_set_name(fn, name))
408 ir_function_delete(fn);
411 vec_push(self->functions, fn);
412 util_htset(self->htfunctions, name, fn);
414 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
416 ir_function_delete(fn);
420 fn->value->hasvalue = true;
421 fn->value->outtype = outtype;
422 fn->value->constval.vfunc = fn;
423 fn->value->context = fn->context;
428 static ir_value* ir_builder_get_global(ir_builder *self, const char *name)
430 return (ir_value*)util_htget(self->htglobals, name);
433 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
437 if (name && name[0] != '#')
439 ve = ir_builder_get_global(self, name);
445 ve = ir_value_var(name, store_global, vtype);
446 vec_push(self->globals, ve);
447 util_htset(self->htglobals, name, ve);
451 ir_value* ir_builder_get_va_count(ir_builder *self)
453 if (self->reserved_va_count)
454 return self->reserved_va_count;
455 return (self->reserved_va_count = ir_builder_create_global(self, "reserved:va_count", TYPE_FLOAT));
458 static ir_value* ir_builder_get_field(ir_builder *self, const char *name)
460 return (ir_value*)util_htget(self->htfields, name);
464 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
466 ir_value *ve = ir_builder_get_field(self, name);
471 ve = ir_value_var(name, store_global, TYPE_FIELD);
472 ve->fieldtype = vtype;
473 vec_push(self->fields, ve);
474 util_htset(self->htfields, name, ve);
478 /***********************************************************************
482 static bool ir_function_naive_phi(ir_function*);
483 static void ir_function_enumerate(ir_function*);
484 static bool ir_function_calculate_liferanges(ir_function*);
485 static bool ir_function_allocate_locals(ir_function*);
487 ir_function* ir_function_new(ir_builder* owner, int outtype)
490 self = (ir_function*)mem_a(sizeof(*self));
495 memset(self, 0, sizeof(*self));
498 if (!ir_function_set_name(self, "<@unnamed>")) {
505 self->context.file = "<@no context>";
506 self->context.line = 0;
507 self->outtype = outtype;
516 self->max_varargs = 0;
518 self->code_function_def = -1;
519 self->allocated_locals = 0;
520 self->globaltemps = 0;
526 bool ir_function_set_name(ir_function *self, const char *name)
529 mem_d((void*)self->name);
530 self->name = util_strdup(name);
534 static void ir_function_delete_quick(ir_function *self)
537 mem_d((void*)self->name);
539 for (i = 0; i != vec_size(self->blocks); ++i)
540 ir_block_delete_quick(self->blocks[i]);
541 vec_free(self->blocks);
543 vec_free(self->params);
545 for (i = 0; i != vec_size(self->values); ++i)
546 ir_value_delete(self->values[i]);
547 vec_free(self->values);
549 for (i = 0; i != vec_size(self->locals); ++i)
550 ir_value_delete(self->locals[i]);
551 vec_free(self->locals);
553 /* self->value is deleted by the builder */
558 void ir_function_delete(ir_function *self)
561 mem_d((void*)self->name);
563 for (i = 0; i != vec_size(self->blocks); ++i)
564 ir_block_delete(self->blocks[i]);
565 vec_free(self->blocks);
567 vec_free(self->params);
569 for (i = 0; i != vec_size(self->values); ++i)
570 ir_value_delete(self->values[i]);
571 vec_free(self->values);
573 for (i = 0; i != vec_size(self->locals); ++i)
574 ir_value_delete(self->locals[i]);
575 vec_free(self->locals);
577 /* self->value is deleted by the builder */
582 static void ir_function_collect_value(ir_function *self, ir_value *v)
584 vec_push(self->values, v);
587 ir_block* ir_function_create_block(lex_ctx_t ctx, ir_function *self, const char *label)
589 ir_block* bn = ir_block_new(self, label);
591 vec_push(self->blocks, bn);
595 static bool instr_is_operation(uint16_t op)
597 return ( (op >= INSTR_MUL_F && op <= INSTR_GT) ||
598 (op >= INSTR_LOAD_F && op <= INSTR_LOAD_FNC) ||
599 (op == INSTR_ADDRESS) ||
600 (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) ||
601 (op >= INSTR_AND && op <= INSTR_BITOR) ||
602 (op >= INSTR_CALL0 && op <= INSTR_CALL8) );
605 static bool ir_function_pass_peephole(ir_function *self)
609 for (b = 0; b < vec_size(self->blocks); ++b) {
611 ir_block *block = self->blocks[b];
613 for (i = 0; i < vec_size(block->instr); ++i) {
615 inst = block->instr[i];
618 (inst->opcode >= INSTR_STORE_F &&
619 inst->opcode <= INSTR_STORE_FNC))
627 oper = block->instr[i-1];
628 if (!instr_is_operation(oper->opcode))
631 if (OPTS_FLAG(LEGACY_VECTOR_MATHS)) {
632 if (oper->opcode == INSTR_MUL_VF && oper->_ops[2]->memberof == oper->_ops[1])
634 if (oper->opcode == INSTR_MUL_FV && oper->_ops[1]->memberof == oper->_ops[2])
638 value = oper->_ops[0];
640 /* only do it for SSA values */
641 if (value->store != store_value)
644 /* don't optimize out the temp if it's used later again */
645 if (vec_size(value->reads) != 1)
648 /* The very next store must use this value */
649 if (value->reads[0] != store)
652 /* And of course the store must _read_ from it, so it's in
654 if (store->_ops[1] != value)
657 ++opts_optimizationcount[OPTIM_PEEPHOLE];
658 (void)!ir_instr_op(oper, 0, store->_ops[0], true);
660 vec_remove(block->instr, i, 1);
661 ir_instr_delete(store);
663 else if (inst->opcode == VINSTR_COND)
665 /* COND on a value resulting from a NOT could
666 * remove the NOT and swap its operands
673 value = inst->_ops[0];
675 if (value->store != store_value ||
676 vec_size(value->reads) != 1 ||
677 value->reads[0] != inst)
682 inot = value->writes[0];
683 if (inot->_ops[0] != value ||
684 inot->opcode < INSTR_NOT_F ||
685 inot->opcode > INSTR_NOT_FNC ||
686 inot->opcode == INSTR_NOT_V || /* can't do these */
687 inot->opcode == INSTR_NOT_S)
693 ++opts_optimizationcount[OPTIM_PEEPHOLE];
695 (void)!ir_instr_op(inst, 0, inot->_ops[1], false);
698 for (inotid = 0; inotid < vec_size(tmp->instr); ++inotid) {
699 if (tmp->instr[inotid] == inot)
702 if (inotid >= vec_size(tmp->instr)) {
703 compile_error(inst->context, "sanity-check failed: failed to find instruction to optimize out");
706 vec_remove(tmp->instr, inotid, 1);
707 ir_instr_delete(inot);
708 /* swap ontrue/onfalse */
710 inst->bops[0] = inst->bops[1];
721 static bool ir_function_pass_tailrecursion(ir_function *self)
725 for (b = 0; b < vec_size(self->blocks); ++b) {
727 ir_instr *ret, *call, *store = NULL;
728 ir_block *block = self->blocks[b];
730 if (!block->final || vec_size(block->instr) < 2)
733 ret = block->instr[vec_size(block->instr)-1];
734 if (ret->opcode != INSTR_DONE && ret->opcode != INSTR_RETURN)
737 call = block->instr[vec_size(block->instr)-2];
738 if (call->opcode >= INSTR_STORE_F && call->opcode <= INSTR_STORE_FNC) {
739 /* account for the unoptimized
741 * STORE %return, %tmp
745 if (vec_size(block->instr) < 3)
749 call = block->instr[vec_size(block->instr)-3];
752 if (call->opcode < INSTR_CALL0 || call->opcode > INSTR_CALL8)
756 /* optimize out the STORE */
758 ret->_ops[0] == store->_ops[0] &&
759 store->_ops[1] == call->_ops[0])
761 ++opts_optimizationcount[OPTIM_PEEPHOLE];
762 call->_ops[0] = store->_ops[0];
763 vec_remove(block->instr, vec_size(block->instr) - 2, 1);
764 ir_instr_delete(store);
773 funcval = call->_ops[1];
776 if (funcval->vtype != TYPE_FUNCTION || funcval->constval.vfunc != self)
779 /* now we have a CALL and a RET, check if it's a tailcall */
780 if (ret->_ops[0] && call->_ops[0] != ret->_ops[0])
783 ++opts_optimizationcount[OPTIM_TAIL_RECURSION];
784 vec_shrinkby(block->instr, 2);
786 block->final = false; /* open it back up */
788 /* emite parameter-stores */
789 for (p = 0; p < vec_size(call->params); ++p) {
790 /* assert(call->params_count <= self->locals_count); */
791 if (!ir_block_create_store(block, call->context, self->locals[p], call->params[p])) {
792 irerror(call->context, "failed to create tailcall store instruction for parameter %i", (int)p);
796 if (!ir_block_create_jump(block, call->context, self->blocks[0])) {
797 irerror(call->context, "failed to create tailcall jump");
801 ir_instr_delete(call);
802 ir_instr_delete(ret);
808 bool ir_function_finalize(ir_function *self)
815 if (OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
816 if (!ir_function_pass_peephole(self)) {
817 irerror(self->context, "generic optimization pass broke something in `%s`", self->name);
822 if (OPTS_OPTIMIZATION(OPTIM_TAIL_RECURSION)) {
823 if (!ir_function_pass_tailrecursion(self)) {
824 irerror(self->context, "tail-recursion optimization pass broke something in `%s`", self->name);
829 if (!ir_function_naive_phi(self)) {
830 irerror(self->context, "internal error: ir_function_naive_phi failed");
834 for (i = 0; i < vec_size(self->locals); ++i) {
835 ir_value *v = self->locals[i];
836 if (v->vtype == TYPE_VECTOR ||
837 (v->vtype == TYPE_FIELD && v->outtype == TYPE_VECTOR))
839 ir_value_vector_member(v, 0);
840 ir_value_vector_member(v, 1);
841 ir_value_vector_member(v, 2);
844 for (i = 0; i < vec_size(self->values); ++i) {
845 ir_value *v = self->values[i];
846 if (v->vtype == TYPE_VECTOR ||
847 (v->vtype == TYPE_FIELD && v->outtype == TYPE_VECTOR))
849 ir_value_vector_member(v, 0);
850 ir_value_vector_member(v, 1);
851 ir_value_vector_member(v, 2);
855 ir_function_enumerate(self);
857 if (!ir_function_calculate_liferanges(self))
859 if (!ir_function_allocate_locals(self))
864 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
869 vec_size(self->locals) &&
870 self->locals[vec_size(self->locals)-1]->store != store_param) {
871 irerror(self->context, "cannot add parameters after adding locals");
875 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
878 vec_push(self->locals, ve);
882 /***********************************************************************
886 ir_block* ir_block_new(ir_function* owner, const char *name)
889 self = (ir_block*)mem_a(sizeof(*self));
893 memset(self, 0, sizeof(*self));
896 if (name && !ir_block_set_label(self, name)) {
901 self->context.file = "<@no context>";
902 self->context.line = 0;
906 self->entries = NULL;
910 self->is_return = false;
914 self->generated = false;
919 static void ir_block_delete_quick(ir_block* self)
922 if (self->label) mem_d(self->label);
923 for (i = 0; i != vec_size(self->instr); ++i)
924 ir_instr_delete_quick(self->instr[i]);
925 vec_free(self->instr);
926 vec_free(self->entries);
927 vec_free(self->exits);
928 vec_free(self->living);
932 void ir_block_delete(ir_block* self)
935 if (self->label) mem_d(self->label);
936 for (i = 0; i != vec_size(self->instr); ++i)
937 ir_instr_delete(self->instr[i]);
938 vec_free(self->instr);
939 vec_free(self->entries);
940 vec_free(self->exits);
941 vec_free(self->living);
945 bool ir_block_set_label(ir_block *self, const char *name)
948 mem_d((void*)self->label);
949 self->label = util_strdup(name);
950 return !!self->label;
953 /***********************************************************************
957 static ir_instr* ir_instr_new(lex_ctx_t ctx, ir_block* owner, int op)
960 self = (ir_instr*)mem_a(sizeof(*self));
967 self->_ops[0] = NULL;
968 self->_ops[1] = NULL;
969 self->_ops[2] = NULL;
970 self->bops[0] = NULL;
971 self->bops[1] = NULL;
982 static void ir_instr_delete_quick(ir_instr *self)
985 vec_free(self->params);
989 static void ir_instr_delete(ir_instr *self)
992 /* The following calls can only delete from
993 * vectors, we still want to delete this instruction
994 * so ignore the return value. Since with the warn_unused_result attribute
995 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
996 * I have to improvise here and use if(foo());
998 for (i = 0; i < vec_size(self->phi); ++i) {
1000 if (vec_ir_instr_find(self->phi[i].value->writes, self, &idx))
1001 vec_remove(self->phi[i].value->writes, idx, 1);
1002 if (vec_ir_instr_find(self->phi[i].value->reads, self, &idx))
1003 vec_remove(self->phi[i].value->reads, idx, 1);
1005 vec_free(self->phi);
1006 for (i = 0; i < vec_size(self->params); ++i) {
1008 if (vec_ir_instr_find(self->params[i]->writes, self, &idx))
1009 vec_remove(self->params[i]->writes, idx, 1);
1010 if (vec_ir_instr_find(self->params[i]->reads, self, &idx))
1011 vec_remove(self->params[i]->reads, idx, 1);
1013 vec_free(self->params);
1014 (void)!ir_instr_op(self, 0, NULL, false);
1015 (void)!ir_instr_op(self, 1, NULL, false);
1016 (void)!ir_instr_op(self, 2, NULL, false);
1020 static bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
1022 if (self->_ops[op]) {
1024 if (writing && vec_ir_instr_find(self->_ops[op]->writes, self, &idx))
1025 vec_remove(self->_ops[op]->writes, idx, 1);
1026 else if (vec_ir_instr_find(self->_ops[op]->reads, self, &idx))
1027 vec_remove(self->_ops[op]->reads, idx, 1);
1031 vec_push(v->writes, self);
1033 vec_push(v->reads, self);
1039 /***********************************************************************
1043 static void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
1045 self->code.globaladdr = gaddr;
1046 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
1047 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
1048 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
1051 static int32_t ir_value_code_addr(const ir_value *self)
1053 if (self->store == store_return)
1054 return OFS_RETURN + self->code.addroffset;
1055 return self->code.globaladdr + self->code.addroffset;
1058 ir_value* ir_value_var(const char *name, int storetype, int vtype)
1061 self = (ir_value*)mem_a(sizeof(*self));
1062 self->vtype = vtype;
1063 self->fieldtype = TYPE_VOID;
1064 self->outtype = TYPE_VOID;
1065 self->store = storetype;
1069 self->writes = NULL;
1071 self->cvq = CV_NONE;
1072 self->hasvalue = false;
1073 self->context.file = "<@no context>";
1074 self->context.line = 0;
1076 if (name && !ir_value_set_name(self, name)) {
1077 irerror(self->context, "out of memory");
1082 memset(&self->constval, 0, sizeof(self->constval));
1083 memset(&self->code, 0, sizeof(self->code));
1085 self->members[0] = NULL;
1086 self->members[1] = NULL;
1087 self->members[2] = NULL;
1088 self->memberof = NULL;
1090 self->unique_life = false;
1091 self->locked = false;
1092 self->callparam = false;
1098 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
1106 if (self->members[member])
1107 return self->members[member];
1110 len = strlen(self->name);
1111 name = (char*)mem_a(len + 3);
1112 memcpy(name, self->name, len);
1114 name[len+1] = 'x' + member;
1120 if (self->vtype == TYPE_VECTOR)
1122 m = ir_value_var(name, self->store, TYPE_FLOAT);
1127 m->context = self->context;
1129 self->members[member] = m;
1130 m->code.addroffset = member;
1132 else if (self->vtype == TYPE_FIELD)
1134 if (self->fieldtype != TYPE_VECTOR)
1136 m = ir_value_var(name, self->store, TYPE_FIELD);
1141 m->fieldtype = TYPE_FLOAT;
1142 m->context = self->context;
1144 self->members[member] = m;
1145 m->code.addroffset = member;
1149 irerror(self->context, "invalid member access on %s", self->name);
1157 static GMQCC_INLINE size_t ir_value_sizeof(const ir_value *self)
1159 if (self->vtype == TYPE_FIELD && self->fieldtype == TYPE_VECTOR)
1160 return type_sizeof_[TYPE_VECTOR];
1161 return type_sizeof_[self->vtype];
1164 static ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
1166 ir_value *v = ir_value_var(name, storetype, vtype);
1169 ir_function_collect_value(owner, v);
1173 void ir_value_delete(ir_value* self)
1177 mem_d((void*)self->name);
1180 if (self->vtype == TYPE_STRING)
1181 mem_d((void*)self->constval.vstring);
1183 for (i = 0; i < 3; ++i) {
1184 if (self->members[i])
1185 ir_value_delete(self->members[i]);
1187 vec_free(self->reads);
1188 vec_free(self->writes);
1189 vec_free(self->life);
1193 bool ir_value_set_name(ir_value *self, const char *name)
1196 mem_d((void*)self->name);
1197 self->name = util_strdup(name);
1198 return !!self->name;
1201 bool ir_value_set_float(ir_value *self, float f)
1203 if (self->vtype != TYPE_FLOAT)
1205 self->constval.vfloat = f;
1206 self->hasvalue = true;
1210 bool ir_value_set_func(ir_value *self, int f)
1212 if (self->vtype != TYPE_FUNCTION)
1214 self->constval.vint = f;
1215 self->hasvalue = true;
1219 bool ir_value_set_vector(ir_value *self, vec3_t v)
1221 if (self->vtype != TYPE_VECTOR)
1223 self->constval.vvec = v;
1224 self->hasvalue = true;
1228 bool ir_value_set_field(ir_value *self, ir_value *fld)
1230 if (self->vtype != TYPE_FIELD)
1232 self->constval.vpointer = fld;
1233 self->hasvalue = true;
1237 bool ir_value_set_string(ir_value *self, const char *str)
1239 if (self->vtype != TYPE_STRING)
1241 self->constval.vstring = util_strdupe(str);
1242 self->hasvalue = true;
1247 bool ir_value_set_int(ir_value *self, int i)
1249 if (self->vtype != TYPE_INTEGER)
1251 self->constval.vint = i;
1252 self->hasvalue = true;
1257 bool ir_value_lives(ir_value *self, size_t at)
1260 for (i = 0; i < vec_size(self->life); ++i)
1262 ir_life_entry_t *life = &self->life[i];
1263 if (life->start <= at && at <= life->end)
1265 if (life->start > at) /* since it's ordered */
1271 static bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
1274 vec_push(self->life, e);
1275 for (k = vec_size(self->life)-1; k > idx; --k)
1276 self->life[k] = self->life[k-1];
1277 self->life[idx] = e;
1281 static bool ir_value_life_merge(ir_value *self, size_t s)
1284 const size_t vs = vec_size(self->life);
1285 ir_life_entry_t *life = NULL;
1286 ir_life_entry_t *before = NULL;
1287 ir_life_entry_t new_entry;
1289 /* Find the first range >= s */
1290 for (i = 0; i < vs; ++i)
1293 life = &self->life[i];
1294 if (life->start > s)
1297 /* nothing found? append */
1300 if (life && life->end+1 == s)
1302 /* previous life range can be merged in */
1306 if (life && life->end >= s)
1308 e.start = e.end = s;
1309 vec_push(self->life, e);
1315 if (before->end + 1 == s &&
1316 life->start - 1 == s)
1319 before->end = life->end;
1320 vec_remove(self->life, i, 1);
1323 if (before->end + 1 == s)
1329 /* already contained */
1330 if (before->end >= s)
1334 if (life->start - 1 == s)
1339 /* insert a new entry */
1340 new_entry.start = new_entry.end = s;
1341 return ir_value_life_insert(self, i, new_entry);
1344 static bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1348 if (!vec_size(other->life))
1351 if (!vec_size(self->life)) {
1352 size_t count = vec_size(other->life);
1353 ir_life_entry_t *life = vec_add(self->life, count);
1354 memcpy(life, other->life, count * sizeof(*life));
1359 for (i = 0; i < vec_size(other->life); ++i)
1361 const ir_life_entry_t *life = &other->life[i];
1364 ir_life_entry_t *entry = &self->life[myi];
1366 if (life->end+1 < entry->start)
1368 /* adding an interval before entry */
1369 if (!ir_value_life_insert(self, myi, *life))
1375 if (life->start < entry->start &&
1376 life->end+1 >= entry->start)
1378 /* starts earlier and overlaps */
1379 entry->start = life->start;
1382 if (life->end > entry->end &&
1383 life->start <= entry->end+1)
1385 /* ends later and overlaps */
1386 entry->end = life->end;
1389 /* see if our change combines it with the next ranges */
1390 while (myi+1 < vec_size(self->life) &&
1391 entry->end+1 >= self->life[1+myi].start)
1393 /* overlaps with (myi+1) */
1394 if (entry->end < self->life[1+myi].end)
1395 entry->end = self->life[1+myi].end;
1396 vec_remove(self->life, myi+1, 1);
1397 entry = &self->life[myi];
1400 /* see if we're after the entry */
1401 if (life->start > entry->end)
1404 /* append if we're at the end */
1405 if (myi >= vec_size(self->life)) {
1406 vec_push(self->life, *life);
1409 /* otherweise check the next range */
1418 static bool ir_values_overlap(const ir_value *a, const ir_value *b)
1420 /* For any life entry in A see if it overlaps with
1421 * any life entry in B.
1422 * Note that the life entries are orderes, so we can make a
1423 * more efficient algorithm there than naively translating the
1427 ir_life_entry_t *la, *lb, *enda, *endb;
1429 /* first of all, if either has no life range, they cannot clash */
1430 if (!vec_size(a->life) || !vec_size(b->life))
1435 enda = la + vec_size(a->life);
1436 endb = lb + vec_size(b->life);
1439 /* check if the entries overlap, for that,
1440 * both must start before the other one ends.
1442 if (la->start < lb->end &&
1443 lb->start < la->end)
1448 /* entries are ordered
1449 * one entry is earlier than the other
1450 * that earlier entry will be moved forward
1452 if (la->start < lb->start)
1454 /* order: A B, move A forward
1455 * check if we hit the end with A
1460 else /* if (lb->start < la->start) actually <= */
1462 /* order: B A, move B forward
1463 * check if we hit the end with B
1472 /***********************************************************************
1476 static bool ir_check_unreachable(ir_block *self)
1478 /* The IR should never have to deal with unreachable code */
1479 if (!self->final/* || OPTS_FLAG(ALLOW_UNREACHABLE_CODE)*/)
1481 irerror(self->context, "unreachable statement (%s)", self->label);
1485 bool ir_block_create_store_op(ir_block *self, lex_ctx_t ctx, int op, ir_value *target, ir_value *what)
1488 if (!ir_check_unreachable(self))
1491 if (target->store == store_value &&
1492 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1494 irerror(self->context, "cannot store to an SSA value");
1495 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1496 irerror(self->context, "instruction: %s", util_instr_str[op]);
1500 in = ir_instr_new(ctx, self, op);
1504 if (!ir_instr_op(in, 0, target, (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC)) ||
1505 !ir_instr_op(in, 1, what, false))
1507 ir_instr_delete(in);
1510 vec_push(self->instr, in);
1514 static bool ir_block_create_store(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1518 if (target->vtype == TYPE_VARIANT)
1519 vtype = what->vtype;
1521 vtype = target->vtype;
1524 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1525 op = INSTR_CONV_ITOF;
1526 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1527 op = INSTR_CONV_FTOI;
1529 op = type_store_instr[vtype];
1531 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1532 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1536 return ir_block_create_store_op(self, ctx, op, target, what);
1539 bool ir_block_create_storep(ir_block *self, lex_ctx_t ctx, ir_value *target, ir_value *what)
1544 if (target->vtype != TYPE_POINTER)
1547 /* storing using pointer - target is a pointer, type must be
1548 * inferred from source
1550 vtype = what->vtype;
1552 op = type_storep_instr[vtype];
1553 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1554 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1555 op = INSTR_STOREP_V;
1558 return ir_block_create_store_op(self, ctx, op, target, what);
1561 bool ir_block_create_return(ir_block *self, lex_ctx_t ctx, ir_value *v)
1564 if (!ir_check_unreachable(self))
1567 self->is_return = true;
1568 in = ir_instr_new(ctx, self, INSTR_RETURN);
1572 if (v && !ir_instr_op(in, 0, v, false)) {
1573 ir_instr_delete(in);
1577 vec_push(self->instr, in);
1581 bool ir_block_create_if(ir_block *self, lex_ctx_t ctx, ir_value *v,
1582 ir_block *ontrue, ir_block *onfalse)
1585 if (!ir_check_unreachable(self))
1588 /*in = ir_instr_new(ctx, self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1589 in = ir_instr_new(ctx, self, VINSTR_COND);
1593 if (!ir_instr_op(in, 0, v, false)) {
1594 ir_instr_delete(in);
1598 in->bops[0] = ontrue;
1599 in->bops[1] = onfalse;
1601 vec_push(self->instr, in);
1603 vec_push(self->exits, ontrue);
1604 vec_push(self->exits, onfalse);
1605 vec_push(ontrue->entries, self);
1606 vec_push(onfalse->entries, self);
1610 bool ir_block_create_jump(ir_block *self, lex_ctx_t ctx, ir_block *to)
1613 if (!ir_check_unreachable(self))
1616 in = ir_instr_new(ctx, self, VINSTR_JUMP);
1621 vec_push(self->instr, in);
1623 vec_push(self->exits, to);
1624 vec_push(to->entries, self);
1628 bool ir_block_create_goto(ir_block *self, lex_ctx_t ctx, ir_block *to)
1630 self->owner->flags |= IR_FLAG_HAS_GOTO;
1631 return ir_block_create_jump(self, ctx, to);
1634 ir_instr* ir_block_create_phi(ir_block *self, lex_ctx_t ctx, const char *label, int ot)
1638 if (!ir_check_unreachable(self))
1640 in = ir_instr_new(ctx, self, VINSTR_PHI);
1643 out = ir_value_out(self->owner, label, store_value, ot);
1645 ir_instr_delete(in);
1648 if (!ir_instr_op(in, 0, out, true)) {
1649 ir_instr_delete(in);
1650 ir_value_delete(out);
1653 vec_push(self->instr, in);
1657 ir_value* ir_phi_value(ir_instr *self)
1659 return self->_ops[0];
1662 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1666 if (!vec_ir_block_find(self->owner->entries, b, NULL)) {
1667 /* Must not be possible to cause this, otherwise the AST
1668 * is doing something wrong.
1670 irerror(self->context, "Invalid entry block for PHI");
1676 vec_push(v->reads, self);
1677 vec_push(self->phi, pe);
1680 /* call related code */
1681 ir_instr* ir_block_create_call(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *func, bool noreturn)
1685 if (!ir_check_unreachable(self))
1687 in = ir_instr_new(ctx, self, (noreturn ? VINSTR_NRCALL : INSTR_CALL0));
1692 self->is_return = true;
1694 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1696 ir_instr_delete(in);
1699 if (!ir_instr_op(in, 0, out, true) ||
1700 !ir_instr_op(in, 1, func, false))
1702 ir_instr_delete(in);
1703 ir_value_delete(out);
1706 vec_push(self->instr, in);
1709 if (!ir_block_create_return(self, ctx, NULL)) {
1710 compile_error(ctx, "internal error: failed to generate dummy-return instruction");
1711 ir_instr_delete(in);
1719 ir_value* ir_call_value(ir_instr *self)
1721 return self->_ops[0];
1724 void ir_call_param(ir_instr* self, ir_value *v)
1726 vec_push(self->params, v);
1727 vec_push(v->reads, self);
1730 /* binary op related code */
1732 ir_value* ir_block_create_binop(ir_block *self, lex_ctx_t ctx,
1733 const char *label, int opcode,
1734 ir_value *left, ir_value *right)
1756 case INSTR_SUB_S: /* -- offset of string as float */
1761 case INSTR_BITOR_IF:
1762 case INSTR_BITOR_FI:
1763 case INSTR_BITAND_FI:
1764 case INSTR_BITAND_IF:
1779 case INSTR_BITAND_I:
1782 case INSTR_RSHIFT_I:
1783 case INSTR_LSHIFT_I:
1804 * after the following default case, the value of opcode can never
1805 * be 1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65
1809 /* boolean operations result in floats */
1812 * opcode >= 10 takes true branch opcode is at least 10
1813 * opcode <= 23 takes false branch opcode is at least 24
1815 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1819 * At condition "opcode <= 23", the value of "opcode" must be
1821 * At condition "opcode <= 23", the value of "opcode" cannot be
1822 * equal to any of {1, 2, 3, 4, 5, 6, 7, 8, 9, 62, 63, 64, 65}.
1823 * The condition "opcode <= 23" cannot be true.
1825 * Thus ot=2 (TYPE_FLOAT) can never be true
1828 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1830 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1835 if (ot == TYPE_VOID) {
1836 /* The AST or parser were supposed to check this! */
1840 return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1843 ir_value* ir_block_create_unary(ir_block *self, lex_ctx_t ctx,
1844 const char *label, int opcode,
1847 int ot = TYPE_FLOAT;
1859 /* QC doesn't have other unary operations. We expect extensions to fill
1860 * the above list, otherwise we assume out-type = in-type, eg for an
1864 ot = operand->vtype;
1867 if (ot == TYPE_VOID) {
1868 /* The AST or parser were supposed to check this! */
1872 /* let's use the general instruction creator and pass NULL for OPB */
1873 return ir_block_create_general_instr(self, ctx, label, opcode, operand, NULL, ot);
1876 static ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx_t ctx, const char *label,
1877 int op, ir_value *a, ir_value *b, int outype)
1882 out = ir_value_out(self->owner, label, store_value, outype);
1886 instr = ir_instr_new(ctx, self, op);
1888 ir_value_delete(out);
1892 if (!ir_instr_op(instr, 0, out, true) ||
1893 !ir_instr_op(instr, 1, a, false) ||
1894 !ir_instr_op(instr, 2, b, false) )
1899 vec_push(self->instr, instr);
1903 ir_instr_delete(instr);
1904 ir_value_delete(out);
1908 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx_t ctx, const char *label, ir_value *ent, ir_value *field)
1912 /* Support for various pointer types todo if so desired */
1913 if (ent->vtype != TYPE_ENTITY)
1916 if (field->vtype != TYPE_FIELD)
1919 v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1920 v->fieldtype = field->fieldtype;
1924 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)
1927 if (ent->vtype != TYPE_ENTITY)
1930 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1931 if (field->vtype != TYPE_FIELD)
1936 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1937 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1938 case TYPE_STRING: op = INSTR_LOAD_S; break;
1939 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1940 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1941 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1943 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1944 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1947 irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1951 return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
1954 /* PHI resolving breaks the SSA, and must thus be the last
1955 * step before life-range calculation.
1958 static bool ir_block_naive_phi(ir_block *self);
1959 bool ir_function_naive_phi(ir_function *self)
1963 for (i = 0; i < vec_size(self->blocks); ++i)
1965 if (!ir_block_naive_phi(self->blocks[i]))
1971 static bool ir_block_naive_phi(ir_block *self)
1973 size_t i, p; /*, w;*/
1974 /* FIXME: optionally, create_phi can add the phis
1975 * to a list so we don't need to loop through blocks
1976 * - anyway: "don't optimize YET"
1978 for (i = 0; i < vec_size(self->instr); ++i)
1980 ir_instr *instr = self->instr[i];
1981 if (instr->opcode != VINSTR_PHI)
1984 vec_remove(self->instr, i, 1);
1985 --i; /* NOTE: i+1 below */
1987 for (p = 0; p < vec_size(instr->phi); ++p)
1989 ir_value *v = instr->phi[p].value;
1990 ir_block *b = instr->phi[p].from;
1992 if (v->store == store_value &&
1993 vec_size(v->reads) == 1 &&
1994 vec_size(v->writes) == 1)
1996 /* replace the value */
1997 if (!ir_instr_op(v->writes[0], 0, instr->_ops[0], true))
2002 /* force a move instruction */
2003 ir_instr *prevjump = vec_last(b->instr);
2006 instr->_ops[0]->store = store_global;
2007 if (!ir_block_create_store(b, instr->context, instr->_ops[0], v))
2009 instr->_ops[0]->store = store_value;
2010 vec_push(b->instr, prevjump);
2014 ir_instr_delete(instr);
2019 /***********************************************************************
2020 *IR Temp allocation code
2021 * Propagating value life ranges by walking through the function backwards
2022 * until no more changes are made.
2023 * In theory this should happen once more than once for every nested loop
2025 * Though this implementation might run an additional time for if nests.
2028 /* Enumerate instructions used by value's life-ranges
2030 static void ir_block_enumerate(ir_block *self, size_t *_eid)
2034 for (i = 0; i < vec_size(self->instr); ++i)
2036 self->instr[i]->eid = eid++;
2041 /* Enumerate blocks and instructions.
2042 * The block-enumeration is unordered!
2043 * We do not really use the block enumreation, however
2044 * the instruction enumeration is important for life-ranges.
2046 void ir_function_enumerate(ir_function *self)
2049 size_t instruction_id = 0;
2050 for (i = 0; i < vec_size(self->blocks); ++i)
2052 /* each block now gets an additional "entry" instruction id
2053 * we can use to avoid point-life issues
2055 self->blocks[i]->entry_id = instruction_id;
2058 self->blocks[i]->eid = i;
2059 ir_block_enumerate(self->blocks[i], &instruction_id);
2063 /* Local-value allocator
2064 * After finishing creating the liferange of all values used in a function
2065 * we can allocate their global-positions.
2066 * This is the counterpart to register-allocation in register machines.
2073 } function_allocator;
2075 static bool function_allocator_alloc(function_allocator *alloc, ir_value *var)
2078 size_t vsize = ir_value_sizeof(var);
2080 var->code.local = vec_size(alloc->locals);
2082 slot = ir_value_var("reg", store_global, var->vtype);
2086 if (!ir_value_life_merge_into(slot, var))
2089 vec_push(alloc->locals, slot);
2090 vec_push(alloc->sizes, vsize);
2091 vec_push(alloc->unique, var->unique_life);
2096 ir_value_delete(slot);
2100 static bool ir_function_allocator_assign(ir_function *self, function_allocator *alloc, ir_value *v)
2106 return function_allocator_alloc(alloc, v);
2108 for (a = 0; a < vec_size(alloc->locals); ++a)
2110 /* if it's reserved for a unique liferange: skip */
2111 if (alloc->unique[a])
2114 slot = alloc->locals[a];
2116 /* never resize parameters
2117 * will be required later when overlapping temps + locals
2119 if (a < vec_size(self->params) &&
2120 alloc->sizes[a] < ir_value_sizeof(v))
2125 if (ir_values_overlap(v, slot))
2128 if (!ir_value_life_merge_into(slot, v))
2131 /* adjust size for this slot */
2132 if (alloc->sizes[a] < ir_value_sizeof(v))
2133 alloc->sizes[a] = ir_value_sizeof(v);
2138 if (a >= vec_size(alloc->locals)) {
2139 if (!function_allocator_alloc(alloc, v))
2145 bool ir_function_allocate_locals(ir_function *self)
2150 bool opt_gt = OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS);
2154 function_allocator lockalloc, globalloc;
2156 if (!vec_size(self->locals) && !vec_size(self->values))
2159 globalloc.locals = NULL;
2160 globalloc.sizes = NULL;
2161 globalloc.positions = NULL;
2162 globalloc.unique = NULL;
2163 lockalloc.locals = NULL;
2164 lockalloc.sizes = NULL;
2165 lockalloc.positions = NULL;
2166 lockalloc.unique = NULL;
2168 for (i = 0; i < vec_size(self->locals); ++i)
2170 v = self->locals[i];
2171 if ((self->flags & IR_FLAG_MASK_NO_LOCAL_TEMPS) || !OPTS_OPTIMIZATION(OPTIM_LOCAL_TEMPS)) {
2173 v->unique_life = true;
2175 else if (i >= vec_size(self->params))
2178 v->locked = true; /* lock parameters locals */
2179 if (!function_allocator_alloc((v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2182 for (; i < vec_size(self->locals); ++i)
2184 v = self->locals[i];
2185 if (!vec_size(v->life))
2187 if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2191 /* Allocate a slot for any value that still exists */
2192 for (i = 0; i < vec_size(self->values); ++i)
2194 v = self->values[i];
2196 if (!vec_size(v->life))
2199 /* CALL optimization:
2200 * If the value is a parameter-temp: 1 write, 1 read from a CALL
2201 * and it's not "locked", write it to the OFS_PARM directly.
2203 if (OPTS_OPTIMIZATION(OPTIM_CALL_STORES) && !v->locked && !v->unique_life) {
2204 if (vec_size(v->reads) == 1 && vec_size(v->writes) == 1 &&
2205 (v->reads[0]->opcode == VINSTR_NRCALL ||
2206 (v->reads[0]->opcode >= INSTR_CALL0 && v->reads[0]->opcode <= INSTR_CALL8)
2211 ir_instr *call = v->reads[0];
2212 if (!vec_ir_value_find(call->params, v, ¶m)) {
2213 irerror(call->context, "internal error: unlocked parameter %s not found", v->name);
2216 ++opts_optimizationcount[OPTIM_CALL_STORES];
2217 v->callparam = true;
2219 ir_value_code_setaddr(v, OFS_PARM0 + 3*param);
2221 size_t nprotos = vec_size(self->owner->extparam_protos);
2224 if (nprotos > param)
2225 ep = self->owner->extparam_protos[param];
2228 ep = ir_gen_extparam_proto(self->owner);
2229 while (++nprotos <= param)
2230 ep = ir_gen_extparam_proto(self->owner);
2232 ir_instr_op(v->writes[0], 0, ep, true);
2233 call->params[param+8] = ep;
2237 if (vec_size(v->writes) == 1 && v->writes[0]->opcode == INSTR_CALL0)
2239 v->store = store_return;
2240 if (v->members[0]) v->members[0]->store = store_return;
2241 if (v->members[1]) v->members[1]->store = store_return;
2242 if (v->members[2]) v->members[2]->store = store_return;
2243 ++opts_optimizationcount[OPTIM_CALL_STORES];
2248 if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2252 if (!lockalloc.sizes && !globalloc.sizes) {
2255 vec_push(lockalloc.positions, 0);
2256 vec_push(globalloc.positions, 0);
2258 /* Adjust slot positions based on sizes */
2259 if (lockalloc.sizes) {
2260 pos = (vec_size(lockalloc.sizes) ? lockalloc.positions[0] : 0);
2261 for (i = 1; i < vec_size(lockalloc.sizes); ++i)
2263 pos = lockalloc.positions[i-1] + lockalloc.sizes[i-1];
2264 vec_push(lockalloc.positions, pos);
2266 self->allocated_locals = pos + vec_last(lockalloc.sizes);
2268 if (globalloc.sizes) {
2269 pos = (vec_size(globalloc.sizes) ? globalloc.positions[0] : 0);
2270 for (i = 1; i < vec_size(globalloc.sizes); ++i)
2272 pos = globalloc.positions[i-1] + globalloc.sizes[i-1];
2273 vec_push(globalloc.positions, pos);
2275 self->globaltemps = pos + vec_last(globalloc.sizes);
2278 /* Locals need to know their new position */
2279 for (i = 0; i < vec_size(self->locals); ++i) {
2280 v = self->locals[i];
2281 if (v->locked || !opt_gt)
2282 v->code.local = lockalloc.positions[v->code.local];
2284 v->code.local = globalloc.positions[v->code.local];
2286 /* Take over the actual slot positions on values */
2287 for (i = 0; i < vec_size(self->values); ++i) {
2288 v = self->values[i];
2289 if (v->locked || !opt_gt)
2290 v->code.local = lockalloc.positions[v->code.local];
2292 v->code.local = globalloc.positions[v->code.local];
2300 for (i = 0; i < vec_size(lockalloc.locals); ++i)
2301 ir_value_delete(lockalloc.locals[i]);
2302 for (i = 0; i < vec_size(globalloc.locals); ++i)
2303 ir_value_delete(globalloc.locals[i]);
2304 vec_free(globalloc.unique);
2305 vec_free(globalloc.locals);
2306 vec_free(globalloc.sizes);
2307 vec_free(globalloc.positions);
2308 vec_free(lockalloc.unique);
2309 vec_free(lockalloc.locals);
2310 vec_free(lockalloc.sizes);
2311 vec_free(lockalloc.positions);
2315 /* Get information about which operand
2316 * is read from, or written to.
2318 static void ir_op_read_write(int op, size_t *read, size_t *write)
2338 case INSTR_STOREP_F:
2339 case INSTR_STOREP_V:
2340 case INSTR_STOREP_S:
2341 case INSTR_STOREP_ENT:
2342 case INSTR_STOREP_FLD:
2343 case INSTR_STOREP_FNC:
2354 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2357 const size_t vs = vec_size(self->living);
2358 bool changed = false;
2359 for (i = 0; i != vs; ++i)
2361 if (ir_value_life_merge(self->living[i], eid))
2367 static bool ir_block_living_lock(ir_block *self)
2370 bool changed = false;
2371 for (i = 0; i != vec_size(self->living); ++i)
2373 if (!self->living[i]->locked) {
2374 self->living[i]->locked = true;
2381 static bool ir_block_life_propagate(ir_block *self, bool *changed)
2385 size_t i, o, p, mem, cnt;
2386 /* bitmasks which operands are read from or written to */
2393 vec_free(self->living);
2395 p = vec_size(self->exits);
2396 for (i = 0; i < p; ++i) {
2397 ir_block *prev = self->exits[i];
2398 cnt = vec_size(prev->living);
2399 for (o = 0; o < cnt; ++o) {
2400 if (!vec_ir_value_find(self->living, prev->living[o], NULL))
2401 vec_push(self->living, prev->living[o]);
2405 i = vec_size(self->instr);
2408 instr = self->instr[i];
2410 /* See which operands are read and write operands */
2411 ir_op_read_write(instr->opcode, &read, &write);
2413 /* Go through the 3 main operands
2414 * writes first, then reads
2416 for (o = 0; o < 3; ++o)
2418 if (!instr->_ops[o]) /* no such operand */
2421 value = instr->_ops[o];
2423 /* We only care about locals */
2424 /* we also calculate parameter liferanges so that locals
2425 * can take up parameter slots */
2426 if (value->store != store_value &&
2427 value->store != store_local &&
2428 value->store != store_param)
2431 /* write operands */
2432 /* When we write to a local, we consider it "dead" for the
2433 * remaining upper part of the function, since in SSA a value
2434 * can only be written once (== created)
2439 bool in_living = vec_ir_value_find(self->living, value, &idx);
2442 /* If the value isn't alive it hasn't been read before... */
2443 /* TODO: See if the warning can be emitted during parsing or AST processing
2444 * otherwise have warning printed here.
2445 * IF printing a warning here: include filecontext_t,
2446 * and make sure it's only printed once
2447 * since this function is run multiple times.
2449 /* con_err( "Value only written %s\n", value->name); */
2450 if (ir_value_life_merge(value, instr->eid))
2453 /* since 'living' won't contain it
2454 * anymore, merge the value, since
2457 if (ir_value_life_merge(value, instr->eid))
2460 vec_remove(self->living, idx, 1);
2462 /* Removing a vector removes all members */
2463 for (mem = 0; mem < 3; ++mem) {
2464 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], &idx)) {
2465 if (ir_value_life_merge(value->members[mem], instr->eid))
2467 vec_remove(self->living, idx, 1);
2470 /* Removing the last member removes the vector */
2471 if (value->memberof) {
2472 value = value->memberof;
2473 for (mem = 0; mem < 3; ++mem) {
2474 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], NULL))
2477 if (mem == 3 && vec_ir_value_find(self->living, value, &idx)) {
2478 if (ir_value_life_merge(value, instr->eid))
2480 vec_remove(self->living, idx, 1);
2486 if (instr->opcode == INSTR_MUL_VF)
2488 value = instr->_ops[2];
2489 /* the float source will get an additional lifetime */
2490 if (ir_value_life_merge(value, instr->eid+1))
2492 if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2495 else if (instr->opcode == INSTR_MUL_FV || instr->opcode == INSTR_LOAD_V)
2497 value = instr->_ops[1];
2498 /* the float source will get an additional lifetime */
2499 if (ir_value_life_merge(value, instr->eid+1))
2501 if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2505 for (o = 0; o < 3; ++o)
2507 if (!instr->_ops[o]) /* no such operand */
2510 value = instr->_ops[o];
2512 /* We only care about locals */
2513 /* we also calculate parameter liferanges so that locals
2514 * can take up parameter slots */
2515 if (value->store != store_value &&
2516 value->store != store_local &&
2517 value->store != store_param)
2523 if (!vec_ir_value_find(self->living, value, NULL))
2524 vec_push(self->living, value);
2525 /* reading adds the full vector */
2526 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2527 vec_push(self->living, value->memberof);
2528 for (mem = 0; mem < 3; ++mem) {
2529 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2530 vec_push(self->living, value->members[mem]);
2534 /* PHI operands are always read operands */
2535 for (p = 0; p < vec_size(instr->phi); ++p)
2537 value = instr->phi[p].value;
2538 if (!vec_ir_value_find(self->living, value, NULL))
2539 vec_push(self->living, value);
2540 /* reading adds the full vector */
2541 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2542 vec_push(self->living, value->memberof);
2543 for (mem = 0; mem < 3; ++mem) {
2544 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2545 vec_push(self->living, value->members[mem]);
2549 /* on a call, all these values must be "locked" */
2550 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2551 if (ir_block_living_lock(self))
2554 /* call params are read operands too */
2555 for (p = 0; p < vec_size(instr->params); ++p)
2557 value = instr->params[p];
2558 if (!vec_ir_value_find(self->living, value, NULL))
2559 vec_push(self->living, value);
2560 /* reading adds the full vector */
2561 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2562 vec_push(self->living, value->memberof);
2563 for (mem = 0; mem < 3; ++mem) {
2564 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2565 vec_push(self->living, value->members[mem]);
2570 if (ir_block_living_add_instr(self, instr->eid))
2573 /* the "entry" instruction ID */
2574 if (ir_block_living_add_instr(self, self->entry_id))
2580 bool ir_function_calculate_liferanges(ir_function *self)
2585 /* parameters live at 0 */
2586 for (i = 0; i < vec_size(self->params); ++i)
2587 if (!ir_value_life_merge(self->locals[i], 0))
2588 compile_error(self->context, "internal error: failed value-life merging");
2593 i = vec_size(self->blocks);
2595 ir_block_life_propagate(self->blocks[i], &changed);
2599 if (vec_size(self->blocks)) {
2600 ir_block *block = self->blocks[0];
2601 for (i = 0; i < vec_size(block->living); ++i) {
2602 ir_value *v = block->living[i];
2603 if (v->store != store_local)
2605 if (v->vtype == TYPE_VECTOR)
2607 self->flags |= IR_FLAG_HAS_UNINITIALIZED;
2608 /* find the instruction reading from it */
2609 for (s = 0; s < vec_size(v->reads); ++s) {
2610 if (v->reads[s]->eid == v->life[0].end)
2613 if (s < vec_size(v->reads)) {
2614 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2615 "variable `%s` may be used uninitialized in this function\n"
2618 v->reads[s]->context.file, v->reads[s]->context.line)
2626 ir_value *vec = v->memberof;
2627 for (s = 0; s < vec_size(vec->reads); ++s) {
2628 if (vec->reads[s]->eid == v->life[0].end)
2631 if (s < vec_size(vec->reads)) {
2632 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2633 "variable `%s` may be used uninitialized in this function\n"
2636 vec->reads[s]->context.file, vec->reads[s]->context.line)
2644 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2645 "variable `%s` may be used uninitialized in this function", v->name))
2654 /***********************************************************************
2657 * Since the IR has the convention of putting 'write' operands
2658 * at the beginning, we have to rotate the operands of instructions
2659 * properly in order to generate valid QCVM code.
2661 * Having destinations at a fixed position is more convenient. In QC
2662 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2663 * read from from OPA, and store to OPB rather than OPC. Which is
2664 * partially the reason why the implementation of these instructions
2665 * in darkplaces has been delayed for so long.
2667 * Breaking conventions is annoying...
2669 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2671 static bool gen_global_field(code_t *code, ir_value *global)
2673 if (global->hasvalue)
2675 ir_value *fld = global->constval.vpointer;
2677 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2681 /* copy the field's value */
2682 ir_value_code_setaddr(global, vec_size(code->globals));
2683 vec_push(code->globals, fld->code.fieldaddr);
2684 if (global->fieldtype == TYPE_VECTOR) {
2685 vec_push(code->globals, fld->code.fieldaddr+1);
2686 vec_push(code->globals, fld->code.fieldaddr+2);
2691 ir_value_code_setaddr(global, vec_size(code->globals));
2692 vec_push(code->globals, 0);
2693 if (global->fieldtype == TYPE_VECTOR) {
2694 vec_push(code->globals, 0);
2695 vec_push(code->globals, 0);
2698 if (global->code.globaladdr < 0)
2703 static bool gen_global_pointer(code_t *code, ir_value *global)
2705 if (global->hasvalue)
2707 ir_value *target = global->constval.vpointer;
2709 irerror(global->context, "Invalid pointer constant: %s", global->name);
2710 /* NULL pointers are pointing to the NULL constant, which also
2711 * sits at address 0, but still has an ir_value for itself.
2716 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2717 * void() foo; <- proto
2718 * void() *fooptr = &foo;
2719 * void() foo = { code }
2721 if (!target->code.globaladdr) {
2722 /* FIXME: Check for the constant nullptr ir_value!
2723 * because then code.globaladdr being 0 is valid.
2725 irerror(global->context, "FIXME: Relocation support");
2729 ir_value_code_setaddr(global, vec_size(code->globals));
2730 vec_push(code->globals, target->code.globaladdr);
2734 ir_value_code_setaddr(global, vec_size(code->globals));
2735 vec_push(code->globals, 0);
2737 if (global->code.globaladdr < 0)
2742 static bool gen_blocks_recursive(code_t *code, ir_function *func, ir_block *block)
2744 prog_section_statement_t stmt;
2752 block->generated = true;
2753 block->code_start = vec_size(code->statements);
2754 for (i = 0; i < vec_size(block->instr); ++i)
2756 instr = block->instr[i];
2758 if (instr->opcode == VINSTR_PHI) {
2759 irerror(block->context, "cannot generate virtual instruction (phi)");
2763 if (instr->opcode == VINSTR_JUMP) {
2764 target = instr->bops[0];
2765 /* for uncoditional jumps, if the target hasn't been generated
2766 * yet, we generate them right here.
2768 if (!target->generated)
2769 return gen_blocks_recursive(code, func, target);
2771 /* otherwise we generate a jump instruction */
2772 stmt.opcode = INSTR_GOTO;
2773 stmt.o1.s1 = (target->code_start) - vec_size(code->statements);
2776 if (stmt.o1.s1 != 1)
2777 code_push_statement(code, &stmt, instr->context.line);
2779 /* no further instructions can be in this block */
2783 if (instr->opcode == VINSTR_COND) {
2784 ontrue = instr->bops[0];
2785 onfalse = instr->bops[1];
2786 /* TODO: have the AST signal which block should
2787 * come first: eg. optimize IFs without ELSE...
2790 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2794 if (ontrue->generated) {
2795 stmt.opcode = INSTR_IF;
2796 stmt.o2.s1 = (ontrue->code_start) - vec_size(code->statements);
2797 if (stmt.o2.s1 != 1)
2798 code_push_statement(code, &stmt, instr->context.line);
2800 if (onfalse->generated) {
2801 stmt.opcode = INSTR_IFNOT;
2802 stmt.o2.s1 = (onfalse->code_start) - vec_size(code->statements);
2803 if (stmt.o2.s1 != 1)
2804 code_push_statement(code, &stmt, instr->context.line);
2806 if (!ontrue->generated) {
2807 if (onfalse->generated)
2808 return gen_blocks_recursive(code, func, ontrue);
2810 if (!onfalse->generated) {
2811 if (ontrue->generated)
2812 return gen_blocks_recursive(code, func, onfalse);
2814 /* neither ontrue nor onfalse exist */
2815 stmt.opcode = INSTR_IFNOT;
2816 if (!instr->likely) {
2817 /* Honor the likelyhood hint */
2818 ir_block *tmp = onfalse;
2819 stmt.opcode = INSTR_IF;
2823 stidx = vec_size(code->statements);
2824 code_push_statement(code, &stmt, instr->context.line);
2825 /* on false we jump, so add ontrue-path */
2826 if (!gen_blocks_recursive(code, func, ontrue))
2828 /* fixup the jump address */
2829 code->statements[stidx].o2.s1 = vec_size(code->statements) - stidx;
2830 /* generate onfalse path */
2831 if (onfalse->generated) {
2832 /* fixup the jump address */
2833 code->statements[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2834 if (stidx+2 == vec_size(code->statements) && code->statements[stidx].o2.s1 == 1) {
2835 code->statements[stidx] = code->statements[stidx+1];
2836 if (code->statements[stidx].o1.s1 < 0)
2837 code->statements[stidx].o1.s1++;
2838 code_pop_statement(code);
2840 stmt.opcode = vec_last(code->statements).opcode;
2841 if (stmt.opcode == INSTR_GOTO ||
2842 stmt.opcode == INSTR_IF ||
2843 stmt.opcode == INSTR_IFNOT ||
2844 stmt.opcode == INSTR_RETURN ||
2845 stmt.opcode == INSTR_DONE)
2847 /* no use jumping from here */
2850 /* may have been generated in the previous recursive call */
2851 stmt.opcode = INSTR_GOTO;
2852 stmt.o1.s1 = (onfalse->code_start) - vec_size(code->statements);
2855 if (stmt.o1.s1 != 1)
2856 code_push_statement(code, &stmt, instr->context.line);
2859 else if (stidx+2 == vec_size(code->statements) && code->statements[stidx].o2.s1 == 1) {
2860 code->statements[stidx] = code->statements[stidx+1];
2861 if (code->statements[stidx].o1.s1 < 0)
2862 code->statements[stidx].o1.s1++;
2863 code_pop_statement(code);
2865 /* if not, generate now */
2866 return gen_blocks_recursive(code, func, onfalse);
2869 if ( (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8)
2870 || instr->opcode == VINSTR_NRCALL)
2875 first = vec_size(instr->params);
2878 for (p = 0; p < first; ++p)
2880 ir_value *param = instr->params[p];
2881 if (param->callparam)
2884 stmt.opcode = INSTR_STORE_F;
2887 if (param->vtype == TYPE_FIELD)
2888 stmt.opcode = field_store_instr[param->fieldtype];
2889 else if (param->vtype == TYPE_NIL)
2890 stmt.opcode = INSTR_STORE_V;
2892 stmt.opcode = type_store_instr[param->vtype];
2893 stmt.o1.u1 = ir_value_code_addr(param);
2894 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2895 code_push_statement(code, &stmt, instr->context.line);
2897 /* Now handle extparams */
2898 first = vec_size(instr->params);
2899 for (; p < first; ++p)
2901 ir_builder *ir = func->owner;
2902 ir_value *param = instr->params[p];
2903 ir_value *targetparam;
2905 if (param->callparam)
2908 if (p-8 >= vec_size(ir->extparams))
2909 ir_gen_extparam(ir);
2911 targetparam = ir->extparams[p-8];
2913 stmt.opcode = INSTR_STORE_F;
2916 if (param->vtype == TYPE_FIELD)
2917 stmt.opcode = field_store_instr[param->fieldtype];
2918 else if (param->vtype == TYPE_NIL)
2919 stmt.opcode = INSTR_STORE_V;
2921 stmt.opcode = type_store_instr[param->vtype];
2922 stmt.o1.u1 = ir_value_code_addr(param);
2923 stmt.o2.u1 = ir_value_code_addr(targetparam);
2924 code_push_statement(code, &stmt, instr->context.line);
2927 stmt.opcode = INSTR_CALL0 + vec_size(instr->params);
2928 if (stmt.opcode > INSTR_CALL8)
2929 stmt.opcode = INSTR_CALL8;
2930 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2933 code_push_statement(code, &stmt, instr->context.line);
2935 retvalue = instr->_ops[0];
2936 if (retvalue && retvalue->store != store_return &&
2937 (retvalue->store == store_global || vec_size(retvalue->life)))
2939 /* not to be kept in OFS_RETURN */
2940 if (retvalue->vtype == TYPE_FIELD && OPTS_FLAG(ADJUST_VECTOR_FIELDS))
2941 stmt.opcode = field_store_instr[retvalue->fieldtype];
2943 stmt.opcode = type_store_instr[retvalue->vtype];
2944 stmt.o1.u1 = OFS_RETURN;
2945 stmt.o2.u1 = ir_value_code_addr(retvalue);
2947 code_push_statement(code, &stmt, instr->context.line);
2952 if (instr->opcode == INSTR_STATE) {
2953 irerror(block->context, "TODO: state instruction");
2957 stmt.opcode = instr->opcode;
2962 /* This is the general order of operands */
2964 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2967 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2970 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2972 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2974 stmt.o1.u1 = stmt.o3.u1;
2977 else if ((stmt.opcode >= INSTR_STORE_F &&
2978 stmt.opcode <= INSTR_STORE_FNC) ||
2979 (stmt.opcode >= INSTR_STOREP_F &&
2980 stmt.opcode <= INSTR_STOREP_FNC))
2982 /* 2-operand instructions with A -> B */
2983 stmt.o2.u1 = stmt.o3.u1;
2986 /* tiny optimization, don't output
2989 if (stmt.o2.u1 == stmt.o1.u1 &&
2990 OPTS_OPTIMIZATION(OPTIM_PEEPHOLE))
2992 ++opts_optimizationcount[OPTIM_PEEPHOLE];
2997 code_push_statement(code, &stmt, instr->context.line);
3002 static bool gen_function_code(code_t *code, ir_function *self)
3005 prog_section_statement_t stmt, *retst;
3007 /* Starting from entry point, we generate blocks "as they come"
3008 * for now. Dead blocks will not be translated obviously.
3010 if (!vec_size(self->blocks)) {
3011 irerror(self->context, "Function '%s' declared without body.", self->name);
3015 block = self->blocks[0];
3016 if (block->generated)
3019 if (!gen_blocks_recursive(code, self, block)) {
3020 irerror(self->context, "failed to generate blocks for '%s'", self->name);
3024 /* code_write and qcvm -disasm need to know that the function ends here */
3025 retst = &vec_last(code->statements);
3026 if (OPTS_OPTIMIZATION(OPTIM_VOID_RETURN) &&
3027 self->outtype == TYPE_VOID &&
3028 retst->opcode == INSTR_RETURN &&
3029 !retst->o1.u1 && !retst->o2.u1 && !retst->o3.u1)
3031 retst->opcode = INSTR_DONE;
3032 ++opts_optimizationcount[OPTIM_VOID_RETURN];
3034 stmt.opcode = INSTR_DONE;
3038 code_push_statement(code, &stmt, vec_last(code->linenums));
3043 static qcint_t ir_builder_filestring(ir_builder *ir, const char *filename)
3045 /* NOTE: filename pointers are copied, we never strdup them,
3046 * thus we can use pointer-comparison to find the string.
3051 for (i = 0; i < vec_size(ir->filenames); ++i) {
3052 if (ir->filenames[i] == filename)
3053 return ir->filestrings[i];
3056 str = code_genstring(ir->code, filename);
3057 vec_push(ir->filenames, filename);
3058 vec_push(ir->filestrings, str);
3062 static bool gen_global_function(ir_builder *ir, ir_value *global)
3064 prog_section_function_t fun;
3069 if (!global->hasvalue || (!global->constval.vfunc))
3071 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
3075 irfun = global->constval.vfunc;
3077 fun.name = global->code.name;
3078 fun.file = ir_builder_filestring(ir, global->context.file);
3079 fun.profile = 0; /* always 0 */
3080 fun.nargs = vec_size(irfun->params);
3084 for (i = 0;i < 8; ++i) {
3085 if ((int32_t)i >= fun.nargs)
3088 fun.argsize[i] = type_sizeof_[irfun->params[i]];
3092 fun.locals = irfun->allocated_locals;
3095 fun.entry = irfun->builtin+1;
3097 irfun->code_function_def = vec_size(ir->code->functions);
3098 fun.entry = vec_size(ir->code->statements);
3101 vec_push(ir->code->functions, fun);
3105 static ir_value* ir_gen_extparam_proto(ir_builder *ir)
3110 util_snprintf(name, sizeof(name), "EXTPARM#%i", (int)(vec_size(ir->extparam_protos)));
3111 global = ir_value_var(name, store_global, TYPE_VECTOR);
3113 vec_push(ir->extparam_protos, global);
3117 static void ir_gen_extparam(ir_builder *ir)
3119 prog_section_def_t def;
3122 if (vec_size(ir->extparam_protos) < vec_size(ir->extparams)+1)
3123 global = ir_gen_extparam_proto(ir);
3125 global = ir->extparam_protos[vec_size(ir->extparams)];
3127 def.name = code_genstring(ir->code, global->name);
3128 def.type = TYPE_VECTOR;
3129 def.offset = vec_size(ir->code->globals);
3131 vec_push(ir->code->defs, def);
3133 ir_value_code_setaddr(global, def.offset);
3135 vec_push(ir->code->globals, 0);
3136 vec_push(ir->code->globals, 0);
3137 vec_push(ir->code->globals, 0);
3139 vec_push(ir->extparams, global);
3142 static bool gen_function_extparam_copy(code_t *code, ir_function *self)
3144 size_t i, ext, numparams;
3146 ir_builder *ir = self->owner;
3148 prog_section_statement_t stmt;
3150 numparams = vec_size(self->params);
3154 stmt.opcode = INSTR_STORE_F;
3156 for (i = 8; i < numparams; ++i) {
3158 if (ext >= vec_size(ir->extparams))
3159 ir_gen_extparam(ir);
3161 ep = ir->extparams[ext];
3163 stmt.opcode = type_store_instr[self->locals[i]->vtype];
3164 if (self->locals[i]->vtype == TYPE_FIELD &&
3165 self->locals[i]->fieldtype == TYPE_VECTOR)
3167 stmt.opcode = INSTR_STORE_V;
3169 stmt.o1.u1 = ir_value_code_addr(ep);
3170 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3171 code_push_statement(code, &stmt, self->context.line);
3177 static bool gen_function_varargs_copy(code_t *code, ir_function *self)
3179 size_t i, ext, numparams, maxparams;
3181 ir_builder *ir = self->owner;
3183 prog_section_statement_t stmt;
3185 numparams = vec_size(self->params);
3189 stmt.opcode = INSTR_STORE_V;
3191 maxparams = numparams + self->max_varargs;
3192 for (i = numparams; i < maxparams; ++i) {
3194 stmt.o1.u1 = OFS_PARM0 + 3*i;
3195 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3196 code_push_statement(code, &stmt, self->context.line);
3200 while (ext >= vec_size(ir->extparams))
3201 ir_gen_extparam(ir);
3203 ep = ir->extparams[ext];
3205 stmt.o1.u1 = ir_value_code_addr(ep);
3206 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3207 code_push_statement(code, &stmt, self->context.line);
3213 static bool gen_function_locals(ir_builder *ir, ir_value *global)
3215 prog_section_function_t *def;
3218 uint32_t firstlocal, firstglobal;
3220 irfun = global->constval.vfunc;
3221 def = ir->code->functions + irfun->code_function_def;
3223 if (OPTS_OPTION_BOOL(OPTION_G) ||
3224 !OPTS_OPTIMIZATION(OPTIM_OVERLAP_LOCALS) ||
3225 (irfun->flags & IR_FLAG_MASK_NO_OVERLAP))
3227 firstlocal = def->firstlocal = vec_size(ir->code->globals);
3229 firstlocal = def->firstlocal = ir->first_common_local;
3230 ++opts_optimizationcount[OPTIM_OVERLAP_LOCALS];
3233 firstglobal = (OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS) ? ir->first_common_globaltemp : firstlocal);
3235 for (i = vec_size(ir->code->globals); i < firstlocal + irfun->allocated_locals; ++i)
3236 vec_push(ir->code->globals, 0);
3237 for (i = 0; i < vec_size(irfun->locals); ++i) {
3238 ir_value *v = irfun->locals[i];
3239 if (v->locked || !OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS)) {
3240 ir_value_code_setaddr(v, firstlocal + v->code.local);
3241 if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
3242 irerror(irfun->locals[i]->context, "failed to generate local %s", irfun->locals[i]->name);
3247 ir_value_code_setaddr(v, firstglobal + v->code.local);
3249 for (i = 0; i < vec_size(irfun->values); ++i)
3251 ir_value *v = irfun->values[i];
3255 ir_value_code_setaddr(v, firstlocal + v->code.local);
3257 ir_value_code_setaddr(v, firstglobal + v->code.local);
3262 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
3264 prog_section_function_t *fundef;
3269 irfun = global->constval.vfunc;
3271 if (global->cvq == CV_NONE) {
3272 irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
3273 "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
3275 /* this was a function pointer, don't generate code for those */
3282 if (irfun->code_function_def < 0) {
3283 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
3286 fundef = &ir->code->functions[irfun->code_function_def];
3288 fundef->entry = vec_size(ir->code->statements);
3289 if (!gen_function_locals(ir, global)) {
3290 irerror(irfun->context, "Failed to generate locals for function %s", irfun->name);
3293 if (!gen_function_extparam_copy(ir->code, irfun)) {
3294 irerror(irfun->context, "Failed to generate extparam-copy code for function %s", irfun->name);
3297 if (irfun->max_varargs && !gen_function_varargs_copy(ir->code, irfun)) {
3298 irerror(irfun->context, "Failed to generate vararg-copy code for function %s", irfun->name);
3301 if (!gen_function_code(ir->code, irfun)) {
3302 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
3308 static void gen_vector_defs(code_t *code, prog_section_def_t def, const char *name)
3313 if (!name || name[0] == '#' || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3316 def.type = TYPE_FLOAT;
3320 component = (char*)mem_a(len+3);
3321 memcpy(component, name, len);
3323 component[len-0] = 0;
3324 component[len-2] = '_';
3326 component[len-1] = 'x';
3328 for (i = 0; i < 3; ++i) {
3329 def.name = code_genstring(code, component);
3330 vec_push(code->defs, def);
3338 static void gen_vector_fields(code_t *code, prog_section_field_t fld, const char *name)
3343 if (!name || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3346 fld.type = TYPE_FLOAT;
3350 component = (char*)mem_a(len+3);
3351 memcpy(component, name, len);
3353 component[len-0] = 0;
3354 component[len-2] = '_';
3356 component[len-1] = 'x';
3358 for (i = 0; i < 3; ++i) {
3359 fld.name = code_genstring(code, component);
3360 vec_push(code->fields, fld);
3368 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
3372 prog_section_def_t def;
3373 bool pushdef = opts.optimizeoff;
3375 def.type = global->vtype;
3376 def.offset = vec_size(self->code->globals);
3378 if (OPTS_OPTION_BOOL(OPTION_G) || !islocal)
3382 if (OPTS_OPTIMIZATION(OPTIM_STRIP_CONSTANT_NAMES) &&
3383 !(global->flags & IR_FLAG_INCLUDE_DEF) &&
3384 (global->name[0] == '#' || global->cvq == CV_CONST))
3389 if (pushdef && global->name) {
3390 if (global->name[0] == '#') {
3391 if (!self->str_immediate)
3392 self->str_immediate = code_genstring(self->code, "IMMEDIATE");
3393 def.name = global->code.name = self->str_immediate;
3396 def.name = global->code.name = code_genstring(self->code, global->name);
3401 def.offset = ir_value_code_addr(global);
3402 vec_push(self->code->defs, def);
3403 if (global->vtype == TYPE_VECTOR)
3404 gen_vector_defs(self->code, def, global->name);
3405 else if (global->vtype == TYPE_FIELD && global->fieldtype == TYPE_VECTOR)
3406 gen_vector_defs(self->code, def, global->name);
3413 switch (global->vtype)
3416 if (!strcmp(global->name, "end_sys_globals")) {
3417 /* TODO: remember this point... all the defs before this one
3418 * should be checksummed and added to progdefs.h when we generate it.
3421 else if (!strcmp(global->name, "end_sys_fields")) {
3422 /* TODO: same as above but for entity-fields rather than globsl
3426 irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3428 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3429 * the system fields actually go? Though the engine knows this anyway...
3430 * Maybe this could be an -foption
3431 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3433 ir_value_code_setaddr(global, vec_size(self->code->globals));
3434 vec_push(self->code->globals, 0);
3436 if (pushdef) vec_push(self->code->defs, def);
3439 if (pushdef) vec_push(self->code->defs, def);
3440 return gen_global_pointer(self->code, global);
3443 vec_push(self->code->defs, def);
3444 if (global->fieldtype == TYPE_VECTOR)
3445 gen_vector_defs(self->code, def, global->name);
3447 return gen_global_field(self->code, global);
3452 ir_value_code_setaddr(global, vec_size(self->code->globals));
3453 if (global->hasvalue) {
3454 iptr = (int32_t*)&global->constval.ivec[0];
3455 vec_push(self->code->globals, *iptr);
3457 vec_push(self->code->globals, 0);
3459 if (!islocal && global->cvq != CV_CONST)
3460 def.type |= DEF_SAVEGLOBAL;
3461 if (pushdef) vec_push(self->code->defs, def);
3463 return global->code.globaladdr >= 0;
3467 ir_value_code_setaddr(global, vec_size(self->code->globals));
3468 if (global->hasvalue) {
3469 uint32_t load = code_genstring(self->code, global->constval.vstring);
3470 vec_push(self->code->globals, load);
3472 vec_push(self->code->globals, 0);
3474 if (!islocal && global->cvq != CV_CONST)
3475 def.type |= DEF_SAVEGLOBAL;
3476 if (pushdef) vec_push(self->code->defs, def);
3477 return global->code.globaladdr >= 0;
3482 ir_value_code_setaddr(global, vec_size(self->code->globals));
3483 if (global->hasvalue) {
3484 iptr = (int32_t*)&global->constval.ivec[0];
3485 vec_push(self->code->globals, iptr[0]);
3486 if (global->code.globaladdr < 0)
3488 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3489 vec_push(self->code->globals, iptr[d]);
3492 vec_push(self->code->globals, 0);
3493 if (global->code.globaladdr < 0)
3495 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3496 vec_push(self->code->globals, 0);
3499 if (!islocal && global->cvq != CV_CONST)
3500 def.type |= DEF_SAVEGLOBAL;
3503 vec_push(self->code->defs, def);
3504 def.type &= ~DEF_SAVEGLOBAL;
3505 gen_vector_defs(self->code, def, global->name);
3507 return global->code.globaladdr >= 0;
3510 ir_value_code_setaddr(global, vec_size(self->code->globals));
3511 if (!global->hasvalue) {
3512 vec_push(self->code->globals, 0);
3513 if (global->code.globaladdr < 0)
3516 vec_push(self->code->globals, vec_size(self->code->functions));
3517 if (!gen_global_function(self, global))
3520 if (!islocal && global->cvq != CV_CONST)
3521 def.type |= DEF_SAVEGLOBAL;
3522 if (pushdef) vec_push(self->code->defs, def);
3525 /* assume biggest type */
3526 ir_value_code_setaddr(global, vec_size(self->code->globals));
3527 vec_push(self->code->globals, 0);
3528 for (i = 1; i < type_sizeof_[TYPE_VARIANT]; ++i)
3529 vec_push(self->code->globals, 0);
3532 /* refuse to create 'void' type or any other fancy business. */
3533 irerror(global->context, "Invalid type for global variable `%s`: %s",
3534 global->name, type_name[global->vtype]);
3539 static GMQCC_INLINE void ir_builder_prepare_field(code_t *code, ir_value *field)
3541 field->code.fieldaddr = code_alloc_field(code, type_sizeof_[field->fieldtype]);
3544 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3546 prog_section_def_t def;
3547 prog_section_field_t fld;
3551 def.type = (uint16_t)field->vtype;
3552 def.offset = (uint16_t)vec_size(self->code->globals);
3554 /* create a global named the same as the field */
3555 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
3556 /* in our standard, the global gets a dot prefix */
3557 size_t len = strlen(field->name);
3560 /* we really don't want to have to allocate this, and 1024
3561 * bytes is more than enough for a variable/field name
3563 if (len+2 >= sizeof(name)) {
3564 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
3569 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
3572 def.name = code_genstring(self->code, name);
3573 fld.name = def.name + 1; /* we reuse that string table entry */
3575 /* in plain QC, there cannot be a global with the same name,
3576 * and so we also name the global the same.
3577 * FIXME: fteqcc should create a global as well
3578 * check if it actually uses the same name. Probably does
3580 def.name = code_genstring(self->code, field->name);
3581 fld.name = def.name;
3584 field->code.name = def.name;
3586 vec_push(self->code->defs, def);
3588 fld.type = field->fieldtype;
3590 if (fld.type == TYPE_VOID) {
3591 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
3595 fld.offset = field->code.fieldaddr;
3597 vec_push(self->code->fields, fld);
3599 ir_value_code_setaddr(field, vec_size(self->code->globals));
3600 vec_push(self->code->globals, fld.offset);
3601 if (fld.type == TYPE_VECTOR) {
3602 vec_push(self->code->globals, fld.offset+1);
3603 vec_push(self->code->globals, fld.offset+2);
3606 if (field->fieldtype == TYPE_VECTOR) {
3607 gen_vector_defs (self->code, def, field->name);
3608 gen_vector_fields(self->code, fld, field->name);
3611 return field->code.globaladdr >= 0;
3614 bool ir_builder_generate(ir_builder *self, const char *filename)
3616 prog_section_statement_t stmt;
3618 char *lnofile = NULL;
3620 for (i = 0; i < vec_size(self->fields); ++i)
3622 ir_builder_prepare_field(self->code, self->fields[i]);
3625 for (i = 0; i < vec_size(self->globals); ++i)
3627 if (!ir_builder_gen_global(self, self->globals[i], false)) {
3630 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3631 ir_function *func = self->globals[i]->constval.vfunc;
3632 if (func && self->max_locals < func->allocated_locals &&
3633 !(func->flags & IR_FLAG_MASK_NO_OVERLAP))
3635 self->max_locals = func->allocated_locals;
3637 if (func && self->max_globaltemps < func->globaltemps)
3638 self->max_globaltemps = func->globaltemps;
3642 for (i = 0; i < vec_size(self->fields); ++i)
3644 if (!ir_builder_gen_field(self, self->fields[i])) {
3650 ir_value_code_setaddr(self->nil, vec_size(self->code->globals));
3651 vec_push(self->code->globals, 0);
3652 vec_push(self->code->globals, 0);
3653 vec_push(self->code->globals, 0);
3655 /* generate global temps */
3656 self->first_common_globaltemp = vec_size(self->code->globals);
3657 for (i = 0; i < self->max_globaltemps; ++i) {
3658 vec_push(self->code->globals, 0);
3660 /* generate common locals */
3661 self->first_common_local = vec_size(self->code->globals);
3662 for (i = 0; i < self->max_locals; ++i) {
3663 vec_push(self->code->globals, 0);
3666 /* generate function code */
3667 for (i = 0; i < vec_size(self->globals); ++i)
3669 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3670 if (!gen_global_function_code(self, self->globals[i])) {
3676 if (vec_size(self->code->globals) >= 65536) {
3677 irerror(vec_last(self->globals)->context, "This progs file would require more globals than the metadata can handle. Bailing out.");
3681 /* DP errors if the last instruction is not an INSTR_DONE. */
3682 if (vec_last(self->code->statements).opcode != INSTR_DONE)
3684 stmt.opcode = INSTR_DONE;
3688 code_push_statement(self->code, &stmt, vec_last(self->code->linenums));
3691 if (OPTS_OPTION_BOOL(OPTION_PP_ONLY))
3694 if (vec_size(self->code->statements) != vec_size(self->code->linenums)) {
3695 con_err("Linecounter wrong: %lu != %lu\n",
3696 (unsigned long)vec_size(self->code->statements),
3697 (unsigned long)vec_size(self->code->linenums));
3698 } else if (OPTS_FLAG(LNO)) {
3700 size_t filelen = strlen(filename);
3702 memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
3703 dot = strrchr(lnofile, '.');
3707 vec_shrinkto(lnofile, dot - lnofile);
3709 memcpy(vec_add(lnofile, 5), ".lno", 5);
3712 if (!code_write(self->code, filename, lnofile)) {
3721 /***********************************************************************
3722 *IR DEBUG Dump functions...
3725 #define IND_BUFSZ 1024
3728 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
3731 static const char *qc_opname(int op)
3733 if (op < 0) return "<INVALID>";
3734 if (op < VINSTR_END)
3735 return util_instr_str[op];
3737 case VINSTR_END: return "END";
3738 case VINSTR_PHI: return "PHI";
3739 case VINSTR_JUMP: return "JUMP";
3740 case VINSTR_COND: return "COND";
3741 default: return "<UNK>";
3745 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
3748 char indent[IND_BUFSZ];
3752 oprintf("module %s\n", b->name);
3753 for (i = 0; i < vec_size(b->globals); ++i)
3756 if (b->globals[i]->hasvalue)
3757 oprintf("%s = ", b->globals[i]->name);
3758 ir_value_dump(b->globals[i], oprintf);
3761 for (i = 0; i < vec_size(b->functions); ++i)
3762 ir_function_dump(b->functions[i], indent, oprintf);
3763 oprintf("endmodule %s\n", b->name);
3766 static const char *storenames[] = {
3767 "[global]", "[local]", "[param]", "[value]", "[return]"
3770 void ir_function_dump(ir_function *f, char *ind,
3771 int (*oprintf)(const char*, ...))
3774 if (f->builtin != 0) {
3775 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
3778 oprintf("%sfunction %s\n", ind, f->name);
3779 strncat(ind, "\t", IND_BUFSZ-1);
3780 if (vec_size(f->locals))
3782 oprintf("%s%i locals:\n", ind, (int)vec_size(f->locals));
3783 for (i = 0; i < vec_size(f->locals); ++i) {
3784 oprintf("%s\t", ind);
3785 ir_value_dump(f->locals[i], oprintf);
3789 oprintf("%sliferanges:\n", ind);
3790 for (i = 0; i < vec_size(f->locals); ++i) {
3791 const char *attr = "";
3793 ir_value *v = f->locals[i];
3794 if (v->unique_life && v->locked)
3795 attr = "unique,locked ";
3796 else if (v->unique_life)
3800 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
3801 storenames[v->store],
3802 attr, (v->callparam ? "callparam " : ""),
3803 (int)v->code.local);
3806 for (l = 0; l < vec_size(v->life); ++l) {
3807 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3810 for (m = 0; m < 3; ++m) {
3811 ir_value *vm = v->members[m];
3814 oprintf("%s\t%s: @%i ", ind, vm->name, (int)vm->code.local);
3815 for (l = 0; l < vec_size(vm->life); ++l) {
3816 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
3821 for (i = 0; i < vec_size(f->values); ++i) {
3822 const char *attr = "";
3824 ir_value *v = f->values[i];
3825 if (v->unique_life && v->locked)
3826 attr = "unique,locked ";
3827 else if (v->unique_life)
3831 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
3832 storenames[v->store],
3833 attr, (v->callparam ? "callparam " : ""),
3834 (int)v->code.local);
3837 for (l = 0; l < vec_size(v->life); ++l) {
3838 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3841 for (m = 0; m < 3; ++m) {
3842 ir_value *vm = v->members[m];
3845 if (vm->unique_life && vm->locked)
3846 attr = "unique,locked ";
3847 else if (vm->unique_life)
3849 else if (vm->locked)
3851 oprintf("%s\t%s: %s@%i ", ind, vm->name, attr, (int)vm->code.local);
3852 for (l = 0; l < vec_size(vm->life); ++l) {
3853 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
3858 if (vec_size(f->blocks))
3860 oprintf("%slife passes: %i\n", ind, (int)f->run_id);
3861 for (i = 0; i < vec_size(f->blocks); ++i) {
3862 ir_block_dump(f->blocks[i], ind, oprintf);
3866 ind[strlen(ind)-1] = 0;
3867 oprintf("%sendfunction %s\n", ind, f->name);
3870 void ir_block_dump(ir_block* b, char *ind,
3871 int (*oprintf)(const char*, ...))
3874 oprintf("%s:%s\n", ind, b->label);
3875 strncat(ind, "\t", IND_BUFSZ-1);
3877 if (b->instr && b->instr[0])
3878 oprintf("%s (%i) [entry]\n", ind, (int)(b->instr[0]->eid-1));
3879 for (i = 0; i < vec_size(b->instr); ++i)
3880 ir_instr_dump(b->instr[i], ind, oprintf);
3881 ind[strlen(ind)-1] = 0;
3884 static void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
3887 oprintf("%s <- phi ", in->_ops[0]->name);
3888 for (i = 0; i < vec_size(in->phi); ++i)
3890 oprintf("([%s] : %s) ", in->phi[i].from->label,
3891 in->phi[i].value->name);
3896 void ir_instr_dump(ir_instr *in, char *ind,
3897 int (*oprintf)(const char*, ...))
3900 const char *comma = NULL;
3902 oprintf("%s (%i) ", ind, (int)in->eid);
3904 if (in->opcode == VINSTR_PHI) {
3905 dump_phi(in, oprintf);
3909 strncat(ind, "\t", IND_BUFSZ-1);
3911 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3912 ir_value_dump(in->_ops[0], oprintf);
3913 if (in->_ops[1] || in->_ops[2])
3916 if (in->opcode == INSTR_CALL0 || in->opcode == VINSTR_NRCALL) {
3917 oprintf("CALL%i\t", vec_size(in->params));
3919 oprintf("%s\t", qc_opname(in->opcode));
3921 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3922 ir_value_dump(in->_ops[0], oprintf);
3927 for (i = 1; i != 3; ++i) {
3931 ir_value_dump(in->_ops[i], oprintf);
3939 oprintf("[%s]", in->bops[0]->label);
3943 oprintf("%s[%s]", comma, in->bops[1]->label);
3944 if (vec_size(in->params)) {
3945 oprintf("\tparams: ");
3946 for (i = 0; i != vec_size(in->params); ++i) {
3947 oprintf("%s, ", in->params[i]->name);
3951 ind[strlen(ind)-1] = 0;
3954 static void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
3957 for (; *str; ++str) {
3959 case '\n': oprintf("\\n"); break;
3960 case '\r': oprintf("\\r"); break;
3961 case '\t': oprintf("\\t"); break;
3962 case '\v': oprintf("\\v"); break;
3963 case '\f': oprintf("\\f"); break;
3964 case '\b': oprintf("\\b"); break;
3965 case '\a': oprintf("\\a"); break;
3966 case '\\': oprintf("\\\\"); break;
3967 case '"': oprintf("\\\""); break;
3968 default: oprintf("%c", *str); break;
3974 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3983 oprintf("fn:%s", v->name);
3986 oprintf("%g", v->constval.vfloat);
3989 oprintf("'%g %g %g'",
3992 v->constval.vvec.z);
3995 oprintf("(entity)");
3998 ir_value_dump_string(v->constval.vstring, oprintf);
4002 oprintf("%i", v->constval.vint);
4007 v->constval.vpointer->name);
4011 oprintf("%s", v->name);
4015 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
4018 oprintf("Life of %12s:", self->name);
4019 for (i = 0; i < vec_size(self->life); ++i)
4021 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);