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