]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ir.c
remember this for later
[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     "integer",
42     "variant",
43     "struct",
44     "union",
45     "array"
46 };
47
48 size_t type_sizeof[TYPE_COUNT] = {
49     1, /* TYPE_VOID     */
50     1, /* TYPE_STRING   */
51     1, /* TYPE_FLOAT    */
52     3, /* TYPE_VECTOR   */
53     1, /* TYPE_ENTITY   */
54     1, /* TYPE_FIELD    */
55     1, /* TYPE_FUNCTION */
56     1, /* TYPE_POINTER  */
57     1, /* TYPE_INTEGER  */
58     3, /* TYPE_VARIANT  */
59     0, /* TYPE_STRUCT   */
60     0, /* TYPE_UNION    */
61     0, /* TYPE_ARRAY    */
62 };
63
64 uint16_t type_store_instr[TYPE_COUNT] = {
65     INSTR_STORE_F, /* should use I when having integer support */
66     INSTR_STORE_S,
67     INSTR_STORE_F,
68     INSTR_STORE_V,
69     INSTR_STORE_ENT,
70     INSTR_STORE_FLD,
71     INSTR_STORE_FNC,
72     INSTR_STORE_ENT, /* should use I */
73 #if 0
74     INSTR_STORE_I, /* integer type */
75 #else
76     INSTR_STORE_F,
77 #endif
78
79     INSTR_STORE_V, /* variant, should never be accessed */
80
81     AINSTR_END, /* struct */
82     AINSTR_END, /* union  */
83     AINSTR_END, /* array  */
84 };
85
86 uint16_t field_store_instr[TYPE_COUNT] = {
87     INSTR_STORE_FLD,
88     INSTR_STORE_FLD,
89     INSTR_STORE_FLD,
90     INSTR_STORE_V,
91     INSTR_STORE_FLD,
92     INSTR_STORE_FLD,
93     INSTR_STORE_FLD,
94     INSTR_STORE_FLD,
95 #if 0
96     INSTR_STORE_FLD, /* integer type */
97 #else
98     INSTR_STORE_FLD,
99 #endif
100
101     INSTR_STORE_V, /* variant, should never be accessed */
102
103     AINSTR_END, /* struct */
104     AINSTR_END, /* union  */
105     AINSTR_END, /* array  */
106 };
107
108 uint16_t type_storep_instr[TYPE_COUNT] = {
109     INSTR_STOREP_F, /* should use I when having integer support */
110     INSTR_STOREP_S,
111     INSTR_STOREP_F,
112     INSTR_STOREP_V,
113     INSTR_STOREP_ENT,
114     INSTR_STOREP_FLD,
115     INSTR_STOREP_FNC,
116     INSTR_STOREP_ENT, /* should use I */
117 #if 0
118     INSTR_STOREP_ENT, /* integer type */
119 #else
120     INSTR_STOREP_F,
121 #endif
122
123     INSTR_STOREP_V, /* variant, should never be accessed */
124
125     AINSTR_END, /* struct */
126     AINSTR_END, /* union  */
127     AINSTR_END, /* array  */
128 };
129
130 uint16_t type_eq_instr[TYPE_COUNT] = {
131     INSTR_EQ_F, /* should use I when having integer support */
132     INSTR_EQ_S,
133     INSTR_EQ_F,
134     INSTR_EQ_V,
135     INSTR_EQ_E,
136     INSTR_EQ_E, /* FLD has no comparison */
137     INSTR_EQ_FNC,
138     INSTR_EQ_E, /* should use I */
139 #if 0
140     INSTR_EQ_I,
141 #else
142     INSTR_EQ_F,
143 #endif
144
145     INSTR_EQ_V, /* variant, should never be accessed */
146
147     AINSTR_END, /* struct */
148     AINSTR_END, /* union  */
149     AINSTR_END, /* array  */
150 };
151
152 uint16_t type_ne_instr[TYPE_COUNT] = {
153     INSTR_NE_F, /* should use I when having integer support */
154     INSTR_NE_S,
155     INSTR_NE_F,
156     INSTR_NE_V,
157     INSTR_NE_E,
158     INSTR_NE_E, /* FLD has no comparison */
159     INSTR_NE_FNC,
160     INSTR_NE_E, /* should use I */
161 #if 0
162     INSTR_NE_I,
163 #else
164     INSTR_NE_F,
165 #endif
166
167     INSTR_NE_V, /* variant, should never be accessed */
168
169     AINSTR_END, /* struct */
170     AINSTR_END, /* union  */
171     AINSTR_END, /* array  */
172 };
173
174 uint16_t type_not_instr[TYPE_COUNT] = {
175     INSTR_NOT_F, /* should use I when having integer support */
176     INSTR_NOT_S,
177     INSTR_NOT_F,
178     INSTR_NOT_V,
179     INSTR_NOT_ENT,
180     INSTR_NOT_ENT,
181     INSTR_NOT_FNC,
182     INSTR_NOT_ENT, /* should use I */
183 #if 0
184     INSTR_NOT_I, /* integer type */
185 #else
186     INSTR_NOT_F,
187 #endif
188
189     INSTR_NOT_V, /* variant, should never be accessed */
190
191     AINSTR_END, /* struct */
192     AINSTR_END, /* union  */
193     AINSTR_END, /* array  */
194 };
195
196 /* protos */
197 static void ir_gen_extparam(ir_builder *ir);
198
199 /* error functions */
200
201 static void irerror(lex_ctx ctx, const char *msg, ...)
202 {
203     va_list ap;
204     va_start(ap, msg);
205     con_cvprintmsg((void*)&ctx, LVL_ERROR, "internal error", msg, ap);
206     va_end(ap);
207 }
208
209 static bool irwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
210 {
211         va_list ap;
212         int lvl = LVL_WARNING;
213
214     if (warntype && !OPTS_WARN(warntype))
215         return false;
216
217     if (opts_werror)
218             lvl = LVL_ERROR;
219
220         va_start(ap, fmt);
221     con_vprintmsg(lvl, ctx.file, ctx.line, (opts_werror ? "error" : "warning"), fmt, ap);
222         va_end(ap);
223
224         return opts_werror;
225 }
226
227 /***********************************************************************
228  * Vector utility functions
229  */
230
231 bool GMQCC_WARN vec_ir_value_find(ir_value **vec, ir_value *what, size_t *idx)
232 {
233     size_t i;
234     size_t len = vec_size(vec);
235     for (i = 0; i < len; ++i) {
236         if (vec[i] == what) {
237             if (idx) *idx = i;
238             return true;
239         }
240     }
241     return false;
242 }
243
244 bool GMQCC_WARN vec_ir_block_find(ir_block **vec, ir_block *what, size_t *idx)
245 {
246     size_t i;
247     size_t len = vec_size(vec);
248     for (i = 0; i < len; ++i) {
249         if (vec[i] == what) {
250             if (idx) *idx = i;
251             return true;
252         }
253     }
254     return false;
255 }
256
257 bool GMQCC_WARN vec_ir_instr_find(ir_instr **vec, ir_instr *what, size_t *idx)
258 {
259     size_t i;
260     size_t len = vec_size(vec);
261     for (i = 0; i < len; ++i) {
262         if (vec[i] == what) {
263             if (idx) *idx = i;
264             return true;
265         }
266     }
267     return false;
268 }
269
270 /***********************************************************************
271  * IR Builder
272  */
273
274 static void ir_block_delete_quick(ir_block* self);
275 static void ir_instr_delete_quick(ir_instr *self);
276 static void ir_function_delete_quick(ir_function *self);
277
278 ir_builder* ir_builder_new(const char *modulename)
279 {
280     ir_builder* self;
281
282     self = (ir_builder*)mem_a(sizeof(*self));
283     if (!self)
284         return NULL;
285
286     self->functions   = NULL;
287     self->globals     = NULL;
288     self->fields      = NULL;
289     self->extparams   = NULL;
290     self->filenames   = NULL;
291     self->filestrings = NULL;
292     self->htglobals   = util_htnew(IR_HT_SIZE);
293     self->htfields    = util_htnew(IR_HT_SIZE);
294     self->htfunctions = util_htnew(IR_HT_SIZE);
295
296     self->str_immediate = 0;
297     self->name = NULL;
298     if (!ir_builder_set_name(self, modulename)) {
299         mem_d(self);
300         return NULL;
301     }
302
303     return self;
304 }
305
306 void ir_builder_delete(ir_builder* self)
307 {
308     size_t i;
309     util_htdel(self->htglobals);
310     util_htdel(self->htfields);
311     util_htdel(self->htfunctions);
312     mem_d((void*)self->name);
313     for (i = 0; i != vec_size(self->functions); ++i) {
314         ir_function_delete_quick(self->functions[i]);
315     }
316     vec_free(self->functions);
317     for (i = 0; i != vec_size(self->extparams); ++i) {
318         ir_value_delete(self->extparams[i]);
319     }
320     vec_free(self->extparams);
321     for (i = 0; i != vec_size(self->globals); ++i) {
322         ir_value_delete(self->globals[i]);
323     }
324     vec_free(self->globals);
325     for (i = 0; i != vec_size(self->fields); ++i) {
326         ir_value_delete(self->fields[i]);
327     }
328     vec_free(self->fields);
329     vec_free(self->filenames);
330     vec_free(self->filestrings);
331     mem_d(self);
332 }
333
334 bool ir_builder_set_name(ir_builder *self, const char *name)
335 {
336     if (self->name)
337         mem_d((void*)self->name);
338     self->name = util_strdup(name);
339     return !!self->name;
340 }
341
342 ir_function* ir_builder_get_function(ir_builder *self, const char *name)
343 {
344     return (ir_function*)util_htget(self->htfunctions, name);
345 }
346
347 ir_function* ir_builder_create_function(ir_builder *self, const char *name, int outtype)
348 {
349     ir_function *fn = ir_builder_get_function(self, name);
350     if (fn) {
351         return NULL;
352     }
353
354     fn = ir_function_new(self, outtype);
355     if (!ir_function_set_name(fn, name))
356     {
357         ir_function_delete(fn);
358         return NULL;
359     }
360     vec_push(self->functions, fn);
361     util_htset(self->htfunctions, name, fn);
362
363     fn->value = ir_builder_create_global(self, fn->name, TYPE_FUNCTION);
364     if (!fn->value) {
365         ir_function_delete(fn);
366         return NULL;
367     }
368
369     fn->value->hasvalue = true;
370     fn->value->outtype = outtype;
371     fn->value->constval.vfunc = fn;
372     fn->value->context = fn->context;
373
374     return fn;
375 }
376
377 ir_value* ir_builder_get_global(ir_builder *self, const char *name)
378 {
379     return (ir_value*)util_htget(self->htglobals, name);
380 }
381
382 ir_value* ir_builder_create_global(ir_builder *self, const char *name, int vtype)
383 {
384     ir_value *ve;
385
386     if (name && name[0] != '#')
387     {
388         ve = ir_builder_get_global(self, name);
389         if (ve) {
390             return NULL;
391         }
392     }
393
394     ve = ir_value_var(name, store_global, vtype);
395     vec_push(self->globals, ve);
396     util_htset(self->htglobals, name, ve);
397     return ve;
398 }
399
400 ir_value* ir_builder_get_field(ir_builder *self, const char *name)
401 {
402     return (ir_value*)util_htget(self->htfields, name);
403 }
404
405
406 ir_value* ir_builder_create_field(ir_builder *self, const char *name, int vtype)
407 {
408     ir_value *ve = ir_builder_get_field(self, name);
409     if (ve) {
410         return NULL;
411     }
412
413     ve = ir_value_var(name, store_global, TYPE_FIELD);
414     ve->fieldtype = vtype;
415     vec_push(self->fields, ve);
416     util_htset(self->htfields, name, ve);
417     return ve;
418 }
419
420 /***********************************************************************
421  *IR Function
422  */
423
424 bool ir_function_naive_phi(ir_function*);
425 void ir_function_enumerate(ir_function*);
426 bool ir_function_calculate_liferanges(ir_function*);
427 bool ir_function_allocate_locals(ir_function*);
428
429 ir_function* ir_function_new(ir_builder* owner, int outtype)
430 {
431     ir_function *self;
432     self = (ir_function*)mem_a(sizeof(*self));
433
434     if (!self)
435         return NULL;
436
437     memset(self, 0, sizeof(*self));
438
439     self->name = NULL;
440     if (!ir_function_set_name(self, "<@unnamed>")) {
441         mem_d(self);
442         return NULL;
443     }
444     self->owner = owner;
445     self->context.file = "<@no context>";
446     self->context.line = 0;
447     self->outtype = outtype;
448     self->value = NULL;
449     self->builtin = 0;
450
451     self->params = NULL;
452     self->blocks = NULL;
453     self->values = NULL;
454     self->locals = NULL;
455
456     self->code_function_def = -1;
457     self->allocated_locals = 0;
458
459     self->run_id = 0;
460     return self;
461 }
462
463 bool ir_function_set_name(ir_function *self, const char *name)
464 {
465     if (self->name)
466         mem_d((void*)self->name);
467     self->name = util_strdup(name);
468     return !!self->name;
469 }
470
471 static void ir_function_delete_quick(ir_function *self)
472 {
473     size_t i;
474     mem_d((void*)self->name);
475
476     for (i = 0; i != vec_size(self->blocks); ++i)
477         ir_block_delete_quick(self->blocks[i]);
478     vec_free(self->blocks);
479
480     vec_free(self->params);
481
482     for (i = 0; i != vec_size(self->values); ++i)
483         ir_value_delete(self->values[i]);
484     vec_free(self->values);
485
486     for (i = 0; i != vec_size(self->locals); ++i)
487         ir_value_delete(self->locals[i]);
488     vec_free(self->locals);
489
490     /* self->value is deleted by the builder */
491
492     mem_d(self);
493 }
494
495 void ir_function_delete(ir_function *self)
496 {
497     size_t i;
498     mem_d((void*)self->name);
499
500     for (i = 0; i != vec_size(self->blocks); ++i)
501         ir_block_delete(self->blocks[i]);
502     vec_free(self->blocks);
503
504     vec_free(self->params);
505
506     for (i = 0; i != vec_size(self->values); ++i)
507         ir_value_delete(self->values[i]);
508     vec_free(self->values);
509
510     for (i = 0; i != vec_size(self->locals); ++i)
511         ir_value_delete(self->locals[i]);
512     vec_free(self->locals);
513
514     /* self->value is deleted by the builder */
515
516     mem_d(self);
517 }
518
519 void ir_function_collect_value(ir_function *self, ir_value *v)
520 {
521     vec_push(self->values, v);
522 }
523
524 ir_block* ir_function_create_block(lex_ctx ctx, ir_function *self, const char *label)
525 {
526     ir_block* bn = ir_block_new(self, label);
527     bn->context = ctx;
528     vec_push(self->blocks, bn);
529     return bn;
530 }
531
532 static bool instr_is_operation(uint16_t op)
533 {
534     return ( (op >= INSTR_MUL_F  && op <= INSTR_GT) ||
535              (op >= INSTR_LOAD_F && op <= INSTR_LOAD_FNC) ||
536              (op == INSTR_ADDRESS) ||
537              (op >= INSTR_NOT_F  && op <= INSTR_NOT_FNC) ||
538              (op >= INSTR_AND    && op <= INSTR_BITOR) );
539 }
540
541 bool ir_function_pass_minor(ir_function *self)
542 {
543     size_t b;
544
545     for (b = 0; b < vec_size(self->blocks); ++b) {
546         size_t    i;
547         ir_block *block = self->blocks[b];
548
549         if (vec_size(block->instr) < 2)
550             continue;
551
552         for (i = 1; i < vec_size(block->instr); ++i) {
553             ir_instr *store;
554             ir_instr *oper;
555             ir_value *value;
556
557             store = block->instr[i];
558             if (store->opcode < INSTR_STORE_F ||
559                 store->opcode > INSTR_STORE_FNC)
560             {
561                 continue;
562             }
563
564             oper  = block->instr[i-1];
565             if (!instr_is_operation(oper->opcode))
566                 continue;
567
568             value = oper->_ops[0];
569
570             /* only do it for SSA values */
571             if (value->store != store_value)
572                 continue;
573
574             /* don't optimize out the temp if it's used later again */
575             if (vec_size(value->reads) != 1)
576                 continue;
577
578             /* The very next store must use this value */
579             if (value->reads[0] != store)
580                 continue;
581
582             /* And of course the store must _read_ from it, so it's in
583              * OP 1 */
584             if (store->_ops[1] != value)
585                 continue;
586
587             ++optimization_count[OPTIM_MINOR];
588             oper->_ops[0] = store->_ops[0];
589
590             vec_remove(block->instr, i, 1);
591             ir_instr_delete(store);
592         }
593     }
594
595     return true;
596 }
597
598 bool ir_function_pass_tailcall(ir_function *self)
599 {
600     size_t b, p;
601
602     for (b = 0; b < vec_size(self->blocks); ++b) {
603         ir_value *funcval;
604         ir_instr *ret, *call, *store = NULL;
605         ir_block *block = self->blocks[b];
606
607         if (!block->final || vec_size(block->instr) < 2)
608             continue;
609
610         ret = block->instr[vec_size(block->instr)-1];
611         if (ret->opcode != INSTR_DONE && ret->opcode != INSTR_RETURN)
612             continue;
613
614         call = block->instr[vec_size(block->instr)-2];
615         if (call->opcode >= INSTR_STORE_F && call->opcode <= INSTR_STORE_FNC) {
616             /* account for the unoptimized
617              * CALL
618              * STORE %return, %tmp
619              * RETURN %tmp
620              * version
621              */
622             if (vec_size(block->instr) < 3)
623                 continue;
624
625             store = call;
626             call = block->instr[vec_size(block->instr)-3];
627         }
628
629         if (call->opcode < INSTR_CALL0 || call->opcode > INSTR_CALL8)
630             continue;
631
632         if (store) {
633             /* optimize out the STORE */
634             if (ret->_ops[0]   &&
635                 ret->_ops[0]   == store->_ops[0] &&
636                 store->_ops[1] == call->_ops[0])
637             {
638                 ++optimization_count[OPTIM_MINOR];
639                 call->_ops[0] = store->_ops[0];
640                 vec_remove(block->instr, vec_size(block->instr) - 2, 1);
641                 ir_instr_delete(store);
642             }
643             else
644                 continue;
645         }
646
647         if (!call->_ops[0])
648             continue;
649
650         funcval = call->_ops[1];
651         if (!funcval)
652             continue;
653         if (funcval->vtype != TYPE_FUNCTION || funcval->constval.vfunc != self)
654             continue;
655
656         /* now we have a CALL and a RET, check if it's a tailcall */
657         if (ret->_ops[0] && call->_ops[0] != ret->_ops[0])
658             continue;
659
660         ++optimization_count[OPTIM_TAIL_RECURSION];
661         vec_shrinkby(block->instr, 2);
662
663         block->final = false; /* open it back up */
664
665         /* emite parameter-stores */
666         for (p = 0; p < vec_size(call->params); ++p) {
667             /* assert(call->params_count <= self->locals_count); */
668             if (!ir_block_create_store(block, call->context, self->locals[p], call->params[p])) {
669                 irerror(call->context, "failed to create tailcall store instruction for parameter %i", (int)p);
670                 return false;
671             }
672         }
673         if (!ir_block_create_jump(block, call->context, self->blocks[0])) {
674             irerror(call->context, "failed to create tailcall jump");
675             return false;
676         }
677
678         ir_instr_delete(call);
679         ir_instr_delete(ret);
680     }
681
682     return true;
683 }
684
685 bool ir_function_finalize(ir_function *self)
686 {
687     if (self->builtin)
688         return true;
689
690     if (OPTS_OPTIMIZATION(OPTIM_MINOR)) {
691         if (!ir_function_pass_minor(self)) {
692             irerror(self->context, "generic optimization pass broke something in `%s`", self->name);
693             return false;
694         }
695     }
696
697     if (OPTS_OPTIMIZATION(OPTIM_TAIL_RECURSION)) {
698         if (!ir_function_pass_tailcall(self)) {
699             irerror(self->context, "tailcall optimization pass broke something in `%s`", self->name);
700             return false;
701         }
702     }
703
704     if (!ir_function_naive_phi(self))
705         return false;
706
707     ir_function_enumerate(self);
708
709     if (!ir_function_calculate_liferanges(self))
710         return false;
711     if (!ir_function_allocate_locals(self))
712         return false;
713     return true;
714 }
715
716 ir_value* ir_function_create_local(ir_function *self, const char *name, int vtype, bool param)
717 {
718     ir_value *ve;
719
720     if (param &&
721         vec_size(self->locals) &&
722         self->locals[vec_size(self->locals)-1]->store != store_param) {
723         irerror(self->context, "cannot add parameters after adding locals");
724         return NULL;
725     }
726
727     ve = ir_value_var(name, (param ? store_param : store_local), vtype);
728     vec_push(self->locals, ve);
729     return ve;
730 }
731
732 /***********************************************************************
733  *IR Block
734  */
735
736 ir_block* ir_block_new(ir_function* owner, const char *name)
737 {
738     ir_block *self;
739     self = (ir_block*)mem_a(sizeof(*self));
740     if (!self)
741         return NULL;
742
743     memset(self, 0, sizeof(*self));
744
745     self->label = NULL;
746     if (name && !ir_block_set_label(self, name)) {
747         mem_d(self);
748         return NULL;
749     }
750     self->owner = owner;
751     self->context.file = "<@no context>";
752     self->context.line = 0;
753     self->final = false;
754
755     self->instr   = NULL;
756     self->entries = NULL;
757     self->exits   = NULL;
758
759     self->eid = 0;
760     self->is_return = false;
761     self->run_id = 0;
762
763     self->living = NULL;
764
765     self->generated = false;
766
767     return self;
768 }
769
770 static void ir_block_delete_quick(ir_block* self)
771 {
772     size_t i;
773     if (self->label) mem_d(self->label);
774     for (i = 0; i != vec_size(self->instr); ++i)
775         ir_instr_delete_quick(self->instr[i]);
776     vec_free(self->instr);
777     vec_free(self->entries);
778     vec_free(self->exits);
779     vec_free(self->living);
780     mem_d(self);
781 }
782
783 void ir_block_delete(ir_block* self)
784 {
785     size_t i;
786     if (self->label) mem_d(self->label);
787     for (i = 0; i != vec_size(self->instr); ++i)
788         ir_instr_delete(self->instr[i]);
789     vec_free(self->instr);
790     vec_free(self->entries);
791     vec_free(self->exits);
792     vec_free(self->living);
793     mem_d(self);
794 }
795
796 bool ir_block_set_label(ir_block *self, const char *name)
797 {
798     if (self->label)
799         mem_d((void*)self->label);
800     self->label = util_strdup(name);
801     return !!self->label;
802 }
803
804 /***********************************************************************
805  *IR Instructions
806  */
807
808 ir_instr* ir_instr_new(lex_ctx ctx, ir_block* owner, int op)
809 {
810     ir_instr *self;
811     self = (ir_instr*)mem_a(sizeof(*self));
812     if (!self)
813         return NULL;
814
815     self->owner = owner;
816     self->context = ctx;
817     self->opcode = op;
818     self->_ops[0] = NULL;
819     self->_ops[1] = NULL;
820     self->_ops[2] = NULL;
821     self->bops[0] = NULL;
822     self->bops[1] = NULL;
823
824     self->phi    = NULL;
825     self->params = NULL;
826
827     self->eid = 0;
828
829     self->likely = true;
830     return self;
831 }
832
833 static void ir_instr_delete_quick(ir_instr *self)
834 {
835     vec_free(self->phi);
836     vec_free(self->params);
837     mem_d(self);
838 }
839
840 void ir_instr_delete(ir_instr *self)
841 {
842     size_t i;
843     /* The following calls can only delete from
844      * vectors, we still want to delete this instruction
845      * so ignore the return value. Since with the warn_unused_result attribute
846      * gcc doesn't care about an explicit: (void)foo(); to ignore the result,
847      * I have to improvise here and use if(foo());
848      */
849     for (i = 0; i < vec_size(self->phi); ++i) {
850         size_t idx;
851         if (vec_ir_instr_find(self->phi[i].value->writes, self, &idx))
852             vec_remove(self->phi[i].value->writes, idx, 1);
853         if (vec_ir_instr_find(self->phi[i].value->reads, self, &idx))
854             vec_remove(self->phi[i].value->reads, idx, 1);
855     }
856     vec_free(self->phi);
857     for (i = 0; i < vec_size(self->params); ++i) {
858         size_t idx;
859         if (vec_ir_instr_find(self->params[i]->writes, self, &idx))
860             vec_remove(self->params[i]->writes, idx, 1);
861         if (vec_ir_instr_find(self->params[i]->reads, self, &idx))
862             vec_remove(self->params[i]->reads, idx, 1);
863     }
864     vec_free(self->params);
865     (void)!ir_instr_op(self, 0, NULL, false);
866     (void)!ir_instr_op(self, 1, NULL, false);
867     (void)!ir_instr_op(self, 2, NULL, false);
868     mem_d(self);
869 }
870
871 bool ir_instr_op(ir_instr *self, int op, ir_value *v, bool writing)
872 {
873     if (self->_ops[op]) {
874         size_t idx;
875         if (writing && vec_ir_instr_find(self->_ops[op]->writes, self, &idx))
876             vec_remove(self->_ops[op]->writes, idx, 1);
877         else if (vec_ir_instr_find(self->_ops[op]->reads, self, &idx))
878             vec_remove(self->_ops[op]->reads, idx, 1);
879     }
880     if (v) {
881         if (writing)
882             vec_push(v->writes, self);
883         else
884             vec_push(v->reads, self);
885     }
886     self->_ops[op] = v;
887     return true;
888 }
889
890 /***********************************************************************
891  *IR Value
892  */
893
894 void ir_value_code_setaddr(ir_value *self, int32_t gaddr)
895 {
896     self->code.globaladdr = gaddr;
897     if (self->members[0]) self->members[0]->code.globaladdr = gaddr;
898     if (self->members[1]) self->members[1]->code.globaladdr = gaddr;
899     if (self->members[2]) self->members[2]->code.globaladdr = gaddr;
900 }
901
902 int32_t ir_value_code_addr(const ir_value *self)
903 {
904     if (self->store == store_return)
905         return OFS_RETURN + self->code.addroffset;
906     return self->code.globaladdr + self->code.addroffset;
907 }
908
909 ir_value* ir_value_var(const char *name, int storetype, int vtype)
910 {
911     ir_value *self;
912     self = (ir_value*)mem_a(sizeof(*self));
913     self->vtype = vtype;
914     self->fieldtype = TYPE_VOID;
915     self->outtype = TYPE_VOID;
916     self->store = storetype;
917
918     self->reads  = NULL;
919     self->writes = NULL;
920
921     self->cvq          = CV_NONE;
922     self->hasvalue     = false;
923     self->context.file = "<@no context>";
924     self->context.line = 0;
925     self->name = NULL;
926     if (name && !ir_value_set_name(self, name)) {
927         irerror(self->context, "out of memory");
928         mem_d(self);
929         return NULL;
930     }
931
932     memset(&self->constval, 0, sizeof(self->constval));
933     memset(&self->code,     0, sizeof(self->code));
934
935     self->members[0] = NULL;
936     self->members[1] = NULL;
937     self->members[2] = NULL;
938     self->memberof = NULL;
939
940     self->life = NULL;
941     return self;
942 }
943
944 ir_value* ir_value_vector_member(ir_value *self, unsigned int member)
945 {
946     ir_value *m;
947     if (member >= 3)
948         return NULL;
949
950     if (self->members[member])
951         return self->members[member];
952
953     if (self->vtype == TYPE_VECTOR)
954     {
955         m = ir_value_var(self->name, self->store, TYPE_FLOAT);
956         if (!m)
957             return NULL;
958         m->context = self->context;
959
960         self->members[member] = m;
961         m->code.addroffset = member;
962     }
963     else if (self->vtype == TYPE_FIELD)
964     {
965         if (self->fieldtype != TYPE_VECTOR)
966             return NULL;
967         m = ir_value_var(self->name, self->store, TYPE_FIELD);
968         if (!m)
969             return NULL;
970         m->fieldtype = TYPE_FLOAT;
971         m->context = self->context;
972
973         self->members[member] = m;
974         m->code.addroffset = member;
975     }
976     else
977     {
978         irerror(self->context, "invalid member access on %s", self->name);
979         return NULL;
980     }
981
982     m->memberof = self;
983     return m;
984 }
985
986 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
987 {
988     ir_value *v = ir_value_var(name, storetype, vtype);
989     if (!v)
990         return NULL;
991     ir_function_collect_value(owner, v);
992     return v;
993 }
994
995 void ir_value_delete(ir_value* self)
996 {
997     size_t i;
998     if (self->name)
999         mem_d((void*)self->name);
1000     if (self->hasvalue)
1001     {
1002         if (self->vtype == TYPE_STRING)
1003             mem_d((void*)self->constval.vstring);
1004     }
1005     for (i = 0; i < 3; ++i) {
1006         if (self->members[i])
1007             ir_value_delete(self->members[i]);
1008     }
1009     vec_free(self->reads);
1010     vec_free(self->writes);
1011     vec_free(self->life);
1012     mem_d(self);
1013 }
1014
1015 bool ir_value_set_name(ir_value *self, const char *name)
1016 {
1017     if (self->name)
1018         mem_d((void*)self->name);
1019     self->name = util_strdup(name);
1020     return !!self->name;
1021 }
1022
1023 bool ir_value_set_float(ir_value *self, float f)
1024 {
1025     if (self->vtype != TYPE_FLOAT)
1026         return false;
1027     self->constval.vfloat = f;
1028     self->hasvalue = true;
1029     return true;
1030 }
1031
1032 bool ir_value_set_func(ir_value *self, int f)
1033 {
1034     if (self->vtype != TYPE_FUNCTION)
1035         return false;
1036     self->constval.vint = f;
1037     self->hasvalue = true;
1038     return true;
1039 }
1040
1041 bool ir_value_set_vector(ir_value *self, vector v)
1042 {
1043     if (self->vtype != TYPE_VECTOR)
1044         return false;
1045     self->constval.vvec = v;
1046     self->hasvalue = true;
1047     return true;
1048 }
1049
1050 bool ir_value_set_field(ir_value *self, ir_value *fld)
1051 {
1052     if (self->vtype != TYPE_FIELD)
1053         return false;
1054     self->constval.vpointer = fld;
1055     self->hasvalue = true;
1056     return true;
1057 }
1058
1059 static char *ir_strdup(const char *str)
1060 {
1061     if (str && !*str) {
1062         /* actually dup empty strings */
1063         char *out = mem_a(1);
1064         *out = 0;
1065         return out;
1066     }
1067     return util_strdup(str);
1068 }
1069
1070 bool ir_value_set_string(ir_value *self, const char *str)
1071 {
1072     if (self->vtype != TYPE_STRING)
1073         return false;
1074     self->constval.vstring = ir_strdup(str);
1075     self->hasvalue = true;
1076     return true;
1077 }
1078
1079 #if 0
1080 bool ir_value_set_int(ir_value *self, int i)
1081 {
1082     if (self->vtype != TYPE_INTEGER)
1083         return false;
1084     self->constval.vint = i;
1085     self->hasvalue = true;
1086     return true;
1087 }
1088 #endif
1089
1090 bool ir_value_lives(ir_value *self, size_t at)
1091 {
1092     size_t i;
1093     for (i = 0; i < vec_size(self->life); ++i)
1094     {
1095         ir_life_entry_t *life = &self->life[i];
1096         if (life->start <= at && at <= life->end)
1097             return true;
1098         if (life->start > at) /* since it's ordered */
1099             return false;
1100     }
1101     return false;
1102 }
1103
1104 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
1105 {
1106     size_t k;
1107     vec_push(self->life, e);
1108     for (k = vec_size(self->life)-1; k > idx; --k)
1109         self->life[k] = self->life[k-1];
1110     self->life[idx] = e;
1111     return true;
1112 }
1113
1114 bool ir_value_life_merge(ir_value *self, size_t s)
1115 {
1116     size_t i;
1117     ir_life_entry_t *life = NULL;
1118     ir_life_entry_t *before = NULL;
1119     ir_life_entry_t new_entry;
1120
1121     /* Find the first range >= s */
1122     for (i = 0; i < vec_size(self->life); ++i)
1123     {
1124         before = life;
1125         life = &self->life[i];
1126         if (life->start > s)
1127             break;
1128     }
1129     /* nothing found? append */
1130     if (i == vec_size(self->life)) {
1131         ir_life_entry_t e;
1132         if (life && life->end+1 == s)
1133         {
1134             /* previous life range can be merged in */
1135             life->end++;
1136             return true;
1137         }
1138         if (life && life->end >= s)
1139             return false;
1140         e.start = e.end = s;
1141         vec_push(self->life, e);
1142         return true;
1143     }
1144     /* found */
1145     if (before)
1146     {
1147         if (before->end + 1 == s &&
1148             life->start - 1 == s)
1149         {
1150             /* merge */
1151             before->end = life->end;
1152             vec_remove(self->life, i, 1);
1153             return true;
1154         }
1155         if (before->end + 1 == s)
1156         {
1157             /* extend before */
1158             before->end++;
1159             return true;
1160         }
1161         /* already contained */
1162         if (before->end >= s)
1163             return false;
1164     }
1165     /* extend */
1166     if (life->start - 1 == s)
1167     {
1168         life->start--;
1169         return true;
1170     }
1171     /* insert a new entry */
1172     new_entry.start = new_entry.end = s;
1173     return ir_value_life_insert(self, i, new_entry);
1174 }
1175
1176 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1177 {
1178     size_t i, myi;
1179
1180     if (!vec_size(other->life))
1181         return true;
1182
1183     if (!vec_size(self->life)) {
1184         size_t count = vec_size(other->life);
1185         ir_life_entry_t *life = vec_add(self->life, count);
1186         memcpy(life, other->life, count * sizeof(*life));
1187         return true;
1188     }
1189
1190     myi = 0;
1191     for (i = 0; i < vec_size(other->life); ++i)
1192     {
1193         const ir_life_entry_t *life = &other->life[i];
1194         while (true)
1195         {
1196             ir_life_entry_t *entry = &self->life[myi];
1197
1198             if (life->end+1 < entry->start)
1199             {
1200                 /* adding an interval before entry */
1201                 if (!ir_value_life_insert(self, myi, *life))
1202                     return false;
1203                 ++myi;
1204                 break;
1205             }
1206
1207             if (life->start <  entry->start &&
1208                 life->end+1 >= entry->start)
1209             {
1210                 /* starts earlier and overlaps */
1211                 entry->start = life->start;
1212             }
1213
1214             if (life->end   >  entry->end &&
1215                 life->start <= entry->end+1)
1216             {
1217                 /* ends later and overlaps */
1218                 entry->end = life->end;
1219             }
1220
1221             /* see if our change combines it with the next ranges */
1222             while (myi+1 < vec_size(self->life) &&
1223                    entry->end+1 >= self->life[1+myi].start)
1224             {
1225                 /* overlaps with (myi+1) */
1226                 if (entry->end < self->life[1+myi].end)
1227                     entry->end = self->life[1+myi].end;
1228                 vec_remove(self->life, myi+1, 1);
1229                 entry = &self->life[myi];
1230             }
1231
1232             /* see if we're after the entry */
1233             if (life->start > entry->end)
1234             {
1235                 ++myi;
1236                 /* append if we're at the end */
1237                 if (myi >= vec_size(self->life)) {
1238                     vec_push(self->life, *life);
1239                     break;
1240                 }
1241                 /* otherweise check the next range */
1242                 continue;
1243             }
1244             break;
1245         }
1246     }
1247     return true;
1248 }
1249
1250 bool ir_values_overlap(const ir_value *a, const ir_value *b)
1251 {
1252     /* For any life entry in A see if it overlaps with
1253      * any life entry in B.
1254      * Note that the life entries are orderes, so we can make a
1255      * more efficient algorithm there than naively translating the
1256      * statement above.
1257      */
1258
1259     ir_life_entry_t *la, *lb, *enda, *endb;
1260
1261     /* first of all, if either has no life range, they cannot clash */
1262     if (!vec_size(a->life) || !vec_size(b->life))
1263         return false;
1264
1265     la = a->life;
1266     lb = b->life;
1267     enda = la + vec_size(a->life);
1268     endb = lb + vec_size(b->life);
1269     while (true)
1270     {
1271         /* check if the entries overlap, for that,
1272          * both must start before the other one ends.
1273          */
1274         if (la->start < lb->end &&
1275             lb->start < la->end)
1276         {
1277             return true;
1278         }
1279
1280         /* entries are ordered
1281          * one entry is earlier than the other
1282          * that earlier entry will be moved forward
1283          */
1284         if (la->start < lb->start)
1285         {
1286             /* order: A B, move A forward
1287              * check if we hit the end with A
1288              */
1289             if (++la == enda)
1290                 break;
1291         }
1292         else /* if (lb->start < la->start)  actually <= */
1293         {
1294             /* order: B A, move B forward
1295              * check if we hit the end with B
1296              */
1297             if (++lb == endb)
1298                 break;
1299         }
1300     }
1301     return false;
1302 }
1303
1304 /***********************************************************************
1305  *IR main operations
1306  */
1307
1308 bool ir_block_create_store_op(ir_block *self, lex_ctx ctx, int op, ir_value *target, ir_value *what)
1309 {
1310     ir_instr *in;
1311     if (self->final) {
1312         irerror(self->context, "unreachable statement (%s)", self->label);
1313         return false;
1314     }
1315     in = ir_instr_new(ctx, self, op);
1316     if (!in)
1317         return false;
1318
1319     if (target->store == store_value &&
1320         (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1321     {
1322         irerror(self->context, "cannot store to an SSA value");
1323         irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1324         irerror(self->context, "instruction: %s", asm_instr[op].m);
1325         return false;
1326     }
1327
1328     if (!ir_instr_op(in, 0, target, true) ||
1329         !ir_instr_op(in, 1, what, false))
1330     {
1331         return false;
1332     }
1333     vec_push(self->instr, in);
1334     return true;
1335 }
1336
1337 bool ir_block_create_store(ir_block *self, lex_ctx ctx, ir_value *target, ir_value *what)
1338 {
1339     int op = 0;
1340     int vtype;
1341     if (target->vtype == TYPE_VARIANT)
1342         vtype = what->vtype;
1343     else
1344         vtype = target->vtype;
1345
1346 #if 0
1347     if      (vtype == TYPE_FLOAT   && what->vtype == TYPE_INTEGER)
1348         op = INSTR_CONV_ITOF;
1349     else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1350         op = INSTR_CONV_FTOI;
1351 #endif
1352         op = type_store_instr[vtype];
1353
1354     if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1355         if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1356             op = INSTR_STORE_V;
1357     }
1358
1359     return ir_block_create_store_op(self, ctx, op, target, what);
1360 }
1361
1362 bool ir_block_create_storep(ir_block *self, lex_ctx ctx, ir_value *target, ir_value *what)
1363 {
1364     int op = 0;
1365     int vtype;
1366
1367     if (target->vtype != TYPE_POINTER)
1368         return false;
1369
1370     /* storing using pointer - target is a pointer, type must be
1371      * inferred from source
1372      */
1373     vtype = what->vtype;
1374
1375     op = type_storep_instr[vtype];
1376     if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1377         if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1378             op = INSTR_STOREP_V;
1379     }
1380
1381     return ir_block_create_store_op(self, ctx, op, target, what);
1382 }
1383
1384 bool ir_block_create_return(ir_block *self, lex_ctx ctx, ir_value *v)
1385 {
1386     ir_instr *in;
1387     if (self->final) {
1388         irerror(self->context, "unreachable statement (%s)", self->label);
1389         return false;
1390     }
1391     self->final = true;
1392     self->is_return = true;
1393     in = ir_instr_new(ctx, self, INSTR_RETURN);
1394     if (!in)
1395         return false;
1396
1397     if (v && !ir_instr_op(in, 0, v, false))
1398         return false;
1399
1400     vec_push(self->instr, in);
1401     return true;
1402 }
1403
1404 bool ir_block_create_if(ir_block *self, lex_ctx ctx, ir_value *v,
1405                         ir_block *ontrue, ir_block *onfalse)
1406 {
1407     ir_instr *in;
1408     if (self->final) {
1409         irerror(self->context, "unreachable statement (%s)", self->label);
1410         return false;
1411     }
1412     self->final = true;
1413     /*in = ir_instr_new(ctx, self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1414     in = ir_instr_new(ctx, self, VINSTR_COND);
1415     if (!in)
1416         return false;
1417
1418     if (!ir_instr_op(in, 0, v, false)) {
1419         ir_instr_delete(in);
1420         return false;
1421     }
1422
1423     in->bops[0] = ontrue;
1424     in->bops[1] = onfalse;
1425
1426     vec_push(self->instr, in);
1427
1428     vec_push(self->exits, ontrue);
1429     vec_push(self->exits, onfalse);
1430     vec_push(ontrue->entries,  self);
1431     vec_push(onfalse->entries, self);
1432     return true;
1433 }
1434
1435 bool ir_block_create_jump(ir_block *self, lex_ctx ctx, ir_block *to)
1436 {
1437     ir_instr *in;
1438     if (self->final) {
1439         irerror(self->context, "unreachable statement (%s)", self->label);
1440         return false;
1441     }
1442     self->final = true;
1443     in = ir_instr_new(ctx, self, VINSTR_JUMP);
1444     if (!in)
1445         return false;
1446
1447     in->bops[0] = to;
1448     vec_push(self->instr, in);
1449
1450     vec_push(self->exits, to);
1451     vec_push(to->entries, self);
1452     return true;
1453 }
1454
1455 bool ir_block_create_goto(ir_block *self, lex_ctx ctx, ir_block *to)
1456 {
1457     ir_instr *in;
1458     if (self->final) {
1459         irerror(self->context, "unreachable statement (%s)", self->label);
1460         return false;
1461     }
1462     self->final = true;
1463     in = ir_instr_new(ctx, self, INSTR_GOTO);
1464     if (!in)
1465         return false;
1466
1467     in->bops[0] = to;
1468     vec_push(self->instr, in);
1469
1470     vec_push(self->exits, to);
1471     vec_push(to->entries, self);
1472     return true;
1473 }
1474
1475 ir_instr* ir_block_create_phi(ir_block *self, lex_ctx ctx, const char *label, int ot)
1476 {
1477     ir_value *out;
1478     ir_instr *in;
1479     in = ir_instr_new(ctx, self, VINSTR_PHI);
1480     if (!in)
1481         return NULL;
1482     out = ir_value_out(self->owner, label, store_value, ot);
1483     if (!out) {
1484         ir_instr_delete(in);
1485         return NULL;
1486     }
1487     if (!ir_instr_op(in, 0, out, true)) {
1488         ir_instr_delete(in);
1489         ir_value_delete(out);
1490         return NULL;
1491     }
1492     vec_push(self->instr, in);
1493     return in;
1494 }
1495
1496 ir_value* ir_phi_value(ir_instr *self)
1497 {
1498     return self->_ops[0];
1499 }
1500
1501 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1502 {
1503     ir_phi_entry_t pe;
1504
1505     if (!vec_ir_block_find(self->owner->entries, b, NULL)) {
1506         /* Must not be possible to cause this, otherwise the AST
1507          * is doing something wrong.
1508          */
1509         irerror(self->context, "Invalid entry block for PHI");
1510         abort();
1511     }
1512
1513     pe.value = v;
1514     pe.from = b;
1515     vec_push(v->reads, self);
1516     vec_push(self->phi, pe);
1517 }
1518
1519 /* call related code */
1520 ir_instr* ir_block_create_call(ir_block *self, lex_ctx ctx, const char *label, ir_value *func)
1521 {
1522     ir_value *out;
1523     ir_instr *in;
1524     in = ir_instr_new(ctx, self, INSTR_CALL0);
1525     if (!in)
1526         return NULL;
1527     out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1528     if (!out) {
1529         ir_instr_delete(in);
1530         return NULL;
1531     }
1532     if (!ir_instr_op(in, 0, out, true) ||
1533         !ir_instr_op(in, 1, func, false))
1534     {
1535         ir_instr_delete(in);
1536         ir_value_delete(out);
1537         return NULL;
1538     }
1539     vec_push(self->instr, in);
1540     return in;
1541 }
1542
1543 ir_value* ir_call_value(ir_instr *self)
1544 {
1545     return self->_ops[0];
1546 }
1547
1548 void ir_call_param(ir_instr* self, ir_value *v)
1549 {
1550     vec_push(self->params, v);
1551     vec_push(v->reads, self);
1552 }
1553
1554 /* binary op related code */
1555
1556 ir_value* ir_block_create_binop(ir_block *self, lex_ctx ctx,
1557                                 const char *label, int opcode,
1558                                 ir_value *left, ir_value *right)
1559 {
1560     int ot = TYPE_VOID;
1561     switch (opcode) {
1562         case INSTR_ADD_F:
1563         case INSTR_SUB_F:
1564         case INSTR_DIV_F:
1565         case INSTR_MUL_F:
1566         case INSTR_MUL_V:
1567         case INSTR_AND:
1568         case INSTR_OR:
1569 #if 0
1570         case INSTR_AND_I:
1571         case INSTR_AND_IF:
1572         case INSTR_AND_FI:
1573         case INSTR_OR_I:
1574         case INSTR_OR_IF:
1575         case INSTR_OR_FI:
1576 #endif
1577         case INSTR_BITAND:
1578         case INSTR_BITOR:
1579 #if 0
1580         case INSTR_SUB_S: /* -- offset of string as float */
1581         case INSTR_MUL_IF:
1582         case INSTR_MUL_FI:
1583         case INSTR_DIV_IF:
1584         case INSTR_DIV_FI:
1585         case INSTR_BITOR_IF:
1586         case INSTR_BITOR_FI:
1587         case INSTR_BITAND_FI:
1588         case INSTR_BITAND_IF:
1589         case INSTR_EQ_I:
1590         case INSTR_NE_I:
1591 #endif
1592             ot = TYPE_FLOAT;
1593             break;
1594 #if 0
1595         case INSTR_ADD_I:
1596         case INSTR_ADD_IF:
1597         case INSTR_ADD_FI:
1598         case INSTR_SUB_I:
1599         case INSTR_SUB_FI:
1600         case INSTR_SUB_IF:
1601         case INSTR_MUL_I:
1602         case INSTR_DIV_I:
1603         case INSTR_BITAND_I:
1604         case INSTR_BITOR_I:
1605         case INSTR_XOR_I:
1606         case INSTR_RSHIFT_I:
1607         case INSTR_LSHIFT_I:
1608             ot = TYPE_INTEGER;
1609             break;
1610 #endif
1611         case INSTR_ADD_V:
1612         case INSTR_SUB_V:
1613         case INSTR_MUL_VF:
1614         case INSTR_MUL_FV:
1615 #if 0
1616         case INSTR_DIV_VF:
1617         case INSTR_MUL_IV:
1618         case INSTR_MUL_VI:
1619 #endif
1620             ot = TYPE_VECTOR;
1621             break;
1622 #if 0
1623         case INSTR_ADD_SF:
1624             ot = TYPE_POINTER;
1625             break;
1626 #endif
1627         default:
1628             /* ranges: */
1629             /* boolean operations result in floats */
1630             if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1631                 ot = TYPE_FLOAT;
1632             else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1633                 ot = TYPE_FLOAT;
1634 #if 0
1635             else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1636                 ot = TYPE_FLOAT;
1637 #endif
1638             break;
1639     };
1640     if (ot == TYPE_VOID) {
1641         /* The AST or parser were supposed to check this! */
1642         return NULL;
1643     }
1644
1645     return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1646 }
1647
1648 ir_value* ir_block_create_unary(ir_block *self, lex_ctx ctx,
1649                                 const char *label, int opcode,
1650                                 ir_value *operand)
1651 {
1652     int ot = TYPE_FLOAT;
1653     switch (opcode) {
1654         case INSTR_NOT_F:
1655         case INSTR_NOT_V:
1656         case INSTR_NOT_S:
1657         case INSTR_NOT_ENT:
1658         case INSTR_NOT_FNC:
1659 #if 0
1660         case INSTR_NOT_I:
1661 #endif
1662             ot = TYPE_FLOAT;
1663             break;
1664         /* QC doesn't have other unary operations. We expect extensions to fill
1665          * the above list, otherwise we assume out-type = in-type, eg for an
1666          * unary minus
1667          */
1668         default:
1669             ot = operand->vtype;
1670             break;
1671     };
1672     if (ot == TYPE_VOID) {
1673         /* The AST or parser were supposed to check this! */
1674         return NULL;
1675     }
1676
1677     /* let's use the general instruction creator and pass NULL for OPB */
1678     return ir_block_create_general_instr(self, ctx, label, opcode, operand, NULL, ot);
1679 }
1680
1681 ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx ctx, const char *label,
1682                                         int op, ir_value *a, ir_value *b, int outype)
1683 {
1684     ir_instr *instr;
1685     ir_value *out;
1686
1687     out = ir_value_out(self->owner, label, store_value, outype);
1688     if (!out)
1689         return NULL;
1690
1691     instr = ir_instr_new(ctx, self, op);
1692     if (!instr) {
1693         ir_value_delete(out);
1694         return NULL;
1695     }
1696
1697     if (!ir_instr_op(instr, 0, out, true) ||
1698         !ir_instr_op(instr, 1, a, false) ||
1699         !ir_instr_op(instr, 2, b, false) )
1700     {
1701         goto on_error;
1702     }
1703
1704     vec_push(self->instr, instr);
1705
1706     return out;
1707 on_error:
1708     ir_instr_delete(instr);
1709     ir_value_delete(out);
1710     return NULL;
1711 }
1712
1713 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx ctx, const char *label, ir_value *ent, ir_value *field)
1714 {
1715     ir_value *v;
1716
1717     /* Support for various pointer types todo if so desired */
1718     if (ent->vtype != TYPE_ENTITY)
1719         return NULL;
1720
1721     if (field->vtype != TYPE_FIELD)
1722         return NULL;
1723
1724     v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1725     v->fieldtype = field->fieldtype;
1726     return v;
1727 }
1728
1729 ir_value* ir_block_create_load_from_ent(ir_block *self, lex_ctx ctx, const char *label, ir_value *ent, ir_value *field, int outype)
1730 {
1731     int op;
1732     if (ent->vtype != TYPE_ENTITY)
1733         return NULL;
1734
1735     /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1736     if (field->vtype != TYPE_FIELD)
1737         return NULL;
1738
1739     switch (outype)
1740     {
1741         case TYPE_FLOAT:    op = INSTR_LOAD_F;   break;
1742         case TYPE_VECTOR:   op = INSTR_LOAD_V;   break;
1743         case TYPE_STRING:   op = INSTR_LOAD_S;   break;
1744         case TYPE_FIELD:    op = INSTR_LOAD_FLD; break;
1745         case TYPE_ENTITY:   op = INSTR_LOAD_ENT; break;
1746         case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1747 #if 0
1748         case TYPE_POINTER: op = INSTR_LOAD_I;   break;
1749         case TYPE_INTEGER: op = INSTR_LOAD_I;   break;
1750 #endif
1751         default:
1752             irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1753             return NULL;
1754     }
1755
1756     return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
1757 }
1758
1759 ir_value* ir_block_create_add(ir_block *self, lex_ctx ctx,
1760                               const char *label,
1761                               ir_value *left, ir_value *right)
1762 {
1763     int op = 0;
1764     int l = left->vtype;
1765     int r = right->vtype;
1766     if (l == r) {
1767         switch (l) {
1768             default:
1769                 irerror(self->context, "invalid type for ir_block_create_add: %s", type_name[l]);
1770                 return NULL;
1771             case TYPE_FLOAT:
1772                 op = INSTR_ADD_F;
1773                 break;
1774 #if 0
1775             case TYPE_INTEGER:
1776                 op = INSTR_ADD_I;
1777                 break;
1778 #endif
1779             case TYPE_VECTOR:
1780                 op = INSTR_ADD_V;
1781                 break;
1782         }
1783     } else {
1784 #if 0
1785         if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1786             op = INSTR_ADD_FI;
1787         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1788             op = INSTR_ADD_IF;
1789         else
1790 #endif
1791         {
1792             irerror(self->context, "invalid type for ir_block_create_add: %s", type_name[l]);
1793             return NULL;
1794         }
1795     }
1796     return ir_block_create_binop(self, ctx, label, op, left, right);
1797 }
1798
1799 ir_value* ir_block_create_sub(ir_block *self, lex_ctx ctx,
1800                               const char *label,
1801                               ir_value *left, ir_value *right)
1802 {
1803     int op = 0;
1804     int l = left->vtype;
1805     int r = right->vtype;
1806     if (l == r) {
1807
1808         switch (l) {
1809             default:
1810                 irerror(self->context, "invalid type for ir_block_create_sub: %s", type_name[l]);
1811                 return NULL;
1812             case TYPE_FLOAT:
1813                 op = INSTR_SUB_F;
1814                 break;
1815 #if 0
1816             case TYPE_INTEGER:
1817                 op = INSTR_SUB_I;
1818                 break;
1819 #endif
1820             case TYPE_VECTOR:
1821                 op = INSTR_SUB_V;
1822                 break;
1823         }
1824     } else {
1825 #if 0
1826         if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1827             op = INSTR_SUB_FI;
1828         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1829             op = INSTR_SUB_IF;
1830         else
1831 #endif
1832         {
1833             irerror(self->context, "invalid type for ir_block_create_sub: %s", type_name[l]);
1834             return NULL;
1835         }
1836     }
1837     return ir_block_create_binop(self, ctx, label, op, left, right);
1838 }
1839
1840 ir_value* ir_block_create_mul(ir_block *self, lex_ctx ctx,
1841                               const char *label,
1842                               ir_value *left, ir_value *right)
1843 {
1844     int op = 0;
1845     int l = left->vtype;
1846     int r = right->vtype;
1847     if (l == r) {
1848
1849         switch (l) {
1850             default:
1851                 irerror(self->context, "invalid type for ir_block_create_mul: %s", type_name[l]);
1852                 return NULL;
1853             case TYPE_FLOAT:
1854                 op = INSTR_MUL_F;
1855                 break;
1856 #if 0
1857             case TYPE_INTEGER:
1858                 op = INSTR_MUL_I;
1859                 break;
1860 #endif
1861             case TYPE_VECTOR:
1862                 op = INSTR_MUL_V;
1863                 break;
1864         }
1865     } else {
1866         if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1867             op = INSTR_MUL_VF;
1868         else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1869             op = INSTR_MUL_FV;
1870 #if 0
1871         else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1872             op = INSTR_MUL_VI;
1873         else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1874             op = INSTR_MUL_IV;
1875         else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1876             op = INSTR_MUL_FI;
1877         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1878             op = INSTR_MUL_IF;
1879 #endif
1880         else {
1881             irerror(self->context, "invalid type for ir_block_create_mul: %s", type_name[l]);
1882             return NULL;
1883         }
1884     }
1885     return ir_block_create_binop(self, ctx, label, op, left, right);
1886 }
1887
1888 ir_value* ir_block_create_div(ir_block *self, lex_ctx ctx,
1889                               const char *label,
1890                               ir_value *left, ir_value *right)
1891 {
1892     int op = 0;
1893     int l = left->vtype;
1894     int r = right->vtype;
1895     if (l == r) {
1896
1897         switch (l) {
1898             default:
1899                 irerror(self->context, "invalid type for ir_block_create_div: %s", type_name[l]);
1900                 return NULL;
1901             case TYPE_FLOAT:
1902                 op = INSTR_DIV_F;
1903                 break;
1904 #if 0
1905             case TYPE_INTEGER:
1906                 op = INSTR_DIV_I;
1907                 break;
1908 #endif
1909         }
1910     } else {
1911 #if 0
1912         if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1913             op = INSTR_DIV_VF;
1914         else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1915             op = INSTR_DIV_FI;
1916         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1917             op = INSTR_DIV_IF;
1918         else
1919 #endif
1920         {
1921             irerror(self->context, "invalid type for ir_block_create_div: %s", type_name[l]);
1922             return NULL;
1923         }
1924     }
1925     return ir_block_create_binop(self, ctx, label, op, left, right);
1926 }
1927
1928 /* PHI resolving breaks the SSA, and must thus be the last
1929  * step before life-range calculation.
1930  */
1931
1932 static bool ir_block_naive_phi(ir_block *self);
1933 bool ir_function_naive_phi(ir_function *self)
1934 {
1935     size_t i;
1936
1937     for (i = 0; i < vec_size(self->blocks); ++i)
1938     {
1939         if (!ir_block_naive_phi(self->blocks[i]))
1940             return false;
1941     }
1942     return true;
1943 }
1944
1945 #if 0
1946 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1947 {
1948     ir_instr *instr;
1949     size_t i;
1950
1951     /* create a store */
1952     if (!ir_block_create_store(block, old, what))
1953         return false;
1954
1955     /* we now move it up */
1956     instr = vec_last(block->instr);
1957     for (i = vec_size(block->instr)-1; i > iid; --i)
1958         block->instr[i] = block->instr[i-1];
1959     block->instr[i] = instr;
1960
1961     return true;
1962 }
1963 #endif
1964
1965 static bool ir_block_naive_phi(ir_block *self)
1966 {
1967     size_t i, p; /*, w;*/
1968     /* FIXME: optionally, create_phi can add the phis
1969      * to a list so we don't need to loop through blocks
1970      * - anyway: "don't optimize YET"
1971      */
1972     for (i = 0; i < vec_size(self->instr); ++i)
1973     {
1974         ir_instr *instr = self->instr[i];
1975         if (instr->opcode != VINSTR_PHI)
1976             continue;
1977
1978         vec_remove(self->instr, i, 1);
1979         --i; /* NOTE: i+1 below */
1980
1981         for (p = 0; p < vec_size(instr->phi); ++p)
1982         {
1983             ir_value *v = instr->phi[p].value;
1984             ir_block *b = instr->phi[p].from;
1985
1986             if (v->store == store_value &&
1987                 vec_size(v->reads) == 1 &&
1988                 vec_size(v->writes) == 1)
1989             {
1990                 /* replace the value */
1991                 if (!ir_instr_op(v->writes[0], 0, instr->_ops[0], true))
1992                     return false;
1993             }
1994             else
1995             {
1996                 /* force a move instruction */
1997                 ir_instr *prevjump = vec_last(b->instr);
1998                 vec_pop(b->instr);
1999                 b->final = false;
2000                 instr->_ops[0]->store = store_global;
2001                 if (!ir_block_create_store(b, instr->context, instr->_ops[0], v))
2002                     return false;
2003                 instr->_ops[0]->store = store_value;
2004                 vec_push(b->instr, prevjump);
2005                 b->final = true;
2006             }
2007
2008 #if 0
2009             ir_value *v = instr->phi[p].value;
2010             for (w = 0; w < vec_size(v->writes); ++w) {
2011                 ir_value *old;
2012
2013                 if (!v->writes[w]->_ops[0])
2014                     continue;
2015
2016                 /* When the write was to a global, we have to emit a mov */
2017                 old = v->writes[w]->_ops[0];
2018
2019                 /* The original instruction now writes to the PHI target local */
2020                 if (v->writes[w]->_ops[0] == v)
2021                     v->writes[w]->_ops[0] = instr->_ops[0];
2022
2023                 if (old->store != store_value && old->store != store_local && old->store != store_param)
2024                 {
2025                     /* If it originally wrote to a global we need to store the value
2026                      * there as welli
2027                      */
2028                     if (!ir_naive_phi_emit_store(self, i+1, old, v))
2029                         return false;
2030                     if (i+1 < vec_size(self->instr))
2031                         instr = self->instr[i+1];
2032                     else
2033                         instr = NULL;
2034                     /* In case I forget and access instr later, it'll be NULL
2035                      * when it's a problem, to make sure we crash, rather than accessing
2036                      * invalid data.
2037                      */
2038                 }
2039                 else
2040                 {
2041                     /* If it didn't, we can replace all reads by the phi target now. */
2042                     size_t r;
2043                     for (r = 0; r < vec_size(old->reads); ++r)
2044                     {
2045                         size_t op;
2046                         ir_instr *ri = old->reads[r];
2047                         for (op = 0; op < vec_size(ri->phi); ++op) {
2048                             if (ri->phi[op].value == old)
2049                                 ri->phi[op].value = v;
2050                         }
2051                         for (op = 0; op < 3; ++op) {
2052                             if (ri->_ops[op] == old)
2053                                 ri->_ops[op] = v;
2054                         }
2055                     }
2056                 }
2057             }
2058 #endif
2059         }
2060         ir_instr_delete(instr);
2061     }
2062     return true;
2063 }
2064
2065 /***********************************************************************
2066  *IR Temp allocation code
2067  * Propagating value life ranges by walking through the function backwards
2068  * until no more changes are made.
2069  * In theory this should happen once more than once for every nested loop
2070  * level.
2071  * Though this implementation might run an additional time for if nests.
2072  */
2073
2074 /* Enumerate instructions used by value's life-ranges
2075  */
2076 static void ir_block_enumerate(ir_block *self, size_t *_eid)
2077 {
2078     size_t i;
2079     size_t eid = *_eid;
2080     for (i = 0; i < vec_size(self->instr); ++i)
2081     {
2082         self->instr[i]->eid = eid++;
2083     }
2084     *_eid = eid;
2085 }
2086
2087 /* Enumerate blocks and instructions.
2088  * The block-enumeration is unordered!
2089  * We do not really use the block enumreation, however
2090  * the instruction enumeration is important for life-ranges.
2091  */
2092 void ir_function_enumerate(ir_function *self)
2093 {
2094     size_t i;
2095     size_t instruction_id = 0;
2096     for (i = 0; i < vec_size(self->blocks); ++i)
2097     {
2098         self->blocks[i]->eid = i;
2099         self->blocks[i]->run_id = 0;
2100         ir_block_enumerate(self->blocks[i], &instruction_id);
2101     }
2102 }
2103
2104 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
2105 bool ir_function_calculate_liferanges(ir_function *self)
2106 {
2107     size_t i;
2108     bool changed;
2109
2110     do {
2111         self->run_id++;
2112         changed = false;
2113         for (i = 0; i != vec_size(self->blocks); ++i)
2114         {
2115             if (self->blocks[i]->is_return)
2116             {
2117                 vec_free(self->blocks[i]->living);
2118                 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
2119                     return false;
2120             }
2121         }
2122     } while (changed);
2123     if (vec_size(self->blocks)) {
2124         ir_block *block = self->blocks[0];
2125         for (i = 0; i < vec_size(block->living); ++i) {
2126             ir_value *v = block->living[i];
2127             if (v->memberof || v->store != store_local)
2128                 continue;
2129             if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2130                           "variable `%s` may be used uninitialized in this function", v->name))
2131             {
2132                 return false;
2133             }
2134         }
2135     }
2136     return true;
2137 }
2138
2139 /* Local-value allocator
2140  * After finishing creating the liferange of all values used in a function
2141  * we can allocate their global-positions.
2142  * This is the counterpart to register-allocation in register machines.
2143  */
2144 typedef struct {
2145     ir_value **locals;
2146     size_t    *sizes;
2147     size_t    *positions;
2148 } function_allocator;
2149
2150 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
2151 {
2152     ir_value *slot;
2153     size_t vsize = type_sizeof[var->vtype];
2154
2155     slot = ir_value_var("reg", store_global, var->vtype);
2156     if (!slot)
2157         return false;
2158
2159     if (!ir_value_life_merge_into(slot, var))
2160         goto localerror;
2161
2162     vec_push(alloc->locals, slot);
2163     vec_push(alloc->sizes, vsize);
2164
2165     return true;
2166
2167 localerror:
2168     ir_value_delete(slot);
2169     return false;
2170 }
2171
2172 bool ir_function_allocate_locals(ir_function *self)
2173 {
2174     size_t i, a;
2175     bool   retval = true;
2176     size_t pos;
2177
2178     ir_value *slot;
2179     const ir_value *v;
2180
2181     function_allocator alloc;
2182
2183     if (!vec_size(self->locals) && !vec_size(self->values))
2184         return true;
2185
2186     alloc.locals    = NULL;
2187     alloc.sizes     = NULL;
2188     alloc.positions = NULL;
2189
2190     for (i = 0; i < vec_size(self->locals); ++i)
2191     {
2192         if (!function_allocator_alloc(&alloc, self->locals[i]))
2193             goto error;
2194     }
2195
2196     /* Allocate a slot for any value that still exists */
2197     for (i = 0; i < vec_size(self->values); ++i)
2198     {
2199         v = self->values[i];
2200
2201         if (!vec_size(v->life))
2202             continue;
2203
2204         for (a = 0; a < vec_size(alloc.locals); ++a)
2205         {
2206             slot = alloc.locals[a];
2207
2208             /* never resize parameters
2209              * will be required later when overlapping temps + locals
2210              */
2211             if (a < vec_size(self->params) &&
2212                 alloc.sizes[a] < type_sizeof[v->vtype])
2213             {
2214                 continue;
2215             }
2216
2217             if (ir_values_overlap(v, slot))
2218                 continue;
2219
2220             if (!ir_value_life_merge_into(slot, v))
2221                 goto error;
2222
2223             /* adjust size for this slot */
2224             if (alloc.sizes[a] < type_sizeof[v->vtype])
2225                 alloc.sizes[a] = type_sizeof[v->vtype];
2226
2227             self->values[i]->code.local = a;
2228             break;
2229         }
2230         if (a >= vec_size(alloc.locals)) {
2231             self->values[i]->code.local = vec_size(alloc.locals);
2232             if (!function_allocator_alloc(&alloc, v))
2233                 goto error;
2234         }
2235     }
2236
2237     if (!alloc.sizes) {
2238         goto cleanup;
2239     }
2240
2241     /* Adjust slot positions based on sizes */
2242     vec_push(alloc.positions, 0);
2243
2244     if (vec_size(alloc.sizes))
2245         pos = alloc.positions[0] + alloc.sizes[0];
2246     else
2247         pos = 0;
2248     for (i = 1; i < vec_size(alloc.sizes); ++i)
2249     {
2250         pos = alloc.positions[i-1] + alloc.sizes[i-1];
2251         vec_push(alloc.positions, pos);
2252     }
2253
2254     self->allocated_locals = pos + vec_last(alloc.sizes);
2255
2256     /* Take over the actual slot positions */
2257     for (i = 0; i < vec_size(self->values); ++i) {
2258         self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
2259     }
2260
2261     goto cleanup;
2262
2263 error:
2264     retval = false;
2265 cleanup:
2266     for (i = 0; i < vec_size(alloc.locals); ++i)
2267         ir_value_delete(alloc.locals[i]);
2268     vec_free(alloc.locals);
2269     vec_free(alloc.sizes);
2270     vec_free(alloc.positions);
2271     return retval;
2272 }
2273
2274 /* Get information about which operand
2275  * is read from, or written to.
2276  */
2277 static void ir_op_read_write(int op, size_t *read, size_t *write)
2278 {
2279     switch (op)
2280     {
2281     case VINSTR_JUMP:
2282     case INSTR_GOTO:
2283         *write = 0;
2284         *read = 0;
2285         break;
2286     case INSTR_IF:
2287     case INSTR_IFNOT:
2288 #if 0
2289     case INSTR_IF_S:
2290     case INSTR_IFNOT_S:
2291 #endif
2292     case INSTR_RETURN:
2293     case VINSTR_COND:
2294         *write = 0;
2295         *read = 1;
2296         break;
2297     case INSTR_STOREP_F:
2298     case INSTR_STOREP_V:
2299     case INSTR_STOREP_S:
2300     case INSTR_STOREP_ENT:
2301     case INSTR_STOREP_FLD:
2302     case INSTR_STOREP_FNC:
2303         *write = 0;
2304         *read  = 7;
2305         break;
2306     default:
2307         *write = 1;
2308         *read = 6;
2309         break;
2310     };
2311 }
2312
2313 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2314 {
2315     size_t i;
2316     bool changed = false;
2317     bool tempbool;
2318     for (i = 0; i != vec_size(self->living); ++i)
2319     {
2320         tempbool = ir_value_life_merge(self->living[i], eid);
2321         /* debug
2322         if (tempbool)
2323             irerror(self->context, "block_living_add_instr() value instruction added %s: %i", self->living[i]->_name, (int)eid);
2324         */
2325         changed = changed || tempbool;
2326     }
2327     return changed;
2328 }
2329
2330 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
2331 {
2332     size_t i;
2333
2334     (void)changed;
2335
2336     /* values which have been read in a previous iteration are now
2337      * in the "living" array even if the previous block doesn't use them.
2338      * So we have to remove whatever does not exist in the previous block.
2339      * They will be re-added on-read, but the liferange merge won't cause
2340      * a change.
2341      */
2342     for (i = 0; i < vec_size(self->living); ++i)
2343     {
2344         if (!vec_ir_value_find(prev->living, self->living[i], NULL)) {
2345             vec_remove(self->living, i, 1);
2346             --i;
2347         }
2348     }
2349
2350     /* Whatever the previous block still has in its living set
2351      * must now be added to ours as well.
2352      */
2353     for (i = 0; i < vec_size(prev->living); ++i)
2354     {
2355         if (vec_ir_value_find(self->living, prev->living[i], NULL))
2356             continue;
2357         vec_push(self->living, prev->living[i]);
2358         /*
2359         irerror(self->contextt from prev: %s", self->label, prev->living[i]->_name);
2360         */
2361     }
2362     return true;
2363 }
2364
2365 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2366 {
2367     ir_instr *instr;
2368     ir_value *value;
2369     bool  tempbool;
2370     size_t i, o, p;
2371     /* bitmasks which operands are read from or written to */
2372     size_t read, write;
2373     char dbg_ind[16] = { '#', '0' };
2374     (void)dbg_ind;
2375
2376     if (prev)
2377     {
2378         if (!ir_block_life_prop_previous(self, prev, changed))
2379             return false;
2380     }
2381
2382     i = vec_size(self->instr);
2383     while (i)
2384     { --i;
2385         instr = self->instr[i];
2386
2387         /* PHI operands are always read operands */
2388         for (p = 0; p < vec_size(instr->phi); ++p)
2389         {
2390             value = instr->phi[p].value;
2391             if (value->memberof)
2392                 value = value->memberof;
2393             if (!vec_ir_value_find(self->living, value, NULL))
2394                 vec_push(self->living, value);
2395         }
2396
2397         /* call params are read operands too */
2398         for (p = 0; p < vec_size(instr->params); ++p)
2399         {
2400             value = instr->params[p];
2401             if (value->memberof)
2402                 value = value->memberof;
2403             if (!vec_ir_value_find(self->living, value, NULL))
2404                 vec_push(self->living, value);
2405         }
2406
2407         /* See which operands are read and write operands */
2408         ir_op_read_write(instr->opcode, &read, &write);
2409
2410         if (instr->opcode == INSTR_MUL_VF)
2411         {
2412             /* the float source will get an additional lifetime */
2413             tempbool = ir_value_life_merge(instr->_ops[2], instr->eid+1);
2414             *changed = *changed || tempbool;
2415         }
2416         else if (instr->opcode == INSTR_MUL_FV)
2417         {
2418             /* the float source will get an additional lifetime */
2419             tempbool = ir_value_life_merge(instr->_ops[1], instr->eid+1);
2420             *changed = *changed || tempbool;
2421         }
2422
2423         /* Go through the 3 main operands */
2424         for (o = 0; o < 3; ++o)
2425         {
2426             if (!instr->_ops[o]) /* no such operand */
2427                 continue;
2428
2429             value = instr->_ops[o];
2430             if (value->memberof)
2431                 value = value->memberof;
2432
2433             /* We only care about locals */
2434             /* we also calculate parameter liferanges so that locals
2435              * can take up parameter slots */
2436             if (value->store != store_value &&
2437                 value->store != store_local &&
2438                 value->store != store_param)
2439                 continue;
2440
2441             /* read operands */
2442             if (read & (1<<o))
2443             {
2444                 if (!vec_ir_value_find(self->living, value, NULL))
2445                     vec_push(self->living, value);
2446             }
2447
2448             /* write operands */
2449             /* When we write to a local, we consider it "dead" for the
2450              * remaining upper part of the function, since in SSA a value
2451              * can only be written once (== created)
2452              */
2453             if (write & (1<<o))
2454             {
2455                 size_t idx;
2456                 bool in_living = vec_ir_value_find(self->living, value, &idx);
2457                 if (!in_living)
2458                 {
2459                     /* If the value isn't alive it hasn't been read before... */
2460                     /* TODO: See if the warning can be emitted during parsing or AST processing
2461                      * otherwise have warning printed here.
2462                      * IF printing a warning here: include filecontext_t,
2463                      * and make sure it's only printed once
2464                      * since this function is run multiple times.
2465                      */
2466                     /* For now: debug info: */
2467                     /* con_err( "Value only written %s\n", value->name); */
2468                     tempbool = ir_value_life_merge(value, instr->eid);
2469                     *changed = *changed || tempbool;
2470                     /*
2471                     ir_instr_dump(instr, dbg_ind, printf);
2472                     abort();
2473                     */
2474                 } else {
2475                     /* since 'living' won't contain it
2476                      * anymore, merge the value, since
2477                      * (A) doesn't.
2478                      */
2479                     tempbool = ir_value_life_merge(value, instr->eid);
2480                     /*
2481                     if (tempbool)
2482                         con_err( "value added id %s %i\n", value->name, (int)instr->eid);
2483                     */
2484                     *changed = *changed || tempbool;
2485                     /* Then remove */
2486                     vec_remove(self->living, idx, 1);
2487                 }
2488             }
2489         }
2490         /* (A) */
2491         tempbool = ir_block_living_add_instr(self, instr->eid);
2492         /*con_err( "living added values\n");*/
2493         *changed = *changed || tempbool;
2494
2495     }
2496
2497     if (self->run_id == self->owner->run_id)
2498         return true;
2499
2500     self->run_id = self->owner->run_id;
2501
2502     for (i = 0; i < vec_size(self->entries); ++i)
2503     {
2504         ir_block *entry = self->entries[i];
2505         ir_block_life_propagate(entry, self, changed);
2506     }
2507
2508     return true;
2509 }
2510
2511 /***********************************************************************
2512  *IR Code-Generation
2513  *
2514  * Since the IR has the convention of putting 'write' operands
2515  * at the beginning, we have to rotate the operands of instructions
2516  * properly in order to generate valid QCVM code.
2517  *
2518  * Having destinations at a fixed position is more convenient. In QC
2519  * this is *mostly* OPC,  but FTE adds at least 2 instructions which
2520  * read from from OPA,  and store to OPB rather than OPC.   Which is
2521  * partially the reason why the implementation of these instructions
2522  * in darkplaces has been delayed for so long.
2523  *
2524  * Breaking conventions is annoying...
2525  */
2526 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2527
2528 static bool gen_global_field(ir_value *global)
2529 {
2530     if (global->hasvalue)
2531     {
2532         ir_value *fld = global->constval.vpointer;
2533         if (!fld) {
2534             irerror(global->context, "Invalid field constant with no field: %s", global->name);
2535             return false;
2536         }
2537
2538         /* copy the field's value */
2539         ir_value_code_setaddr(global, vec_size(code_globals));
2540         vec_push(code_globals, fld->code.fieldaddr);
2541         if (global->fieldtype == TYPE_VECTOR) {
2542             vec_push(code_globals, fld->code.fieldaddr+1);
2543             vec_push(code_globals, fld->code.fieldaddr+2);
2544         }
2545     }
2546     else
2547     {
2548         ir_value_code_setaddr(global, vec_size(code_globals));
2549         vec_push(code_globals, 0);
2550         if (global->fieldtype == TYPE_VECTOR) {
2551             vec_push(code_globals, 0);
2552             vec_push(code_globals, 0);
2553         }
2554     }
2555     if (global->code.globaladdr < 0)
2556         return false;
2557     return true;
2558 }
2559
2560 static bool gen_global_pointer(ir_value *global)
2561 {
2562     if (global->hasvalue)
2563     {
2564         ir_value *target = global->constval.vpointer;
2565         if (!target) {
2566             irerror(global->context, "Invalid pointer constant: %s", global->name);
2567             /* NULL pointers are pointing to the NULL constant, which also
2568              * sits at address 0, but still has an ir_value for itself.
2569              */
2570             return false;
2571         }
2572
2573         /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2574          * void() foo; <- proto
2575          * void() *fooptr = &foo;
2576          * void() foo = { code }
2577          */
2578         if (!target->code.globaladdr) {
2579             /* FIXME: Check for the constant nullptr ir_value!
2580              * because then code.globaladdr being 0 is valid.
2581              */
2582             irerror(global->context, "FIXME: Relocation support");
2583             return false;
2584         }
2585
2586         ir_value_code_setaddr(global, vec_size(code_globals));
2587         vec_push(code_globals, target->code.globaladdr);
2588     }
2589     else
2590     {
2591         ir_value_code_setaddr(global, vec_size(code_globals));
2592         vec_push(code_globals, 0);
2593     }
2594     if (global->code.globaladdr < 0)
2595         return false;
2596     return true;
2597 }
2598
2599 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2600 {
2601     prog_section_statement stmt;
2602     ir_instr *instr;
2603     ir_block *target;
2604     ir_block *ontrue;
2605     ir_block *onfalse;
2606     size_t    stidx;
2607     size_t    i;
2608
2609 tailcall:
2610     block->generated = true;
2611     block->code_start = vec_size(code_statements);
2612     for (i = 0; i < vec_size(block->instr); ++i)
2613     {
2614         instr = block->instr[i];
2615
2616         if (instr->opcode == VINSTR_PHI) {
2617             irerror(block->context, "cannot generate virtual instruction (phi)");
2618             return false;
2619         }
2620
2621         if (instr->opcode == VINSTR_JUMP) {
2622             target = instr->bops[0];
2623             /* for uncoditional jumps, if the target hasn't been generated
2624              * yet, we generate them right here.
2625              */
2626             if (!target->generated) {
2627                 block = target;
2628                 goto tailcall;
2629             }
2630
2631             /* otherwise we generate a jump instruction */
2632             stmt.opcode = INSTR_GOTO;
2633             stmt.o1.s1 = (target->code_start) - vec_size(code_statements);
2634             stmt.o2.s1 = 0;
2635             stmt.o3.s1 = 0;
2636             code_push_statement(&stmt, instr->context.line);
2637
2638             /* no further instructions can be in this block */
2639             return true;
2640         }
2641
2642         if (instr->opcode == VINSTR_COND) {
2643             ontrue  = instr->bops[0];
2644             onfalse = instr->bops[1];
2645             /* TODO: have the AST signal which block should
2646              * come first: eg. optimize IFs without ELSE...
2647              */
2648
2649             stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2650             stmt.o2.u1 = 0;
2651             stmt.o3.s1 = 0;
2652
2653             if (ontrue->generated) {
2654                 stmt.opcode = INSTR_IF;
2655                 stmt.o2.s1 = (ontrue->code_start) - vec_size(code_statements);
2656                 code_push_statement(&stmt, instr->context.line);
2657             }
2658             if (onfalse->generated) {
2659                 stmt.opcode = INSTR_IFNOT;
2660                 stmt.o2.s1 = (onfalse->code_start) - vec_size(code_statements);
2661                 code_push_statement(&stmt, instr->context.line);
2662             }
2663             if (!ontrue->generated) {
2664                 if (onfalse->generated) {
2665                     block = ontrue;
2666                     goto tailcall;
2667                 }
2668             }
2669             if (!onfalse->generated) {
2670                 if (ontrue->generated) {
2671                     block = onfalse;
2672                     goto tailcall;
2673                 }
2674             }
2675             /* neither ontrue nor onfalse exist */
2676             stmt.opcode = INSTR_IFNOT;
2677             if (!instr->likely) {
2678                 /* Honor the likelyhood hint */
2679                 ir_block *tmp = onfalse;
2680                 stmt.opcode = INSTR_IF;
2681                 onfalse = ontrue;
2682                 ontrue = tmp;
2683             }
2684             stidx = vec_size(code_statements);
2685             code_push_statement(&stmt, instr->context.line);
2686             /* on false we jump, so add ontrue-path */
2687             if (!gen_blocks_recursive(func, ontrue))
2688                 return false;
2689             /* fixup the jump address */
2690             code_statements[stidx].o2.s1 = vec_size(code_statements) - stidx;
2691             /* generate onfalse path */
2692             if (onfalse->generated) {
2693                 /* fixup the jump address */
2694                 code_statements[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2695                 stmt.opcode = vec_last(code_statements).opcode;
2696                 if (stmt.opcode == INSTR_GOTO ||
2697                     stmt.opcode == INSTR_IF ||
2698                     stmt.opcode == INSTR_IFNOT ||
2699                     stmt.opcode == INSTR_RETURN ||
2700                     stmt.opcode == INSTR_DONE)
2701                 {
2702                     /* no use jumping from here */
2703                     return true;
2704                 }
2705                 /* may have been generated in the previous recursive call */
2706                 stmt.opcode = INSTR_GOTO;
2707                 stmt.o1.s1 = (onfalse->code_start) - vec_size(code_statements);
2708                 stmt.o2.s1 = 0;
2709                 stmt.o3.s1 = 0;
2710                 code_push_statement(&stmt, instr->context.line);
2711                 return true;
2712             }
2713             /* if not, generate now */
2714             block = onfalse;
2715             goto tailcall;
2716         }
2717
2718         if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2719             /* Trivial call translation:
2720              * copy all params to OFS_PARM*
2721              * if the output's storetype is not store_return,
2722              * add append a STORE instruction!
2723              *
2724              * NOTES on how to do it better without much trouble:
2725              * -) The liferanges!
2726              *      Simply check the liferange of all parameters for
2727              *      other CALLs. For each param with no CALL in its
2728              *      liferange, we can store it in an OFS_PARM at
2729              *      generation already. This would even include later
2730              *      reuse.... probably... :)
2731              */
2732             size_t p, first;
2733             ir_value *retvalue;
2734
2735             first = vec_size(instr->params);
2736             if (first > 8)
2737                 first = 8;
2738             for (p = 0; p < first; ++p)
2739             {
2740                 ir_value *param = instr->params[p];
2741
2742                 stmt.opcode = INSTR_STORE_F;
2743                 stmt.o3.u1 = 0;
2744
2745                 if (param->vtype == TYPE_FIELD)
2746                     stmt.opcode = field_store_instr[param->fieldtype];
2747                 else
2748                     stmt.opcode = type_store_instr[param->vtype];
2749                 stmt.o1.u1 = ir_value_code_addr(param);
2750                 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2751                 code_push_statement(&stmt, instr->context.line);
2752             }
2753             /* Now handle extparams */
2754             first = vec_size(instr->params);
2755             for (; p < first; ++p)
2756             {
2757                 ir_builder *ir = func->owner;
2758                 ir_value *param = instr->params[p];
2759                 ir_value *targetparam;
2760
2761                 if (p-8 >= vec_size(ir->extparams))
2762                     ir_gen_extparam(ir);
2763
2764                 targetparam = ir->extparams[p-8];
2765
2766                 stmt.opcode = INSTR_STORE_F;
2767                 stmt.o3.u1 = 0;
2768
2769                 if (param->vtype == TYPE_FIELD)
2770                     stmt.opcode = field_store_instr[param->fieldtype];
2771                 else
2772                     stmt.opcode = type_store_instr[param->vtype];
2773                 stmt.o1.u1 = ir_value_code_addr(param);
2774                 stmt.o2.u1 = ir_value_code_addr(targetparam);
2775                 code_push_statement(&stmt, instr->context.line);
2776             }
2777
2778             stmt.opcode = INSTR_CALL0 + vec_size(instr->params);
2779             if (stmt.opcode > INSTR_CALL8)
2780                 stmt.opcode = INSTR_CALL8;
2781             stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2782             stmt.o2.u1 = 0;
2783             stmt.o3.u1 = 0;
2784             code_push_statement(&stmt, instr->context.line);
2785
2786             retvalue = instr->_ops[0];
2787             if (retvalue && retvalue->store != store_return && vec_size(retvalue->life))
2788             {
2789                 /* not to be kept in OFS_RETURN */
2790                 if (retvalue->vtype == TYPE_FIELD)
2791                     stmt.opcode = field_store_instr[retvalue->vtype];
2792                 else
2793                     stmt.opcode = type_store_instr[retvalue->vtype];
2794                 stmt.o1.u1 = OFS_RETURN;
2795                 stmt.o2.u1 = ir_value_code_addr(retvalue);
2796                 stmt.o3.u1 = 0;
2797                 code_push_statement(&stmt, instr->context.line);
2798             }
2799             continue;
2800         }
2801
2802         if (instr->opcode == INSTR_STATE) {
2803             irerror(block->context, "TODO: state instruction");
2804             return false;
2805         }
2806
2807         stmt.opcode = instr->opcode;
2808         stmt.o1.u1 = 0;
2809         stmt.o2.u1 = 0;
2810         stmt.o3.u1 = 0;
2811
2812         /* This is the general order of operands */
2813         if (instr->_ops[0])
2814             stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2815
2816         if (instr->_ops[1])
2817             stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2818
2819         if (instr->_ops[2])
2820             stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2821
2822         if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2823         {
2824             stmt.o1.u1 = stmt.o3.u1;
2825             stmt.o3.u1 = 0;
2826         }
2827         else if ((stmt.opcode >= INSTR_STORE_F &&
2828                   stmt.opcode <= INSTR_STORE_FNC) ||
2829                  (stmt.opcode >= INSTR_STOREP_F &&
2830                   stmt.opcode <= INSTR_STOREP_FNC))
2831         {
2832             /* 2-operand instructions with A -> B */
2833             stmt.o2.u1 = stmt.o3.u1;
2834             stmt.o3.u1 = 0;
2835         }
2836
2837         code_push_statement(&stmt, instr->context.line);
2838     }
2839     return true;
2840 }
2841
2842 static bool gen_function_code(ir_function *self)
2843 {
2844     ir_block *block;
2845     prog_section_statement stmt;
2846
2847     /* Starting from entry point, we generate blocks "as they come"
2848      * for now. Dead blocks will not be translated obviously.
2849      */
2850     if (!vec_size(self->blocks)) {
2851         irerror(self->context, "Function '%s' declared without body.", self->name);
2852         return false;
2853     }
2854
2855     block = self->blocks[0];
2856     if (block->generated)
2857         return true;
2858
2859     if (!gen_blocks_recursive(self, block)) {
2860         irerror(self->context, "failed to generate blocks for '%s'", self->name);
2861         return false;
2862     }
2863
2864     /* otherwise code_write crashes since it debug-prints functions until AINSTR_END */
2865     stmt.opcode = AINSTR_END;
2866     stmt.o1.u1 = 0;
2867     stmt.o2.u1 = 0;
2868     stmt.o3.u1 = 0;
2869     code_push_statement(&stmt, vec_last(code_linenums));
2870     return true;
2871 }
2872
2873 static qcint ir_builder_filestring(ir_builder *ir, const char *filename)
2874 {
2875     /* NOTE: filename pointers are copied, we never strdup them,
2876      * thus we can use pointer-comparison to find the string.
2877      */
2878     size_t i;
2879     qcint  str;
2880
2881     for (i = 0; i < vec_size(ir->filenames); ++i) {
2882         if (ir->filenames[i] == filename)
2883             return ir->filestrings[i];
2884     }
2885
2886     str = code_genstring(filename);
2887     vec_push(ir->filenames, filename);
2888     vec_push(ir->filestrings, str);
2889     return str;
2890 }
2891
2892 static bool gen_global_function(ir_builder *ir, ir_value *global)
2893 {
2894     prog_section_function fun;
2895     ir_function          *irfun;
2896
2897     size_t i;
2898     size_t local_var_end;
2899
2900     if (!global->hasvalue || (!global->constval.vfunc))
2901     {
2902         irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
2903         return false;
2904     }
2905
2906     irfun = global->constval.vfunc;
2907
2908     fun.name    = global->code.name;
2909     fun.file    = ir_builder_filestring(ir, global->context.file);
2910     fun.profile = 0; /* always 0 */
2911     fun.nargs   = vec_size(irfun->params);
2912     if (fun.nargs > 8)
2913         fun.nargs = 8;
2914
2915     for (i = 0;i < 8; ++i) {
2916         if ((int32_t)i >= fun.nargs)
2917             fun.argsize[i] = 0;
2918         else
2919             fun.argsize[i] = type_sizeof[irfun->params[i]];
2920     }
2921
2922     fun.firstlocal = vec_size(code_globals);
2923
2924     local_var_end = fun.firstlocal;
2925     for (i = 0; i < vec_size(irfun->locals); ++i) {
2926         if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
2927             irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
2928             return false;
2929         }
2930     }
2931     if (vec_size(irfun->locals)) {
2932         ir_value *last = vec_last(irfun->locals);
2933         local_var_end = last->code.globaladdr;
2934         if (last->vtype == TYPE_FIELD && last->fieldtype == TYPE_VECTOR)
2935             local_var_end += type_sizeof[TYPE_VECTOR];
2936         else
2937             local_var_end += type_sizeof[last->vtype];
2938     }
2939     for (i = 0; i < vec_size(irfun->values); ++i)
2940     {
2941         /* generate code.globaladdr for ssa values */
2942         ir_value *v = irfun->values[i];
2943         ir_value_code_setaddr(v, local_var_end + v->code.local);
2944     }
2945     for (i = 0; i < irfun->allocated_locals; ++i) {
2946         /* fill the locals with zeros */
2947         vec_push(code_globals, 0);
2948     }
2949
2950     fun.locals = vec_size(code_globals) - fun.firstlocal;
2951
2952     if (irfun->builtin)
2953         fun.entry = irfun->builtin+1;
2954     else {
2955         irfun->code_function_def = vec_size(code_functions);
2956         fun.entry = vec_size(code_statements);
2957     }
2958
2959     vec_push(code_functions, fun);
2960     return true;
2961 }
2962
2963 static void ir_gen_extparam(ir_builder *ir)
2964 {
2965     prog_section_def def;
2966     ir_value        *global;
2967     char             name[128];
2968
2969     snprintf(name, sizeof(name), "EXTPARM#%i", (int)(vec_size(ir->extparams)+8));
2970     global = ir_value_var(name, store_global, TYPE_VECTOR);
2971
2972     def.name = code_genstring(name);
2973     def.type = TYPE_VECTOR;
2974     def.offset = vec_size(code_globals);
2975
2976     vec_push(code_defs, def);
2977     ir_value_code_setaddr(global, def.offset);
2978     vec_push(code_globals, 0);
2979     vec_push(code_globals, 0);
2980     vec_push(code_globals, 0);
2981
2982     vec_push(ir->extparams, global);
2983 }
2984
2985 static bool gen_function_extparam_copy(ir_function *self)
2986 {
2987     size_t i, ext, numparams;
2988
2989     ir_builder *ir = self->owner;
2990     ir_value   *ep;
2991     prog_section_statement stmt;
2992
2993     numparams = vec_size(self->params);
2994     if (!numparams)
2995         return true;
2996
2997     stmt.opcode = INSTR_STORE_F;
2998     stmt.o3.s1 = 0;
2999     for (i = 8; i < numparams; ++i) {
3000         ext = i - 8;
3001         if (ext >= vec_size(ir->extparams))
3002             ir_gen_extparam(ir);
3003
3004         ep = ir->extparams[ext];
3005
3006         stmt.opcode = type_store_instr[self->locals[i]->vtype];
3007         if (self->locals[i]->vtype == TYPE_FIELD &&
3008             self->locals[i]->fieldtype == TYPE_VECTOR)
3009         {
3010             stmt.opcode = INSTR_STORE_V;
3011         }
3012         stmt.o1.u1 = ir_value_code_addr(ep);
3013         stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3014         code_push_statement(&stmt, self->context.line);
3015     }
3016
3017     return true;
3018 }
3019
3020 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
3021 {
3022     prog_section_function *fundef;
3023     ir_function           *irfun;
3024
3025     (void)ir;
3026
3027     irfun = global->constval.vfunc;
3028     if (!irfun) {
3029         if (global->cvq == CV_NONE) {
3030             irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
3031                       "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
3032         }
3033         /* this was a function pointer, don't generate code for those */
3034         return true;
3035     }
3036
3037     if (irfun->builtin)
3038         return true;
3039
3040     if (irfun->code_function_def < 0) {
3041         irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
3042         return false;
3043     }
3044     fundef = &code_functions[irfun->code_function_def];
3045
3046     fundef->entry = vec_size(code_statements);
3047     if (!gen_function_extparam_copy(irfun)) {
3048         irerror(irfun->context, "Failed to generate extparam-copy code for function %s", irfun->name);
3049         return false;
3050     }
3051     if (!gen_function_code(irfun)) {
3052         irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
3053         return false;
3054     }
3055     return true;
3056 }
3057
3058 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
3059 {
3060     size_t           i;
3061     int32_t         *iptr;
3062     prog_section_def def;
3063
3064     def.type   = global->vtype;
3065     def.offset = vec_size(code_globals);
3066
3067     if (global->name) {
3068         if (global->name[0] == '#') {
3069             if (!self->str_immediate)
3070                 self->str_immediate = code_genstring("IMMEDIATE");
3071             def.name = global->code.name = self->str_immediate;
3072         }
3073         else
3074             def.name = global->code.name = code_genstring(global->name);
3075     }
3076     else
3077         def.name   = 0;
3078
3079     switch (global->vtype)
3080     {
3081     case TYPE_VOID:
3082         if (!strcmp(global->name, "end_sys_globals")) {
3083             /* TODO: remember this point... all the defs before this one
3084              * should be checksummed and added to progdefs.h when we generate it.
3085              */
3086         }
3087         else if (!strcmp(global->name, "end_sys_fields")) {
3088             /* TODO: same as above but for entity-fields rather than globsl
3089              */
3090         }
3091         else
3092             irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3093                       global->name);
3094         /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3095          * the system fields actually go? Though the engine knows this anyway...
3096          * Maybe this could be an -foption
3097          * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3098          */
3099         ir_value_code_setaddr(global, vec_size(code_globals));
3100         vec_push(code_globals, 0);
3101         /* Add the def */
3102         vec_push(code_defs, def);
3103         return true;
3104     case TYPE_POINTER:
3105         vec_push(code_defs, def);
3106         return gen_global_pointer(global);
3107     case TYPE_FIELD:
3108         vec_push(code_defs, def);
3109         return gen_global_field(global);
3110     case TYPE_ENTITY:
3111         /* fall through */
3112     case TYPE_FLOAT:
3113     {
3114         ir_value_code_setaddr(global, vec_size(code_globals));
3115         if (global->hasvalue) {
3116             iptr = (int32_t*)&global->constval.ivec[0];
3117             vec_push(code_globals, *iptr);
3118         } else {
3119             vec_push(code_globals, 0);
3120             if (!islocal)
3121                 def.type |= DEF_SAVEGLOBAL;
3122         }
3123         vec_push(code_defs, def);
3124
3125         return global->code.globaladdr >= 0;
3126     }
3127     case TYPE_STRING:
3128     {
3129         ir_value_code_setaddr(global, vec_size(code_globals));
3130         if (global->hasvalue) {
3131             vec_push(code_globals, code_genstring(global->constval.vstring));
3132         } else {
3133             vec_push(code_globals, 0);
3134             if (!islocal)
3135                 def.type |= DEF_SAVEGLOBAL;
3136         }
3137         vec_push(code_defs, def);
3138         return global->code.globaladdr >= 0;
3139     }
3140     case TYPE_VECTOR:
3141     {
3142         size_t d;
3143         ir_value_code_setaddr(global, vec_size(code_globals));
3144         if (global->hasvalue) {
3145             iptr = (int32_t*)&global->constval.ivec[0];
3146             vec_push(code_globals, iptr[0]);
3147             if (global->code.globaladdr < 0)
3148                 return false;
3149             for (d = 1; d < type_sizeof[global->vtype]; ++d)
3150             {
3151                 vec_push(code_globals, iptr[d]);
3152             }
3153         } else {
3154             vec_push(code_globals, 0);
3155             if (global->code.globaladdr < 0)
3156                 return false;
3157             for (d = 1; d < type_sizeof[global->vtype]; ++d)
3158             {
3159                 vec_push(code_globals, 0);
3160             }
3161             if (!islocal)
3162                 def.type |= DEF_SAVEGLOBAL;
3163         }
3164
3165         vec_push(code_defs, def);
3166         return global->code.globaladdr >= 0;
3167     }
3168     case TYPE_FUNCTION:
3169         ir_value_code_setaddr(global, vec_size(code_globals));
3170         if (!global->hasvalue) {
3171             vec_push(code_globals, 0);
3172             if (global->code.globaladdr < 0)
3173                 return false;
3174         } else {
3175             vec_push(code_globals, vec_size(code_functions));
3176             if (!gen_global_function(self, global))
3177                 return false;
3178             if (!islocal)
3179                 def.type |= DEF_SAVEGLOBAL;
3180         }
3181         vec_push(code_defs, def);
3182         return true;
3183     case TYPE_VARIANT:
3184         /* assume biggest type */
3185             ir_value_code_setaddr(global, vec_size(code_globals));
3186             vec_push(code_globals, 0);
3187             for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
3188                 vec_push(code_globals, 0);
3189             return true;
3190     default:
3191         /* refuse to create 'void' type or any other fancy business. */
3192         irerror(global->context, "Invalid type for global variable `%s`: %s",
3193                 global->name, type_name[global->vtype]);
3194         return false;
3195     }
3196 }
3197
3198 static void ir_builder_prepare_field(ir_value *field)
3199 {
3200     field->code.fieldaddr = code_alloc_field(type_sizeof[field->fieldtype]);
3201 }
3202
3203 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3204 {
3205     prog_section_def def;
3206     prog_section_field fld;
3207
3208     (void)self;
3209
3210     def.type   = (uint16_t)field->vtype;
3211     def.offset = (uint16_t)vec_size(code_globals);
3212
3213     /* create a global named the same as the field */
3214     if (opts_standard == COMPILER_GMQCC) {
3215         /* in our standard, the global gets a dot prefix */
3216         size_t len = strlen(field->name);
3217         char name[1024];
3218
3219         /* we really don't want to have to allocate this, and 1024
3220          * bytes is more than enough for a variable/field name
3221          */
3222         if (len+2 >= sizeof(name)) {
3223             irerror(field->context, "invalid field name size: %u", (unsigned int)len);
3224             return false;
3225         }
3226
3227         name[0] = '.';
3228         memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
3229         name[len+1] = 0;
3230
3231         def.name = code_genstring(name);
3232         fld.name = def.name + 1; /* we reuse that string table entry */
3233     } else {
3234         /* in plain QC, there cannot be a global with the same name,
3235          * and so we also name the global the same.
3236          * FIXME: fteqcc should create a global as well
3237          * check if it actually uses the same name. Probably does
3238          */
3239         def.name = code_genstring(field->name);
3240         fld.name = def.name;
3241     }
3242
3243     field->code.name = def.name;
3244
3245     vec_push(code_defs, def);
3246
3247     fld.type = field->fieldtype;
3248
3249     if (fld.type == TYPE_VOID) {
3250         irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
3251         return false;
3252     }
3253
3254     fld.offset = field->code.fieldaddr;
3255
3256     vec_push(code_fields, fld);
3257
3258     ir_value_code_setaddr(field, vec_size(code_globals));
3259     vec_push(code_globals, fld.offset);
3260     if (fld.type == TYPE_VECTOR) {
3261         vec_push(code_globals, fld.offset+1);
3262         vec_push(code_globals, fld.offset+2);
3263     }
3264
3265     return field->code.globaladdr >= 0;
3266 }
3267
3268 bool ir_builder_generate(ir_builder *self, const char *filename)
3269 {
3270     prog_section_statement stmt;
3271     size_t i;
3272     char   *lnofile = NULL;
3273
3274     code_init();
3275
3276     for (i = 0; i < vec_size(self->fields); ++i)
3277     {
3278         ir_builder_prepare_field(self->fields[i]);
3279     }
3280
3281     for (i = 0; i < vec_size(self->globals); ++i)
3282     {
3283         if (!ir_builder_gen_global(self, self->globals[i], false)) {
3284             return false;
3285         }
3286     }
3287
3288     for (i = 0; i < vec_size(self->fields); ++i)
3289     {
3290         if (!ir_builder_gen_field(self, self->fields[i])) {
3291             return false;
3292         }
3293     }
3294
3295     /* generate function code */
3296     for (i = 0; i < vec_size(self->globals); ++i)
3297     {
3298         if (self->globals[i]->vtype == TYPE_FUNCTION) {
3299             if (!gen_global_function_code(self, self->globals[i])) {
3300                 return false;
3301             }
3302         }
3303     }
3304
3305     if (vec_size(code_globals) >= 65536) {
3306         irerror(vec_last(self->globals)->context, "This progs file would require more globals than the metadata can handle. Bailing out.");
3307         return false;
3308     }
3309
3310     /* DP errors if the last instruction is not an INSTR_DONE
3311      * and for debugging purposes we add an additional AINSTR_END
3312      * to the end of functions, so here it goes:
3313      */
3314     stmt.opcode = INSTR_DONE;
3315     stmt.o1.u1 = 0;
3316     stmt.o2.u1 = 0;
3317     stmt.o3.u1 = 0;
3318     code_push_statement(&stmt, vec_last(code_linenums));
3319
3320     if (opts_pp_only)
3321         return true;
3322
3323     if (vec_size(code_statements) != vec_size(code_linenums)) {
3324         con_err("Linecounter wrong: %lu != %lu\n",
3325                 (unsigned long)vec_size(code_statements),
3326                 (unsigned long)vec_size(code_linenums));
3327     } else if (OPTS_FLAG(LNO)) {
3328         char *dot;
3329         size_t filelen = strlen(filename);
3330
3331         memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
3332         dot = strrchr(lnofile, '.');
3333         if (!dot) {
3334             vec_pop(lnofile);
3335         } else {
3336             vec_shrinkto(lnofile, dot - lnofile);
3337         }
3338         memcpy(vec_add(lnofile, 5), ".lno", 5);
3339     }
3340
3341     if (lnofile)
3342         con_out("writing '%s' and '%s'...\n", filename, lnofile);
3343     else
3344         con_out("writing '%s'\n", filename);
3345     if (!code_write(filename, lnofile)) {
3346         vec_free(lnofile);
3347         return false;
3348     }
3349     vec_free(lnofile);
3350     return true;
3351 }
3352
3353 /***********************************************************************
3354  *IR DEBUG Dump functions...
3355  */
3356
3357 #define IND_BUFSZ 1024
3358
3359 #ifdef WIN32
3360 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
3361 #endif
3362
3363 const char *qc_opname(int op)
3364 {
3365     if (op < 0) return "<INVALID>";
3366     if (op < (int)( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
3367         return asm_instr[op].m;
3368     switch (op) {
3369         case VINSTR_PHI:  return "PHI";
3370         case VINSTR_JUMP: return "JUMP";
3371         case VINSTR_COND: return "COND";
3372         default:          return "<UNK>";
3373     }
3374 }
3375
3376 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
3377 {
3378     size_t i;
3379     char indent[IND_BUFSZ];
3380     indent[0] = '\t';
3381     indent[1] = 0;
3382
3383     oprintf("module %s\n", b->name);
3384     for (i = 0; i < vec_size(b->globals); ++i)
3385     {
3386         oprintf("global ");
3387         if (b->globals[i]->hasvalue)
3388             oprintf("%s = ", b->globals[i]->name);
3389         ir_value_dump(b->globals[i], oprintf);
3390         oprintf("\n");
3391     }
3392     for (i = 0; i < vec_size(b->functions); ++i)
3393         ir_function_dump(b->functions[i], indent, oprintf);
3394     oprintf("endmodule %s\n", b->name);
3395 }
3396
3397 void ir_function_dump(ir_function *f, char *ind,
3398                       int (*oprintf)(const char*, ...))
3399 {
3400     size_t i;
3401     if (f->builtin != 0) {
3402         oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
3403         return;
3404     }
3405     oprintf("%sfunction %s\n", ind, f->name);
3406     strncat(ind, "\t", IND_BUFSZ);
3407     if (vec_size(f->locals))
3408     {
3409         oprintf("%s%i locals:\n", ind, (int)vec_size(f->locals));
3410         for (i = 0; i < vec_size(f->locals); ++i) {
3411             oprintf("%s\t", ind);
3412             ir_value_dump(f->locals[i], oprintf);
3413             oprintf("\n");
3414         }
3415     }
3416     oprintf("%sliferanges:\n", ind);
3417     for (i = 0; i < vec_size(f->locals); ++i) {
3418         size_t l;
3419         ir_value *v = f->locals[i];
3420         oprintf("%s\t%s: unique ", ind, v->name);
3421         for (l = 0; l < vec_size(v->life); ++l) {
3422             oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3423         }
3424         oprintf("\n");
3425     }
3426     for (i = 0; i < vec_size(f->values); ++i) {
3427         size_t l;
3428         ir_value *v = f->values[i];
3429         oprintf("%s\t%s: @%i ", ind, v->name, (int)v->code.local);
3430         for (l = 0; l < vec_size(v->life); ++l) {
3431             oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3432         }
3433         oprintf("\n");
3434     }
3435     if (vec_size(f->blocks))
3436     {
3437         oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
3438         for (i = 0; i < vec_size(f->blocks); ++i) {
3439             if (f->blocks[i]->run_id != f->run_id) {
3440                 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
3441             }
3442             ir_block_dump(f->blocks[i], ind, oprintf);
3443         }
3444
3445     }
3446     ind[strlen(ind)-1] = 0;
3447     oprintf("%sendfunction %s\n", ind, f->name);
3448 }
3449
3450 void ir_block_dump(ir_block* b, char *ind,
3451                    int (*oprintf)(const char*, ...))
3452 {
3453     size_t i;
3454     oprintf("%s:%s\n", ind, b->label);
3455     strncat(ind, "\t", IND_BUFSZ);
3456
3457     for (i = 0; i < vec_size(b->instr); ++i)
3458         ir_instr_dump(b->instr[i], ind, oprintf);
3459     ind[strlen(ind)-1] = 0;
3460 }
3461
3462 void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
3463 {
3464     size_t i;
3465     oprintf("%s <- phi ", in->_ops[0]->name);
3466     for (i = 0; i < vec_size(in->phi); ++i)
3467     {
3468         oprintf("([%s] : %s) ", in->phi[i].from->label,
3469                                 in->phi[i].value->name);
3470     }
3471     oprintf("\n");
3472 }
3473
3474 void ir_instr_dump(ir_instr *in, char *ind,
3475                        int (*oprintf)(const char*, ...))
3476 {
3477     size_t i;
3478     const char *comma = NULL;
3479
3480     oprintf("%s (%i) ", ind, (int)in->eid);
3481
3482     if (in->opcode == VINSTR_PHI) {
3483         dump_phi(in, oprintf);
3484         return;
3485     }
3486
3487     strncat(ind, "\t", IND_BUFSZ);
3488
3489     if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3490         ir_value_dump(in->_ops[0], oprintf);
3491         if (in->_ops[1] || in->_ops[2])
3492             oprintf(" <- ");
3493     }
3494     if (in->opcode == INSTR_CALL0) {
3495         oprintf("CALL%i\t", vec_size(in->params));
3496     } else
3497         oprintf("%s\t", qc_opname(in->opcode));
3498
3499     if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3500         ir_value_dump(in->_ops[0], oprintf);
3501         comma = ",\t";
3502     }
3503     else
3504     {
3505         for (i = 1; i != 3; ++i) {
3506             if (in->_ops[i]) {
3507                 if (comma)
3508                     oprintf(comma);
3509                 ir_value_dump(in->_ops[i], oprintf);
3510                 comma = ",\t";
3511             }
3512         }
3513     }
3514     if (in->bops[0]) {
3515         if (comma)
3516             oprintf(comma);
3517         oprintf("[%s]", in->bops[0]->label);
3518         comma = ",\t";
3519     }
3520     if (in->bops[1])
3521         oprintf("%s[%s]", comma, in->bops[1]->label);
3522     if (vec_size(in->params)) {
3523         oprintf("\tparams: ");
3524         for (i = 0; i != vec_size(in->params); ++i) {
3525             oprintf("%s, ", in->params[i]->name);
3526         }
3527     }
3528     oprintf("\n");
3529     ind[strlen(ind)-1] = 0;
3530 }
3531
3532 void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
3533 {
3534     oprintf("\"");
3535     for (; *str; ++str) {
3536         switch (*str) {
3537             case '\n': oprintf("\\n"); break;
3538             case '\r': oprintf("\\r"); break;
3539             case '\t': oprintf("\\t"); break;
3540             case '\v': oprintf("\\v"); break;
3541             case '\f': oprintf("\\f"); break;
3542             case '\b': oprintf("\\b"); break;
3543             case '\a': oprintf("\\a"); break;
3544             case '\\': oprintf("\\\\"); break;
3545             case '"': oprintf("\\\""); break;
3546             default: oprintf("%c", *str); break;
3547         }
3548     }
3549     oprintf("\"");
3550 }
3551
3552 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3553 {
3554     if (v->hasvalue) {
3555         switch (v->vtype) {
3556             default:
3557             case TYPE_VOID:
3558                 oprintf("(void)");
3559                 break;
3560             case TYPE_FUNCTION:
3561                 oprintf("fn:%s", v->name);
3562                 break;
3563             case TYPE_FLOAT:
3564                 oprintf("%g", v->constval.vfloat);
3565                 break;
3566             case TYPE_VECTOR:
3567                 oprintf("'%g %g %g'",
3568                         v->constval.vvec.x,
3569                         v->constval.vvec.y,
3570                         v->constval.vvec.z);
3571                 break;
3572             case TYPE_ENTITY:
3573                 oprintf("(entity)");
3574                 break;
3575             case TYPE_STRING:
3576                 ir_value_dump_string(v->constval.vstring, oprintf);
3577                 break;
3578 #if 0
3579             case TYPE_INTEGER:
3580                 oprintf("%i", v->constval.vint);
3581                 break;
3582 #endif
3583             case TYPE_POINTER:
3584                 oprintf("&%s",
3585                     v->constval.vpointer->name);
3586                 break;
3587         }
3588     } else {
3589         oprintf("%s", v->name);
3590     }
3591 }
3592
3593 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
3594 {
3595     size_t i;
3596     oprintf("Life of %12s:", self->name);
3597     for (i = 0; i < vec_size(self->life); ++i)
3598     {
3599         oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);
3600     }
3601 }