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