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