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