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