]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ir.c
8c467ad99d5c0011b616f2b158376f24da42fadc
[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     if (!ir_function_set_name(self, "<@unnamed>")) {
144         mem_d(self);
145         return NULL;
146     }
147     self->owner = owner;
148     self->context.file = "<@no context>";
149     self->context.line = 0;
150     self->retype = TYPE_VOID;
151     MEM_VECTOR_INIT(self, params);
152     MEM_VECTOR_INIT(self, blocks);
153     MEM_VECTOR_INIT(self, values);
154     MEM_VECTOR_INIT(self, locals);
155
156     self->run_id = 0;
157     return self;
158 }
159 MEM_VEC_FUNCTIONS(ir_function, ir_value*, values)
160 MEM_VEC_FUNCTIONS(ir_function, ir_block*, blocks)
161 MEM_VEC_FUNCTIONS(ir_function, ir_value*, locals)
162
163 bool ir_function_set_name(ir_function *self, const char *name)
164 {
165     if (self->name)
166         mem_d((void*)self->name);
167     self->name = util_strdup(name);
168     return !!self->name;
169 }
170
171 void ir_function_delete(ir_function *self)
172 {
173     size_t i;
174     mem_d((void*)self->name);
175
176     for (i = 0; i != self->blocks_count; ++i)
177         ir_block_delete(self->blocks[i]);
178     MEM_VECTOR_CLEAR(self, blocks);
179
180     MEM_VECTOR_CLEAR(self, params);
181
182     for (i = 0; i != self->values_count; ++i)
183         ir_value_delete(self->values[i]);
184     MEM_VECTOR_CLEAR(self, values);
185
186     for (i = 0; i != self->locals_count; ++i)
187         ir_value_delete(self->locals[i]);
188     MEM_VECTOR_CLEAR(self, locals);
189
190     mem_d(self);
191 }
192
193 bool GMQCC_WARN ir_function_collect_value(ir_function *self, ir_value *v)
194 {
195     return ir_function_values_add(self, v);
196 }
197
198 ir_block* ir_function_create_block(ir_function *self, const char *label)
199 {
200     ir_block* bn = ir_block_new(self, label);
201     memcpy(&bn->context, &self->context, sizeof(self->context));
202     if (!ir_function_blocks_add(self, bn)) {
203         ir_block_delete(bn);
204         return NULL;
205     }
206     return bn;
207 }
208
209 bool ir_function_finalize(ir_function *self)
210 {
211     if (!ir_function_naive_phi(self))
212         return false;
213
214     ir_function_enumerate(self);
215
216     if (!ir_function_calculate_liferanges(self))
217         return false;
218     return true;
219 }
220
221 ir_value* ir_function_get_local(ir_function *self, const char *name)
222 {
223     size_t i;
224     for (i = 0; i < self->locals_count; ++i) {
225         if (!strcmp(self->locals[i]->name, name))
226             return self->locals[i];
227     }
228     return NULL;
229 }
230
231 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype)
232 {
233     ir_value *ve = ir_function_get_local(self, name);
234     if (ve) {
235         return NULL;
236     }
237
238     ve = ir_value_var(name, store_local, vtype);
239     if (!ir_function_locals_add(self, ve)) {
240         ir_value_delete(ve);
241         return NULL;
242     }
243     return ve;
244 }
245
246 /***********************************************************************
247  *IR Block
248  */
249
250 ir_block* ir_block_new(ir_function* owner, const char *name)
251 {
252     ir_block *self;
253     self = (ir_block*)mem_a(sizeof(*self));
254     if (!ir_block_set_label(self, name)) {
255         mem_d(self);
256         return NULL;
257     }
258     self->owner = owner;
259     self->context.file = "<@no context>";
260     self->context.line = 0;
261     self->final = false;
262     MEM_VECTOR_INIT(self, instr);
263     MEM_VECTOR_INIT(self, entries);
264     MEM_VECTOR_INIT(self, exits);
265     self->label = NULL;
266
267     self->eid = 0;
268     self->is_return = false;
269     self->run_id = 0;
270     MEM_VECTOR_INIT(self, living);
271     return self;
272 }
273 MEM_VEC_FUNCTIONS(ir_block, ir_instr*, instr)
274 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, entries)
275 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_block*, exits)
276 MEM_VEC_FUNCTIONS_ALL(ir_block, ir_value*, living)
277
278 void ir_block_delete(ir_block* self)
279 {
280     size_t i;
281     mem_d((void*)self->label);
282     for (i = 0; i != self->instr_count; ++i)
283         ir_instr_delete(self->instr[i]);
284     MEM_VECTOR_CLEAR(self, instr);
285     MEM_VECTOR_CLEAR(self, entries);
286     MEM_VECTOR_CLEAR(self, exits);
287     MEM_VECTOR_CLEAR(self, living);
288     mem_d(self);
289 }
290
291 bool ir_block_set_label(ir_block *self, const char *name)
292 {
293     if (self->label)
294         mem_d((void*)self->label);
295     self->label = util_strdup(name);
296     return !!self->label;
297 }
298
299 /***********************************************************************
300  *IR Instructions
301  */
302
303 ir_instr* ir_instr_new(ir_block* owner, int op)
304 {
305     ir_instr *self;
306     self = (ir_instr*)mem_a(sizeof(*self));
307     self->owner = owner;
308     self->context.file = "<@no context>";
309     self->context.line = 0;
310     self->opcode = op;
311     self->_ops[0] = NULL;
312     self->_ops[1] = NULL;
313     self->_ops[2] = NULL;
314     self->bops[0] = NULL;
315     self->bops[1] = NULL;
316     MEM_VECTOR_INIT(self, phi);
317
318     self->eid = 0;
319     return self;
320 }
321 MEM_VEC_FUNCTIONS(ir_instr, ir_phi_entry_t, phi)
322
323 void ir_instr_delete(ir_instr *self)
324 {
325     size_t i;
326     /* The following calls can only delete from
327      * vectors, we still want to delete this instruction
328      * so ignore the return value. Since with the warn_unused_result attribute
329      * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
330      * I have to improvise here and use if(foo());
331      */
332     for (i = 0; i < self->phi_count; ++i) {
333         size_t idx;
334         if (ir_value_writes_find(self->phi[i].value, self, &idx))
335             if (ir_value_writes_remove(self->phi[i].value, idx));
336         if (ir_value_reads_find(self->phi[i].value, self, &idx))
337             if (ir_value_reads_remove(self->phi[i].value, idx));
338     }
339     MEM_VECTOR_CLEAR(self, phi);
340     if (ir_instr_op(self, 0, NULL, false));
341     if (ir_instr_op(self, 1, NULL, false));
342     if (ir_instr_op(self, 2, NULL, false));
343     mem_d(self);
344 }
345
346 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
347 {
348     if (self->_ops[op]) {
349         size_t idx;
350         if (writing && ir_value_writes_find(self->_ops[op], self, &idx))
351         {
352             if (!ir_value_writes_remove(self->_ops[op], idx))
353                 return false;
354         }
355         else if (ir_value_reads_find(self->_ops[op], self, &idx))
356         {
357             if (!ir_value_reads_remove(self->_ops[op], idx))
358                 return false;
359         }
360     }
361     if (v) {
362         if (writing) {
363             if (!ir_value_writes_add(v, self))
364                 return false;
365         } else {
366             if (!ir_value_reads_add(v, self))
367                 return false;
368         }
369     }
370     self->_ops[op] = v;
371     return true;
372 }
373
374 /***********************************************************************
375  *IR Value
376  */
377
378 ir_value* ir_value_var(const char *name, int storetype, int vtype)
379 {
380     ir_value *self;
381     self = (ir_value*)mem_a(sizeof(*self));
382     self->vtype = vtype;
383     self->store = storetype;
384     MEM_VECTOR_INIT(self, reads);
385     MEM_VECTOR_INIT(self, writes);
386     self->isconst = false;
387     self->context.file = "<@no context>";
388     self->context.line = 0;
389     self->name = NULL;
390     ir_value_set_name(self, name);
391
392     MEM_VECTOR_INIT(self, life);
393     return self;
394 }
395 MEM_VEC_FUNCTIONS(ir_value, ir_life_entry_t, life)
396 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, reads)
397 MEM_VEC_FUNCTIONS_ALL(ir_value, ir_instr*, writes)
398
399 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
400 {
401     ir_value *v = ir_value_var(name, storetype, vtype);
402     if (!v)
403         return NULL;
404     if (!ir_function_collect_value(owner, v))
405     {
406         ir_value_delete(v);
407         return NULL;
408     }
409     return v;
410 }
411
412 void ir_value_delete(ir_value* self)
413 {
414     mem_d((void*)self->name);
415     if (self->isconst)
416     {
417         if (self->vtype == TYPE_STRING)
418             mem_d((void*)self->constval.vstring);
419     }
420     MEM_VECTOR_CLEAR(self, reads);
421     MEM_VECTOR_CLEAR(self, writes);
422     MEM_VECTOR_CLEAR(self, life);
423     mem_d(self);
424 }
425
426 void ir_value_set_name(ir_value *self, const char *name)
427 {
428     if (self->name)
429         mem_d((void*)self->name);
430     self->name = util_strdup(name);
431 }
432
433 bool ir_value_set_float(ir_value *self, float f)
434 {
435     if (self->vtype != TYPE_FLOAT)
436         return false;
437     self->constval.vfloat = f;
438     self->isconst = true;
439     return true;
440 }
441
442 bool ir_value_set_vector(ir_value *self, vector v)
443 {
444     if (self->vtype != TYPE_VECTOR)
445         return false;
446     self->constval.vvec = v;
447     self->isconst = true;
448     return true;
449 }
450
451 bool ir_value_set_string(ir_value *self, const char *str)
452 {
453     if (self->vtype != TYPE_STRING)
454         return false;
455     self->constval.vstring = util_strdup(str);
456     self->isconst = true;
457     return true;
458 }
459
460 #if 0
461 bool ir_value_set_int(ir_value *self, int i)
462 {
463     if (self->vtype != TYPE_INTEGER)
464         return false;
465     self->constval.vint = i;
466     self->isconst = true;
467     return true;
468 }
469 #endif
470
471 bool ir_value_lives(ir_value *self, size_t at)
472 {
473     size_t i;
474     for (i = 0; i < self->life_count; ++i)
475     {
476         ir_life_entry_t *life = &self->life[i];
477         if (life->start <= at && at <= life->end)
478             return true;
479         if (life->start > at) /* since it's ordered */
480             return false;
481     }
482     return false;
483 }
484
485 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
486 {
487     size_t k;
488     if (!ir_value_life_add(self, e)) /* naive... */
489         return false;
490     for (k = self->life_count-1; k > idx; --k)
491         self->life[k] = self->life[k-1];
492     self->life[idx] = e;
493     return true;
494 }
495
496 bool ir_value_life_merge(ir_value *self, size_t s)
497 {
498     size_t i;
499     ir_life_entry_t *life = NULL;
500     ir_life_entry_t *before = NULL;
501     ir_life_entry_t new_entry;
502
503     /* Find the first range >= s */
504     for (i = 0; i < self->life_count; ++i)
505     {
506         before = life;
507         life = &self->life[i];
508         if (life->start > s)
509             break;
510     }
511     /* nothing found? append */
512     if (i == self->life_count) {
513         if (life && life->end+1 == s)
514         {
515             /* previous life range can be merged in */
516             life->end++;
517             return true;
518         }
519         if (life && life->end >= s)
520             return false;
521         ir_life_entry_t e;
522         e.start = e.end = s;
523         if (!ir_value_life_add(self, e))
524             return false; /* failing */
525         return true;
526     }
527     /* found */
528     if (before)
529     {
530         if (before->end + 1 == s &&
531             life->start - 1 == s)
532         {
533             /* merge */
534             before->end = life->end;
535             if (!ir_value_life_remove(self, i))
536                 return false; /* failing */
537             return true;
538         }
539         if (before->end + 1 == s)
540         {
541             /* extend before */
542             before->end++;
543             return true;
544         }
545         /* already contained */
546         if (before->end >= s)
547             return false;
548     }
549     /* extend */
550     if (life->start - 1 == s)
551     {
552         life->start--;
553         return true;
554     }
555     /* insert a new entry */
556     new_entry.start = new_entry.end = s;
557     return ir_value_life_insert(self, i, new_entry);
558 }
559
560 /***********************************************************************
561  *IR main operations
562  */
563
564 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
565 {
566     if (target->store == store_value) {
567         fprintf(stderr, "cannot store to an SSA value\n");
568         return false;
569     } else {
570         ir_instr *in = ir_instr_new(self, op);
571         if (!in)
572             return false;
573         if (!ir_instr_op(in, 0, target, true) ||
574             !ir_instr_op(in, 1, what, false)  ||
575             !ir_block_instr_add(self, in) )
576         {
577             return false;
578         }
579         return true;
580     }
581 }
582
583 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
584 {
585     int op = 0;
586     int vtype;
587     if (target->vtype == TYPE_VARIANT)
588         vtype = what->vtype;
589     else
590         vtype = target->vtype;
591
592     switch (vtype) {
593         case TYPE_FLOAT:
594 #if 0
595             if (what->vtype == TYPE_INTEGER)
596                 op = INSTR_CONV_ITOF;
597             else
598 #endif
599                 op = INSTR_STORE_F;
600             break;
601         case TYPE_VECTOR:
602             op = INSTR_STORE_V;
603             break;
604         case TYPE_ENTITY:
605             op = INSTR_STORE_ENT;
606             break;
607         case TYPE_STRING:
608             op = INSTR_STORE_S;
609             break;
610 #if 0
611         case TYPE_INTEGER:
612             if (what->vtype == TYPE_INTEGER)
613                 op = INSTR_CONV_FTOI;
614             else
615                 op = INSTR_STORE_I;
616             break;
617 #endif
618         case TYPE_POINTER:
619 #if 0
620             op = INSTR_STORE_I;
621 #else
622             op = INSTR_STORE_ENT;
623 #endif
624             break;
625     }
626     return ir_block_create_store_op(self, op, target, what);
627 }
628
629 bool ir_block_create_return(ir_block *self, ir_value *v)
630 {
631     ir_instr *in;
632     if (self->final) {
633         fprintf(stderr, "block already ended (%s)\n", self->label);
634         return false;
635     }
636     self->final = true;
637     self->is_return = true;
638     in = ir_instr_new(self, INSTR_RETURN);
639     if (!in)
640         return false;
641
642     if (!ir_instr_op(in, 0, v, false) ||
643         !ir_block_instr_add(self, in) )
644     {
645         return false;
646     }
647     return true;
648 }
649
650 bool ir_block_create_if(ir_block *self, ir_value *v,
651                         ir_block *ontrue, ir_block *onfalse)
652 {
653     ir_instr *in;
654     if (self->final) {
655         fprintf(stderr, "block already ended (%s)\n", self->label);
656         return false;
657     }
658     self->final = true;
659     //in = ir_instr_new(self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));
660     in = ir_instr_new(self, VINSTR_COND);
661     if (!in)
662         return false;
663
664     if (!ir_instr_op(in, 0, v, false)) {
665         ir_instr_delete(in);
666         return false;
667     }
668
669     in->bops[0] = ontrue;
670     in->bops[1] = onfalse;
671
672     if (!ir_block_instr_add(self, in))
673         return false;
674
675     if (!ir_block_exits_add(self, ontrue)    ||
676         !ir_block_exits_add(self, onfalse)   ||
677         !ir_block_entries_add(ontrue, self)  ||
678         !ir_block_entries_add(onfalse, self) )
679     {
680         return false;
681     }
682     return true;
683 }
684
685 bool ir_block_create_jump(ir_block *self, ir_block *to)
686 {
687     ir_instr *in;
688     if (self->final) {
689         fprintf(stderr, "block already ended (%s)\n", self->label);
690         return false;
691     }
692     self->final = true;
693     in = ir_instr_new(self, VINSTR_JUMP);
694     if (!in)
695         return false;
696
697     in->bops[0] = to;
698     if (!ir_block_instr_add(self, in))
699         return false;
700
701     if (!ir_block_exits_add(self, to) ||
702         !ir_block_entries_add(to, self) )
703     {
704         return false;
705     }
706     return true;
707 }
708
709 bool ir_block_create_goto(ir_block *self, ir_block *to)
710 {
711     ir_instr *in;
712     if (self->final) {
713         fprintf(stderr, "block already ended (%s)\n", self->label);
714         return false;
715     }
716     self->final = true;
717     in = ir_instr_new(self, INSTR_GOTO);
718     if (!in)
719         return false;
720
721     in->bops[0] = to;
722     if (!ir_block_instr_add(self, in))
723         return false;
724
725     if (!ir_block_exits_add(self, to) ||
726         !ir_block_entries_add(to, self) )
727     {
728         return false;
729     }
730     return true;
731 }
732
733 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
734 {
735     ir_value *out;
736     ir_instr *in;
737     in = ir_instr_new(self, VINSTR_PHI);
738     if (!in)
739         return NULL;
740     out = ir_value_out(self->owner, label, store_local, ot);
741     if (!out) {
742         ir_instr_delete(in);
743         return NULL;
744     }
745     if (!ir_instr_op(in, 0, out, true)) {
746         ir_instr_delete(in);
747         ir_value_delete(out);
748         return NULL;
749     }
750     if (!ir_block_instr_add(self, in)) {
751         ir_instr_delete(in);
752         ir_value_delete(out);
753         return NULL;
754     }
755     return in;
756 }
757
758 ir_value* ir_phi_value(ir_instr *self)
759 {
760     return self->_ops[0];
761 }
762
763 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
764 {
765     ir_phi_entry_t pe;
766
767     if (!ir_block_entries_find(self->owner, b, NULL)) {
768         /* Must not be possible to cause this, otherwise the AST
769          * is doing something wrong.
770          */
771         fprintf(stderr, "Invalid entry block for PHI\n");
772         abort();
773     }
774
775     pe.value = v;
776     pe.from = b;
777     if (!ir_value_reads_add(v, self))
778         return false;
779     return ir_instr_phi_add(self, pe);
780 }
781
782 /* binary op related code */
783
784 ir_value* ir_block_create_binop(ir_block *self,
785                                 const char *label, int opcode,
786                                 ir_value *left, ir_value *right)
787 {
788     int ot = TYPE_VOID;
789     switch (opcode) {
790         case INSTR_ADD_F:
791         case INSTR_SUB_F:
792         case INSTR_DIV_F:
793         case INSTR_MUL_F:
794         case INSTR_MUL_V:
795         case INSTR_AND:
796         case INSTR_OR:
797 #if 0
798         case INSTR_AND_I:
799         case INSTR_AND_IF:
800         case INSTR_AND_FI:
801         case INSTR_OR_I:
802         case INSTR_OR_IF:
803         case INSTR_OR_FI:
804 #endif
805         case INSTR_BITAND:
806         case INSTR_BITOR:
807 #if 0
808         case INSTR_SUB_S: /* -- offset of string as float */
809         case INSTR_MUL_IF:
810         case INSTR_MUL_FI:
811         case INSTR_DIV_IF:
812         case INSTR_DIV_FI:
813         case INSTR_BITOR_IF:
814         case INSTR_BITOR_FI:
815         case INSTR_BITAND_FI:
816         case INSTR_BITAND_IF:
817         case INSTR_EQ_I:
818         case INSTR_NE_I:
819 #endif
820             ot = TYPE_FLOAT;
821             break;
822 #if 0
823         case INSTR_ADD_I:
824         case INSTR_ADD_IF:
825         case INSTR_ADD_FI:
826         case INSTR_SUB_I:
827         case INSTR_SUB_FI:
828         case INSTR_SUB_IF:
829         case INSTR_MUL_I:
830         case INSTR_DIV_I:
831         case INSTR_BITAND_I:
832         case INSTR_BITOR_I:
833         case INSTR_XOR_I:
834         case INSTR_RSHIFT_I:
835         case INSTR_LSHIFT_I:
836             ot = TYPE_INTEGER;
837             break;
838 #endif
839         case INSTR_ADD_V:
840         case INSTR_SUB_V:
841         case INSTR_MUL_VF:
842         case INSTR_MUL_FV:
843 #if 0
844         case INSTR_DIV_VF:
845         case INSTR_MUL_IV:
846         case INSTR_MUL_VI:
847 #endif
848             ot = TYPE_VECTOR;
849             break;
850 #if 0
851         case INSTR_ADD_SF:
852             ot = TYPE_POINTER;
853             break;
854 #endif
855         default:
856             // ranges:
857             /* boolean operations result in floats */
858             if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
859                 ot = TYPE_FLOAT;
860             else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
861                 ot = TYPE_FLOAT;
862 #if 0
863             else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
864                 ot = TYPE_FLOAT;
865 #endif
866             break;
867     };
868     if (ot == TYPE_VOID) {
869         /* The AST or parser were supposed to check this! */
870         return NULL;
871     }
872
873     ir_value *out = ir_value_out(self->owner, label, store_local, ot);
874     if (!out)
875         return NULL;
876
877     ir_instr *in = ir_instr_new(self, opcode);
878     if (!in) {
879         ir_value_delete(out);
880         return NULL;
881     }
882
883     if (!ir_instr_op(in, 0, out, true) ||
884         !ir_instr_op(in, 1, left, false) ||
885         !ir_instr_op(in, 2, right, false) )
886     {
887         goto on_error;
888     }
889
890     if (!ir_block_instr_add(self, in))
891         goto on_error;
892
893     return out;
894 on_error:
895     ir_value_delete(out);
896     ir_instr_delete(in);
897     return NULL;
898 }
899
900 ir_value* ir_block_create_add(ir_block *self,
901                               const char *label,
902                               ir_value *left, ir_value *right)
903 {
904     int op = 0;
905     int l = left->vtype;
906     int r = right->vtype;
907     if (l == r) {
908         switch (l) {
909             default:
910                 return NULL;
911             case TYPE_FLOAT:
912                 op = INSTR_ADD_F;
913                 break;
914 #if 0
915             case TYPE_INTEGER:
916                 op = INSTR_ADD_I;
917                 break;
918 #endif
919             case TYPE_VECTOR:
920                 op = INSTR_ADD_V;
921                 break;
922         }
923     } else {
924 #if 0
925         if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
926             op = INSTR_ADD_FI;
927         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
928             op = INSTR_ADD_IF;
929         else
930 #endif
931             return NULL;
932     }
933     return ir_block_create_binop(self, label, op, left, right);
934 }
935
936 ir_value* ir_block_create_sub(ir_block *self,
937                               const char *label,
938                               ir_value *left, ir_value *right)
939 {
940     int op = 0;
941     int l = left->vtype;
942     int r = right->vtype;
943     if (l == r) {
944
945         switch (l) {
946             default:
947                 return NULL;
948             case TYPE_FLOAT:
949                 op = INSTR_SUB_F;
950                 break;
951 #if 0
952             case TYPE_INTEGER:
953                 op = INSTR_SUB_I;
954                 break;
955 #endif
956             case TYPE_VECTOR:
957                 op = INSTR_SUB_V;
958                 break;
959         }
960     } else {
961 #if 0
962         if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
963             op = INSTR_SUB_FI;
964         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
965             op = INSTR_SUB_IF;
966         else
967 #endif
968             return NULL;
969     }
970     return ir_block_create_binop(self, label, op, left, right);
971 }
972
973 ir_value* ir_block_create_mul(ir_block *self,
974                               const char *label,
975                               ir_value *left, ir_value *right)
976 {
977     int op = 0;
978     int l = left->vtype;
979     int r = right->vtype;
980     if (l == r) {
981
982         switch (l) {
983             default:
984                 return NULL;
985             case TYPE_FLOAT:
986                 op = INSTR_MUL_F;
987                 break;
988 #if 0
989             case TYPE_INTEGER:
990                 op = INSTR_MUL_I;
991                 break;
992 #endif
993             case TYPE_VECTOR:
994                 op = INSTR_MUL_V;
995                 break;
996         }
997     } else {
998         if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
999             op = INSTR_MUL_VF;
1000         else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1001             op = INSTR_MUL_FV;
1002 #if 0
1003         else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1004             op = INSTR_MUL_VI;
1005         else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1006             op = INSTR_MUL_IV;
1007         else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1008             op = INSTR_MUL_FI;
1009         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1010             op = INSTR_MUL_IF;
1011 #endif
1012         else
1013             return NULL;
1014     }
1015     return ir_block_create_binop(self, label, op, left, right);
1016 }
1017
1018 ir_value* ir_block_create_div(ir_block *self,
1019                               const char *label,
1020                               ir_value *left, ir_value *right)
1021 {
1022     int op = 0;
1023     int l = left->vtype;
1024     int r = right->vtype;
1025     if (l == r) {
1026
1027         switch (l) {
1028             default:
1029                 return NULL;
1030             case TYPE_FLOAT:
1031                 op = INSTR_DIV_F;
1032                 break;
1033 #if 0
1034             case TYPE_INTEGER:
1035                 op = INSTR_DIV_I;
1036                 break;
1037 #endif
1038         }
1039     } else {
1040 #if 0
1041         if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1042             op = INSTR_DIV_VF;
1043         else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1044             op = INSTR_DIV_FI;
1045         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1046             op = INSTR_DIV_IF;
1047         else
1048 #endif
1049             return NULL;
1050     }
1051     return ir_block_create_binop(self, label, op, left, right);
1052 }
1053
1054 /* PHI resolving breaks the SSA, and must thus be the last
1055  * step before life-range calculation.
1056  */
1057
1058 static bool ir_block_naive_phi(ir_block *self);
1059 bool ir_function_naive_phi(ir_function *self)
1060 {
1061     size_t i;
1062
1063     for (i = 0; i < self->blocks_count; ++i)
1064     {
1065         if (!ir_block_naive_phi(self->blocks[i]))
1066             return false;
1067     }
1068     return true;
1069 }
1070
1071 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1072 {
1073     ir_instr *instr;
1074     size_t i;
1075
1076     /* create a store */
1077     if (!ir_block_create_store(block, old, what))
1078         return false;
1079
1080     /* we now move it up */
1081     instr = block->instr[block->instr_count-1];
1082     for (i = block->instr_count; i > iid; --i)
1083         block->instr[i] = block->instr[i-1];
1084     block->instr[i] = instr;
1085
1086     return true;
1087 }
1088
1089 static bool ir_block_naive_phi(ir_block *self)
1090 {
1091     size_t i, p, w;
1092     /* FIXME: optionally, create_phi can add the phis
1093      * to a list so we don't need to loop through blocks
1094      * - anyway: "don't optimize YET"
1095      */
1096     for (i = 0; i < self->instr_count; ++i)
1097     {
1098         ir_instr *instr = self->instr[i];
1099         if (instr->opcode != VINSTR_PHI)
1100             continue;
1101
1102         if (!ir_block_instr_remove(self, i))
1103             return false;
1104         --i; /* NOTE: i+1 below */
1105
1106         for (p = 0; p < instr->phi_count; ++p)
1107         {
1108             ir_value *v = instr->phi[p].value;
1109             for (w = 0; w < v->writes_count; ++w) {
1110                 ir_value *old;
1111
1112                 if (!v->writes[w]->_ops[0])
1113                     continue;
1114
1115                 /* When the write was to a global, we have to emit a mov */
1116                 old = v->writes[w]->_ops[0];
1117
1118                 /* The original instruction now writes to the PHI target local */
1119                 if (v->writes[w]->_ops[0] == v)
1120                     v->writes[w]->_ops[0] = instr->_ops[0];
1121
1122                 if (old->store != store_local)
1123                 {
1124                     /* If it originally wrote to a global we need to store the value
1125                      * there as welli
1126                      */
1127                     if (!ir_naive_phi_emit_store(self, i+1, old, v))
1128                         return false;
1129                     if (i+1 < self->instr_count)
1130                         instr = self->instr[i+1];
1131                     else
1132                         instr = NULL;
1133                     /* In case I forget and access instr later, it'll be NULL
1134                      * when it's a problem, to make sure we crash, rather than accessing
1135                      * invalid data.
1136                      */
1137                 }
1138                 else
1139                 {
1140                     /* If it didn't, we can replace all reads by the phi target now. */
1141                     size_t r;
1142                     for (r = 0; r < old->reads_count; ++r)
1143                     {
1144                         size_t op;
1145                         ir_instr *ri = old->reads[r];
1146                         for (op = 0; op < ri->phi_count; ++op) {
1147                             if (ri->phi[op].value == old)
1148                                 ri->phi[op].value = v;
1149                         }
1150                         for (op = 0; op < 3; ++op) {
1151                             if (ri->_ops[op] == old)
1152                                 ri->_ops[op] = v;
1153                         }
1154                     }
1155                 }
1156             }
1157         }
1158         ir_instr_delete(instr);
1159     }
1160     return true;
1161 }
1162
1163 /***********************************************************************
1164  *IR Temp allocation code
1165  * Propagating value life ranges by walking through the function backwards
1166  * until no more changes are made.
1167  * In theory this should happen once more than once for every nested loop
1168  * level.
1169  * Though this implementation might run an additional time for if nests.
1170  */
1171
1172 typedef struct
1173 {
1174     ir_value* *v;
1175     size_t    v_count;
1176     size_t    v_alloc;
1177 } new_reads_t;
1178 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1179
1180 /* Enumerate instructions used by value's life-ranges
1181  */
1182 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1183 {
1184     size_t i;
1185     size_t eid = *_eid;
1186     for (i = 0; i < self->instr_count; ++i)
1187     {
1188         self->instr[i]->eid = eid++;
1189     }
1190     *_eid = eid;
1191 }
1192
1193 /* Enumerate blocks and instructions.
1194  * The block-enumeration is unordered!
1195  * We do not really use the block enumreation, however
1196  * the instruction enumeration is important for life-ranges.
1197  */
1198 void ir_function_enumerate(ir_function *self)
1199 {
1200     size_t i;
1201     size_t instruction_id = 0;
1202     for (i = 0; i < self->blocks_count; ++i)
1203     {
1204         self->blocks[i]->eid = i;
1205         self->blocks[i]->run_id = 0;
1206         ir_block_enumerate(self->blocks[i], &instruction_id);
1207     }
1208 }
1209
1210 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1211 bool ir_function_calculate_liferanges(ir_function *self)
1212 {
1213     size_t i;
1214     bool changed;
1215
1216     do {
1217         self->run_id++;
1218         changed = false;
1219         for (i = 0; i != self->blocks_count; ++i)
1220         {
1221             if (self->blocks[i]->is_return)
1222             {
1223                 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1224                     return false;
1225             }
1226         }
1227     } while (changed);
1228     return true;
1229 }
1230
1231 /* Get information about which operand
1232  * is read from, or written to.
1233  */
1234 static void ir_op_read_write(int op, size_t *read, size_t *write)
1235 {
1236     switch (op)
1237     {
1238     case VINSTR_JUMP:
1239     case INSTR_GOTO:
1240         *write = 0;
1241         *read = 0;
1242         break;
1243     case INSTR_IF:
1244     case INSTR_IFNOT:
1245 #if 0
1246     case INSTR_IF_S:
1247     case INSTR_IFNOT_S:
1248 #endif
1249     case INSTR_RETURN:
1250     case VINSTR_COND:
1251         *write = 0;
1252         *read = 1;
1253         break;
1254     default:
1255         *write = 1;
1256         *read = 6;
1257         break;
1258     };
1259 }
1260
1261 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1262 {
1263     size_t i;
1264     bool changed = false;
1265     bool tempbool;
1266     for (i = 0; i != self->living_count; ++i)
1267     {
1268         tempbool = ir_value_life_merge(self->living[i], eid);
1269         /* debug
1270         if (tempbool)
1271             fprintf(stderr, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1272         */
1273         changed = changed || tempbool;
1274     }
1275     return changed;
1276 }
1277
1278 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1279 {
1280     size_t i;
1281     /* values which have been read in a previous iteration are now
1282      * in the "living" array even if the previous block doesn't use them.
1283      * So we have to remove whatever does not exist in the previous block.
1284      * They will be re-added on-read, but the liferange merge won't cause
1285      * a change.
1286      */
1287     for (i = 0; i < self->living_count; ++i)
1288     {
1289         if (!ir_block_living_find(prev, self->living[i], NULL)) {
1290             if (!ir_block_living_remove(self, i))
1291                 return false;
1292             --i;
1293         }
1294     }
1295
1296     /* Whatever the previous block still has in its living set
1297      * must now be added to ours as well.
1298      */
1299     for (i = 0; i < prev->living_count; ++i)
1300     {
1301         if (ir_block_living_find(self, prev->living[i], NULL))
1302             continue;
1303         if (!ir_block_living_add(self, prev->living[i]))
1304             return false;
1305         /*
1306         printf("%s got from prev: %s\n", self->label, prev->living[i]->_name);
1307         */
1308     }
1309     return true;
1310 }
1311
1312 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
1313 {
1314     ir_instr *instr;
1315     ir_value *value;
1316     bool  tempbool;
1317     size_t i, o, p, rd;
1318     /* bitmasks which operands are read from or written to */
1319     size_t read, write;
1320     new_reads_t new_reads;
1321     char dbg_ind[16] = { '#', '0' };
1322     (void)dbg_ind;
1323
1324     MEM_VECTOR_INIT(&new_reads, v);
1325
1326     if (prev)
1327     {
1328         if (!ir_block_life_prop_previous(self, prev, changed))
1329             return false;
1330     }
1331
1332     i = self->instr_count;
1333     while (i)
1334     { --i;
1335         instr = self->instr[i];
1336
1337         /* PHI operands are always read operands */
1338         for (p = 0; p < instr->phi_count; ++p)
1339         {
1340             value = instr->phi[p].value;
1341             /* used this before new_reads - puts the last read into the life range as well
1342             if (!ir_block_living_find(self, value, NULL))
1343                 ir_block_living_add(self, value);
1344             */
1345             /* fprintf(stderr, "read: %s\n", value->_name); */
1346             if (!new_reads_t_v_find(&new_reads, value, NULL))
1347             {
1348                 if (!new_reads_t_v_add(&new_reads, value))
1349                     goto on_error;
1350             }
1351         }
1352
1353         /* See which operands are read and write operands */
1354         ir_op_read_write(instr->opcode, &read, &write);
1355
1356         /* Go through the 3 main operands */
1357         for (o = 0; o < 3; ++o)
1358         {
1359             if (!instr->_ops[o]) /* no such operand */
1360                 continue;
1361
1362             value = instr->_ops[o];
1363
1364             /* We only care about locals */
1365             if (value->store != store_value &&
1366                 value->store != store_local)
1367                 continue;
1368
1369             /* read operands */
1370             if (read & (1<<o))
1371             {
1372                 /* used this before new_reads - puts the last read into the life range as well
1373                 if (!ir_block_living_find(self, value, NULL))
1374                     ir_block_living_add(self, value);
1375                 */
1376                 /* fprintf(stderr, "read: %s\n", value->_name); */
1377                 if (!new_reads_t_v_find(&new_reads, value, NULL))
1378                 {
1379                     if (!new_reads_t_v_add(&new_reads, value))
1380                         goto on_error;
1381                 }
1382             }
1383
1384             /* write operands */
1385             /* When we write to a local, we consider it "dead" for the
1386              * remaining upper part of the function, since in SSA a value
1387              * can only be written once (== created)
1388              */
1389             if (write & (1<<o))
1390             {
1391                 size_t idx, readidx;
1392                 bool in_living = ir_block_living_find(self, value, &idx);
1393                 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
1394                 if (!in_living && !in_reads)
1395                 {
1396                     /* If the value isn't alive it hasn't been read before... */
1397                     /* TODO: See if the warning can be emitted during parsing or AST processing
1398                      * otherwise have warning printed here.
1399                      * IF printing a warning here: include filecontext_t,
1400                      * and make sure it's only printed once
1401                      * since this function is run multiple times.
1402                      */
1403                     /* For now: debug info: */
1404                     fprintf(stderr, "Value only written %s\n", value->name);
1405                     tempbool = ir_value_life_merge(value, instr->eid);
1406                     *changed = *changed || tempbool;
1407                     /*
1408                     ir_instr_dump(instr, dbg_ind, printf);
1409                     abort();
1410                     */
1411                 } else {
1412                     /* since 'living' won't contain it
1413                      * anymore, merge the value, since
1414                      * (A) doesn't.
1415                      */
1416                     tempbool = ir_value_life_merge(value, instr->eid);
1417                     /*
1418                     if (tempbool)
1419                         fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
1420                     */
1421                     *changed = *changed || tempbool;
1422                     /* Then remove */
1423                     if (!ir_block_living_remove(self, idx))
1424                         goto on_error;
1425                     if (in_reads)
1426                     {
1427                         if (!new_reads_t_v_remove(&new_reads, readidx))
1428                             goto on_error;
1429                     }
1430                 }
1431             }
1432         }
1433         /* (A) */
1434         tempbool = ir_block_living_add_instr(self, instr->eid);
1435         //fprintf(stderr, "living added values\n");
1436         *changed = *changed || tempbool;
1437
1438         /* new reads: */
1439         for (rd = 0; rd < new_reads.v_count; ++rd)
1440         {
1441             if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
1442                 if (!ir_block_living_add(self, new_reads.v[rd]))
1443                     goto on_error;
1444             }
1445             if (!i && !self->entries_count) {
1446                 /* fix the top */
1447                 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
1448             }
1449         }
1450         MEM_VECTOR_CLEAR(&new_reads, v);
1451     }
1452
1453     if (self->run_id == self->owner->run_id)
1454         return true;
1455
1456     self->run_id = self->owner->run_id;
1457
1458     for (i = 0; i < self->entries_count; ++i)
1459     {
1460         ir_block *entry = self->entries[i];
1461         ir_block_life_propagate(entry, self, changed);
1462     }
1463
1464     return true;
1465 on_error:
1466     MEM_VECTOR_CLEAR(&new_reads, v);
1467     return false;
1468 }