]> de.git.xonotic.org Git - xonotic/gmqcc.git/blob - ir.c
More jump removal
[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     ir_value *m;
992     if (member >= 3)
993         return NULL;
994
995     if (self->members[member])
996         return self->members[member];
997
998     if (self->vtype == TYPE_VECTOR)
999     {
1000         m = ir_value_var(self->name, self->store, TYPE_FLOAT);
1001         if (!m)
1002             return NULL;
1003         m->context = self->context;
1004
1005         self->members[member] = m;
1006         m->code.addroffset = member;
1007     }
1008     else if (self->vtype == TYPE_FIELD)
1009     {
1010         if (self->fieldtype != TYPE_VECTOR)
1011             return NULL;
1012         m = ir_value_var(self->name, self->store, TYPE_FIELD);
1013         if (!m)
1014             return NULL;
1015         m->fieldtype = TYPE_FLOAT;
1016         m->context = self->context;
1017
1018         self->members[member] = m;
1019         m->code.addroffset = member;
1020     }
1021     else
1022     {
1023         irerror(self->context, "invalid member access on %s", self->name);
1024         return NULL;
1025     }
1026
1027     m->memberof = self;
1028     return m;
1029 }
1030
1031 ir_value* ir_value_out(ir_function *owner, const char *name, int storetype, int vtype)
1032 {
1033     ir_value *v = ir_value_var(name, storetype, vtype);
1034     if (!v)
1035         return NULL;
1036     ir_function_collect_value(owner, v);
1037     return v;
1038 }
1039
1040 void ir_value_delete(ir_value* self)
1041 {
1042     size_t i;
1043     if (self->name)
1044         mem_d((void*)self->name);
1045     if (self->hasvalue)
1046     {
1047         if (self->vtype == TYPE_STRING)
1048             mem_d((void*)self->constval.vstring);
1049     }
1050     for (i = 0; i < 3; ++i) {
1051         if (self->members[i])
1052             ir_value_delete(self->members[i]);
1053     }
1054     vec_free(self->reads);
1055     vec_free(self->writes);
1056     vec_free(self->life);
1057     mem_d(self);
1058 }
1059
1060 bool ir_value_set_name(ir_value *self, const char *name)
1061 {
1062     if (self->name)
1063         mem_d((void*)self->name);
1064     self->name = util_strdup(name);
1065     return !!self->name;
1066 }
1067
1068 bool ir_value_set_float(ir_value *self, float f)
1069 {
1070     if (self->vtype != TYPE_FLOAT)
1071         return false;
1072     self->constval.vfloat = f;
1073     self->hasvalue = true;
1074     return true;
1075 }
1076
1077 bool ir_value_set_func(ir_value *self, int f)
1078 {
1079     if (self->vtype != TYPE_FUNCTION)
1080         return false;
1081     self->constval.vint = f;
1082     self->hasvalue = true;
1083     return true;
1084 }
1085
1086 bool ir_value_set_vector(ir_value *self, vector v)
1087 {
1088     if (self->vtype != TYPE_VECTOR)
1089         return false;
1090     self->constval.vvec = v;
1091     self->hasvalue = true;
1092     return true;
1093 }
1094
1095 bool ir_value_set_field(ir_value *self, ir_value *fld)
1096 {
1097     if (self->vtype != TYPE_FIELD)
1098         return false;
1099     self->constval.vpointer = fld;
1100     self->hasvalue = true;
1101     return true;
1102 }
1103
1104 static char *ir_strdup(const char *str)
1105 {
1106     if (str && !*str) {
1107         /* actually dup empty strings */
1108         char *out = mem_a(1);
1109         *out = 0;
1110         return out;
1111     }
1112     return util_strdup(str);
1113 }
1114
1115 bool ir_value_set_string(ir_value *self, const char *str)
1116 {
1117     if (self->vtype != TYPE_STRING)
1118         return false;
1119     self->constval.vstring = ir_strdup(str);
1120     self->hasvalue = true;
1121     return true;
1122 }
1123
1124 #if 0
1125 bool ir_value_set_int(ir_value *self, int i)
1126 {
1127     if (self->vtype != TYPE_INTEGER)
1128         return false;
1129     self->constval.vint = i;
1130     self->hasvalue = true;
1131     return true;
1132 }
1133 #endif
1134
1135 bool ir_value_lives(ir_value *self, size_t at)
1136 {
1137     size_t i;
1138     for (i = 0; i < vec_size(self->life); ++i)
1139     {
1140         ir_life_entry_t *life = &self->life[i];
1141         if (life->start <= at && at <= life->end)
1142             return true;
1143         if (life->start > at) /* since it's ordered */
1144             return false;
1145     }
1146     return false;
1147 }
1148
1149 bool ir_value_life_insert(ir_value *self, size_t idx, ir_life_entry_t e)
1150 {
1151     size_t k;
1152     vec_push(self->life, e);
1153     for (k = vec_size(self->life)-1; k > idx; --k)
1154         self->life[k] = self->life[k-1];
1155     self->life[idx] = e;
1156     return true;
1157 }
1158
1159 bool ir_value_life_merge(ir_value *self, size_t s)
1160 {
1161     size_t i;
1162     ir_life_entry_t *life = NULL;
1163     ir_life_entry_t *before = NULL;
1164     ir_life_entry_t new_entry;
1165
1166     /* Find the first range >= s */
1167     for (i = 0; i < vec_size(self->life); ++i)
1168     {
1169         before = life;
1170         life = &self->life[i];
1171         if (life->start > s)
1172             break;
1173     }
1174     /* nothing found? append */
1175     if (i == vec_size(self->life)) {
1176         ir_life_entry_t e;
1177         if (life && life->end+1 == s)
1178         {
1179             /* previous life range can be merged in */
1180             life->end++;
1181             return true;
1182         }
1183         if (life && life->end >= s)
1184             return false;
1185         e.start = e.end = s;
1186         vec_push(self->life, e);
1187         return true;
1188     }
1189     /* found */
1190     if (before)
1191     {
1192         if (before->end + 1 == s &&
1193             life->start - 1 == s)
1194         {
1195             /* merge */
1196             before->end = life->end;
1197             vec_remove(self->life, i, 1);
1198             return true;
1199         }
1200         if (before->end + 1 == s)
1201         {
1202             /* extend before */
1203             before->end++;
1204             return true;
1205         }
1206         /* already contained */
1207         if (before->end >= s)
1208             return false;
1209     }
1210     /* extend */
1211     if (life->start - 1 == s)
1212     {
1213         life->start--;
1214         return true;
1215     }
1216     /* insert a new entry */
1217     new_entry.start = new_entry.end = s;
1218     return ir_value_life_insert(self, i, new_entry);
1219 }
1220
1221 bool ir_value_life_merge_into(ir_value *self, const ir_value *other)
1222 {
1223     size_t i, myi;
1224
1225     if (!vec_size(other->life))
1226         return true;
1227
1228     if (!vec_size(self->life)) {
1229         size_t count = vec_size(other->life);
1230         ir_life_entry_t *life = vec_add(self->life, count);
1231         memcpy(life, other->life, count * sizeof(*life));
1232         return true;
1233     }
1234
1235     myi = 0;
1236     for (i = 0; i < vec_size(other->life); ++i)
1237     {
1238         const ir_life_entry_t *life = &other->life[i];
1239         while (true)
1240         {
1241             ir_life_entry_t *entry = &self->life[myi];
1242
1243             if (life->end+1 < entry->start)
1244             {
1245                 /* adding an interval before entry */
1246                 if (!ir_value_life_insert(self, myi, *life))
1247                     return false;
1248                 ++myi;
1249                 break;
1250             }
1251
1252             if (life->start <  entry->start &&
1253                 life->end+1 >= entry->start)
1254             {
1255                 /* starts earlier and overlaps */
1256                 entry->start = life->start;
1257             }
1258
1259             if (life->end   >  entry->end &&
1260                 life->start <= entry->end+1)
1261             {
1262                 /* ends later and overlaps */
1263                 entry->end = life->end;
1264             }
1265
1266             /* see if our change combines it with the next ranges */
1267             while (myi+1 < vec_size(self->life) &&
1268                    entry->end+1 >= self->life[1+myi].start)
1269             {
1270                 /* overlaps with (myi+1) */
1271                 if (entry->end < self->life[1+myi].end)
1272                     entry->end = self->life[1+myi].end;
1273                 vec_remove(self->life, myi+1, 1);
1274                 entry = &self->life[myi];
1275             }
1276
1277             /* see if we're after the entry */
1278             if (life->start > entry->end)
1279             {
1280                 ++myi;
1281                 /* append if we're at the end */
1282                 if (myi >= vec_size(self->life)) {
1283                     vec_push(self->life, *life);
1284                     break;
1285                 }
1286                 /* otherweise check the next range */
1287                 continue;
1288             }
1289             break;
1290         }
1291     }
1292     return true;
1293 }
1294
1295 bool ir_values_overlap(const ir_value *a, const ir_value *b)
1296 {
1297     /* For any life entry in A see if it overlaps with
1298      * any life entry in B.
1299      * Note that the life entries are orderes, so we can make a
1300      * more efficient algorithm there than naively translating the
1301      * statement above.
1302      */
1303
1304     ir_life_entry_t *la, *lb, *enda, *endb;
1305
1306     /* first of all, if either has no life range, they cannot clash */
1307     if (!vec_size(a->life) || !vec_size(b->life))
1308         return false;
1309
1310     la = a->life;
1311     lb = b->life;
1312     enda = la + vec_size(a->life);
1313     endb = lb + vec_size(b->life);
1314     while (true)
1315     {
1316         /* check if the entries overlap, for that,
1317          * both must start before the other one ends.
1318          */
1319         if (la->start < lb->end &&
1320             lb->start < la->end)
1321         {
1322             return true;
1323         }
1324
1325         /* entries are ordered
1326          * one entry is earlier than the other
1327          * that earlier entry will be moved forward
1328          */
1329         if (la->start < lb->start)
1330         {
1331             /* order: A B, move A forward
1332              * check if we hit the end with A
1333              */
1334             if (++la == enda)
1335                 break;
1336         }
1337         else /* if (lb->start < la->start)  actually <= */
1338         {
1339             /* order: B A, move B forward
1340              * check if we hit the end with B
1341              */
1342             if (++lb == endb)
1343                 break;
1344         }
1345     }
1346     return false;
1347 }
1348
1349 /***********************************************************************
1350  *IR main operations
1351  */
1352
1353 bool ir_block_create_store_op(ir_block *self, lex_ctx ctx, int op, ir_value *target, ir_value *what)
1354 {
1355     ir_instr *in;
1356     if (self->final) {
1357         irerror(self->context, "unreachable statement (%s)", self->label);
1358         return false;
1359     }
1360     in = ir_instr_new(ctx, self, op);
1361     if (!in)
1362         return false;
1363
1364     if (target->store == store_value &&
1365         (op < INSTR_STOREP_F || op > INSTR_STOREP_FNC))
1366     {
1367         irerror(self->context, "cannot store to an SSA value");
1368         irerror(self->context, "trying to store: %s <- %s", target->name, what->name);
1369         irerror(self->context, "instruction: %s", asm_instr[op].m);
1370         return false;
1371     }
1372
1373     if (!ir_instr_op(in, 0, target, true) ||
1374         !ir_instr_op(in, 1, what, false))
1375     {
1376         return false;
1377     }
1378     vec_push(self->instr, in);
1379     return true;
1380 }
1381
1382 bool ir_block_create_store(ir_block *self, lex_ctx ctx, ir_value *target, ir_value *what)
1383 {
1384     int op = 0;
1385     int vtype;
1386     if (target->vtype == TYPE_VARIANT)
1387         vtype = what->vtype;
1388     else
1389         vtype = target->vtype;
1390
1391 #if 0
1392     if      (vtype == TYPE_FLOAT   && what->vtype == TYPE_INTEGER)
1393         op = INSTR_CONV_ITOF;
1394     else if (vtype == TYPE_INTEGER && what->vtype == TYPE_FLOAT)
1395         op = INSTR_CONV_FTOI;
1396 #endif
1397         op = type_store_instr[vtype];
1398
1399     if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1400         if (op == INSTR_STORE_FLD && what->fieldtype == TYPE_VECTOR)
1401             op = INSTR_STORE_V;
1402     }
1403
1404     return ir_block_create_store_op(self, ctx, op, target, what);
1405 }
1406
1407 bool ir_block_create_storep(ir_block *self, lex_ctx ctx, ir_value *target, ir_value *what)
1408 {
1409     int op = 0;
1410     int vtype;
1411
1412     if (target->vtype != TYPE_POINTER)
1413         return false;
1414
1415     /* storing using pointer - target is a pointer, type must be
1416      * inferred from source
1417      */
1418     vtype = what->vtype;
1419
1420     op = type_storep_instr[vtype];
1421     if (OPTS_FLAG(ADJUST_VECTOR_FIELDS)) {
1422         if (op == INSTR_STOREP_FLD && what->fieldtype == TYPE_VECTOR)
1423             op = INSTR_STOREP_V;
1424     }
1425
1426     return ir_block_create_store_op(self, ctx, op, target, what);
1427 }
1428
1429 bool ir_block_create_return(ir_block *self, lex_ctx ctx, ir_value *v)
1430 {
1431     ir_instr *in;
1432     if (self->final) {
1433         irerror(self->context, "unreachable statement (%s)", self->label);
1434         return false;
1435     }
1436     self->final = true;
1437     self->is_return = true;
1438     in = ir_instr_new(ctx, self, INSTR_RETURN);
1439     if (!in)
1440         return false;
1441
1442     if (v && !ir_instr_op(in, 0, v, false))
1443         return false;
1444
1445     vec_push(self->instr, in);
1446     return true;
1447 }
1448
1449 bool ir_block_create_if(ir_block *self, lex_ctx ctx, ir_value *v,
1450                         ir_block *ontrue, ir_block *onfalse)
1451 {
1452     ir_instr *in;
1453     if (self->final) {
1454         irerror(self->context, "unreachable statement (%s)", self->label);
1455         return false;
1456     }
1457     self->final = true;
1458     /*in = ir_instr_new(ctx, self, (v->vtype == TYPE_STRING ? INSTR_IF_S : INSTR_IF_F));*/
1459     in = ir_instr_new(ctx, self, VINSTR_COND);
1460     if (!in)
1461         return false;
1462
1463     if (!ir_instr_op(in, 0, v, false)) {
1464         ir_instr_delete(in);
1465         return false;
1466     }
1467
1468     in->bops[0] = ontrue;
1469     in->bops[1] = onfalse;
1470
1471     vec_push(self->instr, in);
1472
1473     vec_push(self->exits, ontrue);
1474     vec_push(self->exits, onfalse);
1475     vec_push(ontrue->entries,  self);
1476     vec_push(onfalse->entries, self);
1477     return true;
1478 }
1479
1480 bool ir_block_create_jump(ir_block *self, lex_ctx ctx, ir_block *to)
1481 {
1482     ir_instr *in;
1483     if (self->final) {
1484         irerror(self->context, "unreachable statement (%s)", self->label);
1485         return false;
1486     }
1487     self->final = true;
1488     in = ir_instr_new(ctx, self, VINSTR_JUMP);
1489     if (!in)
1490         return false;
1491
1492     in->bops[0] = to;
1493     vec_push(self->instr, in);
1494
1495     vec_push(self->exits, to);
1496     vec_push(to->entries, self);
1497     return true;
1498 }
1499
1500 bool ir_block_create_goto(ir_block *self, lex_ctx ctx, ir_block *to)
1501 {
1502     ir_instr *in;
1503     if (self->final) {
1504         irerror(self->context, "unreachable statement (%s)", self->label);
1505         return false;
1506     }
1507     self->final = true;
1508     in = ir_instr_new(ctx, self, INSTR_GOTO);
1509     if (!in)
1510         return false;
1511
1512     in->bops[0] = to;
1513     vec_push(self->instr, in);
1514
1515     vec_push(self->exits, to);
1516     vec_push(to->entries, self);
1517     return true;
1518 }
1519
1520 ir_instr* ir_block_create_phi(ir_block *self, lex_ctx ctx, const char *label, int ot)
1521 {
1522     ir_value *out;
1523     ir_instr *in;
1524     in = ir_instr_new(ctx, self, VINSTR_PHI);
1525     if (!in)
1526         return NULL;
1527     out = ir_value_out(self->owner, label, store_value, ot);
1528     if (!out) {
1529         ir_instr_delete(in);
1530         return NULL;
1531     }
1532     if (!ir_instr_op(in, 0, out, true)) {
1533         ir_instr_delete(in);
1534         ir_value_delete(out);
1535         return NULL;
1536     }
1537     vec_push(self->instr, in);
1538     return in;
1539 }
1540
1541 ir_value* ir_phi_value(ir_instr *self)
1542 {
1543     return self->_ops[0];
1544 }
1545
1546 void ir_phi_add(ir_instr* self, ir_block *b, ir_value *v)
1547 {
1548     ir_phi_entry_t pe;
1549
1550     if (!vec_ir_block_find(self->owner->entries, b, NULL)) {
1551         /* Must not be possible to cause this, otherwise the AST
1552          * is doing something wrong.
1553          */
1554         irerror(self->context, "Invalid entry block for PHI");
1555         abort();
1556     }
1557
1558     pe.value = v;
1559     pe.from = b;
1560     vec_push(v->reads, self);
1561     vec_push(self->phi, pe);
1562 }
1563
1564 /* call related code */
1565 ir_instr* ir_block_create_call(ir_block *self, lex_ctx ctx, const char *label, ir_value *func)
1566 {
1567     ir_value *out;
1568     ir_instr *in;
1569     in = ir_instr_new(ctx, self, INSTR_CALL0);
1570     if (!in)
1571         return NULL;
1572     out = ir_value_out(self->owner, label, (func->outtype == TYPE_VOID) ? store_return : store_value, func->outtype);
1573     if (!out) {
1574         ir_instr_delete(in);
1575         return NULL;
1576     }
1577     if (!ir_instr_op(in, 0, out, true) ||
1578         !ir_instr_op(in, 1, func, false))
1579     {
1580         ir_instr_delete(in);
1581         ir_value_delete(out);
1582         return NULL;
1583     }
1584     vec_push(self->instr, in);
1585     return in;
1586 }
1587
1588 ir_value* ir_call_value(ir_instr *self)
1589 {
1590     return self->_ops[0];
1591 }
1592
1593 void ir_call_param(ir_instr* self, ir_value *v)
1594 {
1595     vec_push(self->params, v);
1596     vec_push(v->reads, self);
1597 }
1598
1599 /* binary op related code */
1600
1601 ir_value* ir_block_create_binop(ir_block *self, lex_ctx ctx,
1602                                 const char *label, int opcode,
1603                                 ir_value *left, ir_value *right)
1604 {
1605     int ot = TYPE_VOID;
1606     switch (opcode) {
1607         case INSTR_ADD_F:
1608         case INSTR_SUB_F:
1609         case INSTR_DIV_F:
1610         case INSTR_MUL_F:
1611         case INSTR_MUL_V:
1612         case INSTR_AND:
1613         case INSTR_OR:
1614 #if 0
1615         case INSTR_AND_I:
1616         case INSTR_AND_IF:
1617         case INSTR_AND_FI:
1618         case INSTR_OR_I:
1619         case INSTR_OR_IF:
1620         case INSTR_OR_FI:
1621 #endif
1622         case INSTR_BITAND:
1623         case INSTR_BITOR:
1624 #if 0
1625         case INSTR_SUB_S: /* -- offset of string as float */
1626         case INSTR_MUL_IF:
1627         case INSTR_MUL_FI:
1628         case INSTR_DIV_IF:
1629         case INSTR_DIV_FI:
1630         case INSTR_BITOR_IF:
1631         case INSTR_BITOR_FI:
1632         case INSTR_BITAND_FI:
1633         case INSTR_BITAND_IF:
1634         case INSTR_EQ_I:
1635         case INSTR_NE_I:
1636 #endif
1637             ot = TYPE_FLOAT;
1638             break;
1639 #if 0
1640         case INSTR_ADD_I:
1641         case INSTR_ADD_IF:
1642         case INSTR_ADD_FI:
1643         case INSTR_SUB_I:
1644         case INSTR_SUB_FI:
1645         case INSTR_SUB_IF:
1646         case INSTR_MUL_I:
1647         case INSTR_DIV_I:
1648         case INSTR_BITAND_I:
1649         case INSTR_BITOR_I:
1650         case INSTR_XOR_I:
1651         case INSTR_RSHIFT_I:
1652         case INSTR_LSHIFT_I:
1653             ot = TYPE_INTEGER;
1654             break;
1655 #endif
1656         case INSTR_ADD_V:
1657         case INSTR_SUB_V:
1658         case INSTR_MUL_VF:
1659         case INSTR_MUL_FV:
1660 #if 0
1661         case INSTR_DIV_VF:
1662         case INSTR_MUL_IV:
1663         case INSTR_MUL_VI:
1664 #endif
1665             ot = TYPE_VECTOR;
1666             break;
1667 #if 0
1668         case INSTR_ADD_SF:
1669             ot = TYPE_POINTER;
1670             break;
1671 #endif
1672         default:
1673             /* ranges: */
1674             /* boolean operations result in floats */
1675             if (opcode >= INSTR_EQ_F && opcode <= INSTR_GT)
1676                 ot = TYPE_FLOAT;
1677             else if (opcode >= INSTR_LE && opcode <= INSTR_GT)
1678                 ot = TYPE_FLOAT;
1679 #if 0
1680             else if (opcode >= INSTR_LE_I && opcode <= INSTR_EQ_FI)
1681                 ot = TYPE_FLOAT;
1682 #endif
1683             break;
1684     };
1685     if (ot == TYPE_VOID) {
1686         /* The AST or parser were supposed to check this! */
1687         return NULL;
1688     }
1689
1690     return ir_block_create_general_instr(self, ctx, label, opcode, left, right, ot);
1691 }
1692
1693 ir_value* ir_block_create_unary(ir_block *self, lex_ctx ctx,
1694                                 const char *label, int opcode,
1695                                 ir_value *operand)
1696 {
1697     int ot = TYPE_FLOAT;
1698     switch (opcode) {
1699         case INSTR_NOT_F:
1700         case INSTR_NOT_V:
1701         case INSTR_NOT_S:
1702         case INSTR_NOT_ENT:
1703         case INSTR_NOT_FNC:
1704 #if 0
1705         case INSTR_NOT_I:
1706 #endif
1707             ot = TYPE_FLOAT;
1708             break;
1709         /* QC doesn't have other unary operations. We expect extensions to fill
1710          * the above list, otherwise we assume out-type = in-type, eg for an
1711          * unary minus
1712          */
1713         default:
1714             ot = operand->vtype;
1715             break;
1716     };
1717     if (ot == TYPE_VOID) {
1718         /* The AST or parser were supposed to check this! */
1719         return NULL;
1720     }
1721
1722     /* let's use the general instruction creator and pass NULL for OPB */
1723     return ir_block_create_general_instr(self, ctx, label, opcode, operand, NULL, ot);
1724 }
1725
1726 ir_value* ir_block_create_general_instr(ir_block *self, lex_ctx ctx, const char *label,
1727                                         int op, ir_value *a, ir_value *b, int outype)
1728 {
1729     ir_instr *instr;
1730     ir_value *out;
1731
1732     out = ir_value_out(self->owner, label, store_value, outype);
1733     if (!out)
1734         return NULL;
1735
1736     instr = ir_instr_new(ctx, self, op);
1737     if (!instr) {
1738         ir_value_delete(out);
1739         return NULL;
1740     }
1741
1742     if (!ir_instr_op(instr, 0, out, true) ||
1743         !ir_instr_op(instr, 1, a, false) ||
1744         !ir_instr_op(instr, 2, b, false) )
1745     {
1746         goto on_error;
1747     }
1748
1749     vec_push(self->instr, instr);
1750
1751     return out;
1752 on_error:
1753     ir_instr_delete(instr);
1754     ir_value_delete(out);
1755     return NULL;
1756 }
1757
1758 ir_value* ir_block_create_fieldaddress(ir_block *self, lex_ctx ctx, const char *label, ir_value *ent, ir_value *field)
1759 {
1760     ir_value *v;
1761
1762     /* Support for various pointer types todo if so desired */
1763     if (ent->vtype != TYPE_ENTITY)
1764         return NULL;
1765
1766     if (field->vtype != TYPE_FIELD)
1767         return NULL;
1768
1769     v = ir_block_create_general_instr(self, ctx, label, INSTR_ADDRESS, ent, field, TYPE_POINTER);
1770     v->fieldtype = field->fieldtype;
1771     return v;
1772 }
1773
1774 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)
1775 {
1776     int op;
1777     if (ent->vtype != TYPE_ENTITY)
1778         return NULL;
1779
1780     /* at some point we could redirect for TYPE_POINTER... but that could lead to carelessness */
1781     if (field->vtype != TYPE_FIELD)
1782         return NULL;
1783
1784     switch (outype)
1785     {
1786         case TYPE_FLOAT:    op = INSTR_LOAD_F;   break;
1787         case TYPE_VECTOR:   op = INSTR_LOAD_V;   break;
1788         case TYPE_STRING:   op = INSTR_LOAD_S;   break;
1789         case TYPE_FIELD:    op = INSTR_LOAD_FLD; break;
1790         case TYPE_ENTITY:   op = INSTR_LOAD_ENT; break;
1791         case TYPE_FUNCTION: op = INSTR_LOAD_FNC; break;
1792 #if 0
1793         case TYPE_POINTER: op = INSTR_LOAD_I;   break;
1794         case TYPE_INTEGER: op = INSTR_LOAD_I;   break;
1795 #endif
1796         default:
1797             irerror(self->context, "invalid type for ir_block_create_load_from_ent: %s", type_name[outype]);
1798             return NULL;
1799     }
1800
1801     return ir_block_create_general_instr(self, ctx, label, op, ent, field, outype);
1802 }
1803
1804 ir_value* ir_block_create_add(ir_block *self, lex_ctx ctx,
1805                               const char *label,
1806                               ir_value *left, ir_value *right)
1807 {
1808     int op = 0;
1809     int l = left->vtype;
1810     int r = right->vtype;
1811     if (l == r) {
1812         switch (l) {
1813             default:
1814                 irerror(self->context, "invalid type for ir_block_create_add: %s", type_name[l]);
1815                 return NULL;
1816             case TYPE_FLOAT:
1817                 op = INSTR_ADD_F;
1818                 break;
1819 #if 0
1820             case TYPE_INTEGER:
1821                 op = INSTR_ADD_I;
1822                 break;
1823 #endif
1824             case TYPE_VECTOR:
1825                 op = INSTR_ADD_V;
1826                 break;
1827         }
1828     } else {
1829 #if 0
1830         if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1831             op = INSTR_ADD_FI;
1832         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1833             op = INSTR_ADD_IF;
1834         else
1835 #endif
1836         {
1837             irerror(self->context, "invalid type for ir_block_create_add: %s", type_name[l]);
1838             return NULL;
1839         }
1840     }
1841     return ir_block_create_binop(self, ctx, label, op, left, right);
1842 }
1843
1844 ir_value* ir_block_create_sub(ir_block *self, lex_ctx ctx,
1845                               const char *label,
1846                               ir_value *left, ir_value *right)
1847 {
1848     int op = 0;
1849     int l = left->vtype;
1850     int r = right->vtype;
1851     if (l == r) {
1852
1853         switch (l) {
1854             default:
1855                 irerror(self->context, "invalid type for ir_block_create_sub: %s", type_name[l]);
1856                 return NULL;
1857             case TYPE_FLOAT:
1858                 op = INSTR_SUB_F;
1859                 break;
1860 #if 0
1861             case TYPE_INTEGER:
1862                 op = INSTR_SUB_I;
1863                 break;
1864 #endif
1865             case TYPE_VECTOR:
1866                 op = INSTR_SUB_V;
1867                 break;
1868         }
1869     } else {
1870 #if 0
1871         if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1872             op = INSTR_SUB_FI;
1873         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1874             op = INSTR_SUB_IF;
1875         else
1876 #endif
1877         {
1878             irerror(self->context, "invalid type for ir_block_create_sub: %s", type_name[l]);
1879             return NULL;
1880         }
1881     }
1882     return ir_block_create_binop(self, ctx, label, op, left, right);
1883 }
1884
1885 ir_value* ir_block_create_mul(ir_block *self, lex_ctx ctx,
1886                               const char *label,
1887                               ir_value *left, ir_value *right)
1888 {
1889     int op = 0;
1890     int l = left->vtype;
1891     int r = right->vtype;
1892     if (l == r) {
1893
1894         switch (l) {
1895             default:
1896                 irerror(self->context, "invalid type for ir_block_create_mul: %s", type_name[l]);
1897                 return NULL;
1898             case TYPE_FLOAT:
1899                 op = INSTR_MUL_F;
1900                 break;
1901 #if 0
1902             case TYPE_INTEGER:
1903                 op = INSTR_MUL_I;
1904                 break;
1905 #endif
1906             case TYPE_VECTOR:
1907                 op = INSTR_MUL_V;
1908                 break;
1909         }
1910     } else {
1911         if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1912             op = INSTR_MUL_VF;
1913         else if ( (l == TYPE_FLOAT && r == TYPE_VECTOR) )
1914             op = INSTR_MUL_FV;
1915 #if 0
1916         else if ( (l == TYPE_VECTOR && r == TYPE_INTEGER) )
1917             op = INSTR_MUL_VI;
1918         else if ( (l == TYPE_INTEGER && r == TYPE_VECTOR) )
1919             op = INSTR_MUL_IV;
1920         else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1921             op = INSTR_MUL_FI;
1922         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1923             op = INSTR_MUL_IF;
1924 #endif
1925         else {
1926             irerror(self->context, "invalid type for ir_block_create_mul: %s", type_name[l]);
1927             return NULL;
1928         }
1929     }
1930     return ir_block_create_binop(self, ctx, label, op, left, right);
1931 }
1932
1933 ir_value* ir_block_create_div(ir_block *self, lex_ctx ctx,
1934                               const char *label,
1935                               ir_value *left, ir_value *right)
1936 {
1937     int op = 0;
1938     int l = left->vtype;
1939     int r = right->vtype;
1940     if (l == r) {
1941
1942         switch (l) {
1943             default:
1944                 irerror(self->context, "invalid type for ir_block_create_div: %s", type_name[l]);
1945                 return NULL;
1946             case TYPE_FLOAT:
1947                 op = INSTR_DIV_F;
1948                 break;
1949 #if 0
1950             case TYPE_INTEGER:
1951                 op = INSTR_DIV_I;
1952                 break;
1953 #endif
1954         }
1955     } else {
1956 #if 0
1957         if ( (l == TYPE_VECTOR && r == TYPE_FLOAT) )
1958             op = INSTR_DIV_VF;
1959         else if ( (l == TYPE_FLOAT && r == TYPE_INTEGER) )
1960             op = INSTR_DIV_FI;
1961         else if ( (l == TYPE_INTEGER && r == TYPE_FLOAT) )
1962             op = INSTR_DIV_IF;
1963         else
1964 #endif
1965         {
1966             irerror(self->context, "invalid type for ir_block_create_div: %s", type_name[l]);
1967             return NULL;
1968         }
1969     }
1970     return ir_block_create_binop(self, ctx, label, op, left, right);
1971 }
1972
1973 /* PHI resolving breaks the SSA, and must thus be the last
1974  * step before life-range calculation.
1975  */
1976
1977 static bool ir_block_naive_phi(ir_block *self);
1978 bool ir_function_naive_phi(ir_function *self)
1979 {
1980     size_t i;
1981
1982     for (i = 0; i < vec_size(self->blocks); ++i)
1983     {
1984         if (!ir_block_naive_phi(self->blocks[i]))
1985             return false;
1986     }
1987     return true;
1988 }
1989
1990 #if 0
1991 static bool ir_naive_phi_emit_store(ir_block *block, size_t iid, ir_value *old, ir_value *what)
1992 {
1993     ir_instr *instr;
1994     size_t i;
1995
1996     /* create a store */
1997     if (!ir_block_create_store(block, old, what))
1998         return false;
1999
2000     /* we now move it up */
2001     instr = vec_last(block->instr);
2002     for (i = vec_size(block->instr)-1; i > iid; --i)
2003         block->instr[i] = block->instr[i-1];
2004     block->instr[i] = instr;
2005
2006     return true;
2007 }
2008 #endif
2009
2010 static bool ir_block_naive_phi(ir_block *self)
2011 {
2012     size_t i, p; /*, w;*/
2013     /* FIXME: optionally, create_phi can add the phis
2014      * to a list so we don't need to loop through blocks
2015      * - anyway: "don't optimize YET"
2016      */
2017     for (i = 0; i < vec_size(self->instr); ++i)
2018     {
2019         ir_instr *instr = self->instr[i];
2020         if (instr->opcode != VINSTR_PHI)
2021             continue;
2022
2023         vec_remove(self->instr, i, 1);
2024         --i; /* NOTE: i+1 below */
2025
2026         for (p = 0; p < vec_size(instr->phi); ++p)
2027         {
2028             ir_value *v = instr->phi[p].value;
2029             ir_block *b = instr->phi[p].from;
2030
2031             if (v->store == store_value &&
2032                 vec_size(v->reads) == 1 &&
2033                 vec_size(v->writes) == 1)
2034             {
2035                 /* replace the value */
2036                 if (!ir_instr_op(v->writes[0], 0, instr->_ops[0], true))
2037                     return false;
2038             }
2039             else
2040             {
2041                 /* force a move instruction */
2042                 ir_instr *prevjump = vec_last(b->instr);
2043                 vec_pop(b->instr);
2044                 b->final = false;
2045                 instr->_ops[0]->store = store_global;
2046                 if (!ir_block_create_store(b, instr->context, instr->_ops[0], v))
2047                     return false;
2048                 instr->_ops[0]->store = store_value;
2049                 vec_push(b->instr, prevjump);
2050                 b->final = true;
2051             }
2052
2053 #if 0
2054             ir_value *v = instr->phi[p].value;
2055             for (w = 0; w < vec_size(v->writes); ++w) {
2056                 ir_value *old;
2057
2058                 if (!v->writes[w]->_ops[0])
2059                     continue;
2060
2061                 /* When the write was to a global, we have to emit a mov */
2062                 old = v->writes[w]->_ops[0];
2063
2064                 /* The original instruction now writes to the PHI target local */
2065                 if (v->writes[w]->_ops[0] == v)
2066                     v->writes[w]->_ops[0] = instr->_ops[0];
2067
2068                 if (old->store != store_value && old->store != store_local && old->store != store_param)
2069                 {
2070                     /* If it originally wrote to a global we need to store the value
2071                      * there as welli
2072                      */
2073                     if (!ir_naive_phi_emit_store(self, i+1, old, v))
2074                         return false;
2075                     if (i+1 < vec_size(self->instr))
2076                         instr = self->instr[i+1];
2077                     else
2078                         instr = NULL;
2079                     /* In case I forget and access instr later, it'll be NULL
2080                      * when it's a problem, to make sure we crash, rather than accessing
2081                      * invalid data.
2082                      */
2083                 }
2084                 else
2085                 {
2086                     /* If it didn't, we can replace all reads by the phi target now. */
2087                     size_t r;
2088                     for (r = 0; r < vec_size(old->reads); ++r)
2089                     {
2090                         size_t op;
2091                         ir_instr *ri = old->reads[r];
2092                         for (op = 0; op < vec_size(ri->phi); ++op) {
2093                             if (ri->phi[op].value == old)
2094                                 ri->phi[op].value = v;
2095                         }
2096                         for (op = 0; op < 3; ++op) {
2097                             if (ri->_ops[op] == old)
2098                                 ri->_ops[op] = v;
2099                         }
2100                     }
2101                 }
2102             }
2103 #endif
2104         }
2105         ir_instr_delete(instr);
2106     }
2107     return true;
2108 }
2109
2110 /***********************************************************************
2111  *IR Temp allocation code
2112  * Propagating value life ranges by walking through the function backwards
2113  * until no more changes are made.
2114  * In theory this should happen once more than once for every nested loop
2115  * level.
2116  * Though this implementation might run an additional time for if nests.
2117  */
2118
2119 /* Enumerate instructions used by value's life-ranges
2120  */
2121 static void ir_block_enumerate(ir_block *self, size_t *_eid)
2122 {
2123     size_t i;
2124     size_t eid = *_eid;
2125     for (i = 0; i < vec_size(self->instr); ++i)
2126     {
2127         self->instr[i]->eid = eid++;
2128     }
2129     *_eid = eid;
2130 }
2131
2132 /* Enumerate blocks and instructions.
2133  * The block-enumeration is unordered!
2134  * We do not really use the block enumreation, however
2135  * the instruction enumeration is important for life-ranges.
2136  */
2137 void ir_function_enumerate(ir_function *self)
2138 {
2139     size_t i;
2140     size_t instruction_id = 0;
2141     for (i = 0; i < vec_size(self->blocks); ++i)
2142     {
2143         self->blocks[i]->eid = i;
2144         self->blocks[i]->run_id = 0;
2145         ir_block_enumerate(self->blocks[i], &instruction_id);
2146     }
2147 }
2148
2149 static bool ir_block_life_propagate(ir_block *b, ir_block *prev, bool *changed);
2150 bool ir_function_calculate_liferanges(ir_function *self)
2151 {
2152     size_t i;
2153     bool changed;
2154
2155     do {
2156         self->run_id++;
2157         changed = false;
2158         for (i = 0; i != vec_size(self->blocks); ++i)
2159         {
2160             if (self->blocks[i]->is_return)
2161             {
2162                 vec_free(self->blocks[i]->living);
2163                 if (!ir_block_life_propagate(self->blocks[i], NULL, &changed))
2164                     return false;
2165             }
2166         }
2167     } while (changed);
2168     if (vec_size(self->blocks)) {
2169         ir_block *block = self->blocks[0];
2170         for (i = 0; i < vec_size(block->living); ++i) {
2171             ir_value *v = block->living[i];
2172             if (v->memberof || v->store != store_local)
2173                 continue;
2174             if (irwarning(v->context, WARN_USED_UNINITIALIZED,
2175                           "variable `%s` may be used uninitialized in this function", v->name))
2176             {
2177                 return false;
2178             }
2179         }
2180     }
2181     return true;
2182 }
2183
2184 /* Local-value allocator
2185  * After finishing creating the liferange of all values used in a function
2186  * we can allocate their global-positions.
2187  * This is the counterpart to register-allocation in register machines.
2188  */
2189 typedef struct {
2190     ir_value **locals;
2191     size_t    *sizes;
2192     size_t    *positions;
2193     bool      *unique;
2194 } function_allocator;
2195
2196 static bool function_allocator_alloc(function_allocator *alloc, const ir_value *var)
2197 {
2198     ir_value *slot;
2199     size_t vsize = type_sizeof[var->vtype];
2200
2201     slot = ir_value_var("reg", store_global, var->vtype);
2202     if (!slot)
2203         return false;
2204
2205     if (!ir_value_life_merge_into(slot, var))
2206         goto localerror;
2207
2208     vec_push(alloc->locals, slot);
2209     vec_push(alloc->sizes, vsize);
2210     vec_push(alloc->unique, var->unique_life);
2211
2212     return true;
2213
2214 localerror:
2215     ir_value_delete(slot);
2216     return false;
2217 }
2218
2219 bool ir_function_allocate_locals(ir_function *self)
2220 {
2221     size_t i, a;
2222     bool   retval = true;
2223     size_t pos;
2224
2225     ir_value *slot;
2226     const ir_value *v;
2227
2228     function_allocator alloc;
2229
2230     if (!vec_size(self->locals) && !vec_size(self->values))
2231         return true;
2232
2233     alloc.locals    = NULL;
2234     alloc.sizes     = NULL;
2235     alloc.positions = NULL;
2236     alloc.unique    = NULL;
2237
2238     for (i = 0; i < vec_size(self->locals); ++i)
2239     {
2240         if (!OPTS_OPTIMIZATION(OPTIM_LOCALTEMPS))
2241             self->locals[i]->unique_life = true;
2242         if (!function_allocator_alloc(&alloc, self->locals[i]))
2243             goto error;
2244     }
2245
2246     /* Allocate a slot for any value that still exists */
2247     for (i = 0; i < vec_size(self->values); ++i)
2248     {
2249         v = self->values[i];
2250
2251         if (!vec_size(v->life))
2252             continue;
2253
2254         for (a = 0; a < vec_size(alloc.locals); ++a)
2255         {
2256             /* if it's reserved for a unique liferange: skip */
2257             if (alloc.unique[a])
2258                 continue;
2259
2260             slot = alloc.locals[a];
2261
2262             /* never resize parameters
2263              * will be required later when overlapping temps + locals
2264              */
2265             if (a < vec_size(self->params) &&
2266                 alloc.sizes[a] < type_sizeof[v->vtype])
2267             {
2268                 continue;
2269             }
2270
2271             if (ir_values_overlap(v, slot))
2272                 continue;
2273
2274             if (!ir_value_life_merge_into(slot, v))
2275                 goto error;
2276
2277             /* adjust size for this slot */
2278             if (alloc.sizes[a] < type_sizeof[v->vtype])
2279                 alloc.sizes[a] = type_sizeof[v->vtype];
2280
2281             self->values[i]->code.local = a;
2282             break;
2283         }
2284         if (a >= vec_size(alloc.locals)) {
2285             self->values[i]->code.local = vec_size(alloc.locals);
2286             if (!function_allocator_alloc(&alloc, v))
2287                 goto error;
2288         }
2289     }
2290
2291     if (!alloc.sizes) {
2292         goto cleanup;
2293     }
2294
2295     /* Adjust slot positions based on sizes */
2296     vec_push(alloc.positions, 0);
2297
2298     if (vec_size(alloc.sizes))
2299         pos = alloc.positions[0] + alloc.sizes[0];
2300     else
2301         pos = 0;
2302     for (i = 1; i < vec_size(alloc.sizes); ++i)
2303     {
2304         pos = alloc.positions[i-1] + alloc.sizes[i-1];
2305         vec_push(alloc.positions, pos);
2306     }
2307
2308     self->allocated_locals = pos + vec_last(alloc.sizes);
2309
2310     /* Locals need to know their new position */
2311     for (i = 0; i < vec_size(self->locals); ++i) {
2312         self->locals[i]->code.local = alloc.positions[i];
2313     }
2314     /* Take over the actual slot positions on values */
2315     for (i = 0; i < vec_size(self->values); ++i) {
2316         self->values[i]->code.local = alloc.positions[self->values[i]->code.local];
2317     }
2318
2319     goto cleanup;
2320
2321 error:
2322     retval = false;
2323 cleanup:
2324     for (i = 0; i < vec_size(alloc.locals); ++i)
2325         ir_value_delete(alloc.locals[i]);
2326     vec_free(alloc.locals);
2327     vec_free(alloc.sizes);
2328     vec_free(alloc.positions);
2329     return retval;
2330 }
2331
2332 /* Get information about which operand
2333  * is read from, or written to.
2334  */
2335 static void ir_op_read_write(int op, size_t *read, size_t *write)
2336 {
2337     switch (op)
2338     {
2339     case VINSTR_JUMP:
2340     case INSTR_GOTO:
2341         *write = 0;
2342         *read = 0;
2343         break;
2344     case INSTR_IF:
2345     case INSTR_IFNOT:
2346 #if 0
2347     case INSTR_IF_S:
2348     case INSTR_IFNOT_S:
2349 #endif
2350     case INSTR_RETURN:
2351     case VINSTR_COND:
2352         *write = 0;
2353         *read = 1;
2354         break;
2355     case INSTR_STOREP_F:
2356     case INSTR_STOREP_V:
2357     case INSTR_STOREP_S:
2358     case INSTR_STOREP_ENT:
2359     case INSTR_STOREP_FLD:
2360     case INSTR_STOREP_FNC:
2361         *write = 0;
2362         *read  = 7;
2363         break;
2364     default:
2365         *write = 1;
2366         *read = 6;
2367         break;
2368     };
2369 }
2370
2371 static bool ir_block_living_add_instr(ir_block *self, size_t eid)
2372 {
2373     size_t i;
2374     bool changed = false;
2375     bool tempbool;
2376     for (i = 0; i != vec_size(self->living); ++i)
2377     {
2378         tempbool = ir_value_life_merge(self->living[i], eid);
2379         /* debug
2380         if (tempbool)
2381             irerror(self->context, "block_living_add_instr() value instruction added %s: %i", self->living[i]->_name, (int)eid);
2382         */
2383         changed = changed || tempbool;
2384     }
2385     return changed;
2386 }
2387
2388 static bool ir_block_life_prop_previous(ir_block* self, ir_block *prev, bool *changed)
2389 {
2390     size_t i;
2391
2392     (void)changed;
2393
2394     /* values which have been read in a previous iteration are now
2395      * in the "living" array even if the previous block doesn't use them.
2396      * So we have to remove whatever does not exist in the previous block.
2397      * They will be re-added on-read, but the liferange merge won't cause
2398      * a change.
2399     for (i = 0; i < vec_size(self->living); ++i)
2400     {
2401         if (!vec_ir_value_find(prev->living, self->living[i], NULL)) {
2402             vec_remove(self->living, i, 1);
2403             --i;
2404         }
2405     }
2406      */
2407
2408     /* Whatever the previous block still has in its living set
2409      * must now be added to ours as well.
2410      */
2411     for (i = 0; i < vec_size(prev->living); ++i)
2412     {
2413         if (vec_ir_value_find(self->living, prev->living[i], NULL))
2414             continue;
2415         vec_push(self->living, prev->living[i]);
2416         /*
2417         irerror(self->contextt from prev: %s", self->label, prev->living[i]->_name);
2418         */
2419     }
2420     return true;
2421 }
2422
2423 static bool ir_block_life_propagate(ir_block *self, ir_block *prev, bool *changed)
2424 {
2425     ir_instr *instr;
2426     ir_value *value;
2427     bool  tempbool;
2428     size_t i, o, p;
2429     /* bitmasks which operands are read from or written to */
2430     size_t read, write;
2431     char dbg_ind[16] = { '#', '0' };
2432     (void)dbg_ind;
2433
2434     if (prev)
2435     {
2436         if (!ir_block_life_prop_previous(self, prev, changed))
2437             return false;
2438     }
2439
2440     i = vec_size(self->instr);
2441     while (i)
2442     { --i;
2443         instr = self->instr[i];
2444
2445         /* PHI operands are always read operands */
2446         for (p = 0; p < vec_size(instr->phi); ++p)
2447         {
2448             value = instr->phi[p].value;
2449             if (value->memberof)
2450                 value = value->memberof;
2451             if (!vec_ir_value_find(self->living, value, NULL))
2452                 vec_push(self->living, value);
2453         }
2454
2455         /* call params are read operands too */
2456         for (p = 0; p < vec_size(instr->params); ++p)
2457         {
2458             value = instr->params[p];
2459             if (value->memberof)
2460                 value = value->memberof;
2461             if (!vec_ir_value_find(self->living, value, NULL))
2462                 vec_push(self->living, value);
2463         }
2464
2465         /* See which operands are read and write operands */
2466         ir_op_read_write(instr->opcode, &read, &write);
2467
2468         if (instr->opcode == INSTR_MUL_VF)
2469         {
2470             /* the float source will get an additional lifetime */
2471             tempbool = ir_value_life_merge(instr->_ops[2], instr->eid+1);
2472             *changed = *changed || tempbool;
2473         }
2474         else if (instr->opcode == INSTR_MUL_FV)
2475         {
2476             /* the float source will get an additional lifetime */
2477             tempbool = ir_value_life_merge(instr->_ops[1], instr->eid+1);
2478             *changed = *changed || tempbool;
2479         }
2480
2481         /* Go through the 3 main operands */
2482         for (o = 0; o < 3; ++o)
2483         {
2484             if (!instr->_ops[o]) /* no such operand */
2485                 continue;
2486
2487             value = instr->_ops[o];
2488             if (value->memberof)
2489                 value = value->memberof;
2490
2491             /* We only care about locals */
2492             /* we also calculate parameter liferanges so that locals
2493              * can take up parameter slots */
2494             if (value->store != store_value &&
2495                 value->store != store_local &&
2496                 value->store != store_param)
2497                 continue;
2498
2499             /* read operands */
2500             if (read & (1<<o))
2501             {
2502                 if (!vec_ir_value_find(self->living, value, NULL))
2503                     vec_push(self->living, value);
2504             }
2505
2506             /* write operands */
2507             /* When we write to a local, we consider it "dead" for the
2508              * remaining upper part of the function, since in SSA a value
2509              * can only be written once (== created)
2510              */
2511             if (write & (1<<o))
2512             {
2513                 size_t idx;
2514                 bool in_living = vec_ir_value_find(self->living, value, &idx);
2515                 if (!in_living)
2516                 {
2517                     /* If the value isn't alive it hasn't been read before... */
2518                     /* TODO: See if the warning can be emitted during parsing or AST processing
2519                      * otherwise have warning printed here.
2520                      * IF printing a warning here: include filecontext_t,
2521                      * and make sure it's only printed once
2522                      * since this function is run multiple times.
2523                      */
2524                     /* For now: debug info: */
2525                     /* con_err( "Value only written %s\n", value->name); */
2526                     tempbool = ir_value_life_merge(value, instr->eid);
2527                     *changed = *changed || tempbool;
2528                     /*
2529                     ir_instr_dump(instr, dbg_ind, printf);
2530                     abort();
2531                     */
2532                 } else {
2533                     /* since 'living' won't contain it
2534                      * anymore, merge the value, since
2535                      * (A) doesn't.
2536                      */
2537                     tempbool = ir_value_life_merge(value, instr->eid);
2538                     /*
2539                     if (tempbool)
2540                         con_err( "value added id %s %i\n", value->name, (int)instr->eid);
2541                     */
2542                     *changed = *changed || tempbool;
2543                     /* Then remove */
2544                     vec_remove(self->living, idx, 1);
2545                 }
2546             }
2547         }
2548         /* (A) */
2549         tempbool = ir_block_living_add_instr(self, instr->eid);
2550         /*con_err( "living added values\n");*/
2551         *changed = *changed || tempbool;
2552
2553     }
2554
2555     if (self->run_id == self->owner->run_id)
2556         return true;
2557
2558     self->run_id = self->owner->run_id;
2559
2560     for (i = 0; i < vec_size(self->entries); ++i)
2561     {
2562         ir_block *entry = self->entries[i];
2563         ir_block_life_propagate(entry, self, changed);
2564     }
2565
2566     return true;
2567 }
2568
2569 /***********************************************************************
2570  *IR Code-Generation
2571  *
2572  * Since the IR has the convention of putting 'write' operands
2573  * at the beginning, we have to rotate the operands of instructions
2574  * properly in order to generate valid QCVM code.
2575  *
2576  * Having destinations at a fixed position is more convenient. In QC
2577  * this is *mostly* OPC,  but FTE adds at least 2 instructions which
2578  * read from from OPA,  and store to OPB rather than OPC.   Which is
2579  * partially the reason why the implementation of these instructions
2580  * in darkplaces has been delayed for so long.
2581  *
2582  * Breaking conventions is annoying...
2583  */
2584 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal);
2585
2586 static bool gen_global_field(ir_value *global)
2587 {
2588     if (global->hasvalue)
2589     {
2590         ir_value *fld = global->constval.vpointer;
2591         if (!fld) {
2592             irerror(global->context, "Invalid field constant with no field: %s", global->name);
2593             return false;
2594         }
2595
2596         /* copy the field's value */
2597         ir_value_code_setaddr(global, vec_size(code_globals));
2598         vec_push(code_globals, fld->code.fieldaddr);
2599         if (global->fieldtype == TYPE_VECTOR) {
2600             vec_push(code_globals, fld->code.fieldaddr+1);
2601             vec_push(code_globals, fld->code.fieldaddr+2);
2602         }
2603     }
2604     else
2605     {
2606         ir_value_code_setaddr(global, vec_size(code_globals));
2607         vec_push(code_globals, 0);
2608         if (global->fieldtype == TYPE_VECTOR) {
2609             vec_push(code_globals, 0);
2610             vec_push(code_globals, 0);
2611         }
2612     }
2613     if (global->code.globaladdr < 0)
2614         return false;
2615     return true;
2616 }
2617
2618 static bool gen_global_pointer(ir_value *global)
2619 {
2620     if (global->hasvalue)
2621     {
2622         ir_value *target = global->constval.vpointer;
2623         if (!target) {
2624             irerror(global->context, "Invalid pointer constant: %s", global->name);
2625             /* NULL pointers are pointing to the NULL constant, which also
2626              * sits at address 0, but still has an ir_value for itself.
2627              */
2628             return false;
2629         }
2630
2631         /* Here, relocations ARE possible - in fteqcc-enhanced-qc:
2632          * void() foo; <- proto
2633          * void() *fooptr = &foo;
2634          * void() foo = { code }
2635          */
2636         if (!target->code.globaladdr) {
2637             /* FIXME: Check for the constant nullptr ir_value!
2638              * because then code.globaladdr being 0 is valid.
2639              */
2640             irerror(global->context, "FIXME: Relocation support");
2641             return false;
2642         }
2643
2644         ir_value_code_setaddr(global, vec_size(code_globals));
2645         vec_push(code_globals, target->code.globaladdr);
2646     }
2647     else
2648     {
2649         ir_value_code_setaddr(global, vec_size(code_globals));
2650         vec_push(code_globals, 0);
2651     }
2652     if (global->code.globaladdr < 0)
2653         return false;
2654     return true;
2655 }
2656
2657 static bool gen_blocks_recursive(ir_function *func, ir_block *block)
2658 {
2659     prog_section_statement stmt;
2660     ir_instr *instr;
2661     ir_block *target;
2662     ir_block *ontrue;
2663     ir_block *onfalse;
2664     size_t    stidx;
2665     size_t    i;
2666
2667 tailcall:
2668     block->generated = true;
2669     block->code_start = vec_size(code_statements);
2670     for (i = 0; i < vec_size(block->instr); ++i)
2671     {
2672         instr = block->instr[i];
2673
2674         if (instr->opcode == VINSTR_PHI) {
2675             irerror(block->context, "cannot generate virtual instruction (phi)");
2676             return false;
2677         }
2678
2679         if (instr->opcode == VINSTR_JUMP) {
2680             target = instr->bops[0];
2681             /* for uncoditional jumps, if the target hasn't been generated
2682              * yet, we generate them right here.
2683              */
2684             if (!target->generated) {
2685                 block = target;
2686                 goto tailcall;
2687             }
2688
2689             /* otherwise we generate a jump instruction */
2690             stmt.opcode = INSTR_GOTO;
2691             stmt.o1.s1 = (target->code_start) - vec_size(code_statements);
2692             stmt.o2.s1 = 0;
2693             stmt.o3.s1 = 0;
2694             if (stmt.o1.s1 != 1)
2695                 code_push_statement(&stmt, instr->context.line);
2696
2697             /* no further instructions can be in this block */
2698             return true;
2699         }
2700
2701         if (instr->opcode == VINSTR_COND) {
2702             ontrue  = instr->bops[0];
2703             onfalse = instr->bops[1];
2704             /* TODO: have the AST signal which block should
2705              * come first: eg. optimize IFs without ELSE...
2706              */
2707
2708             stmt.o1.u1 = ir_value_code_addr(instr->_ops[0]);
2709             stmt.o2.u1 = 0;
2710             stmt.o3.s1 = 0;
2711
2712             if (ontrue->generated) {
2713                 stmt.opcode = INSTR_IF;
2714                 stmt.o2.s1 = (ontrue->code_start) - vec_size(code_statements);
2715                 if (stmt.o2.s1 != 1)
2716                     code_push_statement(&stmt, instr->context.line);
2717             }
2718             if (onfalse->generated) {
2719                 stmt.opcode = INSTR_IFNOT;
2720                 stmt.o2.s1 = (onfalse->code_start) - vec_size(code_statements);
2721                 if (stmt.o2.s1 != 1)
2722                     code_push_statement(&stmt, instr->context.line);
2723             }
2724             if (!ontrue->generated) {
2725                 if (onfalse->generated) {
2726                     block = ontrue;
2727                     goto tailcall;
2728                 }
2729             }
2730             if (!onfalse->generated) {
2731                 if (ontrue->generated) {
2732                     block = onfalse;
2733                     goto tailcall;
2734                 }
2735             }
2736             /* neither ontrue nor onfalse exist */
2737             stmt.opcode = INSTR_IFNOT;
2738             if (!instr->likely) {
2739                 /* Honor the likelyhood hint */
2740                 ir_block *tmp = onfalse;
2741                 stmt.opcode = INSTR_IF;
2742                 onfalse = ontrue;
2743                 ontrue = tmp;
2744             }
2745             stidx = vec_size(code_statements);
2746             code_push_statement(&stmt, instr->context.line);
2747             /* on false we jump, so add ontrue-path */
2748             if (!gen_blocks_recursive(func, ontrue))
2749                 return false;
2750             /* fixup the jump address */
2751             code_statements[stidx].o2.s1 = vec_size(code_statements) - stidx;
2752             /* generate onfalse path */
2753             if (onfalse->generated) {
2754                 /* fixup the jump address */
2755                 code_statements[stidx].o2.s1 = (onfalse->code_start) - (stidx);
2756                 if (code_statements[stidx].o2.s1 == 1) {
2757                     code_statements[stidx] = code_statements[stidx+1];
2758                     if (code_statements[stidx].o1.s1 < 0)
2759                         code_statements[stidx].o1.s1++;
2760                     code_pop_statement();
2761                 }
2762                 stmt.opcode = vec_last(code_statements).opcode;
2763                 if (stmt.opcode == INSTR_GOTO ||
2764                     stmt.opcode == INSTR_IF ||
2765                     stmt.opcode == INSTR_IFNOT ||
2766                     stmt.opcode == INSTR_RETURN ||
2767                     stmt.opcode == INSTR_DONE)
2768                 {
2769                     /* no use jumping from here */
2770                     return true;
2771                 }
2772                 /* may have been generated in the previous recursive call */
2773                 stmt.opcode = INSTR_GOTO;
2774                 stmt.o1.s1 = (onfalse->code_start) - vec_size(code_statements);
2775                 stmt.o2.s1 = 0;
2776                 stmt.o3.s1 = 0;
2777                 if (stmt.o1.s1 != 1)
2778                     code_push_statement(&stmt, instr->context.line);
2779                 return true;
2780             }
2781             else if (code_statements[stidx].o2.s1 == 1) {
2782                 code_statements[stidx] = code_statements[stidx+1];
2783                 if (code_statements[stidx].o1.s1 < 0)
2784                     code_statements[stidx].o1.s1++;
2785                 code_pop_statement();
2786             }
2787             /* if not, generate now */
2788             block = onfalse;
2789             goto tailcall;
2790         }
2791
2792         if (instr->opcode >= INSTR_CALL0 && instr->opcode <= INSTR_CALL8) {
2793             /* Trivial call translation:
2794              * copy all params to OFS_PARM*
2795              * if the output's storetype is not store_return,
2796              * add append a STORE instruction!
2797              *
2798              * NOTES on how to do it better without much trouble:
2799              * -) The liferanges!
2800              *      Simply check the liferange of all parameters for
2801              *      other CALLs. For each param with no CALL in its
2802              *      liferange, we can store it in an OFS_PARM at
2803              *      generation already. This would even include later
2804              *      reuse.... probably... :)
2805              */
2806             size_t p, first;
2807             ir_value *retvalue;
2808
2809             first = vec_size(instr->params);
2810             if (first > 8)
2811                 first = 8;
2812             for (p = 0; p < first; ++p)
2813             {
2814                 ir_value *param = instr->params[p];
2815
2816                 stmt.opcode = INSTR_STORE_F;
2817                 stmt.o3.u1 = 0;
2818
2819                 if (param->vtype == TYPE_FIELD)
2820                     stmt.opcode = field_store_instr[param->fieldtype];
2821                 else
2822                     stmt.opcode = type_store_instr[param->vtype];
2823                 stmt.o1.u1 = ir_value_code_addr(param);
2824                 stmt.o2.u1 = OFS_PARM0 + 3 * p;
2825                 code_push_statement(&stmt, instr->context.line);
2826             }
2827             /* Now handle extparams */
2828             first = vec_size(instr->params);
2829             for (; p < first; ++p)
2830             {
2831                 ir_builder *ir = func->owner;
2832                 ir_value *param = instr->params[p];
2833                 ir_value *targetparam;
2834
2835                 if (p-8 >= vec_size(ir->extparams))
2836                     ir_gen_extparam(ir);
2837
2838                 targetparam = ir->extparams[p-8];
2839
2840                 stmt.opcode = INSTR_STORE_F;
2841                 stmt.o3.u1 = 0;
2842
2843                 if (param->vtype == TYPE_FIELD)
2844                     stmt.opcode = field_store_instr[param->fieldtype];
2845                 else
2846                     stmt.opcode = type_store_instr[param->vtype];
2847                 stmt.o1.u1 = ir_value_code_addr(param);
2848                 stmt.o2.u1 = ir_value_code_addr(targetparam);
2849                 code_push_statement(&stmt, instr->context.line);
2850             }
2851
2852             stmt.opcode = INSTR_CALL0 + vec_size(instr->params);
2853             if (stmt.opcode > INSTR_CALL8)
2854                 stmt.opcode = INSTR_CALL8;
2855             stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2856             stmt.o2.u1 = 0;
2857             stmt.o3.u1 = 0;
2858             code_push_statement(&stmt, instr->context.line);
2859
2860             retvalue = instr->_ops[0];
2861             if (retvalue && retvalue->store != store_return && vec_size(retvalue->life))
2862             {
2863                 /* not to be kept in OFS_RETURN */
2864                 if (retvalue->vtype == TYPE_FIELD)
2865                     stmt.opcode = field_store_instr[retvalue->vtype];
2866                 else
2867                     stmt.opcode = type_store_instr[retvalue->vtype];
2868                 stmt.o1.u1 = OFS_RETURN;
2869                 stmt.o2.u1 = ir_value_code_addr(retvalue);
2870                 stmt.o3.u1 = 0;
2871                 code_push_statement(&stmt, instr->context.line);
2872             }
2873             continue;
2874         }
2875
2876         if (instr->opcode == INSTR_STATE) {
2877             irerror(block->context, "TODO: state instruction");
2878             return false;
2879         }
2880
2881         stmt.opcode = instr->opcode;
2882         stmt.o1.u1 = 0;
2883         stmt.o2.u1 = 0;
2884         stmt.o3.u1 = 0;
2885
2886         /* This is the general order of operands */
2887         if (instr->_ops[0])
2888             stmt.o3.u1 = ir_value_code_addr(instr->_ops[0]);
2889
2890         if (instr->_ops[1])
2891             stmt.o1.u1 = ir_value_code_addr(instr->_ops[1]);
2892
2893         if (instr->_ops[2])
2894             stmt.o2.u1 = ir_value_code_addr(instr->_ops[2]);
2895
2896         if (stmt.opcode == INSTR_RETURN || stmt.opcode == INSTR_DONE)
2897         {
2898             stmt.o1.u1 = stmt.o3.u1;
2899             stmt.o3.u1 = 0;
2900         }
2901         else if ((stmt.opcode >= INSTR_STORE_F &&
2902                   stmt.opcode <= INSTR_STORE_FNC) ||
2903                  (stmt.opcode >= INSTR_STOREP_F &&
2904                   stmt.opcode <= INSTR_STOREP_FNC))
2905         {
2906             /* 2-operand instructions with A -> B */
2907             stmt.o2.u1 = stmt.o3.u1;
2908             stmt.o3.u1 = 0;
2909
2910             /* tiny optimization, don't output
2911              * STORE a, a
2912              */
2913             if (stmt.o2.u1 == stmt.o1.u1 &&
2914                 OPTS_OPTIMIZATION(OPTIM_PEEPHOLE))
2915             {
2916                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
2917                 continue;
2918             }
2919         }
2920
2921         code_push_statement(&stmt, instr->context.line);
2922     }
2923     return true;
2924 }
2925
2926 static bool gen_function_code(ir_function *self)
2927 {
2928     ir_block *block;
2929     prog_section_statement stmt;
2930
2931     /* Starting from entry point, we generate blocks "as they come"
2932      * for now. Dead blocks will not be translated obviously.
2933      */
2934     if (!vec_size(self->blocks)) {
2935         irerror(self->context, "Function '%s' declared without body.", self->name);
2936         return false;
2937     }
2938
2939     block = self->blocks[0];
2940     if (block->generated)
2941         return true;
2942
2943     if (!gen_blocks_recursive(self, block)) {
2944         irerror(self->context, "failed to generate blocks for '%s'", self->name);
2945         return false;
2946     }
2947
2948     /* code_write and qcvm -disasm need to know that the function ends here */
2949     stmt.opcode = INSTR_DONE;
2950     stmt.o1.u1 = 0;
2951     stmt.o2.u1 = 0;
2952     stmt.o3.u1 = 0;
2953     code_push_statement(&stmt, vec_last(code_linenums));
2954     return true;
2955 }
2956
2957 static qcint ir_builder_filestring(ir_builder *ir, const char *filename)
2958 {
2959     /* NOTE: filename pointers are copied, we never strdup them,
2960      * thus we can use pointer-comparison to find the string.
2961      */
2962     size_t i;
2963     qcint  str;
2964
2965     for (i = 0; i < vec_size(ir->filenames); ++i) {
2966         if (ir->filenames[i] == filename)
2967             return ir->filestrings[i];
2968     }
2969
2970     str = code_genstring(filename);
2971     vec_push(ir->filenames, filename);
2972     vec_push(ir->filestrings, str);
2973     return str;
2974 }
2975
2976 static bool gen_global_function(ir_builder *ir, ir_value *global)
2977 {
2978     prog_section_function fun;
2979     ir_function          *irfun;
2980
2981     size_t i;
2982 #ifndef NEW_ALLOC_STRAT
2983     size_t local_var_end;
2984 #endif
2985
2986     if (!global->hasvalue || (!global->constval.vfunc))
2987     {
2988         irerror(global->context, "Invalid state of function-global: not constant: %s", global->name);
2989         return false;
2990     }
2991
2992     irfun = global->constval.vfunc;
2993
2994     fun.name    = global->code.name;
2995     fun.file    = ir_builder_filestring(ir, global->context.file);
2996     fun.profile = 0; /* always 0 */
2997     fun.nargs   = vec_size(irfun->params);
2998     if (fun.nargs > 8)
2999         fun.nargs = 8;
3000
3001     for (i = 0;i < 8; ++i) {
3002         if ((int32_t)i >= fun.nargs)
3003             fun.argsize[i] = 0;
3004         else
3005             fun.argsize[i] = type_sizeof[irfun->params[i]];
3006     }
3007
3008     fun.firstlocal = vec_size(code_globals);
3009
3010 #ifndef NEW_ALLOC_STRAT
3011     local_var_end = fun.firstlocal;
3012     for (i = 0; i < vec_size(irfun->locals); ++i) {
3013         if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
3014             irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
3015             return false;
3016         }
3017     }
3018     if (vec_size(irfun->locals)) {
3019         ir_value *last = vec_last(irfun->locals);
3020         local_var_end = last->code.globaladdr;
3021         if (last->vtype == TYPE_FIELD && last->fieldtype == TYPE_VECTOR)
3022             local_var_end += type_sizeof[TYPE_VECTOR];
3023         else
3024             local_var_end += type_sizeof[last->vtype];
3025     }
3026     for (i = 0; i < vec_size(irfun->values); ++i)
3027     {
3028         /* generate code.globaladdr for ssa values */
3029         ir_value *v = irfun->values[i];
3030         ir_value_code_setaddr(v, local_var_end + v->code.local);
3031     }
3032     for (i = 0; i < irfun->allocated_locals; ++i) {
3033         /* fill the locals with zeros */
3034         vec_push(code_globals, 0);
3035     }
3036
3037     fun.locals = vec_size(code_globals) - fun.firstlocal;
3038 #else
3039     fun.locals = irfun->allocated_locals;
3040     for (i = 0; i < vec_size(irfun->locals); ++i) {
3041         if (!ir_builder_gen_global(ir, irfun->locals[i], true)) {
3042             irerror(irfun->locals[i]->context, "Failed to generate local %s", irfun->locals[i]->name);
3043             return false;
3044         }
3045         ir_value_code_setaddr(irfun->locals[i], fun.firstlocal + irfun->locals[i]->code.local);
3046     }
3047     for (i = vec_size(code_globals) - fun.firstlocal; i < fun.locals; ++i) {
3048         vec_push(code_globals, 0);
3049     }
3050     for (i = 0; i < vec_size(irfun->values); ++i)
3051     {
3052         /* generate code.globaladdr for ssa values */
3053         ir_value *v = irfun->values[i];
3054         ir_value_code_setaddr(v, fun.firstlocal + v->code.local);
3055     }
3056 #endif
3057
3058     if (irfun->builtin)
3059         fun.entry = irfun->builtin+1;
3060     else {
3061         irfun->code_function_def = vec_size(code_functions);
3062         fun.entry = vec_size(code_statements);
3063     }
3064
3065     vec_push(code_functions, fun);
3066     return true;
3067 }
3068
3069 static void ir_gen_extparam(ir_builder *ir)
3070 {
3071     prog_section_def def;
3072     ir_value        *global;
3073     char             name[128];
3074
3075     snprintf(name, sizeof(name), "EXTPARM#%i", (int)(vec_size(ir->extparams)+8));
3076     global = ir_value_var(name, store_global, TYPE_VECTOR);
3077
3078     def.name = code_genstring(name);
3079     def.type = TYPE_VECTOR;
3080     def.offset = vec_size(code_globals);
3081
3082     vec_push(code_defs, def);
3083     ir_value_code_setaddr(global, def.offset);
3084     vec_push(code_globals, 0);
3085     vec_push(code_globals, 0);
3086     vec_push(code_globals, 0);
3087
3088     vec_push(ir->extparams, global);
3089 }
3090
3091 static bool gen_function_extparam_copy(ir_function *self)
3092 {
3093     size_t i, ext, numparams;
3094
3095     ir_builder *ir = self->owner;
3096     ir_value   *ep;
3097     prog_section_statement stmt;
3098
3099     numparams = vec_size(self->params);
3100     if (!numparams)
3101         return true;
3102
3103     stmt.opcode = INSTR_STORE_F;
3104     stmt.o3.s1 = 0;
3105     for (i = 8; i < numparams; ++i) {
3106         ext = i - 8;
3107         if (ext >= vec_size(ir->extparams))
3108             ir_gen_extparam(ir);
3109
3110         ep = ir->extparams[ext];
3111
3112         stmt.opcode = type_store_instr[self->locals[i]->vtype];
3113         if (self->locals[i]->vtype == TYPE_FIELD &&
3114             self->locals[i]->fieldtype == TYPE_VECTOR)
3115         {
3116             stmt.opcode = INSTR_STORE_V;
3117         }
3118         stmt.o1.u1 = ir_value_code_addr(ep);
3119         stmt.o2.u1 = ir_value_code_addr(self->locals[i]);
3120         code_push_statement(&stmt, self->context.line);
3121     }
3122
3123     return true;
3124 }
3125
3126 static bool gen_global_function_code(ir_builder *ir, ir_value *global)
3127 {
3128     prog_section_function *fundef;
3129     ir_function           *irfun;
3130
3131     (void)ir;
3132
3133     irfun = global->constval.vfunc;
3134     if (!irfun) {
3135         if (global->cvq == CV_NONE) {
3136             irwarning(global->context, WARN_IMPLICIT_FUNCTION_POINTER,
3137                       "function `%s` has no body and in QC implicitly becomes a function-pointer", global->name);
3138         }
3139         /* this was a function pointer, don't generate code for those */
3140         return true;
3141     }
3142
3143     if (irfun->builtin)
3144         return true;
3145
3146     if (irfun->code_function_def < 0) {
3147         irerror(irfun->context, "`%s`: IR global wasn't generated, failed to access function-def", irfun->name);
3148         return false;
3149     }
3150     fundef = &code_functions[irfun->code_function_def];
3151
3152     fundef->entry = vec_size(code_statements);
3153     if (!gen_function_extparam_copy(irfun)) {
3154         irerror(irfun->context, "Failed to generate extparam-copy code for function %s", irfun->name);
3155         return false;
3156     }
3157     if (!gen_function_code(irfun)) {
3158         irerror(irfun->context, "Failed to generate code for function %s", irfun->name);
3159         return false;
3160     }
3161     return true;
3162 }
3163
3164 static void gen_vector_defs(prog_section_def def, const char *name)
3165 {
3166     char  *component;
3167     size_t len, i;
3168
3169     if (!name || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3170         return;
3171
3172     def.type = TYPE_FLOAT;
3173
3174     len = strlen(name);
3175
3176     component = (char*)mem_a(len+3);
3177     memcpy(component, name, len);
3178     len += 2;
3179     component[len-0] = 0;
3180     component[len-2] = '_';
3181
3182     component[len-1] = 'x';
3183
3184     for (i = 0; i < 3; ++i) {
3185         def.name = code_genstring(component);
3186         vec_push(code_defs, def);
3187         def.offset++;
3188         component[len-1]++;
3189     }
3190 }
3191
3192 static void gen_vector_fields(prog_section_field fld, const char *name)
3193 {
3194     char  *component;
3195     size_t len, i;
3196
3197     if (!name || OPTS_FLAG(SINGLE_VECTOR_DEFS))
3198         return;
3199
3200     fld.type = TYPE_FLOAT;
3201
3202     len = strlen(name);
3203
3204     component = (char*)mem_a(len+3);
3205     memcpy(component, name, len);
3206     len += 2;
3207     component[len-0] = 0;
3208     component[len-2] = '_';
3209
3210     component[len-1] = 'x';
3211
3212     for (i = 0; i < 3; ++i) {
3213         fld.name = code_genstring(component);
3214         vec_push(code_fields, fld);
3215         fld.offset++;
3216         component[len-1]++;
3217     }
3218 }
3219
3220 static bool ir_builder_gen_global(ir_builder *self, ir_value *global, bool islocal)
3221 {
3222     size_t           i;
3223     int32_t         *iptr;
3224     prog_section_def def;
3225
3226     def.type   = global->vtype;
3227     def.offset = vec_size(code_globals);
3228
3229     if (global->name) {
3230         if (global->name[0] == '#') {
3231             if (!self->str_immediate)
3232                 self->str_immediate = code_genstring("IMMEDIATE");
3233             def.name = global->code.name = self->str_immediate;
3234         }
3235         else
3236             def.name = global->code.name = code_genstring(global->name);
3237     }
3238     else
3239         def.name   = 0;
3240
3241     switch (global->vtype)
3242     {
3243     case TYPE_VOID:
3244         if (!strcmp(global->name, "end_sys_globals")) {
3245             /* TODO: remember this point... all the defs before this one
3246              * should be checksummed and added to progdefs.h when we generate it.
3247              */
3248         }
3249         else if (!strcmp(global->name, "end_sys_fields")) {
3250             /* TODO: same as above but for entity-fields rather than globsl
3251              */
3252         }
3253         else
3254             irwarning(global->context, WARN_VOID_VARIABLES, "unrecognized variable of type void `%s`",
3255                       global->name);
3256         /* I'd argue setting it to 0 is sufficient, but maybe some depend on knowing how far
3257          * the system fields actually go? Though the engine knows this anyway...
3258          * Maybe this could be an -foption
3259          * fteqcc creates data for end_sys_* - of size 1, so let's do the same
3260          */
3261         ir_value_code_setaddr(global, vec_size(code_globals));
3262         vec_push(code_globals, 0);
3263         /* Add the def */
3264         vec_push(code_defs, def);
3265         return true;
3266     case TYPE_POINTER:
3267         vec_push(code_defs, def);
3268         return gen_global_pointer(global);
3269     case TYPE_FIELD:
3270         vec_push(code_defs, def);
3271         gen_vector_defs(def, global->name);
3272         return gen_global_field(global);
3273     case TYPE_ENTITY:
3274         /* fall through */
3275     case TYPE_FLOAT:
3276     {
3277         ir_value_code_setaddr(global, vec_size(code_globals));
3278         if (global->hasvalue) {
3279             iptr = (int32_t*)&global->constval.ivec[0];
3280             vec_push(code_globals, *iptr);
3281         } else {
3282             vec_push(code_globals, 0);
3283         }
3284         if (!islocal && global->cvq != CV_CONST)
3285             def.type |= DEF_SAVEGLOBAL;
3286         vec_push(code_defs, def);
3287
3288         return global->code.globaladdr >= 0;
3289     }
3290     case TYPE_STRING:
3291     {
3292         ir_value_code_setaddr(global, vec_size(code_globals));
3293         if (global->hasvalue) {
3294             vec_push(code_globals, code_genstring(global->constval.vstring));
3295         } else {
3296             vec_push(code_globals, 0);
3297         }
3298         if (!islocal && global->cvq != CV_CONST)
3299             def.type |= DEF_SAVEGLOBAL;
3300         vec_push(code_defs, def);
3301         return global->code.globaladdr >= 0;
3302     }
3303     case TYPE_VECTOR:
3304     {
3305         size_t d;
3306         ir_value_code_setaddr(global, vec_size(code_globals));
3307         if (global->hasvalue) {
3308             iptr = (int32_t*)&global->constval.ivec[0];
3309             vec_push(code_globals, iptr[0]);
3310             if (global->code.globaladdr < 0)
3311                 return false;
3312             for (d = 1; d < type_sizeof[global->vtype]; ++d) {
3313                 vec_push(code_globals, iptr[d]);
3314             }
3315         } else {
3316             vec_push(code_globals, 0);
3317             if (global->code.globaladdr < 0)
3318                 return false;
3319             for (d = 1; d < type_sizeof[global->vtype]; ++d) {
3320                 vec_push(code_globals, 0);
3321             }
3322         }
3323         if (!islocal && global->cvq != CV_CONST)
3324             def.type |= DEF_SAVEGLOBAL;
3325
3326         vec_push(code_defs, def);
3327         def.type &= ~DEF_SAVEGLOBAL;
3328         gen_vector_defs(def, global->name);
3329         return global->code.globaladdr >= 0;
3330     }
3331     case TYPE_FUNCTION:
3332         ir_value_code_setaddr(global, vec_size(code_globals));
3333         if (!global->hasvalue) {
3334             vec_push(code_globals, 0);
3335             if (global->code.globaladdr < 0)
3336                 return false;
3337         } else {
3338             vec_push(code_globals, vec_size(code_functions));
3339             if (!gen_global_function(self, global))
3340                 return false;
3341         }
3342         if (!islocal && global->cvq != CV_CONST)
3343             def.type |= DEF_SAVEGLOBAL;
3344         vec_push(code_defs, def);
3345         return true;
3346     case TYPE_VARIANT:
3347         /* assume biggest type */
3348             ir_value_code_setaddr(global, vec_size(code_globals));
3349             vec_push(code_globals, 0);
3350             for (i = 1; i < type_sizeof[TYPE_VARIANT]; ++i)
3351                 vec_push(code_globals, 0);
3352             return true;
3353     default:
3354         /* refuse to create 'void' type or any other fancy business. */
3355         irerror(global->context, "Invalid type for global variable `%s`: %s",
3356                 global->name, type_name[global->vtype]);
3357         return false;
3358     }
3359 }
3360
3361 static void ir_builder_prepare_field(ir_value *field)
3362 {
3363     field->code.fieldaddr = code_alloc_field(type_sizeof[field->fieldtype]);
3364 }
3365
3366 static bool ir_builder_gen_field(ir_builder *self, ir_value *field)
3367 {
3368     prog_section_def def;
3369     prog_section_field fld;
3370
3371     (void)self;
3372
3373     def.type   = (uint16_t)field->vtype;
3374     def.offset = (uint16_t)vec_size(code_globals);
3375
3376     /* create a global named the same as the field */
3377     if (opts.standard == COMPILER_GMQCC) {
3378         /* in our standard, the global gets a dot prefix */
3379         size_t len = strlen(field->name);
3380         char name[1024];
3381
3382         /* we really don't want to have to allocate this, and 1024
3383          * bytes is more than enough for a variable/field name
3384          */
3385         if (len+2 >= sizeof(name)) {
3386             irerror(field->context, "invalid field name size: %u", (unsigned int)len);
3387             return false;
3388         }
3389
3390         name[0] = '.';
3391         memcpy(name+1, field->name, len); /* no strncpy - we used strlen above */
3392         name[len+1] = 0;
3393
3394         def.name = code_genstring(name);
3395         fld.name = def.name + 1; /* we reuse that string table entry */
3396     } else {
3397         /* in plain QC, there cannot be a global with the same name,
3398          * and so we also name the global the same.
3399          * FIXME: fteqcc should create a global as well
3400          * check if it actually uses the same name. Probably does
3401          */
3402         def.name = code_genstring(field->name);
3403         fld.name = def.name;
3404     }
3405
3406     field->code.name = def.name;
3407
3408     vec_push(code_defs, def);
3409
3410     fld.type = field->fieldtype;
3411
3412     if (fld.type == TYPE_VOID) {
3413         irerror(field->context, "field is missing a type: %s - don't know its size", field->name);
3414         return false;
3415     }
3416
3417     fld.offset = field->code.fieldaddr;
3418
3419     vec_push(code_fields, fld);
3420
3421     ir_value_code_setaddr(field, vec_size(code_globals));
3422     vec_push(code_globals, fld.offset);
3423     if (fld.type == TYPE_VECTOR) {
3424         vec_push(code_globals, fld.offset+1);
3425         vec_push(code_globals, fld.offset+2);
3426     }
3427
3428     if (field->fieldtype == TYPE_VECTOR) {
3429         gen_vector_defs(def, field->name);
3430         gen_vector_fields(fld, field->name);
3431     }
3432
3433     return field->code.globaladdr >= 0;
3434 }
3435
3436 bool ir_builder_generate(ir_builder *self, const char *filename)
3437 {
3438     prog_section_statement stmt;
3439     size_t i;
3440     char   *lnofile = NULL;
3441
3442     code_init();
3443
3444     for (i = 0; i < vec_size(self->fields); ++i)
3445     {
3446         ir_builder_prepare_field(self->fields[i]);
3447     }
3448
3449     for (i = 0; i < vec_size(self->globals); ++i)
3450     {
3451         if (!ir_builder_gen_global(self, self->globals[i], false)) {
3452             return false;
3453         }
3454     }
3455
3456     for (i = 0; i < vec_size(self->fields); ++i)
3457     {
3458         if (!ir_builder_gen_field(self, self->fields[i])) {
3459             return false;
3460         }
3461     }
3462
3463     /* generate function code */
3464     for (i = 0; i < vec_size(self->globals); ++i)
3465     {
3466         if (self->globals[i]->vtype == TYPE_FUNCTION) {
3467             if (!gen_global_function_code(self, self->globals[i])) {
3468                 return false;
3469             }
3470         }
3471     }
3472
3473     if (vec_size(code_globals) >= 65536) {
3474         irerror(vec_last(self->globals)->context, "This progs file would require more globals than the metadata can handle. Bailing out.");
3475         return false;
3476     }
3477
3478     /* DP errors if the last instruction is not an INSTR_DONE. */
3479     if (vec_last(code_statements).opcode != INSTR_DONE)
3480     {
3481         stmt.opcode = INSTR_DONE;
3482         stmt.o1.u1 = 0;
3483         stmt.o2.u1 = 0;
3484         stmt.o3.u1 = 0;
3485         code_push_statement(&stmt, vec_last(code_linenums));
3486     }
3487
3488     if (opts.pp_only)
3489         return true;
3490
3491     if (vec_size(code_statements) != vec_size(code_linenums)) {
3492         con_err("Linecounter wrong: %lu != %lu\n",
3493                 (unsigned long)vec_size(code_statements),
3494                 (unsigned long)vec_size(code_linenums));
3495     } else if (OPTS_FLAG(LNO)) {
3496         char *dot;
3497         size_t filelen = strlen(filename);
3498
3499         memcpy(vec_add(lnofile, filelen+1), filename, filelen+1);
3500         dot = strrchr(lnofile, '.');
3501         if (!dot) {
3502             vec_pop(lnofile);
3503         } else {
3504             vec_shrinkto(lnofile, dot - lnofile);
3505         }
3506         memcpy(vec_add(lnofile, 5), ".lno", 5);
3507     }
3508
3509     if (lnofile)
3510         con_out("writing '%s' and '%s'...\n", filename, lnofile);
3511     else
3512         con_out("writing '%s'\n", filename);
3513     if (!code_write(filename, lnofile)) {
3514         vec_free(lnofile);
3515         return false;
3516     }
3517     vec_free(lnofile);
3518     return true;
3519 }
3520
3521 /***********************************************************************
3522  *IR DEBUG Dump functions...
3523  */
3524
3525 #define IND_BUFSZ 1024
3526
3527 #ifdef WIN32
3528 # define strncat(dst, src, sz) strncat_s(dst, sz, src, _TRUNCATE)
3529 #endif
3530
3531 const char *qc_opname(int op)
3532 {
3533     if (op < 0) return "<INVALID>";
3534     if (op < (int)( sizeof(asm_instr) / sizeof(asm_instr[0]) ))
3535         return asm_instr[op].m;
3536     switch (op) {
3537         case VINSTR_PHI:  return "PHI";
3538         case VINSTR_JUMP: return "JUMP";
3539         case VINSTR_COND: return "COND";
3540         default:          return "<UNK>";
3541     }
3542 }
3543
3544 void ir_builder_dump(ir_builder *b, int (*oprintf)(const char*, ...))
3545 {
3546     size_t i;
3547     char indent[IND_BUFSZ];
3548     indent[0] = '\t';
3549     indent[1] = 0;
3550
3551     oprintf("module %s\n", b->name);
3552     for (i = 0; i < vec_size(b->globals); ++i)
3553     {
3554         oprintf("global ");
3555         if (b->globals[i]->hasvalue)
3556             oprintf("%s = ", b->globals[i]->name);
3557         ir_value_dump(b->globals[i], oprintf);
3558         oprintf("\n");
3559     }
3560     for (i = 0; i < vec_size(b->functions); ++i)
3561         ir_function_dump(b->functions[i], indent, oprintf);
3562     oprintf("endmodule %s\n", b->name);
3563 }
3564
3565 void ir_function_dump(ir_function *f, char *ind,
3566                       int (*oprintf)(const char*, ...))
3567 {
3568     size_t i;
3569     if (f->builtin != 0) {
3570         oprintf("%sfunction %s = builtin %i\n", ind, f->name, -f->builtin);
3571         return;
3572     }
3573     oprintf("%sfunction %s\n", ind, f->name);
3574     strncat(ind, "\t", IND_BUFSZ);
3575     if (vec_size(f->locals))
3576     {
3577         oprintf("%s%i locals:\n", ind, (int)vec_size(f->locals));
3578         for (i = 0; i < vec_size(f->locals); ++i) {
3579             oprintf("%s\t", ind);
3580             ir_value_dump(f->locals[i], oprintf);
3581             oprintf("\n");
3582         }
3583     }
3584     oprintf("%sliferanges:\n", ind);
3585     for (i = 0; i < vec_size(f->locals); ++i) {
3586         size_t l;
3587         ir_value *v = f->locals[i];
3588         oprintf("%s\t%s: %s@%i ", ind, v->name, (v->unique_life ? "unique " : ""), (int)v->code.local);
3589         for (l = 0; l < vec_size(v->life); ++l) {
3590             oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3591         }
3592         oprintf("\n");
3593     }
3594     for (i = 0; i < vec_size(f->values); ++i) {
3595         size_t l;
3596         ir_value *v = f->values[i];
3597         oprintf("%s\t%s: @%i ", ind, v->name, (int)v->code.local);
3598         for (l = 0; l < vec_size(v->life); ++l) {
3599             oprintf("[%i,%i] ", v->life[l].start, v->life[l].end);
3600         }
3601         oprintf("\n");
3602     }
3603     if (vec_size(f->blocks))
3604     {
3605         oprintf("%slife passes (check): %i\n", ind, (int)f->run_id);
3606         for (i = 0; i < vec_size(f->blocks); ++i) {
3607             if (f->blocks[i]->run_id != f->run_id) {
3608                 oprintf("%slife pass check fail! %i != %i\n", ind, (int)f->blocks[i]->run_id, (int)f->run_id);
3609             }
3610             ir_block_dump(f->blocks[i], ind, oprintf);
3611         }
3612
3613     }
3614     ind[strlen(ind)-1] = 0;
3615     oprintf("%sendfunction %s\n", ind, f->name);
3616 }
3617
3618 void ir_block_dump(ir_block* b, char *ind,
3619                    int (*oprintf)(const char*, ...))
3620 {
3621     size_t i;
3622     oprintf("%s:%s\n", ind, b->label);
3623     strncat(ind, "\t", IND_BUFSZ);
3624
3625     for (i = 0; i < vec_size(b->instr); ++i)
3626         ir_instr_dump(b->instr[i], ind, oprintf);
3627     ind[strlen(ind)-1] = 0;
3628 }
3629
3630 void dump_phi(ir_instr *in, int (*oprintf)(const char*, ...))
3631 {
3632     size_t i;
3633     oprintf("%s <- phi ", in->_ops[0]->name);
3634     for (i = 0; i < vec_size(in->phi); ++i)
3635     {
3636         oprintf("([%s] : %s) ", in->phi[i].from->label,
3637                                 in->phi[i].value->name);
3638     }
3639     oprintf("\n");
3640 }
3641
3642 void ir_instr_dump(ir_instr *in, char *ind,
3643                        int (*oprintf)(const char*, ...))
3644 {
3645     size_t i;
3646     const char *comma = NULL;
3647
3648     oprintf("%s (%i) ", ind, (int)in->eid);
3649
3650     if (in->opcode == VINSTR_PHI) {
3651         dump_phi(in, oprintf);
3652         return;
3653     }
3654
3655     strncat(ind, "\t", IND_BUFSZ);
3656
3657     if (in->_ops[0] && (in->_ops[1] || in->_ops[2])) {
3658         ir_value_dump(in->_ops[0], oprintf);
3659         if (in->_ops[1] || in->_ops[2])
3660             oprintf(" <- ");
3661     }
3662     if (in->opcode == INSTR_CALL0) {
3663         oprintf("CALL%i\t", vec_size(in->params));
3664     } else
3665         oprintf("%s\t", qc_opname(in->opcode));
3666
3667     if (in->_ops[0] && !(in->_ops[1] || in->_ops[2])) {
3668         ir_value_dump(in->_ops[0], oprintf);
3669         comma = ",\t";
3670     }
3671     else
3672     {
3673         for (i = 1; i != 3; ++i) {
3674             if (in->_ops[i]) {
3675                 if (comma)
3676                     oprintf(comma);
3677                 ir_value_dump(in->_ops[i], oprintf);
3678                 comma = ",\t";
3679             }
3680         }
3681     }
3682     if (in->bops[0]) {
3683         if (comma)
3684             oprintf(comma);
3685         oprintf("[%s]", in->bops[0]->label);
3686         comma = ",\t";
3687     }
3688     if (in->bops[1])
3689         oprintf("%s[%s]", comma, in->bops[1]->label);
3690     if (vec_size(in->params)) {
3691         oprintf("\tparams: ");
3692         for (i = 0; i != vec_size(in->params); ++i) {
3693             oprintf("%s, ", in->params[i]->name);
3694         }
3695     }
3696     oprintf("\n");
3697     ind[strlen(ind)-1] = 0;
3698 }
3699
3700 void ir_value_dump_string(const char *str, int (*oprintf)(const char*, ...))
3701 {
3702     oprintf("\"");
3703     for (; *str; ++str) {
3704         switch (*str) {
3705             case '\n': oprintf("\\n"); break;
3706             case '\r': oprintf("\\r"); break;
3707             case '\t': oprintf("\\t"); break;
3708             case '\v': oprintf("\\v"); break;
3709             case '\f': oprintf("\\f"); break;
3710             case '\b': oprintf("\\b"); break;
3711             case '\a': oprintf("\\a"); break;
3712             case '\\': oprintf("\\\\"); break;
3713             case '"': oprintf("\\\""); break;
3714             default: oprintf("%c", *str); break;
3715         }
3716     }
3717     oprintf("\"");
3718 }
3719
3720 void ir_value_dump(ir_value* v, int (*oprintf)(const char*, ...))
3721 {
3722     if (v->hasvalue) {
3723         switch (v->vtype) {
3724             default:
3725             case TYPE_VOID:
3726                 oprintf("(void)");
3727                 break;
3728             case TYPE_FUNCTION:
3729                 oprintf("fn:%s", v->name);
3730                 break;
3731             case TYPE_FLOAT:
3732                 oprintf("%g", v->constval.vfloat);
3733                 break;
3734             case TYPE_VECTOR:
3735                 oprintf("'%g %g %g'",
3736                         v->constval.vvec.x,
3737                         v->constval.vvec.y,
3738                         v->constval.vvec.z);
3739                 break;
3740             case TYPE_ENTITY:
3741                 oprintf("(entity)");
3742                 break;
3743             case TYPE_STRING:
3744                 ir_value_dump_string(v->constval.vstring, oprintf);
3745                 break;
3746 #if 0
3747             case TYPE_INTEGER:
3748                 oprintf("%i", v->constval.vint);
3749                 break;
3750 #endif
3751             case TYPE_POINTER:
3752                 oprintf("&%s",
3753                     v->constval.vpointer->name);
3754                 break;
3755         }
3756     } else {
3757         oprintf("%s", v->name);
3758     }
3759 }
3760
3761 void ir_value_dump_life(const ir_value *self, int (*oprintf)(const char*,...))
3762 {
3763     size_t i;
3764     oprintf("Life of %12s:", self->name);
3765     for (i = 0; i < vec_size(self->life); ++i)
3766     {
3767         oprintf(" + [%i, %i]\n", self->life[i].start, self->life[i].end);
3768     }
3769 }