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