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