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