]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ir.c
Fix more bugs (mostly possible NULL pointer dereferences)
[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, 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, 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 ctx, const char *msg, ...)
244 {
245     va_list ap;
246     va_start(ap, msg);
247     con_cvprintmsg((void*)&ctx, LVL_ERROR, "internal error", msg, ap);
248     va_end(ap);
249 }
250
251 static bool irwarning(lex_ctx 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 && 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 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 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, vector 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 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", asm_instr[op].m);
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 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 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 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 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 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 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 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 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 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         default:
1804             /* ranges: */
1805             /* boolean operations result in floats */
1806             if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1807                 ot = TYPE_FLOAT;
1808             else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1809                 ot = TYPE_FLOAT;
1810 #if 0
1811             else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1812                 ot = TYPE_FLOAT;
1813 #endif
1814             break;
1815     };
1816     if (ot == TYPE_VOID) {
1817         /* The AST or parser were supposed to check this! */
1818         return NULL;
1819     }
1820
1821     return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1822 }
1823
1824 ir_value* ir_block_create_unary(ir_block *self, lex_ctx ctx,
1825                                 const char *label, int opcode,
1826                                 ir_value *operand)
1827 {
1828     int ot = TYPE_FLOAT;
1829     switch (opcode) {
1830         case INSTR_NOT_F:
1831         case INSTR_NOT_V:
1832         case INSTR_NOT_S:
1833         case INSTR_NOT_ENT:
1834         case INSTR_NOT_FNC:
1835 #if 0
1836         case INSTR_NOT_I:
1837 #endif
1838             ot = TYPE_FLOAT;
1839             break;
1840         /* QC doesn't have other unary operations. We expect extensions to fill
1841          * the above list, otherwise we assume out-type = in-type, eg for an
1842          * unary minus
1843          */
1844         default:
1845             ot = operand->vtype;
1846             break;
1847     };
1848     if (ot == TYPE_VOID) {
1849         /* The AST or parser were supposed to check this! */
1850         return NULL;
1851     }
1852
1853     /* let's use the general instruction creator and pass NULL for OPB */
1854     return ir_block_create_general_instr(self, ctx, label, opcode, operand, NULL, ot);
1855 }
1856
1857 static ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx ctx, const char *label,
1858                                         int op, ir_value *a, ir_value *b, int outype)
1859 {
1860     ir_instr *instr;
1861     ir_value *out;
1862
1863     out = ir_value_out(self->owner, label, store_value, outype);
1864     if (!out)
1865         return NULL;
1866
1867     instr = ir_instr_new(ctx, self, op);
1868     if (!instr) {
1869         ir_value_delete(out);
1870         return NULL;
1871     }
1872
1873     if (!ir_instr_op(instr, 0, out, true) ||
1874         !ir_instr_op(instr, 1, a, false) ||
1875         !ir_instr_op(instr, 2, b, false) )
1876     {
1877         goto on_error;
1878     }
1879
1880     vec_push(self->instr, instr);
1881
1882     return out;
1883 on_error:
1884     ir_instr_delete(instr);
1885     ir_value_delete(out);
1886     return NULL;
1887 }
1888
1889 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx ctx, const char *label, ir_value *ent, ir_value *field)
1890 {
1891     ir_value *v;
1892
1893     /* Support for various pointer types todo if so desired */
1894     if (ent->vtype != TYPE_ENTITY)
1895         return NULL;
1896
1897     if (field->vtype != TYPE_FIELD)
1898         return NULL;
1899
1900     v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1901     v->fieldtype = field->fieldtype;
1902     return v;
1903 }
1904
1905 ir_value* ir_block_create_load_from_ent(ir_block *self, lex_ctx ctx, const char *label, ir_value *ent, ir_value *field, int outype)
1906 {
1907     int op;
1908     if (ent->vtype != TYPE_ENTITY)
1909         return NULL;
1910
1911     /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1912     if (field->vtype != TYPE_FIELD)
1913         return NULL;
1914
1915     switch (outype)
1916     {
1917         case TYPE_FLOAT:    op = INSTR_LOAD_F;   break;
1918         case TYPE_VECTOR:   op = INSTR_LOAD_V;   break;
1919         case TYPE_STRING:   op = INSTR_LOAD_S;   break;
1920         case TYPE_FIELD:    op = INSTR_LOAD_FLD; break;
1921         case TYPE_ENTITY:   op = INSTR_LOAD_ENT; break;
1922         case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1923 #if 0
1924         case TYPE_POINTER: op = INSTR_LOAD_I;   break;
1925         case TYPE_INTEGER: op = INSTR_LOAD_I;   break;
1926 #endif
1927         default:
1928             irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1929             return NULL;
1930     }
1931
1932     return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
1933 }
1934
1935 /* PHI resolving breaks the SSA, and must thus be the last
1936  * step before life-range calculation.
1937  */
1938
1939 static bool ir_block_naive_phi(ir_block *self);
1940 bool ir_function_naive_phi(ir_function *self)
1941 {
1942     size_t i;
1943
1944     for (i = 0; i < vec_size(self->blocks); ++i)
1945     {
1946         if (!ir_block_naive_phi(self->blocks[i]))
1947             return false;
1948     }
1949     return true;
1950 }
1951
1952 static bool ir_block_naive_phi(ir_block *self)
1953 {
1954     size_t i, p; /*, w;*/
1955     /* FIXME: optionally, create_phi can add the phis
1956      * to a list so we don't need to loop through blocks
1957      * - anyway: "don't optimize YET"
1958      */
1959     for (i = 0; i < vec_size(self->instr); ++i)
1960     {
1961         ir_instr *instr = self->instr[i];
1962         if (instr->opcode != VINSTR_PHI)
1963             continue;
1964
1965         vec_remove(self->instr, i, 1);
1966         --i; /* NOTE: i+1 below */
1967
1968         for (p = 0; p < vec_size(instr->phi); ++p)
1969         {
1970             ir_value *v = instr->phi[p].value;
1971             ir_block *b = instr->phi[p].from;
1972
1973             if (v->store == store_value &&
1974                 vec_size(v->reads) == 1 &&
1975                 vec_size(v->writes) == 1)
1976             {
1977                 /* replace the value */
1978                 if (!ir_instr_op(v->writes[0], 0, instr->_ops[0], true))
1979                     return false;
1980             }
1981             else
1982             {
1983                 /* force a move instruction */
1984                 ir_instr *prevjump = vec_last(b->instr);
1985                 vec_pop(b->instr);
1986                 b->final = false;
1987                 instr->_ops[0]->store = store_global;
1988                 if (!ir_block_create_store(b, instr->context, instr->_ops[0], v))
1989                     return false;
1990                 instr->_ops[0]->store = store_value;
1991                 vec_push(b->instr, prevjump);
1992                 b->final = true;
1993             }
1994         }
1995         ir_instr_delete(instr);
1996     }
1997     return true;
1998 }
1999
2000 /***********************************************************************
2001  *IR Temp allocation code
2002  * Propagating value life ranges by walking through the function backwards
2003  * until no more changes are made.
2004  * In theory this should happen once more than once for every nested loop
2005  * level.
2006  * Though this implementation might run an additional time for if nests.
2007  */
2008
2009 /* Enumerate instructions used by value's life-ranges
2010  */
2011 static void ir_block_enumerate(ir_block *self, size_t *_eid)
2012 {
2013     size_t i;
2014     size_t eid = *_eid;
2015     for (i = 0; i < vec_size(self->instr); ++i)
2016     {
2017         self->instr[i]->eid = eid++;
2018     }
2019     *_eid = eid;
2020 }
2021
2022 /* Enumerate blocks and instructions.
2023  * The block-enumeration is unordered!
2024  * We do not really use the block enumreation, however
2025  * the instruction enumeration is important for life-ranges.
2026  */
2027 void ir_function_enumerate(ir_function *self)
2028 {
2029     size_t i;
2030     size_t instruction_id = 0;
2031     for (i = 0; i < vec_size(self->blocks); ++i)
2032     {
2033         /* each block now gets an additional "entry" instruction id
2034          * we can use to avoid point-life issues
2035          */
2036         self->blocks[i]->entry_id = instruction_id;
2037         ++instruction_id;
2038
2039         self->blocks[i]->eid = i;
2040         ir_block_enumerate(self->blocks[i], &instruction_id);
2041     }
2042 }
2043
2044 /* Local-value allocator
2045  * After finishing creating the liferange of all values used in a function
2046  * we can allocate their global-positions.
2047  * This is the counterpart to register-allocation in register machines.
2048  */
2049 typedef struct {
2050     ir_value **locals;
2051     size_t    *sizes;
2052     size_t    *positions;
2053     bool      *unique;
2054 } function_allocator;
2055
2056 static bool function_allocator_alloc(function_allocator *alloc, ir_value *var)
2057 {
2058     ir_value *slot;
2059     size_t vsize = ir_value_sizeof(var);
2060
2061     var->code.local = vec_size(alloc->locals);
2062
2063     slot = ir_value_var("reg", store_global, var->vtype);
2064     if (!slot)
2065         return false;
2066
2067     if (!ir_value_life_merge_into(slot, var))
2068         goto localerror;
2069
2070     vec_push(alloc->locals, slot);
2071     vec_push(alloc->sizes, vsize);
2072     vec_push(alloc->unique, var->unique_life);
2073
2074     return true;
2075
2076 localerror:
2077     ir_value_delete(slot);
2078     return false;
2079 }
2080
2081 static bool ir_function_allocator_assign(ir_function *self, function_allocator *alloc, ir_value *v)
2082 {
2083     size_t a;
2084     ir_value *slot;
2085
2086     if (v->unique_life)
2087         return function_allocator_alloc(alloc, v);
2088
2089     for (a = 0; a < vec_size(alloc->locals); ++a)
2090     {
2091         /* if it's reserved for a unique liferange: skip */
2092         if (alloc->unique[a])
2093             continue;
2094
2095         slot = alloc->locals[a];
2096
2097         /* never resize parameters
2098          * will be required later when overlapping temps + locals
2099          */
2100         if (a < vec_size(self->params) &&
2101             alloc->sizes[a] < ir_value_sizeof(v))
2102         {
2103             continue;
2104         }
2105
2106         if (ir_values_overlap(v, slot))
2107             continue;
2108
2109         if (!ir_value_life_merge_into(slot, v))
2110             return false;
2111
2112         /* adjust size for this slot */
2113         if (alloc->sizes[a] < ir_value_sizeof(v))
2114             alloc->sizes[a] = ir_value_sizeof(v);
2115
2116         v->code.local = a;
2117         return true;
2118     }
2119     if (a >= vec_size(alloc->locals)) {
2120         if (!function_allocator_alloc(alloc, v))
2121             return false;
2122     }
2123     return true;
2124 }
2125
2126 bool ir_function_allocate_locals(ir_function *self)
2127 {
2128     size_t i;
2129     bool   retval = true;
2130     size_t pos;
2131     bool   opt_gt = OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS);
2132
2133     ir_value *v;
2134
2135     function_allocator lockalloc, globalloc;
2136
2137     if (!vec_size(self->locals) && !vec_size(self->values))
2138         return true;
2139
2140     globalloc.locals    = NULL;
2141     globalloc.sizes     = NULL;
2142     globalloc.positions = NULL;
2143     globalloc.unique    = NULL;
2144     lockalloc.locals    = NULL;
2145     lockalloc.sizes     = NULL;
2146     lockalloc.positions = NULL;
2147     lockalloc.unique    = NULL;
2148
2149     for (i = 0; i < vec_size(self->locals); ++i)
2150     {
2151         v = self->locals[i];
2152         if ((self->flags & IR_FLAG_MASK_NO_LOCAL_TEMPS) || !OPTS_OPTIMIZATION(OPTIM_LOCAL_TEMPS)) {
2153             v->locked      = true;
2154             v->unique_life = true;
2155         }
2156         else if (i >= vec_size(self->params))
2157             break;
2158         else
2159             v->locked = true; /* lock parameters locals */
2160         if (!function_allocator_alloc((v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2161             goto error;
2162     }
2163     for (; i < vec_size(self->locals); ++i)
2164     {
2165         v = self->locals[i];
2166         if (!vec_size(v->life))
2167             continue;
2168         if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2169             goto error;
2170     }
2171
2172     /* Allocate a slot for any value that still exists */
2173     for (i = 0; i < vec_size(self->values); ++i)
2174     {
2175         v = self->values[i];
2176
2177         if (!vec_size(v->life))
2178             continue;
2179
2180         /* CALL optimization:
2181          * If the value is a parameter-temp: 1 write, 1 read from a CALL
2182          * and it's not "locked", write it to the OFS_PARM directly.
2183          */
2184         if (OPTS_OPTIMIZATION(OPTIM_CALL_STORES) && !v->locked && !v->unique_life) {
2185             if (vec_size(v->reads) == 1 && vec_size(v->writes) == 1 &&
2186                 (v->reads[0]->opcode == VINSTR_NRCALL ||
2187                  (v->reads[0]->opcode >= INSTR_CALL0 && v->reads[0]->opcode <= INSTR_CALL8)
2188                 )
2189                )
2190             {
2191                 size_t    param;
2192                 ir_instr *call = v->reads[0];
2193                 if (!vec_ir_value_find(call->params, v, &param)) {
2194                     irerror(call->context, "internal error: unlocked parameter %s not found", v->name);
2195                     goto error;
2196                 }
2197                 ++opts_optimizationcount[OPTIM_CALL_STORES];
2198                 v->callparam = true;
2199                 if (param < 8)
2200                     ir_value_code_setaddr(v, OFS_PARM0 + 3*param);
2201                 else {
2202                     size_t nprotos = vec_size(self->owner->extparam_protos);
2203                     ir_value *ep;
2204                     param -= 8;
2205                     if (nprotos > param)
2206                         ep = self->owner->extparam_protos[param];
2207                     else
2208                     {
2209                         ep = ir_gen_extparam_proto(self->owner);
2210                         while (++nprotos <= param)
2211                             ep = ir_gen_extparam_proto(self->owner);
2212                     }
2213                     ir_instr_op(v->writes[0], 0, ep, true);
2214                     call->params[param+8] = ep;
2215                 }
2216                 continue;
2217             }
2218             if (vec_size(v->writes) == 1 && v->writes[0]->opcode == INSTR_CALL0)
2219             {
2220                 v->store = store_return;
2221                 if (v->members[0]) v->members[0]->store = store_return;
2222                 if (v->members[1]) v->members[1]->store = store_return;
2223                 if (v->members[2]) v->members[2]->store = store_return;
2224                 ++opts_optimizationcount[OPTIM_CALL_STORES];
2225                 continue;
2226             }
2227         }
2228
2229         if (!ir_function_allocator_assign(self, (v->locked || !opt_gt ? &lockalloc : &globalloc), v))
2230             goto error;
2231     }
2232
2233     if (!lockalloc.sizes && !globalloc.sizes) {
2234         goto cleanup;
2235     }
2236     vec_push(lockalloc.positions, 0);
2237     vec_push(globalloc.positions, 0);
2238
2239     /* Adjust slot positions based on sizes */
2240     if (lockalloc.sizes) {
2241         pos = (vec_size(lockalloc.sizes) ? lockalloc.positions[0] : 0);
2242         for (i = 1; i < vec_size(lockalloc.sizes); ++i)
2243         {
2244             pos = lockalloc.positions[i-1] + lockalloc.sizes[i-1];
2245             vec_push(lockalloc.positions, pos);
2246         }
2247         self->allocated_locals = pos + vec_last(lockalloc.sizes);
2248     }
2249     if (globalloc.sizes) {
2250         pos = (vec_size(globalloc.sizes) ? globalloc.positions[0] : 0);
2251         for (i = 1; i < vec_size(globalloc.sizes); ++i)
2252         {
2253             pos = globalloc.positions[i-1] + globalloc.sizes[i-1];
2254             vec_push(globalloc.positions, pos);
2255         }
2256         self->globaltemps = pos + vec_last(globalloc.sizes);
2257     }
2258
2259     /* Locals need to know their new position */
2260     for (i = 0; i < vec_size(self->locals); ++i) {
2261         v = self->locals[i];
2262         if (v->locked || !opt_gt)
2263             v->code.local = lockalloc.positions[v->code.local];
2264         else
2265             v->code.local = globalloc.positions[v->code.local];
2266     }
2267     /* Take over the actual slot positions on values */
2268     for (i = 0; i < vec_size(self->values); ++i) {
2269         v = self->values[i];
2270         if (v->locked || !opt_gt)
2271             v->code.local = lockalloc.positions[v->code.local];
2272         else
2273             v->code.local = globalloc.positions[v->code.local];
2274     }
2275
2276     goto cleanup;
2277
2278 error:
2279     retval = false;
2280 cleanup:
2281     for (i = 0; i < vec_size(lockalloc.locals); ++i)
2282         ir_value_delete(lockalloc.locals[i]);
2283     for (i = 0; i < vec_size(globalloc.locals); ++i)
2284         ir_value_delete(globalloc.locals[i]);
2285     vec_free(globalloc.unique);
2286     vec_free(globalloc.locals);
2287     vec_free(globalloc.sizes);
2288     vec_free(globalloc.positions);
2289     vec_free(lockalloc.unique);
2290     vec_free(lockalloc.locals);
2291     vec_free(lockalloc.sizes);
2292     vec_free(lockalloc.positions);
2293     return retval;
2294 }
2295
2296 /* Get information about which operand
2297  * is read from, or written to.
2298  */
2299 static void ir_op_read_write(int op, size_t *read, size_t *write)
2300 {
2301     switch (op)
2302     {
2303     case VINSTR_JUMP:
2304     case INSTR_GOTO:
2305         *write = 0;
2306         *read = 0;
2307         break;
2308     case INSTR_IF:
2309     case INSTR_IFNOT:
2310 #if 0
2311     case INSTR_IF_S:
2312     case INSTR_IFNOT_S:
2313 #endif
2314     case INSTR_RETURN:
2315     case VINSTR_COND:
2316         *write = 0;
2317         *read = 1;
2318         break;
2319     case INSTR_STOREP_F:
2320     case INSTR_STOREP_V:
2321     case INSTR_STOREP_S:
2322     case INSTR_STOREP_ENT:
2323     case INSTR_STOREP_FLD:
2324     case INSTR_STOREP_FNC:
2325         *write = 0;
2326         *read  = 7;
2327         break;
2328     default:
2329         *write = 1;
2330         *read = 6;
2331         break;
2332     };
2333 }
2334
2335 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2336 {
2337     size_t       i;
2338     const size_t vs = vec_size(self->living);
2339     bool         changed = false;
2340     for (i = 0; i != vs; ++i)
2341     {
2342         if (ir_value_life_merge(self->living[i], eid))
2343             changed = true;
2344     }
2345     return changed;
2346 }
2347
2348 static bool ir_block_living_lock(ir_block *self)
2349 {
2350     size_t i;
2351     bool changed = false;
2352     for (i = 0; i != vec_size(self->living); ++i)
2353     {
2354         if (!self->living[i]->locked) {
2355             self->living[i]->locked = true;
2356             changed = true;
2357         }
2358     }
2359     return changed;
2360 }
2361
2362 static bool ir_block_life_propagate(ir_block *self, bool *changed)
2363 {
2364     ir_instr *instr;
2365     ir_value *value;
2366     size_t i, o, p, mem, cnt;
2367     /* bitmasks which operands are read from or written to */
2368     size_t read, write;
2369     char dbg_ind[16];
2370     dbg_ind[0] = '#';
2371     dbg_ind[1] = '0';
2372     (void)dbg_ind;
2373
2374     vec_free(self->living);
2375
2376     p = vec_size(self->exits);
2377     for (i = 0; i < p; ++i) {
2378         ir_block *prev = self->exits[i];
2379         cnt = vec_size(prev->living);
2380         for (o = 0; o < cnt; ++o) {
2381             if (!vec_ir_value_find(self->living, prev->living[o], NULL))
2382                 vec_push(self->living, prev->living[o]);
2383         }
2384     }
2385
2386     i = vec_size(self->instr);
2387     while (i)
2388     { --i;
2389         instr = self->instr[i];
2390
2391         /* See which operands are read and write operands */
2392         ir_op_read_write(instr->opcode, &read, &write);
2393
2394         /* Go through the 3 main operands
2395          * writes first, then reads
2396          */
2397         for (o = 0; o < 3; ++o)
2398         {
2399             if (!instr->_ops[o]) /* no such operand */
2400                 continue;
2401
2402             value = instr->_ops[o];
2403
2404             /* We only care about locals */
2405             /* we also calculate parameter liferanges so that locals
2406              * can take up parameter slots */
2407             if (value->store != store_value &&
2408                 value->store != store_local &&
2409                 value->store != store_param)
2410                 continue;
2411
2412             /* write operands */
2413             /* When we write to a local, we consider it "dead" for the
2414              * remaining upper part of the function, since in SSA a value
2415              * can only be written once (== created)
2416              */
2417             if (write & (1<<o))
2418             {
2419                 size_t idx;
2420                 bool in_living = vec_ir_value_find(self->living, value, &idx);
2421                 if (!in_living)
2422                 {
2423                     /* If the value isn't alive it hasn't been read before... */
2424                     /* TODO: See if the warning can be emitted during parsing or AST processing
2425                      * otherwise have warning printed here.
2426                      * IF printing a warning here: include filecontext_t,
2427                      * and make sure it's only printed once
2428                      * since this function is run multiple times.
2429                      */
2430                     /* con_err( "Value only written %s\n", value->name); */
2431                     if (ir_value_life_merge(value, instr->eid))
2432                         *changed = true;
2433                 } else {
2434                     /* since 'living' won't contain it
2435                      * anymore, merge the value, since
2436                      * (A) doesn't.
2437                      */
2438                     if (ir_value_life_merge(value, instr->eid))
2439                         *changed = true;
2440                     /* Then remove */
2441                     vec_remove(self->living, idx, 1);
2442                 }
2443                 /* Removing a vector removes all members */
2444                 for (mem = 0; mem < 3; ++mem) {
2445                     if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], &idx)) {
2446                         if (ir_value_life_merge(value->members[mem], instr->eid))
2447                             *changed = true;
2448                         vec_remove(self->living, idx, 1);
2449                     }
2450                 }
2451                 /* Removing the last member removes the vector */
2452                 if (value->memberof) {
2453                     value = value->memberof;
2454                     for (mem = 0; mem < 3; ++mem) {
2455                         if (value->members[mem] && vec_ir_value_find(self->living, value->members[mem], NULL))
2456                             break;
2457                     }
2458                     if (mem == 3 && vec_ir_value_find(self->living, value, &idx)) {
2459                         if (ir_value_life_merge(value, instr->eid))
2460                             *changed = true;
2461                         vec_remove(self->living, idx, 1);
2462                     }
2463                 }
2464             }
2465         }
2466
2467         if (instr->opcode == INSTR_MUL_VF)
2468         {
2469             value = instr->_ops[2];
2470             /* the float source will get an additional lifetime */
2471             if (ir_value_life_merge(value, instr->eid+1))
2472                 *changed = true;
2473             if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2474                 *changed = true;
2475         }
2476         else if (instr->opcode == INSTR_MUL_FV || instr->opcode == INSTR_LOAD_V)
2477         {
2478             value = instr->_ops[1];
2479             /* the float source will get an additional lifetime */
2480             if (ir_value_life_merge(value, instr->eid+1))
2481                 *changed = true;
2482             if (value->memberof && ir_value_life_merge(value->memberof, instr->eid+1))
2483                 *changed = true;
2484         }
2485
2486         for (o = 0; o < 3; ++o)
2487         {
2488             if (!instr->_ops[o]) /* no such operand */
2489                 continue;
2490
2491             value = instr->_ops[o];
2492
2493             /* We only care about locals */
2494             /* we also calculate parameter liferanges so that locals
2495              * can take up parameter slots */
2496             if (value->store != store_value &&
2497                 value->store != store_local &&
2498                 value->store != store_param)
2499                 continue;
2500
2501             /* read operands */
2502             if (read & (1<<o))
2503             {
2504                 if (!vec_ir_value_find(self->living, value, NULL))
2505                     vec_push(self->living, value);
2506                 /* reading adds the full vector */
2507                 if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2508                     vec_push(self->living, value->memberof);
2509                 for (mem = 0; mem < 3; ++mem) {
2510                     if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2511                         vec_push(self->living, value->members[mem]);
2512                 }
2513             }
2514         }
2515         /* PHI operands are always read operands */
2516         for (p = 0; p < vec_size(instr->phi); ++p)
2517         {
2518             value = instr->phi[p].value;
2519             if (!vec_ir_value_find(self->living, value, NULL))
2520                 vec_push(self->living, value);
2521             /* reading adds the full vector */
2522             if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2523                 vec_push(self->living, value->memberof);
2524             for (mem = 0; mem < 3; ++mem) {
2525                 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2526                     vec_push(self->living, value->members[mem]);
2527             }
2528         }
2529
2530         /* on a call, all these values must be "locked" */
2531         if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2532             if (ir_block_living_lock(self))
2533                 *changed = true;
2534         }
2535         /* call params are read operands too */
2536         for (p = 0; p < vec_size(instr->params); ++p)
2537         {
2538             value = instr->params[p];
2539             if (!vec_ir_value_find(self->living, value, NULL))
2540                 vec_push(self->living, value);
2541             /* reading adds the full vector */
2542             if (value->memberof && !vec_ir_value_find(self->living, value->memberof, NULL))
2543                 vec_push(self->living, value->memberof);
2544             for (mem = 0; mem < 3; ++mem) {
2545                 if (value->members[mem] && !vec_ir_value_find(self->living, value->members[mem], NULL))
2546                     vec_push(self->living, value->members[mem]);
2547             }
2548         }
2549
2550         /* (A) */
2551         if (ir_block_living_add_instr(self, instr->eid))
2552             *changed = true;
2553     }
2554     /* the "entry" instruction ID */
2555     if (ir_block_living_add_instr(self, self->entry_id))
2556         *changed = true;
2557
2558     return true;
2559 }
2560
2561 bool ir_function_calculate_liferanges(ir_function *self)
2562 {
2563     size_t i, s;
2564     bool changed;
2565
2566     /* parameters live at 0 */
2567     for (i = 0; i < vec_size(self->params); ++i)
2568         ir_value_life_merge(self->locals[i], 0);
2569
2570     do {
2571         self->run_id++;
2572         changed = false;
2573         i = vec_size(self->blocks);
2574         while (i--) {
2575             ir_block_life_propagate(self->blocks[i], &changed);
2576         }
2577     } while (changed);
2578
2579     if (vec_size(self->blocks)) {
2580         ir_block *block = self->blocks[0];
2581         for (i = 0; i < vec_size(block->living); ++i) {
2582             ir_value *v = block->living[i];
2583             if (v->store != store_local)
2584                 continue;
2585             if (v->vtype == TYPE_VECTOR)
2586                 continue;
2587             self->flags |= IR_FLAG_HAS_UNINITIALIZED;
2588             /* find the instruction reading from it */
2589             for (s = 0; s < vec_size(v->reads); ++s) {
2590                 if (v->reads[s]->eid == v->life[0].end)
2591                     break;
2592             }
2593             if (s < vec_size(v->reads)) {
2594                 if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2595                               "variable `%s` may be used uninitialized in this function\n"
2596                               " -> %s:%i",
2597                               v->name,
2598                               v->reads[s]->context.file, v->reads[s]->context.line)
2599                    )
2600                 {
2601                     return false;
2602                 }
2603                 continue;
2604             }
2605             if (v->memberof) {
2606                 ir_value *vec = v->memberof;
2607                 for (s = 0; s < vec_size(vec->reads); ++s) {
2608                     if (vec->reads[s]->eid == v->life[0].end)
2609                         break;
2610                 }
2611                 if (s < vec_size(vec->reads)) {
2612                     if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2613                                   "variable `%s` may be used uninitialized in this function\n"
2614                                   " -> %s:%i",
2615                                   v->name,
2616                                   vec->reads[s]->context.file, vec->reads[s]->context.line)
2617                        )
2618                     {
2619                         return false;
2620                     }
2621                     continue;
2622                 }
2623             }
2624             if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2625                           "variable `%s` may be used uninitialized in this function", v->name))
2626             {
2627                 return false;
2628             }
2629         }
2630     }
2631     return true;
2632 }
2633
2634 /***********************************************************************
2635  *IR Code-Generation
2636  *
2637  * Since the IR has the convention of putting 'write' operands
2638  * at the beginning, we have to rotate the operands of instructions
2639  * properly in order to generate valid QCVM code.
2640  *
2641  * Having destinations at a fixed position is more convenient. In QC
2642  * this is *mostly* OPC,  but FTE adds at least 2 instructions which
2643  * read from from OPA,  and store to OPB rather than OPC.   Which is
2644  * partially the reason why the implementation of these instructions
2645  * in darkplaces has been delayed for so long.
2646  *
2647  * Breaking conventions is annoying...
2648  */
2649 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2650
2651 static bool gen_global_field(code_t *code, ir_value *global)
2652 {
2653     if (global->hasvalue)
2654     {
2655         ir_value *fld = global->constval.vpointer;
2656         if (!fld) {
2657             irerror(global->context, "Invalid field constant with no field: %s", global->name);
2658             return false;
2659         }
2660
2661         /* copy the field's value */
2662         ir_value_code_setaddr(global, vec_size(code->globals));
2663         vec_push(code->globals, fld->code.fieldaddr);
2664         if (global->fieldtype == TYPE_VECTOR) {
2665             vec_push(code->globals, fld->code.fieldaddr+1);
2666             vec_push(code->globals, fld->code.fieldaddr+2);
2667         }
2668     }
2669     else
2670     {
2671         ir_value_code_setaddr(global, vec_size(code->globals));
2672         vec_push(code->globals, 0);
2673         if (global->fieldtype == TYPE_VECTOR) {
2674             vec_push(code->globals, 0);
2675             vec_push(code->globals, 0);
2676         }
2677     }
2678     if (global->code.globaladdr < 0)
2679         return false;
2680     return true;
2681 }
2682
2683 static bool gen_global_pointer(code_t *code, ir_value *global)
2684 {
2685     if (global->hasvalue)
2686     {
2687         ir_value *target = global->constval.vpointer;
2688         if (!target) {
2689             irerror(global->context, "Invalid pointer constant: %s", global->name);
2690             /* NULL pointers are pointing to the NULL constant, which also
2691              * sits at address 0, but still has an ir_value for itself.
2692              */
2693             return false;
2694         }
2695
2696         /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2697          * void() foo; <- proto
2698          * void() *fooptr = &foo;
2699          * void() foo = { code }
2700          */
2701         if (!target->code.globaladdr) {
2702             /* FIXME: Check for the constant nullptr ir_value!
2703              * because then code.globaladdr being 0 is valid.
2704              */
2705             irerror(global->context, "FIXME: Relocation support");
2706             return false;
2707         }
2708
2709         ir_value_code_setaddr(global, vec_size(code->globals));
2710         vec_push(code->globals, target->code.globaladdr);
2711     }
2712     else
2713     {
2714         ir_value_code_setaddr(global, vec_size(code->globals));
2715         vec_push(code->globals, 0);
2716     }
2717     if (global->code.globaladdr < 0)
2718         return false;
2719     return true;
2720 }
2721
2722 static bool gen_blocks_recursive(code_t *code, ir_function *func, ir_block *block)
2723 {
2724     prog_section_statement stmt;
2725     ir_instr *instr;
2726     ir_block *target;
2727     ir_block *ontrue;
2728     ir_block *onfalse;
2729     size_t    stidx;
2730     size_t    i;
2731
2732     block->generated = true;
2733     block->code_start = vec_size(code->statements);
2734     for (i = 0; i < vec_size(block->instr); ++i)
2735     {
2736         instr = block->instr[i];
2737
2738         if (instr->opcode == VINSTR_PHI) {
2739             irerror(block->context, "cannot generate virtual instruction (phi)");
2740             return false;
2741         }
2742
2743         if (instr->opcode == VINSTR_JUMP) {
2744             target = instr->bops[0];
2745             /* for uncoditional jumps, if the target hasn't been generated
2746              * yet, we generate them right here.
2747              */
2748             if (!target->generated)
2749                 return gen_blocks_recursive(code, func, target);
2750
2751             /* otherwise we generate a jump instruction */
2752             stmt.opcode = INSTR_GOTO;
2753             stmt.o1.s1 = (target->code_start) - vec_size(code->statements);
2754             stmt.o2.s1 = 0;
2755             stmt.o3.s1 = 0;
2756             if (stmt.o1.s1 != 1)
2757                 code_push_statement(code, &stmt, instr->context.line);
2758
2759             /* no further instructions can be in this block */
2760             return true;
2761         }
2762
2763         if (instr->opcode == VINSTR_COND) {
2764             ontrue  = instr->bops[0];
2765             onfalse = instr->bops[1];
2766             /* TODO: have the AST signal which block should
2767              * come first: eg. optimize IFs without ELSE...
2768              */
2769
2770             stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2771             stmt.o2.u1 = 0;
2772             stmt.o3.s1 = 0;
2773
2774             if (ontrue->generated) {
2775                 stmt.opcode = INSTR_IF;
2776                 stmt.o2.s1 = (ontrue->code_start) - vec_size(code->statements);
2777                 if (stmt.o2.s1 != 1)
2778                     code_push_statement(code, &stmt, instr->context.line);
2779             }
2780             if (onfalse->generated) {
2781                 stmt.opcode = INSTR_IFNOT;
2782                 stmt.o2.s1 = (onfalse->code_start) - vec_size(code->statements);
2783                 if (stmt.o2.s1 != 1)
2784                     code_push_statement(code, &stmt, instr->context.line);
2785             }
2786             if (!ontrue->generated) {
2787                 if (onfalse->generated)
2788                     return gen_blocks_recursive(code, func, ontrue);
2789             }
2790             if (!onfalse->generated) {
2791                 if (ontrue->generated)
2792                     return gen_blocks_recursive(code, func, onfalse);
2793             }
2794             /* neither ontrue nor onfalse exist */
2795             stmt.opcode = INSTR_IFNOT;
2796             if (!instr->likely) {
2797                 /* Honor the likelyhood hint */
2798                 ir_block *tmp = onfalse;
2799                 stmt.opcode = INSTR_IF;
2800                 onfalse = ontrue;
2801                 ontrue = tmp;
2802             }
2803             stidx = vec_size(code->statements);
2804             code_push_statement(code, &stmt, instr->context.line);
2805             /* on false we jump, so add ontrue-path */
2806             if (!gen_blocks_recursive(code, func, ontrue))
2807                 return false;
2808             /* fixup the jump address */
2809             code->statements[stidx].o2.s1 = vec_size(code->statements) - stidx;
2810             /* generate onfalse path */
2811             if (onfalse->generated) {
2812                 /* fixup the jump address */
2813                 code->statements[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2814                 if (stidx+2 == vec_size(code->statements) && code->statements[stidx].o2.s1 == 1) {
2815                     code->statements[stidx] = code->statements[stidx+1];
2816                     if (code->statements[stidx].o1.s1 < 0)
2817                         code->statements[stidx].o1.s1++;
2818                     code_pop_statement(code);
2819                 }
2820                 stmt.opcode = vec_last(code->statements).opcode;
2821                 if (stmt.opcode == INSTR_GOTO ||
2822                     stmt.opcode == INSTR_IF ||
2823                     stmt.opcode == INSTR_IFNOT ||
2824                     stmt.opcode == INSTR_RETURN ||
2825                     stmt.opcode == INSTR_DONE)
2826                 {
2827                     /* no use jumping from here */
2828                     return true;
2829                 }
2830                 /* may have been generated in the previous recursive call */
2831                 stmt.opcode = INSTR_GOTO;
2832                 stmt.o1.s1 = (onfalse->code_start) - vec_size(code->statements);
2833                 stmt.o2.s1 = 0;
2834                 stmt.o3.s1 = 0;
2835                 if (stmt.o1.s1 != 1)
2836                     code_push_statement(code, &stmt, instr->context.line);
2837                 return true;
2838             }
2839             else if (stidx+2 == vec_size(code->statements) && code->statements[stidx].o2.s1 == 1) {
2840                 code->statements[stidx] = code->statements[stidx+1];
2841                 if (code->statements[stidx].o1.s1 < 0)
2842                     code->statements[stidx].o1.s1++;
2843                 code_pop_statement(code);
2844             }
2845             /* if not, generate now */
2846             return gen_blocks_recursive(code, func, onfalse);
2847         }
2848
2849         if ( (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8)
2850            || instr->opcode == VINSTR_NRCALL)
2851         {
2852             size_t p, first;
2853             ir_value *retvalue;
2854
2855             first = vec_size(instr->params);
2856             if (first > 8)
2857                 first = 8;
2858             for (p = 0; p < first; ++p)
2859             {
2860                 ir_value *param = instr->params[p];
2861                 if (param->callparam)
2862                     continue;
2863
2864                 stmt.opcode = INSTR_STORE_F;
2865                 stmt.o3.u1 = 0;
2866
2867                 if (param->vtype == TYPE_FIELD)
2868                     stmt.opcode = field_store_instr[param->fieldtype];
2869                 else if (param->vtype == TYPE_NIL)
2870                     stmt.opcode = INSTR_STORE_V;
2871                 else
2872                     stmt.opcode = type_store_instr[param->vtype];
2873                 stmt.o1.u1 = ir_value_code_addr(param);
2874                 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2875                 code_push_statement(code, &stmt, instr->context.line);
2876             }
2877             /* Now handle extparams */
2878             first = vec_size(instr->params);
2879             for (; p < first; ++p)
2880             {
2881                 ir_builder *ir = func->owner;
2882                 ir_value *param = instr->params[p];
2883                 ir_value *targetparam;
2884
2885                 if (param->callparam)
2886                     continue;
2887
2888                 if (p-8 >= vec_size(ir->extparams))
2889                     ir_gen_extparam(ir);
2890
2891                 targetparam = ir->extparams[p-8];
2892
2893                 stmt.opcode = INSTR_STORE_F;
2894                 stmt.o3.u1 = 0;
2895
2896                 if (param->vtype == TYPE_FIELD)
2897                     stmt.opcode = field_store_instr[param->fieldtype];
2898                 else if (param->vtype == TYPE_NIL)
2899                     stmt.opcode = INSTR_STORE_V;
2900                 else
2901                     stmt.opcode = type_store_instr[param->vtype];
2902                 stmt.o1.u1 = ir_value_code_addr(param);
2903                 stmt.o2.u1 = ir_value_code_addr(targetparam);
2904                 code_push_statement(code, &stmt, instr->context.line);
2905             }
2906
2907             stmt.opcode = INSTR_CALL0 + vec_size(instr->params);
2908             if (stmt.opcode > INSTR_CALL8)
2909                 stmt.opcode = INSTR_CALL8;
2910             stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2911             stmt.o2.u1 = 0;
2912             stmt.o3.u1 = 0;
2913             code_push_statement(code, &stmt, instr->context.line);
2914
2915             retvalue = instr->_ops[0];
2916             if (retvalue && retvalue->store != store_return &&
2917                 (retvalue->store == store_global || vec_size(retvalue->life)))
2918             {
2919                 /* not to be kept in OFS_RETURN */
2920                 if (retvalue->vtype == TYPE_FIELD && OPTS_FLAG(ADJUST_VECTOR_FIELDS))
2921                     stmt.opcode = field_store_instr[retvalue->fieldtype];
2922                 else
2923                     stmt.opcode = type_store_instr[retvalue->vtype];
2924                 stmt.o1.u1 = OFS_RETURN;
2925                 stmt.o2.u1 = ir_value_code_addr(retvalue);
2926                 stmt.o3.u1 = 0;
2927                 code_push_statement(code, &stmt, instr->context.line);
2928             }
2929             continue;
2930         }
2931
2932         if (instr->opcode == INSTR_STATE) {
2933             irerror(block->context, "TODO: state instruction");
2934             return false;
2935         }
2936
2937         stmt.opcode = instr->opcode;
2938         stmt.o1.u1 = 0;
2939         stmt.o2.u1 = 0;
2940         stmt.o3.u1 = 0;
2941
2942         /* This is the general order of operands */
2943         if (instr->_ops[0])
2944             stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2945
2946         if (instr->_ops[1])
2947             stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2948
2949         if (instr->_ops[2])
2950             stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2951
2952         if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2953         {
2954             stmt.o1.u1 = stmt.o3.u1;
2955             stmt.o3.u1 = 0;
2956         }
2957         else if ((stmt.opcode >= INSTR_STORE_F &&
2958                   stmt.opcode <= INSTR_STORE_FNC) ||
2959                  (stmt.opcode >= INSTR_STOREP_F &&
2960                   stmt.opcode <= INSTR_STOREP_FNC))
2961         {
2962             /* 2-operand instructions with A -> B */
2963             stmt.o2.u1 = stmt.o3.u1;
2964             stmt.o3.u1 = 0;
2965
2966             /* tiny optimization, don't output
2967              * STORE a, a
2968              */
2969             if (stmt.o2.u1 == stmt.o1.u1 &&
2970                 OPTS_OPTIMIZATION(OPTIM_PEEPHOLE))
2971             {
2972                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
2973                 continue;
2974             }
2975         }
2976
2977         code_push_statement(code, &stmt, instr->context.line);
2978     }
2979     return true;
2980 }
2981
2982 static bool gen_function_code(code_t *code, ir_function *self)
2983 {
2984     ir_block *block;
2985     prog_section_statement stmt, *retst;
2986
2987     /* Starting from entry point, we generate blocks "as they come"
2988      * for now. Dead blocks will not be translated obviously.
2989      */
2990     if (!vec_size(self->blocks)) {
2991         irerror(self->context, "Function '%s' declared without body.", self->name);
2992         return false;
2993     }
2994
2995     block = self->blocks[0];
2996     if (block->generated)
2997         return true;
2998
2999     if (!gen_blocks_recursive(code, self, block)) {
3000         irerror(self->context, "failed to generate blocks for '%s'", self->name);
3001         return false;
3002     }
3003
3004     /* code_write and qcvm -disasm need to know that the function ends here */
3005     retst = &vec_last(code->statements);
3006     if (OPTS_OPTIMIZATION(OPTIM_VOID_RETURN) &&
3007         self->outtype == TYPE_VOID &&
3008         retst->opcode == INSTR_RETURN &&
3009         !retst->o1.u1 && !retst->o2.u1 && !retst->o3.u1)
3010     {
3011         retst->opcode = INSTR_DONE;
3012         ++opts_optimizationcount[OPTIM_VOID_RETURN];
3013     } else {
3014         stmt.opcode = INSTR_DONE;
3015         stmt.o1.u1 = 0;
3016         stmt.o2.u1 = 0;
3017         stmt.o3.u1 = 0;
3018         code_push_statement(code, &stmt, vec_last(code->linenums));
3019     }
3020     return true;
3021 }
3022
3023 static qcint ir_builder_filestring(ir_builder *ir, const char *filename)
3024 {
3025     /* NOTE: filename pointers are copied, we never strdup them,
3026      * thus we can use pointer-comparison to find the string.
3027      */
3028     size_t i;
3029     qcint  str;
3030
3031     for (i = 0; i < vec_size(ir->filenames); ++i) {
3032         if (ir->filenames[i] == filename)
3033             return ir->filestrings[i];
3034     }
3035
3036     str = code_genstring(ir->code, filename);
3037     vec_push(ir->filenames, filename);
3038     vec_push(ir->filestrings, str);
3039     return str;
3040 }
3041
3042 static bool gen_global_function(ir_builder *ir, ir_value *global)
3043 {
3044     prog_section_function fun;
3045     ir_function          *irfun;
3046
3047     size_t i;
3048
3049     if (!global->hasvalue || (!global->constval.vfunc))
3050     {
3051         irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
3052         return false;
3053     }
3054
3055     irfun = global->constval.vfunc;
3056
3057     fun.name    = global->code.name;
3058     fun.file    = ir_builder_filestring(ir, global->context.file);
3059     fun.profile = 0; /* always 0 */
3060     fun.nargs   = vec_size(irfun->params);
3061     if (fun.nargs > 8)
3062         fun.nargs = 8;
3063
3064     for (i = 0;i < 8; ++i) {
3065         if ((int32_t)i >= fun.nargs)
3066             fun.argsize[i] = 0;
3067         else
3068             fun.argsize[i] = type_sizeof_[irfun->params[i]];
3069     }
3070
3071     fun.firstlocal = 0;
3072     fun.locals     = irfun->allocated_locals;
3073
3074     if (irfun->builtin)
3075         fun.entry = irfun->builtin+1;
3076     else {
3077         irfun->code_function_def = vec_size(ir->code->functions);
3078         fun.entry                = vec_size(ir->code->statements);
3079     }
3080
3081     vec_push(ir->code->functions, fun);
3082     return true;
3083 }
3084
3085 static ir_value* ir_gen_extparam_proto(ir_builder *ir)
3086 {
3087     ir_value *global;
3088     char      name[128];
3089
3090     util_snprintf(name, sizeof(name), "EXTPARM#%i", (int)(vec_size(ir->extparam_protos)));
3091     global = ir_value_var(name, store_global, TYPE_VECTOR);
3092
3093     vec_push(ir->extparam_protos, global);
3094     return global;
3095 }
3096
3097 static void ir_gen_extparam(ir_builder *ir)
3098 {
3099     prog_section_def def;
3100     ir_value        *global;
3101
3102     if (vec_size(ir->extparam_protos) < vec_size(ir->extparams)+1)
3103         global = ir_gen_extparam_proto(ir);
3104     else
3105         global = ir->extparam_protos[vec_size(ir->extparams)];
3106
3107     def.name   = code_genstring(ir->code, global->name);
3108     def.type   = TYPE_VECTOR;
3109     def.offset = vec_size(ir->code->globals);
3110
3111     vec_push(ir->code->defs, def);
3112
3113     ir_value_code_setaddr(global, def.offset);
3114
3115     vec_push(ir->code->globals, 0);
3116     vec_push(ir->code->globals, 0);
3117     vec_push(ir->code->globals, 0);
3118
3119     vec_push(ir->extparams, global);
3120 }
3121
3122 static bool gen_function_extparam_copy(code_t *code, ir_function *self)
3123 {
3124     size_t i, ext, numparams;
3125
3126     ir_builder *ir = self->owner;
3127     ir_value   *ep;
3128     prog_section_statement stmt;
3129
3130     numparams = vec_size(self->params);
3131     if (!numparams)
3132         return true;
3133
3134     stmt.opcode = INSTR_STORE_F;
3135     stmt.o3.s1 = 0;
3136     for (i = 8; i < numparams; ++i) {
3137         ext = i - 8;
3138         if (ext >= vec_size(ir->extparams))
3139             ir_gen_extparam(ir);
3140
3141         ep = ir->extparams[ext];
3142
3143         stmt.opcode = type_store_instr[self->locals[i]->vtype];
3144         if (self->locals[i]->vtype == TYPE_FIELD &&
3145             self->locals[i]->fieldtype == TYPE_VECTOR)
3146         {
3147             stmt.opcode = INSTR_STORE_V;
3148         }
3149         stmt.o1.u1 = ir_value_code_addr(ep);
3150         stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3151         code_push_statement(code, &stmt, self->context.line);
3152     }
3153
3154     return true;
3155 }
3156
3157 static bool gen_function_varargs_copy(code_t *code, ir_function *self)
3158 {
3159     size_t i, ext, numparams, maxparams;
3160
3161     ir_builder *ir = self->owner;
3162     ir_value   *ep;
3163     prog_section_statement stmt;
3164
3165     numparams = vec_size(self->params);
3166     if (!numparams)
3167         return true;
3168
3169     stmt.opcode = INSTR_STORE_V;
3170     stmt.o3.s1 = 0;
3171     maxparams = numparams + self->max_varargs;
3172     for (i = numparams; i < maxparams; ++i) {
3173         if (i < 8) {
3174             stmt.o1.u1 = OFS_PARM0 + 3*i;
3175             stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3176             code_push_statement(code, &stmt, self->context.line);
3177             continue;
3178         }
3179         ext = i - 8;
3180         while (ext >= vec_size(ir->extparams))
3181             ir_gen_extparam(ir);
3182
3183         ep = ir->extparams[ext];
3184
3185         stmt.o1.u1 = ir_value_code_addr(ep);
3186         stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3187         code_push_statement(code, &stmt, self->context.line);
3188     }
3189
3190     return true;
3191 }
3192
3193 static bool gen_function_locals(ir_builder *ir, ir_value *global)
3194 {
3195     prog_section_function *def;
3196     ir_function           *irfun;
3197     size_t                 i;
3198     uint32_t               firstlocal, firstglobal;
3199
3200     irfun = global->constval.vfunc;
3201     def   = ir->code->functions + irfun->code_function_def;
3202
3203     if (OPTS_OPTION_BOOL(OPTION_G) ||
3204         !OPTS_OPTIMIZATION(OPTIM_OVERLAP_LOCALS)        ||
3205         (irfun->flags & IR_FLAG_MASK_NO_OVERLAP))
3206     {
3207         firstlocal = def->firstlocal = vec_size(ir->code->globals);
3208     } else {
3209         firstlocal = def->firstlocal = ir->first_common_local;
3210         ++opts_optimizationcount[OPTIM_OVERLAP_LOCALS];
3211     }
3212
3213     firstglobal = (OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS) ? ir->first_common_globaltemp : firstlocal);
3214
3215     for (i = vec_size(ir->code->globals); i < firstlocal + irfun->allocated_locals; ++i)
3216         vec_push(ir->code->globals, 0);
3217     for (i = 0; i < vec_size(irfun->locals); ++i) {
3218         ir_value *v = irfun->locals[i];
3219         if (v->locked || !OPTS_OPTIMIZATION(OPTIM_GLOBAL_TEMPS)) {
3220             ir_value_code_setaddr(v, firstlocal + v->code.local);
3221             if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
3222                 irerror(irfun->locals[i]->context, "failed to generate local %s", irfun->locals[i]->name);
3223                 return false;
3224             }
3225         }
3226         else
3227             ir_value_code_setaddr(v, firstglobal + v->code.local);
3228     }
3229     for (i = 0; i < vec_size(irfun->values); ++i)
3230     {
3231         ir_value *v = irfun->values[i];
3232         if (v->callparam)
3233             continue;
3234         if (v->locked)
3235             ir_value_code_setaddr(v, firstlocal + v->code.local);
3236         else
3237             ir_value_code_setaddr(v, firstglobal + v->code.local);
3238     }
3239     return true;
3240 }
3241
3242 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
3243 {
3244     prog_section_function *fundef;
3245     ir_function           *irfun;
3246
3247     (void)ir;
3248
3249     irfun = global->constval.vfunc;
3250     if (!irfun) {
3251         if (global->cvq == CV_NONE) {
3252             irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
3253                       "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
3254         }
3255         /* this was a function pointer, don't generate code for those */
3256         return true;
3257     }
3258
3259     if (irfun->builtin)
3260         return true;
3261
3262     if (irfun->code_function_def < 0) {
3263         irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
3264         return false;
3265     }
3266     fundef = &ir->code->functions[irfun->code_function_def];
3267
3268     fundef->entry = vec_size(ir->code->statements);
3269     if (!gen_function_locals(ir, global)) {
3270         irerror(irfun->context, "Failed to generate locals for function %s", irfun->name);
3271         return false;
3272     }
3273     if (!gen_function_extparam_copy(ir->code, irfun)) {
3274         irerror(irfun->context, "Failed to generate extparam-copy code for function %s", irfun->name);
3275         return false;
3276     }
3277     if (irfun->max_varargs && !gen_function_varargs_copy(ir->code, irfun)) {
3278         irerror(irfun->context, "Failed to generate vararg-copy code for function %s", irfun->name);
3279         return false;
3280     }
3281     if (!gen_function_code(ir->code, irfun)) {
3282         irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
3283         return false;
3284     }
3285     return true;
3286 }
3287
3288 static void gen_vector_defs(code_t *code, prog_section_def def, const char *name)
3289 {
3290     char  *component;
3291     size_t len, i;
3292
3293     if (!name || name[0] == '#' || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3294         return;
3295
3296     def.type = TYPE_FLOAT;
3297
3298     len = strlen(name);
3299
3300     component = (char*)mem_a(len+3);
3301     memcpy(component, name, len);
3302     len += 2;
3303     component[len-0] = 0;
3304     component[len-2] = '_';
3305
3306     component[len-1] = 'x';
3307
3308     for (i = 0; i < 3; ++i) {
3309         def.name = code_genstring(code, component);
3310         vec_push(code->defs, def);
3311         def.offset++;
3312         component[len-1]++;
3313     }
3314
3315     mem_d(component);
3316 }
3317
3318 static void gen_vector_fields(code_t *code, prog_section_field fld, const char *name)
3319 {
3320     char  *component;
3321     size_t len, i;
3322
3323     if (!name || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3324         return;
3325
3326     fld.type = TYPE_FLOAT;
3327
3328     len = strlen(name);
3329
3330     component = (char*)mem_a(len+3);
3331     memcpy(component, name, len);
3332     len += 2;
3333     component[len-0] = 0;
3334     component[len-2] = '_';
3335
3336     component[len-1] = 'x';
3337
3338     for (i = 0; i < 3; ++i) {
3339         fld.name = code_genstring(code, component);
3340         vec_push(code->fields, fld);
3341         fld.offset++;
3342         component[len-1]++;
3343     }
3344
3345     mem_d(component);
3346 }
3347
3348 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
3349 {
3350     size_t           i;
3351     int32_t         *iptr;
3352     prog_section_def def;
3353     bool             pushdef = opts.optimizeoff;
3354
3355     def.type   = global->vtype;
3356     def.offset = vec_size(self->code->globals);
3357     def.name   = 0;
3358     if (OPTS_OPTION_BOOL(OPTION_G) || !islocal)
3359     {
3360         pushdef = true;
3361
3362         if (OPTS_OPTIMIZATION(OPTIM_STRIP_CONSTANT_NAMES) &&
3363             !(global->flags & IR_FLAG_INCLUDE_DEF) &&
3364             (global->name[0] == '#' || global->cvq == CV_CONST))
3365         {
3366             pushdef = false;
3367         }
3368
3369         if (pushdef && global->name) {
3370             if (global->name[0] == '#') {
3371                 if (!self->str_immediate)
3372                     self->str_immediate = code_genstring(self->code, "IMMEDIATE");
3373                 def.name = global->code.name = self->str_immediate;
3374             }
3375             else
3376                 def.name = global->code.name = code_genstring(self->code, global->name);
3377         }
3378         else
3379             def.name   = 0;
3380         if (islocal) {
3381             def.offset = ir_value_code_addr(global);
3382             vec_push(self->code->defs, def);
3383             if (global->vtype == TYPE_VECTOR)
3384                 gen_vector_defs(self->code, def, global->name);
3385             else if (global->vtype == TYPE_FIELD && global->fieldtype == TYPE_VECTOR)
3386                 gen_vector_defs(self->code, def, global->name);
3387             return true;
3388         }
3389     }
3390     if (islocal)
3391         return true;
3392
3393     switch (global->vtype)
3394     {
3395     case TYPE_VOID:
3396         if (!strcmp(global->name, "end_sys_globals")) {
3397             /* TODO: remember this point... all the defs before this one
3398              * should be checksummed and added to progdefs.h when we generate it.
3399              */
3400         }
3401         else if (!strcmp(global->name, "end_sys_fields")) {
3402             /* TODO: same as above but for entity-fields rather than globsl
3403              */
3404         }
3405         else
3406             irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3407                       global->name);
3408         /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3409          * the system fields actually go? Though the engine knows this anyway...
3410          * Maybe this could be an -foption
3411          * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3412          */
3413         ir_value_code_setaddr(global, vec_size(self->code->globals));
3414         vec_push(self->code->globals, 0);
3415         /* Add the def */
3416         if (pushdef) vec_push(self->code->defs, def);
3417         return true;
3418     case TYPE_POINTER:
3419         if (pushdef) vec_push(self->code->defs, def);
3420         return gen_global_pointer(self->code, global);
3421     case TYPE_FIELD:
3422         if (pushdef) {
3423             vec_push(self->code->defs, def);
3424             if (global->fieldtype == TYPE_VECTOR)
3425                 gen_vector_defs(self->code, def, global->name);
3426         }
3427         return gen_global_field(self->code, global);
3428     case TYPE_ENTITY:
3429         /* fall through */
3430     case TYPE_FLOAT:
3431     {
3432         ir_value_code_setaddr(global, vec_size(self->code->globals));
3433         if (global->hasvalue) {
3434             iptr = (int32_t*)&global->constval.ivec[0];
3435             vec_push(self->code->globals, *iptr);
3436         } else {
3437             vec_push(self->code->globals, 0);
3438         }
3439         if (!islocal && global->cvq != CV_CONST)
3440             def.type |= DEF_SAVEGLOBAL;
3441         if (pushdef) vec_push(self->code->defs, def);
3442
3443         return global->code.globaladdr >= 0;
3444     }
3445     case TYPE_STRING:
3446     {
3447         ir_value_code_setaddr(global, vec_size(self->code->globals));
3448         if (global->hasvalue) {
3449             uint32_t load = code_genstring(self->code, global->constval.vstring);
3450             vec_push(self->code->globals, load);
3451         } else {
3452             vec_push(self->code->globals, 0);
3453         }
3454         if (!islocal && global->cvq != CV_CONST)
3455             def.type |= DEF_SAVEGLOBAL;
3456         if (pushdef) vec_push(self->code->defs, def);
3457         return global->code.globaladdr >= 0;
3458     }
3459     case TYPE_VECTOR:
3460     {
3461         size_t d;
3462         ir_value_code_setaddr(global, vec_size(self->code->globals));
3463         if (global->hasvalue) {
3464             iptr = (int32_t*)&global->constval.ivec[0];
3465             vec_push(self->code->globals, iptr[0]);
3466             if (global->code.globaladdr < 0)
3467                 return false;
3468             for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3469                 vec_push(self->code->globals, iptr[d]);
3470             }
3471         } else {
3472             vec_push(self->code->globals, 0);
3473             if (global->code.globaladdr < 0)
3474                 return false;
3475             for (d = 1; d < type_sizeof_[global->vtype]; ++d) {
3476                 vec_push(self->code->globals, 0);
3477             }
3478         }
3479         if (!islocal && global->cvq != CV_CONST)
3480             def.type |= DEF_SAVEGLOBAL;
3481
3482         if (pushdef) {
3483             vec_push(self->code->defs, def);
3484             def.type &= ~DEF_SAVEGLOBAL;
3485             gen_vector_defs(self->code, def, global->name);
3486         }
3487         return global->code.globaladdr >= 0;
3488     }
3489     case TYPE_FUNCTION:
3490         ir_value_code_setaddr(global, vec_size(self->code->globals));
3491         if (!global->hasvalue) {
3492             vec_push(self->code->globals, 0);
3493             if (global->code.globaladdr < 0)
3494                 return false;
3495         } else {
3496             vec_push(self->code->globals, vec_size(self->code->functions));
3497             if (!gen_global_function(self, global))
3498                 return false;
3499         }
3500         if (!islocal && global->cvq != CV_CONST)
3501             def.type |= DEF_SAVEGLOBAL;
3502         if (pushdef) vec_push(self->code->defs, def);
3503         return true;
3504     case TYPE_VARIANT:
3505         /* assume biggest type */
3506             ir_value_code_setaddr(global, vec_size(self->code->globals));
3507             vec_push(self->code->globals, 0);
3508             for (i = 1; i < type_sizeof_[TYPE_VARIANT]; ++i)
3509                 vec_push(self->code->globals, 0);
3510             return true;
3511     default:
3512         /* refuse to create 'void' type or any other fancy business. */
3513         irerror(global->context, "Invalid type for global variable `%s`: %s",
3514                 global->name, type_name[global->vtype]);
3515         return false;
3516     }
3517 }
3518
3519 static GMQCC_INLINE void ir_builder_prepare_field(code_t *code, ir_value *field)
3520 {
3521     field->code.fieldaddr = code_alloc_field(code, type_sizeof_[field->fieldtype]);
3522 }
3523
3524 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3525 {
3526     prog_section_def def;
3527     prog_section_field fld;
3528
3529     (void)self;
3530
3531     def.type   = (uint16_t)field->vtype;
3532     def.offset = (uint16_t)vec_size(self->code->globals);
3533
3534     /* create a global named the same as the field */
3535     if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
3536         /* in our standard, the global gets a dot prefix */
3537         size_t len = strlen(field->name);
3538         char name[1024];
3539
3540         /* we really don't want to have to allocate this, and 1024
3541          * bytes is more than enough for a variable/field name
3542          */
3543         if (len+2 >= sizeof(name)) {
3544             irerror(field->context, "invalid field name size: %u", (unsigned int)len);
3545             return false;
3546         }
3547
3548         name[0] = '.';
3549         memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
3550         name[len+1] = 0;
3551
3552         def.name = code_genstring(self->code, name);
3553         fld.name = def.name + 1; /* we reuse that string table entry */
3554     } else {
3555         /* in plain QC, there cannot be a global with the same name,
3556          * and so we also name the global the same.
3557          * FIXME: fteqcc should create a global as well
3558          * check if it actually uses the same name. Probably does
3559          */
3560         def.name = code_genstring(self->code, field->name);
3561         fld.name = def.name;
3562     }
3563
3564     field->code.name = def.name;
3565
3566     vec_push(self->code->defs, def);
3567
3568     fld.type = field->fieldtype;
3569
3570     if (fld.type == TYPE_VOID) {
3571         irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
3572         return false;
3573     }
3574
3575     fld.offset = field->code.fieldaddr;
3576
3577     vec_push(self->code->fields, fld);
3578
3579     ir_value_code_setaddr(field, vec_size(self->code->globals));
3580     vec_push(self->code->globals, fld.offset);
3581     if (fld.type == TYPE_VECTOR) {
3582         vec_push(self->code->globals, fld.offset+1);
3583         vec_push(self->code->globals, fld.offset+2);
3584     }
3585
3586     if (field->fieldtype == TYPE_VECTOR) {
3587         gen_vector_defs  (self->code, def, field->name);
3588         gen_vector_fields(self->code, fld, field->name);
3589     }
3590
3591     return field->code.globaladdr >= 0;
3592 }
3593
3594 bool ir_builder_generate(ir_builder *self, const char *filename)
3595 {
3596     prog_section_statement stmt;
3597     size_t i;
3598     char  *lnofile = NULL;
3599
3600     for (i = 0; i < vec_size(self->fields); ++i)
3601     {
3602         ir_builder_prepare_field(self->code, self->fields[i]);
3603     }
3604
3605     for (i = 0; i < vec_size(self->globals); ++i)
3606     {
3607         if (!ir_builder_gen_global(self, self->globals[i], false)) {
3608             return false;
3609         }
3610         if (self->globals[i]->vtype == TYPE_FUNCTION) {
3611             ir_function *func = self->globals[i]->constval.vfunc;
3612             if (func && self->max_locals < func->allocated_locals &&
3613                 !(func->flags & IR_FLAG_MASK_NO_OVERLAP))
3614             {
3615                 self->max_locals = func->allocated_locals;
3616             }
3617             if (func && self->max_globaltemps < func->globaltemps)
3618                 self->max_globaltemps = func->globaltemps;
3619         }
3620     }
3621
3622     for (i = 0; i < vec_size(self->fields); ++i)
3623     {
3624         if (!ir_builder_gen_field(self, self->fields[i])) {
3625             return false;
3626         }
3627     }
3628
3629     /* generate nil */
3630     ir_value_code_setaddr(self->nil, vec_size(self->code->globals));
3631     vec_push(self->code->globals, 0);
3632     vec_push(self->code->globals, 0);
3633     vec_push(self->code->globals, 0);
3634
3635     /* generate global temps */
3636     self->first_common_globaltemp = vec_size(self->code->globals);
3637     for (i = 0; i < self->max_globaltemps; ++i) {
3638         vec_push(self->code->globals, 0);
3639     }
3640     /* generate common locals */
3641     self->first_common_local = vec_size(self->code->globals);
3642     for (i = 0; i < self->max_locals; ++i) {
3643         vec_push(self->code->globals, 0);
3644     }
3645
3646     /* generate function code */
3647     for (i = 0; i < vec_size(self->globals); ++i)
3648     {
3649         if (self->globals[i]->vtype == TYPE_FUNCTION) {
3650             if (!gen_global_function_code(self, self->globals[i])) {
3651                 return false;
3652             }
3653         }
3654     }
3655
3656     if (vec_size(self->code->globals) >= 65536) {
3657         irerror(vec_last(self->globals)->context, "This progs file would require more globals than the metadata can handle. Bailing out.");
3658         return false;
3659     }
3660
3661     /* DP errors if the last instruction is not an INSTR_DONE. */
3662     if (vec_last(self->code->statements).opcode != INSTR_DONE)
3663     {
3664         stmt.opcode = INSTR_DONE;
3665         stmt.o1.u1 = 0;
3666         stmt.o2.u1 = 0;
3667         stmt.o3.u1 = 0;
3668         code_push_statement(self->code, &stmt, vec_last(self->code->linenums));
3669     }
3670
3671     if (OPTS_OPTION_BOOL(OPTION_PP_ONLY))
3672         return true;
3673
3674     if (vec_size(self->code->statements) != vec_size(self->code->linenums)) {
3675         con_err("Linecounter wrong: %lu != %lu\n",
3676                 (unsigned long)vec_size(self->code->statements),
3677                 (unsigned long)vec_size(self->code->linenums));
3678     } else if (OPTS_FLAG(LNO)) {
3679         char  *dot;
3680         size_t filelen = strlen(filename);
3681
3682         memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
3683         dot = strrchr(lnofile, '.');
3684         if (!dot) {
3685             vec_pop(lnofile);
3686         } else {
3687             vec_shrinkto(lnofile, dot - lnofile);
3688         }
3689         memcpy(vec_add(lnofile, 5), ".lno", 5);
3690     }
3691
3692     if (!OPTS_OPTION_BOOL(OPTION_QUIET)) {
3693         if (lnofile)
3694             con_out("writing '%s' and '%s'...\n", filename, lnofile);
3695         else
3696             con_out("writing '%s'\n", filename);
3697     }
3698     if (!code_write(self->code, filename, lnofile)) {
3699         vec_free(lnofile);
3700         return false;
3701     }
3702     vec_free(lnofile);
3703     return true;
3704 }
3705
3706 /***********************************************************************
3707  *IR DEBUG Dump functions...
3708  */
3709
3710 #define IND_BUFSZ 1024
3711
3712 #ifdef _MSC_VER
3713 #   define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
3714 #endif
3715
3716 static const char *qc_opname(int op)
3717 {
3718     if (op < 0) return "<INVALID>";
3719     if (op < (int)( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
3720         return asm_instr[op].m;
3721     switch (op) {
3722         case VINSTR_PHI:  return "PHI";
3723         case VINSTR_JUMP: return "JUMP";
3724         case VINSTR_COND: return "COND";
3725         default:          return "<UNK>";
3726     }
3727 }
3728
3729 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
3730 {
3731     size_t i;
3732     char indent[IND_BUFSZ];
3733     indent[0] = '\t';
3734     indent[1] = 0;
3735
3736     oprintf("module %s\n", b->name);
3737     for (i = 0; i < vec_size(b->globals); ++i)
3738     {
3739         oprintf("global ");
3740         if (b->globals[i]->hasvalue)
3741             oprintf("%s = ", b->globals[i]->name);
3742         ir_value_dump(b->globals[i], oprintf);
3743         oprintf("\n");
3744     }
3745     for (i = 0; i < vec_size(b->functions); ++i)
3746         ir_function_dump(b->functions[i], indent, oprintf);
3747     oprintf("endmodule %s\n", b->name);
3748 }
3749
3750 static const char *storenames[] = {
3751     "[global]", "[local]", "[param]", "[value]", "[return]"
3752 };
3753
3754 void ir_function_dump(ir_function *f, char *ind,
3755                       int (*oprintf)(const char*, ...))
3756 {
3757     size_t i;
3758     if (f->builtin != 0) {
3759         oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
3760         return;
3761     }
3762     oprintf("%sfunction %s\n", ind, f->name);
3763     strncat(ind, "\t", IND_BUFSZ);
3764     if (vec_size(f->locals))
3765     {
3766         oprintf("%s%i locals:\n", ind, (int)vec_size(f->locals));
3767         for (i = 0; i < vec_size(f->locals); ++i) {
3768             oprintf("%s\t", ind);
3769             ir_value_dump(f->locals[i], oprintf);
3770             oprintf("\n");
3771         }
3772     }
3773     oprintf("%sliferanges:\n", ind);
3774     for (i = 0; i < vec_size(f->locals); ++i) {
3775         const char *attr = "";
3776         size_t l, m;
3777         ir_value *v = f->locals[i];
3778         if (v->unique_life && v->locked)
3779             attr = "unique,locked ";
3780         else if (v->unique_life)
3781             attr = "unique ";
3782         else if (v->locked)
3783             attr = "locked ";
3784         oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
3785                 storenames[v->store],
3786                 attr, (v->callparam ? "callparam " : ""),
3787                 (int)v->code.local);
3788         if (!v->life)
3789             oprintf("[null]");
3790         for (l = 0; l < vec_size(v->life); ++l) {
3791             oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3792         }
3793         oprintf("\n");
3794         for (m = 0; m < 3; ++m) {
3795             ir_value *vm = v->members[m];
3796             if (!vm)
3797                 continue;
3798             oprintf("%s\t%s: @%i ", ind, vm->name, (int)vm->code.local);
3799             for (l = 0; l < vec_size(vm->life); ++l) {
3800                 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
3801             }
3802             oprintf("\n");
3803         }
3804     }
3805     for (i = 0; i < vec_size(f->values); ++i) {
3806         const char *attr = "";
3807         size_t l, m;
3808         ir_value *v = f->values[i];
3809         if (v->unique_life && v->locked)
3810             attr = "unique,locked ";
3811         else if (v->unique_life)
3812             attr = "unique ";
3813         else if (v->locked)
3814             attr = "locked ";
3815         oprintf("%s\t%s: %s %s %s%s@%i ", ind, v->name, type_name[v->vtype],
3816                 storenames[v->store],
3817                 attr, (v->callparam ? "callparam " : ""),
3818                 (int)v->code.local);
3819         if (!v->life)
3820             oprintf("[null]");
3821         for (l = 0; l < vec_size(v->life); ++l) {
3822             oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3823         }
3824         oprintf("\n");
3825         for (m = 0; m < 3; ++m) {
3826             ir_value *vm = v->members[m];
3827             if (!vm)
3828                 continue;
3829             if (vm->unique_life && vm->locked)
3830                 attr = "unique,locked ";
3831             else if (vm->unique_life)
3832                 attr = "unique ";
3833             else if (vm->locked)
3834                 attr = "locked ";
3835             oprintf("%s\t%s: %s@%i ", ind, vm->name, attr, (int)vm->code.local);
3836             for (l = 0; l < vec_size(vm->life); ++l) {
3837                 oprintf("[%i,%i] ", vm->life[l].start, vm->life[l].end);
3838             }
3839             oprintf("\n");
3840         }
3841     }
3842     if (vec_size(f->blocks))
3843     {
3844         oprintf("%slife passes: %i\n", ind, (int)f->run_id);
3845         for (i = 0; i < vec_size(f->blocks); ++i) {
3846             ir_block_dump(f->blocks[i], ind, oprintf);
3847         }
3848
3849     }
3850     ind[strlen(ind)-1] = 0;
3851     oprintf("%sendfunction %s\n", ind, f->name);
3852 }
3853
3854 void ir_block_dump(ir_block* b, char *ind,
3855                    int (*oprintf)(const char*, ...))
3856 {
3857     size_t i;
3858     oprintf("%s:%s\n", ind, b->label);
3859     strncat(ind, "\t", IND_BUFSZ);
3860
3861     if (b->instr && b->instr[0])
3862         oprintf("%s (%i) [entry]\n", ind, (int)(b->instr[0]->eid-1));
3863     for (i = 0; i < vec_size(b->instr); ++i)
3864         ir_instr_dump(b->instr[i], ind, oprintf);
3865     ind[strlen(ind)-1] = 0;
3866 }
3867
3868 static void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
3869 {
3870     size_t i;
3871     oprintf("%s <- phi ", in->_ops[0]->name);
3872     for (i = 0; i < vec_size(in->phi); ++i)
3873     {
3874         oprintf("([%s] : %s) ", in->phi[i].from->label,
3875                                 in->phi[i].value->name);
3876     }
3877     oprintf("\n");
3878 }
3879
3880 void ir_instr_dump(ir_instr *in, char *ind,
3881                        int (*oprintf)(const char*, ...))
3882 {
3883     size_t i;
3884     const char *comma = NULL;
3885
3886     oprintf("%s (%i) ", ind, (int)in->eid);
3887
3888     if (in->opcode == VINSTR_PHI) {
3889         dump_phi(in, oprintf);
3890         return;
3891     }
3892
3893     strncat(ind, "\t", IND_BUFSZ);
3894
3895     if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3896         ir_value_dump(in->_ops[0], oprintf);
3897         if (in->_ops[1] || in->_ops[2])
3898             oprintf(" <- ");
3899     }
3900     if (in->opcode == INSTR_CALL0 || in->opcode == VINSTR_NRCALL) {
3901         oprintf("CALL%i\t", vec_size(in->params));
3902     } else
3903         oprintf("%s\t", qc_opname(in->opcode));
3904
3905     if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3906         ir_value_dump(in->_ops[0], oprintf);
3907         comma = ",\t";
3908     }
3909     else
3910     {
3911         for (i = 1; i != 3; ++i) {
3912             if (in->_ops[i]) {
3913                 if (comma)
3914                     oprintf(comma);
3915                 ir_value_dump(in->_ops[i], oprintf);
3916                 comma = ",\t";
3917             }
3918         }
3919     }
3920     if (in->bops[0]) {
3921         if (comma)
3922             oprintf(comma);
3923         oprintf("[%s]", in->bops[0]->label);
3924         comma = ",\t";
3925     }
3926     if (in->bops[1])
3927         oprintf("%s[%s]", comma, in->bops[1]->label);
3928     if (vec_size(in->params)) {
3929         oprintf("\tparams: ");
3930         for (i = 0; i != vec_size(in->params); ++i) {
3931             oprintf("%s, ", in->params[i]->name);
3932         }
3933     }
3934     oprintf("\n");
3935     ind[strlen(ind)-1] = 0;
3936 }
3937
3938 static void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
3939 {
3940     oprintf("\"");
3941     for (; *str; ++str) {
3942         switch (*str) {
3943             case '\n': oprintf("\\n"); break;
3944             case '\r': oprintf("\\r"); break;
3945             case '\t': oprintf("\\t"); break;
3946             case '\v': oprintf("\\v"); break;
3947             case '\f': oprintf("\\f"); break;
3948             case '\b': oprintf("\\b"); break;
3949             case '\a': oprintf("\\a"); break;
3950             case '\\': oprintf("\\\\"); break;
3951             case '"': oprintf("\\\""); break;
3952             default: oprintf("%c", *str); break;
3953         }
3954     }
3955     oprintf("\"");
3956 }
3957
3958 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3959 {
3960     if (v->hasvalue) {
3961         switch (v->vtype) {
3962             default:
3963             case TYPE_VOID:
3964                 oprintf("(void)");
3965                 break;
3966             case TYPE_FUNCTION:
3967                 oprintf("fn:%s", v->name);
3968                 break;
3969             case TYPE_FLOAT:
3970                 oprintf("%g", v->constval.vfloat);
3971                 break;
3972             case TYPE_VECTOR:
3973                 oprintf("'%g %g %g'",
3974                         v->constval.vvec.x,
3975                         v->constval.vvec.y,
3976                         v->constval.vvec.z);
3977                 break;
3978             case TYPE_ENTITY:
3979                 oprintf("(entity)");
3980                 break;
3981             case TYPE_STRING:
3982                 ir_value_dump_string(v->constval.vstring, oprintf);
3983                 break;
3984 #if 0
3985             case TYPE_INTEGER:
3986                 oprintf("%i", v->constval.vint);
3987                 break;
3988 #endif
3989             case TYPE_POINTER:
3990                 oprintf("&%s",
3991                     v->constval.vpointer->name);
3992                 break;
3993         }
3994     } else {
3995         oprintf("%s", v->name);
3996     }
3997 }
3998
3999 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
4000 {
4001     size_t i;
4002     oprintf("Life of %12s:", self->name);
4003     for (i = 0; i < vec_size(self->life); ++i)
4004     {
4005         oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);
4006     }
4007 }