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