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 (code_t *, 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, 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, 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 ctx, const char *msg, ...)
247 con_cvprintmsg((void*)&ctx, LVL_ERROR, "internal error", msg, ap);
251 static bool irwarning(lex_ctx 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;
352 void ir_builder_delete(ir_builder* self)
355 util_htdel(self->htglobals);
356 util_htdel(self->htfields);
357 util_htdel(self->htfunctions);
358 mem_d((void*)self->name);
359 for (i = 0; i != vec_size(self->functions); ++i) {
360 ir_function_delete_quick(self->functions[i]);
362 vec_free(self->functions);
363 for (i = 0; i != vec_size(self->extparams); ++i) {
364 ir_value_delete(self->extparams[i]);
366 vec_free(self->extparams);
367 vec_free(self->extparam_protos);
368 for (i = 0; i != vec_size(self->globals); ++i) {
369 ir_value_delete(self->globals[i]);
371 vec_free(self->globals);
372 for (i = 0; i != vec_size(self->fields); ++i) {
373 ir_value_delete(self->fields[i]);
375 ir_value_delete(self->nil);
376 vec_free(self->fields);
377 vec_free(self->filenames);
378 vec_free(self->filestrings);
382 bool ir_builder_set_name(ir_builder *self, const char *name)
385 mem_d((void*)self->name);
386 self->name = util_strdup(name);
390 static ir_function* ir_builder_get_function(ir_builder *self, const char *name)
392 return (ir_function*)util_htget(self->htfunctions, name);
395 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
397 ir_function *fn = ir_builder_get_function(self, name);
402 fn = ir_function_new(self, outtype);
403 if (!ir_function_set_name(fn, name))
405 ir_function_delete(fn);
408 vec_push(self->functions, fn);
409 util_htset(self->htfunctions, name, fn);
411 fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
413 ir_function_delete(fn);
417 fn->value->hasvalue = true;
418 fn->value->outtype = outtype;
419 fn->value->constval.vfunc = fn;
420 fn->value->context = fn->context;
425 static ir_value* ir_builder_get_global(ir_builder *self, const char *name)
427 return (ir_value*)util_htget(self->htglobals, name);
430 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
434 if (name && name[0] != '#')
436 ve = ir_builder_get_global(self, name);
442 ve = ir_value_var(name, store_global, vtype);
443 vec_push(self->globals, ve);
444 util_htset(self->htglobals, name, ve);
448 ir_value* ir_builder_get_va_count(ir_builder *self)
450 if (self->reserved_va_count)
451 return self->reserved_va_count;
452 return (self->reserved_va_count = ir_builder_create_global(self, "reserved:va_count", TYPE_FLOAT));
455 static ir_value* ir_builder_get_field(ir_builder *self, const char *name)
457 return (ir_value*)util_htget(self->htfields, name);
461 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
463 ir_value *ve = ir_builder_get_field(self, name);
468 ve = ir_value_var(name, store_global, TYPE_FIELD);
469 ve->fieldtype = vtype;
470 vec_push(self->fields, ve);
471 util_htset(self->htfields, name, ve);
475 /***********************************************************************
479 static bool ir_function_naive_phi(ir_function*);
480 static void ir_function_enumerate(ir_function*);
481 static bool ir_function_calculate_liferanges(ir_function*);
482 static bool ir_function_allocate_locals(ir_function*);
484 ir_function* ir_function_new(ir_builder* owner, int outtype)
487 self = (ir_function*)mem_a(sizeof(*self));
492 memset(self, 0, sizeof(*self));
495 if (!ir_function_set_name(self, "<@unnamed>")) {
502 self->context.file = "<@no context>";
503 self->context.line = 0;
504 self->outtype = outtype;
513 self->max_varargs = 0;
515 self->code_function_def = -1;
516 self->allocated_locals = 0;
517 self->globaltemps = 0;
523 bool ir_function_set_name(ir_function *self, const char *name)
526 mem_d((void*)self->name);
527 self->name = util_strdup(name);
531 static void ir_function_delete_quick(ir_function *self)
534 mem_d((void*)self->name);
536 for (i = 0; i != vec_size(self->blocks); ++i)
537 ir_block_delete_quick(self->blocks[i]);
538 vec_free(self->blocks);
540 vec_free(self->params);
542 for (i = 0; i != vec_size(self->values); ++i)
543 ir_value_delete(self->values[i]);
544 vec_free(self->values);
546 for (i = 0; i != vec_size(self->locals); ++i)
547 ir_value_delete(self->locals[i]);
548 vec_free(self->locals);
550 /* self->value is deleted by the builder */
555 void ir_function_delete(ir_function *self)
558 mem_d((void*)self->name);
560 for (i = 0; i != vec_size(self->blocks); ++i)
561 ir_block_delete(self->blocks[i]);
562 vec_free(self->blocks);
564 vec_free(self->params);
566 for (i = 0; i != vec_size(self->values); ++i)
567 ir_value_delete(self->values[i]);
568 vec_free(self->values);
570 for (i = 0; i != vec_size(self->locals); ++i)
571 ir_value_delete(self->locals[i]);
572 vec_free(self->locals);
574 /* self->value is deleted by the builder */
579 static void ir_function_collect_value(ir_function *self, ir_value *v)
581 vec_push(self->values, v);
584 ir_block* ir_function_create_block(lex_ctx ctx, ir_function *self, const char *label)
586 ir_block* bn = ir_block_new(self, label);
588 vec_push(self->blocks, bn);
592 static bool instr_is_operation(uint16_t op)
594 return ( (op >= INSTR_MUL_F && op <= INSTR_GT) ||
595 (op >= INSTR_LOAD_F && op <= INSTR_LOAD_FNC) ||
596 (op == INSTR_ADDRESS) ||
597 (op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) ||
598 (op >= INSTR_AND && op <= INSTR_BITOR) ||
599 (op >= INSTR_CALL0 && op <= INSTR_CALL8) );
602 static bool ir_function_pass_peephole(ir_function *self)
606 for (b = 0; b < vec_size(self->blocks); ++b) {
608 ir_block *block = self->blocks[b];
610 for (i = 0; i < vec_size(block->instr); ++i) {
612 inst = block->instr[i];
615 (inst->opcode >= INSTR_STORE_F &&
616 inst->opcode <= INSTR_STORE_FNC))
624 oper = block->instr[i-1];
625 if (!instr_is_operation(oper->opcode))
628 if (OPTS_FLAG(LEGACY_VECTOR_MATHS)) {
629 if (oper->opcode == INSTR_MUL_VF && oper->_ops[2]->memberof == oper->_ops[1])
631 if (oper->opcode == INSTR_MUL_FV && oper->_ops[1]->memberof == oper->_ops[2])
635 value = oper->_ops[0];
637 /* only do it for SSA values */
638 if (value->store != store_value)
641 /* don't optimize out the temp if it's used later again */
642 if (vec_size(value->reads) != 1)
645 /* The very next store must use this value */
646 if (value->reads[0] != store)
649 /* And of course the store must _read_ from it, so it's in
651 if (store->_ops[1] != value)
654 ++opts_optimizationcount[OPTIM_PEEPHOLE];
655 (void)!ir_instr_op(oper, 0, store->_ops[0], true);
657 vec_remove(block->instr, i, 1);
658 ir_instr_delete(store);
660 else if (inst->opcode == VINSTR_COND)
662 /* COND on a value resulting from a NOT could
663 * remove the NOT and swap its operands
670 value = inst->_ops[0];
672 if (value->store != store_value ||
673 vec_size(value->reads) != 1 ||
674 value->reads[0] != inst)
679 inot = value->writes[0];
680 if (inot->_ops[0] != value ||
681 inot->opcode < INSTR_NOT_F ||
682 inot->opcode > INSTR_NOT_FNC ||
683 inot->opcode == INSTR_NOT_V || /* can't do these */
684 inot->opcode == INSTR_NOT_S)
690 ++opts_optimizationcount[OPTIM_PEEPHOLE];
692 (void)!ir_instr_op(inst, 0, inot->_ops[1], false);
695 for (inotid = 0; inotid < vec_size(tmp->instr); ++inotid) {
696 if (tmp->instr[inotid] == inot)
699 if (inotid >= vec_size(tmp->instr)) {
700 compile_error(inst->context, "sanity-check failed: failed to find instruction to optimize out");
703 vec_remove(tmp->instr, inotid, 1);
704 ir_instr_delete(inot);
705 /* swap ontrue/onfalse */
707 inst->bops[0] = inst->bops[1];
718 static bool ir_function_pass_tailrecursion(ir_function *self)
722 for (b = 0; b < vec_size(self->blocks); ++b) {
724 ir_instr *ret, *call, *store = NULL;
725 ir_block *block = self->blocks[b];
727 if (!block->final || vec_size(block->instr) < 2)
730 ret = block->instr[vec_size(block->instr)-1];
731 if (ret->opcode != INSTR_DONE && ret->opcode != INSTR_RETURN)
734 call = block->instr[vec_size(block->instr)-2];
735 if (call->opcode >= INSTR_STORE_F && call->opcode <= INSTR_STORE_FNC) {
736 /* account for the unoptimized
738 * STORE %return, %tmp
742 if (vec_size(block->instr) < 3)
746 call = block->instr[vec_size(block->instr)-3];
749 if (call->opcode < INSTR_CALL0 || call->opcode > INSTR_CALL8)
753 /* optimize out the STORE */
755 ret->_ops[0] == store->_ops[0] &&
756 store->_ops[1] == call->_ops[0])
758 ++opts_optimizationcount[OPTIM_PEEPHOLE];
759 call->_ops[0] = store->_ops[0];
760 vec_remove(block->instr, vec_size(block->instr) - 2, 1);
761 ir_instr_delete(store);
770 funcval = call->_ops[1];
773 if (funcval->vtype != TYPE_FUNCTION || funcval->constval.vfunc != self)
776 /* now we have a CALL and a RET, check if it's a tailcall */
777 if (ret->_ops[0] && call->_ops[0] != ret->_ops[0])
780 ++opts_optimizationcount[OPTIM_TAIL_RECURSION];
781 vec_shrinkby(block->instr, 2);
783 block->final = false; /* open it back up */
785 /* emite parameter-stores */
786 for (p = 0; p < vec_size(call->params); ++p) {
787 /* assert(call->params_count <= self->locals_count); */
788 if (!ir_block_create_store(block, call->context, self->locals[p], call->params[p])) {
789 irerror(call->context, "failed to create tailcall store instruction for parameter %i", (int)p);
793 if (!ir_block_create_jump(block, call->context, self->blocks[0])) {
794 irerror(call->context, "failed to create tailcall jump");
798 ir_instr_delete(call);
799 ir_instr_delete(ret);
805 bool ir_function_finalize(ir_function *self)
812 if (OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
813 if (!ir_function_pass_peephole(self)) {
814 irerror(self->context, "generic optimization pass broke something in `%s`", self->name);
819 if (OPTS_OPTIMIZATION(OPTIM_TAIL_RECURSION)) {
820 if (!ir_function_pass_tailrecursion(self)) {
821 irerror(self->context, "tail-recursion optimization pass broke something in `%s`", self->name);
826 if (!ir_function_naive_phi(self)) {
827 irerror(self->context, "internal error: ir_function_naive_phi failed");
831 for (i = 0; i < vec_size(self->locals); ++i) {
832 ir_value *v = self->locals[i];
833 if (v->vtype == TYPE_VECTOR ||
834 (v->vtype == TYPE_FIELD && v->outtype == TYPE_VECTOR))
836 ir_value_vector_member(v, 0);
837 ir_value_vector_member(v, 1);
838 ir_value_vector_member(v, 2);
841 for (i = 0; i < vec_size(self->values); ++i) {
842 ir_value *v = self->values[i];
843 if (v->vtype == TYPE_VECTOR ||
844 (v->vtype == TYPE_FIELD && v->outtype == TYPE_VECTOR))
846 ir_value_vector_member(v, 0);
847 ir_value_vector_member(v, 1);
848 ir_value_vector_member(v, 2);
852 ir_function_enumerate(self);
854 if (!ir_function_calculate_liferanges(self))
856 if (!ir_function_allocate_locals(self))
861 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
866 vec_size(self->locals) &&
867 self->locals[vec_size(self->locals)-1]->store != store_param) {
868 irerror(self->context, "cannot add parameters after adding locals");
872 ve = ir_value_var(name, (param ? store_param : store_local), vtype);
875 vec_push(self->locals, ve);
879 /***********************************************************************
883 ir_block* ir_block_new(ir_function* owner, const char *name)
886 self = (ir_block*)mem_a(sizeof(*self));
890 memset(self, 0, sizeof(*self));
893 if (name && !ir_block_set_label(self, name)) {
898 self->context.file = "<@no context>";
899 self->context.line = 0;
903 self->entries = NULL;
907 self->is_return = false;
911 self->generated = false;
916 static void ir_block_delete_quick(ir_block* self)
919 if (self->label) mem_d(self->label);
920 for (i = 0; i != vec_size(self->instr); ++i)
921 ir_instr_delete_quick(self->instr[i]);
922 vec_free(self->instr);
923 vec_free(self->entries);
924 vec_free(self->exits);
925 vec_free(self->living);
929 void ir_block_delete(ir_block* self)
932 if (self->label) mem_d(self->label);
933 for (i = 0; i != vec_size(self->instr); ++i)
934 ir_instr_delete(self->instr[i]);
935 vec_free(self->instr);
936 vec_free(self->entries);
937 vec_free(self->exits);
938 vec_free(self->living);
942 bool ir_block_set_label(ir_block *self, const char *name)
945 mem_d((void*)self->label);
946 self->label = util_strdup(name);
947 return !!self->label;
950 /***********************************************************************
954 static ir_instr* ir_instr_new(lex_ctx ctx, ir_block* owner, int op)
957 self = (ir_instr*)mem_a(sizeof(*self));
964 self->_ops[0] = NULL;
965 self->_ops[1] = NULL;
966 self->_ops[2] = NULL;
967 self->bops[0] = NULL;
968 self->bops[1] = NULL;
979 static void ir_instr_delete_quick(ir_instr *self)
982 vec_free(self->params);
986 static void ir_instr_delete(ir_instr *self)
989 /* The following calls can only delete from
990 * vectors, we still want to delete this instruction
991 * so ignore the return value. Since with the warn_unused_result attribute
992 * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
993 * I have to improvise here and use if(foo());
995 for (i = 0; i < vec_size(self->phi); ++i) {
997 if (vec_ir_instr_find(self->phi[i].value->writes, self, &idx))
998 vec_remove(self->phi[i].value->writes, idx, 1);
999 if (vec_ir_instr_find(self->phi[i].value->reads, self, &idx))
1000 vec_remove(self->phi[i].value->reads, idx, 1);
1002 vec_free(self->phi);
1003 for (i = 0; i < vec_size(self->params); ++i) {
1005 if (vec_ir_instr_find(self->params[i]->writes, self, &idx))
1006 vec_remove(self->params[i]->writes, idx, 1);
1007 if (vec_ir_instr_find(self->params[i]->reads, self, &idx))
1008 vec_remove(self->params[i]->reads, idx, 1);
1010 vec_free(self->params);
1011 (void)!ir_instr_op(self, 0, NULL, false);
1012 (void)!ir_instr_op(self, 1, NULL, false);
1013 (void)!ir_instr_op(self, 2, NULL, false);
1017 static bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
1019 if (self->_ops[op]) {
1021 if (writing && vec_ir_instr_find(self->_ops[op]->writes, self, &idx))
1022 vec_remove(self->_ops[op]->writes, idx, 1);
1023 else if (vec_ir_instr_find(self->_ops[op]->reads, self, &idx))
1024 vec_remove(self->_ops[op]->reads, idx, 1);
1028 vec_push(v->writes, self);
1030 vec_push(v->reads, self);
1036 /***********************************************************************
1040 static void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
1042 self->code.globaladdr = gaddr;
1043 if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
1044 if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
1045 if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
1048 static int32_t ir_value_code_addr(const ir_value *self)
1050 if (self->store == store_return)
1051 return OFS_RETURN + self->code.addroffset;
1052 return self->code.globaladdr + self->code.addroffset;
1055 ir_value* ir_value_var(const char *name, int storetype, int vtype)
1058 self = (ir_value*)mem_a(sizeof(*self));
1059 self->vtype = vtype;
1060 self->fieldtype = TYPE_VOID;
1061 self->outtype = TYPE_VOID;
1062 self->store = storetype;
1066 self->writes = NULL;
1068 self->cvq = CV_NONE;
1069 self->hasvalue = false;
1070 self->context.file = "<@no context>";
1071 self->context.line = 0;
1073 if (name && !ir_value_set_name(self, name)) {
1074 irerror(self->context, "out of memory");
1079 memset(&self->constval, 0, sizeof(self->constval));
1080 memset(&self->code, 0, sizeof(self->code));
1082 self->members[0] = NULL;
1083 self->members[1] = NULL;
1084 self->members[2] = NULL;
1085 self->memberof = NULL;
1087 self->unique_life = false;
1088 self->locked = false;
1089 self->callparam = false;
1095 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
1103 if (self->members[member])
1104 return self->members[member];
1107 len = strlen(self->name);
1108 name = (char*)mem_a(len + 3);
1109 memcpy(name, self->name, len);
1111 name[len+1] = 'x' + member;
1117 if (self->vtype == TYPE_VECTOR)
1119 m = ir_value_var(name, self->store, TYPE_FLOAT);
1124 m->context = self->context;
1126 self->members[member] = m;
1127 m->code.addroffset = member;
1129 else if (self->vtype == TYPE_FIELD)
1131 if (self->fieldtype != TYPE_VECTOR)
1133 m = ir_value_var(name, self->store, TYPE_FIELD);
1138 m->fieldtype = TYPE_FLOAT;
1139 m->context = self->context;
1141 self->members[member] = m;
1142 m->code.addroffset = member;
1146 irerror(self->context, "invalid member access on %s", self->name);
1154 static GMQCC_INLINE size_t ir_value_sizeof(const ir_value *self)
1156 if (self->vtype == TYPE_FIELD && self->fieldtype == TYPE_VECTOR)
1157 return type_sizeof_[TYPE_VECTOR];
1158 return type_sizeof_[self->vtype];
1161 static ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
1163 ir_value *v = ir_value_var(name, storetype, vtype);
1166 ir_function_collect_value(owner, v);
1170 void ir_value_delete(ir_value* self)
1174 mem_d((void*)self->name);
1177 if (self->vtype == TYPE_STRING)
1178 mem_d((void*)self->constval.vstring);
1180 for (i = 0; i < 3; ++i) {
1181 if (self->members[i])
1182 ir_value_delete(self->members[i]);
1184 vec_free(self->reads);
1185 vec_free(self->writes);
1186 vec_free(self->life);
1190 bool ir_value_set_name(ir_value *self, const char *name)
1193 mem_d((void*)self->name);
1194 self->name = util_strdup(name);
1195 return !!self->name;
1198 bool ir_value_set_float(ir_value *self, float f)
1200 if (self->vtype != TYPE_FLOAT)
1202 self->constval.vfloat = f;
1203 self->hasvalue = true;
1207 bool ir_value_set_func(ir_value *self, int f)
1209 if (self->vtype != TYPE_FUNCTION)
1211 self->constval.vint = f;
1212 self->hasvalue = true;
1216 bool ir_value_set_vector(ir_value *self, vector v)
1218 if (self->vtype != TYPE_VECTOR)
1220 self->constval.vvec = v;
1221 self->hasvalue = true;
1225 bool ir_value_set_field(ir_value *self, ir_value *fld)
1227 if (self->vtype != TYPE_FIELD)
1229 self->constval.vpointer = fld;
1230 self->hasvalue = true;
1234 bool ir_value_set_string(ir_value *self, const char *str)
1236 if (self->vtype != TYPE_STRING)
1238 self->constval.vstring = util_strdupe(str);
1239 self->hasvalue = true;
1244 bool ir_value_set_int(ir_value *self, int i)
1246 if (self->vtype != TYPE_INTEGER)
1248 self->constval.vint = i;
1249 self->hasvalue = true;
1254 bool ir_value_lives(ir_value *self, size_t at)
1257 for (i = 0; i < vec_size(self->life); ++i)
1259 ir_life_entry_t *life = &self->life[i];
1260 if (life->start <= at && at <= life->end)
1262 if (life->start > at) /* since it's ordered */
1268 static bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
1271 vec_push(self->life, e);
1272 for (k = vec_size(self->life)-1; k > idx; --k)
1273 self->life[k] = self->life[k-1];
1274 self->life[idx] = e;
1278 static bool ir_value_life_merge(ir_value *self, size_t s)
1281 const size_t vs = vec_size(self->life);
1282 ir_life_entry_t *life = NULL;
1283 ir_life_entry_t *before = NULL;
1284 ir_life_entry_t new_entry;
1286 /* Find the first range >= s */
1287 for (i = 0; i < vs; ++i)
1290 life = &self->life[i];
1291 if (life->start > s)
1294 /* nothing found? append */
1297 if (life && life->end+1 == s)
1299 /* previous life range can be merged in */
1303 if (life && life->end >= s)
1305 e.start = e.end = s;
1306 vec_push(self->life, e);
1312 if (before->end + 1 == s &&
1313 life->start - 1 == s)
1316 before->end = life->end;
1317 vec_remove(self->life, i, 1);
1320 if (before->end + 1 == s)
1326 /* already contained */
1327 if (before->end >= s)
1331 if (life->start - 1 == s)
1336 /* insert a new entry */
1337 new_entry.start = new_entry.end = s;
1338 return ir_value_life_insert(self, i, new_entry);
1341 static bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1345 if (!vec_size(other->life))
1348 if (!vec_size(self->life)) {
1349 size_t count = vec_size(other->life);
1350 ir_life_entry_t *life = vec_add(self->life, count);
1351 memcpy(life, other->life, count * sizeof(*life));
1356 for (i = 0; i < vec_size(other->life); ++i)
1358 const ir_life_entry_t *life = &other->life[i];
1361 ir_life_entry_t *entry = &self->life[myi];
1363 if (life->end+1 < entry->start)
1365 /* adding an interval before entry */
1366 if (!ir_value_life_insert(self, myi, *life))
1372 if (life->start < entry->start &&
1373 life->end+1 >= entry->start)
1375 /* starts earlier and overlaps */
1376 entry->start = life->start;
1379 if (life->end > entry->end &&
1380 life->start <= entry->end+1)
1382 /* ends later and overlaps */
1383 entry->end = life->end;
1386 /* see if our change combines it with the next ranges */
1387 while (myi+1 < vec_size(self->life) &&
1388 entry->end+1 >= self->life[1+myi].start)
1390 /* overlaps with (myi+1) */
1391 if (entry->end < self->life[1+myi].end)
1392 entry->end = self->life[1+myi].end;
1393 vec_remove(self->life, myi+1, 1);
1394 entry = &self->life[myi];
1397 /* see if we're after the entry */
1398 if (life->start > entry->end)
1401 /* append if we're at the end */
1402 if (myi >= vec_size(self->life)) {
1403 vec_push(self->life, *life);
1406 /* otherweise check the next range */
1415 static bool ir_values_overlap(const ir_value *a, const ir_value *b)
1417 /* For any life entry in A see if it overlaps with
1418 * any life entry in B.
1419 * Note that the life entries are orderes, so we can make a
1420 * more efficient algorithm there than naively translating the
1424 ir_life_entry_t *la, *lb, *enda, *endb;
1426 /* first of all, if either has no life range, they cannot clash */
1427 if (!vec_size(a->life) || !vec_size(b->life))
1432 enda = la + vec_size(a->life);
1433 endb = lb + vec_size(b->life);
1436 /* check if the entries overlap, for that,
1437 * both must start before the other one ends.
1439 if (la->start < lb->end &&
1440 lb->start < la->end)
1445 /* entries are ordered
1446 * one entry is earlier than the other
1447 * that earlier entry will be moved forward
1449 if (la->start < lb->start)
1451 /* order: A B, move A forward
1452 * check if we hit the end with A
1457 else /* if (lb->start < la->start) actually <= */
1459 /* order: B A, move B forward
1460 * check if we hit the end with B
1469 /***********************************************************************
1473 static bool ir_check_unreachable(ir_block *self)
1475 /* The IR should never have to deal with unreachable code */
1476 if (!self->final/* || OPTS_FLAG(ALLOW_UNREACHABLE_CODE)*/)
1478 irerror(self->context, "unreachable statement (%s)", self->label);
1482 bool ir_block_create_store_op(ir_block *self, lex_ctx ctx, int op, ir_value *target, ir_value *what)
1485 if (!ir_check_unreachable(self))
1488 if (target->store == store_value &&
1489 (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1491 irerror(self->context, "cannot store to an SSA value");
1492 irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1493 irerror(self->context, "instruction: %s", asm_instr[op].m);
1497 in = ir_instr_new(ctx, self, op);
1501 if (!ir_instr_op(in, 0, target, (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC)) ||
1502 !ir_instr_op(in, 1, what, false))
1504 ir_instr_delete(in);
1507 vec_push(self->instr, in);
1511 static bool ir_block_create_store(ir_block *self, lex_ctx ctx, ir_value *target, ir_value *what)
1515 if (target->vtype == TYPE_VARIANT)
1516 vtype = what->vtype;
1518 vtype = target->vtype;
1521 if (vtype == TYPE_FLOAT && what->vtype == TYPE_INTEGER)
1522 op = INSTR_CONV_ITOF;
1523 else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1524 op = INSTR_CONV_FTOI;
1526 op = type_store_instr[vtype];
1528 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1529 if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1533 return ir_block_create_store_op(self, ctx, op, target, what);
1536 bool ir_block_create_storep(ir_block *self, lex_ctx ctx, ir_value *target, ir_value *what)
1541 if (target->vtype != TYPE_POINTER)
1544 /* storing using pointer - target is a pointer, type must be
1545 * inferred from source
1547 vtype = what->vtype;
1549 op = type_storep_instr[vtype];
1550 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1551 if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1552 op = INSTR_STOREP_V;
1555 return ir_block_create_store_op(self, ctx, op, target, what);
1558 bool ir_block_create_return(ir_block *self, lex_ctx ctx, ir_value *v)
1561 if (!ir_check_unreachable(self))
1564 self->is_return = true;
1565 in = ir_instr_new(ctx, self, INSTR_RETURN);
1569 if (v && !ir_instr_op(in, 0, v, false)) {
1570 ir_instr_delete(in);
1574 vec_push(self->instr, in);
1578 bool ir_block_create_if(ir_block *self, lex_ctx ctx, ir_value *v,
1579 ir_block *ontrue, ir_block *onfalse)
1582 if (!ir_check_unreachable(self))
1585 /*in = ir_instr_new(ctx, self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1586 in = ir_instr_new(ctx, self, VINSTR_COND);
1590 if (!ir_instr_op(in, 0, v, false)) {
1591 ir_instr_delete(in);
1595 in->bops[0] = ontrue;
1596 in->bops[1] = onfalse;
1598 vec_push(self->instr, in);
1600 vec_push(self->exits, ontrue);
1601 vec_push(self->exits, onfalse);
1602 vec_push(ontrue->entries, self);
1603 vec_push(onfalse->entries, self);
1607 bool ir_block_create_jump(ir_block *self, lex_ctx ctx, ir_block *to)
1610 if (!ir_check_unreachable(self))
1613 in = ir_instr_new(ctx, self, VINSTR_JUMP);
1618 vec_push(self->instr, in);
1620 vec_push(self->exits, to);
1621 vec_push(to->entries, self);
1625 bool ir_block_create_goto(ir_block *self, lex_ctx ctx, ir_block *to)
1627 self->owner->flags |= IR_FLAG_HAS_GOTO;
1628 return ir_block_create_jump(self, ctx, to);
1631 ir_instr* ir_block_create_phi(ir_block *self, lex_ctx ctx, const char *label, int ot)
1635 if (!ir_check_unreachable(self))
1637 in = ir_instr_new(ctx, self, VINSTR_PHI);
1640 out = ir_value_out(self->owner, label, store_value, ot);
1642 ir_instr_delete(in);
1645 if (!ir_instr_op(in, 0, out, true)) {
1646 ir_instr_delete(in);
1647 ir_value_delete(out);
1650 vec_push(self->instr, in);
1654 ir_value* ir_phi_value(ir_instr *self)
1656 return self->_ops[0];
1659 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1663 if (!vec_ir_block_find(self->owner->entries, b, NULL)) {
1664 /* Must not be possible to cause this, otherwise the AST
1665 * is doing something wrong.
1667 irerror(self->context, "Invalid entry block for PHI");
1673 vec_push(v->reads, self);
1674 vec_push(self->phi, pe);
1677 /* call related code */
1678 ir_instr* ir_block_create_call(ir_block *self, lex_ctx ctx, const char *label, ir_value *func, bool noreturn)
1682 if (!ir_check_unreachable(self))
1684 in = ir_instr_new(ctx, self, (noreturn ? VINSTR_NRCALL : INSTR_CALL0));
1689 self->is_return = true;
1691 out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1693 ir_instr_delete(in);
1696 if (!ir_instr_op(in, 0, out, true) ||
1697 !ir_instr_op(in, 1, func, false))
1699 ir_instr_delete(in);
1700 ir_value_delete(out);
1703 vec_push(self->instr, in);
1706 if (!ir_block_create_return(self, ctx, NULL)) {
1707 compile_error(ctx, "internal error: failed to generate dummy-return instruction");
1708 ir_instr_delete(in);
1716 ir_value* ir_call_value(ir_instr *self)
1718 return self->_ops[0];
1721 void ir_call_param(ir_instr* self, ir_value *v)
1723 vec_push(self->params, v);
1724 vec_push(v->reads, self);
1727 /* binary op related code */
1729 ir_value* ir_block_create_binop(ir_block *self, lex_ctx ctx,
1730 const char *label, int opcode,
1731 ir_value *left, ir_value *right)
1753 case INSTR_SUB_S: /* -- offset of string as float */
1758 case INSTR_BITOR_IF:
1759 case INSTR_BITOR_FI:
1760 case INSTR_BITAND_FI:
1761 case INSTR_BITAND_IF:
1776 case INSTR_BITAND_I:
1779 case INSTR_RSHIFT_I:
1780 case INSTR_LSHIFT_I:
1802 /* boolean operations result in floats */
1803 if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1805 else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1808 else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1813 if (ot == TYPE_VOID) {
1814 /* The AST or parser were supposed to check this! */
1818 return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1821 ir_value* ir_block_create_unary(ir_block *self, lex_ctx ctx,
1822 const char *label, int opcode,
1825 int ot = TYPE_FLOAT;
1837 /* QC doesn't have other unary operations. We expect extensions to fill
1838 * the above list, otherwise we assume out-type = in-type, eg for an
1842 ot = operand->vtype;
1845 if (ot == TYPE_VOID) {
1846 /* The AST or parser were supposed to check this! */
1850 /* let's use the general instruction creator and pass NULL for OPB */
1851 return ir_block_create_general_instr(self, ctx, label, opcode, operand, NULL, ot);
1854 static ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx ctx, const char *label,
1855 int op, ir_value *a, ir_value *b, int outype)
1860 out = ir_value_out(self->owner, label, store_value, outype);
1864 instr = ir_instr_new(ctx, self, op);
1866 ir_value_delete(out);
1870 if (!ir_instr_op(instr, 0, out, true) ||
1871 !ir_instr_op(instr, 1, a, false) ||
1872 !ir_instr_op(instr, 2, b, false) )
1877 vec_push(self->instr, instr);
1881 ir_instr_delete(instr);
1882 ir_value_delete(out);
1886 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx ctx, const char *label, ir_value *ent, ir_value *field)
1890 /* Support for various pointer types todo if so desired */
1891 if (ent->vtype != TYPE_ENTITY)
1894 if (field->vtype != TYPE_FIELD)
1897 v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1898 v->fieldtype = field->fieldtype;
1902 ir_value* ir_block_create_load_from_ent(ir_block *self, lex_ctx ctx, const char *label, ir_value *ent, ir_value *field, int outype)
1905 if (ent->vtype != TYPE_ENTITY)
1908 /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1909 if (field->vtype != TYPE_FIELD)
1914 case TYPE_FLOAT: op = INSTR_LOAD_F; break;
1915 case TYPE_VECTOR: op = INSTR_LOAD_V; break;
1916 case TYPE_STRING: op = INSTR_LOAD_S; break;
1917 case TYPE_FIELD: op = INSTR_LOAD_FLD; break;
1918 case TYPE_ENTITY: op = INSTR_LOAD_ENT; break;
1919 case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1921 case TYPE_POINTER: op = INSTR_LOAD_I; break;
1922 case TYPE_INTEGER: op = INSTR_LOAD_I; break;
1925 irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1929 return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
1932 /* PHI resolving breaks the SSA, and must thus be the last
1933 * step before life-range calculation.
1936 static bool ir_block_naive_phi(ir_block *self);
1937 bool ir_function_naive_phi(ir_function *self)
1941 for (i = 0; i < vec_size(self->blocks); ++i)
1943 if (!ir_block_naive_phi(self->blocks[i]))
1949 static bool ir_block_naive_phi(ir_block *self)
1951 size_t i, p; /*, w;*/
1952 /* FIXME: optionally, create_phi can add the phis
1953 * to a list so we don't need to loop through blocks
1954 * - anyway: "don't optimize YET"
1956 for (i = 0; i < vec_size(self->instr); ++i)
1958 ir_instr *instr = self->instr[i];
1959 if (instr->opcode != VINSTR_PHI)
1962 vec_remove(self->instr, i, 1);
1963 --i; /* NOTE: i+1 below */
1965 for (p = 0; p < vec_size(instr->phi); ++p)
1967 ir_value *v = instr->phi[p].value;
1968 ir_block *b = instr->phi[p].from;
1970 if (v->store == store_value &&
1971 vec_size(v->reads) == 1 &&
1972 vec_size(v->writes) == 1)
1974 /* replace the value */
1975 if (!ir_instr_op(v->writes[0], 0, instr->_ops[0], true))
1980 /* force a move instruction */
1981 ir_instr *prevjump = vec_last(b->instr);
1984 instr->_ops[0]->store = store_global;
1985 if (!ir_block_create_store(b, instr->context, instr->_ops[0], v))
1987 instr->_ops[0]->store = store_value;
1988 vec_push(b->instr, prevjump);
1992 ir_instr_delete(instr);
1997 /***********************************************************************
1998 *IR Temp allocation code
1999 * Propagating value life ranges by walking through the function backwards
2000 * until no more changes are made.
2001 * In theory this should happen once more than once for every nested loop
2003 * Though this implementation might run an additional time for if nests.
2006 /* Enumerate instructions used by value's life-ranges
2008 static void ir_block_enumerate(ir_block *self, size_t *_eid)
2012 for (i = 0; i < vec_size(self->instr); ++i)
2014 self->instr[i]->eid = eid++;
2019 /* Enumerate blocks and instructions.
2020 * The block-enumeration is unordered!
2021 * We do not really use the block enumreation, however
2022 * the instruction enumeration is important for life-ranges.
2024 void ir_function_enumerate(ir_function *self)
2027 size_t instruction_id = 0;
2028 for (i = 0; i < vec_size(self->blocks); ++i)
2030 /* each block now gets an additional "entry" instruction id
2031 * we can use to avoid point-life issues
2033 self->blocks[i]->entry_id = instruction_id;
2036 self->blocks[i]->eid = i;
2037 ir_block_enumerate(self->blocks[i], &instruction_id);
2041 /* Local-value allocator
2042 * After finishing creating the liferange of all values used in a function
2043 * we can allocate their global-positions.
2044 * This is the counterpart to register-allocation in register machines.
2051 } function_allocator;
2053 static bool function_allocator_alloc(function_allocator *alloc, ir_value *var)
2056 size_t vsize = ir_value_sizeof(var);
2058 var->code.local = vec_size(alloc->locals);
2060 slot = ir_value_var("reg", store_global, var->vtype);
2064 if (!ir_value_life_merge_into(slot, var))
2067 vec_push(alloc->locals, slot);
2068 vec_push(alloc->sizes, vsize);
2069 vec_push(alloc->unique, var->unique_life);
2074 ir_value_delete(slot);
2078 static bool ir_function_allocator_assign(ir_function *self, function_allocator *alloc, ir_value *v)
2084 return function_allocator_alloc(alloc, v);
2086 for (a = 0; a < vec_size(alloc->locals); ++a)
2088 /* if it's reserved for a unique liferange: skip */
2089 if (alloc->unique[a])
2092 slot = alloc->locals[a];
2094 /* never resize parameters
2095 * will be required later when overlapping temps + locals
2097 if (a < vec_size(self->params) &&
2098 alloc->sizes[a] < ir_value_sizeof(v))
2103 if (ir_values_overlap(v, slot))
2106 if (!ir_value_life_merge_into(slot, v))
2109 /* adjust size for this slot */
2110 if (alloc->sizes[a] < ir_value_sizeof(v))
2111 alloc->sizes[a] = ir_value_sizeof(v);
2116 if (a >= vec_size(alloc->locals)) {
2117 if (!function_allocator_alloc(alloc, v))
2123 bool ir_function_allocate_locals(ir_function *self)
2128 bool opt_gt = OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS);
2132 function_allocator lockalloc, globalloc;
2134 if (!vec_size(self->locals) && !vec_size(self->values))
2137 globalloc.locals = NULL;
2138 globalloc.sizes = NULL;
2139 globalloc.positions = NULL;
2140 globalloc.unique = NULL;
2141 lockalloc.locals = NULL;
2142 lockalloc.sizes = NULL;
2143 lockalloc.positions = NULL;
2144 lockalloc.unique = NULL;
2146 for (i = 0; i < vec_size(self->locals); ++i)
2148 v = self->locals[i];
2149 if ((self->flags & IR_FLAG_MASK_NO_LOCAL_TEMPS) || !OPTS_OPTIMIZATION(OPTIM_LOCAL_TEMPS)) {
2151 v->unique_life = true;
2153 else if (i >= vec_size(self->params))
2156 v->locked = true; /* lock parameters locals */
2157 if (!function_allocator_alloc((v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2160 for (; i < vec_size(self->locals); ++i)
2162 v = self->locals[i];
2163 if (!vec_size(v->life))
2165 if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2169 /* Allocate a slot for any value that still exists */
2170 for (i = 0; i < vec_size(self->values); ++i)
2172 v = self->values[i];
2174 if (!vec_size(v->life))
2177 /* CALL optimization:
2178 * If the value is a parameter-temp: 1 write, 1 read from a CALL
2179 * and it's not "locked", write it to the OFS_PARM directly.
2181 if (OPTS_OPTIMIZATION(OPTIM_CALL_STORES) && !v->locked && !v->unique_life) {
2182 if (vec_size(v->reads) == 1 && vec_size(v->writes) == 1 &&
2183 (v->reads[0]->opcode == VINSTR_NRCALL ||
2184 (v->reads[0]->opcode >= INSTR_CALL0 && v->reads[0]->opcode <= INSTR_CALL8)
2189 ir_instr *call = v->reads[0];
2190 if (!vec_ir_value_find(call->params, v, ¶m)) {
2191 irerror(call->context, "internal error: unlocked parameter %s not found", v->name);
2194 ++opts_optimizationcount[OPTIM_CALL_STORES];
2195 v->callparam = true;
2197 ir_value_code_setaddr(v, OFS_PARM0 + 3*param);
2199 size_t nprotos = vec_size(self->owner->extparam_protos);
2202 if (nprotos > param)
2203 ep = self->owner->extparam_protos[param];
2206 ep = ir_gen_extparam_proto(self->owner);
2207 while (++nprotos <= param)
2208 ep = ir_gen_extparam_proto(self->owner);
2210 ir_instr_op(v->writes[0], 0, ep, true);
2211 call->params[param+8] = ep;
2215 if (vec_size(v->writes) == 1 && v->writes[0]->opcode == INSTR_CALL0)
2217 v->store = store_return;
2218 if (v->members[0]) v->members[0]->store = store_return;
2219 if (v->members[1]) v->members[1]->store = store_return;
2220 if (v->members[2]) v->members[2]->store = store_return;
2221 ++opts_optimizationcount[OPTIM_CALL_STORES];
2226 if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2230 if (!lockalloc.sizes && !globalloc.sizes) {
2233 vec_push(lockalloc.positions, 0);
2234 vec_push(globalloc.positions, 0);
2236 /* Adjust slot positions based on sizes */
2237 if (lockalloc.sizes) {
2238 pos = (vec_size(lockalloc.sizes) ? lockalloc.positions[0] : 0);
2239 for (i = 1; i < vec_size(lockalloc.sizes); ++i)
2241 pos = lockalloc.positions[i-1] + lockalloc.sizes[i-1];
2242 vec_push(lockalloc.positions, pos);
2244 self->allocated_locals = pos + vec_last(lockalloc.sizes);
2246 if (globalloc.sizes) {
2247 pos = (vec_size(globalloc.sizes) ? globalloc.positions[0] : 0);
2248 for (i = 1; i < vec_size(globalloc.sizes); ++i)
2250 pos = globalloc.positions[i-1] + globalloc.sizes[i-1];
2251 vec_push(globalloc.positions, pos);
2253 self->globaltemps = pos + vec_last(globalloc.sizes);
2256 /* Locals need to know their new position */
2257 for (i = 0; i < vec_size(self->locals); ++i) {
2258 v = self->locals[i];
2259 if (v->locked || !opt_gt)
2260 v->code.local = lockalloc.positions[v->code.local];
2262 v->code.local = globalloc.positions[v->code.local];
2264 /* Take over the actual slot positions on values */
2265 for (i = 0; i < vec_size(self->values); ++i) {
2266 v = self->values[i];
2267 if (v->locked || !opt_gt)
2268 v->code.local = lockalloc.positions[v->code.local];
2270 v->code.local = globalloc.positions[v->code.local];
2278 for (i = 0; i < vec_size(lockalloc.locals); ++i)
2279 ir_value_delete(lockalloc.locals[i]);
2280 for (i = 0; i < vec_size(globalloc.locals); ++i)
2281 ir_value_delete(globalloc.locals[i]);
2282 vec_free(globalloc.unique);
2283 vec_free(globalloc.locals);
2284 vec_free(globalloc.sizes);
2285 vec_free(globalloc.positions);
2286 vec_free(lockalloc.unique);
2287 vec_free(lockalloc.locals);
2288 vec_free(lockalloc.sizes);
2289 vec_free(lockalloc.positions);
2293 /* Get information about which operand
2294 * is read from, or written to.
2296 static void ir_op_read_write(int op, size_t *read, size_t *write)
2316 case INSTR_STOREP_F:
2317 case INSTR_STOREP_V:
2318 case INSTR_STOREP_S:
2319 case INSTR_STOREP_ENT:
2320 case INSTR_STOREP_FLD:
2321 case INSTR_STOREP_FNC:
2332 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2335 const size_t vs = vec_size(self->living);
2336 bool changed = false;
2337 for (i = 0; i != vs; ++i)
2339 if (ir_value_life_merge(self->living[i], eid))
2345 static bool ir_block_living_lock(ir_block *self)
2348 bool changed = false;
2349 for (i = 0; i != vec_size(self->living); ++i)
2351 if (!self->living[i]->locked) {
2352 self->living[i]->locked = true;
2359 static bool ir_block_life_propagate(ir_block *self, bool *changed)
2363 size_t i, o, p, mem, cnt;
2364 /* bitmasks which operands are read from or written to */
2371 vec_free(self->living);
2373 p = vec_size(self->exits);
2374 for (i = 0; i < p; ++i) {
2375 ir_block *prev = self->exits[i];
2376 cnt = vec_size(prev->living);
2377 for (o = 0; o < cnt; ++o) {
2378 if (!vec_ir_value_find(self->living, prev->living[o], NULL))
2379 vec_push(self->living, prev->living[o]);
2383 i = vec_size(self->instr);
2386 instr = self->instr[i];
2388 /* See which operands are read and write operands */
2389 ir_op_read_write(instr->opcode, &read, &write);
2391 /* Go through the 3 main operands
2392 * writes first, then reads
2394 for (o = 0; o < 3; ++o)
2396 if (!instr->_ops[o]) /* no such operand */
2399 value = instr->_ops[o];
2401 /* We only care about locals */
2402 /* we also calculate parameter liferanges so that locals
2403 * can take up parameter slots */
2404 if (value->store != store_value &&
2405 value->store != store_local &&
2406 value->store != store_param)
2409 /* write operands */
2410 /* When we write to a local, we consider it "dead" for the
2411 * remaining upper part of the function, since in SSA a value
2412 * can only be written once (== created)
2417 bool in_living = vec_ir_value_find(self->living, value, &idx);
2420 /* If the value isn't alive it hasn't been read before... */
2421 /* TODO: See if the warning can be emitted during parsing or AST processing
2422 * otherwise have warning printed here.
2423 * IF printing a warning here: include filecontext_t,
2424 * and make sure it's only printed once
2425 * since this function is run multiple times.
2427 /* con_err( "Value only written %s\n", value->name); */
2428 if (ir_value_life_merge(value, instr->eid))
2431 /* since 'living' won't contain it
2432 * anymore, merge the value, since
2435 if (ir_value_life_merge(value, instr->eid))
2438 vec_remove(self->living, idx, 1);
2440 /* Removing a vector removes all members */
2441 for (mem = 0; mem < 3; ++mem) {
2442 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], &idx)) {
2443 if (ir_value_life_merge(value->members[mem], instr->eid))
2445 vec_remove(self->living, idx, 1);
2448 /* Removing the last member removes the vector */
2449 if (value->memberof) {
2450 value = value->memberof;
2451 for (mem = 0; mem < 3; ++mem) {
2452 if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], NULL))
2455 if (mem == 3 && vec_ir_value_find(self->living, value, &idx)) {
2456 if (ir_value_life_merge(value, instr->eid))
2458 vec_remove(self->living, idx, 1);
2464 if (instr->opcode == INSTR_MUL_VF)
2466 value = instr->_ops[2];
2467 /* the float source will get an additional lifetime */
2468 if (ir_value_life_merge(value, instr->eid+1))
2470 if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2473 else if (instr->opcode == INSTR_MUL_FV || instr->opcode == INSTR_LOAD_V)
2475 value = instr->_ops[1];
2476 /* the float source will get an additional lifetime */
2477 if (ir_value_life_merge(value, instr->eid+1))
2479 if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2483 for (o = 0; o < 3; ++o)
2485 if (!instr->_ops[o]) /* no such operand */
2488 value = instr->_ops[o];
2490 /* We only care about locals */
2491 /* we also calculate parameter liferanges so that locals
2492 * can take up parameter slots */
2493 if (value->store != store_value &&
2494 value->store != store_local &&
2495 value->store != store_param)
2501 if (!vec_ir_value_find(self->living, value, NULL))
2502 vec_push(self->living, value);
2503 /* reading adds the full vector */
2504 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2505 vec_push(self->living, value->memberof);
2506 for (mem = 0; mem < 3; ++mem) {
2507 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2508 vec_push(self->living, value->members[mem]);
2512 /* PHI operands are always read operands */
2513 for (p = 0; p < vec_size(instr->phi); ++p)
2515 value = instr->phi[p].value;
2516 if (!vec_ir_value_find(self->living, value, NULL))
2517 vec_push(self->living, value);
2518 /* reading adds the full vector */
2519 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2520 vec_push(self->living, value->memberof);
2521 for (mem = 0; mem < 3; ++mem) {
2522 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2523 vec_push(self->living, value->members[mem]);
2527 /* on a call, all these values must be "locked" */
2528 if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2529 if (ir_block_living_lock(self))
2532 /* call params are read operands too */
2533 for (p = 0; p < vec_size(instr->params); ++p)
2535 value = instr->params[p];
2536 if (!vec_ir_value_find(self->living, value, NULL))
2537 vec_push(self->living, value);
2538 /* reading adds the full vector */
2539 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2540 vec_push(self->living, value->memberof);
2541 for (mem = 0; mem < 3; ++mem) {
2542 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2543 vec_push(self->living, value->members[mem]);
2548 if (ir_block_living_add_instr(self, instr->eid))
2551 /* the "entry" instruction ID */
2552 if (ir_block_living_add_instr(self, self->entry_id))
2558 bool ir_function_calculate_liferanges(ir_function *self)
2563 /* parameters live at 0 */
2564 for (i = 0; i < vec_size(self->params); ++i)
2565 ir_value_life_merge(self->locals[i], 0);
2570 i = vec_size(self->blocks);
2572 ir_block_life_propagate(self->blocks[i], &changed);
2576 if (vec_size(self->blocks)) {
2577 ir_block *block = self->blocks[0];
2578 for (i = 0; i < vec_size(block->living); ++i) {
2579 ir_value *v = block->living[i];
2580 if (v->store != store_local)
2582 if (v->vtype == TYPE_VECTOR)
2584 self->flags |= IR_FLAG_HAS_UNINITIALIZED;
2585 /* find the instruction reading from it */
2586 for (s = 0; s < vec_size(v->reads); ++s) {
2587 if (v->reads[s]->eid == v->life[0].end)
2590 if (s < vec_size(v->reads)) {
2591 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2592 "variable `%s` may be used uninitialized in this function\n"
2595 v->reads[s]->context.file, v->reads[s]->context.line)
2603 ir_value *vec = v->memberof;
2604 for (s = 0; s < vec_size(vec->reads); ++s) {
2605 if (vec->reads[s]->eid == v->life[0].end)
2608 if (s < vec_size(vec->reads)) {
2609 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2610 "variable `%s` may be used uninitialized in this function\n"
2613 vec->reads[s]->context.file, vec->reads[s]->context.line)
2621 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2622 "variable `%s` may be used uninitialized in this function", v->name))
2631 /***********************************************************************
2634 * Since the IR has the convention of putting 'write' operands
2635 * at the beginning, we have to rotate the operands of instructions
2636 * properly in order to generate valid QCVM code.
2638 * Having destinations at a fixed position is more convenient. In QC
2639 * this is *mostly* OPC, but FTE adds at least 2 instructions which
2640 * read from from OPA, and store to OPB rather than OPC. Which is
2641 * partially the reason why the implementation of these instructions
2642 * in darkplaces has been delayed for so long.
2644 * Breaking conventions is annoying...
2646 static bool ir_builder_gen_global(code_t *, ir_builder *self, ir_value *global, bool islocal);
2648 static bool gen_global_field(code_t *code, ir_value *global)
2650 if (global->hasvalue)
2652 ir_value *fld = global->constval.vpointer;
2654 irerror(global->context, "Invalid field constant with no field: %s", global->name);
2658 /* copy the field's value */
2659 ir_value_code_setaddr(global, vec_size(code->globals));
2660 vec_push(code->globals, fld->code.fieldaddr);
2661 if (global->fieldtype == TYPE_VECTOR) {
2662 vec_push(code->globals, fld->code.fieldaddr+1);
2663 vec_push(code->globals, fld->code.fieldaddr+2);
2668 ir_value_code_setaddr(global, vec_size(code->globals));
2669 vec_push(code->globals, 0);
2670 if (global->fieldtype == TYPE_VECTOR) {
2671 vec_push(code->globals, 0);
2672 vec_push(code->globals, 0);
2675 if (global->code.globaladdr < 0)
2680 static bool gen_global_pointer(code_t *code, ir_value *global)
2682 if (global->hasvalue)
2684 ir_value *target = global->constval.vpointer;
2686 irerror(global->context, "Invalid pointer constant: %s", global->name);
2687 /* NULL pointers are pointing to the NULL constant, which also
2688 * sits at address 0, but still has an ir_value for itself.
2693 /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2694 * void() foo; <- proto
2695 * void() *fooptr = &foo;
2696 * void() foo = { code }
2698 if (!target->code.globaladdr) {
2699 /* FIXME: Check for the constant nullptr ir_value!
2700 * because then code.globaladdr being 0 is valid.
2702 irerror(global->context, "FIXME: Relocation support");
2706 ir_value_code_setaddr(global, vec_size(code->globals));
2707 vec_push(code->globals, target->code.globaladdr);
2711 ir_value_code_setaddr(global, vec_size(code->globals));
2712 vec_push(code->globals, 0);
2714 if (global->code.globaladdr < 0)
2719 static bool gen_blocks_recursive(code_t *code, ir_function *func, ir_block *block)
2721 prog_section_statement stmt;
2729 block->generated = true;
2730 block->code_start = vec_size(code->statements);
2731 for (i = 0; i < vec_size(block->instr); ++i)
2733 instr = block->instr[i];
2735 if (instr->opcode == VINSTR_PHI) {
2736 irerror(block->context, "cannot generate virtual instruction (phi)");
2740 if (instr->opcode == VINSTR_JUMP) {
2741 target = instr->bops[0];
2742 /* for uncoditional jumps, if the target hasn't been generated
2743 * yet, we generate them right here.
2745 if (!target->generated)
2746 return gen_blocks_recursive(code, func, target);
2748 /* otherwise we generate a jump instruction */
2749 stmt.opcode = INSTR_GOTO;
2750 stmt.o1.s1 = (target->code_start) - vec_size(code->statements);
2753 if (stmt.o1.s1 != 1)
2754 code_push_statement(code, &stmt, instr->context.line);
2756 /* no further instructions can be in this block */
2760 if (instr->opcode == VINSTR_COND) {
2761 ontrue = instr->bops[0];
2762 onfalse = instr->bops[1];
2763 /* TODO: have the AST signal which block should
2764 * come first: eg. optimize IFs without ELSE...
2767 stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2771 if (ontrue->generated) {
2772 stmt.opcode = INSTR_IF;
2773 stmt.o2.s1 = (ontrue->code_start) - vec_size(code->statements);
2774 if (stmt.o2.s1 != 1)
2775 code_push_statement(code, &stmt, instr->context.line);
2777 if (onfalse->generated) {
2778 stmt.opcode = INSTR_IFNOT;
2779 stmt.o2.s1 = (onfalse->code_start) - vec_size(code->statements);
2780 if (stmt.o2.s1 != 1)
2781 code_push_statement(code, &stmt, instr->context.line);
2783 if (!ontrue->generated) {
2784 if (onfalse->generated)
2785 return gen_blocks_recursive(code, func, ontrue);
2787 if (!onfalse->generated) {
2788 if (ontrue->generated)
2789 return gen_blocks_recursive(code, func, onfalse);
2791 /* neither ontrue nor onfalse exist */
2792 stmt.opcode = INSTR_IFNOT;
2793 if (!instr->likely) {
2794 /* Honor the likelyhood hint */
2795 ir_block *tmp = onfalse;
2796 stmt.opcode = INSTR_IF;
2800 stidx = vec_size(code->statements);
2801 code_push_statement(code, &stmt, instr->context.line);
2802 /* on false we jump, so add ontrue-path */
2803 if (!gen_blocks_recursive(code, func, ontrue))
2805 /* fixup the jump address */
2806 code->statements[stidx].o2.s1 = vec_size(code->statements) - stidx;
2807 /* generate onfalse path */
2808 if (onfalse->generated) {
2809 /* fixup the jump address */
2810 code->statements[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2811 if (stidx+2 == vec_size(code->statements) && code->statements[stidx].o2.s1 == 1) {
2812 code->statements[stidx] = code->statements[stidx+1];
2813 if (code->statements[stidx].o1.s1 < 0)
2814 code->statements[stidx].o1.s1++;
2815 code_pop_statement(code);
2817 stmt.opcode = vec_last(code->statements).opcode;
2818 if (stmt.opcode == INSTR_GOTO ||
2819 stmt.opcode == INSTR_IF ||
2820 stmt.opcode == INSTR_IFNOT ||
2821 stmt.opcode == INSTR_RETURN ||
2822 stmt.opcode == INSTR_DONE)
2824 /* no use jumping from here */
2827 /* may have been generated in the previous recursive call */
2828 stmt.opcode = INSTR_GOTO;
2829 stmt.o1.s1 = (onfalse->code_start) - vec_size(code->statements);
2832 if (stmt.o1.s1 != 1)
2833 code_push_statement(code, &stmt, instr->context.line);
2836 else if (stidx+2 == vec_size(code->statements) && code->statements[stidx].o2.s1 == 1) {
2837 code->statements[stidx] = code->statements[stidx+1];
2838 if (code->statements[stidx].o1.s1 < 0)
2839 code->statements[stidx].o1.s1++;
2840 code_pop_statement(code);
2842 /* if not, generate now */
2843 return gen_blocks_recursive(code, func, onfalse);
2846 if ( (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8)
2847 || instr->opcode == VINSTR_NRCALL)
2852 first = vec_size(instr->params);
2855 for (p = 0; p < first; ++p)
2857 ir_value *param = instr->params[p];
2858 if (param->callparam)
2861 stmt.opcode = INSTR_STORE_F;
2864 if (param->vtype == TYPE_FIELD)
2865 stmt.opcode = field_store_instr[param->fieldtype];
2866 else if (param->vtype == TYPE_NIL)
2867 stmt.opcode = INSTR_STORE_V;
2869 stmt.opcode = type_store_instr[param->vtype];
2870 stmt.o1.u1 = ir_value_code_addr(param);
2871 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2872 code_push_statement(code, &stmt, instr->context.line);
2874 /* Now handle extparams */
2875 first = vec_size(instr->params);
2876 for (; p < first; ++p)
2878 ir_builder *ir = func->owner;
2879 ir_value *param = instr->params[p];
2880 ir_value *targetparam;
2882 if (param->callparam)
2885 if (p-8 >= vec_size(ir->extparams))
2886 ir_gen_extparam(code, ir);
2888 targetparam = ir->extparams[p-8];
2890 stmt.opcode = INSTR_STORE_F;
2893 if (param->vtype == TYPE_FIELD)
2894 stmt.opcode = field_store_instr[param->fieldtype];
2895 else if (param->vtype == TYPE_NIL)
2896 stmt.opcode = INSTR_STORE_V;
2898 stmt.opcode = type_store_instr[param->vtype];
2899 stmt.o1.u1 = ir_value_code_addr(param);
2900 stmt.o2.u1 = ir_value_code_addr(targetparam);
2901 code_push_statement(code, &stmt, instr->context.line);
2904 stmt.opcode = INSTR_CALL0 + vec_size(instr->params);
2905 if (stmt.opcode > INSTR_CALL8)
2906 stmt.opcode = INSTR_CALL8;
2907 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2910 code_push_statement(code, &stmt, instr->context.line);
2912 retvalue = instr->_ops[0];
2913 if (retvalue && retvalue->store != store_return &&
2914 (retvalue->store == store_global || vec_size(retvalue->life)))
2916 /* not to be kept in OFS_RETURN */
2917 if (retvalue->vtype == TYPE_FIELD && OPTS_FLAG(ADJUST_VECTOR_FIELDS))
2918 stmt.opcode = field_store_instr[retvalue->fieldtype];
2920 stmt.opcode = type_store_instr[retvalue->vtype];
2921 stmt.o1.u1 = OFS_RETURN;
2922 stmt.o2.u1 = ir_value_code_addr(retvalue);
2924 code_push_statement(code, &stmt, instr->context.line);
2929 if (instr->opcode == INSTR_STATE) {
2930 irerror(block->context, "TODO: state instruction");
2934 stmt.opcode = instr->opcode;
2939 /* This is the general order of operands */
2941 stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2944 stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2947 stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2949 if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2951 stmt.o1.u1 = stmt.o3.u1;
2954 else if ((stmt.opcode >= INSTR_STORE_F &&
2955 stmt.opcode <= INSTR_STORE_FNC) ||
2956 (stmt.opcode >= INSTR_STOREP_F &&
2957 stmt.opcode <= INSTR_STOREP_FNC))
2959 /* 2-operand instructions with A -> B */
2960 stmt.o2.u1 = stmt.o3.u1;
2963 /* tiny optimization, don't output
2966 if (stmt.o2.u1 == stmt.o1.u1 &&
2967 OPTS_OPTIMIZATION(OPTIM_PEEPHOLE))
2969 ++opts_optimizationcount[OPTIM_PEEPHOLE];
2974 code_push_statement(code, &stmt, instr->context.line);
2979 static bool gen_function_code(code_t *code, ir_function *self)
2982 prog_section_statement stmt, *retst;
2984 /* Starting from entry point, we generate blocks "as they come"
2985 * for now. Dead blocks will not be translated obviously.
2987 if (!vec_size(self->blocks)) {
2988 irerror(self->context, "Function '%s' declared without body.", self->name);
2992 block = self->blocks[0];
2993 if (block->generated)
2996 if (!gen_blocks_recursive(code, self, block)) {
2997 irerror(self->context, "failed to generate blocks for '%s'", self->name);
3001 /* code_write and qcvm -disasm need to know that the function ends here */
3002 retst = &vec_last(code->statements);
3003 if (OPTS_OPTIMIZATION(OPTIM_VOID_RETURN) &&
3004 self->outtype == TYPE_VOID &&
3005 retst->opcode == INSTR_RETURN &&
3006 !retst->o1.u1 && !retst->o2.u1 && !retst->o3.u1)
3008 retst->opcode = INSTR_DONE;
3009 ++opts_optimizationcount[OPTIM_VOID_RETURN];
3011 stmt.opcode = INSTR_DONE;
3015 code_push_statement(code, &stmt, vec_last(code->linenums));
3020 static qcint ir_builder_filestring(code_t *code, ir_builder *ir, const char *filename)
3022 /* NOTE: filename pointers are copied, we never strdup them,
3023 * thus we can use pointer-comparison to find the string.
3028 for (i = 0; i < vec_size(ir->filenames); ++i) {
3029 if (ir->filenames[i] == filename)
3030 return ir->filestrings[i];
3033 str = code_genstring(code, filename);
3034 vec_push(ir->filenames, filename);
3035 vec_push(ir->filestrings, str);
3039 static bool gen_global_function(code_t *code, ir_builder *ir, ir_value *global)
3041 prog_section_function fun;
3046 if (!global->hasvalue || (!global->constval.vfunc))
3048 irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
3052 irfun = global->constval.vfunc;
3054 fun.name = global->code.name;
3055 fun.file = ir_builder_filestring(code, ir, global->context.file);
3056 fun.profile = 0; /* always 0 */
3057 fun.nargs = vec_size(irfun->params);
3061 for (i = 0;i < 8; ++i) {
3062 if ((int32_t)i >= fun.nargs)
3065 fun.argsize[i] = type_sizeof_[irfun->params[i]];
3069 fun.locals = irfun->allocated_locals;
3072 fun.entry = irfun->builtin+1;
3074 irfun->code_function_def = vec_size(code->functions);
3075 fun.entry = vec_size(code->statements);
3078 vec_push(code->functions, fun);
3082 static ir_value* ir_gen_extparam_proto(ir_builder *ir)
3087 util_snprintf(name, sizeof(name), "EXTPARM#%i", (int)(vec_size(ir->extparam_protos)));
3088 global = ir_value_var(name, store_global, TYPE_VECTOR);
3090 vec_push(ir->extparam_protos, global);
3094 static void ir_gen_extparam(code_t *code, ir_builder *ir)
3096 prog_section_def def;
3099 if (vec_size(ir->extparam_protos) < vec_size(ir->extparams)+1)
3100 global = ir_gen_extparam_proto(ir);
3102 global = ir->extparam_protos[vec_size(ir->extparams)];
3104 def.name = code_genstring(code, global->name);
3105 def.type = TYPE_VECTOR;
3106 def.offset = vec_size(code->globals);
3108 vec_push(code->defs, def);
3110 ir_value_code_setaddr(global, def.offset);
3112 vec_push(code->globals, 0);
3113 vec_push(code->globals, 0);
3114 vec_push(code->globals, 0);
3116 vec_push(ir->extparams, global);
3119 static bool gen_function_extparam_copy(code_t *code, ir_function *self)
3121 size_t i, ext, numparams;
3123 ir_builder *ir = self->owner;
3125 prog_section_statement stmt;
3127 numparams = vec_size(self->params);
3131 stmt.opcode = INSTR_STORE_F;
3133 for (i = 8; i < numparams; ++i) {
3135 if (ext >= vec_size(ir->extparams))
3136 ir_gen_extparam(code, ir);
3138 ep = ir->extparams[ext];
3140 stmt.opcode = type_store_instr[self->locals[i]->vtype];
3141 if (self->locals[i]->vtype == TYPE_FIELD &&
3142 self->locals[i]->fieldtype == TYPE_VECTOR)
3144 stmt.opcode = INSTR_STORE_V;
3146 stmt.o1.u1 = ir_value_code_addr(ep);
3147 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3148 code_push_statement(code, &stmt, self->context.line);
3154 static bool gen_function_varargs_copy(code_t *code, ir_function *self)
3156 size_t i, ext, numparams, maxparams;
3158 ir_builder *ir = self->owner;
3160 prog_section_statement stmt;
3162 numparams = vec_size(self->params);
3166 stmt.opcode = INSTR_STORE_V;
3168 maxparams = numparams + self->max_varargs;
3169 for (i = numparams; i < maxparams; ++i) {
3171 stmt.o1.u1 = OFS_PARM0 + 3*i;
3172 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3173 code_push_statement(code, &stmt, self->context.line);
3177 while (ext >= vec_size(ir->extparams))
3178 ir_gen_extparam(code, ir);
3180 ep = ir->extparams[ext];
3182 stmt.o1.u1 = ir_value_code_addr(ep);
3183 stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3184 code_push_statement(code, &stmt, self->context.line);
3190 static bool gen_function_locals(code_t *code, ir_builder *ir, ir_value *global)
3192 prog_section_function *def;
3195 uint32_t firstlocal, firstglobal;
3197 irfun = global->constval.vfunc;
3198 def = code->functions + irfun->code_function_def;
3200 if (OPTS_OPTION_BOOL(OPTION_G) ||
3201 !OPTS_OPTIMIZATION(OPTIM_OVERLAP_LOCALS) ||
3202 (irfun->flags & IR_FLAG_MASK_NO_OVERLAP))
3204 firstlocal = def->firstlocal = vec_size(code->globals);
3206 firstlocal = def->firstlocal = ir->first_common_local;
3207 ++opts_optimizationcount[OPTIM_OVERLAP_LOCALS];
3210 firstglobal = (OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS) ? ir->first_common_globaltemp : firstlocal);
3212 for (i = vec_size(code->globals); i < firstlocal + irfun->allocated_locals; ++i)
3213 vec_push(code->globals, 0);
3214 for (i = 0; i < vec_size(irfun->locals); ++i) {
3215 ir_value *v = irfun->locals[i];
3216 if (v->locked || !OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS)) {
3217 ir_value_code_setaddr(v, firstlocal + v->code.local);
3218 if (!ir_builder_gen_global(code, ir, irfun->locals[i], true)) {
3219 irerror(irfun->locals[i]->context, "failed to generate local %s", irfun->locals[i]->name);
3224 ir_value_code_setaddr(v, firstglobal + v->code.local);
3226 for (i = 0; i < vec_size(irfun->values); ++i)
3228 ir_value *v = irfun->values[i];
3232 ir_value_code_setaddr(v, firstlocal + v->code.local);
3234 ir_value_code_setaddr(v, firstglobal + v->code.local);
3239 static bool gen_global_function_code(code_t *code, ir_builder *ir, ir_value *global)
3241 prog_section_function *fundef;
3246 irfun = global->constval.vfunc;
3248 if (global->cvq == CV_NONE) {
3249 irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
3250 "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
3252 /* this was a function pointer, don't generate code for those */
3259 if (irfun->code_function_def < 0) {
3260 irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
3263 fundef = &code->functions[irfun->code_function_def];
3265 fundef->entry = vec_size(code->statements);
3266 if (!gen_function_locals(code, ir, global)) {
3267 irerror(irfun->context, "Failed to generate locals for function %s", irfun->name);
3270 if (!gen_function_extparam_copy(code, irfun)) {
3271 irerror(irfun->context, "Failed to generate extparam-copy code for function %s", irfun->name);
3274 if (irfun->max_varargs && !gen_function_varargs_copy(code, irfun)) {
3275 irerror(irfun->context, "Failed to generate vararg-copy code for function %s", irfun->name);
3278 if (!gen_function_code(code, irfun)) {
3279 irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
3285 static void gen_vector_defs(code_t *code, prog_section_def def, const char *name)
3290 if (!name || name[0] == '#' || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3293 def.type = TYPE_FLOAT;
3297 component = (char*)mem_a(len+3);
3298 memcpy(component, name, len);
3300 component[len-0] = 0;
3301 component[len-2] = '_';
3303 component[len-1] = 'x';
3305 for (i = 0; i < 3; ++i) {
3306 def.name = code_genstring(code, component);
3307 vec_push(code->defs, def);
3315 static void gen_vector_fields(code_t *code, prog_section_field fld, const char *name)
3320 if (!name || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3323 fld.type = TYPE_FLOAT;
3327 component = (char*)mem_a(len+3);
3328 memcpy(component, name, len);
3330 component[len-0] = 0;
3331 component[len-2] = '_';
3333 component[len-1] = 'x';
3335 for (i = 0; i < 3; ++i) {
3336 fld.name = code_genstring(code, component);
3337 vec_push(code->fields, fld);
3345 static bool ir_builder_gen_global(code_t *code, ir_builder *self, ir_value *global, bool islocal)
3349 prog_section_def def;
3350 bool pushdef = opts.optimizeoff;
3352 def.type = global->vtype;
3353 def.offset = vec_size(code->globals);
3355 if (OPTS_OPTION_BOOL(OPTION_G) || !islocal)
3359 if (OPTS_OPTIMIZATION(OPTIM_STRIP_CONSTANT_NAMES) &&
3360 !(global->flags & IR_FLAG_INCLUDE_DEF) &&
3361 (global->name[0] == '#' || global->cvq == CV_CONST))
3366 if (pushdef && global->name) {
3367 if (global->name[0] == '#') {
3368 if (!self->str_immediate)
3369 self->str_immediate = code_genstring(code, "IMMEDIATE");
3370 def.name = global->code.name = self->str_immediate;
3373 def.name = global->code.name = code_genstring(code, global->name);
3378 def.offset = ir_value_code_addr(global);
3379 vec_push(code->defs, def);
3380 if (global->vtype == TYPE_VECTOR)
3381 gen_vector_defs(code, def, global->name);
3382 else if (global->vtype == TYPE_FIELD && global->fieldtype == TYPE_VECTOR)
3383 gen_vector_defs(code, def, global->name);
3390 switch (global->vtype)
3393 if (!strcmp(global->name, "end_sys_globals")) {
3394 /* TODO: remember this point... all the defs before this one
3395 * should be checksummed and added to progdefs.h when we generate it.
3398 else if (!strcmp(global->name, "end_sys_fields")) {
3399 /* TODO: same as above but for entity-fields rather than globsl
3403 irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3405 /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3406 * the system fields actually go? Though the engine knows this anyway...
3407 * Maybe this could be an -foption
3408 * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3410 ir_value_code_setaddr(global, vec_size(code->globals));
3411 vec_push(code->globals, 0);
3413 if (pushdef) vec_push(code->defs, def);
3416 if (pushdef) vec_push(code->defs, def);
3417 return gen_global_pointer(code, global);
3420 vec_push(code->defs, def);
3421 if (global->fieldtype == TYPE_VECTOR)
3422 gen_vector_defs(code, def, global->name);
3424 return gen_global_field(code, global);
3429 ir_value_code_setaddr(global, vec_size(code->globals));
3430 if (global->hasvalue) {
3431 iptr = (int32_t*)&global->constval.ivec[0];
3432 vec_push(code->globals, *iptr);
3434 vec_push(code->globals, 0);
3436 if (!islocal && global->cvq != CV_CONST)
3437 def.type |= DEF_SAVEGLOBAL;
3438 if (pushdef) vec_push(code->defs, def);
3440 return global->code.globaladdr >= 0;
3444 ir_value_code_setaddr(global, vec_size(code->globals));
3445 if (global->hasvalue) {
3446 uint32_t load = code_genstring(code, global->constval.vstring);
3447 vec_push(code->globals, load);
3449 vec_push(code->globals, 0);
3451 if (!islocal && global->cvq != CV_CONST)
3452 def.type |= DEF_SAVEGLOBAL;
3453 if (pushdef) vec_push(code->defs, def);
3454 return global->code.globaladdr >= 0;
3459 ir_value_code_setaddr(global, vec_size(code->globals));
3460 if (global->hasvalue) {
3461 iptr = (int32_t*)&global->constval.ivec[0];
3462 vec_push(code->globals, iptr[0]);
3463 if (global->code.globaladdr < 0)
3465 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3466 vec_push(code->globals, iptr[d]);
3469 vec_push(code->globals, 0);
3470 if (global->code.globaladdr < 0)
3472 for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3473 vec_push(code->globals, 0);
3476 if (!islocal && global->cvq != CV_CONST)
3477 def.type |= DEF_SAVEGLOBAL;
3480 vec_push(code->defs, def);
3481 def.type &= ~DEF_SAVEGLOBAL;
3482 gen_vector_defs(code, def, global->name);
3484 return global->code.globaladdr >= 0;
3487 ir_value_code_setaddr(global, vec_size(code->globals));
3488 if (!global->hasvalue) {
3489 vec_push(code->globals, 0);
3490 if (global->code.globaladdr < 0)
3493 vec_push(code->globals, vec_size(code->functions));
3494 if (!gen_global_function(code, self, global))
3497 if (!islocal && global->cvq != CV_CONST)
3498 def.type |= DEF_SAVEGLOBAL;
3499 if (pushdef) vec_push(code->defs, def);
3502 /* assume biggest type */
3503 ir_value_code_setaddr(global, vec_size(code->globals));
3504 vec_push(code->globals, 0);
3505 for (i = 1; i < type_sizeof_[TYPE_VARIANT]; ++i)
3506 vec_push(code->globals, 0);
3509 /* refuse to create 'void' type or any other fancy business. */
3510 irerror(global->context, "Invalid type for global variable `%s`: %s",
3511 global->name, type_name[global->vtype]);
3516 static GMQCC_INLINE void ir_builder_prepare_field(code_t *code, ir_value *field)
3518 field->code.fieldaddr = code_alloc_field(code, type_sizeof_[field->fieldtype]);
3521 static bool ir_builder_gen_field(code_t *code, ir_builder *self, ir_value *field)
3523 prog_section_def def;
3524 prog_section_field fld;
3528 def.type = (uint16_t)field->vtype;
3529 def.offset = (uint16_t)vec_size(code->globals);
3531 /* create a global named the same as the field */
3532 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
3533 /* in our standard, the global gets a dot prefix */
3534 size_t len = strlen(field->name);
3537 /* we really don't want to have to allocate this, and 1024
3538 * bytes is more than enough for a variable/field name
3540 if (len+2 >= sizeof(name)) {
3541 irerror(field->context, "invalid field name size: %u", (unsigned int)len);
3546 memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
3549 def.name = code_genstring(code, name);
3550 fld.name = def.name + 1; /* we reuse that string table entry */
3552 /* in plain QC, there cannot be a global with the same name,
3553 * and so we also name the global the same.
3554 * FIXME: fteqcc should create a global as well
3555 * check if it actually uses the same name. Probably does
3557 def.name = code_genstring(code, field->name);
3558 fld.name = def.name;
3561 field->code.name = def.name;
3563 vec_push(code->defs, def);
3565 fld.type = field->fieldtype;
3567 if (fld.type == TYPE_VOID) {
3568 irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
3572 fld.offset = field->code.fieldaddr;
3574 vec_push(code->fields, fld);
3576 ir_value_code_setaddr(field, vec_size(code->globals));
3577 vec_push(code->globals, fld.offset);
3578 if (fld.type == TYPE_VECTOR) {
3579 vec_push(code->globals, fld.offset+1);
3580 vec_push(code->globals, fld.offset+2);
3583 if (field->fieldtype == TYPE_VECTOR) {
3584 gen_vector_defs (code, def, field->name);
3585 gen_vector_fields(code, fld, field->name);
3588 return field->code.globaladdr >= 0;
3591 bool ir_builder_generate(code_t *code, ir_builder *self, const char *filename)
3593 prog_section_statement stmt;
3595 char *lnofile = NULL;
3597 for (i = 0; i < vec_size(self->fields); ++i)
3599 ir_builder_prepare_field(code, self->fields[i]);
3602 for (i = 0; i < vec_size(self->globals); ++i)
3604 if (!ir_builder_gen_global(code, self, self->globals[i], false)) {
3607 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3608 ir_function *func = self->globals[i]->constval.vfunc;
3609 if (func && self->max_locals < func->allocated_locals &&
3610 !(func->flags & IR_FLAG_MASK_NO_OVERLAP))
3612 self->max_locals = func->allocated_locals;
3614 if (func && self->max_globaltemps < func->globaltemps)
3615 self->max_globaltemps = func->globaltemps;
3619 for (i = 0; i < vec_size(self->fields); ++i)
3621 if (!ir_builder_gen_field(code, self, self->fields[i])) {
3627 ir_value_code_setaddr(self->nil, vec_size(code->globals));
3628 vec_push(code->globals, 0);
3629 vec_push(code->globals, 0);
3630 vec_push(code->globals, 0);
3632 /* generate global temps */
3633 self->first_common_globaltemp = vec_size(code->globals);
3634 for (i = 0; i < self->max_globaltemps; ++i) {
3635 vec_push(code->globals, 0);
3637 /* generate common locals */
3638 self->first_common_local = vec_size(code->globals);
3639 for (i = 0; i < self->max_locals; ++i) {
3640 vec_push(code->globals, 0);
3643 /* generate function code */
3644 for (i = 0; i < vec_size(self->globals); ++i)
3646 if (self->globals[i]->vtype == TYPE_FUNCTION) {
3647 if (!gen_global_function_code(code, self, self->globals[i])) {
3653 if (vec_size(code->globals) >= 65536) {
3654 irerror(vec_last(self->globals)->context, "This progs file would require more globals than the metadata can handle. Bailing out.");
3658 /* DP errors if the last instruction is not an INSTR_DONE. */
3659 if (vec_last(code->statements).opcode != INSTR_DONE)
3661 stmt.opcode = INSTR_DONE;
3665 code_push_statement(code, &stmt, vec_last(code->linenums));
3668 if (OPTS_OPTION_BOOL(OPTION_PP_ONLY))
3671 if (vec_size(code->statements) != vec_size(code->linenums)) {
3672 con_err("Linecounter wrong: %lu != %lu\n",
3673 (unsigned long)vec_size(code->statements),
3674 (unsigned long)vec_size(code->linenums));
3675 } else if (OPTS_FLAG(LNO)) {
3677 size_t filelen = strlen(filename);
3679 memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
3680 dot = strrchr(lnofile, '.');
3684 vec_shrinkto(lnofile, dot - lnofile);
3686 memcpy(vec_add(lnofile, 5), ".lno", 5);
3689 if (!OPTS_OPTION_BOOL(OPTION_QUIET)) {
3691 con_out("writing '%s' and '%s'...\n", filename, lnofile);
3693 con_out("writing '%s'\n", filename);
3695 if (!code_write(code, filename, lnofile)) {
3703 /***********************************************************************
3704 *IR DEBUG Dump functions...
3707 #define IND_BUFSZ 1024
3710 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
3713 static const char *qc_opname(int op)
3715 if (op < 0) return "<INVALID>";
3716 if (op < (int)( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
3717 return asm_instr[op].m;
3719 case VINSTR_PHI: return "PHI";
3720 case VINSTR_JUMP: return "JUMP";
3721 case VINSTR_COND: return "COND";
3722 default: return "<UNK>";
3726 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
3729 char indent[IND_BUFSZ];
3733 oprintf("module %s\n", b->name);
3734 for (i = 0; i < vec_size(b->globals); ++i)
3737 if (b->globals[i]->hasvalue)
3738 oprintf("%s = ", b->globals[i]->name);
3739 ir_value_dump(b->globals[i], oprintf);
3742 for (i = 0; i < vec_size(b->functions); ++i)
3743 ir_function_dump(b->functions[i], indent, oprintf);
3744 oprintf("endmodule %s\n", b->name);
3747 static const char *storenames[] = {
3748 "[global]", "[local]", "[param]", "[value]", "[return]"
3751 void ir_function_dump(ir_function *f, char *ind,
3752 int (*oprintf)(const char*, ...))
3755 if (f->builtin != 0) {
3756 oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
3759 oprintf("%sfunction %s\n", ind, f->name);
3760 strncat(ind, "\t", IND_BUFSZ);
3761 if (vec_size(f->locals))
3763 oprintf("%s%i locals:\n", ind, (int)vec_size(f->locals));
3764 for (i = 0; i < vec_size(f->locals); ++i) {
3765 oprintf("%s\t", ind);
3766 ir_value_dump(f->locals[i], oprintf);
3770 oprintf("%sliferanges:\n", ind);
3771 for (i = 0; i < vec_size(f->locals); ++i) {
3772 const char *attr = "";
3774 ir_value *v = f->locals[i];
3775 if (v->unique_life && v->locked)
3776 attr = "unique,locked ";
3777 else if (v->unique_life)
3781 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
3782 storenames[v->store],
3783 attr, (v->callparam ? "callparam " : ""),
3784 (int)v->code.local);
3787 for (l = 0; l < vec_size(v->life); ++l) {
3788 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3791 for (m = 0; m < 3; ++m) {
3792 ir_value *vm = v->members[m];
3795 oprintf("%s\t%s: @%i ", ind, vm->name, (int)vm->code.local);
3796 for (l = 0; l < vec_size(vm->life); ++l) {
3797 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
3802 for (i = 0; i < vec_size(f->values); ++i) {
3803 const char *attr = "";
3805 ir_value *v = f->values[i];
3806 if (v->unique_life && v->locked)
3807 attr = "unique,locked ";
3808 else if (v->unique_life)
3812 oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
3813 storenames[v->store],
3814 attr, (v->callparam ? "callparam " : ""),
3815 (int)v->code.local);
3818 for (l = 0; l < vec_size(v->life); ++l) {
3819 oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3822 for (m = 0; m < 3; ++m) {
3823 ir_value *vm = v->members[m];
3826 if (vm->unique_life && vm->locked)
3827 attr = "unique,locked ";
3828 else if (vm->unique_life)
3830 else if (vm->locked)
3832 oprintf("%s\t%s: %s@%i ", ind, vm->name, attr, (int)vm->code.local);
3833 for (l = 0; l < vec_size(vm->life); ++l) {
3834 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
3839 if (vec_size(f->blocks))
3841 oprintf("%slife passes: %i\n", ind, (int)f->run_id);
3842 for (i = 0; i < vec_size(f->blocks); ++i) {
3843 ir_block_dump(f->blocks[i], ind, oprintf);
3847 ind[strlen(ind)-1] = 0;
3848 oprintf("%sendfunction %s\n", ind, f->name);
3851 void ir_block_dump(ir_block* b, char *ind,
3852 int (*oprintf)(const char*, ...))
3855 oprintf("%s:%s\n", ind, b->label);
3856 strncat(ind, "\t", IND_BUFSZ);
3858 if (b->instr && b->instr[0])
3859 oprintf("%s (%i) [entry]\n", ind, (int)(b->instr[0]->eid-1));
3860 for (i = 0; i < vec_size(b->instr); ++i)
3861 ir_instr_dump(b->instr[i], ind, oprintf);
3862 ind[strlen(ind)-1] = 0;
3865 static void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
3868 oprintf("%s <- phi ", in->_ops[0]->name);
3869 for (i = 0; i < vec_size(in->phi); ++i)
3871 oprintf("([%s] : %s) ", in->phi[i].from->label,
3872 in->phi[i].value->name);
3877 void ir_instr_dump(ir_instr *in, char *ind,
3878 int (*oprintf)(const char*, ...))
3881 const char *comma = NULL;
3883 oprintf("%s (%i) ", ind, (int)in->eid);
3885 if (in->opcode == VINSTR_PHI) {
3886 dump_phi(in, oprintf);
3890 strncat(ind, "\t", IND_BUFSZ);
3892 if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3893 ir_value_dump(in->_ops[0], oprintf);
3894 if (in->_ops[1] || in->_ops[2])
3897 if (in->opcode == INSTR_CALL0 || in->opcode == VINSTR_NRCALL) {
3898 oprintf("CALL%i\t", vec_size(in->params));
3900 oprintf("%s\t", qc_opname(in->opcode));
3902 if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3903 ir_value_dump(in->_ops[0], oprintf);
3908 for (i = 1; i != 3; ++i) {
3912 ir_value_dump(in->_ops[i], oprintf);
3920 oprintf("[%s]", in->bops[0]->label);
3924 oprintf("%s[%s]", comma, in->bops[1]->label);
3925 if (vec_size(in->params)) {
3926 oprintf("\tparams: ");
3927 for (i = 0; i != vec_size(in->params); ++i) {
3928 oprintf("%s, ", in->params[i]->name);
3932 ind[strlen(ind)-1] = 0;
3935 static void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
3938 for (; *str; ++str) {
3940 case '\n': oprintf("\\n"); break;
3941 case '\r': oprintf("\\r"); break;
3942 case '\t': oprintf("\\t"); break;
3943 case '\v': oprintf("\\v"); break;
3944 case '\f': oprintf("\\f"); break;
3945 case '\b': oprintf("\\b"); break;
3946 case '\a': oprintf("\\a"); break;
3947 case '\\': oprintf("\\\\"); break;
3948 case '"': oprintf("\\\""); break;
3949 default: oprintf("%c", *str); break;
3955 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3964 oprintf("fn:%s", v->name);
3967 oprintf("%g", v->constval.vfloat);
3970 oprintf("'%g %g %g'",
3973 v->constval.vvec.z);
3976 oprintf("(entity)");
3979 ir_value_dump_string(v->constval.vstring, oprintf);
3983 oprintf("%i", v->constval.vint);
3988 v->constval.vpointer->name);
3992 oprintf("%s", v->name);
3996 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
3999 oprintf("Life of %12s:", self->name);
4000 for (i = 0; i < vec_size(self->life); ++i)
4002 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);