]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ir.c
Turned nearly every void-returning function into a bool-returning function, and check...
[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", qc_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 = qc_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 == qc_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 != qc_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_t v)
443 {
444     if (self->vtype != qc_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 != qc_string)
454         return false;
455     self->constval.vstring = util_strdup(str);
456     self->isconst = true;
457     return true;
458 }
459
460 bool ir_value_set_int(ir_value *self, int i)
461 {
462     if (self->vtype != qc_int)
463         return false;
464     self->constval.vint = i;
465     self->isconst = true;
466     return true;
467 }
468
469 bool ir_value_lives(ir_value *self, size_t at)
470 {
471     size_t i;
472     for (i = 0; i < self->life_count; ++i)
473     {
474         ir_life_entry_t *life = &self->life[i];
475         if (life->start <= at && at <= life->end)
476             return true;
477         if (life->start > at) /* since it's ordered */
478             return false;
479     }
480     return false;
481 }
482
483 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
484 {
485     size_t k;
486     if (!ir_value_life_add(self, e)) /* naive... */
487         return false;
488     for (k = self->life_count-1; k > idx; --k)
489         self->life[k] = self->life[k-1];
490     self->life[idx] = e;
491     return true;
492 }
493
494 bool ir_value_life_merge(ir_value *self, size_t s)
495 {
496     size_t i;
497     ir_life_entry_t *life = NULL;
498     ir_life_entry_t *before = NULL;
499     ir_life_entry_t new_entry;
500
501     /* Find the first range >= s */
502     for (i = 0; i < self->life_count; ++i)
503     {
504         before = life;
505         life = &self->life[i];
506         if (life->start > s)
507             break;
508     }
509     /* nothing found? append */
510     if (i == self->life_count) {
511         if (life && life->end+1 == s)
512         {
513             /* previous life range can be merged in */
514             life->end++;
515             return true;
516         }
517         if (life && life->end >= s)
518             return false;
519         ir_life_entry_t e;
520         e.start = e.end = s;
521         if (!ir_value_life_add(self, e))
522             return false; /* failing */
523         return true;
524     }
525     /* found */
526     if (before)
527     {
528         if (before->end + 1 == s &&
529             life->start - 1 == s)
530         {
531             /* merge */
532             before->end = life->end;
533             if (!ir_value_life_remove(self, i))
534                 return false; /* failing */
535             return true;
536         }
537         if (before->end + 1 == s)
538         {
539             /* extend before */
540             before->end++;
541             return true;
542         }
543         /* already contained */
544         if (before->end >= s)
545             return false;
546     }
547     /* extend */
548     if (life->start - 1 == s)
549     {
550         life->start--;
551         return true;
552     }
553     /* insert a new entry */
554     new_entry.start = new_entry.end = s;
555     return ir_value_life_insert(self, i, new_entry);
556 }
557
558 /***********************************************************************
559  *IR main operations
560  */
561
562 bool ir_block_create_store_op(ir_block *self, int op, ir_value *target, ir_value *what)
563 {
564     if (target->store == store_value) {
565         fprintf(stderr, "cannot store to an SSA value\n");
566         return false;
567     } else {
568         ir_instr *in = ir_instr_new(self, op);
569         if (!in)
570             return false;
571         if (!ir_instr_op(in, 0, target, true) ||
572             !ir_instr_op(in, 1, what, false)  ||
573             !ir_block_instr_add(self, in) )
574         {
575             return false;
576         }
577         return true;
578     }
579 }
580
581 bool ir_block_create_store(ir_block *self, ir_value *target, ir_value *what)
582 {
583     int op = 0;
584     int vtype;
585     if (target->vtype == qc_variant)
586         vtype = what->vtype;
587     else
588         vtype = target->vtype;
589
590     switch (vtype) {
591         case qc_float:
592 #if 0
593             if (what->vtype == qc_int)
594                 op = INSTR_CONV_ITOF;
595             else
596 #endif
597                 op = INSTR_STORE_F;
598             break;
599         case qc_vector:
600             op = INSTR_STORE_V;
601             break;
602         case qc_entity:
603             op = INSTR_STORE_ENT;
604             break;
605         case qc_string:
606             op = INSTR_STORE_S;
607             break;
608 #if 0
609         case qc_int:
610             if (what->vtype == qc_int)
611                 op = INSTR_CONV_FTOI;
612             else
613                 op = INSTR_STORE_I;
614             break;
615 #endif
616         case qc_pointer:
617 #if 0
618             op = INSTR_STORE_I;
619 #else
620             op = INSTR_STORE_ENT;
621 #endif
622             break;
623     }
624     return ir_block_create_store_op(self, op, target, what);
625 }
626
627 bool ir_block_create_return(ir_block *self, ir_value *v)
628 {
629     ir_instr *in;
630     if (self->final) {
631         fprintf(stderr, "block already ended (%s)\n", self->label);
632         return false;
633     }
634     self->final = true;
635     self->is_return = true;
636     in = ir_instr_new(self, INSTR_RETURN);
637     if (!in)
638         return false;
639
640     if (!ir_instr_op(in, 0, v, false) ||
641         !ir_block_instr_add(self, in) )
642     {
643         return false;
644     }
645     return true;
646 }
647
648 bool ir_block_create_if(ir_block *self, ir_value *v,
649                         ir_block *ontrue, ir_block *onfalse)
650 {
651     ir_instr *in;
652     if (self->final) {
653         fprintf(stderr, "block already ended (%s)\n", self->label);
654         return false;
655     }
656     self->final = true;
657     //in = ir_instr_new(self, (v->vtype == qc_string ? INSTR_IF_S : INSTR_IF_F));
658     in = ir_instr_new(self, VINSTR_COND);
659     if (!in)
660         return false;
661
662     if (!ir_instr_op(in, 0, v, false)) {
663         ir_instr_delete(in);
664         return false;
665     }
666
667     in->bops[0] = ontrue;
668     in->bops[1] = onfalse;
669
670     if (!ir_block_instr_add(self, in))
671         return false;
672
673     if (!ir_block_exits_add(self, ontrue)    ||
674         !ir_block_exits_add(self, onfalse)   ||
675         !ir_block_entries_add(ontrue, self)  ||
676         !ir_block_entries_add(onfalse, self) )
677     {
678         return false;
679     }
680     return true;
681 }
682
683 bool ir_block_create_jump(ir_block *self, ir_block *to)
684 {
685     ir_instr *in;
686     if (self->final) {
687         fprintf(stderr, "block already ended (%s)\n", self->label);
688         return false;
689     }
690     self->final = true;
691     in = ir_instr_new(self, VINSTR_JUMP);
692     if (!in)
693         return false;
694
695     in->bops[0] = to;
696     if (!ir_block_instr_add(self, in))
697         return false;
698
699     if (!ir_block_exits_add(self, to) ||
700         !ir_block_entries_add(to, self) )
701     {
702         return false;
703     }
704     return true;
705 }
706
707 bool ir_block_create_goto(ir_block *self, ir_block *to)
708 {
709     ir_instr *in;
710     if (self->final) {
711         fprintf(stderr, "block already ended (%s)\n", self->label);
712         return false;
713     }
714     self->final = true;
715     in = ir_instr_new(self, INSTR_GOTO);
716     if (!in)
717         return false;
718
719     in->bops[0] = to;
720     if (!ir_block_instr_add(self, in))
721         return false;
722
723     if (!ir_block_exits_add(self, to) ||
724         !ir_block_entries_add(to, self) )
725     {
726         return false;
727     }
728     return true;
729 }
730
731 ir_instr* ir_block_create_phi(ir_block *self, const char *label, int ot)
732 {
733     ir_value *out;
734     ir_instr *in;
735     in = ir_instr_new(self, VINSTR_PHI);
736     if (!in)
737         return NULL;
738     out = ir_value_out(self->owner, label, store_local, ot);
739     if (!out) {
740         ir_instr_delete(in);
741         return NULL;
742     }
743     if (!ir_instr_op(in, 0, out, true)) {
744         ir_instr_delete(in);
745         ir_value_delete(out);
746         return NULL;
747     }
748     if (!ir_block_instr_add(self, in)) {
749         ir_instr_delete(in);
750         ir_value_delete(out);
751         return NULL;
752     }
753     return in;
754 }
755
756 ir_value* ir_phi_value(ir_instr *self)
757 {
758     return self->_ops[0];
759 }
760
761 bool ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
762 {
763     ir_phi_entry_t pe;
764
765     if (!ir_block_entries_find(self->owner, b, NULL)) {
766         /* Must not be possible to cause this, otherwise the AST
767          * is doing something wrong.
768          */
769         fprintf(stderr, "Invalid entry block for PHI\n");
770         abort();
771     }
772
773     pe.value = v;
774     pe.from = b;
775     if (!ir_value_reads_add(v, self))
776         return false;
777     return ir_instr_phi_add(self, pe);
778 }
779
780 /* binary op related code */
781
782 ir_value* ir_block_create_binop(ir_block *self,
783                                 const char *label, int opcode,
784                                 ir_value *left, ir_value *right)
785 {
786     int ot = qc_void;
787     switch (opcode) {
788         case INSTR_ADD_F:
789         case INSTR_SUB_F:
790         case INSTR_DIV_F:
791         case INSTR_MUL_F:
792         case INSTR_MUL_V:
793         case INSTR_AND:
794         case INSTR_OR:
795 #if 0
796         case INSTR_AND_I:
797         case INSTR_AND_IF:
798         case INSTR_AND_FI:
799         case INSTR_OR_I:
800         case INSTR_OR_IF:
801         case INSTR_OR_FI:
802 #endif
803         case INSTR_BITAND:
804         case INSTR_BITOR:
805 #if 0
806         case INSTR_SUB_S: /* -- offset of string as float */
807         case INSTR_MUL_IF:
808         case INSTR_MUL_FI:
809         case INSTR_DIV_IF:
810         case INSTR_DIV_FI:
811         case INSTR_BITOR_IF:
812         case INSTR_BITOR_FI:
813         case INSTR_BITAND_FI:
814         case INSTR_BITAND_IF:
815         case INSTR_EQ_I:
816         case INSTR_NE_I:
817 #endif
818             ot = qc_float;
819             break;
820 #if 0
821         case INSTR_ADD_I:
822         case INSTR_ADD_IF:
823         case INSTR_ADD_FI:
824         case INSTR_SUB_I:
825         case INSTR_SUB_FI:
826         case INSTR_SUB_IF:
827         case INSTR_MUL_I:
828         case INSTR_DIV_I:
829         case INSTR_BITAND_I:
830         case INSTR_BITOR_I:
831         case INSTR_XOR_I:
832         case INSTR_RSHIFT_I:
833         case INSTR_LSHIFT_I:
834             ot = qc_int;
835             break;
836 #endif
837         case INSTR_ADD_V:
838         case INSTR_SUB_V:
839         case INSTR_MUL_VF:
840         case INSTR_MUL_FV:
841 #if 0
842         case INSTR_DIV_VF:
843         case INSTR_MUL_IV:
844         case INSTR_MUL_VI:
845 #endif
846             ot = qc_vector;
847             break;
848 #if 0
849         case INSTR_ADD_SF:
850             ot = qc_pointer;
851             break;
852 #endif
853         default:
854             // ranges:
855             /* boolean operations result in floats */
856             if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
857                 ot = qc_float;
858             else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
859                 ot = qc_float;
860 #if 0
861             else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
862                 ot = qc_float;
863 #endif
864             break;
865     };
866     if (ot == qc_void) {
867         /* The AST or parser were supposed to check this! */
868         return NULL;
869     }
870
871     ir_value *out = ir_value_out(self->owner, label, store_local, ot);
872     if (!out)
873         return NULL;
874
875     ir_instr *in = ir_instr_new(self, opcode);
876     if (!in) {
877         ir_value_delete(out);
878         return NULL;
879     }
880
881     if (!ir_instr_op(in, 0, out, true) ||
882         !ir_instr_op(in, 1, left, false) ||
883         !ir_instr_op(in, 2, right, false) )
884     {
885         goto on_error;
886     }
887
888     if (!ir_block_instr_add(self, in))
889         goto on_error;
890
891     return out;
892 on_error:
893     ir_value_delete(out);
894     ir_instr_delete(in);
895     return NULL;
896 }
897
898 ir_value* ir_block_create_add(ir_block *self,
899                               const char *label,
900                               ir_value *left, ir_value *right)
901 {
902     int op = 0;
903     int l = left->vtype;
904     int r = right->vtype;
905     if (l == r) {
906         switch (l) {
907             default:
908                 return NULL;
909             case qc_float:
910                 op = INSTR_ADD_F;
911                 break;
912 #if 0
913             case qc_int:
914                 op = INSTR_ADD_I;
915                 break;
916 #endif
917             case qc_vector:
918                 op = INSTR_ADD_V;
919                 break;
920         }
921     } else {
922 #if 0
923         if ( (l == qc_float && r == qc_int) )
924             op = INSTR_ADD_FI;
925         else if ( (l == qc_int && r == qc_float) )
926             op = INSTR_ADD_IF;
927         else
928 #endif
929             return NULL;
930     }
931     return ir_block_create_binop(self, label, op, left, right);
932 }
933
934 ir_value* ir_block_create_sub(ir_block *self,
935                               const char *label,
936                               ir_value *left, ir_value *right)
937 {
938     int op = 0;
939     int l = left->vtype;
940     int r = right->vtype;
941     if (l == r) {
942
943         switch (l) {
944             default:
945                 return NULL;
946             case qc_float:
947                 op = INSTR_SUB_F;
948                 break;
949 #if 0
950             case qc_int:
951                 op = INSTR_SUB_I;
952                 break;
953 #endif
954             case qc_vector:
955                 op = INSTR_SUB_V;
956                 break;
957         }
958     } else {
959 #if 0
960         if ( (l == qc_float && r == qc_int) )
961             op = INSTR_SUB_FI;
962         else if ( (l == qc_int && r == qc_float) )
963             op = INSTR_SUB_IF;
964         else
965 #endif
966             return NULL;
967     }
968     return ir_block_create_binop(self, label, op, left, right);
969 }
970
971 ir_value* ir_block_create_mul(ir_block *self,
972                               const char *label,
973                               ir_value *left, ir_value *right)
974 {
975     int op = 0;
976     int l = left->vtype;
977     int r = right->vtype;
978     if (l == r) {
979
980         switch (l) {
981             default:
982                 return NULL;
983             case qc_float:
984                 op = INSTR_MUL_F;
985                 break;
986 #if 0
987             case qc_int:
988                 op = INSTR_MUL_I;
989                 break;
990 #endif
991             case qc_vector:
992                 op = INSTR_MUL_V;
993                 break;
994         }
995     } else {
996         if ( (l == qc_vector && r == qc_float) )
997             op = INSTR_MUL_VF;
998         else if ( (l == qc_float && r == qc_vector) )
999             op = INSTR_MUL_FV;
1000 #if 0
1001         else if ( (l == qc_vector && r == qc_int) )
1002             op = INSTR_MUL_VI;
1003         else if ( (l == qc_int && r == qc_vector) )
1004             op = INSTR_MUL_IV;
1005         else if ( (l == qc_float && r == qc_int) )
1006             op = INSTR_MUL_FI;
1007         else if ( (l == qc_int && r == qc_float) )
1008             op = INSTR_MUL_IF;
1009 #endif
1010         else
1011             return NULL;
1012     }
1013     return ir_block_create_binop(self, label, op, left, right);
1014 }
1015
1016 ir_value* ir_block_create_div(ir_block *self,
1017                               const char *label,
1018                               ir_value *left, ir_value *right)
1019 {
1020     int op = 0;
1021     int l = left->vtype;
1022     int r = right->vtype;
1023     if (l == r) {
1024
1025         switch (l) {
1026             default:
1027                 return NULL;
1028             case qc_float:
1029                 op = INSTR_DIV_F;
1030                 break;
1031 #if 0
1032             case qc_int:
1033                 op = INSTR_DIV_I;
1034                 break;
1035 #endif
1036         }
1037     } else {
1038 #if 0
1039         if ( (l == qc_vector && r == qc_float) )
1040             op = INSTR_DIV_VF;
1041         else if ( (l == qc_float && r == qc_int) )
1042             op = INSTR_DIV_FI;
1043         else if ( (l == qc_int && r == qc_float) )
1044             op = INSTR_DIV_IF;
1045         else
1046 #endif
1047             return NULL;
1048     }
1049     return ir_block_create_binop(self, label, op, left, right);
1050 }
1051
1052 /* PHI resolving breaks the SSA, and must thus be the last
1053  * step before life-range calculation.
1054  */
1055
1056 static bool ir_block_naive_phi(ir_block *self);
1057 bool ir_function_naive_phi(ir_function *self)
1058 {
1059     size_t i;
1060
1061     for (i = 0; i < self->blocks_count; ++i)
1062     {
1063         if (!ir_block_naive_phi(self->blocks[i]))
1064             return false;
1065     }
1066     return true;
1067 }
1068
1069 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1070 {
1071     ir_instr *instr;
1072     size_t i;
1073
1074     /* create a store */
1075     ir_block_create_store(block, old, what);
1076
1077     /* we now move it up */
1078     instr = block->instr[block->instr_count-1];
1079     for (i = block->instr_count; i > iid; --i)
1080         block->instr[i] = block->instr[i-1];
1081     block->instr[i] = instr;
1082
1083     return true;
1084 }
1085
1086 static bool ir_block_naive_phi(ir_block *self)
1087 {
1088     size_t i, p, w;
1089     /* FIXME: optionally, create_phi can add the phis
1090      * to a list so we don't need to loop through blocks
1091      * - anyway: "don't optimize YET"
1092      */
1093     for (i = 0; i < self->instr_count; ++i)
1094     {
1095         ir_instr *instr = self->instr[i];
1096         if (instr->opcode != VINSTR_PHI)
1097             continue;
1098
1099         if (!ir_block_instr_remove(self, i))
1100             return false;
1101         --i; /* NOTE: i+1 below */
1102
1103         for (p = 0; p < instr->phi_count; ++p)
1104         {
1105             ir_value *v = instr->phi[p].value;
1106             for (w = 0; w < v->writes_count; ++w) {
1107                 ir_value *old;
1108
1109                 if (!v->writes[w]->_ops[0])
1110                     continue;
1111
1112                 /* When the write was to a global, we have to emit a mov */
1113                 old = v->writes[w]->_ops[0];
1114
1115                 /* The original instruction now writes to the PHI target local */
1116                 if (v->writes[w]->_ops[0] == v)
1117                     v->writes[w]->_ops[0] = instr->_ops[0];
1118
1119                 if (old->store != store_local)
1120                 {
1121                     /* If it originally wrote to a global we need to store the value
1122                      * there as welli
1123                      */
1124                     ir_naive_phi_emit_store(self, i+1, old, v);
1125                     if (i+1 < self->instr_count)
1126                         instr = self->instr[i+1];
1127                     else
1128                         instr = NULL;
1129                     /* In case I forget and access instr later, it'll be NULL
1130                      * when it's a problem, to make sure we crash, rather than accessing
1131                      * invalid data.
1132                      */
1133                 }
1134                 else
1135                 {
1136                     /* If it didn't, we can replace all reads by the phi target now. */
1137                     size_t r;
1138                     for (r = 0; r < old->reads_count; ++r)
1139                     {
1140                         size_t op;
1141                         ir_instr *ri = old->reads[r];
1142                         for (op = 0; op < ri->phi_count; ++op) {
1143                             if (ri->phi[op].value == old)
1144                                 ri->phi[op].value = v;
1145                         }
1146                         for (op = 0; op < 3; ++op) {
1147                             if (ri->_ops[op] == old)
1148                                 ri->_ops[op] = v;
1149                         }
1150                     }
1151                 }
1152             }
1153         }
1154         ir_instr_delete(instr);
1155     }
1156     return true;
1157 }
1158
1159 /***********************************************************************
1160  *IR Temp allocation code
1161  * Propagating value life ranges by walking through the function backwards
1162  * until no more changes are made.
1163  * In theory this should happen once more than once for every nested loop
1164  * level.
1165  * Though this implementation might run an additional time for if nests.
1166  */
1167
1168 typedef struct
1169 {
1170     ir_value* *v;
1171     size_t    v_count;
1172     size_t    v_alloc;
1173 } new_reads_t;
1174 MEM_VEC_FUNCTIONS_ALL(new_reads_t, ir_value*, v)
1175
1176 /* Enumerate instructions used by value's life-ranges
1177  */
1178 static void ir_block_enumerate(ir_block *self, size_t *_eid)
1179 {
1180     size_t i;
1181     size_t eid = *_eid;
1182     for (i = 0; i < self->instr_count; ++i)
1183     {
1184         self->instr[i]->eid = eid++;
1185     }
1186     *_eid = eid;
1187 }
1188
1189 /* Enumerate blocks and instructions.
1190  * The block-enumeration is unordered!
1191  * We do not really use the block enumreation, however
1192  * the instruction enumeration is important for life-ranges.
1193  */
1194 void ir_function_enumerate(ir_function *self)
1195 {
1196     size_t i;
1197     size_t instruction_id = 0;
1198     for (i = 0; i < self->blocks_count; ++i)
1199     {
1200         self->blocks[i]->eid = i;
1201         self->blocks[i]->run_id = 0;
1202         ir_block_enumerate(self->blocks[i], &instruction_id);
1203     }
1204 }
1205
1206 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
1207 bool ir_function_calculate_liferanges(ir_function *self)
1208 {
1209     size_t i;
1210     bool changed;
1211
1212     do {
1213         self->run_id++;
1214         changed = false;
1215         for (i = 0; i != self->blocks_count; ++i)
1216         {
1217             if (self->blocks[i]->is_return)
1218             {
1219                 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
1220                     return false;
1221             }
1222         }
1223     } while (changed);
1224     return true;
1225 }
1226
1227 /* Get information about which operand
1228  * is read from, or written to.
1229  */
1230 static void ir_op_read_write(int op, size_t *read, size_t *write)
1231 {
1232     switch (op)
1233     {
1234     case VINSTR_JUMP:
1235     case INSTR_GOTO:
1236         *write = 0;
1237         *read = 0;
1238         break;
1239     case INSTR_IF:
1240     case INSTR_IFNOT:
1241 #if 0
1242     case INSTR_IF_S:
1243     case INSTR_IFNOT_S:
1244 #endif
1245     case INSTR_RETURN:
1246     case VINSTR_COND:
1247         *write = 0;
1248         *read = 1;
1249         break;
1250     default:
1251         *write = 1;
1252         *read = 6;
1253         break;
1254     };
1255 }
1256
1257 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
1258 {
1259     size_t i;
1260     bool changed = false;
1261     bool tempbool;
1262     for (i = 0; i != self->living_count; ++i)
1263     {
1264         tempbool = ir_value_life_merge(self->living[i], eid);
1265         /* debug
1266         if (tempbool)
1267             fprintf(stderr, "block_living_add_instr() value instruction added %s: %i\n", self->living[i]->_name, (int)eid);
1268         */
1269         changed = changed || tempbool;
1270     }
1271     return changed;
1272 }
1273
1274 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
1275 {
1276     size_t i;
1277     /* values which have been read in a previous iteration are now
1278      * in the "living" array even if the previous block doesn't use them.
1279      * So we have to remove whatever does not exist in the previous block.
1280      * They will be re-added on-read, but the liferange merge won't cause
1281      * a change.
1282      */
1283     for (i = 0; i < self->living_count; ++i)
1284     {
1285         if (!ir_block_living_find(prev, self->living[i], NULL)) {
1286             if (!ir_block_living_remove(self, i))
1287                 return false;
1288             --i;
1289         }
1290     }
1291
1292     /* Whatever the previous block still has in its living set
1293      * must now be added to ours as well.
1294      */
1295     for (i = 0; i < prev->living_count; ++i)
1296     {
1297         if (ir_block_living_find(self, prev->living[i], NULL))
1298             continue;
1299         if (!ir_block_living_add(self, prev->living[i]))
1300             return false;
1301         /*
1302         printf("%s got from prev: %s\n", self->label, prev->living[i]->_name);
1303         */
1304     }
1305 }
1306
1307 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
1308 {
1309     ir_instr *instr;
1310     ir_value *value;
1311     bool  tempbool;
1312     size_t i, o, p, rd;
1313     /* bitmasks which operands are read from or written to */
1314     size_t read, write;
1315     new_reads_t new_reads;
1316     char dbg_ind[16] = { '#', '0' };
1317     (void)dbg_ind;
1318
1319     MEM_VECTOR_INIT(&new_reads, v);
1320
1321     if (prev)
1322     {
1323         if (!ir_block_life_prop_previous(self, prev, changed))
1324             return false;
1325     }
1326
1327     i = self->instr_count;
1328     while (i)
1329     { --i;
1330         instr = self->instr[i];
1331
1332         /* PHI operands are always read operands */
1333         for (p = 0; p < instr->phi_count; ++p)
1334         {
1335             value = instr->phi[p].value;
1336             /* used this before new_reads - puts the last read into the life range as well
1337             if (!ir_block_living_find(self, value, NULL))
1338                 ir_block_living_add(self, value);
1339             */
1340             /* fprintf(stderr, "read: %s\n", value->_name); */
1341             if (!new_reads_t_v_find(&new_reads, value, NULL))
1342             {
1343                 if (!new_reads_t_v_add(&new_reads, value))
1344                     goto on_error;
1345             }
1346         }
1347
1348         /* See which operands are read and write operands */
1349         ir_op_read_write(instr->opcode, &read, &write);
1350
1351         /* Go through the 3 main operands */
1352         for (o = 0; o < 3; ++o)
1353         {
1354             if (!instr->_ops[o]) /* no such operand */
1355                 continue;
1356
1357             value = instr->_ops[o];
1358
1359             /* We only care about locals */
1360             if (value->store != store_value &&
1361                 value->store != store_local)
1362                 continue;
1363
1364             /* read operands */
1365             if (read & (1<<o))
1366             {
1367                 /* used this before new_reads - puts the last read into the life range as well
1368                 if (!ir_block_living_find(self, value, NULL))
1369                     ir_block_living_add(self, value);
1370                 */
1371                 /* fprintf(stderr, "read: %s\n", value->_name); */
1372                 if (!new_reads_t_v_find(&new_reads, value, NULL))
1373                 {
1374                     if (!new_reads_t_v_add(&new_reads, value))
1375                         goto on_error;
1376                 }
1377             }
1378
1379             /* write operands */
1380             /* When we write to a local, we consider it "dead" for the
1381              * remaining upper part of the function, since in SSA a value
1382              * can only be written once (== created)
1383              */
1384             if (write & (1<<o))
1385             {
1386                 size_t idx, readidx;
1387                 bool in_living = ir_block_living_find(self, value, &idx);
1388                 bool in_reads = new_reads_t_v_find(&new_reads, value, &readidx);
1389                 if (!in_living && !in_reads)
1390                 {
1391                     /* If the value isn't alive it hasn't been read before... */
1392                     /* TODO: See if the warning can be emitted during parsing or AST processing
1393                      * otherwise have warning printed here.
1394                      * IF printing a warning here: include filecontext_t,
1395                      * and make sure it's only printed once
1396                      * since this function is run multiple times.
1397                      */
1398                     /* For now: debug info: */
1399                     fprintf(stderr, "Value only written %s\n", value->name);
1400                     tempbool = ir_value_life_merge(value, instr->eid);
1401                     *changed = *changed || tempbool;
1402                     /*
1403                     ir_instr_dump(instr, dbg_ind, printf);
1404                     abort();
1405                     */
1406                 } else {
1407                     /* since 'living' won't contain it
1408                      * anymore, merge the value, since
1409                      * (A) doesn't.
1410                      */
1411                     tempbool = ir_value_life_merge(value, instr->eid);
1412                     /*
1413                     if (tempbool)
1414                         fprintf(stderr, "value added id %s %i\n", value->name, (int)instr->eid);
1415                     */
1416                     *changed = *changed || tempbool;
1417                     /* Then remove */
1418                     if (!ir_block_living_remove(self, idx))
1419                         goto on_error;
1420                     if (in_reads)
1421                     {
1422                         if (!new_reads_t_v_remove(&new_reads, readidx))
1423                             goto on_error;
1424                     }
1425                 }
1426             }
1427         }
1428         /* (A) */
1429         tempbool = ir_block_living_add_instr(self, instr->eid);
1430         //fprintf(stderr, "living added values\n");
1431         *changed = *changed || tempbool;
1432
1433         /* new reads: */
1434         for (rd = 0; rd < new_reads.v_count; ++rd)
1435         {
1436             if (!ir_block_living_find(self, new_reads.v[rd], NULL)) {
1437                 if (!ir_block_living_add(self, new_reads.v[rd]))
1438                     goto on_error;
1439             }
1440             if (!i && !self->entries_count) {
1441                 /* fix the top */
1442                 *changed = *changed || ir_value_life_merge(new_reads.v[rd], instr->eid);
1443             }
1444         }
1445         MEM_VECTOR_CLEAR(&new_reads, v);
1446     }
1447
1448     if (self->run_id == self->owner->run_id)
1449         return;
1450     self->run_id = self->owner->run_id;
1451
1452     for (i = 0; i < self->entries_count; ++i)
1453     {
1454         ir_block *entry = self->entries[i];
1455         ir_block_life_propagate(entry, self, changed);
1456     }
1457
1458     return true;
1459 on_error:
1460     MEM_VECTOR_CLEAR(&new_reads, v);
1461     return false;
1462 }