]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ast.c
ast_binary_codegen, ast_function_label (no I don't like sprintf...)
[xonotic/gmqcc.git] / ast.c
1 /*
2  * Copyright (C) 2012
3  *     Wolfgang Bumiller
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of
6  * this software and associated documentation files (the "Software"), to deal in
7  * the Software without restriction, including without limitation the rights to
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9  * of the Software, and to permit persons to whom the Software is furnished to do
10  * so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  */
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include "gmqcc.h"
28 #include "ast.h"
29
30 #define ast_instantiate(T, ctx, destroyfn)                          \
31     T* self = (T*)mem_a(sizeof(T));                                 \
32     if (!self) {                                                    \
33         return NULL;                                                \
34     }                                                               \
35     ast_node_init((ast_node*)self, ctx);                            \
36     ( (ast_node*)self )->node.destroy = (ast_node_delete*)destroyfn
37
38 /* It must not be possible to get here. */
39 static void _ast_node_destroy(ast_node *self)
40 {
41     fprintf(stderr, "ast node missing destroy()\n");
42     abort();
43 }
44
45 /* Initialize main ast node aprts */
46 static void ast_node_init(ast_node *self, lex_ctx ctx)
47 {
48     self->node.context = ctx;
49     self->node.destroy = &_ast_node_destroy;
50     self->node.keep    = false;
51 }
52
53 /* General expression initialization */
54 static void ast_expression_init(ast_expression *self,
55                                 ast_expression_codegen *codegen)
56 {
57     self->expression.codegen = codegen;
58 }
59
60 ast_value* ast_value_new(lex_ctx ctx, const char *name, int t)
61 {
62     ast_instantiate(ast_value, ctx, ast_value_delete);
63     ast_expression_init((ast_expression*)self,
64                         (ast_expression_codegen*)&ast_value_codegen);
65     self->expression.node.keep = true; /* keep */
66
67     self->name = name ? util_strdup(name) : NULL;
68     self->vtype = t;
69     self->next = NULL;
70     MEM_VECTOR_INIT(self, params);
71     self->isconst = false;
72     memset(&self->constval, 0, sizeof(self->constval));
73
74     self->ir_v    = NULL;
75
76     return self;
77 }
78 MEM_VEC_FUNCTIONS(ast_value, ast_value*, params)
79
80 void ast_value_delete(ast_value* self)
81 {
82     size_t i;
83     if (self->name)
84         mem_d((void*)self->name);
85     for (i = 0; i < self->params_count; ++i)
86         ast_value_delete(self->params[i]); /* delete, the ast_function is expected to die first */
87     MEM_VECTOR_CLEAR(self, params);
88     if (self->next) /* delete, not unref, types are always copied */
89         ast_delete(self->next);
90     if (self->isconst) {
91         switch (self->vtype)
92         {
93         case TYPE_STRING:
94             mem_d((void*)self->constval.vstring);
95             break;
96         case TYPE_FUNCTION:
97             /* unlink us from the function node */
98             self->constval.vfunc->vtype = NULL;
99             break;
100         /* NOTE: delete function? currently collected in
101          * the parser structure
102          */
103         default:
104             break;
105         }
106     }
107     mem_d(self);
108 }
109
110 bool ast_value_set_name(ast_value *self, const char *name)
111 {
112     if (self->name)
113         mem_d((void*)self->name);
114     self->name = util_strdup(name);
115     return !!self->name;
116 }
117
118 ast_binary* ast_binary_new(lex_ctx ctx, int op,
119                            ast_expression* left, ast_expression* right)
120 {
121     ast_instantiate(ast_binary, ctx, ast_binary_delete);
122     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_binary_codegen);
123
124     self->op = op;
125     self->left = left;
126     self->right = right;
127
128     return self;
129 }
130
131 void ast_binary_delete(ast_binary *self)
132 {
133     ast_unref(self->left);
134     ast_unref(self->right);
135     mem_d(self);
136 }
137
138 ast_entfield* ast_entfield_new(lex_ctx ctx, ast_expression *entity, ast_expression *field)
139 {
140     ast_instantiate(ast_entfield, ctx, ast_entfield_delete);
141     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_entfield_codegen);
142
143     self->entity = entity;
144     self->field  = field;
145
146     return self;
147 }
148
149 void ast_entfield_delete(ast_entfield *self)
150 {
151     ast_unref(self->entity);
152     ast_unref(self->field);
153     mem_d(self);
154 }
155
156 ast_ifthen* ast_ifthen_new(lex_ctx ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
157 {
158     ast_instantiate(ast_ifthen, ctx, ast_ifthen_delete);
159     if (!ontrue && !onfalse) {
160         /* because it is invalid */
161         mem_d(self);
162         return NULL;
163     }
164     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ifthen_codegen);
165
166     self->cond     = cond;
167     self->on_true  = ontrue;
168     self->on_false = onfalse;
169
170     return self;
171 }
172
173 void ast_ifthen_delete(ast_ifthen *self)
174 {
175     ast_unref(self->cond);
176     ast_unref(self->on_true);
177     ast_unref(self->on_false);
178     mem_d(self);
179 }
180
181 ast_ternary* ast_ternary_new(lex_ctx ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse)
182 {
183     ast_instantiate(ast_ternary, ctx, ast_ternary_delete);
184     /* This time NEITHER must be NULL */
185     if (!ontrue || !onfalse) {
186         mem_d(self);
187         return NULL;
188     }
189     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_ternary_codegen);
190
191     self->cond     = cond;
192     self->on_true  = ontrue;
193     self->on_false = onfalse;
194     self->phi_out  = NULL;
195
196     return self;
197 }
198
199 void ast_ternary_delete(ast_ternary *self)
200 {
201     ast_unref(self->cond);
202     ast_unref(self->on_true);
203     ast_unref(self->on_false);
204     mem_d(self);
205 }
206
207 ast_store* ast_store_new(lex_ctx ctx, int op,
208                          ast_value *dest, ast_expression *source)
209 {
210     ast_instantiate(ast_store, ctx, ast_store_delete);
211     ast_expression_init((ast_expression*)self, (ast_expression_codegen*)&ast_store_codegen);
212
213     self->op = op;
214     self->dest = dest;
215     self->source = source;
216
217     return self;
218 }
219
220 void ast_store_delete(ast_store *self)
221 {
222     ast_unref(self->dest);
223     ast_unref(self->source);
224     mem_d(self);
225 }
226
227 ast_block* ast_block_new(lex_ctx ctx)
228 {
229     ast_instantiate(ast_block, ctx, ast_block_delete);
230     ast_expression_init((ast_expression*)self,
231                         (ast_expression_codegen*)&ast_block_codegen);
232
233     MEM_VECTOR_INIT(self, locals);
234     MEM_VECTOR_INIT(self, exprs);
235
236     return self;
237 }
238 MEM_VEC_FUNCTIONS(ast_block, ast_value*, locals)
239 MEM_VEC_FUNCTIONS(ast_block, ast_expression*, exprs)
240
241 void ast_block_delete(ast_block *self)
242 {
243     size_t i;
244     for (i = 0; i < self->exprs_count; ++i)
245         ast_unref(self->exprs[i]);
246     MEM_VECTOR_CLEAR(self, exprs);
247     for (i = 0; i < self->locals_count; ++i)
248         ast_delete(self->locals[i]);
249     MEM_VECTOR_CLEAR(self, locals);
250     mem_d(self);
251 }
252
253 ast_function* ast_function_new(lex_ctx ctx, const char *name, ast_value *vtype)
254 {
255     ast_instantiate(ast_function, ctx, ast_function_delete);
256
257     if (!vtype ||
258         vtype->isconst ||
259         vtype->vtype != TYPE_FUNCTION)
260     {
261         mem_d(self);
262         return NULL;
263     }
264
265     self->vtype = vtype;
266     self->name = name ? util_strdup(name) : NULL;
267     MEM_VECTOR_INIT(self, blocks);
268
269     self->labelcount = 0;
270
271     self->ir_func = NULL;
272     self->curblock = NULL;
273
274     vtype->isconst = true;
275     vtype->constval.vfunc = self;
276
277     return self;
278 }
279
280 MEM_VEC_FUNCTIONS(ast_function, ast_block*, blocks)
281
282 void ast_function_delete(ast_function *self)
283 {
284     size_t i;
285     if (self->name)
286         mem_d((void*)self->name);
287     if (self->vtype) {
288         /* ast_value_delete(self->vtype); */
289         self->vtype->isconst = false;
290         self->vtype->constval.vfunc = NULL;
291         /* We use unref - if it was stored in a global table it is supposed
292          * to be deleted from *there*
293          */
294         ast_unref(self->vtype);
295     }
296     for (i = 0; i < self->blocks_count; ++i)
297         ast_delete(self->blocks[i]);
298     MEM_VECTOR_CLEAR(self, blocks);
299     mem_d(self);
300 }
301
302 const char* ast_function_label(ast_function *self)
303 {
304     size_t id = (self->labelcount++);
305     sprintf(self->labelbuf, "label%8u", (unsigned int)id);
306     return self->labelbuf;
307 }
308
309 /*********************************************************************/
310 /* AST codegen part
311  * by convention you must never pass NULL to the 'ir_value **out'
312  * parameter. If you really don't care about the output, pass a dummy.
313  * But I can't imagine a pituation where the output is truly unnecessary.
314  */
315
316 bool ast_value_codegen(ast_value *self, ast_function *func, bool lvalue, ir_value **out)
317 {
318     /* NOTE: This is the codegen for a variable used in an expression.
319      * It is not the codegen to generate the value. For this purpose,
320      * ast_local_codegen and ast_global_codegen are to be used before this
321      * is executed. ast_function_codegen should take care of its locals,
322      * and the ast-user should take care of ast_global_codegen to be used
323      * on all the globals.
324      */
325     if (!self->ir_v)
326         return false;
327     *out = self->ir_v;
328     return true;
329 }
330
331 bool ast_global_codegen(ast_value *self, ir_builder *ir)
332 {
333     ir_value *v = NULL;
334     if (self->isconst && self->vtype == TYPE_FUNCTION)
335     {
336         ir_function *func = ir_builder_create_function(ir, self->name);
337         if (!func)
338             return false;
339
340         self->constval.vfunc->ir_func = func;
341         /* The function is filled later on ast_function_codegen... */
342         return true;
343     }
344
345     v = ir_builder_create_global(ir, self->name, self->vtype);
346     if (!v)
347         return false;
348
349     if (self->isconst) {
350         switch (self->vtype)
351         {
352             case TYPE_FLOAT:
353                 if (!ir_value_set_float(v, self->constval.vfloat))
354                     goto error;
355                 break;
356             case TYPE_VECTOR:
357                 if (!ir_value_set_vector(v, self->constval.vvec))
358                     goto error;
359                 break;
360             case TYPE_STRING:
361                 if (!ir_value_set_string(v, self->constval.vstring))
362                     goto error;
363                 break;
364             case TYPE_FUNCTION:
365                 /* Cannot generate an IR value for a function,
366                  * need a pointer pointing to a function rather.
367                  */
368                 goto error;
369             default:
370                 printf("TODO: global constant type %i\n", self->vtype);
371                 break;
372         }
373     }
374
375     /* link us to the ir_value */
376     self->ir_v = v;
377     return true;
378
379 error: /* clean up */
380     ir_value_delete(v);
381     return false;
382 }
383
384 bool ast_local_codegen(ast_value *self, ir_function *func)
385 {
386     ir_value *v = NULL;
387     if (self->isconst && self->vtype == TYPE_FUNCTION)
388     {
389         /* Do we allow local functions? I think not...
390          * this is NOT a function pointer atm.
391          */
392         return false;
393     }
394
395     v = ir_function_create_local(func, self->name, self->vtype);
396     if (!v)
397         return false;
398
399     /* A constant local... hmmm...
400      * I suppose the IR will have to deal with this
401      */
402     if (self->isconst) {
403         switch (self->vtype)
404         {
405             case TYPE_FLOAT:
406                 if (!ir_value_set_float(v, self->constval.vfloat))
407                     goto error;
408                 break;
409             case TYPE_VECTOR:
410                 if (!ir_value_set_vector(v, self->constval.vvec))
411                     goto error;
412                 break;
413             case TYPE_STRING:
414                 if (!ir_value_set_string(v, self->constval.vstring))
415                     goto error;
416                 break;
417             default:
418                 printf("TODO: global constant type %i\n", self->vtype);
419                 break;
420         }
421     }
422
423     /* link us to the ir_value */
424     self->ir_v = v;
425     return true;
426
427 error: /* clean up */
428     ir_value_delete(v);
429     return false;
430 }
431
432 bool ast_function_codegen(ast_function *self, ir_builder *ir)
433 {
434     ir_function *irf;
435     ir_value    *dummy;
436     size_t    i;
437
438     irf = self->ir_func;
439     if (!irf) {
440         printf("ast_function's related ast_value was not generated yet\n");
441         return false;
442     }
443
444     self->curblock = ir_function_create_block(irf, "entry");
445     if (!self->curblock)
446         return false;
447
448     for (i = 0; i < self->blocks_count; ++i) {
449         ast_expression_codegen *gen = self->blocks[i]->expression.codegen;
450         if (!(*gen)((ast_expression*)self->blocks[i], self, false, &dummy))
451             return false;
452     }
453     return true;
454 }
455
456 /* Note, you will not see ast_block_codegen generate ir_blocks.
457  * To the AST and the IR, blocks are 2 different things.
458  * In the AST it represents a block of code, usually enclosed in
459  * curly braces {...}.
460  * While in the IR it represents a block in terms of control-flow.
461  */
462 bool ast_block_codegen(ast_block *self, ast_function *func, bool lvalue, ir_value **out)
463 {
464     size_t i;
465
466     /* We don't use this
467      * Note: an ast-representation using the comma-operator
468      * of the form: (a, b, c) = x should not assign to c...
469      */
470     (void)lvalue;
471
472     /* output is NULL at first, we'll have each expression
473      * assign to out output, thus, a comma-operator represention
474      * using an ast_block will return the last generated value,
475      * so: (b, c) + a  executed both b and c, and returns c,
476      * which is then added to a.
477      */
478     *out = NULL;
479
480     /* generate locals */
481     for (i = 0; i < self->locals_count; ++i)
482     {
483         if (!ast_local_codegen(self->locals[i], func->ir_func))
484             return false;
485     }
486
487     for (i = 0; i < self->exprs_count; ++i)
488     {
489         ast_expression_codegen *gen = self->exprs[i]->expression.codegen;
490         if (!(*gen)(self->exprs[i], func, false, out))
491             return false;
492     }
493
494     return true;
495 }
496
497 bool ast_store_codegen(ast_store *self, ast_function *func, bool lvalue, ir_value **out)
498 {
499     ast_expression_codegen *cgen;
500     ir_value *left, *right;
501
502     cgen = self->dest->expression.codegen;
503     /* lvalue! */
504     if (!(*cgen)((ast_expression*)(self->dest), func, true, &left))
505         return false;
506
507     cgen = self->source->expression.codegen;
508     /* rvalue! */
509     if (!(*cgen)((ast_expression*)(self->source), func, false, &right))
510         return false;
511
512     if (!ir_block_create_store_op(func->curblock, self->op, left, right))
513         return false;
514
515     /* Theoretically, an assinment returns its left side as an
516      * lvalue, if we don't need an lvalue though, we return
517      * the right side as an rvalue, otherwise we have to
518      * somehow know whether or not we need to dereference the pointer
519      * on the left side - that is: OP_LOAD if it was an address.
520      * Also: in original QC we cannot OP_LOADP *anyway*.
521      */
522     *out = (lvalue ? left : right);
523
524     return true;
525 }
526
527 bool ast_binary_codegen(ast_binary *self, ast_function *func, bool lvalue, ir_value **out)
528 {
529     ast_expression_codegen *cgen;
530     ir_value *left, *right;
531
532     /* In the context of a binary operation, we can disregard
533      * the lvalue flag.
534      */
535      (void)lvalue;
536
537     cgen = self->left->expression.codegen;
538     /* lvalue! */
539     if (!(*cgen)((ast_expression*)(self->left), func, false, &left))
540         return false;
541
542     cgen = self->right->expression.codegen;
543     /* rvalue! */
544     if (!(*cgen)((ast_expression*)(self->right), func, false, &right))
545         return false;
546
547     *out = ir_block_create_binop(func->curblock, ast_function_label(func),
548                                  self->op, left, right);
549     if (!*out)
550         return false;
551
552     return true;
553 }
554
555 bool ast_entfield_codegen(ast_entfield *self, ast_function *func, bool lvalue, ir_value **out)
556 {
557     return false;
558 }
559
560 bool ast_ifthen_codegen(ast_ifthen *self, ast_function *func, bool lvalue, ir_value **out)
561 {
562     if (out) *out = NULL;
563     return false;
564 }
565
566 bool ast_ternary_codegen(ast_ternary *self, ast_function *func, bool lvalue, ir_value **out)
567 {
568     /* In theory it shouldn't be possible to pass through a node twice, but
569      * in case we add any kind of optimization pass for the AST itself, it
570      * may still happen, thus we remember a created ir_value and simply return one
571      * if it already exists.
572      */
573     if (self->phi_out) {
574         *out = self->phi_out;
575         return true;
576     }
577     return false;
578 }