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