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