]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ast.cpp
ast conversion mostly finished
[xonotic/gmqcc.git] / ast.cpp
1 #include <new>
2
3 #include <stdlib.h>
4 #include <string.h>
5
6 #include "gmqcc.h"
7 #include "ast.h"
8 #include "fold.h"
9 //#include "parser.h"
10
11 #include "algo.h"
12
13 /* Initialize main ast node aprts */
14 ast_node::ast_node(lex_ctx_t ctx, int node_type)
15     : m_context(ctx)
16     , m_node_type(node_type)
17     , m_keep_node(false)
18     , m_side_effects(false)
19 {
20 }
21
22 ast_node::~ast_node()
23 {
24 }
25
26 /* weight and side effects */
27 void ast_node::propagateSideEffects(ast_node *other) const
28 {
29     other->m_side_effects = m_side_effects;
30 }
31
32 /* General expression initialization */
33 ast_expression::ast_expression(lex_ctx_t ctx, int nodetype, qc_type type)
34     : ast_node(ctx, nodetype)
35     , m_vtype(type)
36 {
37     if (OPTS_OPTION_BOOL(OPTION_COVERAGE))
38         m_flags |= AST_FLAG_BLOCK_COVERAGE;
39 }
40 ast_expression::ast_expression(lex_ctx_t ctx, int nodetype)
41     : ast_expression(ctx, nodetype, TYPE_VOID)
42 {}
43
44 ast_expression::~ast_expression()
45 {
46     if (m_next)
47         delete m_next;
48     if (m_varparam)
49         delete m_varparam;
50 }
51
52 ast_expression::ast_expression(ast_copy_type_t, const ast_expression &other)
53     : ast_expression(ast_copy_type, other.m_context, other)
54 {}
55
56 ast_expression::ast_expression(ast_copy_type_t, lex_ctx_t ctx, const ast_expression &other)
57     : ast_expression(ast_copy_type, TYPE_ast_expression, ctx, other)
58 {}
59
60 ast_expression::ast_expression(ast_copy_type_t, int nodetype, const ast_expression &other)
61     : ast_expression(ast_copy_type, nodetype, other.m_context, other)
62 {}
63
64 ast_expression::ast_expression(ast_copy_type_t, int nodetype, lex_ctx_t ctx, const ast_expression &other)
65     : ast_expression(ctx, nodetype)
66 {
67     m_vtype = other.m_vtype;
68     m_count = other.m_count;
69     m_flags = other.m_flags;
70     if (other.m_next)
71         m_next = new ast_expression(ast_copy_type, *other.m_next);
72     m_type_params.reserve(other.m_type_params.size());
73     for (auto &it : other.m_type_params)
74         m_type_params.emplace_back(new ast_value(ast_copy_type, *it));
75 }
76
77
78 ast_expression *ast_expression::shallowType(lex_ctx_t ctx, qc_type vtype) {
79     auto expr = new ast_expression(ctx, TYPE_ast_expression);
80     expr->m_vtype = vtype;
81     return expr;
82 }
83
84 void ast_expression::adoptType(const ast_expression &other)
85 {
86     m_vtype = other.m_vtype;
87     if (other.m_next)
88         m_next = new ast_expression(ast_copy_type, *other.m_next);
89     m_count = other.m_count;
90     m_flags = other.m_flags;
91     m_type_params.clear();
92     m_type_params.reserve(other.m_type_params.size());
93     for (auto &it : other.m_type_params)
94         m_type_params.emplace_back(new ast_value(ast_copy_type, *it));
95 }
96
97 bool ast_expression::compareType(const ast_expression &other) const
98 {
99     if (m_vtype == TYPE_NIL ||
100         other.m_vtype == TYPE_NIL)
101         return true;
102     if (m_vtype != other.m_vtype)
103         return false;
104     if (!m_next != !other.m_next)
105         return false;
106     if (m_type_params.size() != other.m_type_params.size())
107         return false;
108     if ((m_flags & AST_FLAG_TYPE_MASK) !=
109         (other.m_flags & AST_FLAG_TYPE_MASK) )
110     {
111         return false;
112     }
113     if (m_type_params.size()) {
114         size_t i;
115         for (i = 0; i < m_type_params.size(); ++i) {
116             if (!m_type_params[i]->compareType(*other.m_type_params[i]))
117                 return false;
118         }
119     }
120     if (m_next)
121         return m_next->compareType(*other.m_next);
122     return true;
123 }
124
125 bool ast_expression::codegen(ast_function*, bool, ir_value**) {
126     compile_error(m_context, "ast_expression::codegen called!");
127     abort();
128     return false;
129 }
130
131 ast_value::ast_value(ast_copy_type_t, const ast_value &other, const std::string &name)
132     : ast_value(ast_copy_type, static_cast<const ast_expression&>(other), name)
133 {
134     m_keep_node = true; // keep values, always
135     memset(&m_constval, 0, sizeof(m_constval));
136 }
137
138 ast_value::ast_value(ast_copy_type_t, const ast_value &other)
139     : ast_value(ast_copy_type, static_cast<const ast_expression&>(other), other.m_name)
140 {
141     m_keep_node = true; // keep values, always
142     memset(&m_constval, 0, sizeof(m_constval));
143 }
144
145 ast_value::ast_value(ast_copy_type_t, const ast_expression &other, const std::string &name)
146     : ast_expression(ast_copy_type, TYPE_ast_value, other)
147     , m_name(name)
148 {
149     m_keep_node = true; // keep values, always
150     memset(&m_constval, 0, sizeof(m_constval));
151 }
152
153 ast_value::ast_value(lex_ctx_t ctx, const std::string &name, qc_type t)
154     : ast_expression(ctx, TYPE_ast_value, t)
155     , m_name(name)
156 {
157     m_keep_node = true; // keep values, always
158     memset(&m_constval, 0, sizeof(m_constval));
159 }
160
161 ast_value::~ast_value()
162 {
163     if (m_argcounter)
164         mem_d((void*)m_argcounter);
165     if (m_hasvalue) {
166         switch (m_vtype)
167         {
168         case TYPE_STRING:
169             mem_d((void*)m_constval.vstring);
170             break;
171         case TYPE_FUNCTION:
172             // unlink us from the function node
173             m_constval.vfunc->m_function_type = nullptr;
174             break;
175         // NOTE: delete function? currently collected in
176         // the parser structure
177         default:
178             break;
179         }
180     }
181
182     // initlist imples an array which implies .next in the expression exists.
183     if (m_initlist.size() && m_next->m_vtype == TYPE_STRING) {
184         for (auto &it : m_initlist)
185             if (it.vstring)
186                 mem_d(it.vstring);
187     }
188 }
189
190 static size_t ast_type_to_string_impl(const ast_expression *e, char *buf, size_t bufsize, size_t pos)
191 {
192     const char *typestr;
193     size_t typelen;
194     size_t i;
195
196     if (!e) {
197         if (pos + 6 >= bufsize)
198             goto full;
199         util_strncpy(buf + pos, "(null)", 6);
200         return pos + 6;
201     }
202
203     if (pos + 1 >= bufsize)
204         goto full;
205
206     switch (e->m_vtype) {
207         case TYPE_VARIANT:
208             util_strncpy(buf + pos, "(variant)", 9);
209             return pos + 9;
210
211         case TYPE_FIELD:
212             buf[pos++] = '.';
213             return ast_type_to_string_impl(e->m_next, buf, bufsize, pos);
214
215         case TYPE_POINTER:
216             if (pos + 3 >= bufsize)
217                 goto full;
218             buf[pos++] = '*';
219             buf[pos++] = '(';
220             pos = ast_type_to_string_impl(e->m_next, buf, bufsize, pos);
221             if (pos + 1 >= bufsize)
222                 goto full;
223             buf[pos++] = ')';
224             return pos;
225
226         case TYPE_FUNCTION:
227             pos = ast_type_to_string_impl(e->m_next, buf, bufsize, pos);
228             if (pos + 2 >= bufsize)
229                 goto full;
230             if (e->m_type_params.empty()) {
231                 buf[pos++] = '(';
232                 buf[pos++] = ')';
233                 return pos;
234             }
235             buf[pos++] = '(';
236             pos = ast_type_to_string_impl(e->m_type_params[0].get(), buf, bufsize, pos);
237             for (i = 1; i < e->m_type_params.size(); ++i) {
238                 if (pos + 2 >= bufsize)
239                     goto full;
240                 buf[pos++] = ',';
241                 buf[pos++] = ' ';
242                 pos = ast_type_to_string_impl(e->m_type_params[i].get(), buf, bufsize, pos);
243             }
244             if (pos + 1 >= bufsize)
245                 goto full;
246             buf[pos++] = ')';
247             return pos;
248
249         case TYPE_ARRAY:
250             pos = ast_type_to_string_impl(e->m_next, buf, bufsize, pos);
251             if (pos + 1 >= bufsize)
252                 goto full;
253             buf[pos++] = '[';
254             pos += util_snprintf(buf + pos, bufsize - pos - 1, "%i", (int)e->m_count);
255             if (pos + 1 >= bufsize)
256                 goto full;
257             buf[pos++] = ']';
258             return pos;
259
260         default:
261             typestr = type_name[e->m_vtype];
262             typelen = strlen(typestr);
263             if (pos + typelen >= bufsize)
264                 goto full;
265             util_strncpy(buf + pos, typestr, typelen);
266             return pos + typelen;
267     }
268
269 full:
270     buf[bufsize-3] = '.';
271     buf[bufsize-2] = '.';
272     buf[bufsize-1] = '.';
273     return bufsize;
274 }
275
276 void ast_type_to_string(const ast_expression *e, char *buf, size_t bufsize)
277 {
278     size_t pos = ast_type_to_string_impl(e, buf, bufsize-1, 0);
279     buf[pos] = 0;
280 }
281
282 void ast_value::addParam(ast_value *p)
283 {
284     m_type_params.emplace_back(p);
285 }
286
287 ast_binary::ast_binary(lex_ctx_t ctx, int op,
288                        ast_expression* left, ast_expression* right)
289     : ast_expression(ctx, TYPE_ast_binary)
290     , m_op(op)
291     // m_left/m_right happen after the peephole step right below
292     , m_right_first(false)
293 {
294     if (ast_istype(right, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
295         ast_unary      *unary  = ((ast_unary*)right);
296         ast_expression *normal = unary->m_operand;
297
298         /* make a-(-b) => a + b */
299         if (unary->m_op == VINSTR_NEG_F || unary->m_op == VINSTR_NEG_V) {
300             if (op == INSTR_SUB_F) {
301                 op = INSTR_ADD_F;
302                 right = normal;
303                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
304             } else if (op == INSTR_SUB_V) {
305                 op = INSTR_ADD_V;
306                 right = normal;
307                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
308             }
309         }
310     }
311
312     m_left = left;
313     m_right = right;
314
315     propagateSideEffects(left);
316     propagateSideEffects(right);
317
318     if (op >= INSTR_EQ_F && op <= INSTR_GT)
319         m_vtype = TYPE_FLOAT;
320     else if (op == INSTR_AND || op == INSTR_OR) {
321         if (OPTS_FLAG(PERL_LOGIC))
322             adoptType(*right);
323         else
324             m_vtype = TYPE_FLOAT;
325     }
326     else if (op == INSTR_BITAND || op == INSTR_BITOR)
327         m_vtype = TYPE_FLOAT;
328     else if (op == INSTR_MUL_VF || op == INSTR_MUL_FV)
329         m_vtype = TYPE_VECTOR;
330     else if (op == INSTR_MUL_V)
331         m_vtype = TYPE_FLOAT;
332     else
333         m_vtype = left->m_vtype;
334
335     // references all
336     m_refs = AST_REF_ALL;
337 }
338
339 ast_binary::~ast_binary()
340 {
341     if (m_refs & AST_REF_LEFT)  ast_unref(m_left);
342     if (m_refs & AST_REF_RIGHT) ast_unref(m_right);
343 }
344
345 ast_binstore::ast_binstore(lex_ctx_t ctx, int storop, int mathop,
346                            ast_expression* left, ast_expression* right)
347     : ast_expression(ctx, TYPE_ast_binstore)
348     , m_opstore(storop)
349     , m_opbin(mathop)
350     , m_dest(left)
351     , m_source(right)
352     , m_keep_dest(false)
353 {
354     m_side_effects = true;
355     adoptType(*left);
356 }
357
358 ast_binstore::~ast_binstore()
359 {
360     if (!m_keep_dest)
361         ast_unref(m_dest);
362     ast_unref(m_source);
363 }
364
365 ast_unary* ast_unary::make(lex_ctx_t ctx, int op, ast_expression *expr)
366 {
367     if (ast_istype(expr, ast_unary) && OPTS_OPTIMIZATION(OPTIM_PEEPHOLE)) {
368         ast_unary *prev = (ast_unary*)((ast_unary*)expr)->m_operand;
369
370         /* Handle for double negation */
371         if (((ast_unary*)expr)->m_op == op)
372             prev = (ast_unary*)((ast_unary*)expr)->m_operand;
373
374         if (ast_istype(prev, ast_unary)) {
375             ++opts_optimizationcount[OPTIM_PEEPHOLE];
376             return prev;
377         }
378     }
379
380     return new ast_unary(ctx, op, expr);
381 }
382
383 ast_unary::ast_unary(lex_ctx_t ctx, int op, ast_expression *expr)
384     : ast_expression(ctx, TYPE_ast_unary)
385     , m_op(op)
386     , m_operand(expr)
387 {
388     propagateSideEffects(expr);
389     if ((op >= INSTR_NOT_F && op <= INSTR_NOT_FNC) || op == VINSTR_NEG_F) {
390         m_vtype = TYPE_FLOAT;
391     } else if (op == VINSTR_NEG_V) {
392         m_vtype = TYPE_VECTOR;
393     } else {
394         compile_error(ctx, "cannot determine type of unary operation %s", util_instr_str[op]);
395     }
396 }
397
398 ast_unary::~ast_unary()
399 {
400     if (m_operand)
401         ast_unref(m_operand);
402 }
403
404 ast_return::ast_return(lex_ctx_t ctx, ast_expression *expr)
405     : ast_expression(ctx, TYPE_ast_return)
406     , m_operand(expr)
407 {
408     if (expr)
409         propagateSideEffects(expr);
410 }
411
412 ast_return::~ast_return()
413 {
414     if (m_operand)
415         ast_unref(m_operand);
416 }
417
418 ast_entfield::ast_entfield(lex_ctx_t ctx, ast_expression *entity, ast_expression *field)
419     : ast_entfield(ctx, entity, field, field->m_next)
420 {
421     if (field->m_vtype != TYPE_FIELD)
422         compile_error(ctx, "ast_entfield with expression not of type field");
423 }
424
425 ast_entfield::ast_entfield(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype)
426     : ast_expression(ctx, TYPE_ast_entfield)
427     , m_entity(entity)
428     , m_field(field)
429 {
430     propagateSideEffects(m_entity);
431     propagateSideEffects(m_field);
432
433     if (!outtype) {
434         compile_error(ctx, "ast_entfield: field has no type");
435         m_vtype = TYPE_VOID;
436     }
437     else
438         adoptType(*outtype);
439 }
440
441 ast_entfield::~ast_entfield()
442 {
443     ast_unref(m_entity);
444     ast_unref(m_field);
445 }
446
447 ast_member *ast_member::make(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const std::string &name)
448 {
449     if (field >= 3) {
450         compile_error(ctx, "ast_member: invalid field (>=3): %u", field);
451         return nullptr;
452     }
453     if (owner->m_vtype != TYPE_VECTOR &&
454         owner->m_vtype != TYPE_FIELD)
455     {
456         compile_error(ctx, "member-access on an invalid owner of type %s", type_name[owner->m_vtype]);
457         return nullptr;
458     }
459     return new ast_member(ctx, owner, field, name);
460 }
461
462 ast_member::ast_member(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const std::string &name)
463     : ast_expression(ctx, TYPE_ast_member)
464     , m_owner(owner)
465     , m_field(field)
466     , m_name(name)
467     , m_rvalue(false)
468 {
469     m_keep_node = true;
470
471     if (m_owner->m_vtype == TYPE_VECTOR) {
472         m_vtype = TYPE_FLOAT;
473         m_next  = nullptr;
474     } else {
475         m_vtype = TYPE_FIELD;
476         m_next = ast_expression::shallowType(ctx, TYPE_FLOAT);
477     }
478
479     propagateSideEffects(owner);
480 }
481
482 ast_member::~ast_member()
483 {
484     // The owner is always an ast_value, which has .keep_node=true,
485     // also: ast_members are usually deleted after the owner, thus
486     // this will cause invalid access
487         //ast_unref(self->m_owner);
488     // once we allow (expression).x to access a vector-member, we need
489     // to change this: preferably by creating an alternate ast node for this
490     // purpose that is not garbage-collected.
491 }
492
493 ast_array_index* ast_array_index::make(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
494 {
495     ast_expression *outtype = array->m_next;
496     if (!outtype) {
497         // field has no type
498         return nullptr;
499     }
500
501     return new ast_array_index(ctx, array, index);
502 }
503
504 ast_array_index::ast_array_index(lex_ctx_t ctx, ast_expression *array, ast_expression *index)
505     : ast_expression(ctx, TYPE_ast_array_index)
506     , m_array(array)
507     , m_index(index)
508 {
509     propagateSideEffects(array);
510     propagateSideEffects(index);
511
512     ast_expression *outtype = m_array->m_next;
513     adoptType(*outtype);
514
515     if (array->m_vtype == TYPE_FIELD && outtype->m_vtype == TYPE_ARRAY) {
516         // FIXME: investigate - this is not possible after adoptType
517         //if (m_vtype != TYPE_ARRAY) {
518         //    compile_error(self->m_context, "array_index node on type");
519         //    ast_array_index_delete(self);
520         //    return nullptr;
521         //}
522
523         m_array = outtype;
524         m_vtype = TYPE_FIELD;
525     }
526 }
527
528 ast_array_index::~ast_array_index()
529 {
530     if (m_array)
531         ast_unref(m_array);
532     if (m_index)
533         ast_unref(m_index);
534 }
535
536 ast_argpipe::ast_argpipe(lex_ctx_t ctx, ast_expression *index)
537     : ast_expression(ctx, TYPE_ast_argpipe)
538     , m_index(index)
539 {
540     m_vtype = TYPE_NOEXPR;
541 }
542
543 ast_argpipe::~ast_argpipe()
544 {
545     if (m_index)
546         ast_unref(m_index);
547 }
548
549 ast_store::ast_store(lex_ctx_t ctx, int op, ast_expression *dest, ast_expression *source)
550     : ast_expression(ctx, TYPE_ast_store)
551     , m_op(op)
552     , m_dest(dest)
553     , m_source(source)
554 {
555     m_side_effects = true;
556     adoptType(*dest);
557 }
558
559 ast_store::~ast_store()
560 {
561     ast_unref(m_dest);
562     ast_unref(m_source);
563 }
564
565 ast_ifthen::ast_ifthen(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
566     : ast_expression(ctx, TYPE_ast_ifthen)
567     , m_cond(cond)
568     , m_on_true(ontrue)
569     , m_on_false(onfalse)
570 {
571     propagateSideEffects(cond);
572     if (ontrue)
573         propagateSideEffects(ontrue);
574     if (onfalse)
575         propagateSideEffects(onfalse);
576 }
577
578 ast_ifthen::~ast_ifthen()
579 {
580     ast_unref(m_cond);
581     if (m_on_true)
582         ast_unref(m_on_true);
583     if (m_on_false)
584         ast_unref(m_on_false);
585 }
586
587 ast_ternary::ast_ternary(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
588     : ast_expression(ctx, TYPE_ast_ternary)
589     , m_cond(cond)
590     , m_on_true(ontrue)
591     , m_on_false(onfalse)
592 {
593     propagateSideEffects(cond);
594     propagateSideEffects(ontrue);
595     propagateSideEffects(onfalse);
596
597     if (ontrue->m_vtype == TYPE_NIL)
598         adoptType(*onfalse);
599     else
600         adoptType(*ontrue);
601 }
602
603 ast_ternary::~ast_ternary()
604 {
605     /* the if()s are only there because computed-gotos can set them
606      * to nullptr
607      */
608     if (m_cond)     ast_unref(m_cond);
609     if (m_on_true)  ast_unref(m_on_true);
610     if (m_on_false) ast_unref(m_on_false);
611 }
612
613 ast_loop::ast_loop(lex_ctx_t ctx,
614                    ast_expression *initexpr,
615                    ast_expression *precond, bool pre_not,
616                    ast_expression *postcond, bool post_not,
617                    ast_expression *increment,
618                    ast_expression *body)
619     : ast_expression(ctx, TYPE_ast_loop)
620     , m_initexpr(initexpr)
621     , m_precond(precond)
622     , m_postcond(postcond)
623     , m_increment(increment)
624     , m_body(body)
625     , m_pre_not(pre_not)
626     , m_post_not(post_not)
627 {
628     if (initexpr)
629         propagateSideEffects(initexpr);
630     if (precond)
631         propagateSideEffects(precond);
632     if (postcond)
633         propagateSideEffects(postcond);
634     if (increment)
635         propagateSideEffects(increment);
636     if (body)
637         propagateSideEffects(body);
638 }
639
640 ast_loop::~ast_loop()
641 {
642     if (m_initexpr)
643         ast_unref(m_initexpr);
644     if (m_precond)
645         ast_unref(m_precond);
646     if (m_postcond)
647         ast_unref(m_postcond);
648     if (m_increment)
649         ast_unref(m_increment);
650     if (m_body)
651         ast_unref(m_body);
652 }
653
654 ast_breakcont::ast_breakcont(lex_ctx_t ctx, bool iscont, unsigned int levels)
655     : ast_expression(ctx, TYPE_ast_breakcont)
656     , m_is_continue(iscont)
657     , m_levels(levels)
658 {
659 }
660
661 ast_breakcont::~ast_breakcont()
662 {
663 }
664
665 ast_switch::ast_switch(lex_ctx_t ctx, ast_expression *op)
666     : ast_expression(ctx, TYPE_ast_switch)
667     , m_operand(op)
668 {
669     propagateSideEffects(op);
670 }
671
672 ast_switch::~ast_switch()
673 {
674     ast_unref(m_operand);
675
676     for (auto &it : m_cases) {
677         if (it.m_value)
678             ast_unref(it.m_value);
679         ast_unref(it.m_code);
680     }
681 }
682
683 ast_label::ast_label(lex_ctx_t ctx, const std::string &name, bool undefined)
684     : ast_expression(ctx, TYPE_ast_label)
685     , m_name(name)
686     , m_irblock(nullptr)
687     , m_undefined(undefined)
688 {
689     m_vtype = TYPE_NOEXPR;
690 }
691
692 ast_label::~ast_label()
693 {
694 }
695
696 void ast_label::registerGoto(ast_goto *g)
697 {
698    m_gotos.push_back(g);
699 }
700
701 ast_goto::ast_goto(lex_ctx_t ctx, const std::string &name)
702     : ast_expression(ctx, TYPE_ast_goto)
703     , m_name(name)
704     , m_target(nullptr)
705     , m_irblock_from(nullptr)
706 {
707 }
708
709 ast_goto::~ast_goto()
710 {
711 }
712
713 void ast_goto::setLabel(ast_label *label)
714 {
715     m_target = label;
716 }
717
718 ast_state::ast_state(lex_ctx_t ctx, ast_expression *frame, ast_expression *think)
719     : ast_expression(ctx, TYPE_ast_expression)
720     , m_framenum(frame)
721     , m_nextthink(think)
722 {
723 }
724
725 ast_state::~ast_state()
726 {
727     if (m_framenum)
728         ast_unref(m_framenum);
729     if (m_nextthink)
730         ast_unref(m_nextthink);
731 }
732
733 ast_call *ast_call::make(lex_ctx_t ctx, ast_expression *funcexpr)
734 {
735     if (!funcexpr->m_next) {
736         compile_error(ctx, "not a function");
737         return nullptr;
738     }
739     return new ast_call(ctx, funcexpr);
740 }
741
742 ast_call::ast_call(lex_ctx_t ctx, ast_expression *funcexpr)
743     : ast_expression(ctx, TYPE_ast_call)
744     , m_func(funcexpr)
745     , m_va_count(nullptr)
746 {
747     m_side_effects = true;
748     adoptType(*funcexpr->m_next);
749 }
750
751 ast_call::~ast_call()
752 {
753     for (auto &it : m_params)
754         ast_unref(it);
755
756     if (m_func)
757         ast_unref(m_func);
758
759     if (m_va_count)
760         ast_unref(m_va_count);
761 }
762
763 bool ast_call::checkVararg(ast_expression *va_type, ast_expression *exp_type) const
764 {
765     char texp[1024];
766     char tgot[1024];
767     if (!exp_type)
768         return true;
769     if (!va_type || !va_type->compareType(*exp_type))
770     {
771         if (va_type && exp_type)
772         {
773             ast_type_to_string(va_type,  tgot, sizeof(tgot));
774             ast_type_to_string(exp_type, texp, sizeof(texp));
775             if (OPTS_FLAG(UNSAFE_VARARGS)) {
776                 if (compile_warning(m_context, WARN_UNSAFE_TYPES,
777                                     "piped variadic argument differs in type: constrained to type %s, expected type %s",
778                                     tgot, texp))
779                     return false;
780             } else {
781                 compile_error(m_context,
782                               "piped variadic argument differs in type: constrained to type %s, expected type %s",
783                               tgot, texp);
784                 return false;
785             }
786         }
787         else
788         {
789             ast_type_to_string(exp_type, texp, sizeof(texp));
790             if (OPTS_FLAG(UNSAFE_VARARGS)) {
791                 if (compile_warning(m_context, WARN_UNSAFE_TYPES,
792                                     "piped variadic argument may differ in type: expected type %s",
793                                     texp))
794                     return false;
795             } else {
796                 compile_error(m_context,
797                               "piped variadic argument may differ in type: expected type %s",
798                               texp);
799                 return false;
800             }
801         }
802     }
803     return true;
804 }
805
806 bool ast_call::checkTypes(ast_expression *va_type) const
807 {
808     char texp[1024];
809     char tgot[1024];
810     size_t i;
811     bool retval = true;
812
813     size_t count = m_params.size();
814     if (count > m_func->m_type_params.size())
815         count = m_func->m_type_params.size();
816
817     for (i = 0; i < count; ++i) {
818         if (ast_istype(m_params[i], ast_argpipe)) {
819             /* warn about type safety instead */
820             if (i+1 != count) {
821                 compile_error(m_context, "argpipe must be the last parameter to a function call");
822                 return false;
823             }
824             if (!checkVararg(va_type, m_func->m_type_params[i].get()))
825                 retval = false;
826         }
827         else if (!m_params[i]->compareType(*m_func->m_type_params[i]))
828         {
829             ast_type_to_string(m_params[i], tgot, sizeof(tgot));
830             ast_type_to_string(m_func->m_type_params[i].get(), texp, sizeof(texp));
831             compile_error(m_context, "invalid type for parameter %u in function call: expected %s, got %s",
832                      (unsigned int)(i+1), texp, tgot);
833             /* we don't immediately return */
834             retval = false;
835         }
836     }
837     count = m_params.size();
838     if (count > m_func->m_type_params.size() && m_func->m_varparam) {
839         for (; i < count; ++i) {
840             if (ast_istype(m_params[i], ast_argpipe)) {
841                 /* warn about type safety instead */
842                 if (i+1 != count) {
843                     compile_error(m_context, "argpipe must be the last parameter to a function call");
844                     return false;
845                 }
846                 if (!checkVararg(va_type, m_func->m_varparam))
847                     retval = false;
848             }
849             else if (!m_params[i]->compareType(*m_func->m_varparam))
850             {
851                 ast_type_to_string(m_params[i], tgot, sizeof(tgot));
852                 ast_type_to_string(m_func->m_varparam, texp, sizeof(texp));
853                 compile_error(m_context, "invalid type for variadic parameter %u in function call: expected %s, got %s",
854                          (unsigned int)(i+1), texp, tgot);
855                 /* we don't immediately return */
856                 retval = false;
857             }
858         }
859     }
860     return retval;
861 }
862
863 ast_block::ast_block(lex_ctx_t ctx)
864     : ast_expression(ctx, TYPE_ast_block)
865 {
866 }
867
868 ast_block::~ast_block()
869 {
870     for (auto &it : m_exprs) ast_unref(it);
871     for (auto &it : m_locals) delete it;
872     for (auto &it : m_collect) delete it;
873 }
874
875 void ast_block::setType(const ast_expression &from)
876 {
877     if (m_next)
878         delete m_next;
879     adoptType(from);
880 }
881
882
883 bool ast_block::addExpr(ast_expression *e)
884 {
885     propagateSideEffects(e);
886     m_exprs.push_back(e);
887     if (m_next) {
888         delete m_next;
889         m_next = nullptr;
890     }
891     adoptType(*e);
892     return true;
893 }
894
895 void ast_block::collect(ast_expression *expr)
896 {
897     m_collect.push_back(expr);
898     expr->m_keep_node = true;
899 }
900
901 ast_function *ast_function::make(lex_ctx_t ctx, const std::string &name, ast_value *vtype)
902 {
903     if (!vtype) {
904         compile_error(ctx, "internal error: ast_function_new condition 0");
905         return nullptr;
906     } else if (vtype->m_hasvalue || vtype->m_vtype != TYPE_FUNCTION) {
907         compile_error(ctx, "internal error: ast_function_new condition %i %i type=%i (probably 2 bodies?)",
908                  (int)!vtype,
909                  (int)vtype->m_hasvalue,
910                  vtype->m_vtype);
911         return nullptr;
912     }
913     return new ast_function(ctx, name, vtype);
914 }
915
916 ast_function::ast_function(lex_ctx_t ctx, const std::string &name, ast_value *vtype)
917     : ast_node(ctx, TYPE_ast_function)
918     , m_function_type(vtype)
919     , m_name(name)
920     , m_builtin(0)
921     , m_static_count(0)
922     , m_ir_func(nullptr)
923     , m_curblock(nullptr)
924     , m_labelcount(0)
925     , m_varargs(nullptr)
926     , m_argc(nullptr)
927     , m_fixedparams(nullptr)
928     , m_return_value(nullptr)
929 {
930     vtype->m_hasvalue = true;
931     vtype->m_constval.vfunc = this;
932 }
933
934 ast_function::~ast_function()
935 {
936     if (m_function_type) {
937         // ast_value_delete(m_function_type);
938         m_function_type->m_hasvalue = false;
939         m_function_type->m_constval.vfunc = nullptr;
940         // We use unref - if it was stored in a global table it is supposed
941         // to be deleted from *there*
942         ast_unref(m_function_type);
943     }
944
945     if (m_fixedparams)
946         ast_unref(m_fixedparams);
947     if (m_return_value)
948         ast_unref(m_return_value);
949 }
950
951 const char* ast_function::makeLabel(const char *prefix)
952 {
953     size_t id;
954     size_t len;
955     char  *from;
956
957     if (!OPTS_OPTION_BOOL(OPTION_DUMP)    &&
958         !OPTS_OPTION_BOOL(OPTION_DUMPFIN) &&
959         !OPTS_OPTION_BOOL(OPTION_DEBUG))
960     {
961         return nullptr;
962     }
963
964     id  = (m_labelcount++);
965     len = strlen(prefix);
966
967     from = m_labelbuf + sizeof(m_labelbuf)-1;
968     *from-- = 0;
969     do {
970         *from-- = (id%10) + '0';
971         id /= 10;
972     } while (id);
973     ++from;
974     memcpy(from - len, prefix, len);
975     return from - len;
976 }
977
978 /*********************************************************************/
979 /* AST codegen part
980  * by convention you must never pass nullptr to the 'ir_value **out'
981  * parameter. If you really don't care about the output, pass a dummy.
982  * But I can't imagine a pituation where the output is truly unnecessary.
983  */
984
985 static void codegen_output_type(ast_expression *self, ir_value *out)
986 {
987     if (out->m_vtype == TYPE_FIELD)
988         out->m_fieldtype = self->m_next->m_vtype;
989     if (out->m_vtype == TYPE_FUNCTION)
990         out->m_outtype = self->m_next->m_vtype;
991 }
992
993 bool ast_value::codegen(ast_function *func, bool lvalue, ir_value **out)
994 {
995     (void)func;
996     (void)lvalue;
997     if (m_vtype == TYPE_NIL) {
998         *out = func->m_ir_func->m_owner->m_nil;
999         return true;
1000     }
1001     // NOTE: This is the codegen for a variable used in an expression.
1002     // It is not the codegen to generate the value storage. For this purpose,
1003     // generateLocal and generateGlobal are to be used before this
1004     // is executed. ast_function::generateFunction should take care of its
1005     // locals, and the ast-user should take care of generateGlobal to be used
1006     // on all the globals.
1007     if (!m_ir_v) {
1008         char tname[1024]; /* typename is reserved in C++ */
1009         ast_type_to_string(this, tname, sizeof(tname));
1010         compile_error(m_context, "ast_value used before generated %s %s", tname, m_name);
1011         return false;
1012     }
1013     *out = m_ir_v;
1014     return true;
1015 }
1016
1017 bool ast_value::setGlobalArray()
1018 {
1019     size_t count = m_initlist.size();
1020     size_t i;
1021
1022     if (count > m_count) {
1023         compile_error(m_context, "too many elements in initializer");
1024         count = m_count;
1025     }
1026     else if (count < m_count) {
1027         /* add this?
1028         compile_warning(m_context, "not all elements are initialized");
1029         */
1030     }
1031
1032     for (i = 0; i != count; ++i) {
1033         switch (m_next->m_vtype) {
1034             case TYPE_FLOAT:
1035                 if (!ir_value_set_float(m_ir_values[i], m_initlist[i].vfloat))
1036                     return false;
1037                 break;
1038             case TYPE_VECTOR:
1039                 if (!ir_value_set_vector(m_ir_values[i], m_initlist[i].vvec))
1040                     return false;
1041                 break;
1042             case TYPE_STRING:
1043                 if (!ir_value_set_string(m_ir_values[i], m_initlist[i].vstring))
1044                     return false;
1045                 break;
1046             case TYPE_ARRAY:
1047                 /* we don't support them in any other place yet either */
1048                 compile_error(m_context, "TODO: nested arrays");
1049                 return false;
1050             case TYPE_FUNCTION:
1051                 /* this requiers a bit more work - similar to the fields I suppose */
1052                 compile_error(m_context, "global of type function not properly generated");
1053                 return false;
1054             case TYPE_FIELD:
1055                 if (!m_initlist[i].vfield) {
1056                     compile_error(m_context, "field constant without vfield set");
1057                     return false;
1058                 }
1059                 if (!m_initlist[i].vfield->m_ir_v) {
1060                     compile_error(m_context, "field constant generated before its field");
1061                     return false;
1062                 }
1063                 if (!ir_value_set_field(m_ir_values[i], m_initlist[i].vfield->m_ir_v))
1064                     return false;
1065                 break;
1066             default:
1067                 compile_error(m_context, "TODO: global constant type %i", m_vtype);
1068                 break;
1069         }
1070     }
1071     return true;
1072 }
1073
1074 bool ast_value::checkArray(const ast_value &array) const
1075 {
1076     if (array.m_flags & AST_FLAG_ARRAY_INIT && array.m_initlist.empty()) {
1077         compile_error(m_context, "array without size: %s", m_name);
1078         return false;
1079     }
1080     // we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements
1081     if (!array.m_count || array.m_count > OPTS_OPTION_U32(OPTION_MAX_ARRAY_SIZE)) {
1082         compile_error(m_context, "Invalid array of size %lu", (unsigned long)array.m_count);
1083         return false;
1084     }
1085     return true;
1086 }
1087
1088 bool ast_value::generateGlobal(ir_builder *ir, bool isfield)
1089 {
1090     if (m_vtype == TYPE_NIL) {
1091         compile_error(m_context, "internal error: trying to generate a variable of TYPE_NIL");
1092         return false;
1093     }
1094
1095     if (m_hasvalue && m_vtype == TYPE_FUNCTION)
1096         return generateGlobalFunction(ir);
1097
1098     if (isfield && m_vtype == TYPE_FIELD)
1099         return generateGlobalField(ir);
1100
1101     ir_value *v = nullptr;
1102     if (m_vtype == TYPE_ARRAY) {
1103         v = prepareGlobalArray(ir);
1104         if (!v)
1105             return false;
1106     } else {
1107         // Arrays don't do this since there's no "array" value which spans across the
1108         // whole thing.
1109         v = ir_builder_create_global(ir, m_name, m_vtype);
1110         if (!v) {
1111             compile_error(m_context, "ir_builder_create_global failed on `%s`", m_name);
1112             return false;
1113         }
1114         codegen_output_type(this, v);
1115         v->m_context = m_context;
1116     }
1117
1118     /* link us to the ir_value */
1119     v->m_cvq = m_cvq;
1120     m_ir_v = v;
1121
1122     if (m_flags & AST_FLAG_INCLUDE_DEF)
1123         m_ir_v->m_flags |= IR_FLAG_INCLUDE_DEF;
1124     if (m_flags & AST_FLAG_ERASEABLE)
1125         m_ir_v->m_flags |= IR_FLAG_ERASABLE;
1126
1127     /* initialize */
1128     if (m_hasvalue) {
1129         switch (m_vtype)
1130         {
1131             case TYPE_FLOAT:
1132                 if (!ir_value_set_float(v, m_constval.vfloat))
1133                     return false;
1134                 break;
1135             case TYPE_VECTOR:
1136                 if (!ir_value_set_vector(v, m_constval.vvec))
1137                     return false;
1138                 break;
1139             case TYPE_STRING:
1140                 if (!ir_value_set_string(v, m_constval.vstring))
1141                     return false;
1142                 break;
1143             case TYPE_ARRAY:
1144                 if (!setGlobalArray())
1145                     return false;
1146                 break;
1147             case TYPE_FUNCTION:
1148                 compile_error(m_context, "global of type function not properly generated");
1149                 return false;
1150                 /* Cannot generate an IR value for a function,
1151                  * need a pointer pointing to a function rather.
1152                  */
1153             case TYPE_FIELD:
1154                 if (!m_constval.vfield) {
1155                     compile_error(m_context, "field constant without vfield set");
1156                     return false;
1157                 }
1158                 if (!m_constval.vfield->m_ir_v) {
1159                     compile_error(m_context, "field constant generated before its field");
1160                     return false;
1161                 }
1162                 if (!ir_value_set_field(v, m_constval.vfield->m_ir_v))
1163                     return false;
1164                 break;
1165             default:
1166                 compile_error(m_context, "TODO: global constant type %i", m_vtype);
1167                 break;
1168         }
1169     }
1170
1171     return true;
1172 }
1173
1174 bool ast_value::generateGlobalFunction(ir_builder *ir)
1175 {
1176     ir_function *func = ir_builder_create_function(ir, m_name, m_next->m_vtype);
1177     if (!func)
1178         return false;
1179     func->m_context = m_context;
1180     func->m_value->m_context = m_context;
1181
1182     m_constval.vfunc->m_ir_func = func;
1183     m_ir_v = func->m_value;
1184     if (m_flags & AST_FLAG_INCLUDE_DEF)
1185         m_ir_v->m_flags |= IR_FLAG_INCLUDE_DEF;
1186     if (m_flags & AST_FLAG_ERASEABLE)
1187         m_ir_v->m_flags |= IR_FLAG_ERASABLE;
1188     if (m_flags & AST_FLAG_BLOCK_COVERAGE)
1189         func->m_flags |= IR_FLAG_BLOCK_COVERAGE;
1190     // The function is filled later on ast_function::generateFunction...
1191     return true;
1192 }
1193
1194 bool ast_value::generateGlobalField(ir_builder *ir)
1195 {
1196     ast_expression *fieldtype = m_next;
1197
1198     if (m_hasvalue) {
1199         compile_error(m_context, "TODO: constant field pointers with value");
1200         return false;
1201     }
1202
1203     if (fieldtype->m_vtype == TYPE_ARRAY) {
1204         if (!ast_istype(fieldtype, ast_value)) {
1205             compile_error(m_context, "internal error: ast_value required");
1206             return false;
1207         }
1208         ast_value      *array = reinterpret_cast<ast_value*>(fieldtype);
1209
1210         if (!checkArray(*array))
1211             return false;
1212
1213         ast_expression *elemtype = array->m_next;
1214         qc_type vtype = elemtype->m_vtype;
1215
1216         ir_value *v = ir_builder_create_field(ir, m_name, vtype);
1217         if (!v) {
1218             compile_error(m_context, "ir_builder_create_global failed on `%s`", m_name);
1219             return false;
1220         }
1221         v->m_context = m_context;
1222         v->m_unique_life = true;
1223         v->m_locked      = true;
1224         array->m_ir_v = m_ir_v = v;
1225
1226         if (m_flags & AST_FLAG_INCLUDE_DEF)
1227             m_ir_v->m_flags |= IR_FLAG_INCLUDE_DEF;
1228         if (m_flags & AST_FLAG_ERASEABLE)
1229             m_ir_v->m_flags |= IR_FLAG_ERASABLE;
1230
1231         const size_t namelen = m_name.length();
1232         std::unique_ptr<char[]> name(new char[namelen+16]);
1233         util_strncpy(name.get(), m_name.c_str(), namelen);
1234
1235         array->m_ir_values.resize(array->m_count);
1236         array->m_ir_values[0] = v;
1237         for (size_t ai = 1; ai < array->m_count; ++ai) {
1238             util_snprintf(name.get() + namelen, 16, "[%u]", (unsigned int)ai);
1239             array->m_ir_values[ai] = ir_builder_create_field(ir, name.get(), vtype);
1240             if (!array->m_ir_values[ai]) {
1241                 compile_error(m_context, "ir_builder_create_global failed on `%s`", name.get());
1242                 return false;
1243             }
1244             array->m_ir_values[ai]->m_context = m_context;
1245             array->m_ir_values[ai]->m_unique_life = true;
1246             array->m_ir_values[ai]->m_locked      = true;
1247             if (m_flags & AST_FLAG_INCLUDE_DEF)
1248                 m_ir_values[ai]->m_flags |= IR_FLAG_INCLUDE_DEF;
1249         }
1250     }
1251     else
1252     {
1253         ir_value *v = ir_builder_create_field(ir, m_name, m_next->m_vtype);
1254         if (!v)
1255             return false;
1256         v->m_context = m_context;
1257         m_ir_v = v;
1258         if (m_flags & AST_FLAG_INCLUDE_DEF)
1259             m_ir_v->m_flags |= IR_FLAG_INCLUDE_DEF;
1260
1261         if (m_flags & AST_FLAG_ERASEABLE)
1262             m_ir_v->m_flags |= IR_FLAG_ERASABLE;
1263     }
1264     return true;
1265 }
1266
1267 ir_value *ast_value::prepareGlobalArray(ir_builder *ir)
1268 {
1269     ast_expression *elemtype = m_next;
1270     qc_type vtype = elemtype->m_vtype;
1271
1272     if (m_flags & AST_FLAG_ARRAY_INIT && !m_count) {
1273         compile_error(m_context, "array `%s' has no size", m_name);
1274         return nullptr;
1275     }
1276
1277     /* same as with field arrays */
1278     if (!checkArray(*this))
1279         return nullptr;
1280
1281     ir_value *v = ir_builder_create_global(ir, m_name, vtype);
1282     if (!v) {
1283         compile_error(m_context, "ir_builder_create_global failed `%s`", m_name);
1284         return nullptr;
1285     }
1286     v->m_context = m_context;
1287     v->m_unique_life = true;
1288     v->m_locked      = true;
1289
1290     if (m_flags & AST_FLAG_INCLUDE_DEF)
1291         v->m_flags |= IR_FLAG_INCLUDE_DEF;
1292     if (m_flags & AST_FLAG_ERASEABLE)
1293         m_ir_v->m_flags |= IR_FLAG_ERASABLE;
1294
1295     const size_t namelen = m_name.length();
1296     std::unique_ptr<char[]> name(new char[namelen+16]);
1297     util_strncpy(name.get(), m_name.c_str(), namelen);
1298
1299     m_ir_values.resize(m_count);
1300     m_ir_values[0] = v;
1301     for (size_t ai = 1; ai < m_count; ++ai) {
1302         util_snprintf(name.get() + namelen, 16, "[%u]", (unsigned int)ai);
1303         m_ir_values[ai] = ir_builder_create_global(ir, name.get(), vtype);
1304         if (!m_ir_values[ai]) {
1305             compile_error(m_context, "ir_builder_create_global failed `%s`", name.get());
1306             return nullptr;
1307         }
1308         m_ir_values[ai]->m_context = m_context;
1309         m_ir_values[ai]->m_unique_life = true;
1310         m_ir_values[ai]->m_locked      = true;
1311         if (m_flags & AST_FLAG_INCLUDE_DEF)
1312             m_ir_values[ai]->m_flags |= IR_FLAG_INCLUDE_DEF;
1313     }
1314
1315     return v;
1316 }
1317
1318 bool ast_value::generateLocal(ir_function *func, bool param)
1319 {
1320     if (m_vtype == TYPE_NIL) {
1321         compile_error(m_context, "internal error: trying to generate a variable of TYPE_NIL");
1322         return false;
1323     }
1324
1325     if (m_hasvalue && m_vtype == TYPE_FUNCTION)
1326     {
1327         /* Do we allow local functions? I think not...
1328          * this is NOT a function pointer atm.
1329          */
1330         return false;
1331     }
1332
1333     ir_value *v = nullptr;
1334     if (m_vtype == TYPE_ARRAY) {
1335         ast_expression *elemtype = m_next;
1336         qc_type vtype = elemtype->m_vtype;
1337
1338         func->m_flags |= IR_FLAG_HAS_ARRAYS;
1339
1340         if (param && !(m_flags & AST_FLAG_IS_VARARG)) {
1341             compile_error(m_context, "array-parameters are not supported");
1342             return false;
1343         }
1344
1345         /* we are lame now - considering the way QC works we won't tolerate arrays > 1024 elements */
1346         if (!checkArray(*this))
1347             return false;
1348
1349         m_ir_values.resize(m_count);
1350         v = ir_function_create_local(func, m_name, vtype, param);
1351         if (!v) {
1352             compile_error(m_context, "internal error: ir_function_create_local failed");
1353             return false;
1354         }
1355         v->m_context = m_context;
1356         v->m_unique_life = true;
1357         v->m_locked      = true;
1358
1359         const size_t namelen = m_name.length();
1360         std::unique_ptr<char[]> name(new char[namelen+16]);
1361         util_strncpy(name.get(), m_name.c_str(), namelen);
1362
1363         m_ir_values[0] = v;
1364         for (size_t ai = 1; ai < m_count; ++ai) {
1365             util_snprintf(name.get() + namelen, 16, "[%u]", (unsigned int)ai);
1366             m_ir_values[ai] = ir_function_create_local(func, name.get(), vtype, param);
1367             if (!m_ir_values[ai]) {
1368                 compile_error(m_context, "internal_error: ir_builder_create_global failed on `%s`", name.get());
1369                 return false;
1370             }
1371             m_ir_values[ai]->m_context = m_context;
1372             m_ir_values[ai]->m_unique_life = true;
1373             m_ir_values[ai]->m_locked      = true;
1374         }
1375     }
1376     else
1377     {
1378         v = ir_function_create_local(func, m_name, m_vtype, param);
1379         if (!v)
1380             return false;
1381         codegen_output_type(this, v);
1382         v->m_context = m_context;
1383     }
1384
1385     // A constant local... hmmm...
1386     // I suppose the IR will have to deal with this
1387     if (m_hasvalue) {
1388         switch (m_vtype)
1389         {
1390             case TYPE_FLOAT:
1391                 if (!ir_value_set_float(v, m_constval.vfloat))
1392                     goto error;
1393                 break;
1394             case TYPE_VECTOR:
1395                 if (!ir_value_set_vector(v, m_constval.vvec))
1396                     goto error;
1397                 break;
1398             case TYPE_STRING:
1399                 if (!ir_value_set_string(v, m_constval.vstring))
1400                     goto error;
1401                 break;
1402             default:
1403                 compile_error(m_context, "TODO: global constant type %i", m_vtype);
1404                 break;
1405         }
1406     }
1407
1408     // link us to the ir_value
1409     v->m_cvq = m_cvq;
1410     m_ir_v = v;
1411
1412     if (!generateAccessors(func->m_owner))
1413         return false;
1414     return true;
1415
1416 error: /* clean up */
1417     delete v;
1418     return false;
1419 }
1420
1421 bool ast_value::generateAccessors(ir_builder *ir)
1422 {
1423     size_t i;
1424     bool warn = OPTS_WARN(WARN_USED_UNINITIALIZED);
1425     if (!m_setter || !m_getter)
1426         return true;
1427     if (m_count && m_ir_values.empty()) {
1428         compile_error(m_context, "internal error: no array values generated for `%s`", m_name);
1429         return false;
1430     }
1431     for (i = 0; i < m_count; ++i) {
1432         if (!m_ir_values[i]) {
1433             compile_error(m_context, "internal error: not all array values have been generated for `%s`", m_name);
1434             return false;
1435         }
1436         if (!m_ir_values[i]->m_life.empty()) {
1437             compile_error(m_context, "internal error: function containing `%s` already generated", m_name);
1438             return false;
1439         }
1440     }
1441
1442     opts_set(opts.warn, WARN_USED_UNINITIALIZED, false);
1443     if (m_setter) {
1444         if (!m_setter->generateGlobal(ir, false) ||
1445             !m_setter->m_constval.vfunc->generateFunction(ir) ||
1446             !ir_function_finalize(m_setter->m_constval.vfunc->m_ir_func))
1447         {
1448             compile_error(m_context, "internal error: failed to generate setter for `%s`", m_name);
1449             opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1450             return false;
1451         }
1452     }
1453     if (m_getter) {
1454         if (!m_getter->generateGlobal(ir, false) ||
1455             !m_getter->m_constval.vfunc->generateFunction(ir) ||
1456             !ir_function_finalize(m_getter->m_constval.vfunc->m_ir_func))
1457         {
1458             compile_error(m_context, "internal error: failed to generate getter for `%s`", m_name);
1459             opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1460             return false;
1461         }
1462     }
1463     for (i = 0; i < m_count; ++i)
1464         m_ir_values[i]->m_life.clear();
1465     opts_set(opts.warn, WARN_USED_UNINITIALIZED, warn);
1466     return true;
1467 }
1468
1469 bool ast_function::generateFunction(ir_builder *ir)
1470 {
1471     (void)ir;
1472
1473     ir_value *dummy;
1474
1475     ir_function *irf = m_ir_func;
1476     if (!irf) {
1477         compile_error(m_context, "internal error: ast_function's related ast_value was not generated yet");
1478         return false;
1479     }
1480
1481     /* fill the parameter list */
1482     for (auto &it : m_function_type->m_type_params) {
1483         if (it->m_vtype == TYPE_FIELD)
1484             vec_push(irf->m_params, it->m_next->m_vtype);
1485         else
1486             vec_push(irf->m_params, it->m_vtype);
1487         if (!m_builtin) {
1488             if (!it->generateLocal(m_ir_func, true))
1489                 return false;
1490         }
1491     }
1492
1493     if (m_varargs) {
1494         if (!m_varargs->generateLocal(m_ir_func, true))
1495             return false;
1496         irf->m_max_varargs = m_varargs->m_count;
1497     }
1498
1499     if (m_builtin) {
1500         irf->m_builtin = m_builtin;
1501         return true;
1502     }
1503
1504     /* have a local return value variable? */
1505     if (m_return_value) {
1506         if (!m_return_value->generateLocal(m_ir_func, false))
1507             return false;
1508     }
1509
1510     if (m_blocks.empty()) {
1511         compile_error(m_context, "function `%s` has no body", m_name);
1512         return false;
1513     }
1514
1515     irf->m_first = m_curblock = ir_function_create_block(m_context, irf, "entry");
1516     if (!m_curblock) {
1517         compile_error(m_context, "failed to allocate entry block for `%s`", m_name);
1518         return false;
1519     }
1520
1521     if (m_argc) {
1522         ir_value *va_count;
1523         ir_value *fixed;
1524         ir_value *sub;
1525         if (!m_argc->generateLocal(m_ir_func, true))
1526             return false;
1527         if (!m_argc->codegen(this, false, &va_count))
1528             return false;
1529         if (!m_fixedparams->codegen(this, false, &fixed))
1530             return false;
1531         sub = ir_block_create_binop(m_curblock, m_context,
1532                                     makeLabel("va_count"), INSTR_SUB_F,
1533                                     ir_builder_get_va_count(ir), fixed);
1534         if (!sub)
1535             return false;
1536         if (!ir_block_create_store_op(m_curblock, m_context, INSTR_STORE_F,
1537                                       va_count, sub))
1538         {
1539             return false;
1540         }
1541     }
1542
1543     for (auto &it : m_blocks) {
1544         if (!it->codegen(this, false, &dummy))
1545           return false;
1546     }
1547
1548     /* TODO: check return types */
1549     if (!m_curblock->m_final)
1550     {
1551         if (!m_function_type->m_next ||
1552             m_function_type->m_next->m_vtype == TYPE_VOID)
1553         {
1554             return ir_block_create_return(m_curblock, m_context, nullptr);
1555         }
1556         else if (vec_size(m_curblock->m_entries) || m_curblock == irf->m_first)
1557         {
1558             if (m_return_value) {
1559                 if (!m_return_value->codegen(this, false, &dummy))
1560                     return false;
1561                 return ir_block_create_return(m_curblock, m_context, dummy);
1562             }
1563             else if (compile_warning(m_context, WARN_MISSING_RETURN_VALUES,
1564                                 "control reaches end of non-void function (`%s`) via %s",
1565                                 m_name.c_str(), m_curblock->m_label.c_str()))
1566             {
1567                 return false;
1568             }
1569             return ir_block_create_return(m_curblock, m_context, nullptr);
1570         }
1571     }
1572     return true;
1573 }
1574
1575 static bool starts_a_label(const ast_expression *ex)
1576 {
1577     while (ex && ast_istype(ex, ast_block)) {
1578         auto b = reinterpret_cast<const ast_block*>(ex);
1579         ex = b->m_exprs[0];
1580     }
1581     if (!ex)
1582         return false;
1583     return ast_istype(ex, ast_label);
1584 }
1585
1586 /* Note, you will not see ast_block_codegen generate ir_blocks.
1587  * To the AST and the IR, blocks are 2 different things.
1588  * In the AST it represents a block of code, usually enclosed in
1589  * curly braces {...}.
1590  * While in the IR it represents a block in terms of control-flow.
1591  */
1592 bool ast_block::codegen(ast_function *func, bool lvalue, ir_value **out)
1593 {
1594     /* We don't use this
1595      * Note: an ast-representation using the comma-operator
1596      * of the form: (a, b, c) = x should not assign to c...
1597      */
1598     if (lvalue) {
1599         compile_error(m_context, "not an l-value (code-block)");
1600         return false;
1601     }
1602
1603     if (m_outr) {
1604         *out = m_outr;
1605         return true;
1606     }
1607
1608     /* output is nullptr at first, we'll have each expression
1609      * assign to out output, thus, a comma-operator represention
1610      * using an ast_block will return the last generated value,
1611      * so: (b, c) + a  executed both b and c, and returns c,
1612      * which is then added to a.
1613      */
1614     *out = nullptr;
1615
1616     /* generate locals */
1617     for (auto &it : m_locals) {
1618         if (!it->generateLocal(func->m_ir_func, false)) {
1619             if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1620                 compile_error(m_context, "failed to generate local `%s`", it->m_name);
1621             return false;
1622         }
1623     }
1624
1625     for (auto &it : m_exprs) {
1626         if (func->m_curblock->m_final && !starts_a_label(it)) {
1627             if (compile_warning(it->m_context, WARN_UNREACHABLE_CODE, "unreachable statement"))
1628                 return false;
1629             continue;
1630         }
1631         if (!it->codegen(func, false, out))
1632             return false;
1633     }
1634
1635     m_outr = *out;
1636
1637     return true;
1638 }
1639
1640 bool ast_store::codegen(ast_function *func, bool lvalue, ir_value **out)
1641 {
1642     ir_value *left  = nullptr;
1643     ir_value *right = nullptr;
1644
1645     ast_value       *idx = 0;
1646     ast_array_index *ai = nullptr;
1647
1648     if (lvalue && m_outl) {
1649         *out = m_outl;
1650         return true;
1651     }
1652
1653     if (!lvalue && m_outr) {
1654         *out = m_outr;
1655         return true;
1656     }
1657
1658     if (ast_istype(m_dest, ast_array_index))
1659     {
1660
1661         ai = (ast_array_index*)m_dest;
1662         idx = (ast_value*)ai->m_index;
1663
1664         if (ast_istype(ai->m_index, ast_value) && idx->m_hasvalue && idx->m_cvq == CV_CONST)
1665             ai = nullptr;
1666     }
1667
1668     if (ai) {
1669         /* we need to call the setter */
1670         ir_value  *iridx, *funval;
1671         ir_instr  *call;
1672
1673         if (lvalue) {
1674             compile_error(m_context, "array-subscript assignment cannot produce lvalues");
1675             return false;
1676         }
1677
1678         auto arr = reinterpret_cast<ast_value*>(ai->m_array);
1679         if (!ast_istype(ai->m_array, ast_value) || !arr->m_setter) {
1680             compile_error(m_context, "value has no setter (%s)", arr->m_name);
1681             return false;
1682         }
1683
1684         if (!idx->codegen(func, false, &iridx))
1685             return false;
1686
1687         if (!arr->m_setter->codegen(func, true, &funval))
1688             return false;
1689
1690         if (!m_source->codegen(func, false, &right))
1691             return false;
1692
1693         call = ir_block_create_call(func->m_curblock, m_context, func->makeLabel("store"), funval, false);
1694         if (!call)
1695             return false;
1696         ir_call_param(call, iridx);
1697         ir_call_param(call, right);
1698         m_outr = right;
1699     }
1700     else
1701     {
1702         // regular code
1703
1704         // lvalue!
1705         if (!m_dest->codegen(func, true, &left))
1706             return false;
1707         m_outl = left;
1708
1709         /* rvalue! */
1710         if (!m_source->codegen(func, false, &right))
1711             return false;
1712
1713         if (!ir_block_create_store_op(func->m_curblock, m_context, m_op, left, right))
1714             return false;
1715         m_outr = right;
1716     }
1717
1718     /* Theoretically, an assinment returns its left side as an
1719      * lvalue, if we don't need an lvalue though, we return
1720      * the right side as an rvalue, otherwise we have to
1721      * somehow know whether or not we need to dereference the pointer
1722      * on the left side - that is: OP_LOAD if it was an address.
1723      * Also: in original QC we cannot OP_LOADP *anyway*.
1724      */
1725     *out = (lvalue ? left : right);
1726
1727     return true;
1728 }
1729
1730 bool ast_binary::codegen(ast_function *func, bool lvalue, ir_value **out)
1731 {
1732     ir_value *left, *right;
1733
1734     /* A binary operation cannot yield an l-value */
1735     if (lvalue) {
1736         compile_error(m_context, "not an l-value (binop)");
1737         return false;
1738     }
1739
1740     if (m_outr) {
1741         *out = m_outr;
1742         return true;
1743     }
1744
1745     if ((OPTS_FLAG(SHORT_LOGIC) || OPTS_FLAG(PERL_LOGIC)) &&
1746         (m_op == INSTR_AND || m_op == INSTR_OR))
1747     {
1748         /* NOTE: The short-logic path will ignore right_first */
1749
1750         /* short circuit evaluation */
1751         ir_block *other, *merge;
1752         ir_block *from_left, *from_right;
1753         ir_instr *phi;
1754         size_t    merge_id;
1755
1756         /* prepare end-block */
1757         merge_id = func->m_ir_func->m_blocks.size();
1758         merge    = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("sce_merge"));
1759
1760         /* generate the left expression */
1761         if (!m_left->codegen(func, false, &left))
1762             return false;
1763         /* remember the block */
1764         from_left = func->m_curblock;
1765
1766         /* create a new block for the right expression */
1767         other = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("sce_other"));
1768         if (m_op == INSTR_AND) {
1769             /* on AND: left==true -> other */
1770             if (!ir_block_create_if(func->m_curblock, m_context, left, other, merge))
1771                 return false;
1772         } else {
1773             /* on OR: left==false -> other */
1774             if (!ir_block_create_if(func->m_curblock, m_context, left, merge, other))
1775                 return false;
1776         }
1777         /* use the likely flag */
1778         vec_last(func->m_curblock->m_instr)->m_likely = true;
1779
1780         /* enter the right-expression's block */
1781         func->m_curblock = other;
1782         /* generate */
1783         if (!m_right->codegen(func, false, &right))
1784             return false;
1785         /* remember block */
1786         from_right = func->m_curblock;
1787
1788         /* jump to the merge block */
1789         if (!ir_block_create_jump(func->m_curblock, m_context, merge))
1790             return false;
1791
1792         algo::shiftback(func->m_ir_func->m_blocks.begin() + merge_id,
1793                         func->m_ir_func->m_blocks.end());
1794         // FIXME::DELME::
1795         //func->m_ir_func->m_blocks[merge_id].release();
1796         //func->m_ir_func->m_blocks.erase(func->m_ir_func->m_blocks.begin() + merge_id);
1797         //func->m_ir_func->m_blocks.emplace_back(merge);
1798
1799         func->m_curblock = merge;
1800         phi = ir_block_create_phi(func->m_curblock, m_context,
1801                                   func->makeLabel("sce_value"),
1802                                   m_vtype);
1803         ir_phi_add(phi, from_left, left);
1804         ir_phi_add(phi, from_right, right);
1805         *out = ir_phi_value(phi);
1806         if (!*out)
1807             return false;
1808
1809         if (!OPTS_FLAG(PERL_LOGIC)) {
1810             /* cast-to-bool */
1811             if (OPTS_FLAG(CORRECT_LOGIC) && (*out)->m_vtype == TYPE_VECTOR) {
1812                 *out = ir_block_create_unary(func->m_curblock, m_context,
1813                                              func->makeLabel("sce_bool_v"),
1814                                              INSTR_NOT_V, *out);
1815                 if (!*out)
1816                     return false;
1817                 *out = ir_block_create_unary(func->m_curblock, m_context,
1818                                              func->makeLabel("sce_bool"),
1819                                              INSTR_NOT_F, *out);
1820                 if (!*out)
1821                     return false;
1822             }
1823             else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && (*out)->m_vtype == TYPE_STRING) {
1824                 *out = ir_block_create_unary(func->m_curblock, m_context,
1825                                              func->makeLabel("sce_bool_s"),
1826                                              INSTR_NOT_S, *out);
1827                 if (!*out)
1828                     return false;
1829                 *out = ir_block_create_unary(func->m_curblock, m_context,
1830                                              func->makeLabel("sce_bool"),
1831                                              INSTR_NOT_F, *out);
1832                 if (!*out)
1833                     return false;
1834             }
1835             else {
1836                 *out = ir_block_create_binop(func->m_curblock, m_context,
1837                                              func->makeLabel("sce_bool"),
1838                                              INSTR_AND, *out, *out);
1839                 if (!*out)
1840                     return false;
1841             }
1842         }
1843
1844         m_outr = *out;
1845         codegen_output_type(this, *out);
1846         return true;
1847     }
1848
1849     if (m_right_first) {
1850         if (!m_right->codegen(func, false, &right))
1851             return false;
1852         if (!m_left->codegen(func, false, &left))
1853             return false;
1854     } else {
1855         if (!m_left->codegen(func, false, &left))
1856             return false;
1857         if (!m_right->codegen(func, false, &right))
1858             return false;
1859     }
1860
1861     *out = ir_block_create_binop(func->m_curblock, m_context, func->makeLabel("bin"),
1862                                  m_op, left, right);
1863     if (!*out)
1864         return false;
1865     m_outr = *out;
1866     codegen_output_type(this, *out);
1867
1868     return true;
1869 }
1870
1871 bool ast_binstore::codegen(ast_function *func, bool lvalue, ir_value **out)
1872 {
1873     ir_value *leftl = nullptr, *leftr, *right, *bin;
1874
1875     ast_value       *arr;
1876     ast_value       *idx = 0;
1877     ast_array_index *ai = nullptr;
1878     ir_value        *iridx = nullptr;
1879
1880     if (lvalue && m_outl) {
1881         *out = m_outl;
1882         return true;
1883     }
1884
1885     if (!lvalue && m_outr) {
1886         *out = m_outr;
1887         return true;
1888     }
1889
1890     if (ast_istype(m_dest, ast_array_index))
1891     {
1892
1893         ai = (ast_array_index*)m_dest;
1894         idx = (ast_value*)ai->m_index;
1895
1896         if (ast_istype(ai->m_index, ast_value) && idx->m_hasvalue && idx->m_cvq == CV_CONST)
1897             ai = nullptr;
1898     }
1899
1900     /* for a binstore we need both an lvalue and an rvalue for the left side */
1901     /* rvalue of destination! */
1902     if (ai) {
1903         if (!idx->codegen(func, false, &iridx))
1904             return false;
1905     }
1906     if (!m_dest->codegen(func, false, &leftr))
1907         return false;
1908
1909     /* source as rvalue only */
1910     if (!m_source->codegen(func, false, &right))
1911         return false;
1912
1913     /* now the binary */
1914     bin = ir_block_create_binop(func->m_curblock, m_context, func->makeLabel("binst"),
1915                                 m_opbin, leftr, right);
1916     m_outr = bin;
1917
1918     if (ai) {
1919         /* we need to call the setter */
1920         ir_value  *funval;
1921         ir_instr  *call;
1922
1923         if (lvalue) {
1924             compile_error(m_context, "array-subscript assignment cannot produce lvalues");
1925             return false;
1926         }
1927
1928         arr = (ast_value*)ai->m_array;
1929         if (!ast_istype(ai->m_array, ast_value) || !arr->m_setter) {
1930             compile_error(m_context, "value has no setter (%s)", arr->m_name);
1931             return false;
1932         }
1933
1934         if (!arr->m_setter->codegen(func, true, &funval))
1935             return false;
1936
1937         call = ir_block_create_call(func->m_curblock, m_context, func->makeLabel("store"), funval, false);
1938         if (!call)
1939             return false;
1940         ir_call_param(call, iridx);
1941         ir_call_param(call, bin);
1942         m_outr = bin;
1943     } else {
1944         // now store them
1945         // lvalue of destination
1946         if (!m_dest->codegen(func, true, &leftl))
1947             return false;
1948         m_outl = leftl;
1949
1950         if (!ir_block_create_store_op(func->m_curblock, m_context, m_opstore, leftl, bin))
1951             return false;
1952         m_outr = bin;
1953     }
1954
1955     /* Theoretically, an assinment returns its left side as an
1956      * lvalue, if we don't need an lvalue though, we return
1957      * the right side as an rvalue, otherwise we have to
1958      * somehow know whether or not we need to dereference the pointer
1959      * on the left side - that is: OP_LOAD if it was an address.
1960      * Also: in original QC we cannot OP_LOADP *anyway*.
1961      */
1962     *out = (lvalue ? leftl : bin);
1963
1964     return true;
1965 }
1966
1967 bool ast_unary::codegen(ast_function *func, bool lvalue, ir_value **out)
1968 {
1969     ir_value *operand;
1970
1971     /* An unary operation cannot yield an l-value */
1972     if (lvalue) {
1973         compile_error(m_context, "not an l-value (binop)");
1974         return false;
1975     }
1976
1977     if (m_outr) {
1978         *out = m_outr;
1979         return true;
1980     }
1981
1982     /* lvalue! */
1983     if (!m_operand->codegen(func, false, &operand))
1984         return false;
1985
1986     *out = ir_block_create_unary(func->m_curblock, m_context, func->makeLabel("unary"),
1987                                  m_op, operand);
1988     if (!*out)
1989         return false;
1990     m_outr = *out;
1991
1992     return true;
1993 }
1994
1995 bool ast_return::codegen(ast_function *func, bool lvalue, ir_value **out)
1996 {
1997     ir_value *operand;
1998
1999     *out = nullptr;
2000
2001     /* In the context of a return operation, we don't actually return
2002      * anything...
2003      */
2004     if (lvalue) {
2005         compile_error(m_context, "return-expression is not an l-value");
2006         return false;
2007     }
2008
2009     if (m_outr) {
2010         compile_error(m_context, "internal error: ast_return cannot be reused, it bears no result!");
2011         return false;
2012     }
2013     m_outr = (ir_value*)1;
2014
2015     if (m_operand) {
2016         /* lvalue! */
2017         if (!m_operand->codegen(func, false, &operand))
2018             return false;
2019
2020         if (!ir_block_create_return(func->m_curblock, m_context, operand))
2021             return false;
2022     } else {
2023         if (!ir_block_create_return(func->m_curblock, m_context, nullptr))
2024             return false;
2025     }
2026
2027     return true;
2028 }
2029
2030 bool ast_entfield::codegen(ast_function *func, bool lvalue, ir_value **out)
2031 {
2032     ir_value *ent, *field;
2033
2034     // This function needs to take the 'lvalue' flag into account!
2035     // As lvalue we provide a field-pointer, as rvalue we provide the
2036     // value in a temp.
2037
2038     if (lvalue && m_outl) {
2039         *out = m_outl;
2040         return true;
2041     }
2042
2043     if (!lvalue && m_outr) {
2044         *out = m_outr;
2045         return true;
2046     }
2047
2048     if (!m_entity->codegen(func, false, &ent))
2049         return false;
2050
2051     if (!m_field->codegen(func, false, &field))
2052         return false;
2053
2054     if (lvalue) {
2055         /* address! */
2056         *out = ir_block_create_fieldaddress(func->m_curblock, m_context, func->makeLabel("efa"),
2057                                             ent, field);
2058     } else {
2059         *out = ir_block_create_load_from_ent(func->m_curblock, m_context, func->makeLabel("efv"),
2060                                              ent, field, m_vtype);
2061         /* Done AFTER error checking:
2062         codegen_output_type(this, *out);
2063         */
2064     }
2065     if (!*out) {
2066         compile_error(m_context, "failed to create %s instruction (output type %s)",
2067                  (lvalue ? "ADDRESS" : "FIELD"),
2068                  type_name[m_vtype]);
2069         return false;
2070     }
2071     if (!lvalue)
2072         codegen_output_type(this, *out);
2073
2074     if (lvalue)
2075         m_outl = *out;
2076     else
2077         m_outr = *out;
2078
2079     // Hm that should be it...
2080     return true;
2081 }
2082
2083 bool ast_member::codegen(ast_function *func, bool lvalue, ir_value **out)
2084 {
2085     ir_value *vec;
2086
2087     /* in QC this is always an lvalue */
2088     if (lvalue && m_rvalue) {
2089         compile_error(m_context, "not an l-value (member access)");
2090         return false;
2091     }
2092     if (m_outl) {
2093         *out = m_outl;
2094         return true;
2095     }
2096
2097     if (!m_owner->codegen(func, false, &vec))
2098         return false;
2099
2100     if (vec->m_vtype != TYPE_VECTOR &&
2101         !(vec->m_vtype == TYPE_FIELD && m_owner->m_next->m_vtype == TYPE_VECTOR))
2102     {
2103         return false;
2104     }
2105
2106     *out = ir_value_vector_member(vec, m_field);
2107     m_outl = *out;
2108
2109     return (*out != nullptr);
2110 }
2111
2112 bool ast_array_index::codegen(ast_function *func, bool lvalue, ir_value **out)
2113 {
2114     ast_value *arr;
2115     ast_value *idx;
2116
2117     if (!lvalue && m_outr) {
2118         *out = m_outr;
2119         return true;
2120     }
2121     if (lvalue && m_outl) {
2122         *out = m_outl;
2123         return true;
2124     }
2125
2126     if (!ast_istype(m_array, ast_value)) {
2127         compile_error(m_context, "array indexing this way is not supported");
2128         /* note this would actually be pointer indexing because the left side is
2129          * not an actual array but (hopefully) an indexable expression.
2130          * Once we get integer arithmetic, and GADDRESS/GSTORE/GLOAD instruction
2131          * support this path will be filled.
2132          */
2133         return false;
2134     }
2135
2136     arr = reinterpret_cast<ast_value*>(m_array);
2137     idx = reinterpret_cast<ast_value*>(m_index);
2138
2139     if (!ast_istype(m_index, ast_value) || !idx->m_hasvalue || idx->m_cvq != CV_CONST) {
2140         /* Time to use accessor functions */
2141         ir_value               *iridx, *funval;
2142         ir_instr               *call;
2143
2144         if (lvalue) {
2145             compile_error(m_context, "(.2) array indexing here needs a compile-time constant");
2146             return false;
2147         }
2148
2149         if (!arr->m_getter) {
2150             compile_error(m_context, "value has no getter, don't know how to index it");
2151             return false;
2152         }
2153
2154         if (!m_index->codegen(func, false, &iridx))
2155             return false;
2156
2157         if (!arr->m_getter->codegen(func, true, &funval))
2158             return false;
2159
2160         call = ir_block_create_call(func->m_curblock, m_context, func->makeLabel("fetch"), funval, false);
2161         if (!call)
2162             return false;
2163         ir_call_param(call, iridx);
2164
2165         *out = ir_call_value(call);
2166         m_outr = *out;
2167         (*out)->m_vtype = m_vtype;
2168         codegen_output_type(this, *out);
2169         return true;
2170     }
2171
2172     if (idx->m_vtype == TYPE_FLOAT) {
2173         unsigned int arridx = idx->m_constval.vfloat;
2174         if (arridx >= m_array->m_count)
2175         {
2176             compile_error(m_context, "array index out of bounds: %i", arridx);
2177             return false;
2178         }
2179         *out = arr->m_ir_values[arridx];
2180     }
2181     else if (idx->m_vtype == TYPE_INTEGER) {
2182         unsigned int arridx = idx->m_constval.vint;
2183         if (arridx >= m_array->m_count)
2184         {
2185             compile_error(m_context, "array index out of bounds: %i", arridx);
2186             return false;
2187         }
2188         *out = arr->m_ir_values[arridx];
2189     }
2190     else {
2191         compile_error(m_context, "array indexing here needs an integer constant");
2192         return false;
2193     }
2194     (*out)->m_vtype = m_vtype;
2195     codegen_output_type(this, *out);
2196     return true;
2197 }
2198
2199 bool ast_argpipe::codegen(ast_function *func, bool lvalue, ir_value **out)
2200 {
2201     *out = nullptr;
2202     if (lvalue) {
2203         compile_error(m_context, "argpipe node: not an lvalue");
2204         return false;
2205     }
2206     (void)func;
2207     (void)out;
2208     compile_error(m_context, "TODO: argpipe codegen not implemented");
2209     return false;
2210 }
2211
2212 bool ast_ifthen::codegen(ast_function *func, bool lvalue, ir_value **out)
2213 {
2214     ir_value *condval;
2215     ir_value *dummy;
2216
2217     ir_block *cond;
2218     ir_block *ontrue;
2219     ir_block *onfalse;
2220     ir_block *ontrue_endblock = nullptr;
2221     ir_block *onfalse_endblock = nullptr;
2222     ir_block *merge = nullptr;
2223     int folded = 0;
2224
2225     /* We don't output any value, thus also don't care about r/lvalue */
2226     (void)out;
2227     (void)lvalue;
2228
2229     if (m_outr) {
2230         compile_error(m_context, "internal error: ast_ifthen cannot be reused, it bears no result!");
2231         return false;
2232     }
2233     m_outr = (ir_value*)1;
2234
2235     /* generate the condition */
2236     if (!m_cond->codegen(func, false, &condval))
2237         return false;
2238     /* update the block which will get the jump - because short-logic or ternaries may have changed this */
2239     cond = func->m_curblock;
2240
2241     /* try constant folding away the condition */
2242     if ((folded = fold::cond_ifthen(condval, func, this)) != -1)
2243         return folded;
2244
2245     if (m_on_true) {
2246         /* create on-true block */
2247         ontrue = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("ontrue"));
2248         if (!ontrue)
2249             return false;
2250
2251         /* enter the block */
2252         func->m_curblock = ontrue;
2253
2254         /* generate */
2255         if (!m_on_true->codegen(func, false, &dummy))
2256             return false;
2257
2258         /* we now need to work from the current endpoint */
2259         ontrue_endblock = func->m_curblock;
2260     } else
2261         ontrue = nullptr;
2262
2263     /* on-false path */
2264     if (m_on_false) {
2265         /* create on-false block */
2266         onfalse = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("onfalse"));
2267         if (!onfalse)
2268             return false;
2269
2270         /* enter the block */
2271         func->m_curblock = onfalse;
2272
2273         /* generate */
2274         if (!m_on_false->codegen(func, false, &dummy))
2275             return false;
2276
2277         /* we now need to work from the current endpoint */
2278         onfalse_endblock = func->m_curblock;
2279     } else
2280         onfalse = nullptr;
2281
2282     /* Merge block were they all merge in to */
2283     if (!ontrue || !onfalse || !ontrue_endblock->m_final || !onfalse_endblock->m_final)
2284     {
2285         merge = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("endif"));
2286         if (!merge)
2287             return false;
2288         /* add jumps ot the merge block */
2289         if (ontrue && !ontrue_endblock->m_final && !ir_block_create_jump(ontrue_endblock, m_context, merge))
2290             return false;
2291         if (onfalse && !onfalse_endblock->m_final && !ir_block_create_jump(onfalse_endblock, m_context, merge))
2292             return false;
2293
2294         /* Now enter the merge block */
2295         func->m_curblock = merge;
2296     }
2297
2298     /* we create the if here, that way all blocks are ordered :)
2299      */
2300     if (!ir_block_create_if(cond, m_context, condval,
2301                             (ontrue  ? ontrue  : merge),
2302                             (onfalse ? onfalse : merge)))
2303     {
2304         return false;
2305     }
2306
2307     return true;
2308 }
2309
2310 bool ast_ternary::codegen(ast_function *func, bool lvalue, ir_value **out)
2311 {
2312     ir_value *condval;
2313     ir_value *trueval, *falseval;
2314     ir_instr *phi;
2315
2316     ir_block *cond = func->m_curblock;
2317     ir_block *cond_out = nullptr;
2318     ir_block *ontrue, *ontrue_out = nullptr;
2319     ir_block *onfalse, *onfalse_out = nullptr;
2320     ir_block *merge;
2321     int folded = 0;
2322
2323     /* Ternary can never create an lvalue... */
2324     if (lvalue)
2325         return false;
2326
2327     /* In theory it shouldn't be possible to pass through a node twice, but
2328      * in case we add any kind of optimization pass for the AST itself, it
2329      * may still happen, thus we remember a created ir_value and simply return one
2330      * if it already exists.
2331      */
2332     if (m_outr) {
2333         *out = m_outr;
2334         return true;
2335     }
2336
2337     /* In the following, contraty to ast_ifthen, we assume both paths exist. */
2338
2339     /* generate the condition */
2340     func->m_curblock = cond;
2341     if (!m_cond->codegen(func, false, &condval))
2342         return false;
2343     cond_out = func->m_curblock;
2344
2345     /* try constant folding away the condition */
2346     if ((folded = fold::cond_ternary(condval, func, this)) != -1)
2347         return folded;
2348
2349     /* create on-true block */
2350     ontrue = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("tern_T"));
2351     if (!ontrue)
2352         return false;
2353     else
2354     {
2355         /* enter the block */
2356         func->m_curblock = ontrue;
2357
2358         /* generate */
2359         if (!m_on_true->codegen(func, false, &trueval))
2360             return false;
2361
2362         ontrue_out = func->m_curblock;
2363     }
2364
2365     /* create on-false block */
2366     onfalse = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("tern_F"));
2367     if (!onfalse)
2368         return false;
2369     else
2370     {
2371         /* enter the block */
2372         func->m_curblock = onfalse;
2373
2374         /* generate */
2375         if (!m_on_false->codegen(func, false, &falseval))
2376             return false;
2377
2378         onfalse_out = func->m_curblock;
2379     }
2380
2381     /* create merge block */
2382     merge = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("tern_out"));
2383     if (!merge)
2384         return false;
2385     /* jump to merge block */
2386     if (!ir_block_create_jump(ontrue_out, m_context, merge))
2387         return false;
2388     if (!ir_block_create_jump(onfalse_out, m_context, merge))
2389         return false;
2390
2391     /* create if instruction */
2392     if (!ir_block_create_if(cond_out, m_context, condval, ontrue, onfalse))
2393         return false;
2394
2395     /* Now enter the merge block */
2396     func->m_curblock = merge;
2397
2398     /* Here, now, we need a PHI node
2399      * but first some sanity checking...
2400      */
2401     if (trueval->m_vtype != falseval->m_vtype && trueval->m_vtype != TYPE_NIL && falseval->m_vtype != TYPE_NIL) {
2402         /* error("ternary with different types on the two sides"); */
2403         compile_error(m_context, "internal error: ternary operand types invalid");
2404         return false;
2405     }
2406
2407     /* create PHI */
2408     phi = ir_block_create_phi(merge, m_context, func->makeLabel("phi"), m_vtype);
2409     if (!phi) {
2410         compile_error(m_context, "internal error: failed to generate phi node");
2411         return false;
2412     }
2413     ir_phi_add(phi, ontrue_out,  trueval);
2414     ir_phi_add(phi, onfalse_out, falseval);
2415
2416     m_outr = ir_phi_value(phi);
2417     *out = m_outr;
2418
2419     codegen_output_type(this, *out);
2420
2421     return true;
2422 }
2423
2424 bool ast_loop::codegen(ast_function *func, bool lvalue, ir_value **out)
2425 {
2426     ir_value *dummy      = nullptr;
2427     ir_value *precond    = nullptr;
2428     ir_value *postcond   = nullptr;
2429
2430     /* Since we insert some jumps "late" so we have blocks
2431      * ordered "nicely", we need to keep track of the actual end-blocks
2432      * of expressions to add the jumps to.
2433      */
2434     ir_block *bbody      = nullptr, *end_bbody      = nullptr;
2435     ir_block *bprecond   = nullptr, *end_bprecond   = nullptr;
2436     ir_block *bpostcond  = nullptr, *end_bpostcond  = nullptr;
2437     ir_block *bincrement = nullptr, *end_bincrement = nullptr;
2438     ir_block *bout       = nullptr, *bin            = nullptr;
2439
2440     /* let's at least move the outgoing block to the end */
2441     size_t    bout_id;
2442
2443     /* 'break' and 'continue' need to be able to find the right blocks */
2444     ir_block *bcontinue     = nullptr;
2445     ir_block *bbreak        = nullptr;
2446
2447     ir_block *tmpblock      = nullptr;
2448
2449     (void)lvalue;
2450     (void)out;
2451
2452     if (m_outr) {
2453         compile_error(m_context, "internal error: ast_loop cannot be reused, it bears no result!");
2454         return false;
2455     }
2456     m_outr = (ir_value*)1;
2457
2458     /* NOTE:
2459      * Should we ever need some kind of block ordering, better make this function
2460      * move blocks around than write a block ordering algorithm later... after all
2461      * the ast and ir should work together, not against each other.
2462      */
2463
2464     /* initexpr doesn't get its own block, it's pointless, it could create more blocks
2465      * anyway if for example it contains a ternary.
2466      */
2467     if (m_initexpr)
2468     {
2469         if (!m_initexpr->codegen(func, false, &dummy))
2470             return false;
2471     }
2472
2473     /* Store the block from which we enter this chaos */
2474     bin = func->m_curblock;
2475
2476     /* The pre-loop condition needs its own block since we
2477      * need to be able to jump to the start of that expression.
2478      */
2479     if (m_precond)
2480     {
2481         bprecond = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("pre_loop_cond"));
2482         if (!bprecond)
2483             return false;
2484
2485         /* the pre-loop-condition the least important place to 'continue' at */
2486         bcontinue = bprecond;
2487
2488         /* enter */
2489         func->m_curblock = bprecond;
2490
2491         /* generate */
2492         if (!m_precond->codegen(func, false, &precond))
2493             return false;
2494
2495         end_bprecond = func->m_curblock;
2496     } else {
2497         bprecond = end_bprecond = nullptr;
2498     }
2499
2500     /* Now the next blocks won't be ordered nicely, but we need to
2501      * generate them this early for 'break' and 'continue'.
2502      */
2503     if (m_increment) {
2504         bincrement = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("loop_increment"));
2505         if (!bincrement)
2506             return false;
2507         bcontinue = bincrement; /* increment comes before the pre-loop-condition */
2508     } else {
2509         bincrement = end_bincrement = nullptr;
2510     }
2511
2512     if (m_postcond) {
2513         bpostcond = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("post_loop_cond"));
2514         if (!bpostcond)
2515             return false;
2516         bcontinue = bpostcond; /* postcond comes before the increment */
2517     } else {
2518         bpostcond = end_bpostcond = nullptr;
2519     }
2520
2521     bout_id = func->m_ir_func->m_blocks.size();
2522     bout = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("after_loop"));
2523     if (!bout)
2524         return false;
2525     bbreak = bout;
2526
2527     /* The loop body... */
2528     /* if (m_body) */
2529     {
2530         bbody = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("loop_body"));
2531         if (!bbody)
2532             return false;
2533
2534         /* enter */
2535         func->m_curblock = bbody;
2536
2537         func->m_breakblocks.push_back(bbreak);
2538         if (bcontinue)
2539             func->m_continueblocks.push_back(bcontinue);
2540         else
2541             func->m_continueblocks.push_back(bbody);
2542
2543         /* generate */
2544         if (m_body) {
2545             if (!m_body->codegen(func, false, &dummy))
2546                 return false;
2547         }
2548
2549         end_bbody = func->m_curblock;
2550         func->m_breakblocks.pop_back();
2551         func->m_continueblocks.pop_back();
2552     }
2553
2554     /* post-loop-condition */
2555     if (m_postcond)
2556     {
2557         /* enter */
2558         func->m_curblock = bpostcond;
2559
2560         /* generate */
2561         if (!m_postcond->codegen(func, false, &postcond))
2562             return false;
2563
2564         end_bpostcond = func->m_curblock;
2565     }
2566
2567     /* The incrementor */
2568     if (m_increment)
2569     {
2570         /* enter */
2571         func->m_curblock = bincrement;
2572
2573         /* generate */
2574         if (!m_increment->codegen(func, false, &dummy))
2575             return false;
2576
2577         end_bincrement = func->m_curblock;
2578     }
2579
2580     /* In any case now, we continue from the outgoing block */
2581     func->m_curblock = bout;
2582
2583     /* Now all blocks are in place */
2584     /* From 'bin' we jump to whatever comes first */
2585     if      (bprecond)   tmpblock = bprecond;
2586     else                 tmpblock = bbody;    /* can never be null */
2587
2588     /* DEAD CODE
2589     else if (bpostcond)  tmpblock = bpostcond;
2590     else                 tmpblock = bout;
2591     */
2592
2593     if (!ir_block_create_jump(bin, m_context, tmpblock))
2594         return false;
2595
2596     /* From precond */
2597     if (bprecond)
2598     {
2599         ir_block *ontrue, *onfalse;
2600         ontrue = bbody; /* can never be null */
2601
2602         /* all of this is dead code
2603         else if (bincrement) ontrue = bincrement;
2604         else                 ontrue = bpostcond;
2605         */
2606
2607         onfalse = bout;
2608         if (m_pre_not) {
2609             tmpblock = ontrue;
2610             ontrue   = onfalse;
2611             onfalse  = tmpblock;
2612         }
2613         if (!ir_block_create_if(end_bprecond, m_context, precond, ontrue, onfalse))
2614             return false;
2615     }
2616
2617     /* from body */
2618     if (bbody)
2619     {
2620         if      (bincrement) tmpblock = bincrement;
2621         else if (bpostcond)  tmpblock = bpostcond;
2622         else if (bprecond)   tmpblock = bprecond;
2623         else                 tmpblock = bbody;
2624         if (!end_bbody->m_final && !ir_block_create_jump(end_bbody, m_context, tmpblock))
2625             return false;
2626     }
2627
2628     /* from increment */
2629     if (bincrement)
2630     {
2631         if      (bpostcond)  tmpblock = bpostcond;
2632         else if (bprecond)   tmpblock = bprecond;
2633         else if (bbody)      tmpblock = bbody;
2634         else                 tmpblock = bout;
2635         if (!ir_block_create_jump(end_bincrement, m_context, tmpblock))
2636             return false;
2637     }
2638
2639     /* from postcond */
2640     if (bpostcond)
2641     {
2642         ir_block *ontrue, *onfalse;
2643         if      (bprecond)   ontrue = bprecond;
2644         else                 ontrue = bbody; /* can never be null */
2645
2646         /* all of this is dead code
2647         else if (bincrement) ontrue = bincrement;
2648         else                 ontrue = bpostcond;
2649         */
2650
2651         onfalse = bout;
2652         if (m_post_not) {
2653             tmpblock = ontrue;
2654             ontrue   = onfalse;
2655             onfalse  = tmpblock;
2656         }
2657         if (!ir_block_create_if(end_bpostcond, m_context, postcond, ontrue, onfalse))
2658             return false;
2659     }
2660
2661     /* Move 'bout' to the end */
2662     algo::shiftback(func->m_ir_func->m_blocks.begin() + bout_id,
2663                     func->m_ir_func->m_blocks.end());
2664     // FIXME::DELME::
2665     //func->m_ir_func->m_blocks[bout_id].release(); // it's a vector<std::unique_ptr<>>
2666     //func->m_ir_func->m_blocks.erase(func->m_ir_func->m_blocks.begin() + bout_id);
2667     //func->m_ir_func->m_blocks.emplace_back(bout);
2668
2669     return true;
2670 }
2671
2672 bool ast_breakcont::codegen(ast_function *func, bool lvalue, ir_value **out)
2673 {
2674     ir_block *target;
2675
2676     *out = nullptr;
2677
2678     if (lvalue) {
2679         compile_error(m_context, "break/continue expression is not an l-value");
2680         return false;
2681     }
2682
2683     if (m_outr) {
2684         compile_error(m_context, "internal error: ast_breakcont cannot be reused!");
2685         return false;
2686     }
2687     m_outr = (ir_value*)1;
2688
2689     if (m_is_continue)
2690         target = func->m_continueblocks[func->m_continueblocks.size()-1-m_levels];
2691     else
2692         target = func->m_breakblocks[func->m_breakblocks.size()-1-m_levels];
2693
2694     if (!target) {
2695         compile_error(m_context, "%s is lacking a target block", (m_is_continue ? "continue" : "break"));
2696         return false;
2697     }
2698
2699     if (!ir_block_create_jump(func->m_curblock, m_context, target))
2700         return false;
2701     return true;
2702 }
2703
2704 bool ast_switch::codegen(ast_function *func, bool lvalue, ir_value **out)
2705 {
2706     ast_switch_case *def_case     = nullptr;
2707     ir_block        *def_bfall    = nullptr;
2708     ir_block        *def_bfall_to = nullptr;
2709     bool set_def_bfall_to = false;
2710
2711     ir_value *dummy     = nullptr;
2712     ir_value *irop      = nullptr;
2713     ir_block *bout      = nullptr;
2714     ir_block *bfall     = nullptr;
2715     size_t    bout_id;
2716
2717     char      typestr[1024];
2718     uint16_t  cmpinstr;
2719
2720     if (lvalue) {
2721         compile_error(m_context, "switch expression is not an l-value");
2722         return false;
2723     }
2724
2725     if (m_outr) {
2726         compile_error(m_context, "internal error: ast_switch cannot be reused!");
2727         return false;
2728     }
2729     m_outr = (ir_value*)1;
2730
2731     (void)lvalue;
2732     (void)out;
2733
2734     if (!m_operand->codegen(func, false, &irop))
2735         return false;
2736
2737     if (m_cases.empty())
2738         return true;
2739
2740     cmpinstr = type_eq_instr[irop->m_vtype];
2741     if (cmpinstr >= VINSTR_END) {
2742         ast_type_to_string(m_operand, typestr, sizeof(typestr));
2743         compile_error(m_context, "invalid type to perform a switch on: %s", typestr);
2744         return false;
2745     }
2746
2747     bout_id = func->m_ir_func->m_blocks.size();
2748     bout = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("after_switch"));
2749     if (!bout)
2750         return false;
2751
2752     /* setup the break block */
2753     func->m_breakblocks.push_back(bout);
2754
2755     /* Now create all cases */
2756     for (auto &it : m_cases) {
2757         ir_value *cond, *val;
2758         ir_block *bcase, *bnot;
2759         size_t bnot_id;
2760
2761         ast_switch_case *swcase = &it;
2762
2763         if (swcase->m_value) {
2764             /* A regular case */
2765             /* generate the condition operand */
2766             if (!swcase->m_value->codegen(func, false, &val))
2767                 return false;
2768             /* generate the condition */
2769             cond = ir_block_create_binop(func->m_curblock, m_context, func->makeLabel("switch_eq"), cmpinstr, irop, val);
2770             if (!cond)
2771                 return false;
2772
2773             bcase = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("case"));
2774             bnot_id = func->m_ir_func->m_blocks.size();
2775             bnot = ir_function_create_block(m_context, func->m_ir_func, func->makeLabel("not_case"));
2776             if (!bcase || !bnot)
2777                 return false;
2778             if (set_def_bfall_to) {
2779                 set_def_bfall_to = false;
2780                 def_bfall_to = bcase;
2781             }
2782             if (!ir_block_create_if(func->m_curblock, m_context, cond, bcase, bnot))
2783                 return false;
2784
2785             /* Make the previous case-end fall through */
2786             if (bfall && !bfall->m_final) {
2787                 if (!ir_block_create_jump(bfall, m_context, bcase))
2788                     return false;
2789             }
2790
2791             /* enter the case */
2792             func->m_curblock = bcase;
2793             if (!swcase->m_code->codegen(func, false, &dummy))
2794                 return false;
2795
2796             /* remember this block to fall through from */
2797             bfall = func->m_curblock;
2798
2799             /* enter the else and move it down */
2800             func->m_curblock = bnot;
2801             algo::shiftback(func->m_ir_func->m_blocks.begin() + bnot_id,
2802                             func->m_ir_func->m_blocks.end());
2803             // FIXME::DELME::
2804             //func->m_ir_func->m_blocks[bnot_id].release();
2805             //func->m_ir_func->m_blocks.erase(func->m_ir_func->m_blocks.begin() + bnot_id);
2806             //func->m_ir_func->m_blocks.emplace_back(bnot);
2807         } else {
2808             /* The default case */
2809             /* Remember where to fall through from: */
2810             def_bfall = bfall;
2811             bfall     = nullptr;
2812             /* remember which case it was */
2813             def_case  = swcase;
2814             /* And the next case will be remembered */
2815             set_def_bfall_to = true;
2816         }
2817     }
2818
2819     /* Jump from the last bnot to bout */
2820     if (bfall && !bfall->m_final && !ir_block_create_jump(bfall, m_context, bout)) {
2821         /*
2822         astwarning(bfall->m_context, WARN_???, "missing break after last case");
2823         */
2824         return false;
2825     }
2826
2827     /* If there was a default case, put it down here */
2828     if (def_case) {
2829         ir_block *bcase;
2830
2831         /* No need to create an extra block */
2832         bcase = func->m_curblock;
2833
2834         /* Insert the fallthrough jump */
2835         if (def_bfall && !def_bfall->m_final) {
2836             if (!ir_block_create_jump(def_bfall, m_context, bcase))
2837                 return false;
2838         }
2839
2840         /* Now generate the default code */
2841         if (!def_case->m_code->codegen(func, false, &dummy))
2842             return false;
2843
2844         /* see if we need to fall through */
2845         if (def_bfall_to && !func->m_curblock->m_final)
2846         {
2847             if (!ir_block_create_jump(func->m_curblock, m_context, def_bfall_to))
2848                 return false;
2849         }
2850     }
2851
2852     /* Jump from the last bnot to bout */
2853     if (!func->m_curblock->m_final && !ir_block_create_jump(func->m_curblock, m_context, bout))
2854         return false;
2855     /* enter the outgoing block */
2856     func->m_curblock = bout;
2857
2858     /* restore the break block */
2859     func->m_breakblocks.pop_back();
2860
2861     /* Move 'bout' to the end, it's nicer */
2862     algo::shiftback(func->m_ir_func->m_blocks.begin() + bout_id,
2863                     func->m_ir_func->m_blocks.end());
2864     // FIXME::DELME::
2865     //func->m_ir_func->m_blocks[bout_id].release();
2866     //func->m_ir_func->m_blocks.erase(func->m_ir_func->m_blocks.begin() + bout_id);
2867     //func->m_ir_func->m_blocks.emplace_back(bout);
2868
2869     return true;
2870 }
2871
2872 bool ast_label::codegen(ast_function *func, bool lvalue, ir_value **out)
2873 {
2874     ir_value *dummy;
2875
2876     if (m_undefined) {
2877         compile_error(m_context, "internal error: ast_label never defined");
2878         return false;
2879     }
2880
2881     *out = nullptr;
2882     if (lvalue) {
2883         compile_error(m_context, "internal error: ast_label cannot be an lvalue");
2884         return false;
2885     }
2886
2887     /* simply create a new block and jump to it */
2888     m_irblock = ir_function_create_block(m_context, func->m_ir_func, m_name.c_str());
2889     if (!m_irblock) {
2890         compile_error(m_context, "failed to allocate label block `%s`", m_name);
2891         return false;
2892     }
2893     if (!func->m_curblock->m_final) {
2894         if (!ir_block_create_jump(func->m_curblock, m_context, m_irblock))
2895             return false;
2896     }
2897
2898     /* enter the new block */
2899     func->m_curblock = m_irblock;
2900
2901     /* Generate all the leftover gotos */
2902     for (auto &it : m_gotos) {
2903         if (!it->codegen(func, false, &dummy))
2904             return false;
2905     }
2906
2907     return true;
2908 }
2909
2910 bool ast_goto::codegen(ast_function *func, bool lvalue, ir_value **out)
2911 {
2912     *out = nullptr;
2913     if (lvalue) {
2914         compile_error(m_context, "internal error: ast_goto cannot be an lvalue");
2915         return false;
2916     }
2917
2918     if (m_target->m_irblock) {
2919         if (m_irblock_from) {
2920             /* we already tried once, this is the callback */
2921             m_irblock_from->m_final = false;
2922             if (!ir_block_create_goto(m_irblock_from, m_context, m_target->m_irblock)) {
2923                 compile_error(m_context, "failed to generate goto to `%s`", m_name);
2924                 return false;
2925             }
2926         }
2927         else
2928         {
2929             if (!ir_block_create_goto(func->m_curblock, m_context, m_target->m_irblock)) {
2930                 compile_error(m_context, "failed to generate goto to `%s`", m_name);
2931                 return false;
2932             }
2933         }
2934     }
2935     else
2936     {
2937         /* the target has not yet been created...
2938          * close this block in a sneaky way:
2939          */
2940         func->m_curblock->m_final = true;
2941         m_irblock_from = func->m_curblock;
2942         m_target->registerGoto(this);
2943     }
2944
2945     return true;
2946 }
2947
2948 bool ast_state::codegen(ast_function *func, bool lvalue, ir_value **out)
2949 {
2950     ir_value *frameval, *thinkval;
2951
2952     if (lvalue) {
2953         compile_error(m_context, "not an l-value (state operation)");
2954         return false;
2955     }
2956     if (m_outr) {
2957         compile_error(m_context, "internal error: ast_state cannot be reused!");
2958         return false;
2959     }
2960     *out = nullptr;
2961
2962     if (!m_framenum->codegen(func, false, &frameval))
2963         return false;
2964     if (!frameval)
2965         return false;
2966
2967     if (!m_nextthink->codegen(func, false, &thinkval))
2968         return false;
2969     if (!frameval)
2970         return false;
2971
2972     if (!ir_block_create_state_op(func->m_curblock, m_context, frameval, thinkval)) {
2973         compile_error(m_context, "failed to create STATE instruction");
2974         return false;
2975     }
2976
2977     m_outr = (ir_value*)1;
2978     return true;
2979 }
2980
2981 bool ast_call::codegen(ast_function *func, bool lvalue, ir_value **out)
2982 {
2983     std::vector<ir_value*> params;
2984     ir_instr *callinstr;
2985
2986     ir_value *funval = nullptr;
2987
2988     /* return values are never lvalues */
2989     if (lvalue) {
2990         compile_error(m_context, "not an l-value (function call)");
2991         return false;
2992     }
2993
2994     if (m_outr) {
2995         *out = m_outr;
2996         return true;
2997     }
2998
2999     if (!m_func->codegen(func, false, &funval))
3000         return false;
3001     if (!funval)
3002         return false;
3003
3004     /* parameters */
3005     for (auto &it : m_params) {
3006         ir_value *param;
3007         if (!it->codegen(func, false, &param))
3008             return false;
3009         if (!param)
3010             return false;
3011         params.push_back(param);
3012     }
3013
3014     /* varargs counter */
3015     if (m_va_count) {
3016         ir_value   *va_count;
3017         ir_builder *builder = func->m_curblock->m_owner->m_owner;
3018         if (!m_va_count->codegen(func, false, &va_count))
3019             return false;
3020         if (!ir_block_create_store_op(func->m_curblock, m_context, INSTR_STORE_F,
3021                                       ir_builder_get_va_count(builder), va_count))
3022         {
3023             return false;
3024         }
3025     }
3026
3027     callinstr = ir_block_create_call(func->m_curblock, m_context,
3028                                      func->makeLabel("call"),
3029                                      funval, !!(m_func->m_flags & AST_FLAG_NORETURN));
3030     if (!callinstr)
3031         return false;
3032
3033     for (auto &it : params)
3034         ir_call_param(callinstr, it);
3035
3036     *out = ir_call_value(callinstr);
3037     m_outr = *out;
3038
3039     codegen_output_type(this, *out);
3040
3041     return true;
3042 }