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