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