Merge branch 'master' of git+ssh://pmandin@git.freedesktop.org/git/mesa/mesa
[mesa.git] / src / mesa / shader / slang / slang_codegen.c
1 /*
2 * Mesa 3-D graphics library
3 * Version: 6.5.3
4 *
5 * Copyright (C) 2005-2007 Brian Paul All Rights Reserved.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a
8 * copy of this software and associated documentation files (the "Software"),
9 * to deal in the Software without restriction, including without limitation
10 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 * and/or sell copies of the Software, and to permit persons to whom the
12 * Software is furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included
15 * in all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
21 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 */
24
25 /**
26 * \file slang_codegen.c
27 * Generate IR tree from AST.
28 * \author Brian Paul
29 */
30
31
32 /***
33 *** NOTES:
34 *** The new_() functions return a new instance of a simple IR node.
35 *** The gen_() functions generate larger IR trees from the simple nodes.
36 ***/
37
38
39
40 #include "main/imports.h"
41 #include "main/macros.h"
42 #include "main/mtypes.h"
43 #include "shader/program.h"
44 #include "shader/prog_instruction.h"
45 #include "shader/prog_parameter.h"
46 #include "shader/prog_statevars.h"
47 #include "slang_typeinfo.h"
48 #include "slang_codegen.h"
49 #include "slang_compile.h"
50 #include "slang_label.h"
51 #include "slang_mem.h"
52 #include "slang_simplify.h"
53 #include "slang_emit.h"
54 #include "slang_vartable.h"
55 #include "slang_ir.h"
56 #include "slang_print.h"
57
58
59 static slang_ir_node *
60 _slang_gen_operation(slang_assemble_ctx * A, slang_operation *oper);
61
62
63 static GLboolean
64 is_sampler_type(const slang_fully_specified_type *t)
65 {
66 switch (t->specifier.type) {
67 case SLANG_SPEC_SAMPLER1D:
68 case SLANG_SPEC_SAMPLER2D:
69 case SLANG_SPEC_SAMPLER3D:
70 case SLANG_SPEC_SAMPLERCUBE:
71 case SLANG_SPEC_SAMPLER1DSHADOW:
72 case SLANG_SPEC_SAMPLER2DSHADOW:
73 case SLANG_SPEC_SAMPLER2DRECT:
74 case SLANG_SPEC_SAMPLER2DRECTSHADOW:
75 return GL_TRUE;
76 default:
77 return GL_FALSE;
78 }
79 }
80
81
82 /**
83 * Return the offset (in floats or ints) of the named field within
84 * the given struct. Return -1 if field not found.
85 * If field is NULL, return the size of the struct instead.
86 */
87 static GLint
88 _slang_field_offset(const slang_type_specifier *spec, slang_atom field)
89 {
90 GLint offset = 0;
91 GLuint i;
92 for (i = 0; i < spec->_struct->fields->num_variables; i++) {
93 const slang_variable *v = spec->_struct->fields->variables[i];
94 const GLuint sz = _slang_sizeof_type_specifier(&v->type.specifier);
95 if (sz > 1) {
96 /* types larger than 1 float are register (4-float) aligned */
97 offset = (offset + 3) & ~3;
98 }
99 if (field && v->a_name == field) {
100 return offset;
101 }
102 offset += sz;
103 }
104 if (field)
105 return -1; /* field not found */
106 else
107 return offset; /* struct size */
108 }
109
110
111 /**
112 * Return the size (in floats) of the given type specifier.
113 * If the size is greater than 4, the size should be a multiple of 4
114 * so that the correct number of 4-float registers are allocated.
115 * For example, a mat3x2 is size 12 because we want to store the
116 * 3 columns in 3 float[4] registers.
117 */
118 GLuint
119 _slang_sizeof_type_specifier(const slang_type_specifier *spec)
120 {
121 GLuint sz;
122 switch (spec->type) {
123 case SLANG_SPEC_VOID:
124 sz = 0;
125 break;
126 case SLANG_SPEC_BOOL:
127 sz = 1;
128 break;
129 case SLANG_SPEC_BVEC2:
130 sz = 2;
131 break;
132 case SLANG_SPEC_BVEC3:
133 sz = 3;
134 break;
135 case SLANG_SPEC_BVEC4:
136 sz = 4;
137 break;
138 case SLANG_SPEC_INT:
139 sz = 1;
140 break;
141 case SLANG_SPEC_IVEC2:
142 sz = 2;
143 break;
144 case SLANG_SPEC_IVEC3:
145 sz = 3;
146 break;
147 case SLANG_SPEC_IVEC4:
148 sz = 4;
149 break;
150 case SLANG_SPEC_FLOAT:
151 sz = 1;
152 break;
153 case SLANG_SPEC_VEC2:
154 sz = 2;
155 break;
156 case SLANG_SPEC_VEC3:
157 sz = 3;
158 break;
159 case SLANG_SPEC_VEC4:
160 sz = 4;
161 break;
162 case SLANG_SPEC_MAT2:
163 sz = 2 * 4; /* 2 columns (regs) */
164 break;
165 case SLANG_SPEC_MAT3:
166 sz = 3 * 4;
167 break;
168 case SLANG_SPEC_MAT4:
169 sz = 4 * 4;
170 break;
171 case SLANG_SPEC_MAT23:
172 sz = 2 * 4; /* 2 columns (regs) */
173 break;
174 case SLANG_SPEC_MAT32:
175 sz = 3 * 4; /* 3 columns (regs) */
176 break;
177 case SLANG_SPEC_MAT24:
178 sz = 2 * 4;
179 break;
180 case SLANG_SPEC_MAT42:
181 sz = 4 * 4; /* 4 columns (regs) */
182 break;
183 case SLANG_SPEC_MAT34:
184 sz = 3 * 4;
185 break;
186 case SLANG_SPEC_MAT43:
187 sz = 4 * 4; /* 4 columns (regs) */
188 break;
189 case SLANG_SPEC_SAMPLER1D:
190 case SLANG_SPEC_SAMPLER2D:
191 case SLANG_SPEC_SAMPLER3D:
192 case SLANG_SPEC_SAMPLERCUBE:
193 case SLANG_SPEC_SAMPLER1DSHADOW:
194 case SLANG_SPEC_SAMPLER2DSHADOW:
195 case SLANG_SPEC_SAMPLER2DRECT:
196 case SLANG_SPEC_SAMPLER2DRECTSHADOW:
197 sz = 1; /* a sampler is basically just an integer index */
198 break;
199 case SLANG_SPEC_STRUCT:
200 sz = _slang_field_offset(spec, 0); /* special use */
201 if (sz > 4) {
202 sz = (sz + 3) & ~0x3; /* round up to multiple of four */
203 }
204 break;
205 case SLANG_SPEC_ARRAY:
206 sz = _slang_sizeof_type_specifier(spec->_array);
207 break;
208 default:
209 _mesa_problem(NULL, "Unexpected type in _slang_sizeof_type_specifier()");
210 sz = 0;
211 }
212
213 if (sz > 4) {
214 /* if size is > 4, it should be a multiple of four */
215 assert((sz & 0x3) == 0);
216 }
217 return sz;
218 }
219
220
221 /**
222 * Establish the binding between a slang_ir_node and a slang_variable.
223 * Then, allocate/attach a slang_ir_storage object to the IR node if needed.
224 * The IR node must be a IR_VAR or IR_VAR_DECL node.
225 * \param n the IR node
226 * \param var the variable to associate with the IR node
227 */
228 static void
229 _slang_attach_storage(slang_ir_node *n, slang_variable *var)
230 {
231 assert(n);
232 assert(var);
233 assert(n->Opcode == IR_VAR || n->Opcode == IR_VAR_DECL);
234 assert(!n->Var || n->Var == var);
235
236 n->Var = var;
237
238 if (!n->Store) {
239 /* need to setup storage */
240 if (n->Var && n->Var->aux) {
241 /* node storage info = var storage info */
242 n->Store = (slang_ir_storage *) n->Var->aux;
243 }
244 else {
245 /* alloc new storage info */
246 n->Store = _slang_new_ir_storage(PROGRAM_UNDEFINED, -1, -5);
247 if (n->Var)
248 n->Var->aux = n->Store;
249 assert(n->Var->aux);
250 }
251 }
252 }
253
254
255 /**
256 * Return the TEXTURE_*_INDEX value that corresponds to a sampler type,
257 * or -1 if the type is not a sampler.
258 */
259 static GLint
260 sampler_to_texture_index(const slang_type_specifier_type type)
261 {
262 switch (type) {
263 case SLANG_SPEC_SAMPLER1D:
264 return TEXTURE_1D_INDEX;
265 case SLANG_SPEC_SAMPLER2D:
266 return TEXTURE_2D_INDEX;
267 case SLANG_SPEC_SAMPLER3D:
268 return TEXTURE_3D_INDEX;
269 case SLANG_SPEC_SAMPLERCUBE:
270 return TEXTURE_CUBE_INDEX;
271 case SLANG_SPEC_SAMPLER1DSHADOW:
272 return TEXTURE_1D_INDEX; /* XXX fix */
273 case SLANG_SPEC_SAMPLER2DSHADOW:
274 return TEXTURE_2D_INDEX; /* XXX fix */
275 case SLANG_SPEC_SAMPLER2DRECT:
276 return TEXTURE_RECT_INDEX;
277 case SLANG_SPEC_SAMPLER2DRECTSHADOW:
278 return TEXTURE_RECT_INDEX; /* XXX fix */
279 default:
280 return -1;
281 }
282 }
283
284
285 /**
286 * Return the VERT_ATTRIB_* or FRAG_ATTRIB_* value that corresponds to
287 * a vertex or fragment program input variable. Return -1 if the input
288 * name is invalid.
289 * XXX return size too
290 */
291 static GLint
292 _slang_input_index(const char *name, GLenum target, GLuint *swizzleOut)
293 {
294 struct input_info {
295 const char *Name;
296 GLuint Attrib;
297 GLuint Swizzle;
298 };
299 static const struct input_info vertInputs[] = {
300 { "gl_Vertex", VERT_ATTRIB_POS, SWIZZLE_NOOP },
301 { "gl_Normal", VERT_ATTRIB_NORMAL, SWIZZLE_NOOP },
302 { "gl_Color", VERT_ATTRIB_COLOR0, SWIZZLE_NOOP },
303 { "gl_SecondaryColor", VERT_ATTRIB_COLOR1, SWIZZLE_NOOP },
304 { "gl_FogCoord", VERT_ATTRIB_FOG, SWIZZLE_XXXX },
305 { "gl_MultiTexCoord0", VERT_ATTRIB_TEX0, SWIZZLE_NOOP },
306 { "gl_MultiTexCoord1", VERT_ATTRIB_TEX1, SWIZZLE_NOOP },
307 { "gl_MultiTexCoord2", VERT_ATTRIB_TEX2, SWIZZLE_NOOP },
308 { "gl_MultiTexCoord3", VERT_ATTRIB_TEX3, SWIZZLE_NOOP },
309 { "gl_MultiTexCoord4", VERT_ATTRIB_TEX4, SWIZZLE_NOOP },
310 { "gl_MultiTexCoord5", VERT_ATTRIB_TEX5, SWIZZLE_NOOP },
311 { "gl_MultiTexCoord6", VERT_ATTRIB_TEX6, SWIZZLE_NOOP },
312 { "gl_MultiTexCoord7", VERT_ATTRIB_TEX7, SWIZZLE_NOOP },
313 { NULL, 0, SWIZZLE_NOOP }
314 };
315 static const struct input_info fragInputs[] = {
316 { "gl_FragCoord", FRAG_ATTRIB_WPOS, SWIZZLE_NOOP },
317 { "gl_Color", FRAG_ATTRIB_COL0, SWIZZLE_NOOP },
318 { "gl_SecondaryColor", FRAG_ATTRIB_COL1, SWIZZLE_NOOP },
319 { "gl_FogFragCoord", FRAG_ATTRIB_FOGC, SWIZZLE_XXXX },
320 { "gl_TexCoord", FRAG_ATTRIB_TEX0, SWIZZLE_NOOP },
321 { "gl_FrontFacing", FRAG_ATTRIB_FOGC, SWIZZLE_YYYY }, /*XXX*/
322 { NULL, 0, SWIZZLE_NOOP }
323 };
324 GLuint i;
325 const struct input_info *inputs
326 = (target == GL_VERTEX_PROGRAM_ARB) ? vertInputs : fragInputs;
327
328 ASSERT(MAX_TEXTURE_UNITS == 8); /* if this fails, fix vertInputs above */
329
330 for (i = 0; inputs[i].Name; i++) {
331 if (strcmp(inputs[i].Name, name) == 0) {
332 /* found */
333 *swizzleOut = inputs[i].Swizzle;
334 return inputs[i].Attrib;
335 }
336 }
337 return -1;
338 }
339
340
341 /**
342 * Return the VERT_RESULT_* or FRAG_RESULT_* value that corresponds to
343 * a vertex or fragment program output variable. Return -1 for an invalid
344 * output name.
345 */
346 static GLint
347 _slang_output_index(const char *name, GLenum target)
348 {
349 struct output_info {
350 const char *Name;
351 GLuint Attrib;
352 };
353 static const struct output_info vertOutputs[] = {
354 { "gl_Position", VERT_RESULT_HPOS },
355 { "gl_FrontColor", VERT_RESULT_COL0 },
356 { "gl_BackColor", VERT_RESULT_BFC0 },
357 { "gl_FrontSecondaryColor", VERT_RESULT_COL1 },
358 { "gl_BackSecondaryColor", VERT_RESULT_BFC1 },
359 { "gl_TexCoord", VERT_RESULT_TEX0 },
360 { "gl_FogFragCoord", VERT_RESULT_FOGC },
361 { "gl_PointSize", VERT_RESULT_PSIZ },
362 { NULL, 0 }
363 };
364 static const struct output_info fragOutputs[] = {
365 { "gl_FragColor", FRAG_RESULT_COLR },
366 { "gl_FragDepth", FRAG_RESULT_DEPR },
367 { "gl_FragData", FRAG_RESULT_DATA0 },
368 { NULL, 0 }
369 };
370 GLuint i;
371 const struct output_info *outputs
372 = (target == GL_VERTEX_PROGRAM_ARB) ? vertOutputs : fragOutputs;
373
374 for (i = 0; outputs[i].Name; i++) {
375 if (strcmp(outputs[i].Name, name) == 0) {
376 /* found */
377 return outputs[i].Attrib;
378 }
379 }
380 return -1;
381 }
382
383
384
385 /**********************************************************************/
386
387
388 /**
389 * Map "_asm foo" to IR_FOO, etc.
390 */
391 typedef struct
392 {
393 const char *Name;
394 slang_ir_opcode Opcode;
395 GLuint HaveRetValue, NumParams;
396 } slang_asm_info;
397
398
399 static slang_asm_info AsmInfo[] = {
400 /* vec4 binary op */
401 { "vec4_add", IR_ADD, 1, 2 },
402 { "vec4_subtract", IR_SUB, 1, 2 },
403 { "vec4_multiply", IR_MUL, 1, 2 },
404 { "vec4_dot", IR_DOT4, 1, 2 },
405 { "vec3_dot", IR_DOT3, 1, 2 },
406 { "vec3_cross", IR_CROSS, 1, 2 },
407 { "vec4_lrp", IR_LRP, 1, 3 },
408 { "vec4_min", IR_MIN, 1, 2 },
409 { "vec4_max", IR_MAX, 1, 2 },
410 { "vec4_clamp", IR_CLAMP, 1, 3 },
411 { "vec4_seq", IR_SEQUAL, 1, 2 },
412 { "vec4_sne", IR_SNEQUAL, 1, 2 },
413 { "vec4_sge", IR_SGE, 1, 2 },
414 { "vec4_sgt", IR_SGT, 1, 2 },
415 { "vec4_sle", IR_SLE, 1, 2 },
416 { "vec4_slt", IR_SLT, 1, 2 },
417 /* vec4 unary */
418 { "vec4_floor", IR_FLOOR, 1, 1 },
419 { "vec4_frac", IR_FRAC, 1, 1 },
420 { "vec4_abs", IR_ABS, 1, 1 },
421 { "vec4_negate", IR_NEG, 1, 1 },
422 { "vec4_ddx", IR_DDX, 1, 1 },
423 { "vec4_ddy", IR_DDY, 1, 1 },
424 /* float binary op */
425 { "float_power", IR_POW, 1, 2 },
426 /* texture / sampler */
427 { "vec4_tex1d", IR_TEX, 1, 2 },
428 { "vec4_texb1d", IR_TEXB, 1, 2 }, /* 1d w/ bias */
429 { "vec4_texp1d", IR_TEXP, 1, 2 }, /* 1d w/ projection */
430 { "vec4_tex2d", IR_TEX, 1, 2 },
431 { "vec4_texb2d", IR_TEXB, 1, 2 }, /* 2d w/ bias */
432 { "vec4_texp2d", IR_TEXP, 1, 2 }, /* 2d w/ projection */
433 { "vec4_tex3d", IR_TEX, 1, 2 },
434 { "vec4_texb3d", IR_TEXB, 1, 2 }, /* 3d w/ bias */
435 { "vec4_texp3d", IR_TEXP, 1, 2 }, /* 3d w/ projection */
436 { "vec4_texcube", IR_TEX, 1, 2 }, /* cubemap */
437 { "vec4_tex_rect", IR_TEX, 1, 2 }, /* rectangle */
438 { "vec4_texp_rect", IR_TEX, 1, 2 },/* rectangle w/ projection */
439
440 /* unary op */
441 { "int_to_float", IR_I_TO_F, 1, 1 },
442 { "float_to_int", IR_F_TO_I, 1, 1 },
443 { "float_exp", IR_EXP, 1, 1 },
444 { "float_exp2", IR_EXP2, 1, 1 },
445 { "float_log2", IR_LOG2, 1, 1 },
446 { "float_rsq", IR_RSQ, 1, 1 },
447 { "float_rcp", IR_RCP, 1, 1 },
448 { "float_sine", IR_SIN, 1, 1 },
449 { "float_cosine", IR_COS, 1, 1 },
450 { "float_noise1", IR_NOISE1, 1, 1},
451 { "float_noise2", IR_NOISE2, 1, 1},
452 { "float_noise3", IR_NOISE3, 1, 1},
453 { "float_noise4", IR_NOISE4, 1, 1},
454
455 { NULL, IR_NOP, 0, 0 }
456 };
457
458
459 static slang_ir_node *
460 new_node3(slang_ir_opcode op,
461 slang_ir_node *c0, slang_ir_node *c1, slang_ir_node *c2)
462 {
463 slang_ir_node *n = (slang_ir_node *) _slang_alloc(sizeof(slang_ir_node));
464 if (n) {
465 n->Opcode = op;
466 n->Children[0] = c0;
467 n->Children[1] = c1;
468 n->Children[2] = c2;
469 n->Writemask = WRITEMASK_XYZW;
470 n->InstLocation = -1;
471 }
472 return n;
473 }
474
475 static slang_ir_node *
476 new_node2(slang_ir_opcode op, slang_ir_node *c0, slang_ir_node *c1)
477 {
478 return new_node3(op, c0, c1, NULL);
479 }
480
481 static slang_ir_node *
482 new_node1(slang_ir_opcode op, slang_ir_node *c0)
483 {
484 return new_node3(op, c0, NULL, NULL);
485 }
486
487 static slang_ir_node *
488 new_node0(slang_ir_opcode op)
489 {
490 return new_node3(op, NULL, NULL, NULL);
491 }
492
493
494 static slang_ir_node *
495 new_seq(slang_ir_node *left, slang_ir_node *right)
496 {
497 if (!left)
498 return right;
499 if (!right)
500 return left;
501 return new_node2(IR_SEQ, left, right);
502 }
503
504 static slang_ir_node *
505 new_label(slang_label *label)
506 {
507 slang_ir_node *n = new_node0(IR_LABEL);
508 assert(label);
509 if (n)
510 n->Label = label;
511 return n;
512 }
513
514 static slang_ir_node *
515 new_float_literal(const float v[4], GLuint size)
516 {
517 slang_ir_node *n = new_node0(IR_FLOAT);
518 assert(size <= 4);
519 COPY_4V(n->Value, v);
520 /* allocate a storage object, but compute actual location (Index) later */
521 n->Store = _slang_new_ir_storage(PROGRAM_CONSTANT, -1, size);
522 return n;
523 }
524
525
526 static slang_ir_node *
527 new_not(slang_ir_node *n)
528 {
529 return new_node1(IR_NOT, n);
530 }
531
532
533 /**
534 * Inlined subroutine.
535 */
536 static slang_ir_node *
537 new_inlined_function_call(slang_ir_node *code, slang_label *name)
538 {
539 slang_ir_node *n = new_node1(IR_FUNC, code);
540 assert(name);
541 if (n)
542 n->Label = name;
543 return n;
544 }
545
546
547 /**
548 * Unconditional jump.
549 */
550 static slang_ir_node *
551 new_return(slang_label *dest)
552 {
553 slang_ir_node *n = new_node0(IR_RETURN);
554 assert(dest);
555 if (n)
556 n->Label = dest;
557 return n;
558 }
559
560
561 static slang_ir_node *
562 new_loop(slang_ir_node *body)
563 {
564 return new_node1(IR_LOOP, body);
565 }
566
567
568 static slang_ir_node *
569 new_break(slang_ir_node *loopNode)
570 {
571 slang_ir_node *n = new_node0(IR_BREAK);
572 assert(loopNode);
573 assert(loopNode->Opcode == IR_LOOP);
574 if (n) {
575 /* insert this node at head of linked list */
576 n->List = loopNode->List;
577 loopNode->List = n;
578 }
579 return n;
580 }
581
582
583 /**
584 * Make new IR_BREAK_IF_TRUE.
585 */
586 static slang_ir_node *
587 new_break_if_true(slang_ir_node *loopNode, slang_ir_node *cond)
588 {
589 slang_ir_node *n;
590 assert(loopNode);
591 assert(loopNode->Opcode == IR_LOOP);
592 n = new_node1(IR_BREAK_IF_TRUE, cond);
593 if (n) {
594 /* insert this node at head of linked list */
595 n->List = loopNode->List;
596 loopNode->List = n;
597 }
598 return n;
599 }
600
601
602 /**
603 * Make new IR_CONT_IF_TRUE node.
604 */
605 static slang_ir_node *
606 new_cont_if_true(slang_ir_node *loopNode, slang_ir_node *cond)
607 {
608 slang_ir_node *n;
609 assert(loopNode);
610 assert(loopNode->Opcode == IR_LOOP);
611 n = new_node1(IR_CONT_IF_TRUE, cond);
612 if (n) {
613 /* insert this node at head of linked list */
614 n->List = loopNode->List;
615 loopNode->List = n;
616 }
617 return n;
618 }
619
620
621 static slang_ir_node *
622 new_cond(slang_ir_node *n)
623 {
624 slang_ir_node *c = new_node1(IR_COND, n);
625 return c;
626 }
627
628
629 static slang_ir_node *
630 new_if(slang_ir_node *cond, slang_ir_node *ifPart, slang_ir_node *elsePart)
631 {
632 return new_node3(IR_IF, cond, ifPart, elsePart);
633 }
634
635
636 /**
637 * New IR_VAR node - a reference to a previously declared variable.
638 */
639 static slang_ir_node *
640 new_var(slang_assemble_ctx *A, slang_operation *oper, slang_atom name)
641 {
642 slang_ir_node *n;
643 slang_variable *var = _slang_locate_variable(oper->locals, name, GL_TRUE);
644 if (!var)
645 return NULL;
646
647 assert(!oper->var || oper->var == var);
648
649 n = new_node0(IR_VAR);
650 if (n) {
651 _slang_attach_storage(n, var);
652 }
653 return n;
654 }
655
656
657 /**
658 * Check if the given function is really just a wrapper for a
659 * basic assembly instruction.
660 */
661 static GLboolean
662 slang_is_asm_function(const slang_function *fun)
663 {
664 if (fun->body->type == SLANG_OPER_BLOCK_NO_NEW_SCOPE &&
665 fun->body->num_children == 1 &&
666 fun->body->children[0].type == SLANG_OPER_ASM) {
667 return GL_TRUE;
668 }
669 return GL_FALSE;
670 }
671
672
673 static GLboolean
674 _slang_is_noop(const slang_operation *oper)
675 {
676 if (!oper ||
677 oper->type == SLANG_OPER_VOID ||
678 (oper->num_children == 1 && oper->children[0].type == SLANG_OPER_VOID))
679 return GL_TRUE;
680 else
681 return GL_FALSE;
682 }
683
684
685 /**
686 * Recursively search tree for a node of the given type.
687 */
688 static slang_operation *
689 _slang_find_node_type(slang_operation *oper, slang_operation_type type)
690 {
691 GLuint i;
692 if (oper->type == type)
693 return oper;
694 for (i = 0; i < oper->num_children; i++) {
695 slang_operation *p = _slang_find_node_type(&oper->children[i], type);
696 if (p)
697 return p;
698 }
699 return NULL;
700 }
701
702
703 static void
704 slang_resolve_variable(slang_operation *oper)
705 {
706 if (oper->type == SLANG_OPER_IDENTIFIER && !oper->var) {
707 oper->var = _slang_locate_variable(oper->locals, oper->a_id, GL_TRUE);
708 }
709 }
710
711
712 /**
713 * Replace particular variables (SLANG_OPER_IDENTIFIER) with new expressions.
714 */
715 static void
716 slang_substitute(slang_assemble_ctx *A, slang_operation *oper,
717 GLuint substCount, slang_variable **substOld,
718 slang_operation **substNew, GLboolean isLHS)
719 {
720 switch (oper->type) {
721 case SLANG_OPER_VARIABLE_DECL:
722 {
723 slang_variable *v = _slang_locate_variable(oper->locals,
724 oper->a_id, GL_TRUE);
725 assert(v);
726 if (v->initializer && oper->num_children == 0) {
727 /* set child of oper to copy of initializer */
728 oper->num_children = 1;
729 oper->children = slang_operation_new(1);
730 slang_operation_copy(&oper->children[0], v->initializer);
731 }
732 if (oper->num_children == 1) {
733 /* the initializer */
734 slang_substitute(A, &oper->children[0], substCount,
735 substOld, substNew, GL_FALSE);
736 }
737 }
738 break;
739 case SLANG_OPER_IDENTIFIER:
740 assert(oper->num_children == 0);
741 if (1/**!isLHS XXX FIX */) {
742 slang_atom id = oper->a_id;
743 slang_variable *v;
744 GLuint i;
745 v = _slang_locate_variable(oper->locals, id, GL_TRUE);
746 if (!v) {
747 _mesa_problem(NULL, "var %s not found!\n", (char *) oper->a_id);
748 return;
749 }
750
751 /* look for a substitution */
752 for (i = 0; i < substCount; i++) {
753 if (v == substOld[i]) {
754 /* OK, replace this SLANG_OPER_IDENTIFIER with a new expr */
755 #if 0 /* DEBUG only */
756 if (substNew[i]->type == SLANG_OPER_IDENTIFIER) {
757 assert(substNew[i]->var);
758 assert(substNew[i]->var->a_name);
759 printf("Substitute %s with %s in id node %p\n",
760 (char*)v->a_name, (char*) substNew[i]->var->a_name,
761 (void*) oper);
762 }
763 else {
764 printf("Substitute %s with %f in id node %p\n",
765 (char*)v->a_name, substNew[i]->literal[0],
766 (void*) oper);
767 }
768 #endif
769 slang_operation_copy(oper, substNew[i]);
770 break;
771 }
772 }
773 }
774 break;
775
776 case SLANG_OPER_RETURN:
777 /* do return replacement here too */
778 assert(oper->num_children == 0 || oper->num_children == 1);
779 if (oper->num_children == 1 && !_slang_is_noop(&oper->children[0])) {
780 /* replace:
781 * return expr;
782 * with:
783 * __retVal = expr;
784 * return;
785 * then do substitutions on the assignment.
786 */
787 slang_operation *blockOper, *assignOper, *returnOper;
788
789 /* check if function actually has a return type */
790 assert(A->CurFunction);
791 if (A->CurFunction->header.type.specifier.type == SLANG_SPEC_VOID) {
792 slang_info_log_error(A->log, "illegal return expression");
793 return;
794 }
795
796 blockOper = slang_operation_new(1);
797 blockOper->type = SLANG_OPER_BLOCK_NO_NEW_SCOPE;
798 blockOper->num_children = 2;
799 blockOper->locals->outer_scope = oper->locals->outer_scope;
800 blockOper->children = slang_operation_new(2);
801 assignOper = blockOper->children + 0;
802 returnOper = blockOper->children + 1;
803
804 assignOper->type = SLANG_OPER_ASSIGN;
805 assignOper->num_children = 2;
806 assignOper->locals->outer_scope = blockOper->locals;
807 assignOper->children = slang_operation_new(2);
808 assignOper->children[0].type = SLANG_OPER_IDENTIFIER;
809 assignOper->children[0].a_id = slang_atom_pool_atom(A->atoms, "__retVal");
810 assignOper->children[0].locals->outer_scope = assignOper->locals;
811
812 slang_operation_copy(&assignOper->children[1],
813 &oper->children[0]);
814
815 returnOper->type = SLANG_OPER_RETURN; /* return w/ no value */
816 assert(returnOper->num_children == 0);
817
818 /* do substitutions on the "__retVal = expr" sub-tree */
819 slang_substitute(A, assignOper,
820 substCount, substOld, substNew, GL_FALSE);
821
822 /* install new code */
823 slang_operation_copy(oper, blockOper);
824 slang_operation_destruct(blockOper);
825 }
826 else {
827 /* check if return value was expected */
828 assert(A->CurFunction);
829 if (A->CurFunction->header.type.specifier.type != SLANG_SPEC_VOID) {
830 slang_info_log_error(A->log, "return statement requires an expression");
831 return;
832 }
833 }
834 break;
835
836 case SLANG_OPER_ASSIGN:
837 case SLANG_OPER_SUBSCRIPT:
838 /* special case:
839 * child[0] can't have substitutions but child[1] can.
840 */
841 slang_substitute(A, &oper->children[0],
842 substCount, substOld, substNew, GL_TRUE);
843 slang_substitute(A, &oper->children[1],
844 substCount, substOld, substNew, GL_FALSE);
845 break;
846 case SLANG_OPER_FIELD:
847 /* XXX NEW - test */
848 slang_substitute(A, &oper->children[0],
849 substCount, substOld, substNew, GL_TRUE);
850 break;
851 default:
852 {
853 GLuint i;
854 for (i = 0; i < oper->num_children; i++)
855 slang_substitute(A, &oper->children[i],
856 substCount, substOld, substNew, GL_FALSE);
857 }
858 }
859 }
860
861
862
863 /**
864 * Produce inline code for a call to an assembly instruction.
865 * This is typically used to compile a call to a built-in function like this:
866 *
867 * vec4 mix(const vec4 x, const vec4 y, const vec4 a)
868 * {
869 * __asm vec4_lrp __retVal, a, y, x;
870 * }
871 *
872 * We basically translate a SLANG_OPER_CALL into a SLANG_OPER_ASM.
873 */
874 static slang_operation *
875 slang_inline_asm_function(slang_assemble_ctx *A,
876 slang_function *fun, slang_operation *oper)
877 {
878 const GLuint numArgs = oper->num_children;
879 GLuint i;
880 slang_operation *inlined;
881 const GLboolean haveRetValue = _slang_function_has_return_value(fun);
882 slang_variable **substOld;
883 slang_operation **substNew;
884
885 ASSERT(slang_is_asm_function(fun));
886 ASSERT(fun->param_count == numArgs + haveRetValue);
887
888 /*
889 printf("Inline %s as %s\n",
890 (char*) fun->header.a_name,
891 (char*) fun->body->children[0].a_id);
892 */
893
894 /*
895 * We'll substitute formal params with actual args in the asm call.
896 */
897 substOld = (slang_variable **)
898 _slang_alloc(numArgs * sizeof(slang_variable *));
899 substNew = (slang_operation **)
900 _slang_alloc(numArgs * sizeof(slang_operation *));
901 for (i = 0; i < numArgs; i++) {
902 substOld[i] = fun->parameters->variables[i];
903 substNew[i] = oper->children + i;
904 }
905
906 /* make a copy of the code to inline */
907 inlined = slang_operation_new(1);
908 slang_operation_copy(inlined, &fun->body->children[0]);
909 if (haveRetValue) {
910 /* get rid of the __retVal child */
911 for (i = 0; i < numArgs; i++) {
912 inlined->children[i] = inlined->children[i + 1];
913 }
914 inlined->num_children--;
915 }
916
917 /* now do formal->actual substitutions */
918 slang_substitute(A, inlined, numArgs, substOld, substNew, GL_FALSE);
919
920 _slang_free(substOld);
921 _slang_free(substNew);
922
923 return inlined;
924 }
925
926
927 /**
928 * Inline the given function call operation.
929 * Return a new slang_operation that corresponds to the inlined code.
930 */
931 static slang_operation *
932 slang_inline_function_call(slang_assemble_ctx * A, slang_function *fun,
933 slang_operation *oper, slang_operation *returnOper)
934 {
935 typedef enum {
936 SUBST = 1,
937 COPY_IN,
938 COPY_OUT
939 } ParamMode;
940 ParamMode *paramMode;
941 const GLboolean haveRetValue = _slang_function_has_return_value(fun);
942 const GLuint numArgs = oper->num_children;
943 const GLuint totalArgs = numArgs + haveRetValue;
944 slang_operation *args = oper->children;
945 slang_operation *inlined, *top;
946 slang_variable **substOld;
947 slang_operation **substNew;
948 GLuint substCount, numCopyIn, i;
949 slang_function *prevFunction;
950
951 /* save / push */
952 prevFunction = A->CurFunction;
953 A->CurFunction = fun;
954
955 /*assert(oper->type == SLANG_OPER_CALL); (or (matrix) multiply, etc) */
956 assert(fun->param_count == totalArgs);
957
958 /* allocate temporary arrays */
959 paramMode = (ParamMode *)
960 _slang_alloc(totalArgs * sizeof(ParamMode));
961 substOld = (slang_variable **)
962 _slang_alloc(totalArgs * sizeof(slang_variable *));
963 substNew = (slang_operation **)
964 _slang_alloc(totalArgs * sizeof(slang_operation *));
965
966 #if 0
967 printf("Inline call to %s (total vars=%d nparams=%d)\n",
968 (char *) fun->header.a_name,
969 fun->parameters->num_variables, numArgs);
970 #endif
971
972 if (haveRetValue && !returnOper) {
973 /* Create 3-child comma sequence for inlined code:
974 * child[0]: declare __resultTmp
975 * child[1]: inlined function body
976 * child[2]: __resultTmp
977 */
978 slang_operation *commaSeq;
979 slang_operation *declOper = NULL;
980 slang_variable *resultVar;
981
982 commaSeq = slang_operation_new(1);
983 commaSeq->type = SLANG_OPER_SEQUENCE;
984 assert(commaSeq->locals);
985 commaSeq->locals->outer_scope = oper->locals->outer_scope;
986 commaSeq->num_children = 3;
987 commaSeq->children = slang_operation_new(3);
988 /* allocate the return var */
989 resultVar = slang_variable_scope_grow(commaSeq->locals);
990 /*
991 printf("Alloc __resultTmp in scope %p for retval of calling %s\n",
992 (void*)commaSeq->locals, (char *) fun->header.a_name);
993 */
994
995 resultVar->a_name = slang_atom_pool_atom(A->atoms, "__resultTmp");
996 resultVar->type = fun->header.type; /* XXX copy? */
997 resultVar->isTemp = GL_TRUE;
998
999 /* child[0] = __resultTmp declaration */
1000 declOper = &commaSeq->children[0];
1001 declOper->type = SLANG_OPER_VARIABLE_DECL;
1002 declOper->a_id = resultVar->a_name;
1003 declOper->locals->outer_scope = commaSeq->locals;
1004
1005 /* child[1] = function body */
1006 inlined = &commaSeq->children[1];
1007 inlined->locals->outer_scope = commaSeq->locals;
1008
1009 /* child[2] = __resultTmp reference */
1010 returnOper = &commaSeq->children[2];
1011 returnOper->type = SLANG_OPER_IDENTIFIER;
1012 returnOper->a_id = resultVar->a_name;
1013 returnOper->locals->outer_scope = commaSeq->locals;
1014
1015 top = commaSeq;
1016 }
1017 else {
1018 top = inlined = slang_operation_new(1);
1019 /* XXXX this may be inappropriate!!!! */
1020 inlined->locals->outer_scope = oper->locals->outer_scope;
1021 }
1022
1023
1024 assert(inlined->locals);
1025
1026 /* Examine the parameters, look for inout/out params, look for possible
1027 * substitutions, etc:
1028 * param type behaviour
1029 * in copy actual to local
1030 * const in substitute param with actual
1031 * out copy out
1032 */
1033 substCount = 0;
1034 for (i = 0; i < totalArgs; i++) {
1035 slang_variable *p = fun->parameters->variables[i];
1036 /*
1037 printf("Param %d: %s %s \n", i,
1038 slang_type_qual_string(p->type.qualifier),
1039 (char *) p->a_name);
1040 */
1041 if (p->type.qualifier == SLANG_QUAL_INOUT ||
1042 p->type.qualifier == SLANG_QUAL_OUT) {
1043 /* an output param */
1044 slang_operation *arg;
1045 if (i < numArgs)
1046 arg = &args[i];
1047 else
1048 arg = returnOper;
1049 paramMode[i] = SUBST;
1050
1051 if (arg->type == SLANG_OPER_IDENTIFIER)
1052 slang_resolve_variable(arg);
1053
1054 /* replace parameter 'p' with argument 'arg' */
1055 substOld[substCount] = p;
1056 substNew[substCount] = arg; /* will get copied */
1057 substCount++;
1058 }
1059 else if (p->type.qualifier == SLANG_QUAL_CONST) {
1060 /* a constant input param */
1061 if (args[i].type == SLANG_OPER_IDENTIFIER ||
1062 args[i].type == SLANG_OPER_LITERAL_FLOAT) {
1063 /* replace all occurances of this parameter variable with the
1064 * actual argument variable or a literal.
1065 */
1066 paramMode[i] = SUBST;
1067 slang_resolve_variable(&args[i]);
1068 substOld[substCount] = p;
1069 substNew[substCount] = &args[i]; /* will get copied */
1070 substCount++;
1071 }
1072 else {
1073 paramMode[i] = COPY_IN;
1074 }
1075 }
1076 else {
1077 paramMode[i] = COPY_IN;
1078 }
1079 assert(paramMode[i]);
1080 }
1081
1082 /* actual code inlining: */
1083 slang_operation_copy(inlined, fun->body);
1084
1085 /*** XXX review this */
1086 assert(inlined->type = SLANG_OPER_BLOCK_NO_NEW_SCOPE);
1087 inlined->type = SLANG_OPER_BLOCK_NEW_SCOPE;
1088
1089 #if 0
1090 printf("======================= orig body code ======================\n");
1091 printf("=== params scope = %p\n", (void*) fun->parameters);
1092 slang_print_tree(fun->body, 8);
1093 printf("======================= copied code =========================\n");
1094 slang_print_tree(inlined, 8);
1095 #endif
1096
1097 /* do parameter substitution in inlined code: */
1098 slang_substitute(A, inlined, substCount, substOld, substNew, GL_FALSE);
1099
1100 #if 0
1101 printf("======================= subst code ==========================\n");
1102 slang_print_tree(inlined, 8);
1103 printf("=============================================================\n");
1104 #endif
1105
1106 /* New prolog statements: (inserted before the inlined code)
1107 * Copy the 'in' arguments.
1108 */
1109 numCopyIn = 0;
1110 for (i = 0; i < numArgs; i++) {
1111 if (paramMode[i] == COPY_IN) {
1112 slang_variable *p = fun->parameters->variables[i];
1113 /* declare parameter 'p' */
1114 slang_operation *decl = slang_operation_insert(&inlined->num_children,
1115 &inlined->children,
1116 numCopyIn);
1117 /*
1118 printf("COPY_IN %s from expr\n", (char*)p->a_name);
1119 */
1120 decl->type = SLANG_OPER_VARIABLE_DECL;
1121 assert(decl->locals);
1122 decl->locals->outer_scope = inlined->locals;
1123 decl->a_id = p->a_name;
1124 decl->num_children = 1;
1125 decl->children = slang_operation_new(1);
1126
1127 /* child[0] is the var's initializer */
1128 slang_operation_copy(&decl->children[0], args + i);
1129
1130 numCopyIn++;
1131 }
1132 }
1133
1134 /* New epilog statements:
1135 * 1. Create end of function label to jump to from return statements.
1136 * 2. Copy the 'out' parameter vars
1137 */
1138 {
1139 slang_operation *lab = slang_operation_insert(&inlined->num_children,
1140 &inlined->children,
1141 inlined->num_children);
1142 lab->type = SLANG_OPER_LABEL;
1143 lab->label = A->curFuncEndLabel;
1144 }
1145
1146 for (i = 0; i < totalArgs; i++) {
1147 if (paramMode[i] == COPY_OUT) {
1148 const slang_variable *p = fun->parameters->variables[i];
1149 /* actualCallVar = outParam */
1150 /*if (i > 0 || !haveRetValue)*/
1151 slang_operation *ass = slang_operation_insert(&inlined->num_children,
1152 &inlined->children,
1153 inlined->num_children);
1154 ass->type = SLANG_OPER_ASSIGN;
1155 ass->num_children = 2;
1156 ass->locals->outer_scope = inlined->locals;
1157 ass->children = slang_operation_new(2);
1158 ass->children[0] = args[i]; /*XXX copy */
1159 ass->children[1].type = SLANG_OPER_IDENTIFIER;
1160 ass->children[1].a_id = p->a_name;
1161 ass->children[1].locals->outer_scope = ass->locals;
1162 }
1163 }
1164
1165 _slang_free(paramMode);
1166 _slang_free(substOld);
1167 _slang_free(substNew);
1168
1169 #if 0
1170 printf("Done Inline call to %s (total vars=%d nparams=%d)\n",
1171 (char *) fun->header.a_name,
1172 fun->parameters->num_variables, numArgs);
1173 slang_print_tree(top, 0);
1174 #endif
1175
1176 /* pop */
1177 A->CurFunction = prevFunction;
1178
1179 return top;
1180 }
1181
1182
1183 static slang_ir_node *
1184 _slang_gen_function_call(slang_assemble_ctx *A, slang_function *fun,
1185 slang_operation *oper, slang_operation *dest)
1186 {
1187 slang_ir_node *n;
1188 slang_operation *inlined;
1189 slang_label *prevFuncEndLabel;
1190 char name[200];
1191
1192 prevFuncEndLabel = A->curFuncEndLabel;
1193 sprintf(name, "__endOfFunc_%s_", (char *) fun->header.a_name);
1194 A->curFuncEndLabel = _slang_label_new(name);
1195 assert(A->curFuncEndLabel);
1196
1197 if (slang_is_asm_function(fun) && !dest) {
1198 /* assemble assembly function - tree style */
1199 inlined = slang_inline_asm_function(A, fun, oper);
1200 }
1201 else {
1202 /* non-assembly function */
1203 inlined = slang_inline_function_call(A, fun, oper, dest);
1204 if (inlined && _slang_find_node_type(inlined, SLANG_OPER_RETURN)) {
1205 /* This inlined function has one or more 'return' statements.
1206 * So, we can't truly inline this function because we need to
1207 * implement 'return' with RET (and CAL).
1208 * XXX check if there's one 'return' and if it's the very last
1209 * statement in the function - we can optimize that case.
1210 */
1211 assert(inlined->type == SLANG_OPER_BLOCK_NEW_SCOPE ||
1212 inlined->type == SLANG_OPER_SEQUENCE);
1213 inlined->type = SLANG_OPER_INLINED_CALL;
1214 inlined->fun = fun;
1215 inlined->label = _slang_label_new_unique((char*) fun->header.a_name);
1216 }
1217 }
1218
1219 if (!inlined)
1220 return NULL;
1221
1222 /* Replace the function call with the inlined block */
1223 slang_operation_destruct(oper);
1224 *oper = *inlined;
1225 _slang_free(inlined);
1226
1227 #if 0
1228 assert(inlined->locals);
1229 printf("*** Inlined code for call to %s:\n",
1230 (char*) fun->header.a_name);
1231 slang_print_tree(oper, 10);
1232 printf("\n");
1233 #endif
1234
1235 n = _slang_gen_operation(A, oper);
1236
1237 /*_slang_label_delete(A->curFuncEndLabel);*/
1238 A->curFuncEndLabel = prevFuncEndLabel;
1239
1240 return n;
1241 }
1242
1243
1244 static slang_asm_info *
1245 slang_find_asm_info(const char *name)
1246 {
1247 GLuint i;
1248 for (i = 0; AsmInfo[i].Name; i++) {
1249 if (_mesa_strcmp(AsmInfo[i].Name, name) == 0) {
1250 return AsmInfo + i;
1251 }
1252 }
1253 return NULL;
1254 }
1255
1256
1257 static GLuint
1258 make_writemask(const char *field)
1259 {
1260 GLuint mask = 0x0;
1261 while (*field) {
1262 switch (*field) {
1263 case 'x':
1264 case 's':
1265 case 'r':
1266 mask |= WRITEMASK_X;
1267 break;
1268 case 'y':
1269 case 't':
1270 case 'g':
1271 mask |= WRITEMASK_Y;
1272 break;
1273 case 'z':
1274 case 'p':
1275 case 'b':
1276 mask |= WRITEMASK_Z;
1277 break;
1278 case 'w':
1279 case 'q':
1280 case 'a':
1281 mask |= WRITEMASK_W;
1282 break;
1283 default:
1284 _mesa_problem(NULL, "invalid writemask in make_writemask()");
1285 return 0;
1286 }
1287 field++;
1288 }
1289 if (mask == 0x0)
1290 return WRITEMASK_XYZW;
1291 else
1292 return mask;
1293 }
1294
1295
1296 /**
1297 * Generate IR tree for an asm instruction/operation such as:
1298 * __asm vec4_dot __retVal.x, v1, v2;
1299 */
1300 static slang_ir_node *
1301 _slang_gen_asm(slang_assemble_ctx *A, slang_operation *oper,
1302 slang_operation *dest)
1303 {
1304 const slang_asm_info *info;
1305 slang_ir_node *kids[3], *n;
1306 GLuint j, firstOperand;
1307
1308 assert(oper->type == SLANG_OPER_ASM);
1309
1310 info = slang_find_asm_info((char *) oper->a_id);
1311 if (!info) {
1312 _mesa_problem(NULL, "undefined __asm function %s\n",
1313 (char *) oper->a_id);
1314 assert(info);
1315 }
1316 assert(info->NumParams <= 3);
1317
1318 if (info->NumParams == oper->num_children) {
1319 /* Storage for result is not specified.
1320 * Children[0], [1] are the operands.
1321 */
1322 firstOperand = 0;
1323 }
1324 else {
1325 /* Storage for result (child[0]) is specified.
1326 * Children[1], [2] are the operands.
1327 */
1328 firstOperand = 1;
1329 }
1330
1331 /* assemble child(ren) */
1332 kids[0] = kids[1] = kids[2] = NULL;
1333 for (j = 0; j < info->NumParams; j++) {
1334 kids[j] = _slang_gen_operation(A, &oper->children[firstOperand + j]);
1335 if (!kids[j])
1336 return NULL;
1337 }
1338
1339 n = new_node3(info->Opcode, kids[0], kids[1], kids[2]);
1340
1341 if (firstOperand) {
1342 /* Setup n->Store to be a particular location. Otherwise, storage
1343 * for the result (a temporary) will be allocated later.
1344 */
1345 GLuint writemask = WRITEMASK_XYZW;
1346 slang_operation *dest_oper;
1347 slang_ir_node *n0;
1348
1349 dest_oper = &oper->children[0];
1350 while (dest_oper->type == SLANG_OPER_FIELD) {
1351 /* writemask */
1352 writemask &= make_writemask((char*) dest_oper->a_id);
1353 dest_oper = &dest_oper->children[0];
1354 }
1355
1356 n0 = _slang_gen_operation(A, dest_oper);
1357 assert(n0->Var);
1358 assert(n0->Store);
1359 assert(!n->Store);
1360 n->Store = n0->Store;
1361 n->Writemask = writemask;
1362
1363 _slang_free(n0);
1364 }
1365
1366 return n;
1367 }
1368
1369
1370 static void
1371 print_funcs(struct slang_function_scope_ *scope, const char *name)
1372 {
1373 GLuint i;
1374 for (i = 0; i < scope->num_functions; i++) {
1375 slang_function *f = &scope->functions[i];
1376 if (!name || strcmp(name, (char*) f->header.a_name) == 0)
1377 printf(" %s (%d args)\n", name, f->param_count);
1378
1379 }
1380 if (scope->outer_scope)
1381 print_funcs(scope->outer_scope, name);
1382 }
1383
1384
1385 /**
1386 * Return first function in the scope that has the given name.
1387 * This is the function we'll try to call when there is no exact match
1388 * between function parameters and call arguments.
1389 *
1390 * XXX we should really create a list of candidate functions and try
1391 * all of them...
1392 */
1393 static slang_function *
1394 _slang_first_function(struct slang_function_scope_ *scope, const char *name)
1395 {
1396 GLuint i;
1397 for (i = 0; i < scope->num_functions; i++) {
1398 slang_function *f = &scope->functions[i];
1399 if (strcmp(name, (char*) f->header.a_name) == 0)
1400 return f;
1401 }
1402 if (scope->outer_scope)
1403 return _slang_first_function(scope->outer_scope, name);
1404 return NULL;
1405 }
1406
1407
1408
1409 /**
1410 * Assemble a function call, given a particular function name.
1411 * \param name the function's name (operators like '*' are possible).
1412 */
1413 static slang_ir_node *
1414 _slang_gen_function_call_name(slang_assemble_ctx *A, const char *name,
1415 slang_operation *oper, slang_operation *dest)
1416 {
1417 slang_operation *params = oper->children;
1418 const GLuint param_count = oper->num_children;
1419 slang_atom atom;
1420 slang_function *fun;
1421
1422 atom = slang_atom_pool_atom(A->atoms, name);
1423 if (atom == SLANG_ATOM_NULL)
1424 return NULL;
1425
1426 /*
1427 * Use 'name' to find the function to call
1428 */
1429 fun = _slang_locate_function(A->space.funcs, atom, params, param_count,
1430 &A->space, A->atoms, A->log);
1431 if (!fun) {
1432 /* A function with exactly the right parameters/types was not found.
1433 * Try adapting the parameters.
1434 */
1435 fun = _slang_first_function(A->space.funcs, name);
1436 if (!fun || !_slang_adapt_call(oper, fun, &A->space, A->atoms, A->log)) {
1437 slang_info_log_error(A->log, "Function '%s' not found (check argument types)", name);
1438 return NULL;
1439 }
1440 assert(fun);
1441 }
1442
1443 return _slang_gen_function_call(A, fun, oper, dest);
1444 }
1445
1446
1447 static GLboolean
1448 _slang_is_constant_cond(const slang_operation *oper, GLboolean *value)
1449 {
1450 if (oper->type == SLANG_OPER_LITERAL_FLOAT ||
1451 oper->type == SLANG_OPER_LITERAL_INT ||
1452 oper->type == SLANG_OPER_LITERAL_BOOL) {
1453 if (oper->literal[0])
1454 *value = GL_TRUE;
1455 else
1456 *value = GL_FALSE;
1457 return GL_TRUE;
1458 }
1459 else if (oper->type == SLANG_OPER_EXPRESSION &&
1460 oper->num_children == 1) {
1461 return _slang_is_constant_cond(&oper->children[0], value);
1462 }
1463 return GL_FALSE;
1464 }
1465
1466
1467 /**
1468 * Test if an operation is a scalar or boolean.
1469 */
1470 static GLboolean
1471 _slang_is_scalar_or_boolean(slang_assemble_ctx *A, slang_operation *oper)
1472 {
1473 slang_typeinfo type;
1474 GLint size;
1475
1476 slang_typeinfo_construct(&type);
1477 _slang_typeof_operation(A, oper, &type);
1478 size = _slang_sizeof_type_specifier(&type.spec);
1479 slang_typeinfo_destruct(&type);
1480 return size == 1;
1481 }
1482
1483
1484 /**
1485 * Generate loop code using high-level IR_LOOP instruction
1486 */
1487 static slang_ir_node *
1488 _slang_gen_while(slang_assemble_ctx * A, const slang_operation *oper)
1489 {
1490 /*
1491 * LOOP:
1492 * BREAK if !expr (child[0])
1493 * body code (child[1])
1494 */
1495 slang_ir_node *prevLoop, *loop, *breakIf, *body;
1496 GLboolean isConst, constTrue;
1497
1498 /* type-check expression */
1499 if (!_slang_is_scalar_or_boolean(A, &oper->children[0])) {
1500 slang_info_log_error(A->log, "scalar/boolean expression expected for 'while'");
1501 return NULL;
1502 }
1503
1504 /* Check if loop condition is a constant */
1505 isConst = _slang_is_constant_cond(&oper->children[0], &constTrue);
1506
1507 if (isConst && !constTrue) {
1508 /* loop is never executed! */
1509 return new_node0(IR_NOP);
1510 }
1511
1512 loop = new_loop(NULL);
1513
1514 /* save old, push new loop */
1515 prevLoop = A->CurLoop;
1516 A->CurLoop = loop;
1517
1518 if (isConst && constTrue) {
1519 /* while(nonzero constant), no conditional break */
1520 breakIf = NULL;
1521 }
1522 else {
1523 slang_ir_node *cond
1524 = new_cond(new_not(_slang_gen_operation(A, &oper->children[0])));
1525 breakIf = new_break_if_true(A->CurLoop, cond);
1526 }
1527 body = _slang_gen_operation(A, &oper->children[1]);
1528 loop->Children[0] = new_seq(breakIf, body);
1529
1530 /* Do infinite loop detection */
1531 /* loop->List is head of linked list of break/continue nodes */
1532 if (!loop->List && isConst && constTrue) {
1533 /* infinite loop detected */
1534 A->CurLoop = prevLoop; /* clean-up */
1535 slang_info_log_error(A->log, "Infinite loop detected!");
1536 return NULL;
1537 }
1538
1539 /* pop loop, restore prev */
1540 A->CurLoop = prevLoop;
1541
1542 return loop;
1543 }
1544
1545
1546 /**
1547 * Generate IR tree for a do-while loop using high-level LOOP, IF instructions.
1548 */
1549 static slang_ir_node *
1550 _slang_gen_do(slang_assemble_ctx * A, const slang_operation *oper)
1551 {
1552 /*
1553 * LOOP:
1554 * body code (child[0])
1555 * tail code:
1556 * BREAK if !expr (child[1])
1557 */
1558 slang_ir_node *prevLoop, *loop;
1559 GLboolean isConst, constTrue;
1560
1561 /* type-check expression */
1562 if (!_slang_is_scalar_or_boolean(A, &oper->children[1])) {
1563 slang_info_log_error(A->log, "scalar/boolean expression expected for 'do/while'");
1564 return NULL;
1565 }
1566
1567 loop = new_loop(NULL);
1568
1569 /* save old, push new loop */
1570 prevLoop = A->CurLoop;
1571 A->CurLoop = loop;
1572
1573 /* loop body: */
1574 loop->Children[0] = _slang_gen_operation(A, &oper->children[0]);
1575
1576 /* Check if loop condition is a constant */
1577 isConst = _slang_is_constant_cond(&oper->children[1], &constTrue);
1578 if (isConst && constTrue) {
1579 /* do { } while(1) ==> no conditional break */
1580 loop->Children[1] = NULL; /* no tail code */
1581 }
1582 else {
1583 slang_ir_node *cond
1584 = new_cond(new_not(_slang_gen_operation(A, &oper->children[1])));
1585 loop->Children[1] = new_break_if_true(A->CurLoop, cond);
1586 }
1587
1588 /* XXX we should do infinite loop detection, as above */
1589
1590 /* pop loop, restore prev */
1591 A->CurLoop = prevLoop;
1592
1593 return loop;
1594 }
1595
1596
1597 /**
1598 * Generate for-loop using high-level IR_LOOP instruction.
1599 */
1600 static slang_ir_node *
1601 _slang_gen_for(slang_assemble_ctx * A, const slang_operation *oper)
1602 {
1603 /*
1604 * init code (child[0])
1605 * LOOP:
1606 * BREAK if !expr (child[1])
1607 * body code (child[3])
1608 * tail code:
1609 * incr code (child[2]) // XXX continue here
1610 */
1611 slang_ir_node *prevLoop, *loop, *cond, *breakIf, *body, *init, *incr;
1612
1613 init = _slang_gen_operation(A, &oper->children[0]);
1614 loop = new_loop(NULL);
1615
1616 /* save old, push new loop */
1617 prevLoop = A->CurLoop;
1618 A->CurLoop = loop;
1619
1620 cond = new_cond(new_not(_slang_gen_operation(A, &oper->children[1])));
1621 breakIf = new_break_if_true(A->CurLoop, cond);
1622 body = _slang_gen_operation(A, &oper->children[3]);
1623 incr = _slang_gen_operation(A, &oper->children[2]);
1624
1625 loop->Children[0] = new_seq(breakIf, body);
1626 loop->Children[1] = incr; /* tail code */
1627
1628 /* pop loop, restore prev */
1629 A->CurLoop = prevLoop;
1630
1631 return new_seq(init, loop);
1632 }
1633
1634
1635 static slang_ir_node *
1636 _slang_gen_continue(slang_assemble_ctx * A, const slang_operation *oper)
1637 {
1638 slang_ir_node *n, *loopNode;
1639 assert(oper->type == SLANG_OPER_CONTINUE);
1640 loopNode = A->CurLoop;
1641 assert(loopNode);
1642 assert(loopNode->Opcode == IR_LOOP);
1643 n = new_node0(IR_CONT);
1644 if (n) {
1645 n->Parent = loopNode;
1646 /* insert this node at head of linked list */
1647 n->List = loopNode->List;
1648 loopNode->List = n;
1649 }
1650 return n;
1651 }
1652
1653
1654 /**
1655 * Determine if the given operation is of a specific type.
1656 */
1657 static GLboolean
1658 is_operation_type(const slang_operation *oper, slang_operation_type type)
1659 {
1660 if (oper->type == type)
1661 return GL_TRUE;
1662 else if ((oper->type == SLANG_OPER_BLOCK_NEW_SCOPE ||
1663 oper->type == SLANG_OPER_BLOCK_NO_NEW_SCOPE) &&
1664 oper->num_children == 1)
1665 return is_operation_type(&oper->children[0], type);
1666 else
1667 return GL_FALSE;
1668 }
1669
1670
1671 /**
1672 * Generate IR tree for an if/then/else conditional using high-level
1673 * IR_IF instruction.
1674 */
1675 static slang_ir_node *
1676 _slang_gen_if(slang_assemble_ctx * A, const slang_operation *oper)
1677 {
1678 /*
1679 * eval expr (child[0])
1680 * IF expr THEN
1681 * if-body code
1682 * ELSE
1683 * else-body code
1684 * ENDIF
1685 */
1686 const GLboolean haveElseClause = !_slang_is_noop(&oper->children[2]);
1687 slang_ir_node *ifNode, *cond, *ifBody, *elseBody;
1688 GLboolean isConst, constTrue;
1689
1690 /* type-check expression */
1691 if (!_slang_is_scalar_or_boolean(A, &oper->children[0])) {
1692 slang_info_log_error(A->log, "scalar/boolean expression expected for 'if'");
1693 return NULL;
1694 }
1695
1696 isConst = _slang_is_constant_cond(&oper->children[0], &constTrue);
1697 if (isConst) {
1698 if (constTrue) {
1699 /* if (true) ... */
1700 return _slang_gen_operation(A, &oper->children[1]);
1701 }
1702 else {
1703 /* if (false) ... */
1704 return _slang_gen_operation(A, &oper->children[2]);
1705 }
1706 }
1707
1708 cond = _slang_gen_operation(A, &oper->children[0]);
1709 cond = new_cond(cond);
1710
1711 if (is_operation_type(&oper->children[1], SLANG_OPER_BREAK)) {
1712 /* Special case: generate a conditional break */
1713 ifBody = new_break_if_true(A->CurLoop, cond);
1714 if (haveElseClause) {
1715 elseBody = _slang_gen_operation(A, &oper->children[2]);
1716 return new_seq(ifBody, elseBody);
1717 }
1718 return ifBody;
1719 }
1720 else if (is_operation_type(&oper->children[1], SLANG_OPER_CONTINUE)) {
1721 /* Special case: generate a conditional break */
1722 ifBody = new_cont_if_true(A->CurLoop, cond);
1723 if (haveElseClause) {
1724 elseBody = _slang_gen_operation(A, &oper->children[2]);
1725 return new_seq(ifBody, elseBody);
1726 }
1727 return ifBody;
1728 }
1729 else {
1730 /* general case */
1731 ifBody = _slang_gen_operation(A, &oper->children[1]);
1732 if (haveElseClause)
1733 elseBody = _slang_gen_operation(A, &oper->children[2]);
1734 else
1735 elseBody = NULL;
1736 ifNode = new_if(cond, ifBody, elseBody);
1737 return ifNode;
1738 }
1739 }
1740
1741
1742
1743 static slang_ir_node *
1744 _slang_gen_not(slang_assemble_ctx * A, const slang_operation *oper)
1745 {
1746 slang_ir_node *n;
1747
1748 assert(oper->type == SLANG_OPER_NOT);
1749
1750 /* type-check expression */
1751 if (!_slang_is_scalar_or_boolean(A, &oper->children[0])) {
1752 slang_info_log_error(A->log,
1753 "scalar/boolean expression expected for '!'");
1754 return NULL;
1755 }
1756
1757 n = _slang_gen_operation(A, &oper->children[0]);
1758 if (n)
1759 return new_not(n);
1760 else
1761 return NULL;
1762 }
1763
1764
1765 static slang_ir_node *
1766 _slang_gen_xor(slang_assemble_ctx * A, const slang_operation *oper)
1767 {
1768 slang_ir_node *n1, *n2;
1769
1770 assert(oper->type == SLANG_OPER_LOGICALXOR);
1771
1772 if (!_slang_is_scalar_or_boolean(A, &oper->children[0]) ||
1773 !_slang_is_scalar_or_boolean(A, &oper->children[0])) {
1774 slang_info_log_error(A->log,
1775 "scalar/boolean expressions expected for '^^'");
1776 return NULL;
1777 }
1778
1779 n1 = _slang_gen_operation(A, &oper->children[0]);
1780 if (!n1)
1781 return NULL;
1782 n2 = _slang_gen_operation(A, &oper->children[1]);
1783 if (!n2)
1784 return NULL;
1785 return new_node2(IR_NOTEQUAL, n1, n2);
1786 }
1787
1788
1789 /**
1790 * Generate IR node for storage of a temporary of given size.
1791 */
1792 static slang_ir_node *
1793 _slang_gen_temporary(GLint size)
1794 {
1795 slang_ir_storage *store;
1796 slang_ir_node *n = NULL;
1797
1798 store = _slang_new_ir_storage(PROGRAM_TEMPORARY, -1, size);
1799 if (store) {
1800 n = new_node0(IR_VAR_DECL);
1801 if (n) {
1802 n->Store = store;
1803 }
1804 else {
1805 _slang_free(store);
1806 }
1807 }
1808 return n;
1809 }
1810
1811
1812 /**
1813 * Generate IR node for allocating/declaring a variable.
1814 */
1815 static slang_ir_node *
1816 _slang_gen_var_decl(slang_assemble_ctx *A, slang_variable *var)
1817 {
1818 slang_ir_node *n;
1819 assert(!is_sampler_type(&var->type));
1820 n = new_node0(IR_VAR_DECL);
1821 if (n) {
1822 _slang_attach_storage(n, var);
1823
1824 assert(var->aux);
1825 assert(n->Store == var->aux);
1826 assert(n->Store);
1827 assert(n->Store->Index < 0);
1828
1829 n->Store->File = PROGRAM_TEMPORARY;
1830 n->Store->Size = _slang_sizeof_type_specifier(&n->Var->type.specifier);
1831 assert(n->Store->Size > 0);
1832 }
1833 return n;
1834 }
1835
1836
1837 /**
1838 * Generate code for a selection expression: b ? x : y
1839 * XXX In some cases we could implement a selection expression
1840 * with an LRP instruction (use the boolean as the interpolant).
1841 * Otherwise, we use an IF/ELSE/ENDIF construct.
1842 */
1843 static slang_ir_node *
1844 _slang_gen_select(slang_assemble_ctx *A, slang_operation *oper)
1845 {
1846 slang_ir_node *cond, *ifNode, *trueExpr, *falseExpr, *trueNode, *falseNode;
1847 slang_ir_node *tmpDecl, *tmpVar, *tree;
1848 slang_typeinfo type;
1849 int size;
1850
1851 assert(oper->type == SLANG_OPER_SELECT);
1852 assert(oper->num_children == 3);
1853
1854 /* size of x or y's type */
1855 slang_typeinfo_construct(&type);
1856 _slang_typeof_operation(A, &oper->children[1], &type);
1857 size = _slang_sizeof_type_specifier(&type.spec);
1858 assert(size > 0);
1859
1860 /* temporary var */
1861 tmpDecl = _slang_gen_temporary(size);
1862
1863 /* the condition (child 0) */
1864 cond = _slang_gen_operation(A, &oper->children[0]);
1865 cond = new_cond(cond);
1866
1867 /* if-true body (child 1) */
1868 tmpVar = new_node0(IR_VAR);
1869 tmpVar->Store = tmpDecl->Store;
1870 trueExpr = _slang_gen_operation(A, &oper->children[1]);
1871 trueNode = new_node2(IR_MOVE, tmpVar, trueExpr);
1872
1873 /* if-false body (child 2) */
1874 tmpVar = new_node0(IR_VAR);
1875 tmpVar->Store = tmpDecl->Store;
1876 falseExpr = _slang_gen_operation(A, &oper->children[2]);
1877 falseNode = new_node2(IR_MOVE, tmpVar, falseExpr);
1878
1879 ifNode = new_if(cond, trueNode, falseNode);
1880
1881 /* tmp var value */
1882 tmpVar = new_node0(IR_VAR);
1883 tmpVar->Store = tmpDecl->Store;
1884
1885 tree = new_seq(ifNode, tmpVar);
1886 tree = new_seq(tmpDecl, tree);
1887
1888 /*_slang_print_ir_tree(tree, 10);*/
1889 return tree;
1890 }
1891
1892
1893 /**
1894 * Generate code for &&.
1895 */
1896 static slang_ir_node *
1897 _slang_gen_logical_and(slang_assemble_ctx *A, slang_operation *oper)
1898 {
1899 /* rewrite "a && b" as "a ? b : false" */
1900 slang_operation *select;
1901 slang_ir_node *n;
1902
1903 select = slang_operation_new(1);
1904 select->type = SLANG_OPER_SELECT;
1905 select->num_children = 3;
1906 select->children = slang_operation_new(3);
1907
1908 slang_operation_copy(&select->children[0], &oper->children[0]);
1909 slang_operation_copy(&select->children[1], &oper->children[1]);
1910 select->children[2].type = SLANG_OPER_LITERAL_BOOL;
1911 ASSIGN_4V(select->children[2].literal, 0, 0, 0, 0); /* false */
1912 select->children[2].literal_size = 1;
1913
1914 n = _slang_gen_select(A, select);
1915 return n;
1916 }
1917
1918
1919 /**
1920 * Generate code for ||.
1921 */
1922 static slang_ir_node *
1923 _slang_gen_logical_or(slang_assemble_ctx *A, slang_operation *oper)
1924 {
1925 /* rewrite "a || b" as "a ? true : b" */
1926 slang_operation *select;
1927 slang_ir_node *n;
1928
1929 select = slang_operation_new(1);
1930 select->type = SLANG_OPER_SELECT;
1931 select->num_children = 3;
1932 select->children = slang_operation_new(3);
1933
1934 slang_operation_copy(&select->children[0], &oper->children[0]);
1935 select->children[1].type = SLANG_OPER_LITERAL_BOOL;
1936 ASSIGN_4V(select->children[1].literal, 1, 1, 1, 1); /* true */
1937 select->children[1].literal_size = 1;
1938 slang_operation_copy(&select->children[2], &oper->children[1]);
1939
1940 n = _slang_gen_select(A, select);
1941 return n;
1942 }
1943
1944
1945 /**
1946 * Generate IR tree for a return statement.
1947 */
1948 static slang_ir_node *
1949 _slang_gen_return(slang_assemble_ctx * A, slang_operation *oper)
1950 {
1951 const GLboolean haveReturnValue
1952 = (oper->num_children == 1 &&
1953 oper->children[0].type != SLANG_OPER_VOID);
1954
1955 /* error checking */
1956 assert(A->CurFunction);
1957 if (haveReturnValue &&
1958 A->CurFunction->header.type.specifier.type == SLANG_SPEC_VOID) {
1959 slang_info_log_error(A->log, "illegal return expression");
1960 return NULL;
1961 }
1962 else if (!haveReturnValue &&
1963 A->CurFunction->header.type.specifier.type != SLANG_SPEC_VOID) {
1964 slang_info_log_error(A->log, "return statement requires an expression");
1965 return NULL;
1966 }
1967
1968 if (!haveReturnValue) {
1969 return new_return(A->curFuncEndLabel);
1970 }
1971 else {
1972 /*
1973 * Convert from:
1974 * return expr;
1975 * To:
1976 * __retVal = expr;
1977 * return; // goto __endOfFunction
1978 */
1979 slang_operation *assign;
1980 slang_atom a_retVal;
1981 slang_ir_node *n;
1982
1983 a_retVal = slang_atom_pool_atom(A->atoms, "__retVal");
1984 assert(a_retVal);
1985
1986 #if 1 /* DEBUG */
1987 {
1988 slang_variable *v
1989 = _slang_locate_variable(oper->locals, a_retVal, GL_TRUE);
1990 if (!v) {
1991 /* trying to return a value in a void-valued function */
1992 return NULL;
1993 }
1994 }
1995 #endif
1996
1997 assign = slang_operation_new(1);
1998 assign->type = SLANG_OPER_ASSIGN;
1999 assign->num_children = 2;
2000 assign->children = slang_operation_new(2);
2001 /* lhs (__retVal) */
2002 assign->children[0].type = SLANG_OPER_IDENTIFIER;
2003 assign->children[0].a_id = a_retVal;
2004 assign->children[0].locals->outer_scope = assign->locals;
2005 /* rhs (expr) */
2006 /* XXX we might be able to avoid this copy someday */
2007 slang_operation_copy(&assign->children[1], &oper->children[0]);
2008
2009 /* assemble the new code */
2010 n = new_seq(_slang_gen_operation(A, assign),
2011 new_return(A->curFuncEndLabel));
2012
2013 slang_operation_delete(assign);
2014 return n;
2015 }
2016 }
2017
2018
2019 /**
2020 * Generate IR tree for a variable declaration.
2021 */
2022 static slang_ir_node *
2023 _slang_gen_declaration(slang_assemble_ctx *A, slang_operation *oper)
2024 {
2025 slang_ir_node *n;
2026 slang_ir_node *varDecl;
2027 slang_variable *v;
2028 const char *varName = (char *) oper->a_id;
2029
2030 assert(oper->num_children == 0 || oper->num_children == 1);
2031
2032 v = _slang_locate_variable(oper->locals, oper->a_id, GL_TRUE);
2033 assert(v);
2034
2035 varDecl = _slang_gen_var_decl(A, v);
2036
2037 if (oper->num_children > 0) {
2038 /* child is initializer */
2039 slang_ir_node *var, *init, *rhs;
2040 assert(oper->num_children == 1);
2041 var = new_var(A, oper, oper->a_id);
2042 if (!var) {
2043 slang_info_log_error(A->log, "undefined variable '%s'", varName);
2044 return NULL;
2045 }
2046 /* XXX make copy of this initializer? */
2047 rhs = _slang_gen_operation(A, &oper->children[0]);
2048 assert(rhs);
2049 init = new_node2(IR_MOVE, var, rhs);
2050 /*assert(rhs->Opcode != IR_SEQ);*/
2051 n = new_seq(varDecl, init);
2052 }
2053 else if (v->initializer) {
2054 slang_ir_node *var, *init, *rhs;
2055 var = new_var(A, oper, oper->a_id);
2056 if (!var) {
2057 slang_info_log_error(A->log, "undefined variable '%s'", varName);
2058 return NULL;
2059 }
2060 #if 0
2061 /* XXX make copy of this initializer? */
2062 {
2063 slang_operation dup;
2064 slang_operation_construct(&dup);
2065 slang_operation_copy(&dup, v->initializer);
2066 _slang_simplify(&dup, &A->space, A->atoms);
2067 rhs = _slang_gen_operation(A, &dup);
2068 }
2069 #else
2070 _slang_simplify(v->initializer, &A->space, A->atoms);
2071 rhs = _slang_gen_operation(A, v->initializer);
2072 #endif
2073 if (!rhs)
2074 return NULL;
2075
2076 assert(rhs);
2077 init = new_node2(IR_MOVE, var, rhs);
2078 /*
2079 assert(rhs->Opcode != IR_SEQ);
2080 */
2081 n = new_seq(varDecl, init);
2082 }
2083 else {
2084 n = varDecl;
2085 }
2086 return n;
2087 }
2088
2089
2090 /**
2091 * Generate IR tree for a variable (such as in an expression).
2092 */
2093 static slang_ir_node *
2094 _slang_gen_variable(slang_assemble_ctx * A, slang_operation *oper)
2095 {
2096 /* If there's a variable associated with this oper (from inlining)
2097 * use it. Otherwise, use the oper's var id.
2098 */
2099 slang_atom aVar = oper->var ? oper->var->a_name : oper->a_id;
2100 slang_ir_node *n = new_var(A, oper, aVar);
2101 if (!n) {
2102 slang_info_log_error(A->log, "undefined variable '%s'", (char *) aVar);
2103 return NULL;
2104 }
2105 return n;
2106 }
2107
2108
2109 /**
2110 * Some write-masked assignments are simple, but others are hard.
2111 * Simple example:
2112 * vec3 v;
2113 * v.xy = vec2(a, b);
2114 * Hard example:
2115 * vec3 v;
2116 * v.zy = vec2(a, b);
2117 * this gets transformed/swizzled into:
2118 * v.zy = vec2(a, b).*yx* (* = don't care)
2119 * This function helps to determine simple vs. non-simple.
2120 */
2121 static GLboolean
2122 _slang_simple_writemask(GLuint writemask, GLuint swizzle)
2123 {
2124 switch (writemask) {
2125 case WRITEMASK_X:
2126 return GET_SWZ(swizzle, 0) == SWIZZLE_X;
2127 case WRITEMASK_Y:
2128 return GET_SWZ(swizzle, 1) == SWIZZLE_Y;
2129 case WRITEMASK_Z:
2130 return GET_SWZ(swizzle, 2) == SWIZZLE_Z;
2131 case WRITEMASK_W:
2132 return GET_SWZ(swizzle, 3) == SWIZZLE_W;
2133 case WRITEMASK_XY:
2134 return (GET_SWZ(swizzle, 0) == SWIZZLE_X)
2135 && (GET_SWZ(swizzle, 1) == SWIZZLE_Y);
2136 case WRITEMASK_XYZ:
2137 return (GET_SWZ(swizzle, 0) == SWIZZLE_X)
2138 && (GET_SWZ(swizzle, 1) == SWIZZLE_Y)
2139 && (GET_SWZ(swizzle, 2) == SWIZZLE_Z);
2140 case WRITEMASK_XYZW:
2141 return swizzle == SWIZZLE_NOOP;
2142 default:
2143 return GL_FALSE;
2144 }
2145 }
2146
2147
2148 /**
2149 * Convert the given swizzle into a writemask. In some cases this
2150 * is trivial, in other cases, we'll need to also swizzle the right
2151 * hand side to put components in the right places.
2152 * \param swizzle the incoming swizzle
2153 * \param writemaskOut returns the writemask
2154 * \param swizzleOut swizzle to apply to the right-hand-side
2155 * \return GL_FALSE for simple writemasks, GL_TRUE for non-simple
2156 */
2157 static GLboolean
2158 swizzle_to_writemask(GLuint swizzle,
2159 GLuint *writemaskOut, GLuint *swizzleOut)
2160 {
2161 GLuint mask = 0x0, newSwizzle[4];
2162 GLint i, size;
2163
2164 /* make new dst writemask, compute size */
2165 for (i = 0; i < 4; i++) {
2166 const GLuint swz = GET_SWZ(swizzle, i);
2167 if (swz == SWIZZLE_NIL) {
2168 /* end */
2169 break;
2170 }
2171 assert(swz >= 0 && swz <= 3);
2172 mask |= (1 << swz);
2173 }
2174 assert(mask <= 0xf);
2175 size = i; /* number of components in mask/swizzle */
2176
2177 *writemaskOut = mask;
2178
2179 /* make new src swizzle, by inversion */
2180 for (i = 0; i < 4; i++) {
2181 newSwizzle[i] = i; /*identity*/
2182 }
2183 for (i = 0; i < size; i++) {
2184 const GLuint swz = GET_SWZ(swizzle, i);
2185 newSwizzle[swz] = i;
2186 }
2187 *swizzleOut = MAKE_SWIZZLE4(newSwizzle[0],
2188 newSwizzle[1],
2189 newSwizzle[2],
2190 newSwizzle[3]);
2191
2192 if (_slang_simple_writemask(mask, *swizzleOut)) {
2193 if (size >= 1)
2194 assert(GET_SWZ(*swizzleOut, 0) == SWIZZLE_X);
2195 if (size >= 2)
2196 assert(GET_SWZ(*swizzleOut, 1) == SWIZZLE_Y);
2197 if (size >= 3)
2198 assert(GET_SWZ(*swizzleOut, 2) == SWIZZLE_Z);
2199 if (size >= 4)
2200 assert(GET_SWZ(*swizzleOut, 3) == SWIZZLE_W);
2201 return GL_TRUE;
2202 }
2203 else
2204 return GL_FALSE;
2205 }
2206
2207
2208 static slang_ir_node *
2209 _slang_gen_swizzle(slang_ir_node *child, GLuint swizzle)
2210 {
2211 slang_ir_node *n = new_node1(IR_SWIZZLE, child);
2212 assert(child);
2213 if (n) {
2214 n->Store = _slang_new_ir_storage(PROGRAM_UNDEFINED, -1, -1);
2215 n->Store->Swizzle = swizzle;
2216 }
2217 return n;
2218 }
2219
2220
2221 /**
2222 * Generate IR tree for an assignment (=).
2223 */
2224 static slang_ir_node *
2225 _slang_gen_assignment(slang_assemble_ctx * A, slang_operation *oper)
2226 {
2227 if (oper->children[0].type == SLANG_OPER_IDENTIFIER) {
2228 /* Check that var is writeable */
2229 slang_variable *var
2230 = _slang_locate_variable(oper->children[0].locals,
2231 oper->children[0].a_id, GL_TRUE);
2232 if (!var) {
2233 slang_info_log_error(A->log, "undefined variable '%s'",
2234 (char *) oper->children[0].a_id);
2235 return NULL;
2236 }
2237 if (var->type.qualifier == SLANG_QUAL_CONST ||
2238 var->type.qualifier == SLANG_QUAL_ATTRIBUTE ||
2239 var->type.qualifier == SLANG_QUAL_UNIFORM) {
2240 slang_info_log_error(A->log,
2241 "illegal assignment to read-only variable '%s'",
2242 (char *) oper->children[0].a_id);
2243 return NULL;
2244 }
2245 }
2246
2247 if (oper->children[0].type == SLANG_OPER_IDENTIFIER &&
2248 oper->children[1].type == SLANG_OPER_CALL) {
2249 /* Special case of: x = f(a, b)
2250 * Replace with f(a, b, x) (where x == hidden __retVal out param)
2251 *
2252 * XXX this could be even more effective if we could accomodate
2253 * cases such as "v.x = f();" - would help with typical vertex
2254 * transformation.
2255 */
2256 slang_ir_node *n;
2257 n = _slang_gen_function_call_name(A,
2258 (const char *) oper->children[1].a_id,
2259 &oper->children[1], &oper->children[0]);
2260 return n;
2261 }
2262 else {
2263 slang_ir_node *n, *lhs, *rhs;
2264 lhs = _slang_gen_operation(A, &oper->children[0]);
2265
2266 if (lhs) {
2267 if (lhs->Store->File != PROGRAM_OUTPUT &&
2268 lhs->Store->File != PROGRAM_TEMPORARY &&
2269 lhs->Store->File != PROGRAM_VARYING &&
2270 lhs->Store->File != PROGRAM_UNDEFINED) {
2271 slang_info_log_error(A->log,
2272 "illegal assignment to read-only l-value");
2273 return NULL;
2274 }
2275 }
2276
2277 rhs = _slang_gen_operation(A, &oper->children[1]);
2278 if (lhs && rhs) {
2279 /* convert lhs swizzle into writemask */
2280 GLuint writemask, newSwizzle;
2281 if (!swizzle_to_writemask(lhs->Store->Swizzle,
2282 &writemask, &newSwizzle)) {
2283 /* Non-simple writemask, need to swizzle right hand side in
2284 * order to put components into the right place.
2285 */
2286 rhs = _slang_gen_swizzle(rhs, newSwizzle);
2287 }
2288 n = new_node2(IR_MOVE, lhs, rhs);
2289 n->Writemask = writemask;
2290 return n;
2291 }
2292 else {
2293 return NULL;
2294 }
2295 }
2296 }
2297
2298
2299 /**
2300 * Generate IR tree for referencing a field in a struct (or basic vector type)
2301 */
2302 static slang_ir_node *
2303 _slang_gen_field(slang_assemble_ctx * A, slang_operation *oper)
2304 {
2305 slang_typeinfo ti;
2306
2307 /* type of struct */
2308 slang_typeinfo_construct(&ti);
2309 _slang_typeof_operation(A, &oper->children[0], &ti);
2310
2311 if (_slang_type_is_vector(ti.spec.type)) {
2312 /* the field should be a swizzle */
2313 const GLuint rows = _slang_type_dim(ti.spec.type);
2314 slang_swizzle swz;
2315 slang_ir_node *n;
2316 GLuint swizzle;
2317 if (!_slang_is_swizzle((char *) oper->a_id, rows, &swz)) {
2318 slang_info_log_error(A->log, "Bad swizzle");
2319 }
2320 swizzle = MAKE_SWIZZLE4(swz.swizzle[0],
2321 swz.swizzle[1],
2322 swz.swizzle[2],
2323 swz.swizzle[3]);
2324
2325 n = _slang_gen_operation(A, &oper->children[0]);
2326 /* create new parent node with swizzle */
2327 if (n)
2328 n = _slang_gen_swizzle(n, swizzle);
2329 return n;
2330 }
2331 else if (ti.spec.type == SLANG_SPEC_FLOAT) {
2332 const GLuint rows = 1;
2333 slang_swizzle swz;
2334 slang_ir_node *n;
2335 GLuint swizzle;
2336 if (!_slang_is_swizzle((char *) oper->a_id, rows, &swz)) {
2337 slang_info_log_error(A->log, "Bad swizzle");
2338 }
2339 swizzle = MAKE_SWIZZLE4(swz.swizzle[0],
2340 swz.swizzle[1],
2341 swz.swizzle[2],
2342 swz.swizzle[3]);
2343 n = _slang_gen_operation(A, &oper->children[0]);
2344 /* create new parent node with swizzle */
2345 n = _slang_gen_swizzle(n, swizzle);
2346 return n;
2347 }
2348 else {
2349 /* the field is a structure member (base.field) */
2350 /* oper->children[0] is the base */
2351 /* oper->a_id is the field name */
2352 slang_ir_node *base, *n;
2353 slang_typeinfo field_ti;
2354 GLint fieldSize, fieldOffset = -1;
2355 /* type of field */
2356 slang_typeinfo_construct(&field_ti);
2357 _slang_typeof_operation(A, oper, &field_ti);
2358
2359 fieldSize = _slang_sizeof_type_specifier(&field_ti.spec);
2360 if (fieldSize > 0)
2361 fieldOffset = _slang_field_offset(&ti.spec, oper->a_id);
2362
2363 if (fieldSize == 0 || fieldOffset < 0) {
2364 slang_info_log_error(A->log,
2365 "\"%s\" is not a member of struct \"%s\"",
2366 (char *) oper->a_id,
2367 (char *) ti.spec._struct->a_name);
2368 return NULL;
2369 }
2370 assert(fieldSize >= 0);
2371
2372 base = _slang_gen_operation(A, &oper->children[0]);
2373 if (!base) {
2374 /* error msg should have already been logged */
2375 return NULL;
2376 }
2377
2378 n = new_node1(IR_FIELD, base);
2379 if (n) {
2380 n->Field = (char *) oper->a_id;
2381 n->FieldOffset = fieldOffset;
2382 assert(n->FieldOffset >= 0);
2383 n->Store = _slang_new_ir_storage(base->Store->File,
2384 base->Store->Index,
2385 fieldSize);
2386 }
2387 return n;
2388
2389 #if 0
2390 _mesa_problem(NULL, "glsl structs/fields not supported yet");
2391 return NULL;
2392 #endif
2393 }
2394 }
2395
2396
2397 /**
2398 * Gen code for array indexing.
2399 */
2400 static slang_ir_node *
2401 _slang_gen_subscript(slang_assemble_ctx * A, slang_operation *oper)
2402 {
2403 slang_typeinfo array_ti;
2404
2405 /* get array's type info */
2406 slang_typeinfo_construct(&array_ti);
2407 _slang_typeof_operation(A, &oper->children[0], &array_ti);
2408
2409 if (_slang_type_is_vector(array_ti.spec.type)) {
2410 /* indexing a simple vector type: "vec4 v; v[0]=p;" */
2411 /* translate the index into a swizzle/writemask: "v.x=p" */
2412 const GLuint max = _slang_type_dim(array_ti.spec.type);
2413 GLint index;
2414 slang_ir_node *n;
2415
2416 index = (GLint) oper->children[1].literal[0];
2417 if (oper->children[1].type != SLANG_OPER_LITERAL_INT ||
2418 index >= max) {
2419 slang_info_log_error(A->log, "Invalid array index for vector type");
2420 return NULL;
2421 }
2422
2423 n = _slang_gen_operation(A, &oper->children[0]);
2424 if (n) {
2425 /* use swizzle to access the element */
2426 GLuint swizzle = MAKE_SWIZZLE4(SWIZZLE_X + index,
2427 SWIZZLE_NIL,
2428 SWIZZLE_NIL,
2429 SWIZZLE_NIL);
2430 n = _slang_gen_swizzle(n, swizzle);
2431 /*n->Store = _slang_clone_ir_storage_swz(n->Store, */
2432 n->Writemask = WRITEMASK_X << index;
2433 }
2434 return n;
2435 }
2436 else {
2437 /* conventional array */
2438 slang_typeinfo elem_ti;
2439 slang_ir_node *elem, *array, *index;
2440 GLint elemSize, arrayLen;
2441
2442 /* size of array element */
2443 slang_typeinfo_construct(&elem_ti);
2444 _slang_typeof_operation(A, oper, &elem_ti);
2445 elemSize = _slang_sizeof_type_specifier(&elem_ti.spec);
2446
2447 if (_slang_type_is_matrix(array_ti.spec.type))
2448 arrayLen = _slang_type_dim(array_ti.spec.type);
2449 else
2450 arrayLen = array_ti.array_len;
2451
2452 slang_typeinfo_destruct(&array_ti);
2453 slang_typeinfo_destruct(&elem_ti);
2454
2455 if (elemSize <= 0) {
2456 /* unknown var or type */
2457 slang_info_log_error(A->log, "Undefined variable or type");
2458 return NULL;
2459 }
2460
2461 array = _slang_gen_operation(A, &oper->children[0]);
2462 index = _slang_gen_operation(A, &oper->children[1]);
2463 if (array && index) {
2464 /* bounds check */
2465 if (index->Opcode == IR_FLOAT &&
2466 ((int) index->Value[0] < 0 ||
2467 (int) index->Value[0] >= arrayLen)) {
2468 slang_info_log_error(A->log,
2469 "Array index out of bounds (index=%d size=%d)",
2470 (int) index->Value[0], arrayLen);
2471 _slang_free_ir_tree(array);
2472 _slang_free_ir_tree(index);
2473 return NULL;
2474 }
2475
2476 elem = new_node2(IR_ELEMENT, array, index);
2477 elem->Store = _slang_new_ir_storage(array->Store->File,
2478 array->Store->Index,
2479 elemSize);
2480 /* XXX try to do some array bounds checking here */
2481 return elem;
2482 }
2483 else {
2484 _slang_free_ir_tree(array);
2485 _slang_free_ir_tree(index);
2486 return NULL;
2487 }
2488 }
2489 }
2490
2491
2492 /**
2493 * Look for expressions such as: gl_ModelviewMatrix * gl_Vertex
2494 * and replace with this: gl_Vertex * gl_ModelviewMatrixTranpose
2495 * Since matrices are stored in column-major order, the second form of
2496 * multiplication is much more efficient (just 4 dot products).
2497 */
2498 static void
2499 _slang_check_matmul_optimization(slang_assemble_ctx *A, slang_operation *oper)
2500 {
2501 static const struct {
2502 const char *orig;
2503 const char *tranpose;
2504 } matrices[] = {
2505 {"gl_ModelViewMatrix", "gl_ModelViewMatrixTranspose"},
2506 {"gl_ProjectionMatrix", "gl_ProjectionMatrixTranspose"},
2507 {"gl_ModelViewProjectionMatrix", "gl_ModelViewProjectionMatrixTranspose"},
2508 {"gl_TextureMatrix", "gl_TextureMatrixTranspose"},
2509 {"gl_NormalMatrix", "__NormalMatrixTranspose"},
2510 { NULL, NULL }
2511 };
2512
2513 assert(oper->type == SLANG_OPER_MULTIPLY);
2514 if (oper->children[0].type == SLANG_OPER_IDENTIFIER) {
2515 GLuint i;
2516 for (i = 0; matrices[i].orig; i++) {
2517 if (oper->children[0].a_id
2518 == slang_atom_pool_atom(A->atoms, matrices[i].orig)) {
2519 /*
2520 _mesa_printf("Replace %s with %s\n",
2521 matrices[i].orig, matrices[i].tranpose);
2522 */
2523 assert(oper->children[0].type == SLANG_OPER_IDENTIFIER);
2524 oper->children[0].a_id
2525 = slang_atom_pool_atom(A->atoms, matrices[i].tranpose);
2526 /* finally, swap the operands */
2527 _slang_operation_swap(&oper->children[0], &oper->children[1]);
2528 return;
2529 }
2530 }
2531 }
2532 }
2533
2534
2535 /**
2536 * Generate IR tree for a slang_operation (AST node)
2537 */
2538 static slang_ir_node *
2539 _slang_gen_operation(slang_assemble_ctx * A, slang_operation *oper)
2540 {
2541 switch (oper->type) {
2542 case SLANG_OPER_BLOCK_NEW_SCOPE:
2543 {
2544 slang_ir_node *n;
2545
2546 _slang_push_var_table(A->vartable);
2547
2548 oper->type = SLANG_OPER_BLOCK_NO_NEW_SCOPE; /* temp change */
2549 n = _slang_gen_operation(A, oper);
2550 oper->type = SLANG_OPER_BLOCK_NEW_SCOPE; /* restore */
2551
2552 _slang_pop_var_table(A->vartable);
2553
2554 if (n)
2555 n = new_node1(IR_SCOPE, n);
2556 return n;
2557 }
2558 break;
2559
2560 case SLANG_OPER_BLOCK_NO_NEW_SCOPE:
2561 /* list of operations */
2562 if (oper->num_children > 0)
2563 {
2564 slang_ir_node *n, *tree = NULL;
2565 GLuint i;
2566
2567 for (i = 0; i < oper->num_children; i++) {
2568 n = _slang_gen_operation(A, &oper->children[i]);
2569 if (!n) {
2570 _slang_free_ir_tree(tree);
2571 return NULL; /* error must have occured */
2572 }
2573 tree = tree ? new_seq(tree, n) : n;
2574 }
2575
2576 #if 00
2577 if (oper->locals->num_variables > 0) {
2578 int i;
2579 /*
2580 printf("\n****** Deallocate vars in scope!\n");
2581 */
2582 for (i = 0; i < oper->locals->num_variables; i++) {
2583 slang_variable *v = oper->locals->variables + i;
2584 if (v->aux) {
2585 slang_ir_storage *store = (slang_ir_storage *) v->aux;
2586 /*
2587 printf(" Deallocate var %s\n", (char*) v->a_name);
2588 */
2589 assert(store->File == PROGRAM_TEMPORARY);
2590 assert(store->Index >= 0);
2591 _slang_free_temp(A->vartable, store->Index, store->Size);
2592 }
2593 }
2594 }
2595 #endif
2596 return tree;
2597 }
2598 else {
2599 return new_node0(IR_NOP);
2600 }
2601
2602 case SLANG_OPER_EXPRESSION:
2603 return _slang_gen_operation(A, &oper->children[0]);
2604
2605 case SLANG_OPER_FOR:
2606 return _slang_gen_for(A, oper);
2607 case SLANG_OPER_DO:
2608 return _slang_gen_do(A, oper);
2609 case SLANG_OPER_WHILE:
2610 return _slang_gen_while(A, oper);
2611 case SLANG_OPER_BREAK:
2612 if (!A->CurLoop) {
2613 slang_info_log_error(A->log, "'break' not in loop");
2614 return NULL;
2615 }
2616 return new_break(A->CurLoop);
2617 case SLANG_OPER_CONTINUE:
2618 if (!A->CurLoop) {
2619 slang_info_log_error(A->log, "'continue' not in loop");
2620 return NULL;
2621 }
2622 return _slang_gen_continue(A, oper);
2623 case SLANG_OPER_DISCARD:
2624 return new_node0(IR_KILL);
2625
2626 case SLANG_OPER_EQUAL:
2627 return new_node2(IR_EQUAL,
2628 _slang_gen_operation(A, &oper->children[0]),
2629 _slang_gen_operation(A, &oper->children[1]));
2630 case SLANG_OPER_NOTEQUAL:
2631 return new_node2(IR_NOTEQUAL,
2632 _slang_gen_operation(A, &oper->children[0]),
2633 _slang_gen_operation(A, &oper->children[1]));
2634 case SLANG_OPER_GREATER:
2635 return new_node2(IR_SGT,
2636 _slang_gen_operation(A, &oper->children[0]),
2637 _slang_gen_operation(A, &oper->children[1]));
2638 case SLANG_OPER_LESS:
2639 return new_node2(IR_SLT,
2640 _slang_gen_operation(A, &oper->children[0]),
2641 _slang_gen_operation(A, &oper->children[1]));
2642 case SLANG_OPER_GREATEREQUAL:
2643 return new_node2(IR_SGE,
2644 _slang_gen_operation(A, &oper->children[0]),
2645 _slang_gen_operation(A, &oper->children[1]));
2646 case SLANG_OPER_LESSEQUAL:
2647 return new_node2(IR_SLE,
2648 _slang_gen_operation(A, &oper->children[0]),
2649 _slang_gen_operation(A, &oper->children[1]));
2650 case SLANG_OPER_ADD:
2651 {
2652 slang_ir_node *n;
2653 assert(oper->num_children == 2);
2654 n = _slang_gen_function_call_name(A, "+", oper, NULL);
2655 return n;
2656 }
2657 case SLANG_OPER_SUBTRACT:
2658 {
2659 slang_ir_node *n;
2660 assert(oper->num_children == 2);
2661 n = _slang_gen_function_call_name(A, "-", oper, NULL);
2662 return n;
2663 }
2664 case SLANG_OPER_MULTIPLY:
2665 {
2666 slang_ir_node *n;
2667 assert(oper->num_children == 2);
2668 _slang_check_matmul_optimization(A, oper);
2669 n = _slang_gen_function_call_name(A, "*", oper, NULL);
2670 return n;
2671 }
2672 case SLANG_OPER_DIVIDE:
2673 {
2674 slang_ir_node *n;
2675 assert(oper->num_children == 2);
2676 n = _slang_gen_function_call_name(A, "/", oper, NULL);
2677 return n;
2678 }
2679 case SLANG_OPER_MINUS:
2680 {
2681 slang_ir_node *n;
2682 assert(oper->num_children == 1);
2683 n = _slang_gen_function_call_name(A, "-", oper, NULL);
2684 return n;
2685 }
2686 case SLANG_OPER_PLUS:
2687 /* +expr --> do nothing */
2688 return _slang_gen_operation(A, &oper->children[0]);
2689 case SLANG_OPER_VARIABLE_DECL:
2690 return _slang_gen_declaration(A, oper);
2691 case SLANG_OPER_ASSIGN:
2692 return _slang_gen_assignment(A, oper);
2693 case SLANG_OPER_ADDASSIGN:
2694 {
2695 slang_ir_node *n;
2696 assert(oper->num_children == 2);
2697 n = _slang_gen_function_call_name(A, "+=", oper, &oper->children[0]);
2698 return n;
2699 }
2700 case SLANG_OPER_SUBASSIGN:
2701 {
2702 slang_ir_node *n;
2703 assert(oper->num_children == 2);
2704 n = _slang_gen_function_call_name(A, "-=", oper, &oper->children[0]);
2705 return n;
2706 }
2707 break;
2708 case SLANG_OPER_MULASSIGN:
2709 {
2710 slang_ir_node *n;
2711 assert(oper->num_children == 2);
2712 n = _slang_gen_function_call_name(A, "*=", oper, &oper->children[0]);
2713 return n;
2714 }
2715 case SLANG_OPER_DIVASSIGN:
2716 {
2717 slang_ir_node *n;
2718 assert(oper->num_children == 2);
2719 n = _slang_gen_function_call_name(A, "/=", oper, &oper->children[0]);
2720 return n;
2721 }
2722 case SLANG_OPER_LOGICALAND:
2723 {
2724 slang_ir_node *n;
2725 assert(oper->num_children == 2);
2726 n = _slang_gen_logical_and(A, oper);
2727 return n;
2728 }
2729 case SLANG_OPER_LOGICALOR:
2730 {
2731 slang_ir_node *n;
2732 assert(oper->num_children == 2);
2733 n = _slang_gen_logical_or(A, oper);
2734 return n;
2735 }
2736 case SLANG_OPER_LOGICALXOR:
2737 return _slang_gen_xor(A, oper);
2738 case SLANG_OPER_NOT:
2739 return _slang_gen_not(A, oper);
2740 case SLANG_OPER_SELECT: /* b ? x : y */
2741 {
2742 slang_ir_node *n;
2743 assert(oper->num_children == 3);
2744 n = _slang_gen_select(A, oper);
2745 return n;
2746 }
2747
2748 case SLANG_OPER_ASM:
2749 return _slang_gen_asm(A, oper, NULL);
2750 case SLANG_OPER_CALL:
2751 return _slang_gen_function_call_name(A, (const char *) oper->a_id,
2752 oper, NULL);
2753 case SLANG_OPER_RETURN:
2754 return _slang_gen_return(A, oper);
2755 case SLANG_OPER_LABEL:
2756 return new_label(oper->label);
2757 case SLANG_OPER_IDENTIFIER:
2758 return _slang_gen_variable(A, oper);
2759 case SLANG_OPER_IF:
2760 return _slang_gen_if(A, oper);
2761 case SLANG_OPER_FIELD:
2762 return _slang_gen_field(A, oper);
2763 case SLANG_OPER_SUBSCRIPT:
2764 return _slang_gen_subscript(A, oper);
2765 case SLANG_OPER_LITERAL_FLOAT:
2766 /* fall-through */
2767 case SLANG_OPER_LITERAL_INT:
2768 /* fall-through */
2769 case SLANG_OPER_LITERAL_BOOL:
2770 return new_float_literal(oper->literal, oper->literal_size);
2771
2772 case SLANG_OPER_POSTINCREMENT: /* var++ */
2773 {
2774 slang_ir_node *n;
2775 assert(oper->num_children == 1);
2776 n = _slang_gen_function_call_name(A, "__postIncr", oper, NULL);
2777 return n;
2778 }
2779 case SLANG_OPER_POSTDECREMENT: /* var-- */
2780 {
2781 slang_ir_node *n;
2782 assert(oper->num_children == 1);
2783 n = _slang_gen_function_call_name(A, "__postDecr", oper, NULL);
2784 return n;
2785 }
2786 case SLANG_OPER_PREINCREMENT: /* ++var */
2787 {
2788 slang_ir_node *n;
2789 assert(oper->num_children == 1);
2790 n = _slang_gen_function_call_name(A, "++", oper, NULL);
2791 return n;
2792 }
2793 case SLANG_OPER_PREDECREMENT: /* --var */
2794 {
2795 slang_ir_node *n;
2796 assert(oper->num_children == 1);
2797 n = _slang_gen_function_call_name(A, "--", oper, NULL);
2798 return n;
2799 }
2800
2801 case SLANG_OPER_INLINED_CALL:
2802 case SLANG_OPER_SEQUENCE:
2803 {
2804 slang_ir_node *tree = NULL;
2805 GLuint i;
2806 for (i = 0; i < oper->num_children; i++) {
2807 slang_ir_node *n = _slang_gen_operation(A, &oper->children[i]);
2808 tree = tree ? new_seq(tree, n) : n;
2809 }
2810 if (oper->type == SLANG_OPER_INLINED_CALL) {
2811 tree = new_inlined_function_call(tree, oper->label);
2812 }
2813 return tree;
2814 }
2815
2816 case SLANG_OPER_NONE:
2817 case SLANG_OPER_VOID:
2818 /* returning NULL here would generate an error */
2819 return new_node0(IR_NOP);
2820
2821 default:
2822 _mesa_problem(NULL, "bad node type %d in _slang_gen_operation",
2823 oper->type);
2824 return new_node0(IR_NOP);
2825 }
2826
2827 return NULL;
2828 }
2829
2830
2831
2832 /**
2833 * Called by compiler when a global variable has been parsed/compiled.
2834 * Here we examine the variable's type to determine what kind of register
2835 * storage will be used.
2836 *
2837 * A uniform such as "gl_Position" will become the register specification
2838 * (PROGRAM_OUTPUT, VERT_RESULT_HPOS). Or, uniform "gl_FogFragCoord"
2839 * will be (PROGRAM_INPUT, FRAG_ATTRIB_FOGC).
2840 *
2841 * Samplers are interesting. For "uniform sampler2D tex;" we'll specify
2842 * (PROGRAM_SAMPLER, index) where index is resolved at link-time to an
2843 * actual texture unit (as specified by the user calling glUniform1i()).
2844 */
2845 GLboolean
2846 _slang_codegen_global_variable(slang_assemble_ctx *A, slang_variable *var,
2847 slang_unit_type type)
2848 {
2849 struct gl_program *prog = A->program;
2850 const char *varName = (char *) var->a_name;
2851 GLboolean success = GL_TRUE;
2852 slang_ir_storage *store = NULL;
2853 int dbg = 0;
2854 const GLenum datatype = _slang_gltype_from_specifier(&var->type.specifier);
2855 const GLint texIndex = sampler_to_texture_index(var->type.specifier.type);
2856
2857 if (texIndex != -1) {
2858 /* Texture sampler:
2859 * store->File = PROGRAM_SAMPLER
2860 * store->Index = sampler uniform location
2861 * store->Size = texture type index (1D, 2D, 3D, cube, etc)
2862 */
2863 GLint samplerUniform
2864 = _mesa_add_sampler(prog->Parameters, varName, datatype);
2865 store = _slang_new_ir_storage(PROGRAM_SAMPLER, samplerUniform, texIndex);
2866 if (dbg) printf("SAMPLER ");
2867 }
2868 else if (var->type.qualifier == SLANG_QUAL_UNIFORM) {
2869 /* Uniform variable */
2870 const GLint size = _slang_sizeof_type_specifier(&var->type.specifier)
2871 * MAX2(var->array_len, 1);
2872 if (prog) {
2873 /* user-defined uniform */
2874 if (datatype == GL_NONE) {
2875 if (var->type.specifier.type == SLANG_SPEC_STRUCT) {
2876 _mesa_problem(NULL, "user-declared uniform structs not supported yet");
2877 /* XXX what we need to do is unroll the struct into its
2878 * basic types, creating a uniform variable for each.
2879 * For example:
2880 * struct foo {
2881 * vec3 a;
2882 * vec4 b;
2883 * };
2884 * uniform foo f;
2885 *
2886 * Should produce uniforms:
2887 * "f.a" (GL_FLOAT_VEC3)
2888 * "f.b" (GL_FLOAT_VEC4)
2889 */
2890 }
2891 else {
2892 slang_info_log_error(A->log,
2893 "invalid datatype for uniform variable %s",
2894 (char *) var->a_name);
2895 }
2896 return GL_FALSE;
2897 }
2898 else {
2899 GLint uniformLoc = _mesa_add_uniform(prog->Parameters, varName,
2900 size, datatype);
2901 store = _slang_new_ir_storage(PROGRAM_UNIFORM, uniformLoc, size);
2902 }
2903 }
2904 else {
2905 /* pre-defined uniform, like gl_ModelviewMatrix */
2906 /* We know it's a uniform, but don't allocate storage unless
2907 * it's really used.
2908 */
2909 store = _slang_new_ir_storage(PROGRAM_STATE_VAR, -1, size);
2910 }
2911 if (dbg) printf("UNIFORM (sz %d) ", size);
2912 }
2913 else if (var->type.qualifier == SLANG_QUAL_VARYING) {
2914 const GLint size = 4; /* XXX fix */
2915 if (prog) {
2916 /* user-defined varying */
2917 GLint varyingLoc = _mesa_add_varying(prog->Varying, varName, size);
2918 store = _slang_new_ir_storage(PROGRAM_VARYING, varyingLoc, size);
2919 }
2920 else {
2921 /* pre-defined varying, like gl_Color or gl_TexCoord */
2922 if (type == SLANG_UNIT_FRAGMENT_BUILTIN) {
2923 GLuint swizzle;
2924 GLint index = _slang_input_index(varName, GL_FRAGMENT_PROGRAM_ARB,
2925 &swizzle);
2926 assert(index >= 0);
2927 store = _slang_new_ir_storage(PROGRAM_INPUT, index, size);
2928 store->Swizzle = swizzle;
2929 assert(index < FRAG_ATTRIB_MAX);
2930 }
2931 else {
2932 GLint index = _slang_output_index(varName, GL_VERTEX_PROGRAM_ARB);
2933 assert(index >= 0);
2934 assert(type == SLANG_UNIT_VERTEX_BUILTIN);
2935 store = _slang_new_ir_storage(PROGRAM_OUTPUT, index, size);
2936 assert(index < VERT_RESULT_MAX);
2937 }
2938 if (dbg) printf("V/F ");
2939 }
2940 if (dbg) printf("VARYING ");
2941 }
2942 else if (var->type.qualifier == SLANG_QUAL_ATTRIBUTE) {
2943 if (prog) {
2944 /* user-defined vertex attribute */
2945 const GLint size = _slang_sizeof_type_specifier(&var->type.specifier);
2946 const GLint attr = -1; /* unknown */
2947 GLint index = _mesa_add_attribute(prog->Attributes, varName,
2948 size, attr);
2949 assert(index >= 0);
2950 store = _slang_new_ir_storage(PROGRAM_INPUT,
2951 VERT_ATTRIB_GENERIC0 + index, size);
2952 }
2953 else {
2954 /* pre-defined vertex attrib */
2955 GLuint swizzle;
2956 GLint index = _slang_input_index(varName, GL_VERTEX_PROGRAM_ARB,
2957 &swizzle);
2958 GLint size = 4; /* XXX? */
2959 assert(index >= 0);
2960 store = _slang_new_ir_storage(PROGRAM_INPUT, index, size);
2961 store->Swizzle = swizzle;
2962 }
2963 if (dbg) printf("ATTRIB ");
2964 }
2965 else if (var->type.qualifier == SLANG_QUAL_FIXEDINPUT) {
2966 GLuint swizzle = SWIZZLE_XYZW; /* silence compiler warning */
2967 GLint index = _slang_input_index(varName, GL_FRAGMENT_PROGRAM_ARB,
2968 &swizzle);
2969 GLint size = 4; /* XXX? */
2970 store = _slang_new_ir_storage(PROGRAM_INPUT, index, size);
2971 store->Swizzle = swizzle;
2972 if (dbg) printf("INPUT ");
2973 }
2974 else if (var->type.qualifier == SLANG_QUAL_FIXEDOUTPUT) {
2975 if (type == SLANG_UNIT_VERTEX_BUILTIN) {
2976 GLint index = _slang_output_index(varName, GL_VERTEX_PROGRAM_ARB);
2977 GLint size = 4; /* XXX? */
2978 store = _slang_new_ir_storage(PROGRAM_OUTPUT, index, size);
2979 }
2980 else {
2981 GLint index = _slang_output_index(varName, GL_FRAGMENT_PROGRAM_ARB);
2982 GLint size = 4; /* XXX? */
2983 assert(type == SLANG_UNIT_FRAGMENT_BUILTIN);
2984 store = _slang_new_ir_storage(PROGRAM_OUTPUT, index, size);
2985 }
2986 if (dbg) printf("OUTPUT ");
2987 }
2988 else if (var->type.qualifier == SLANG_QUAL_CONST && !prog) {
2989 /* pre-defined global constant, like gl_MaxLights */
2990 const GLint size = _slang_sizeof_type_specifier(&var->type.specifier);
2991 store = _slang_new_ir_storage(PROGRAM_CONSTANT, -1, size);
2992 if (dbg) printf("CONST ");
2993 }
2994 else {
2995 /* ordinary variable (may be const) */
2996 slang_ir_node *n;
2997
2998 /* IR node to declare the variable */
2999 n = _slang_gen_var_decl(A, var);
3000
3001 /* IR code for the var's initializer, if present */
3002 if (var->initializer) {
3003 slang_ir_node *lhs, *rhs, *init;
3004
3005 /* Generate IR_MOVE instruction to initialize the variable */
3006 lhs = new_node0(IR_VAR);
3007 lhs->Var = var;
3008 lhs->Store = n->Store;
3009
3010 /* constant folding, etc */
3011 _slang_simplify(var->initializer, &A->space, A->atoms);
3012
3013 rhs = _slang_gen_operation(A, var->initializer);
3014 assert(rhs);
3015 init = new_node2(IR_MOVE, lhs, rhs);
3016 n = new_seq(n, init);
3017 }
3018
3019 success = _slang_emit_code(n, A->vartable, A->program, GL_FALSE, A->log);
3020
3021 _slang_free_ir_tree(n);
3022 }
3023
3024 if (dbg) printf("GLOBAL VAR %s idx %d\n", (char*) var->a_name,
3025 store ? store->Index : -2);
3026
3027 if (store)
3028 var->aux = store; /* save var's storage info */
3029
3030 return success;
3031 }
3032
3033
3034 /**
3035 * Produce an IR tree from a function AST (fun->body).
3036 * Then call the code emitter to convert the IR tree into gl_program
3037 * instructions.
3038 */
3039 GLboolean
3040 _slang_codegen_function(slang_assemble_ctx * A, slang_function * fun)
3041 {
3042 slang_ir_node *n;
3043 GLboolean success = GL_TRUE;
3044
3045 if (_mesa_strcmp((char *) fun->header.a_name, "main") != 0) {
3046 /* we only really generate code for main, all other functions get
3047 * inlined.
3048 */
3049 #if 0
3050 /* do some basic error checking though */
3051 if (fun->header.type.specifier.type != SLANG_SPEC_VOID) {
3052 /* check that non-void functions actually return something */
3053 slang_operation *op
3054 = _slang_find_node_type(fun->body, SLANG_OPER_RETURN);
3055 if (!op) {
3056 slang_info_log_error(A->log,
3057 "function \"%s\" has no return statement",
3058 (char *) fun->header.a_name);
3059 printf(
3060 "function \"%s\" has no return statement\n",
3061 (char *) fun->header.a_name);
3062 return GL_FALSE;
3063 }
3064 }
3065 #endif
3066 return GL_TRUE; /* not an error */
3067 }
3068
3069 #if 0
3070 printf("\n*********** codegen_function %s\n", (char *) fun->header.a_name);
3071 slang_print_function(fun, 1);
3072 #endif
3073
3074 /* should have been allocated earlier: */
3075 assert(A->program->Parameters );
3076 assert(A->program->Varying);
3077 assert(A->vartable);
3078 A->CurLoop = NULL;
3079 A->CurFunction = fun;
3080
3081 /* fold constant expressions, etc. */
3082 _slang_simplify(fun->body, &A->space, A->atoms);
3083
3084 #if 0
3085 printf("\n*********** simplified %s\n", (char *) fun->header.a_name);
3086 slang_print_function(fun, 1);
3087 #endif
3088
3089 /* Create an end-of-function label */
3090 A->curFuncEndLabel = _slang_label_new("__endOfFunc__main");
3091
3092 /* push new vartable scope */
3093 _slang_push_var_table(A->vartable);
3094
3095 /* Generate IR tree for the function body code */
3096 n = _slang_gen_operation(A, fun->body);
3097 if (n)
3098 n = new_node1(IR_SCOPE, n);
3099
3100 /* pop vartable, restore previous */
3101 _slang_pop_var_table(A->vartable);
3102
3103 if (!n) {
3104 /* XXX record error */
3105 return GL_FALSE;
3106 }
3107
3108 /* append an end-of-function-label to IR tree */
3109 n = new_seq(n, new_label(A->curFuncEndLabel));
3110
3111 /*_slang_label_delete(A->curFuncEndLabel);*/
3112 A->curFuncEndLabel = NULL;
3113
3114 #if 0
3115 printf("************* New AST for %s *****\n", (char*)fun->header.a_name);
3116 slang_print_function(fun, 1);
3117 #endif
3118 #if 0
3119 printf("************* IR for %s *******\n", (char*)fun->header.a_name);
3120 _slang_print_ir_tree(n, 0);
3121 #endif
3122 #if 0
3123 printf("************* End codegen function ************\n\n");
3124 #endif
3125
3126 /* Emit program instructions */
3127 success = _slang_emit_code(n, A->vartable, A->program, GL_TRUE, A->log);
3128 _slang_free_ir_tree(n);
3129
3130 /* free codegen context */
3131 /*
3132 _mesa_free(A->codegen);
3133 */
3134
3135 return success;
3136 }
3137