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