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