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