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