]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ir.c
cache filenames as such instead of using code_cachedstring
[xonotic/gmqcc.git] / ir.c
1 /*
2  * Copyright (C) 2012
3  *     Wolfgang Bumiller
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of
6  * this software and associated documentation files (the "Software"), to deal in
7  * the Software without restriction, including without limitation the rights to
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9  * of the Software, and to permit persons to whom the Software is furnished to do
10  * so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  */
23 #include <stdlib.h>
24 #include <string.h>
25 #include "gmqcc.h"
26 #include "ir.h"
27
28 /***********************************************************************
29  * Type sizes used at multiple points in the IR codegen
30  */
31
32 const char *type_name[TYPE_COUNT] = {
33     "void",
34     "string",
35     "float",
36     "vector",
37     "entity",
38     "field",
39     "function",
40     "pointer",
41 #if 0
42     "integer",
43 #endif
44     "variant"
45 };
46
47 size_t type_sizeof[TYPE_COUNT] = {
48     1, /* TYPE_VOID     */
49     1, /* TYPE_STRING   */
50     1, /* TYPE_FLOAT    */
51     3, /* TYPE_VECTOR   */
52     1, /* TYPE_ENTITY   */
53     1, /* TYPE_FIELD    */
54     1, /* TYPE_FUNCTION */
55     1, /* TYPE_POINTER  */
56 #if 0
57     1, /* TYPE_INTEGER  */
58 #endif
59     3, /* TYPE_VARIANT  */
60 };
61
62 uint16_t type_store_instr[TYPE_COUNT] = {
63     INSTR_STORE_F, /* should use I when having integer support */
64     INSTR_STORE_S,
65     INSTR_STORE_F,
66     INSTR_STORE_V,
67     INSTR_STORE_ENT,
68     INSTR_STORE_FLD,
69     INSTR_STORE_FNC,
70     INSTR_STORE_ENT, /* should use I */
71 #if 0
72     INSTR_STORE_I, /* integer type */
73 #endif
74
75     INSTR_STORE_V, /* variant, should never be accessed */
76 };
77
78 uint16_t type_storep_instr[TYPE_COUNT] = {
79     INSTR_STOREP_F, /* should use I when having integer support */
80     INSTR_STOREP_S,
81     INSTR_STOREP_F,
82     INSTR_STOREP_V,
83     INSTR_STOREP_ENT,
84     INSTR_STOREP_FLD,
85     INSTR_STOREP_FNC,
86     INSTR_STOREP_ENT, /* should use I */
87 #if 0
88     INSTR_STOREP_ENT, /* integer type */
89 #endif
90
91     INSTR_STOREP_V, /* variant, should never be accessed */
92 };
93
94 uint16_t type_eq_instr[TYPE_COUNT] = {
95     INSTR_EQ_F, /* should use I when having integer support */
96     INSTR_EQ_S,
97     INSTR_EQ_F,
98     INSTR_EQ_V,
99     INSTR_EQ_E,
100     INSTR_EQ_E, /* FLD has no comparison */
101     INSTR_EQ_FNC,
102     INSTR_EQ_E, /* should use I */
103 #if 0
104     INSTR_EQ_I,
105 #endif
106
107     INSTR_EQ_V, /* variant, should never be accessed */
108 };
109
110 uint16_t type_ne_instr[TYPE_COUNT] = {
111     INSTR_NE_F, /* should use I when having integer support */
112     INSTR_NE_S,
113     INSTR_NE_F,
114     INSTR_NE_V,
115     INSTR_NE_E,
116     INSTR_NE_E, /* FLD has no comparison */
117     INSTR_NE_FNC,
118     INSTR_NE_E, /* should use I */
119 #if 0
120     INSTR_NE_I,
121 #endif
122
123     INSTR_NE_V, /* variant, should never be accessed */
124 };
125
126 MEM_VEC_FUNCTIONS(ir_value_vector, ir_value*, v)
127
128 static void irerror(lex_ctx ctx, const char *msg, ...)
129 {
130     va_list ap;
131     va_start(ap, msg);
132     cvprintmsg(ctx, LVL_ERROR, "internal error", msg, ap);
133     va_end(ap);
134 }
135
136 static bool irwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
137 {
138         va_list ap;
139         int lvl = LVL_WARNING;
140
141     if (warntype && !OPTS_WARN(warntype))
142         return false;
143
144     if (opts_werror)
145             lvl = LVL_ERROR;
146
147         va_start(ap, fmt);
148     vprintmsg(lvl, ctx.file, ctx.line, "warning", fmt, ap);
149         va_end(ap);
150
151         return opts_werror;
152 }
153
154 /***********************************************************************
155  *IR Builder
156  */
157
158 ir_builder* ir_builder_new(const char *modulename)
159 {
160     ir_builder* self;
161
162     self = (ir_builder*)mem_a(sizeof(*self));
163     if (!self)
164         return NULL;
165
166     MEM_VECTOR_INIT(self, functions);
167     MEM_VECTOR_INIT(self, globals);
168     MEM_VECTOR_INIT(self, fields);
169     MEM_VECTOR_INIT(self, filenames);
170     MEM_VECTOR_INIT(self, filestrings);
171     self->name = NULL;
172     if (!ir_builder_set_name(self, modulename)) {
173         mem_d(self);
174         return NULL;
175     }
176
177     return self;
178 }
179
180 MEM_VEC_FUNCTIONS(ir_builder, ir_value*,    globals)
181 MEM_VEC_FUNCTIONS(ir_builder, ir_value*,    fields)
182 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
183 MEM_VEC_FUNCTIONS(ir_builder, const char*,  filenames)
184 MEM_VEC_FUNCTIONS(ir_builder, qcint,        filestrings)
185
186 void ir_builder_delete(ir_builder* self)
187 {
188     size_t i;
189     mem_d((void*)self->name);
190     for (i = 0; i != self->functions_count; ++i) {
191         ir_function_delete(self->functions[i]);
192     }
193     MEM_VECTOR_CLEAR(self, functions);
194     for (i = 0; i != self->globals_count; ++i) {
195         ir_value_delete(self->globals[i]);
196     }
197     MEM_VECTOR_CLEAR(self, globals);
198     for (i = 0; i != self->fields_count; ++i) {
199         ir_value_delete(self->fields[i]);
200     }
201     MEM_VECTOR_CLEAR(self, fields);
202     MEM_VECTOR_CLEAR(self, filenames);
203     MEM_VECTOR_CLEAR(self, filestrings);
204     mem_d(self);
205 }
206
207 bool ir_builder_set_name(ir_builder *self, const char *name)
208 {
209     if (self->name)
210         mem_d((void*)self->name);
211     self->name = util_strdup(name);
212     return !!self->name;
213 }
214
215 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
216 {
217     size_t i;
218     for (i = 0; i < self->functions_count; ++i) {
219         if (!strcmp(name, self->functions[i]->name))
220             return self->functions[i];
221     }
222     return NULL;
223 }
224
225 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
226 {
227     ir_function *fn = ir_builder_get_function(self, name);
228     if (fn) {
229         return NULL;
230     }
231
232     fn = ir_function_new(self, outtype);
233     if (!ir_function_set_name(fn, name) ||
234         !ir_builder_functions_add(self, fn) )
235     {
236         ir_function_delete(fn);
237         return NULL;
238     }
239
240     fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
241     if (!fn->value) {
242         ir_function_delete(fn);
243         return NULL;
244     }
245
246     fn->value->isconst = true;
247     fn->value->outtype = outtype;
248     fn->value->constval.vfunc = fn;
249     fn->value->context = fn->context;
250
251     return fn;
252 }
253
254 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
255 {
256     size_t i;
257     for (i = 0; i < self->globals_count; ++i) {
258         if (!strcmp(self->globals[i]->name, name))
259             return self->globals[i];
260     }
261     return NULL;
262 }
263
264 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
265 {
266     ir_value *ve;
267
268     if (name && name[0] != '#')
269     {
270         ve = ir_builder_get_global(self, name);
271         if (ve) {
272             return NULL;
273         }
274     }
275
276     ve = ir_value_var(name, store_global, vtype);
277     if (!ir_builder_globals_add(self, ve)) {
278         ir_value_delete(ve);
279         return NULL;
280     }
281     return ve;
282 }
283
284 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
285 {
286     size_t i;
287     for (i = 0; i < self->fields_count; ++i) {
288         if (!strcmp(self->fields[i]->name, name))
289             return self->fields[i];
290     }
291     return NULL;
292 }
293
294
295 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
296 {
297     ir_value *ve = ir_builder_get_field(self, name);
298     if (ve) {
299         return NULL;
300     }
301
302     ve = ir_value_var(name, store_global, TYPE_FIELD);
303     ve->fieldtype = vtype;
304     if (!ir_builder_fields_add(self, ve)) {
305         ir_value_delete(ve);
306         return NULL;
307     }
308     return ve;
309 }
310
311 /***********************************************************************
312  *IR Function
313  */
314
315 bool ir_function_naive_phi(ir_function*);
316 void ir_function_enumerate(ir_function*);
317 bool ir_function_calculate_liferanges(ir_function*);
318 bool ir_function_allocate_locals(ir_function*);
319
320 ir_function* ir_function_new(ir_builder* owner, int outtype)
321 {
322     ir_function *self;
323     self = (ir_function*)mem_a(sizeof(*self));
324
325     if (!self)
326         return NULL;
327
328     memset(self, 0, sizeof(*self));
329
330     self->name = NULL;
331     if (!ir_function_set_name(self, "<@unnamed>")) {
332         mem_d(self);
333         return NULL;
334     }
335     self->owner = owner;
336     self->context.file = "<@no context>";
337     self->context.line = 0;
338     self->outtype = outtype;
339     self->value = NULL;
340     self->builtin = 0;
341     MEM_VECTOR_INIT(self, params);
342     MEM_VECTOR_INIT(self, blocks);
343     MEM_VECTOR_INIT(self, values);
344     MEM_VECTOR_INIT(self, locals);
345
346     self->code_function_def = -1;
347     self->allocated_locals = 0;
348
349     self->run_id = 0;
350     return self;
351 }
352 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
353 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
354 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
355 MEM_VEC_FUNCTIONS(ir_function, int,       params)
356
357 bool ir_function_set_name(ir_function *self, const char *name)
358 {
359     if (self->name)
360         mem_d((void*)self->name);
361     self->name = util_strdup(name);
362     return !!self->name;
363 }
364
365 void ir_function_delete(ir_function *self)
366 {
367     size_t i;
368     mem_d((void*)self->name);
369
370     for (i = 0; i != self->blocks_count; ++i)
371         ir_block_delete(self->blocks[i]);
372     MEM_VECTOR_CLEAR(self, blocks);
373
374     MEM_VECTOR_CLEAR(self, params);
375
376     for (i = 0; i != self->values_count; ++i)
377         ir_value_delete(self->values[i]);
378     MEM_VECTOR_CLEAR(self, values);
379
380     for (i = 0; i != self->locals_count; ++i)
381         ir_value_delete(self->locals[i]);
382     MEM_VECTOR_CLEAR(self, locals);
383
384     /* self->value is deleted by the builder */
385
386     mem_d(self);
387 }
388
389 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
390 {
391     return ir_function_values_add(self, v);
392 }
393
394 ir_block* ir_function_create_block(ir_function *self, const char *label)
395 {
396     ir_block* bn = ir_block_new(self, label);
397     memcpy(&bn->context, &self->context, sizeof(self->context));
398     if (!ir_function_blocks_add(self, bn)) {
399         ir_block_delete(bn);
400         return NULL;
401     }
402     return bn;
403 }
404
405 bool ir_function_finalize(ir_function *self)
406 {
407     if (self->builtin)
408         return true;
409
410     if (!ir_function_naive_phi(self))
411         return false;
412
413     ir_function_enumerate(self);
414
415     if (!ir_function_calculate_liferanges(self))
416         return false;
417
418     if (!ir_function_allocate_locals(self))
419         return false;
420     return true;
421 }
422
423 ir_value* ir_function_get_local(ir_function *self, const char *name)
424 {
425     size_t i;
426     for (i = 0; i < self->locals_count; ++i) {
427         if (!strcmp(self->locals[i]->name, name))
428             return self->locals[i];
429     }
430     return NULL;
431 }
432
433 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
434 {
435     ir_value *ve;
436
437     /*
438     if (ir_function_get_local(self, name))
439         return NULL;
440     */
441
442     if (param &&
443         self->locals_count &&
444         self->locals[self->locals_count-1]->store != store_param) {
445         irerror(self->context, "cannot add parameters after adding locals");
446         return NULL;
447     }
448
449     ve = ir_value_var(name, (param ? store_param : store_local), vtype);
450     if (!ir_function_locals_add(self, ve)) {
451         ir_value_delete(ve);
452         return NULL;
453     }
454     return ve;
455 }
456
457 /***********************************************************************
458  *IR Block
459  */
460
461 ir_block* ir_block_new(ir_function* owner, const char *name)
462 {
463     ir_block *self;
464     self = (ir_block*)mem_a(sizeof(*self));
465     if (!self)
466         return NULL;
467
468     memset(self, 0, sizeof(*self));
469
470     self->label = NULL;
471     if (name && !ir_block_set_label(self, name)) {
472         mem_d(self);
473         return NULL;
474     }
475     self->owner = owner;
476     self->context.file = "<@no context>";
477     self->context.line = 0;
478     self->final = false;
479     MEM_VECTOR_INIT(self, instr);
480     MEM_VECTOR_INIT(self, entries);
481     MEM_VECTOR_INIT(self, exits);
482
483     self->eid = 0;
484     self->is_return = false;
485     self->run_id = 0;
486     MEM_VECTOR_INIT(self, living);
487
488     self->generated = false;
489
490     return self;
491 }
492 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
493 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
494 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
495 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
496
497 void ir_block_delete(ir_block* self)
498 {
499     size_t i;
500     if (self->label) mem_d(self->label);
501     for (i = 0; i != self->instr_count; ++i)
502         ir_instr_delete(self->instr[i]);
503     MEM_VECTOR_CLEAR(self, instr);
504     MEM_VECTOR_CLEAR(self, entries);
505     MEM_VECTOR_CLEAR(self, exits);
506     MEM_VECTOR_CLEAR(self, living);
507     mem_d(self);
508 }
509
510 bool ir_block_set_label(ir_block *self, const char *name)
511 {
512     if (self->label)
513         mem_d((void*)self->label);
514     self->label = util_strdup(name);
515     return !!self->label;
516 }
517
518 /***********************************************************************
519  *IR Instructions
520  */
521
522 ir_instr* ir_instr_new(ir_block* owner, int op)
523 {
524     ir_instr *self;
525     self = (ir_instr*)mem_a(sizeof(*self));
526     if (!self)
527         return NULL;
528
529     self->owner = owner;
530     self->context.file = "<@no context>";
531     self->context.line = 0;
532     self->opcode = op;
533     self->_ops[0] = NULL;
534     self->_ops[1] = NULL;
535     self->_ops[2] = NULL;
536     self->bops[0] = NULL;
537     self->bops[1] = NULL;
538     MEM_VECTOR_INIT(self, phi);
539     MEM_VECTOR_INIT(self, params);
540
541     self->eid = 0;
542     return self;
543 }
544 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
545 MEM_VEC_FUNCTIONS(ir_instr, ir_value*, params)
546
547 void ir_instr_delete(ir_instr *self)
548 {
549     size_t i;
550     /* The following calls can only delete from
551      * vectors, we still want to delete this instruction
552      * so ignore the return value. Since with the warn_unused_result attribute
553      * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
554      * I have to improvise here and use if(foo());
555      */
556     for (i = 0; i < self->phi_count; ++i) {
557         size_t idx;
558         if (ir_value_writes_find(self->phi[i].value, self, &idx))
559             if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
560         if (ir_value_reads_find(self->phi[i].value, self, &idx))
561             if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPPRESS_EMPTY_BODY;
562     }
563     MEM_VECTOR_CLEAR(self, phi);
564     for (i = 0; i < self->params_count; ++i) {
565         size_t idx;
566         if (ir_value_writes_find(self->params[i], self, &idx))
567             if (ir_value_writes_remove(self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
568         if (ir_value_reads_find(self->params[i], self, &idx))
569             if (ir_value_reads_remove (self->params[i], idx)) GMQCC_SUPPRESS_EMPTY_BODY;
570     }
571     MEM_VECTOR_CLEAR(self, params);
572     if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
573     if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
574     if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPPRESS_EMPTY_BODY;
575     mem_d(self);
576 }
577
578 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
579 {
580     if (self->_ops[op]) {
581         size_t idx;
582         if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
583         {
584             if (!ir_value_writes_remove(self->_ops[op], idx))
585                 return false;
586         }
587         else if (ir_value_reads_find(self->_ops[op], self, &idx))
588         {
589             if (!ir_value_reads_remove(self->_ops[op], idx))
590                 return false;
591         }
592     }
593     if (v) {
594         if (writing) {
595             if (!ir_value_writes_add(v, self))
596                 return false;
597         } else {
598             if (!ir_value_reads_add(v, self))
599                 return false;
600         }
601     }
602     self->_ops[op] = v;
603     return true;
604 }
605
606 /***********************************************************************
607  *IR Value
608  */
609
610 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
611 {
612     self->code.globaladdr = gaddr;
613     if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
614     if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
615     if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
616 }
617
618 int32_t ir_value_code_addr(const ir_value *self)
619 {
620     if (self->store == store_return)
621         return OFS_RETURN + self->code.addroffset;
622     return self->code.globaladdr + self->code.addroffset;
623 }
624
625 ir_value* ir_value_var(const char *name, int storetype, int vtype)
626 {
627     ir_value *self;
628     self = (ir_value*)mem_a(sizeof(*self));
629     self->vtype = vtype;
630     self->fieldtype = TYPE_VOID;
631     self->outtype = TYPE_VOID;
632     self->store = storetype;
633     MEM_VECTOR_INIT(self, reads);
634     MEM_VECTOR_INIT(self, writes);
635     self->isconst = false;
636     self->context.file = "<@no context>";
637     self->context.line = 0;
638     self->name = NULL;
639     if (name && !ir_value_set_name(self, name)) {
640         irerror(self->context, "out of memory");
641         mem_d(self);
642         return NULL;
643     }
644
645     memset(&self->constval, 0, sizeof(self->constval));
646     memset(&self->code,     0, sizeof(self->code));
647
648     self->members[0] = NULL;
649     self->members[1] = NULL;
650     self->members[2] = NULL;
651     self->memberof = NULL;
652
653     MEM_VECTOR_INIT(self, life);
654     return self;
655 }
656
657 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
658 {
659     ir_value *m;
660     if (member >= 3)
661         return NULL;
662
663     if (self->members[member])
664         return self->members[member];
665
666     if (self->vtype == TYPE_VECTOR)
667     {
668         m = ir_value_var(self->name, self->store, TYPE_FLOAT);
669         if (!m)
670             return NULL;
671         m->context = self->context;
672
673         self->members[member] = m;
674         m->code.addroffset = member;
675     }
676     else if (self->vtype == TYPE_FIELD)
677     {
678         if (self->fieldtype != TYPE_VECTOR)
679             return NULL;
680         m = ir_value_var(self->name, self->store, TYPE_FIELD);
681         if (!m)
682             return NULL;
683         m->fieldtype = TYPE_FLOAT;
684         m->context = self->context;
685
686         self->members[member] = m;
687         m->code.addroffset = member;
688     }
689     else
690     {
691         irerror(self->context, "invalid member access on %s", self->name);
692         return NULL;
693     }
694
695     m->memberof = self;
696     return m;
697 }
698
699 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
700 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
701 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
702
703 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
704 {
705     ir_value *v = ir_value_var(name, storetype, vtype);
706     if (!v)
707         return NULL;
708     if (!ir_function_collect_value(owner, v))
709     {
710         ir_value_delete(v);
711         return NULL;
712     }
713     return v;
714 }
715
716 void ir_value_delete(ir_value* self)
717 {
718     size_t i;
719     if (self->name)
720         mem_d((void*)self->name);
721     if (self->isconst)
722     {
723         if (self->vtype == TYPE_STRING)
724             mem_d((void*)self->constval.vstring);
725     }
726     for (i = 0; i < 3; ++i) {
727         if (self->members[i])
728             ir_value_delete(self->members[i]);
729     }
730     MEM_VECTOR_CLEAR(self, reads);
731     MEM_VECTOR_CLEAR(self, writes);
732     MEM_VECTOR_CLEAR(self, life);
733     mem_d(self);
734 }
735
736 bool ir_value_set_name(ir_value *self, const char *name)
737 {
738     if (self->name)
739         mem_d((void*)self->name);
740     self->name = util_strdup(name);
741     return !!self->name;
742 }
743
744 bool ir_value_set_float(ir_value *self, float f)
745 {
746     if (self->vtype != TYPE_FLOAT)
747         return false;
748     self->constval.vfloat = f;
749     self->isconst = true;
750     return true;
751 }
752
753 bool ir_value_set_func(ir_value *self, int f)
754 {
755     if (self->vtype != TYPE_FUNCTION)
756         return false;
757     self->constval.vint = f;
758     self->isconst = true;
759     return true;
760 }
761
762 bool ir_value_set_vector(ir_value *self, vector v)
763 {
764     if (self->vtype != TYPE_VECTOR)
765         return false;
766     self->constval.vvec = v;
767     self->isconst = true;
768     return true;
769 }
770
771 bool ir_value_set_field(ir_value *self, ir_value *fld)
772 {
773     if (self->vtype != TYPE_FIELD)
774         return false;
775     self->constval.vpointer = fld;
776     self->isconst = true;
777     return true;
778 }
779
780 static char *ir_strdup(const char *str)
781 {
782     if (str && !*str) {
783         /* actually dup empty strings */
784         char *out = mem_a(1);
785         *out = 0;
786         return out;
787     }
788     return util_strdup(str);
789 }
790
791 bool ir_value_set_string(ir_value *self, const char *str)
792 {
793     if (self->vtype != TYPE_STRING)
794         return false;
795     self->constval.vstring = ir_strdup(str);
796     self->isconst = true;
797     return true;
798 }
799
800 #if 0
801 bool ir_value_set_int(ir_value *self, int i)
802 {
803     if (self->vtype != TYPE_INTEGER)
804         return false;
805     self->constval.vint = i;
806     self->isconst = true;
807     return true;
808 }
809 #endif
810
811 bool ir_value_lives(ir_value *self, size_t at)
812 {
813     size_t i;
814     for (i = 0; i < self->life_count; ++i)
815     {
816         ir_life_entry_t *life = &self->life[i];
817         if (life->start <= at && at <= life->end)
818             return true;
819         if (life->start > at) /* since it's ordered */
820             return false;
821     }
822     return false;
823 }
824
825 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
826 {
827     size_t k;
828     if (!ir_value_life_add(self, e)) /* naive... */
829         return false;
830     for (k = self->life_count-1; k > idx; --k)
831         self->life[k] = self->life[k-1];
832     self->life[idx] = e;
833     return true;
834 }
835
836 bool ir_value_life_merge(ir_value *self, size_t s)
837 {
838     size_t i;
839     ir_life_entry_t *life = NULL;
840     ir_life_entry_t *before = NULL;
841     ir_life_entry_t new_entry;
842
843     /* Find the first range >= s */
844     for (i = 0; i < self->life_count; ++i)
845     {
846         before = life;
847         life = &self->life[i];
848         if (life->start > s)
849             break;
850     }
851     /* nothing found? append */
852     if (i == self->life_count) {
853         ir_life_entry_t e;
854         if (life && life->end+1 == s)
855         {
856             /* previous life range can be merged in */
857             life->end++;
858             return true;
859         }
860         if (life && life->end >= s)
861             return false;
862         e.start = e.end = s;
863         if (!ir_value_life_add(self, e))
864             return false; /* failing */
865         return true;
866     }
867     /* found */
868     if (before)
869     {
870         if (before->end + 1 == s &&
871             life->start - 1 == s)
872         {
873             /* merge */
874             before->end = life->end;
875             if (!ir_value_life_remove(self, i))
876                 return false; /* failing */
877             return true;
878         }
879         if (before->end + 1 == s)
880         {
881             /* extend before */
882             before->end++;
883             return true;
884         }
885         /* already contained */
886         if (before->end >= s)
887             return false;
888     }
889     /* extend */
890     if (life->start - 1 == s)
891     {
892         life->start--;
893         return true;
894     }
895     /* insert a new entry */
896     new_entry.start = new_entry.end = s;
897     return ir_value_life_insert(self, i, new_entry);
898 }
899
900 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
901 {
902     size_t i, myi;
903
904     if (!other->life_count)
905         return true;
906
907     if (!self->life_count) {
908         for (i = 0; i < other->life_count; ++i) {
909             if (!ir_value_life_add(self, other->life[i]))
910                 return false;
911         }
912         return true;
913     }
914
915     myi = 0;
916     for (i = 0; i < other->life_count; ++i)
917     {
918         const ir_life_entry_t *life = &other->life[i];
919         while (true)
920         {
921             ir_life_entry_t *entry = &self->life[myi];
922
923             if (life->end+1 < entry->start)
924             {
925                 /* adding an interval before entry */
926                 if (!ir_value_life_insert(self, myi, *life))
927                     return false;
928                 ++myi;
929                 break;
930             }
931
932             if (life->start <  entry->start &&
933                 life->end+1 >= entry->start)
934             {
935                 /* starts earlier and overlaps */
936                 entry->start = life->start;
937             }
938
939             if (life->end   >  entry->end &&
940                 life->start <= entry->end+1)
941             {
942                 /* ends later and overlaps */
943                 entry->end = life->end;
944             }
945
946             /* see if our change combines it with the next ranges */
947             while (myi+1 < self->life_count &&
948                    entry->end+1 >= self->life[1+myi].start)
949             {
950                 /* overlaps with (myi+1) */
951                 if (entry->end < self->life[1+myi].end)
952                     entry->end = self->life[1+myi].end;
953                 if (!ir_value_life_remove(self, myi+1))
954                     return false;
955                 entry = &self->life[myi];
956             }
957
958             /* see if we're after the entry */
959             if (life->start > entry->end)
960             {
961                 ++myi;
962                 /* append if we're at the end */
963                 if (myi >= self->life_count) {
964                     if (!ir_value_life_add(self, *life))
965                         return false;
966                     break;
967                 }
968                 /* otherweise check the next range */
969                 continue;
970             }
971             break;
972         }
973     }
974     return true;
975 }
976
977 bool ir_values_overlap(const ir_value *a, const ir_value *b)
978 {
979     /* For any life entry in A see if it overlaps with
980      * any life entry in B.
981      * Note that the life entries are orderes, so we can make a
982      * more efficient algorithm there than naively translating the
983      * statement above.
984      */
985
986     ir_life_entry_t *la, *lb, *enda, *endb;
987
988     /* first of all, if either has no life range, they cannot clash */
989     if (!a->life_count || !b->life_count)
990         return false;
991
992     la = a->life;
993     lb = b->life;
994     enda = la + a->life_count;
995     endb = lb + b->life_count;
996     while (true)
997     {
998         /* check if the entries overlap, for that,
999          * both must start before the other one ends.
1000          */
1001         if (la->start < lb->end &&
1002             lb->start < la->end)
1003         {
1004             return true;
1005         }
1006
1007         /* entries are ordered
1008          * one entry is earlier than the other
1009          * that earlier entry will be moved forward
1010          */
1011         if (la->start < lb->start)
1012         {
1013             /* order: A B, move A forward
1014              * check if we hit the end with A
1015              */
1016             if (++la == enda)
1017                 break;
1018         }
1019         else /* if (lb->start < la->start)  actually <= */
1020         {
1021             /* order: B A, move B forward
1022              * check if we hit the end with B
1023              */
1024             if (++lb == endb)
1025                 break;
1026         }
1027     }
1028     return false;
1029 }
1030
1031 /***********************************************************************
1032  *IR main operations
1033  */
1034
1035 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
1036 {
1037     ir_instr *in = ir_instr_new(self, op);
1038     if (!in)
1039         return false;
1040
1041     if (target->store == store_value &&
1042         (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1043     {
1044         irerror(self->context, "cannot store to an SSA value");
1045         irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1046         irerror(self->context, "instruction: %s", asm_instr[op].m);
1047         return false;
1048     }
1049
1050     if (!ir_instr_op(in, 0, target, true) ||
1051         !ir_instr_op(in, 1, what, false)  ||
1052         !ir_block_instr_add(self, in) )
1053     {
1054         return false;
1055     }
1056     return true;
1057 }
1058
1059 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
1060 {
1061     int op = 0;
1062     int vtype;
1063     if (target->vtype == TYPE_VARIANT)
1064         vtype = what->vtype;
1065     else
1066         vtype = target->vtype;
1067
1068 #if 0
1069     if      (vtype == TYPE_FLOAT   && what->vtype == TYPE_INTEGER)
1070         op = INSTR_CONV_ITOF;
1071     else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1072         op = INSTR_CONV_FTOI;
1073 #endif
1074         op = type_store_instr[vtype];
1075
1076     if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1077         if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1078             op = INSTR_STORE_V;
1079     }
1080
1081     return ir_block_create_store_op(self, op, target, what);
1082 }
1083
1084 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
1085 {
1086     int op = 0;
1087     int vtype;
1088
1089     if (target->vtype != TYPE_POINTER)
1090         return false;
1091
1092     /* storing using pointer - target is a pointer, type must be
1093      * inferred from source
1094      */
1095     vtype = what->vtype;
1096
1097     op = type_storep_instr[vtype];
1098     if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1099         if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1100             op = INSTR_STOREP_V;
1101     }
1102
1103     return ir_block_create_store_op(self, op, target, what);
1104 }
1105
1106 bool ir_block_create_return(ir_block *self, ir_value *v)
1107 {
1108     ir_instr *in;
1109     if (self->final) {
1110         irerror(self->context, "block already ended (%s)", self->label);
1111         return false;
1112     }
1113     self->final = true;
1114     self->is_return = true;
1115     in = ir_instr_new(self, INSTR_RETURN);
1116     if (!in)
1117         return false;
1118
1119     if (v && !ir_instr_op(in, 0, v, false))
1120         return false;
1121
1122     if (!ir_block_instr_add(self, in))
1123         return false;
1124     return true;
1125 }
1126
1127 bool ir_block_create_if(ir_block *self, ir_value *v,
1128                         ir_block *ontrue, ir_block *onfalse)
1129 {
1130     ir_instr *in;
1131     if (self->final) {
1132         irerror(self->context, "block already ended (%s)", self->label);
1133         return false;
1134     }
1135     self->final = true;
1136     /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1137     in = ir_instr_new(self, VINSTR_COND);
1138     if (!in)
1139         return false;
1140
1141     if (!ir_instr_op(in, 0, v, false)) {
1142         ir_instr_delete(in);
1143         return false;
1144     }
1145
1146     in->bops[0] = ontrue;
1147     in->bops[1] = onfalse;
1148
1149     if (!ir_block_instr_add(self, in))
1150         return false;
1151
1152     if (!ir_block_exits_add(self, ontrue)    ||
1153         !ir_block_exits_add(self, onfalse)   ||
1154         !ir_block_entries_add(ontrue, self)  ||
1155         !ir_block_entries_add(onfalse, self) )
1156     {
1157         return false;
1158     }
1159     return true;
1160 }
1161
1162 bool ir_block_create_jump(ir_block *self, ir_block *to)
1163 {
1164     ir_instr *in;
1165     if (self->final) {
1166         irerror(self->context, "block already ended (%s)", self->label);
1167         return false;
1168     }
1169     self->final = true;
1170     in = ir_instr_new(self, VINSTR_JUMP);
1171     if (!in)
1172         return false;
1173
1174     in->bops[0] = to;
1175     if (!ir_block_instr_add(self, in))
1176         return false;
1177
1178     if (!ir_block_exits_add(self, to) ||
1179         !ir_block_entries_add(to, self) )
1180     {
1181         return false;
1182     }
1183     return true;
1184 }
1185
1186 bool ir_block_create_goto(ir_block *self, ir_block *to)
1187 {
1188     ir_instr *in;
1189     if (self->final) {
1190         irerror(self->context, "block already ended (%s)", self->label);
1191         return false;
1192     }
1193     self->final = true;
1194     in = ir_instr_new(self, INSTR_GOTO);
1195     if (!in)
1196         return false;
1197
1198     in->bops[0] = to;
1199     if (!ir_block_instr_add(self, in))
1200         return false;
1201
1202     if (!ir_block_exits_add(self, to) ||
1203         !ir_block_entries_add(to, self) )
1204     {
1205         return false;
1206     }
1207     return true;
1208 }
1209
1210 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
1211 {
1212     ir_value *out;
1213     ir_instr *in;
1214     in = ir_instr_new(self, VINSTR_PHI);
1215     if (!in)
1216         return NULL;
1217     out = ir_value_out(self->owner, label, store_value, ot);
1218     if (!out) {
1219         ir_instr_delete(in);
1220         return NULL;
1221     }
1222     if (!ir_instr_op(in, 0, out, true)) {
1223         ir_instr_delete(in);
1224         ir_value_delete(out);
1225         return NULL;
1226     }
1227     if (!ir_block_instr_add(self, in)) {
1228         ir_instr_delete(in);
1229         ir_value_delete(out);
1230         return NULL;
1231     }
1232     return in;
1233 }
1234
1235 ir_value* ir_phi_value(ir_instr *self)
1236 {
1237     return self->_ops[0];
1238 }
1239
1240 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1241 {
1242     ir_phi_entry_t pe;
1243
1244     if (!ir_block_entries_find(self->owner, b, NULL)) {
1245         /* Must not be possible to cause this, otherwise the AST
1246          * is doing something wrong.
1247          */
1248         irerror(self->context, "Invalid entry block for PHI");
1249         abort();
1250     }
1251
1252     pe.value = v;
1253     pe.from = b;
1254     if (!ir_value_reads_add(v, self))
1255         return false;
1256     return ir_instr_phi_add(self, pe);
1257 }
1258
1259 /* call related code */
1260 ir_instr* ir_block_create_call(ir_block *self, const char *label, ir_value *func)
1261 {
1262     ir_value *out;
1263     ir_instr *in;
1264     in = ir_instr_new(self, INSTR_CALL0);
1265     if (!in)
1266         return NULL;
1267     out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1268     if (!out) {
1269         ir_instr_delete(in);
1270         return NULL;
1271     }
1272     if (!ir_instr_op(in, 0, out, true) ||
1273         !ir_instr_op(in, 1, func, false) ||
1274         !ir_block_instr_add(self, in))
1275     {
1276         ir_instr_delete(in);
1277         ir_value_delete(out);
1278         return NULL;
1279     }
1280     return in;
1281 }
1282
1283 ir_value* ir_call_value(ir_instr *self)
1284 {
1285     return self->_ops[0];
1286 }
1287
1288 bool ir_call_param(ir_instr* self, ir_value *v)
1289 {
1290     if (!ir_instr_params_add(self, v))
1291         return false;
1292     if (!ir_value_reads_add(v, self)) {
1293         if (!ir_instr_params_remove(self, self->params_count-1))
1294             GMQCC_SUPPRESS_EMPTY_BODY;
1295         return false;
1296     }
1297     return true;
1298 }
1299
1300 /* binary op related code */
1301
1302 ir_value* ir_block_create_binop(ir_block *self,
1303                                 const char *label, int opcode,
1304                                 ir_value *left, ir_value *right)
1305 {
1306     int ot = TYPE_VOID;
1307     switch (opcode) {
1308         case INSTR_ADD_F:
1309         case INSTR_SUB_F:
1310         case INSTR_DIV_F:
1311         case INSTR_MUL_F:
1312         case INSTR_MUL_V:
1313         case INSTR_AND:
1314         case INSTR_OR:
1315 #if 0
1316         case INSTR_AND_I:
1317         case INSTR_AND_IF:
1318         case INSTR_AND_FI:
1319         case INSTR_OR_I:
1320         case INSTR_OR_IF:
1321         case INSTR_OR_FI:
1322 #endif
1323         case INSTR_BITAND:
1324         case INSTR_BITOR:
1325 #if 0
1326         case INSTR_SUB_S: /* -- offset of string as float */
1327         case INSTR_MUL_IF:
1328         case INSTR_MUL_FI:
1329         case INSTR_DIV_IF:
1330         case INSTR_DIV_FI:
1331         case INSTR_BITOR_IF:
1332         case INSTR_BITOR_FI:
1333         case INSTR_BITAND_FI:
1334         case INSTR_BITAND_IF:
1335         case INSTR_EQ_I:
1336         case INSTR_NE_I:
1337 #endif
1338             ot = TYPE_FLOAT;
1339             break;
1340 #if 0
1341         case INSTR_ADD_I:
1342         case INSTR_ADD_IF:
1343         case INSTR_ADD_FI:
1344         case INSTR_SUB_I:
1345         case INSTR_SUB_FI:
1346         case INSTR_SUB_IF:
1347         case INSTR_MUL_I:
1348         case INSTR_DIV_I:
1349         case INSTR_BITAND_I:
1350         case INSTR_BITOR_I:
1351         case INSTR_XOR_I:
1352         case INSTR_RSHIFT_I:
1353         case INSTR_LSHIFT_I:
1354             ot = TYPE_INTEGER;
1355             break;
1356 #endif
1357         case INSTR_ADD_V:
1358         case INSTR_SUB_V:
1359         case INSTR_MUL_VF:
1360         case INSTR_MUL_FV:
1361 #if 0
1362         case INSTR_DIV_VF:
1363         case INSTR_MUL_IV:
1364         case INSTR_MUL_VI:
1365 #endif
1366             ot = TYPE_VECTOR;
1367             break;
1368 #if 0
1369         case INSTR_ADD_SF:
1370             ot = TYPE_POINTER;
1371             break;
1372 #endif
1373         default:
1374             /* ranges: */
1375             /* boolean operations result in floats */
1376             if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1377                 ot = TYPE_FLOAT;
1378             else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1379                 ot = TYPE_FLOAT;
1380 #if 0
1381             else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1382                 ot = TYPE_FLOAT;
1383 #endif
1384             break;
1385     };
1386     if (ot == TYPE_VOID) {
1387         /* The AST or parser were supposed to check this! */
1388         return NULL;
1389     }
1390
1391     return ir_block_create_general_instr(self, label, opcode, left, right, ot);
1392 }
1393
1394 ir_value* ir_block_create_unary(ir_block *self,
1395                                 const char *label, int opcode,
1396                                 ir_value *operand)
1397 {
1398     int ot = TYPE_FLOAT;
1399     switch (opcode) {
1400         case INSTR_NOT_F:
1401         case INSTR_NOT_V:
1402         case INSTR_NOT_S:
1403         case INSTR_NOT_ENT:
1404         case INSTR_NOT_FNC:
1405 #if 0
1406         case INSTR_NOT_I:
1407 #endif
1408             ot = TYPE_FLOAT;
1409             break;
1410         /* QC doesn't have other unary operations. We expect extensions to fill
1411          * the above list, otherwise we assume out-type = in-type, eg for an
1412          * unary minus
1413          */
1414         default:
1415             ot = operand->vtype;
1416             break;
1417     };
1418     if (ot == TYPE_VOID) {
1419         /* The AST or parser were supposed to check this! */
1420         return NULL;
1421     }
1422
1423     /* let's use the general instruction creator and pass NULL for OPB */
1424     return ir_block_create_general_instr(self, label, opcode, operand, NULL, ot);
1425 }
1426
1427 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
1428                                         int op, ir_value *a, ir_value *b, int outype)
1429 {
1430     ir_instr *instr;
1431     ir_value *out;
1432
1433     out = ir_value_out(self->owner, label, store_value, outype);
1434     if (!out)
1435         return NULL;
1436
1437     instr = ir_instr_new(self, op);
1438     if (!instr) {
1439         ir_value_delete(out);
1440         return NULL;
1441     }
1442
1443     if (!ir_instr_op(instr, 0, out, true) ||
1444         !ir_instr_op(instr, 1, a, false) ||
1445         !ir_instr_op(instr, 2, b, false) )
1446     {
1447         goto on_error;
1448     }
1449
1450     if (!ir_block_instr_add(self, instr))
1451         goto on_error;
1452
1453     return out;
1454 on_error:
1455     ir_instr_delete(instr);
1456     ir_value_delete(out);
1457     return NULL;
1458 }
1459
1460 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1461 {
1462     ir_value *v;
1463
1464     /* Support for various pointer types todo if so desired */
1465     if (ent->vtype != TYPE_ENTITY)
1466         return NULL;
1467
1468     if (field->vtype != TYPE_FIELD)
1469         return NULL;
1470
1471     v = ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1472     v->fieldtype = field->fieldtype;
1473     return v;
1474 }
1475
1476 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1477 {
1478     int op;
1479     if (ent->vtype != TYPE_ENTITY)
1480         return NULL;
1481
1482     /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1483     if (field->vtype != TYPE_FIELD)
1484         return NULL;
1485
1486     switch (outype)
1487     {
1488         case TYPE_FLOAT:    op = INSTR_LOAD_F;   break;
1489         case TYPE_VECTOR:   op = INSTR_LOAD_V;   break;
1490         case TYPE_STRING:   op = INSTR_LOAD_S;   break;
1491         case TYPE_FIELD:    op = INSTR_LOAD_FLD; break;
1492         case TYPE_ENTITY:   op = INSTR_LOAD_ENT; break;
1493         case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1494 #if 0
1495         case TYPE_POINTER: op = INSTR_LOAD_I;   break;
1496         case TYPE_INTEGER: op = INSTR_LOAD_I;   break;
1497 #endif
1498         default:
1499             return NULL;
1500     }
1501
1502     return ir_block_create_general_instr(self, label, op, ent, field, outype);
1503 }
1504
1505 ir_value* ir_block_create_add(ir_block *self,
1506                               const char *label,
1507                               ir_value *left, ir_value *right)
1508 {
1509     int op = 0;
1510     int l = left->vtype;
1511     int r = right->vtype;
1512     if (l == r) {
1513         switch (l) {
1514             default:
1515                 return NULL;
1516             case TYPE_FLOAT:
1517                 op = INSTR_ADD_F;
1518                 break;
1519 #if 0
1520             case TYPE_INTEGER:
1521                 op = INSTR_ADD_I;
1522                 break;
1523 #endif
1524             case TYPE_VECTOR:
1525                 op = INSTR_ADD_V;
1526                 break;
1527         }
1528     } else {
1529 #if 0
1530         if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1531             op = INSTR_ADD_FI;
1532         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1533             op = INSTR_ADD_IF;
1534         else
1535 #endif
1536             return NULL;
1537     }
1538     return ir_block_create_binop(self, label, op, left, right);
1539 }
1540
1541 ir_value* ir_block_create_sub(ir_block *self,
1542                               const char *label,
1543                               ir_value *left, ir_value *right)
1544 {
1545     int op = 0;
1546     int l = left->vtype;
1547     int r = right->vtype;
1548     if (l == r) {
1549
1550         switch (l) {
1551             default:
1552                 return NULL;
1553             case TYPE_FLOAT:
1554                 op = INSTR_SUB_F;
1555                 break;
1556 #if 0
1557             case TYPE_INTEGER:
1558                 op = INSTR_SUB_I;
1559                 break;
1560 #endif
1561             case TYPE_VECTOR:
1562                 op = INSTR_SUB_V;
1563                 break;
1564         }
1565     } else {
1566 #if 0
1567         if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1568             op = INSTR_SUB_FI;
1569         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1570             op = INSTR_SUB_IF;
1571         else
1572 #endif
1573             return NULL;
1574     }
1575     return ir_block_create_binop(self, label, op, left, right);
1576 }
1577
1578 ir_value* ir_block_create_mul(ir_block *self,
1579                               const char *label,
1580                               ir_value *left, ir_value *right)
1581 {
1582     int op = 0;
1583     int l = left->vtype;
1584     int r = right->vtype;
1585     if (l == r) {
1586
1587         switch (l) {
1588             default:
1589                 return NULL;
1590             case TYPE_FLOAT:
1591                 op = INSTR_MUL_F;
1592                 break;
1593 #if 0
1594             case TYPE_INTEGER:
1595                 op = INSTR_MUL_I;
1596                 break;
1597 #endif
1598             case TYPE_VECTOR:
1599                 op = INSTR_MUL_V;
1600                 break;
1601         }
1602     } else {
1603         if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1604             op = INSTR_MUL_VF;
1605         else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1606             op = INSTR_MUL_FV;
1607 #if 0
1608         else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1609             op = INSTR_MUL_VI;
1610         else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1611             op = INSTR_MUL_IV;
1612         else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1613             op = INSTR_MUL_FI;
1614         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1615             op = INSTR_MUL_IF;
1616 #endif
1617         else
1618             return NULL;
1619     }
1620     return ir_block_create_binop(self, label, op, left, right);
1621 }
1622
1623 ir_value* ir_block_create_div(ir_block *self,
1624                               const char *label,
1625                               ir_value *left, ir_value *right)
1626 {
1627     int op = 0;
1628     int l = left->vtype;
1629     int r = right->vtype;
1630     if (l == r) {
1631
1632         switch (l) {
1633             default:
1634                 return NULL;
1635             case TYPE_FLOAT:
1636                 op = INSTR_DIV_F;
1637                 break;
1638 #if 0
1639             case TYPE_INTEGER:
1640                 op = INSTR_DIV_I;
1641                 break;
1642 #endif
1643         }
1644     } else {
1645 #if 0
1646         if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1647             op = INSTR_DIV_VF;
1648         else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1649             op = INSTR_DIV_FI;
1650         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1651             op = INSTR_DIV_IF;
1652         else
1653 #endif
1654             return NULL;
1655     }
1656     return ir_block_create_binop(self, label, op, left, right);
1657 }
1658
1659 /* PHI resolving breaks the SSA, and must thus be the last
1660  * step before life-range calculation.
1661  */
1662
1663 static bool ir_block_naive_phi(ir_block *self);
1664 bool ir_function_naive_phi(ir_function *self)
1665 {
1666     size_t i;
1667
1668     for (i = 0; i < self->blocks_count; ++i)
1669     {
1670         if (!ir_block_naive_phi(self->blocks[i]))
1671             return false;
1672     }
1673     return true;
1674 }
1675
1676 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1677 {
1678     ir_instr *instr;
1679     size_t i;
1680
1681     /* create a store */
1682     if (!ir_block_create_store(block, old, what))
1683         return false;
1684
1685     /* we now move it up */
1686     instr = block->instr[block->instr_count-1];
1687     for (i = block->instr_count; i > iid; --i)
1688         block->instr[i] = block->instr[i-1];
1689     block->instr[i] = instr;
1690
1691     return true;
1692 }
1693
1694 static bool ir_block_naive_phi(ir_block *self)
1695 {
1696     size_t i, p, w;
1697     /* FIXME: optionally, create_phi can add the phis
1698      * to a list so we don't need to loop through blocks
1699      * - anyway: "don't optimize YET"
1700      */
1701     for (i = 0; i < self->instr_count; ++i)
1702     {
1703         ir_instr *instr = self->instr[i];
1704         if (instr->opcode != VINSTR_PHI)
1705             continue;
1706
1707         if (!ir_block_instr_remove(self, i))
1708             return false;
1709         --i; /* NOTE: i+1 below */
1710
1711         for (p = 0; p < instr->phi_count; ++p)
1712         {
1713             ir_value *v = instr->phi[p].value;
1714             for (w = 0; w < v->writes_count; ++w) {
1715                 ir_value *old;
1716
1717                 if (!v->writes[w]->_ops[0])
1718                     continue;
1719
1720                 /* When the write was to a global, we have to emit a mov */
1721                 old = v->writes[w]->_ops[0];
1722
1723                 /* The original instruction now writes to the PHI target local */
1724                 if (v->writes[w]->_ops[0] == v)
1725                     v->writes[w]->_ops[0] = instr->_ops[0];
1726
1727                 if (old->store != store_value && old->store != store_local && old->store != store_param)
1728                 {
1729                     /* If it originally wrote to a global we need to store the value
1730                      * there as welli
1731                      */
1732                     if (!ir_naive_phi_emit_store(self, i+1, old, v))
1733                         return false;
1734                     if (i+1 < self->instr_count)
1735                         instr = self->instr[i+1];
1736                     else
1737                         instr = NULL;
1738                     /* In case I forget and access instr later, it'll be NULL
1739                      * when it's a problem, to make sure we crash, rather than accessing
1740                      * invalid data.
1741                      */
1742                 }
1743                 else
1744                 {
1745                     /* If it didn't, we can replace all reads by the phi target now. */
1746                     size_t r;
1747                     for (r = 0; r < old->reads_count; ++r)
1748                     {
1749                         size_t op;
1750                         ir_instr *ri = old->reads[r];
1751                         for (op = 0; op < ri->phi_count; ++op) {
1752                             if (ri->phi[op].value == old)
1753                                 ri->phi[op].value = v;
1754                         }
1755                         for (op = 0; op < 3; ++op) {
1756                             if (ri->_ops[op] == old)
1757                                 ri->_ops[op] = v;
1758                         }
1759                     }
1760                 }
1761             }
1762         }
1763         ir_instr_delete(instr);
1764     }
1765     return true;
1766 }
1767
1768 /***********************************************************************
1769  *IR Temp allocation code
1770  * Propagating value life ranges by walking through the function backwards
1771  * until no more changes are made.
1772  * In theory this should happen once more than once for every nested loop
1773  * level.
1774  * Though this implementation might run an additional time for if nests.
1775  */
1776
1777 typedef struct
1778 {
1779     ir_value* *v;
1780     size_t    v_count;
1781     size_t    v_alloc;
1782 } new_reads_t;
1783 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1784
1785 /* Enumerate instructions used by value's life-ranges
1786  */
1787 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1788 {
1789     size_t i;
1790     size_t eid = *_eid;
1791     for (i = 0; i < self->instr_count; ++i)
1792     {
1793         self->instr[i]->eid = eid++;
1794     }
1795     *_eid = eid;
1796 }
1797
1798 /* Enumerate blocks and instructions.
1799  * The block-enumeration is unordered!
1800  * We do not really use the block enumreation, however
1801  * the instruction enumeration is important for life-ranges.
1802  */
1803 void ir_function_enumerate(ir_function *self)
1804 {
1805     size_t i;
1806     size_t instruction_id = 0;
1807     for (i = 0; i < self->blocks_count; ++i)
1808     {
1809         self->blocks[i]->eid = i;
1810         self->blocks[i]->run_id = 0;
1811         ir_block_enumerate(self->blocks[i], &instruction_id);
1812     }
1813 }
1814
1815 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1816 bool ir_function_calculate_liferanges(ir_function *self)
1817 {
1818     size_t i;
1819     bool changed;
1820
1821     do {
1822         self->run_id++;
1823         changed = false;
1824         for (i = 0; i != self->blocks_count; ++i)
1825         {
1826             if (self->blocks[i]->is_return)
1827             {
1828                 self->blocks[i]->living_count = 0;
1829                 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1830                     return false;
1831             }
1832         }
1833     } while (changed);
1834     if (self->blocks_count) {
1835         ir_block *block = self->blocks[0];
1836         for (i = 0; i < block->living_count; ++i) {
1837             ir_value *v = block->living[i];
1838             if (v->memberof || v->store != store_local)
1839                 continue;
1840             if (irwarning(v->context, WARN_USED_UNINITIALIZED,
1841                           "variable `%s` may be used uninitialized in this function", v->name))
1842             {
1843                 return false;
1844             }
1845         }
1846     }
1847     return true;
1848 }
1849
1850 /* Local-value allocator
1851  * After finishing creating the liferange of all values used in a function
1852  * we can allocate their global-positions.
1853  * This is the counterpart to register-allocation in register machines.
1854  */
1855 typedef struct {
1856     MEM_VECTOR_MAKE(ir_value*, locals);
1857     MEM_VECTOR_MAKE(size_t,    sizes);
1858     MEM_VECTOR_MAKE(size_t,    positions);
1859 } function_allocator;
1860 MEM_VEC_FUNCTIONS(function_allocator, ir_value*, locals)
1861 MEM_VEC_FUNCTIONS(function_allocator, size_t,    sizes)
1862 MEM_VEC_FUNCTIONS(function_allocator, size_t,    positions)
1863
1864 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
1865 {
1866     ir_value *slot;
1867     size_t vsize = type_sizeof[var->vtype];
1868
1869     slot = ir_value_var("reg", store_global, var->vtype);
1870     if (!slot)
1871         return false;
1872
1873     if (!ir_value_life_merge_into(slot, var))
1874         goto localerror;
1875
1876     if (!function_allocator_locals_add(alloc, slot))
1877         goto localerror;
1878
1879     if (!function_allocator_sizes_add(alloc, vsize))
1880         goto localerror;
1881
1882     return true;
1883
1884 localerror:
1885     ir_value_delete(slot);
1886     return false;
1887 }
1888
1889 bool ir_function_allocate_locals(ir_function *self)
1890 {
1891     size_t i, a;
1892     bool   retval = true;
1893     size_t pos;
1894
1895     ir_value *slot;
1896     const ir_value *v;
1897
1898     function_allocator alloc;
1899
1900     if (!self->locals_count && !self->values_count)
1901         return true;
1902
1903     MEM_VECTOR_INIT(&alloc, locals);
1904     MEM_VECTOR_INIT(&alloc, sizes);
1905     MEM_VECTOR_INIT(&alloc, positions);
1906
1907     for (i = 0; i < self->locals_count; ++i)
1908     {
1909         if (!function_allocator_alloc(&alloc, self->locals[i]))
1910             goto error;
1911     }
1912
1913     /* Allocate a slot for any value that still exists */
1914     for (i = 0; i < self->values_count; ++i)
1915     {
1916         v = self->values[i];
1917
1918         if (!v->life_count)
1919             continue;
1920
1921         for (a = 0; a < alloc.locals_count; ++a)
1922         {
1923             slot = alloc.locals[a];
1924
1925             if (ir_values_overlap(v, slot))
1926                 continue;
1927
1928             if (!ir_value_life_merge_into(slot, v))
1929                 goto error;
1930
1931             /* adjust size for this slot */
1932             if (alloc.sizes[a] < type_sizeof[v->vtype])
1933                 alloc.sizes[a] = type_sizeof[v->vtype];
1934
1935             self->values[i]->code.local = a;
1936             break;
1937         }
1938         if (a >= alloc.locals_count) {
1939             self->values[i]->code.local = alloc.locals_count;
1940             if (!function_allocator_alloc(&alloc, v))
1941                 goto error;
1942         }
1943     }
1944
1945     if (!alloc.sizes) {
1946         goto cleanup;
1947     }
1948
1949     /* Adjust slot positions based on sizes */
1950     if (!function_allocator_positions_add(&alloc, 0))
1951         goto error;
1952
1953     if (alloc.sizes_count)
1954         pos = alloc.positions[0] + alloc.sizes[0];
1955     else
1956         pos = 0;
1957     for (i = 1; i < alloc.sizes_count; ++i)
1958     {
1959         pos = alloc.positions[i-1] + alloc.sizes[i-1];
1960         if (!function_allocator_positions_add(&alloc, pos))
1961             goto error;
1962     }
1963
1964     self->allocated_locals = pos + alloc.sizes[alloc.sizes_count-1];
1965
1966     /* Take over the actual slot positions */
1967     for (i = 0; i < self->values_count; ++i) {
1968         self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
1969     }
1970
1971     goto cleanup;
1972
1973 error:
1974     retval = false;
1975 cleanup:
1976     for (i = 0; i < alloc.locals_count; ++i)
1977         ir_value_delete(alloc.locals[i]);
1978     MEM_VECTOR_CLEAR(&alloc, locals);
1979     MEM_VECTOR_CLEAR(&alloc, sizes);
1980     MEM_VECTOR_CLEAR(&alloc, positions);
1981     return retval;
1982 }
1983
1984 /* Get information about which operand
1985  * is read from, or written to.
1986  */
1987 static void ir_op_read_write(int op, size_t *read, size_t *write)
1988 {
1989     switch (op)
1990     {
1991     case VINSTR_JUMP:
1992     case INSTR_GOTO:
1993         *write = 0;
1994         *read = 0;
1995         break;
1996     case INSTR_IF:
1997     case INSTR_IFNOT:
1998 #if 0
1999     case INSTR_IF_S:
2000     case INSTR_IFNOT_S:
2001 #endif
2002     case INSTR_RETURN:
2003     case VINSTR_COND:
2004         *write = 0;
2005         *read = 1;
2006         break;
2007     case INSTR_STOREP_F:
2008     case INSTR_STOREP_V:
2009     case INSTR_STOREP_S:
2010     case INSTR_STOREP_ENT:
2011     case INSTR_STOREP_FLD:
2012     case INSTR_STOREP_FNC:
2013         *write = 0;
2014         *read  = 7;
2015         break;
2016     default:
2017         *write = 1;
2018         *read = 6;
2019         break;
2020     };
2021 }
2022
2023 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2024 {
2025     size_t i;
2026     bool changed = false;
2027     bool tempbool;
2028     for (i = 0; i != self->living_count; ++i)
2029     {
2030         tempbool = ir_value_life_merge(self->living[i], eid);
2031         /* debug
2032         if (tempbool)
2033             irerror(self->context, "block_living_add_instr() value instruction added %s: %i", self->living[i]->_name, (int)eid);
2034         */
2035         changed = changed || tempbool;
2036     }
2037     return changed;
2038 }
2039
2040 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
2041 {
2042     size_t i;
2043     /* values which have been read in a previous iteration are now
2044      * in the "living" array even if the previous block doesn't use them.
2045      * So we have to remove whatever does not exist in the previous block.
2046      * They will be re-added on-read, but the liferange merge won't cause
2047      * a change.
2048      */
2049     for (i = 0; i < self->living_count; ++i)
2050     {
2051         if (!ir_block_living_find(prev, self->living[i], NULL)) {
2052             if (!ir_block_living_remove(self, i))
2053                 return false;
2054             --i;
2055         }
2056     }
2057
2058     /* Whatever the previous block still has in its living set
2059      * must now be added to ours as well.
2060      */
2061     for (i = 0; i < prev->living_count; ++i)
2062     {
2063         if (ir_block_living_find(self, prev->living[i], NULL))
2064             continue;
2065         if (!ir_block_living_add(self, prev->living[i]))
2066             return false;
2067         /*
2068         irerror(self->contextt from prev: %s", self->label, prev->living[i]->_name);
2069         */
2070     }
2071     return true;
2072 }
2073
2074 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2075 {
2076     ir_instr *instr;
2077     ir_value *value;
2078     bool  tempbool;
2079     size_t i, o, p;
2080     /* bitmasks which operands are read from or written to */
2081     size_t read, write;
2082     char dbg_ind[16] = { '#', '0' };
2083     (void)dbg_ind;
2084
2085     if (prev)
2086     {
2087         if (!ir_block_life_prop_previous(self, prev, changed))
2088             return false;
2089     }
2090
2091     i = self->instr_count;
2092     while (i)
2093     { --i;
2094         instr = self->instr[i];
2095
2096         /* PHI operands are always read operands */
2097         for (p = 0; p < instr->phi_count; ++p)
2098         {
2099             value = instr->phi[p].value;
2100             if (value->memberof)
2101                 value = value->memberof;
2102             if (!ir_block_living_find(self, value, NULL) &&
2103                 !ir_block_living_add(self, value))
2104             {
2105                 return false;
2106             }
2107         }
2108
2109         /* call params are read operands too */
2110         for (p = 0; p < instr->params_count; ++p)
2111         {
2112             value = instr->params[p];
2113             if (value->memberof)
2114                 value = value->memberof;
2115             if (!ir_block_living_find(self, value, NULL) &&
2116                 !ir_block_living_add(self, value))
2117             {
2118                 return false;
2119             }
2120         }
2121
2122         /* See which operands are read and write operands */
2123         ir_op_read_write(instr->opcode, &read, &write);
2124
2125         if (instr->opcode == INSTR_MUL_VF)
2126         {
2127             /* the float source will get an additional lifetime */
2128             tempbool = ir_value_life_merge(instr->_ops[2], instr->eid+1);
2129             *changed = *changed || tempbool;
2130         }
2131         else if (instr->opcode == INSTR_MUL_FV)
2132         {
2133             /* the float source will get an additional lifetime */
2134             tempbool = ir_value_life_merge(instr->_ops[1], instr->eid+1);
2135             *changed = *changed || tempbool;
2136         }
2137
2138         /* Go through the 3 main operands */
2139         for (o = 0; o < 3; ++o)
2140         {
2141             if (!instr->_ops[o]) /* no such operand */
2142                 continue;
2143
2144             value = instr->_ops[o];
2145             if (value->memberof)
2146                 value = value->memberof;
2147
2148             /* We only care about locals */
2149             /* we also calculate parameter liferanges so that locals
2150              * can take up parameter slots */
2151             if (value->store != store_value &&
2152                 value->store != store_local &&
2153                 value->store != store_param)
2154                 continue;
2155
2156             /* read operands */
2157             if (read & (1<<o))
2158             {
2159                 if (!ir_block_living_find(self, value, NULL) &&
2160                     !ir_block_living_add(self, value))
2161                 {
2162                     return false;
2163                 }
2164             }
2165
2166             /* write operands */
2167             /* When we write to a local, we consider it "dead" for the
2168              * remaining upper part of the function, since in SSA a value
2169              * can only be written once (== created)
2170              */
2171             if (write & (1<<o))
2172             {
2173                 size_t idx;
2174                 bool in_living = ir_block_living_find(self, value, &idx);
2175                 if (!in_living)
2176                 {
2177                     /* If the value isn't alive it hasn't been read before... */
2178                     /* TODO: See if the warning can be emitted during parsing or AST processing
2179                      * otherwise have warning printed here.
2180                      * IF printing a warning here: include filecontext_t,
2181                      * and make sure it's only printed once
2182                      * since this function is run multiple times.
2183                      */
2184                     /* For now: debug info: */
2185                     /* fprintf(stderr, "Value only written %s\n", value->name); */
2186                     tempbool = ir_value_life_merge(value, instr->eid);
2187                     *changed = *changed || tempbool;
2188                     /*
2189                     ir_instr_dump(instr, dbg_ind, printf);
2190                     abort();
2191                     */
2192                 } else {
2193                     /* since 'living' won't contain it
2194                      * anymore, merge the value, since
2195                      * (A) doesn't.
2196                      */
2197                     tempbool = ir_value_life_merge(value, instr->eid);
2198                     /*
2199                     if (tempbool)
2200                         fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
2201                     */
2202                     *changed = *changed || tempbool;
2203                     /* Then remove */
2204                     if (!ir_block_living_remove(self, idx))
2205                         return false;
2206                 }
2207             }
2208         }
2209         /* (A) */
2210         tempbool = ir_block_living_add_instr(self, instr->eid);
2211         /*fprintf(stderr, "living added values\n");*/
2212         *changed = *changed || tempbool;
2213
2214     }
2215
2216     if (self->run_id == self->owner->run_id)
2217         return true;
2218
2219     self->run_id = self->owner->run_id;
2220
2221     for (i = 0; i < self->entries_count; ++i)
2222     {
2223         ir_block *entry = self->entries[i];
2224         ir_block_life_propagate(entry, self, changed);
2225     }
2226
2227     return true;
2228 }
2229
2230 /***********************************************************************
2231  *IR Code-Generation
2232  *
2233  * Since the IR has the convention of putting 'write' operands
2234  * at the beginning, we have to rotate the operands of instructions
2235  * properly in order to generate valid QCVM code.
2236  *
2237  * Having destinations at a fixed position is more convenient. In QC
2238  * this is *mostly* OPC,  but FTE adds at least 2 instructions which
2239  * read from from OPA,  and store to OPB rather than OPC.   Which is
2240  * partially the reason why the implementation of these instructions
2241  * in darkplaces has been delayed for so long.
2242  *
2243  * Breaking conventions is annoying...
2244  */
2245 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2246
2247 static bool gen_global_field(ir_value *global)
2248 {
2249     if (global->isconst)
2250     {
2251         ir_value *fld = global->constval.vpointer;
2252         if (!fld) {
2253             irerror(global->context, "Invalid field constant with no field: %s", global->name);
2254             return false;
2255         }
2256
2257         /* Now, in this case, a relocation would be impossible to code
2258          * since it looks like this:
2259          * .vector v = origin;     <- parse error, wtf is 'origin'?
2260          * .vector origin;
2261          *
2262          * But we will need a general relocation support later anyway
2263          * for functions... might as well support that here.
2264          */
2265         if (!fld->code.globaladdr) {
2266             irerror(global->context, "FIXME: Relocation support");
2267             return false;
2268         }
2269
2270         /* copy the field's value */
2271         ir_value_code_setaddr(global, code_globals_add(code_globals_data[fld->code.globaladdr]));
2272         if (global->fieldtype == TYPE_VECTOR) {
2273             code_globals_add(code_globals_data[fld->code.globaladdr]+1);
2274             code_globals_add(code_globals_data[fld->code.globaladdr]+2);
2275         }
2276     }
2277     else
2278     {
2279         ir_value_code_setaddr(global, code_globals_add(0));
2280         if (global->fieldtype == TYPE_VECTOR) {
2281             code_globals_add(0);
2282             code_globals_add(0);
2283         }
2284     }
2285     if (global->code.globaladdr < 0)
2286         return false;
2287     return true;
2288 }
2289
2290 static bool gen_global_pointer(ir_value *global)
2291 {
2292     if (global->isconst)
2293     {
2294         ir_value *target = global->constval.vpointer;
2295         if (!target) {
2296             irerror(global->context, "Invalid pointer constant: %s", global->name);
2297             /* NULL pointers are pointing to the NULL constant, which also
2298              * sits at address 0, but still has an ir_value for itself.
2299              */
2300             return false;
2301         }
2302
2303         /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2304          * void() foo; <- proto
2305          * void() *fooptr = &foo;
2306          * void() foo = { code }
2307          */
2308         if (!target->code.globaladdr) {
2309             /* FIXME: Check for the constant nullptr ir_value!
2310              * because then code.globaladdr being 0 is valid.
2311              */
2312             irerror(global->context, "FIXME: Relocation support");
2313             return false;
2314         }
2315
2316         ir_value_code_setaddr(global, code_globals_add(target->code.globaladdr));
2317     }
2318     else
2319     {
2320         ir_value_code_setaddr(global, code_globals_add(0));
2321     }
2322     if (global->code.globaladdr < 0)
2323         return false;
2324     return true;
2325 }
2326
2327 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2328 {
2329     prog_section_statement stmt;
2330     ir_instr *instr;
2331     ir_block *target;
2332     ir_block *ontrue;
2333     ir_block *onfalse;
2334     size_t    stidx;
2335     size_t    i;
2336
2337 tailcall:
2338     block->generated = true;
2339     block->code_start = code_statements_elements;
2340     for (i = 0; i < block->instr_count; ++i)
2341     {
2342         instr = block->instr[i];
2343
2344         if (instr->opcode == VINSTR_PHI) {
2345             irerror(block->context, "cannot generate virtual instruction (phi)");
2346             return false;
2347         }
2348
2349         if (instr->opcode == VINSTR_JUMP) {
2350             target = instr->bops[0];
2351             /* for uncoditional jumps, if the target hasn't been generated
2352              * yet, we generate them right here.
2353              */
2354             if (!target->generated) {
2355                 block = target;
2356                 goto tailcall;
2357             }
2358
2359             /* otherwise we generate a jump instruction */
2360             stmt.opcode = INSTR_GOTO;
2361             stmt.o1.s1 = (target->code_start) - code_statements_elements;
2362             stmt.o2.s1 = 0;
2363             stmt.o3.s1 = 0;
2364             if (code_statements_add(stmt) < 0)
2365                 return false;
2366
2367             /* no further instructions can be in this block */
2368             return true;
2369         }
2370
2371         if (instr->opcode == VINSTR_COND) {
2372             ontrue  = instr->bops[0];
2373             onfalse = instr->bops[1];
2374             /* TODO: have the AST signal which block should
2375              * come first: eg. optimize IFs without ELSE...
2376              */
2377
2378             stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2379             stmt.o2.u1 = 0;
2380             stmt.o3.s1 = 0;
2381
2382             if (ontrue->generated) {
2383                 stmt.opcode = INSTR_IF;
2384                 stmt.o2.s1 = (ontrue->code_start) - code_statements_elements;
2385                 if (code_statements_add(stmt) < 0)
2386                     return false;
2387             }
2388             if (onfalse->generated) {
2389                 stmt.opcode = INSTR_IFNOT;
2390                 stmt.o2.s1 = (onfalse->code_start) - code_statements_elements;
2391                 if (code_statements_add(stmt) < 0)
2392                     return false;
2393             }
2394             if (!ontrue->generated) {
2395                 if (onfalse->generated) {
2396                     block = ontrue;
2397                     goto tailcall;
2398                 }
2399             }
2400             if (!onfalse->generated) {
2401                 if (ontrue->generated) {
2402                     block = onfalse;
2403                     goto tailcall;
2404                 }
2405             }
2406             /* neither ontrue nor onfalse exist */
2407             stmt.opcode = INSTR_IFNOT;
2408             stidx = code_statements_elements;
2409             if (code_statements_add(stmt) < 0)
2410                 return false;
2411             /* on false we jump, so add ontrue-path */
2412             if (!gen_blocks_recursive(func, ontrue))
2413                 return false;
2414             /* fixup the jump address */
2415             code_statements_data[stidx].o2.s1 = code_statements_elements - stidx;
2416             /* generate onfalse path */
2417             if (onfalse->generated) {
2418                 /* fixup the jump address */
2419                 code_statements_data[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2420                 /* may have been generated in the previous recursive call */
2421                 stmt.opcode = INSTR_GOTO;
2422                 stmt.o1.s1 = (onfalse->code_start) - code_statements_elements;
2423                 stmt.o2.s1 = 0;
2424                 stmt.o3.s1 = 0;
2425                 return (code_statements_add(stmt) >= 0);
2426             }
2427             /* if not, generate now */
2428             block = onfalse;
2429             goto tailcall;
2430         }
2431
2432         if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2433             /* Trivial call translation:
2434              * copy all params to OFS_PARM*
2435              * if the output's storetype is not store_return,
2436              * add append a STORE instruction!
2437              *
2438              * NOTES on how to do it better without much trouble:
2439              * -) The liferanges!
2440              *      Simply check the liferange of all parameters for
2441              *      other CALLs. For each param with no CALL in its
2442              *      liferange, we can store it in an OFS_PARM at
2443              *      generation already. This would even include later
2444              *      reuse.... probably... :)
2445              */
2446             size_t p;
2447             ir_value *retvalue;
2448
2449             for (p = 0; p < instr->params_count; ++p)
2450             {
2451                 ir_value *param = instr->params[p];
2452
2453                 stmt.opcode = INSTR_STORE_F;
2454                 stmt.o3.u1 = 0;
2455
2456                 stmt.opcode = type_store_instr[param->vtype];
2457                 stmt.o1.u1 = ir_value_code_addr(param);
2458                 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2459                 if (code_statements_add(stmt) < 0)
2460                     return false;
2461             }
2462             stmt.opcode = INSTR_CALL0 + instr->params_count;
2463             if (stmt.opcode > INSTR_CALL8)
2464                 stmt.opcode = INSTR_CALL8;
2465             stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2466             stmt.o2.u1 = 0;
2467             stmt.o3.u1 = 0;
2468             if (code_statements_add(stmt) < 0)
2469                 return false;
2470
2471             retvalue = instr->_ops[0];
2472             if (retvalue && retvalue->store != store_return && retvalue->life_count)
2473             {
2474                 /* not to be kept in OFS_RETURN */
2475                 stmt.opcode = type_store_instr[retvalue->vtype];
2476                 stmt.o1.u1 = OFS_RETURN;
2477                 stmt.o2.u1 = ir_value_code_addr(retvalue);
2478                 stmt.o3.u1 = 0;
2479                 if (code_statements_add(stmt) < 0)
2480                     return false;
2481             }
2482             continue;
2483         }
2484
2485         if (instr->opcode == INSTR_STATE) {
2486             irerror(block->context, "TODO: state instruction");
2487             return false;
2488         }
2489
2490         stmt.opcode = instr->opcode;
2491         stmt.o1.u1 = 0;
2492         stmt.o2.u1 = 0;
2493         stmt.o3.u1 = 0;
2494
2495         /* This is the general order of operands */
2496         if (instr->_ops[0])
2497             stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2498
2499         if (instr->_ops[1])
2500             stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2501
2502         if (instr->_ops[2])
2503             stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2504
2505         if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2506         {
2507             stmt.o1.u1 = stmt.o3.u1;
2508             stmt.o3.u1 = 0;
2509         }
2510         else if ((stmt.opcode >= INSTR_STORE_F &&
2511                   stmt.opcode <= INSTR_STORE_FNC) ||
2512                  (stmt.opcode >= INSTR_STOREP_F &&
2513                   stmt.opcode <= INSTR_STOREP_FNC))
2514         {
2515             /* 2-operand instructions with A -> B */
2516             stmt.o2.u1 = stmt.o3.u1;
2517             stmt.o3.u1 = 0;
2518         }
2519
2520         if (code_statements_add(stmt) < 0)
2521             return false;
2522     }
2523     return true;
2524 }
2525
2526 static bool gen_function_code(ir_function *self)
2527 {
2528     ir_block *block;
2529     prog_section_statement stmt;
2530
2531     /* Starting from entry point, we generate blocks "as they come"
2532      * for now. Dead blocks will not be translated obviously.
2533      */
2534     if (!self->blocks_count) {
2535         irerror(self->context, "Function '%s' declared without body.", self->name);
2536         return false;
2537     }
2538
2539     block = self->blocks[0];
2540     if (block->generated)
2541         return true;
2542
2543     if (!gen_blocks_recursive(self, block)) {
2544         irerror(self->context, "failed to generate blocks for '%s'", self->name);
2545         return false;
2546     }
2547
2548     /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2549     stmt.opcode = AINSTR_END;
2550     stmt.o1.u1 = 0;
2551     stmt.o2.u1 = 0;
2552     stmt.o3.u1 = 0;
2553     if (code_statements_add(stmt) < 0)
2554         return false;
2555     return true;
2556 }
2557
2558 static qcint ir_builder_filestring(ir_builder *ir, const char *filename)
2559 {
2560     /* NOTE: filename pointers are copied, we never strdup them,
2561      * thus we can use pointer-comparison to find the string.
2562      */
2563     size_t i;
2564     qcint  str;
2565
2566     for (i = 0; i < ir->filenames_count; ++i) {
2567         if (ir->filenames[i] == filename)
2568             return ir->filestrings[i];
2569     }
2570
2571     str = code_genstring(filename);
2572     if (!ir_builder_filenames_add(ir, filename))
2573         return 0;
2574     if (!ir_builder_filestrings_add(ir, str))
2575         ir->filenames_count--;
2576     return str;
2577 }
2578
2579 static bool gen_global_function(ir_builder *ir, ir_value *global)
2580 {
2581     prog_section_function fun;
2582     ir_function          *irfun;
2583
2584     size_t i;
2585     size_t local_var_end;
2586
2587     if (!global->isconst || (!global->constval.vfunc))
2588     {
2589         irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
2590         return false;
2591     }
2592
2593     irfun = global->constval.vfunc;
2594
2595     fun.name    = global->code.name;
2596     fun.file    = ir_builder_filestring(ir, global->context.file);
2597     fun.profile = 0; /* always 0 */
2598     fun.nargs   = irfun->params_count;
2599
2600     for (i = 0;i < 8; ++i) {
2601         if (i >= fun.nargs)
2602             fun.argsize[i] = 0;
2603         else
2604             fun.argsize[i] = type_sizeof[irfun->params[i]];
2605     }
2606
2607     fun.firstlocal = code_globals_elements;
2608
2609     local_var_end = fun.firstlocal;
2610     for (i = 0; i < irfun->locals_count; ++i) {
2611         if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
2612             irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
2613             return false;
2614         }
2615     }
2616     if (irfun->locals_count) {
2617         ir_value *last = irfun->locals[irfun->locals_count-1];
2618         local_var_end = last->code.globaladdr;
2619         local_var_end += type_sizeof[last->vtype];
2620     }
2621     for (i = 0; i < irfun->values_count; ++i)
2622     {
2623         /* generate code.globaladdr for ssa values */
2624         ir_value *v = irfun->values[i];
2625         ir_value_code_setaddr(v, local_var_end + v->code.local);
2626     }
2627     for (i = 0; i < irfun->allocated_locals; ++i) {
2628         /* fill the locals with zeros */
2629         code_globals_add(0);
2630     }
2631
2632     fun.locals = code_globals_elements - fun.firstlocal;
2633
2634     if (irfun->builtin)
2635         fun.entry = irfun->builtin;
2636     else {
2637         irfun->code_function_def = code_functions_elements;
2638         fun.entry = code_statements_elements;
2639     }
2640
2641     return (code_functions_add(fun) >= 0);
2642 }
2643
2644 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
2645 {
2646     prog_section_function *fundef;
2647     ir_function           *irfun;
2648
2649     irfun = global->constval.vfunc;
2650     if (!irfun) {
2651         irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
2652                   "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
2653         /* this was a function pointer, don't generate code for those */
2654         return true;
2655     }
2656
2657     if (irfun->builtin)
2658         return true;
2659
2660     if (irfun->code_function_def < 0) {
2661         irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
2662         return false;
2663     }
2664     fundef = &code_functions_data[irfun->code_function_def];
2665
2666     fundef->entry = code_statements_elements;
2667     if (!gen_function_code(irfun)) {
2668         irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
2669         return false;
2670     }
2671     return true;
2672 }
2673
2674 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
2675 {
2676     size_t           i;
2677     int32_t         *iptr;
2678     prog_section_def def;
2679
2680     def.type   = global->vtype;
2681     def.offset = code_globals_elements;
2682     def.name   = global->code.name       = code_genstring(global->name);
2683
2684     switch (global->vtype)
2685     {
2686     case TYPE_VOID:
2687         if (!strcmp(global->name, "end_sys_globals")) {
2688             /* TODO: remember this point... all the defs before this one
2689              * should be checksummed and added to progdefs.h when we generate it.
2690              */
2691         }
2692         else if (!strcmp(global->name, "end_sys_fields")) {
2693             /* TODO: same as above but for entity-fields rather than globsl
2694              */
2695         }
2696         else
2697             irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
2698                       global->name);
2699         /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
2700          * the system fields actually go? Though the engine knows this anyway...
2701          * Maybe this could be an -foption
2702          * fteqcc creates data for end_sys_* - of size 1, so let's do the same
2703          */
2704         ir_value_code_setaddr(global, code_globals_add(0));
2705         /* Add the def */
2706         if (code_defs_add(def) < 0)
2707             return false;
2708         return true;
2709     case TYPE_POINTER:
2710         if (code_defs_add(def) < 0)
2711             return false;
2712         return gen_global_pointer(global);
2713     case TYPE_FIELD:
2714         if (code_defs_add(def) < 0)
2715             return false;
2716         return gen_global_field(global);
2717     case TYPE_ENTITY:
2718         /* fall through */
2719     case TYPE_FLOAT:
2720     {
2721         if (global->isconst) {
2722             iptr = (int32_t*)&global->constval.vfloat;
2723             ir_value_code_setaddr(global, code_globals_add(*iptr));
2724         } else {
2725             ir_value_code_setaddr(global, code_globals_add(0));
2726             if (!islocal)
2727                 def.type |= DEF_SAVEGLOBAL;
2728         }
2729         if (code_defs_add(def) < 0)
2730             return false;
2731
2732         return global->code.globaladdr >= 0;
2733     }
2734     case TYPE_STRING:
2735     {
2736         if (global->isconst)
2737             ir_value_code_setaddr(global, code_globals_add(code_genstring(global->constval.vstring)));
2738         else {
2739             ir_value_code_setaddr(global, code_globals_add(0));
2740             if (!islocal)
2741                 def.type |= DEF_SAVEGLOBAL;
2742         }
2743         if (code_defs_add(def) < 0)
2744             return false;
2745         return global->code.globaladdr >= 0;
2746     }
2747     case TYPE_VECTOR:
2748     {
2749         size_t d;
2750         if (global->isconst) {
2751             iptr = (int32_t*)&global->constval.vvec;
2752             ir_value_code_setaddr(global, code_globals_add(iptr[0]));
2753             if (global->code.globaladdr < 0)
2754                 return false;
2755             for (d = 1; d < type_sizeof[global->vtype]; ++d)
2756             {
2757                 if (code_globals_add(iptr[d]) < 0)
2758                     return false;
2759             }
2760         } else {
2761             ir_value_code_setaddr(global, code_globals_add(0));
2762             if (global->code.globaladdr < 0)
2763                 return false;
2764             for (d = 1; d < type_sizeof[global->vtype]; ++d)
2765             {
2766                 if (code_globals_add(0) < 0)
2767                     return false;
2768             }
2769             if (!islocal)
2770                 def.type |= DEF_SAVEGLOBAL;
2771         }
2772
2773         if (code_defs_add(def) < 0)
2774             return false;
2775         return global->code.globaladdr >= 0;
2776     }
2777     case TYPE_FUNCTION:
2778         if (!global->isconst) {
2779             ir_value_code_setaddr(global, code_globals_add(0));
2780             if (global->code.globaladdr < 0)
2781                 return false;
2782         } else {
2783             ir_value_code_setaddr(global, code_globals_elements);
2784             code_globals_add(code_functions_elements);
2785             if (!gen_global_function(self, global))
2786                 return false;
2787             if (!islocal)
2788                 def.type |= DEF_SAVEGLOBAL;
2789         }
2790         if (code_defs_add(def) < 0)
2791             return false;
2792         return true;
2793     case TYPE_VARIANT:
2794         /* assume biggest type */
2795             ir_value_code_setaddr(global, code_globals_add(0));
2796             for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
2797                 code_globals_add(0);
2798             return true;
2799     default:
2800         /* refuse to create 'void' type or any other fancy business. */
2801         irerror(global->context, "Invalid type for global variable `%s`: %s",
2802                 global->name, type_name[global->vtype]);
2803         return false;
2804     }
2805 }
2806
2807 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
2808 {
2809     prog_section_def def;
2810     prog_section_field fld;
2811
2812     def.type   = field->vtype;
2813     def.offset = code_globals_elements;
2814
2815     /* create a global named the same as the field */
2816     if (opts_standard == COMPILER_GMQCC) {
2817         /* in our standard, the global gets a dot prefix */
2818         size_t len = strlen(field->name);
2819         char name[1024];
2820
2821         /* we really don't want to have to allocate this, and 1024
2822          * bytes is more than enough for a variable/field name
2823          */
2824         if (len+2 >= sizeof(name)) {
2825             irerror(field->context, "invalid field name size: %u", (unsigned int)len);
2826             return false;
2827         }
2828
2829         name[0] = '.';
2830         memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
2831         name[len+1] = 0;
2832
2833         def.name = code_genstring(name);
2834         fld.name = def.name + 1; /* we reuse that string table entry */
2835     } else {
2836         /* in plain QC, there cannot be a global with the same name,
2837          * and so we also name the global the same.
2838          * FIXME: fteqcc should create a global as well
2839          * check if it actually uses the same name. Probably does
2840          */
2841         def.name = code_genstring(field->name);
2842         fld.name = def.name;
2843     }
2844
2845     field->code.name = def.name;
2846
2847     if (code_defs_add(def) < 0)
2848         return false;
2849
2850     fld.type = field->fieldtype;
2851
2852     if (fld.type == TYPE_VOID) {
2853         irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
2854         return false;
2855     }
2856
2857     fld.offset = code_alloc_field(type_sizeof[field->fieldtype]);
2858
2859     if (code_fields_add(fld) < 0)
2860         return false;
2861
2862     ir_value_code_setaddr(field, code_globals_elements);
2863     if (!code_globals_add(fld.offset))
2864         return false;
2865     if (fld.type == TYPE_VECTOR) {
2866         if (!code_globals_add(fld.offset+1))
2867             return false;
2868         if (!code_globals_add(fld.offset+2))
2869             return false;
2870     }
2871
2872     return field->code.globaladdr >= 0;
2873 }
2874
2875 bool ir_builder_generate(ir_builder *self, const char *filename)
2876 {
2877     prog_section_statement stmt;
2878     size_t i;
2879
2880     code_init();
2881
2882     for (i = 0; i < self->globals_count; ++i)
2883     {
2884         if (!ir_builder_gen_global(self, self->globals[i], false)) {
2885             return false;
2886         }
2887     }
2888
2889     for (i = 0; i < self->fields_count; ++i)
2890     {
2891         if (!ir_builder_gen_field(self, self->fields[i])) {
2892             return false;
2893         }
2894     }
2895
2896     /* generate function code */
2897     for (i = 0; i < self->globals_count; ++i)
2898     {
2899         if (self->globals[i]->vtype == TYPE_FUNCTION) {
2900             if (!gen_global_function_code(self, self->globals[i])) {
2901                 return false;
2902             }
2903         }
2904     }
2905
2906     /* DP errors if the last instruction is not an INSTR_DONE
2907      * and for debugging purposes we add an additional AINSTR_END
2908      * to the end of functions, so here it goes:
2909      */
2910     stmt.opcode = INSTR_DONE;
2911     stmt.o1.u1 = 0;
2912     stmt.o2.u1 = 0;
2913     stmt.o3.u1 = 0;
2914     if (code_statements_add(stmt) < 0)
2915         return false;
2916
2917     printf("writing '%s'...\n", filename);
2918     return code_write(filename);
2919 }
2920
2921 /***********************************************************************
2922  *IR DEBUG Dump functions...
2923  */
2924
2925 #define IND_BUFSZ 1024
2926
2927 #ifdef WIN32
2928 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
2929 #else
2930 # define strncat strncat
2931 #endif
2932
2933 const char *qc_opname(int op)
2934 {
2935     if (op < 0) return "<INVALID>";
2936     if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
2937         return asm_instr[op].m;
2938     switch (op) {
2939         case VINSTR_PHI:  return "PHI";
2940         case VINSTR_JUMP: return "JUMP";
2941         case VINSTR_COND: return "COND";
2942         default:          return "<UNK>";
2943     }
2944 }
2945
2946 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
2947 {
2948     size_t i;
2949     char indent[IND_BUFSZ];
2950     indent[0] = '\t';
2951     indent[1] = 0;
2952
2953     oprintf("module %s\n", b->name);
2954     for (i = 0; i < b->globals_count; ++i)
2955     {
2956         oprintf("global ");
2957         if (b->globals[i]->isconst)
2958             oprintf("%s = ", b->globals[i]->name);
2959         ir_value_dump(b->globals[i], oprintf);
2960         oprintf("\n");
2961     }
2962     for (i = 0; i < b->functions_count; ++i)
2963         ir_function_dump(b->functions[i], indent, oprintf);
2964     oprintf("endmodule %s\n", b->name);
2965 }
2966
2967 void ir_function_dump(ir_function *f, char *ind,
2968                       int (*oprintf)(const char*, ...))
2969 {
2970     size_t i;
2971     if (f->builtin != 0) {
2972         oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
2973         return;
2974     }
2975     oprintf("%sfunction %s\n", ind, f->name);
2976     strncat(ind, "\t", IND_BUFSZ);
2977     if (f->locals_count)
2978     {
2979         oprintf("%s%i locals:\n", ind, (int)f->locals_count);
2980         for (i = 0; i < f->locals_count; ++i) {
2981             oprintf("%s\t", ind);
2982             ir_value_dump(f->locals[i], oprintf);
2983             oprintf("\n");
2984         }
2985     }
2986     oprintf("%sliferanges:\n", ind);
2987     for (i = 0; i < f->locals_count; ++i) {
2988         size_t l;
2989         ir_value *v = f->locals[i];
2990         oprintf("%s\t%s: unique ", ind, v->name);
2991         for (l = 0; l < v->life_count; ++l) {
2992             oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
2993         }
2994         oprintf("\n");
2995     }
2996     for (i = 0; i < f->values_count; ++i) {
2997         size_t l;
2998         ir_value *v = f->values[i];
2999         oprintf("%s\t%s: @%i ", ind, v->name, (int)v->code.local);
3000         for (l = 0; l < v->life_count; ++l) {
3001             oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3002         }
3003         oprintf("\n");
3004     }
3005     if (f->blocks_count)
3006     {
3007         oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
3008         for (i = 0; i < f->blocks_count; ++i) {
3009             if (f->blocks[i]->run_id != f->run_id) {
3010                 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
3011             }
3012             ir_block_dump(f->blocks[i], ind, oprintf);
3013         }
3014
3015     }
3016     ind[strlen(ind)-1] = 0;
3017     oprintf("%sendfunction %s\n", ind, f->name);
3018 }
3019
3020 void ir_block_dump(ir_block* b, char *ind,
3021                    int (*oprintf)(const char*, ...))
3022 {
3023     size_t i;
3024     oprintf("%s:%s\n", ind, b->label);
3025     strncat(ind, "\t", IND_BUFSZ);
3026
3027     for (i = 0; i < b->instr_count; ++i)
3028         ir_instr_dump(b->instr[i], ind, oprintf);
3029     ind[strlen(ind)-1] = 0;
3030 }
3031
3032 void dump_phi(ir_instr *in, char *ind,
3033               int (*oprintf)(const char*, ...))
3034 {
3035     size_t i;
3036     oprintf("%s <- phi ", in->_ops[0]->name);
3037     for (i = 0; i < in->phi_count; ++i)
3038     {
3039         oprintf("([%s] : %s) ", in->phi[i].from->label,
3040                                 in->phi[i].value->name);
3041     }
3042     oprintf("\n");
3043 }
3044
3045 void ir_instr_dump(ir_instr *in, char *ind,
3046                        int (*oprintf)(const char*, ...))
3047 {
3048     size_t i;
3049     const char *comma = NULL;
3050
3051     oprintf("%s (%i) ", ind, (int)in->eid);
3052
3053     if (in->opcode == VINSTR_PHI) {
3054         dump_phi(in, ind, oprintf);
3055         return;
3056     }
3057
3058     strncat(ind, "\t", IND_BUFSZ);
3059
3060     if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3061         ir_value_dump(in->_ops[0], oprintf);
3062         if (in->_ops[1] || in->_ops[2])
3063             oprintf(" <- ");
3064     }
3065     if (in->opcode == INSTR_CALL0) {
3066         oprintf("CALL%i\t", in->params_count);
3067     } else
3068         oprintf("%s\t", qc_opname(in->opcode));
3069
3070     if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3071         ir_value_dump(in->_ops[0], oprintf);
3072         comma = ",\t";
3073     }
3074     else
3075     {
3076         for (i = 1; i != 3; ++i) {
3077             if (in->_ops[i]) {
3078                 if (comma)
3079                     oprintf(comma);
3080                 ir_value_dump(in->_ops[i], oprintf);
3081                 comma = ",\t";
3082             }
3083         }
3084     }
3085     if (in->bops[0]) {
3086         if (comma)
3087             oprintf(comma);
3088         oprintf("[%s]", in->bops[0]->label);
3089         comma = ",\t";
3090     }
3091     if (in->bops[1])
3092         oprintf("%s[%s]", comma, in->bops[1]->label);
3093     if (in->params_count) {
3094         oprintf("\tparams: ");
3095         for (i = 0; i != in->params_count; ++i) {
3096             oprintf("%s, ", in->params[i]->name);
3097         }
3098     }
3099     oprintf("\n");
3100     ind[strlen(ind)-1] = 0;
3101 }
3102
3103 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3104 {
3105     if (v->isconst) {
3106         switch (v->vtype) {
3107             default:
3108             case TYPE_VOID:
3109                 oprintf("(void)");
3110                 break;
3111             case TYPE_FUNCTION:
3112                 oprintf("fn:%s", v->name);
3113                 break;
3114             case TYPE_FLOAT:
3115                 oprintf("%g", v->constval.vfloat);
3116                 break;
3117             case TYPE_VECTOR:
3118                 oprintf("'%g %g %g'",
3119                         v->constval.vvec.x,
3120                         v->constval.vvec.y,
3121                         v->constval.vvec.z);
3122                 break;
3123             case TYPE_ENTITY:
3124                 oprintf("(entity)");
3125                 break;
3126             case TYPE_STRING:
3127                 oprintf("\"%s\"", v->constval.vstring);
3128                 break;
3129 #if 0
3130             case TYPE_INTEGER:
3131                 oprintf("%i", v->constval.vint);
3132                 break;
3133 #endif
3134             case TYPE_POINTER:
3135                 oprintf("&%s",
3136                     v->constval.vpointer->name);
3137                 break;
3138         }
3139     } else {
3140         oprintf("%s", v->name);
3141     }
3142 }
3143
3144 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
3145 {
3146     size_t i;
3147     oprintf("Life of %12s:", self->name);
3148     for (i = 0; i < self->life_count; ++i)
3149     {
3150         oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);
3151     }
3152 }