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