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