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