]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ir.c
naive_phi now recognizes both store_local and store_value as non-global, create_store...
[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  *IR Builder
30  */
31
32 ir_builder* ir_builder_new(const char *modulename)
33 {
34     ir_builder* self;
35
36     self = (ir_builder*)mem_a(sizeof(*self));
37     MEM_VECTOR_INIT(self, functions);
38     MEM_VECTOR_INIT(self, globals);
39     self->name = NULL;
40     if (!ir_builder_set_name(self, modulename)) {
41         mem_d(self);
42         return NULL;
43     }
44
45     /* globals which always exist */
46
47     /* for now we give it a vector size */
48     ir_builder_create_global(self, "OFS_RETURN", TYPE_VARIANT);
49
50     return self;
51 }
52
53 MEM_VEC_FUNCTIONS(ir_builder, ir_value*, globals)
54 MEM_VEC_FUNCTIONS(ir_builder, ir_function*, functions)
55
56 void ir_builder_delete(ir_builder* self)
57 {
58     size_t i;
59     mem_d((void*)self->name);
60     for (i = 0; i != self->functions_count; ++i) {
61         ir_function_delete(self->functions[i]);
62     }
63     MEM_VECTOR_CLEAR(self, functions);
64     for (i = 0; i != self->globals_count; ++i) {
65         ir_value_delete(self->globals[i]);
66     }
67     MEM_VECTOR_CLEAR(self, globals);
68     mem_d(self);
69 }
70
71 bool ir_builder_set_name(ir_builder *self, const char *name)
72 {
73     if (self->name)
74         mem_d((void*)self->name);
75     self->name = util_strdup(name);
76     return !!self->name;
77 }
78
79 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
80 {
81     size_t i;
82     for (i = 0; i < self->functions_count; ++i) {
83         if (!strcmp(name, self->functions[i]->name))
84             return self->functions[i];
85     }
86     return NULL;
87 }
88
89 ir_function* ir_builder_create_function(ir_builder *self, const char *name)
90 {
91     ir_function *fn = ir_builder_get_function(self, name);
92     if (fn) {
93         return NULL;
94     }
95
96     fn = ir_function_new(self);
97     if (!ir_function_set_name(fn, name) ||
98         !ir_builder_functions_add(self, fn) )
99     {
100         ir_function_delete(fn);
101         return NULL;
102     }
103     return fn;
104 }
105
106 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
107 {
108     size_t i;
109     for (i = 0; i < self->globals_count; ++i) {
110         if (!strcmp(self->globals[i]->name, name))
111             return self->globals[i];
112     }
113     return NULL;
114 }
115
116 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
117 {
118     ir_value *ve = ir_builder_get_global(self, name);
119     if (ve) {
120         return NULL;
121     }
122
123     ve = ir_value_var(name, store_global, vtype);
124     if (!ir_builder_globals_add(self, ve)) {
125         ir_value_delete(ve);
126         return NULL;
127     }
128     return ve;
129 }
130
131 /***********************************************************************
132  *IR Function
133  */
134
135 bool ir_function_naive_phi(ir_function*);
136 void ir_function_enumerate(ir_function*);
137 bool ir_function_calculate_liferanges(ir_function*);
138
139 ir_function* ir_function_new(ir_builder* owner)
140 {
141     ir_function *self;
142     self = (ir_function*)mem_a(sizeof(*self));
143     self->name = NULL;
144     if (!ir_function_set_name(self, "<@unnamed>")) {
145         mem_d(self);
146         return NULL;
147     }
148     self->owner = owner;
149     self->context.file = "<@no context>";
150     self->context.line = 0;
151     self->retype = TYPE_VOID;
152     MEM_VECTOR_INIT(self, params);
153     MEM_VECTOR_INIT(self, blocks);
154     MEM_VECTOR_INIT(self, values);
155     MEM_VECTOR_INIT(self, locals);
156
157     self->run_id = 0;
158     return self;
159 }
160 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
161 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
162 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
163
164 bool ir_function_set_name(ir_function *self, const char *name)
165 {
166     if (self->name)
167         mem_d((void*)self->name);
168     self->name = util_strdup(name);
169     return !!self->name;
170 }
171
172 void ir_function_delete(ir_function *self)
173 {
174     size_t i;
175     mem_d((void*)self->name);
176
177     for (i = 0; i != self->blocks_count; ++i)
178         ir_block_delete(self->blocks[i]);
179     MEM_VECTOR_CLEAR(self, blocks);
180
181     MEM_VECTOR_CLEAR(self, params);
182
183     for (i = 0; i != self->values_count; ++i)
184         ir_value_delete(self->values[i]);
185     MEM_VECTOR_CLEAR(self, values);
186
187     for (i = 0; i != self->locals_count; ++i)
188         ir_value_delete(self->locals[i]);
189     MEM_VECTOR_CLEAR(self, locals);
190
191     mem_d(self);
192 }
193
194 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
195 {
196     return ir_function_values_add(self, v);
197 }
198
199 ir_block* ir_function_create_block(ir_function *self, const char *label)
200 {
201     ir_block* bn = ir_block_new(self, label);
202     memcpy(&bn->context, &self->context, sizeof(self->context));
203     if (!ir_function_blocks_add(self, bn)) {
204         ir_block_delete(bn);
205         return NULL;
206     }
207     return bn;
208 }
209
210 bool ir_function_finalize(ir_function *self)
211 {
212     if (!ir_function_naive_phi(self))
213         return false;
214
215     ir_function_enumerate(self);
216
217     if (!ir_function_calculate_liferanges(self))
218         return false;
219     return true;
220 }
221
222 ir_value* ir_function_get_local(ir_function *self, const char *name)
223 {
224     size_t i;
225     for (i = 0; i < self->locals_count; ++i) {
226         if (!strcmp(self->locals[i]->name, name))
227             return self->locals[i];
228     }
229     return NULL;
230 }
231
232 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype)
233 {
234     ir_value *ve = ir_function_get_local(self, name);
235     if (ve) {
236         return NULL;
237     }
238
239     ve = ir_value_var(name, store_local, vtype);
240     if (!ir_function_locals_add(self, ve)) {
241         ir_value_delete(ve);
242         return NULL;
243     }
244     return ve;
245 }
246
247 /***********************************************************************
248  *IR Block
249  */
250
251 ir_block* ir_block_new(ir_function* owner, const char *name)
252 {
253     ir_block *self;
254     self = (ir_block*)mem_a(sizeof(*self));
255     self->label = NULL;
256     if (!ir_block_set_label(self, name)) {
257         mem_d(self);
258         return NULL;
259     }
260     self->owner = owner;
261     self->context.file = "<@no context>";
262     self->context.line = 0;
263     self->final = false;
264     MEM_VECTOR_INIT(self, instr);
265     MEM_VECTOR_INIT(self, entries);
266     MEM_VECTOR_INIT(self, exits);
267
268     self->eid = 0;
269     self->is_return = false;
270     self->run_id = 0;
271     MEM_VECTOR_INIT(self, living);
272     return self;
273 }
274 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
275 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
276 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
277 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
278
279 void ir_block_delete(ir_block* self)
280 {
281     size_t i;
282     mem_d(self->label);
283     for (i = 0; i != self->instr_count; ++i)
284         ir_instr_delete(self->instr[i]);
285     MEM_VECTOR_CLEAR(self, instr);
286     MEM_VECTOR_CLEAR(self, entries);
287     MEM_VECTOR_CLEAR(self, exits);
288     MEM_VECTOR_CLEAR(self, living);
289     mem_d(self);
290 }
291
292 bool ir_block_set_label(ir_block *self, const char *name)
293 {
294     if (self->label)
295         mem_d((void*)self->label);
296     self->label = util_strdup(name);
297     return !!self->label;
298 }
299
300 /***********************************************************************
301  *IR Instructions
302  */
303
304 ir_instr* ir_instr_new(ir_block* owner, int op)
305 {
306     ir_instr *self;
307     self = (ir_instr*)mem_a(sizeof(*self));
308     self->owner = owner;
309     self->context.file = "<@no context>";
310     self->context.line = 0;
311     self->opcode = op;
312     self->_ops[0] = NULL;
313     self->_ops[1] = NULL;
314     self->_ops[2] = NULL;
315     self->bops[0] = NULL;
316     self->bops[1] = NULL;
317     MEM_VECTOR_INIT(self, phi);
318
319     self->eid = 0;
320     return self;
321 }
322 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
323
324 void ir_instr_delete(ir_instr *self)
325 {
326     size_t i;
327     /* The following calls can only delete from
328      * vectors, we still want to delete this instruction
329      * so ignore the return value. Since with the warn_unused_result attribute
330      * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
331      * I have to improvise here and use if(foo());
332      */
333     for (i = 0; i < self->phi_count; ++i) {
334         size_t idx;
335         if (ir_value_writes_find(self->phi[i].value, self, &idx))
336             if (ir_value_writes_remove(self->phi[i].value, idx)) GMQCC_SUPRESS_EMPTY_BODY;
337         if (ir_value_reads_find(self->phi[i].value, self, &idx))
338             if (ir_value_reads_remove (self->phi[i].value, idx)) GMQCC_SUPRESS_EMPTY_BODY;
339     }
340     MEM_VECTOR_CLEAR(self, phi);
341     if (ir_instr_op(self, 0, NULL, false)) GMQCC_SUPRESS_EMPTY_BODY;
342     if (ir_instr_op(self, 1, NULL, false)) GMQCC_SUPRESS_EMPTY_BODY;
343     if (ir_instr_op(self, 2, NULL, false)) GMQCC_SUPRESS_EMPTY_BODY;
344     mem_d(self);
345 }
346
347 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
348 {
349     if (self->_ops[op]) {
350         size_t idx;
351         if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
352         {
353             if (!ir_value_writes_remove(self->_ops[op], idx))
354                 return false;
355         }
356         else if (ir_value_reads_find(self->_ops[op], self, &idx))
357         {
358             if (!ir_value_reads_remove(self->_ops[op], idx))
359                 return false;
360         }
361     }
362     if (v) {
363         if (writing) {
364             if (!ir_value_writes_add(v, self))
365                 return false;
366         } else {
367             if (!ir_value_reads_add(v, self))
368                 return false;
369         }
370     }
371     self->_ops[op] = v;
372     return true;
373 }
374
375 /***********************************************************************
376  *IR Value
377  */
378
379 ir_value* ir_value_var(const char *name, int storetype, int vtype)
380 {
381     ir_value *self;
382     self = (ir_value*)mem_a(sizeof(*self));
383     self->vtype = vtype;
384     self->store = storetype;
385     MEM_VECTOR_INIT(self, reads);
386     MEM_VECTOR_INIT(self, writes);
387     self->isconst = false;
388     self->context.file = "<@no context>";
389     self->context.line = 0;
390     self->name = NULL;
391     ir_value_set_name(self, name);
392
393     MEM_VECTOR_INIT(self, life);
394     return self;
395 }
396 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
397 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
398 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
399
400 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
401 {
402     ir_value *v = ir_value_var(name, storetype, vtype);
403     if (!v)
404         return NULL;
405     if (!ir_function_collect_value(owner, v))
406     {
407         ir_value_delete(v);
408         return NULL;
409     }
410     return v;
411 }
412
413 void ir_value_delete(ir_value* self)
414 {
415     mem_d((void*)self->name);
416     if (self->isconst)
417     {
418         if (self->vtype == TYPE_STRING)
419             mem_d((void*)self->constval.vstring);
420     }
421     MEM_VECTOR_CLEAR(self, reads);
422     MEM_VECTOR_CLEAR(self, writes);
423     MEM_VECTOR_CLEAR(self, life);
424     mem_d(self);
425 }
426
427 void ir_value_set_name(ir_value *self, const char *name)
428 {
429     if (self->name)
430         mem_d((void*)self->name);
431     self->name = util_strdup(name);
432 }
433
434 bool ir_value_set_float(ir_value *self, float f)
435 {
436     if (self->vtype != TYPE_FLOAT)
437         return false;
438     self->constval.vfloat = f;
439     self->isconst = true;
440     return true;
441 }
442
443 bool ir_value_set_vector(ir_value *self, vector v)
444 {
445     if (self->vtype != TYPE_VECTOR)
446         return false;
447     self->constval.vvec = v;
448     self->isconst = true;
449     return true;
450 }
451
452 bool ir_value_set_string(ir_value *self, const char *str)
453 {
454     if (self->vtype != TYPE_STRING)
455         return false;
456     self->constval.vstring = util_strdup(str);
457     self->isconst = true;
458     return true;
459 }
460
461 #if 0
462 bool ir_value_set_int(ir_value *self, int i)
463 {
464     if (self->vtype != TYPE_INTEGER)
465         return false;
466     self->constval.vint = i;
467     self->isconst = true;
468     return true;
469 }
470 #endif
471
472 bool ir_value_lives(ir_value *self, size_t at)
473 {
474     size_t i;
475     for (i = 0; i < self->life_count; ++i)
476     {
477         ir_life_entry_t *life = &self->life[i];
478         if (life->start <= at && at <= life->end)
479             return true;
480         if (life->start > at) /* since it's ordered */
481             return false;
482     }
483     return false;
484 }
485
486 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
487 {
488     size_t k;
489     if (!ir_value_life_add(self, e)) /* naive... */
490         return false;
491     for (k = self->life_count-1; k > idx; --k)
492         self->life[k] = self->life[k-1];
493     self->life[idx] = e;
494     return true;
495 }
496
497 bool ir_value_life_merge(ir_value *self, size_t s)
498 {
499     size_t i;
500     ir_life_entry_t *life = NULL;
501     ir_life_entry_t *before = NULL;
502     ir_life_entry_t new_entry;
503
504     /* Find the first range >= s */
505     for (i = 0; i < self->life_count; ++i)
506     {
507         before = life;
508         life = &self->life[i];
509         if (life->start > s)
510             break;
511     }
512     /* nothing found? append */
513     if (i == self->life_count) {
514         ir_life_entry_t e;
515         if (life && life->end+1 == s)
516         {
517             /* previous life range can be merged in */
518             life->end++;
519             return true;
520         }
521         if (life && life->end >= s)
522             return false;
523         e.start = e.end = s;
524         if (!ir_value_life_add(self, e))
525             return false; /* failing */
526         return true;
527     }
528     /* found */
529     if (before)
530     {
531         if (before->end + 1 == s &&
532             life->start - 1 == s)
533         {
534             /* merge */
535             before->end = life->end;
536             if (!ir_value_life_remove(self, i))
537                 return false; /* failing */
538             return true;
539         }
540         if (before->end + 1 == s)
541         {
542             /* extend before */
543             before->end++;
544             return true;
545         }
546         /* already contained */
547         if (before->end >= s)
548             return false;
549     }
550     /* extend */
551     if (life->start - 1 == s)
552     {
553         life->start--;
554         return true;
555     }
556     /* insert a new entry */
557     new_entry.start = new_entry.end = s;
558     return ir_value_life_insert(self, i, new_entry);
559 }
560
561 bool ir_values_overlap(ir_value *a, ir_value *b)
562 {
563     /* For any life entry in A see if it overlaps with
564      * any life entry in B.
565      * Note that the life entries are orderes, so we can make a
566      * more efficient algorithm there than naively translating the
567      * statement above.
568      */
569
570     ir_life_entry_t *la, *lb, *enda, *endb;
571
572     /* first of all, if either has no life range, they cannot clash */
573     if (!a->life_count || !b->life_count)
574         return false;
575
576     la = a->life;
577     lb = b->life;
578     enda = la + a->life_count;
579     endb = lb + b->life_count;
580     while (true)
581     {
582         /* check if the entries overlap, for that,
583          * both must start before the other one ends.
584          */
585         if (la->start <= lb->end &&
586             lb->start <= la->end)
587         {
588             return true;
589         }
590
591         /* entries are ordered
592          * one entry is earlier than the other
593          * that earlier entry will be moved forward
594          */
595         if (la->end < lb->end)
596         {
597             /* order: A B, move A forward
598              * check if we hit the end with A
599              */
600             if (++la == enda)
601                 break;
602         }
603         else if (lb->end < la->end)
604         {
605             /* order: B A, move B forward
606              * check if we hit the end with B
607              */
608             if (++lb == endb)
609                 break;
610         }
611     }
612     return false;
613 }
614
615 /***********************************************************************
616  *IR main operations
617  */
618
619 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
620 {
621     if (target->store == store_value) {
622         fprintf(stderr, "cannot store to an SSA value\n");
623         fprintf(stderr, "trying to store: %s <- %s\n", target->name, what->name);
624         return false;
625     } else {
626         ir_instr *in = ir_instr_new(self, op);
627         if (!in)
628             return false;
629         if (!ir_instr_op(in, 0, target, true) ||
630             !ir_instr_op(in, 1, what, false)  ||
631             !ir_block_instr_add(self, in) )
632         {
633             return false;
634         }
635         return true;
636     }
637 }
638
639 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
640 {
641     int op = 0;
642     int vtype;
643     if (target->vtype == TYPE_VARIANT)
644         vtype = what->vtype;
645     else
646         vtype = target->vtype;
647
648     switch (vtype) {
649         case TYPE_FLOAT:
650 #if 0
651             if (what->vtype == TYPE_INTEGER)
652                 op = INSTR_CONV_ITOF;
653             else
654 #endif
655                 op = INSTR_STORE_F;
656             break;
657         case TYPE_VECTOR:
658             op = INSTR_STORE_V;
659             break;
660         case TYPE_ENTITY:
661             op = INSTR_STORE_ENT;
662             break;
663         case TYPE_STRING:
664             op = INSTR_STORE_S;
665             break;
666         case TYPE_FIELD:
667             op = INSTR_STORE_FLD;
668             break;
669 #if 0
670         case TYPE_INTEGER:
671             if (what->vtype == TYPE_INTEGER)
672                 op = INSTR_CONV_FTOI;
673             else
674                 op = INSTR_STORE_I;
675             break;
676 #endif
677         case TYPE_POINTER:
678 #if 0
679             op = INSTR_STORE_I;
680 #else
681             op = INSTR_STORE_ENT;
682 #endif
683             break;
684         default:
685             /* Unknown type */
686             return false;
687     }
688     return ir_block_create_store_op(self, op, target, what);
689 }
690
691 bool ir_block_create_storep(ir_block *self, ir_value *target, ir_value *what)
692 {
693     int op = 0;
694     int vtype;
695
696     if (target->vtype != TYPE_POINTER)
697         return false;
698
699     /* storing using pointer - target is a pointer, type must be
700      * inferred from source
701      */
702     vtype = what->vtype;
703
704     switch (vtype) {
705         case TYPE_FLOAT:
706             op = INSTR_STOREP_F;
707             break;
708         case TYPE_VECTOR:
709             op = INSTR_STOREP_V;
710             break;
711         case TYPE_ENTITY:
712             op = INSTR_STOREP_ENT;
713             break;
714         case TYPE_STRING:
715             op = INSTR_STOREP_S;
716             break;
717         case TYPE_FIELD:
718             op = INSTR_STOREP_FLD;
719             break;
720 #if 0
721         case TYPE_INTEGER:
722             op = INSTR_STOREP_I;
723             break;
724 #endif
725         case TYPE_POINTER:
726 #if 0
727             op = INSTR_STOREP_I;
728 #else
729             op = INSTR_STOREP_ENT;
730 #endif
731             break;
732         default:
733             /* Unknown type */
734             return false;
735     }
736     return ir_block_create_store_op(self, op, target, what);
737 }
738
739 bool ir_block_create_return(ir_block *self, ir_value *v)
740 {
741     ir_instr *in;
742     if (self->final) {
743         fprintf(stderr, "block already ended (%s)\n", self->label);
744         return false;
745     }
746     self->final = true;
747     self->is_return = true;
748     in = ir_instr_new(self, INSTR_RETURN);
749     if (!in)
750         return false;
751
752     if (!ir_instr_op(in, 0, v, false) ||
753         !ir_block_instr_add(self, in) )
754     {
755         return false;
756     }
757     return true;
758 }
759
760 bool ir_block_create_if(ir_block *self, ir_value *v,
761                         ir_block *ontrue, ir_block *onfalse)
762 {
763     ir_instr *in;
764     if (self->final) {
765         fprintf(stderr, "block already ended (%s)\n", self->label);
766         return false;
767     }
768     self->final = true;
769     /*in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
770     in = ir_instr_new(self, VINSTR_COND);
771     if (!in)
772         return false;
773
774     if (!ir_instr_op(in, 0, v, false)) {
775         ir_instr_delete(in);
776         return false;
777     }
778
779     in->bops[0] = ontrue;
780     in->bops[1] = onfalse;
781
782     if (!ir_block_instr_add(self, in))
783         return false;
784
785     if (!ir_block_exits_add(self, ontrue)    ||
786         !ir_block_exits_add(self, onfalse)   ||
787         !ir_block_entries_add(ontrue, self)  ||
788         !ir_block_entries_add(onfalse, self) )
789     {
790         return false;
791     }
792     return true;
793 }
794
795 bool ir_block_create_jump(ir_block *self, ir_block *to)
796 {
797     ir_instr *in;
798     if (self->final) {
799         fprintf(stderr, "block already ended (%s)\n", self->label);
800         return false;
801     }
802     self->final = true;
803     in = ir_instr_new(self, VINSTR_JUMP);
804     if (!in)
805         return false;
806
807     in->bops[0] = to;
808     if (!ir_block_instr_add(self, in))
809         return false;
810
811     if (!ir_block_exits_add(self, to) ||
812         !ir_block_entries_add(to, self) )
813     {
814         return false;
815     }
816     return true;
817 }
818
819 bool ir_block_create_goto(ir_block *self, ir_block *to)
820 {
821     ir_instr *in;
822     if (self->final) {
823         fprintf(stderr, "block already ended (%s)\n", self->label);
824         return false;
825     }
826     self->final = true;
827     in = ir_instr_new(self, INSTR_GOTO);
828     if (!in)
829         return false;
830
831     in->bops[0] = to;
832     if (!ir_block_instr_add(self, in))
833         return false;
834
835     if (!ir_block_exits_add(self, to) ||
836         !ir_block_entries_add(to, self) )
837     {
838         return false;
839     }
840     return true;
841 }
842
843 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
844 {
845     ir_value *out;
846     ir_instr *in;
847     in = ir_instr_new(self, VINSTR_PHI);
848     if (!in)
849         return NULL;
850     out = ir_value_out(self->owner, label, store_value, ot);
851     if (!out) {
852         ir_instr_delete(in);
853         return NULL;
854     }
855     if (!ir_instr_op(in, 0, out, true)) {
856         ir_instr_delete(in);
857         ir_value_delete(out);
858         return NULL;
859     }
860     if (!ir_block_instr_add(self, in)) {
861         ir_instr_delete(in);
862         ir_value_delete(out);
863         return NULL;
864     }
865     return in;
866 }
867
868 ir_value* ir_phi_value(ir_instr *self)
869 {
870     return self->_ops[0];
871 }
872
873 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
874 {
875     ir_phi_entry_t pe;
876
877     if (!ir_block_entries_find(self->owner, b, NULL)) {
878         /* Must not be possible to cause this, otherwise the AST
879          * is doing something wrong.
880          */
881         fprintf(stderr, "Invalid entry block for PHI\n");
882         abort();
883     }
884
885     pe.value = v;
886     pe.from = b;
887     if (!ir_value_reads_add(v, self))
888         return false;
889     return ir_instr_phi_add(self, pe);
890 }
891
892 /* binary op related code */
893
894 ir_value* ir_block_create_binop(ir_block *self,
895                                 const char *label, int opcode,
896                                 ir_value *left, ir_value *right)
897 {
898     int ot = TYPE_VOID;
899     switch (opcode) {
900         case INSTR_ADD_F:
901         case INSTR_SUB_F:
902         case INSTR_DIV_F:
903         case INSTR_MUL_F:
904         case INSTR_MUL_V:
905         case INSTR_AND:
906         case INSTR_OR:
907 #if 0
908         case INSTR_AND_I:
909         case INSTR_AND_IF:
910         case INSTR_AND_FI:
911         case INSTR_OR_I:
912         case INSTR_OR_IF:
913         case INSTR_OR_FI:
914 #endif
915         case INSTR_BITAND:
916         case INSTR_BITOR:
917 #if 0
918         case INSTR_SUB_S: /* -- offset of string as float */
919         case INSTR_MUL_IF:
920         case INSTR_MUL_FI:
921         case INSTR_DIV_IF:
922         case INSTR_DIV_FI:
923         case INSTR_BITOR_IF:
924         case INSTR_BITOR_FI:
925         case INSTR_BITAND_FI:
926         case INSTR_BITAND_IF:
927         case INSTR_EQ_I:
928         case INSTR_NE_I:
929 #endif
930             ot = TYPE_FLOAT;
931             break;
932 #if 0
933         case INSTR_ADD_I:
934         case INSTR_ADD_IF:
935         case INSTR_ADD_FI:
936         case INSTR_SUB_I:
937         case INSTR_SUB_FI:
938         case INSTR_SUB_IF:
939         case INSTR_MUL_I:
940         case INSTR_DIV_I:
941         case INSTR_BITAND_I:
942         case INSTR_BITOR_I:
943         case INSTR_XOR_I:
944         case INSTR_RSHIFT_I:
945         case INSTR_LSHIFT_I:
946             ot = TYPE_INTEGER;
947             break;
948 #endif
949         case INSTR_ADD_V:
950         case INSTR_SUB_V:
951         case INSTR_MUL_VF:
952         case INSTR_MUL_FV:
953 #if 0
954         case INSTR_DIV_VF:
955         case INSTR_MUL_IV:
956         case INSTR_MUL_VI:
957 #endif
958             ot = TYPE_VECTOR;
959             break;
960 #if 0
961         case INSTR_ADD_SF:
962             ot = TYPE_POINTER;
963             break;
964 #endif
965         default:
966             /* ranges: */
967             /* boolean operations result in floats */
968             if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
969                 ot = TYPE_FLOAT;
970             else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
971                 ot = TYPE_FLOAT;
972 #if 0
973             else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
974                 ot = TYPE_FLOAT;
975 #endif
976             break;
977     };
978     if (ot == TYPE_VOID) {
979         /* The AST or parser were supposed to check this! */
980         return NULL;
981     }
982
983     return ir_block_create_general_instr(self, label, opcode, left, right, ot);
984 }
985
986 ir_value* ir_block_create_general_instr(ir_block *self, const char *label,
987                                         int op, ir_value *a, ir_value *b, int outype)
988 {
989     ir_instr *instr;
990     ir_value *out;
991
992     out = ir_value_out(self->owner, label, store_value, outype);
993     if (!out)
994         return NULL;
995
996     instr = ir_instr_new(self, op);
997     if (!instr) {
998         ir_value_delete(out);
999         return NULL;
1000     }
1001
1002     if (!ir_instr_op(instr, 0, out, true) ||
1003         !ir_instr_op(instr, 1, a, false) ||
1004         !ir_instr_op(instr, 2, b, false) )
1005     {
1006         goto on_error;
1007     }
1008
1009     if (!ir_block_instr_add(self, instr))
1010         goto on_error;
1011
1012     return out;
1013 on_error:
1014     ir_instr_delete(instr);
1015     ir_value_delete(out);
1016     return NULL;
1017 }
1018
1019 ir_value* ir_block_create_fieldaddress(ir_block *self, const char *label, ir_value *ent, ir_value *field)
1020 {
1021     /* Support for various pointer types todo if so desired */
1022     if (ent->vtype != TYPE_ENTITY)
1023         return NULL;
1024
1025     if (field->vtype != TYPE_FIELD)
1026         return NULL;
1027
1028     return ir_block_create_general_instr(self, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1029 }
1030
1031 ir_value* ir_block_create_load_from_ent(ir_block *self, const char *label, ir_value *ent, ir_value *field, int outype)
1032 {
1033     int op;
1034     if (ent->vtype != TYPE_ENTITY)
1035         return NULL;
1036
1037     /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1038     if (field->vtype != TYPE_FIELD)
1039         return NULL;
1040
1041     switch (outype)
1042     {
1043         case TYPE_FLOAT:   op = INSTR_LOAD_F;   break;
1044         case TYPE_VECTOR:  op = INSTR_LOAD_V;   break;
1045         case TYPE_STRING:  op = INSTR_LOAD_S;   break;
1046         case TYPE_FIELD:   op = INSTR_LOAD_FLD; break;
1047         case TYPE_ENTITY:  op = INSTR_LOAD_ENT; break;
1048 #if 0
1049         case TYPE_POINTER: op = INSTR_LOAD_I;   break;
1050         case TYPE_INTEGER: op = INSTR_LOAD_I;   break;
1051 #endif
1052         default:
1053             return NULL;
1054     }
1055
1056     return ir_block_create_general_instr(self, label, op, ent, field, outype);
1057 }
1058
1059 ir_value* ir_block_create_add(ir_block *self,
1060                               const char *label,
1061                               ir_value *left, ir_value *right)
1062 {
1063     int op = 0;
1064     int l = left->vtype;
1065     int r = right->vtype;
1066     if (l == r) {
1067         switch (l) {
1068             default:
1069                 return NULL;
1070             case TYPE_FLOAT:
1071                 op = INSTR_ADD_F;
1072                 break;
1073 #if 0
1074             case TYPE_INTEGER:
1075                 op = INSTR_ADD_I;
1076                 break;
1077 #endif
1078             case TYPE_VECTOR:
1079                 op = INSTR_ADD_V;
1080                 break;
1081         }
1082     } else {
1083 #if 0
1084         if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1085             op = INSTR_ADD_FI;
1086         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1087             op = INSTR_ADD_IF;
1088         else
1089 #endif
1090             return NULL;
1091     }
1092     return ir_block_create_binop(self, label, op, left, right);
1093 }
1094
1095 ir_value* ir_block_create_sub(ir_block *self,
1096                               const char *label,
1097                               ir_value *left, ir_value *right)
1098 {
1099     int op = 0;
1100     int l = left->vtype;
1101     int r = right->vtype;
1102     if (l == r) {
1103
1104         switch (l) {
1105             default:
1106                 return NULL;
1107             case TYPE_FLOAT:
1108                 op = INSTR_SUB_F;
1109                 break;
1110 #if 0
1111             case TYPE_INTEGER:
1112                 op = INSTR_SUB_I;
1113                 break;
1114 #endif
1115             case TYPE_VECTOR:
1116                 op = INSTR_SUB_V;
1117                 break;
1118         }
1119     } else {
1120 #if 0
1121         if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1122             op = INSTR_SUB_FI;
1123         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1124             op = INSTR_SUB_IF;
1125         else
1126 #endif
1127             return NULL;
1128     }
1129     return ir_block_create_binop(self, label, op, left, right);
1130 }
1131
1132 ir_value* ir_block_create_mul(ir_block *self,
1133                               const char *label,
1134                               ir_value *left, ir_value *right)
1135 {
1136     int op = 0;
1137     int l = left->vtype;
1138     int r = right->vtype;
1139     if (l == r) {
1140
1141         switch (l) {
1142             default:
1143                 return NULL;
1144             case TYPE_FLOAT:
1145                 op = INSTR_MUL_F;
1146                 break;
1147 #if 0
1148             case TYPE_INTEGER:
1149                 op = INSTR_MUL_I;
1150                 break;
1151 #endif
1152             case TYPE_VECTOR:
1153                 op = INSTR_MUL_V;
1154                 break;
1155         }
1156     } else {
1157         if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1158             op = INSTR_MUL_VF;
1159         else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1160             op = INSTR_MUL_FV;
1161 #if 0
1162         else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1163             op = INSTR_MUL_VI;
1164         else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1165             op = INSTR_MUL_IV;
1166         else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1167             op = INSTR_MUL_FI;
1168         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1169             op = INSTR_MUL_IF;
1170 #endif
1171         else
1172             return NULL;
1173     }
1174     return ir_block_create_binop(self, label, op, left, right);
1175 }
1176
1177 ir_value* ir_block_create_div(ir_block *self,
1178                               const char *label,
1179                               ir_value *left, ir_value *right)
1180 {
1181     int op = 0;
1182     int l = left->vtype;
1183     int r = right->vtype;
1184     if (l == r) {
1185
1186         switch (l) {
1187             default:
1188                 return NULL;
1189             case TYPE_FLOAT:
1190                 op = INSTR_DIV_F;
1191                 break;
1192 #if 0
1193             case TYPE_INTEGER:
1194                 op = INSTR_DIV_I;
1195                 break;
1196 #endif
1197         }
1198     } else {
1199 #if 0
1200         if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1201             op = INSTR_DIV_VF;
1202         else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1203             op = INSTR_DIV_FI;
1204         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1205             op = INSTR_DIV_IF;
1206         else
1207 #endif
1208             return NULL;
1209     }
1210     return ir_block_create_binop(self, label, op, left, right);
1211 }
1212
1213 /* PHI resolving breaks the SSA, and must thus be the last
1214  * step before life-range calculation.
1215  */
1216
1217 static bool ir_block_naive_phi(ir_block *self);
1218 bool ir_function_naive_phi(ir_function *self)
1219 {
1220     size_t i;
1221
1222     for (i = 0; i < self->blocks_count; ++i)
1223     {
1224         if (!ir_block_naive_phi(self->blocks[i]))
1225             return false;
1226     }
1227     return true;
1228 }
1229
1230 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1231 {
1232     ir_instr *instr;
1233     size_t i;
1234
1235     /* create a store */
1236     if (!ir_block_create_store(block, old, what))
1237         return false;
1238
1239     /* we now move it up */
1240     instr = block->instr[block->instr_count-1];
1241     for (i = block->instr_count; i > iid; --i)
1242         block->instr[i] = block->instr[i-1];
1243     block->instr[i] = instr;
1244
1245     return true;
1246 }
1247
1248 static bool ir_block_naive_phi(ir_block *self)
1249 {
1250     size_t i, p, w;
1251     /* FIXME: optionally, create_phi can add the phis
1252      * to a list so we don't need to loop through blocks
1253      * - anyway: "don't optimize YET"
1254      */
1255     for (i = 0; i < self->instr_count; ++i)
1256     {
1257         ir_instr *instr = self->instr[i];
1258         if (instr->opcode != VINSTR_PHI)
1259             continue;
1260
1261         if (!ir_block_instr_remove(self, i))
1262             return false;
1263         --i; /* NOTE: i+1 below */
1264
1265         for (p = 0; p < instr->phi_count; ++p)
1266         {
1267             ir_value *v = instr->phi[p].value;
1268             for (w = 0; w < v->writes_count; ++w) {
1269                 ir_value *old;
1270
1271                 if (!v->writes[w]->_ops[0])
1272                     continue;
1273
1274                 /* When the write was to a global, we have to emit a mov */
1275                 old = v->writes[w]->_ops[0];
1276
1277                 /* The original instruction now writes to the PHI target local */
1278                 if (v->writes[w]->_ops[0] == v)
1279                     v->writes[w]->_ops[0] = instr->_ops[0];
1280
1281                 if (old->store != store_value && old->store != store_local)
1282                 {
1283                     /* If it originally wrote to a global we need to store the value
1284                      * there as welli
1285                      */
1286                     if (!ir_naive_phi_emit_store(self, i+1, old, v))
1287                         return false;
1288                     if (i+1 < self->instr_count)
1289                         instr = self->instr[i+1];
1290                     else
1291                         instr = NULL;
1292                     /* In case I forget and access instr later, it'll be NULL
1293                      * when it's a problem, to make sure we crash, rather than accessing
1294                      * invalid data.
1295                      */
1296                 }
1297                 else
1298                 {
1299                     /* If it didn't, we can replace all reads by the phi target now. */
1300                     size_t r;
1301                     for (r = 0; r < old->reads_count; ++r)
1302                     {
1303                         size_t op;
1304                         ir_instr *ri = old->reads[r];
1305                         for (op = 0; op < ri->phi_count; ++op) {
1306                             if (ri->phi[op].value == old)
1307                                 ri->phi[op].value = v;
1308                         }
1309                         for (op = 0; op < 3; ++op) {
1310                             if (ri->_ops[op] == old)
1311                                 ri->_ops[op] = v;
1312                         }
1313                     }
1314                 }
1315             }
1316         }
1317         ir_instr_delete(instr);
1318     }
1319     return true;
1320 }
1321
1322 /***********************************************************************
1323  *IR Temp allocation code
1324  * Propagating value life ranges by walking through the function backwards
1325  * until no more changes are made.
1326  * In theory this should happen once more than once for every nested loop
1327  * level.
1328  * Though this implementation might run an additional time for if nests.
1329  */
1330
1331 typedef struct
1332 {
1333     ir_value* *v;
1334     size_t    v_count;
1335     size_t    v_alloc;
1336 } new_reads_t;
1337 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1338
1339 /* Enumerate instructions used by value's life-ranges
1340  */
1341 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1342 {
1343     size_t i;
1344     size_t eid = *_eid;
1345     for (i = 0; i < self->instr_count; ++i)
1346     {
1347         self->instr[i]->eid = eid++;
1348     }
1349     *_eid = eid;
1350 }
1351
1352 /* Enumerate blocks and instructions.
1353  * The block-enumeration is unordered!
1354  * We do not really use the block enumreation, however
1355  * the instruction enumeration is important for life-ranges.
1356  */
1357 void ir_function_enumerate(ir_function *self)
1358 {
1359     size_t i;
1360     size_t instruction_id = 0;
1361     for (i = 0; i < self->blocks_count; ++i)
1362     {
1363         self->blocks[i]->eid = i;
1364         self->blocks[i]->run_id = 0;
1365         ir_block_enumerate(self->blocks[i], &instruction_id);
1366     }
1367 }
1368
1369 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1370 bool ir_function_calculate_liferanges(ir_function *self)
1371 {
1372     size_t i;
1373     bool changed;
1374
1375     do {
1376         self->run_id++;
1377         changed = false;
1378         for (i = 0; i != self->blocks_count; ++i)
1379         {
1380             if (self->blocks[i]->is_return)
1381             {
1382                 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1383                     return false;
1384             }
1385         }
1386     } while (changed);
1387     return true;
1388 }
1389
1390 /* Get information about which operand
1391  * is read from, or written to.
1392  */
1393 static void ir_op_read_write(int op, size_t *read, size_t *write)
1394 {
1395     switch (op)
1396     {
1397     case VINSTR_JUMP:
1398     case INSTR_GOTO:
1399         *write = 0;
1400         *read = 0;
1401         break;
1402     case INSTR_IF:
1403     case INSTR_IFNOT:
1404 #if 0
1405     case INSTR_IF_S:
1406     case INSTR_IFNOT_S:
1407 #endif
1408     case INSTR_RETURN:
1409     case VINSTR_COND:
1410         *write = 0;
1411         *read = 1;
1412         break;
1413     default:
1414         *write = 1;
1415         *read = 6;
1416         break;
1417     };
1418 }
1419
1420 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1421 {
1422     size_t i;
1423     bool changed = false;
1424     bool tempbool;
1425     for (i = 0; i != self->living_count; ++i)
1426     {
1427         tempbool = ir_value_life_merge(self->living[i], eid);
1428         /* debug
1429         if (tempbool)
1430             fprintf(stderr, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1431         */
1432         changed = changed || tempbool;
1433     }
1434     return changed;
1435 }
1436
1437 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1438 {
1439     size_t i;
1440     /* values which have been read in a previous iteration are now
1441      * in the "living" array even if the previous block doesn't use them.
1442      * So we have to remove whatever does not exist in the previous block.
1443      * They will be re-added on-read, but the liferange merge won't cause
1444      * a change.
1445      */
1446     for (i = 0; i < self->living_count; ++i)
1447     {
1448         if (!ir_block_living_find(prev, self->living[i], NULL)) {
1449             if (!ir_block_living_remove(self, i))
1450                 return false;
1451             --i;
1452         }
1453     }
1454
1455     /* Whatever the previous block still has in its living set
1456      * must now be added to ours as well.
1457      */
1458     for (i = 0; i < prev->living_count; ++i)
1459     {
1460         if (ir_block_living_find(self, prev->living[i], NULL))
1461             continue;
1462         if (!ir_block_living_add(self, prev->living[i]))
1463             return false;
1464         /*
1465         printf("%s got from prev: %s\n", self->label, prev->living[i]->_name);
1466         */
1467     }
1468     return true;
1469 }
1470
1471 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
1472 {
1473     ir_instr *instr;
1474     ir_value *value;
1475     bool  tempbool;
1476     size_t i, o, p, rd;
1477     /* bitmasks which operands are read from or written to */
1478     size_t read, write;
1479     new_reads_t new_reads;
1480     char dbg_ind[16] = { '#', '0' };
1481     (void)dbg_ind;
1482
1483     MEM_VECTOR_INIT(&new_reads, v);
1484
1485     if (prev)
1486     {
1487         if (!ir_block_life_prop_previous(self, prev, changed))
1488             return false;
1489     }
1490
1491     i = self->instr_count;
1492     while (i)
1493     { --i;
1494         instr = self->instr[i];
1495
1496         /* PHI operands are always read operands */
1497         for (p = 0; p < instr->phi_count; ++p)
1498         {
1499             value = instr->phi[p].value;
1500             /* used this before new_reads - puts the last read into the life range as well
1501             if (!ir_block_living_find(self, value, NULL))
1502                 ir_block_living_add(self, value);
1503             */
1504             /* fprintf(stderr, "read: %s\n", value->_name); */
1505             if (!new_reads_t_v_find(&new_reads, value, NULL))
1506             {
1507                 if (!new_reads_t_v_add(&new_reads, value))
1508                     goto on_error;
1509             }
1510         }
1511
1512         /* See which operands are read and write operands */
1513         ir_op_read_write(instr->opcode, &read, &write);
1514
1515         /* Go through the 3 main operands */
1516         for (o = 0; o < 3; ++o)
1517         {
1518             if (!instr->_ops[o]) /* no such operand */
1519                 continue;
1520
1521             value = instr->_ops[o];
1522
1523             /* We only care about locals */
1524             if (value->store != store_value &&
1525                 value->store != store_local)
1526                 continue;
1527
1528             /* read operands */
1529             if (read & (1<<o))
1530             {
1531                 /* used this before new_reads - puts the last read into the life range as well
1532                 if (!ir_block_living_find(self, value, NULL))
1533                     ir_block_living_add(self, value);
1534                 */
1535                 /* fprintf(stderr, "read: %s\n", value->_name); */
1536                 if (!new_reads_t_v_find(&new_reads, value, NULL))
1537                 {
1538                     if (!new_reads_t_v_add(&new_reads, value))
1539                         goto on_error;
1540                 }
1541             }
1542
1543             /* write operands */
1544             /* When we write to a local, we consider it "dead" for the
1545              * remaining upper part of the function, since in SSA a value
1546              * can only be written once (== created)
1547              */
1548             if (write & (1<<o))
1549             {
1550                 size_t idx, readidx;
1551                 bool in_living = ir_block_living_find(self, value, &idx);
1552                 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
1553                 if (!in_living && !in_reads)
1554                 {
1555                     /* If the value isn't alive it hasn't been read before... */
1556                     /* TODO: See if the warning can be emitted during parsing or AST processing
1557                      * otherwise have warning printed here.
1558                      * IF printing a warning here: include filecontext_t,
1559                      * and make sure it's only printed once
1560                      * since this function is run multiple times.
1561                      */
1562                     /* For now: debug info: */
1563                     fprintf(stderr, "Value only written %s\n", value->name);
1564                     tempbool = ir_value_life_merge(value, instr->eid);
1565                     *changed = *changed || tempbool;
1566                     /*
1567                     ir_instr_dump(instr, dbg_ind, printf);
1568                     abort();
1569                     */
1570                 } else {
1571                     /* since 'living' won't contain it
1572                      * anymore, merge the value, since
1573                      * (A) doesn't.
1574                      */
1575                     tempbool = ir_value_life_merge(value, instr->eid);
1576                     /*
1577                     if (tempbool)
1578                         fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
1579                     */
1580                     *changed = *changed || tempbool;
1581                     /* Then remove */
1582                     if (!ir_block_living_remove(self, idx))
1583                         goto on_error;
1584                     if (in_reads)
1585                     {
1586                         if (!new_reads_t_v_remove(&new_reads, readidx))
1587                             goto on_error;
1588                     }
1589                 }
1590             }
1591         }
1592         /* (A) */
1593         tempbool = ir_block_living_add_instr(self, instr->eid);
1594         /*fprintf(stderr, "living added values\n");*/
1595         *changed = *changed || tempbool;
1596
1597         /* new reads: */
1598         for (rd = 0; rd < new_reads.v_count; ++rd)
1599         {
1600             if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
1601                 if (!ir_block_living_add(self, new_reads.v[rd]))
1602                     goto on_error;
1603             }
1604             if (!i && !self->entries_count) {
1605                 /* fix the top */
1606                 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
1607             }
1608         }
1609         MEM_VECTOR_CLEAR(&new_reads, v);
1610     }
1611
1612     if (self->run_id == self->owner->run_id)
1613         return true;
1614
1615     self->run_id = self->owner->run_id;
1616
1617     for (i = 0; i < self->entries_count; ++i)
1618     {
1619         ir_block *entry = self->entries[i];
1620         ir_block_life_propagate(entry, self, changed);
1621     }
1622
1623     return true;
1624 on_error:
1625     MEM_VECTOR_CLEAR(&new_reads, v);
1626     return false;
1627 }
1628
1629 /***********************************************************************
1630  *IR DEBUG Dump functions...
1631  */
1632
1633 #define IND_BUFSZ 1024
1634
1635 const char *qc_opname(int op)
1636 {
1637     if (op < 0) return "<INVALID>";
1638     if (op < ( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
1639         return asm_instr[op].m;
1640     switch (op) {
1641         case VINSTR_PHI:  return "PHI";
1642         case VINSTR_JUMP: return "JUMP";
1643         case VINSTR_COND: return "COND";
1644         default:          return "<UNK>";
1645     }
1646 }
1647
1648 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
1649 {
1650         size_t i;
1651         char indent[IND_BUFSZ];
1652         indent[0] = '\t';
1653         indent[1] = 0;
1654
1655         oprintf("module %s\n", b->name);
1656         for (i = 0; i < b->globals_count; ++i)
1657         {
1658                 oprintf("global ");
1659                 if (b->globals[i]->isconst)
1660                         oprintf("%s = ", b->globals[i]->name);
1661                 ir_value_dump(b->globals[i], oprintf);
1662                 oprintf("\n");
1663         }
1664         for (i = 0; i < b->functions_count; ++i)
1665                 ir_function_dump(b->functions[i], indent, oprintf);
1666         oprintf("endmodule %s\n", b->name);
1667 }
1668
1669 void ir_function_dump(ir_function *f, char *ind,
1670                       int (*oprintf)(const char*, ...))
1671 {
1672         size_t i;
1673         oprintf("%sfunction %s\n", ind, f->name);
1674         strncat(ind, "\t", IND_BUFSZ);
1675         if (f->locals_count)
1676         {
1677                 oprintf("%s%i locals:\n", ind, (int)f->locals_count);
1678                 for (i = 0; i < f->locals_count; ++i) {
1679                         oprintf("%s\t", ind);
1680                         ir_value_dump(f->locals[i], oprintf);
1681                         oprintf("\n");
1682                 }
1683         }
1684         if (f->blocks_count)
1685         {
1686
1687                 oprintf("%slife passes: %i\n", ind, (int)f->blocks[0]->run_id);
1688                 for (i = 0; i < f->blocks_count; ++i)
1689                         ir_block_dump(f->blocks[i], ind, oprintf);
1690
1691         }
1692         ind[strlen(ind)-1] = 0;
1693         oprintf("%sendfunction %s\n", ind, f->name);
1694 }
1695
1696 void ir_block_dump(ir_block* b, char *ind,
1697                    int (*oprintf)(const char*, ...))
1698 {
1699         size_t i;
1700         oprintf("%s:%s\n", ind, b->label);
1701         strncat(ind, "\t", IND_BUFSZ);
1702
1703         for (i = 0; i < b->instr_count; ++i)
1704                 ir_instr_dump(b->instr[i], ind, oprintf);
1705         ind[strlen(ind)-1] = 0;
1706 }
1707
1708 void dump_phi(ir_instr *in, char *ind,
1709               int (*oprintf)(const char*, ...))
1710 {
1711         size_t i;
1712         oprintf("%s <- phi ", in->_ops[0]->name);
1713         for (i = 0; i < in->phi_count; ++i)
1714         {
1715                 oprintf("([%s] : %s) ", in->phi[i].from->label,
1716                                         in->phi[i].value->name);
1717         }
1718         oprintf("\n");
1719 }
1720
1721 void ir_instr_dump(ir_instr *in, char *ind,
1722                        int (*oprintf)(const char*, ...))
1723 {
1724         size_t i;
1725         const char *comma = NULL;
1726
1727         oprintf("%s (%i) ", ind, (int)in->eid);
1728
1729         if (in->opcode == VINSTR_PHI) {
1730                 dump_phi(in, ind, oprintf);
1731                 return;
1732         }
1733
1734         strncat(ind, "\t", IND_BUFSZ);
1735
1736         if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
1737                 ir_value_dump(in->_ops[0], oprintf);
1738                 if (in->_ops[1] || in->_ops[2])
1739                         oprintf(" <- ");
1740         }
1741         oprintf("%s\t", qc_opname(in->opcode));
1742         if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
1743                 ir_value_dump(in->_ops[0], oprintf);
1744                 comma = ",\t";
1745         }
1746         else
1747         {
1748                 for (i = 1; i != 3; ++i) {
1749                         if (in->_ops[i]) {
1750                                 if (comma)
1751                                         oprintf(comma);
1752                                 ir_value_dump(in->_ops[i], oprintf);
1753                                 comma = ",\t";
1754                         }
1755                 }
1756         }
1757         if (in->bops[0]) {
1758                 if (comma)
1759                         oprintf(comma);
1760                 oprintf("[%s]", in->bops[0]->label);
1761                 comma = ",\t";
1762         }
1763         if (in->bops[1])
1764                 oprintf("%s[%s]", comma, in->bops[1]->label);
1765         oprintf("\n");
1766         ind[strlen(ind)-1] = 0;
1767 }
1768
1769 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
1770 {
1771         if (v->isconst) {
1772                 switch (v->vtype) {
1773                         case TYPE_VOID:
1774                                 oprintf("(void)");
1775                                 break;
1776                         case TYPE_FLOAT:
1777                                 oprintf("%g", v->constval.vfloat);
1778                                 break;
1779                         case TYPE_VECTOR:
1780                                 oprintf("'%g %g %g'",
1781                                         v->constval.vvec.x,
1782                                         v->constval.vvec.y,
1783                                         v->constval.vvec.z);
1784                                 break;
1785                         case TYPE_ENTITY:
1786                                 oprintf("(entity)");
1787                                 break;
1788                         case TYPE_STRING:
1789                                 oprintf("\"%s\"", v->constval.vstring);
1790                                 break;
1791 #if 0
1792                         case TYPE_INTEGER:
1793                                 oprintf("%i", v->constval.vint);
1794                                 break;
1795 #endif
1796                         case TYPE_POINTER:
1797                                 oprintf("&%s",
1798                                         v->constval.vpointer->name);
1799                                 break;
1800                 }
1801         } else {
1802                 oprintf("%s", v->name);
1803         }
1804 }
1805
1806 void ir_value_dump_life(ir_value *self, int (*oprintf)(const char*,...))
1807 {
1808         size_t i;
1809         oprintf("Life of %s:\n", self->name);
1810         for (i = 0; i < self->life_count; ++i)
1811         {
1812                 oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);
1813         }
1814 }