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