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