mesa: fix a GLSL swizzled writemask bug
[mesa.git] / src / mesa / shader / slang / slang_codegen.c
1 /*
2 * Mesa 3-D graphics library
3 *
4 * Copyright (C) 2005-2007 Brian Paul All Rights Reserved.
5 * Copyright (C) 2008 VMware, Inc. 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_print.h"
47 #include "shader/prog_statevars.h"
48 #include "slang_typeinfo.h"
49 #include "slang_codegen.h"
50 #include "slang_compile.h"
51 #include "slang_label.h"
52 #include "slang_mem.h"
53 #include "slang_simplify.h"
54 #include "slang_emit.h"
55 #include "slang_vartable.h"
56 #include "slang_ir.h"
57 #include "slang_print.h"
58
59
60 static slang_ir_node *
61 _slang_gen_operation(slang_assemble_ctx * A, slang_operation *oper);
62
63
64 /**
65 * Retrieves type information about an operation.
66 * Returns GL_TRUE on success.
67 * Returns GL_FALSE otherwise.
68 */
69 static GLboolean
70 typeof_operation(const struct slang_assemble_ctx_ *A,
71 slang_operation *op,
72 slang_typeinfo *ti)
73 {
74 return _slang_typeof_operation(op, &A->space, ti, A->atoms, A->log);
75 }
76
77
78 static GLboolean
79 is_sampler_type(const slang_fully_specified_type *t)
80 {
81 switch (t->specifier.type) {
82 case SLANG_SPEC_SAMPLER1D:
83 case SLANG_SPEC_SAMPLER2D:
84 case SLANG_SPEC_SAMPLER3D:
85 case SLANG_SPEC_SAMPLERCUBE:
86 case SLANG_SPEC_SAMPLER1DSHADOW:
87 case SLANG_SPEC_SAMPLER2DSHADOW:
88 case SLANG_SPEC_SAMPLER2DRECT:
89 case SLANG_SPEC_SAMPLER2DRECTSHADOW:
90 return GL_TRUE;
91 default:
92 return GL_FALSE;
93 }
94 }
95
96
97 /**
98 * Return the offset (in floats or ints) of the named field within
99 * the given struct. Return -1 if field not found.
100 * If field is NULL, return the size of the struct instead.
101 */
102 static GLint
103 _slang_field_offset(const slang_type_specifier *spec, slang_atom field)
104 {
105 GLint offset = 0;
106 GLuint i;
107 for (i = 0; i < spec->_struct->fields->num_variables; i++) {
108 const slang_variable *v = spec->_struct->fields->variables[i];
109 const GLuint sz = _slang_sizeof_type_specifier(&v->type.specifier);
110 if (sz > 1) {
111 /* types larger than 1 float are register (4-float) aligned */
112 offset = (offset + 3) & ~3;
113 }
114 if (field && v->a_name == field) {
115 return offset;
116 }
117 offset += sz;
118 }
119 if (field)
120 return -1; /* field not found */
121 else
122 return offset; /* struct size */
123 }
124
125
126 /**
127 * Return the size (in floats) of the given type specifier.
128 * If the size is greater than 4, the size should be a multiple of 4
129 * so that the correct number of 4-float registers are allocated.
130 * For example, a mat3x2 is size 12 because we want to store the
131 * 3 columns in 3 float[4] registers.
132 */
133 GLuint
134 _slang_sizeof_type_specifier(const slang_type_specifier *spec)
135 {
136 GLuint sz;
137 switch (spec->type) {
138 case SLANG_SPEC_VOID:
139 sz = 0;
140 break;
141 case SLANG_SPEC_BOOL:
142 sz = 1;
143 break;
144 case SLANG_SPEC_BVEC2:
145 sz = 2;
146 break;
147 case SLANG_SPEC_BVEC3:
148 sz = 3;
149 break;
150 case SLANG_SPEC_BVEC4:
151 sz = 4;
152 break;
153 case SLANG_SPEC_INT:
154 sz = 1;
155 break;
156 case SLANG_SPEC_IVEC2:
157 sz = 2;
158 break;
159 case SLANG_SPEC_IVEC3:
160 sz = 3;
161 break;
162 case SLANG_SPEC_IVEC4:
163 sz = 4;
164 break;
165 case SLANG_SPEC_FLOAT:
166 sz = 1;
167 break;
168 case SLANG_SPEC_VEC2:
169 sz = 2;
170 break;
171 case SLANG_SPEC_VEC3:
172 sz = 3;
173 break;
174 case SLANG_SPEC_VEC4:
175 sz = 4;
176 break;
177 case SLANG_SPEC_MAT2:
178 sz = 2 * 4; /* 2 columns (regs) */
179 break;
180 case SLANG_SPEC_MAT3:
181 sz = 3 * 4;
182 break;
183 case SLANG_SPEC_MAT4:
184 sz = 4 * 4;
185 break;
186 case SLANG_SPEC_MAT23:
187 sz = 2 * 4; /* 2 columns (regs) */
188 break;
189 case SLANG_SPEC_MAT32:
190 sz = 3 * 4; /* 3 columns (regs) */
191 break;
192 case SLANG_SPEC_MAT24:
193 sz = 2 * 4;
194 break;
195 case SLANG_SPEC_MAT42:
196 sz = 4 * 4; /* 4 columns (regs) */
197 break;
198 case SLANG_SPEC_MAT34:
199 sz = 3 * 4;
200 break;
201 case SLANG_SPEC_MAT43:
202 sz = 4 * 4; /* 4 columns (regs) */
203 break;
204 case SLANG_SPEC_SAMPLER1D:
205 case SLANG_SPEC_SAMPLER2D:
206 case SLANG_SPEC_SAMPLER3D:
207 case SLANG_SPEC_SAMPLERCUBE:
208 case SLANG_SPEC_SAMPLER1DSHADOW:
209 case SLANG_SPEC_SAMPLER2DSHADOW:
210 case SLANG_SPEC_SAMPLER2DRECT:
211 case SLANG_SPEC_SAMPLER2DRECTSHADOW:
212 sz = 1; /* a sampler is basically just an integer index */
213 break;
214 case SLANG_SPEC_STRUCT:
215 sz = _slang_field_offset(spec, 0); /* special use */
216 if (sz > 4) {
217 sz = (sz + 3) & ~0x3; /* round up to multiple of four */
218 }
219 break;
220 case SLANG_SPEC_ARRAY:
221 sz = _slang_sizeof_type_specifier(spec->_array);
222 break;
223 default:
224 _mesa_problem(NULL, "Unexpected type in _slang_sizeof_type_specifier()");
225 sz = 0;
226 }
227
228 if (sz > 4) {
229 /* if size is > 4, it should be a multiple of four */
230 assert((sz & 0x3) == 0);
231 }
232 return sz;
233 }
234
235
236 /**
237 * Query variable/array length (number of elements).
238 * This is slightly non-trivial because there are two ways to express
239 * arrays: "float x[3]" vs. "float[3] x".
240 * \return the length of the array for the given variable, or 0 if not an array
241 */
242 static GLint
243 _slang_array_length(const slang_variable *var)
244 {
245 if (var->type.array_len > 0) {
246 /* Ex: float[4] x; */
247 return var->type.array_len;
248 }
249 if (var->array_len > 0) {
250 /* Ex: float x[4]; */
251 return var->array_len;
252 }
253 return 0;
254 }
255
256
257 /**
258 * Compute total size of array give size of element, number of elements.
259 * \return size in floats
260 */
261 static GLint
262 _slang_array_size(GLint elemSize, GLint arrayLen)
263 {
264 GLint total;
265 assert(elemSize > 0);
266 if (arrayLen > 1) {
267 /* round up base type to multiple of 4 */
268 total = ((elemSize + 3) & ~0x3) * MAX2(arrayLen, 1);
269 }
270 else {
271 total = elemSize;
272 }
273 return total;
274 }
275
276
277
278 /**
279 * Establish the binding between a slang_ir_node and a slang_variable.
280 * Then, allocate/attach a slang_ir_storage object to the IR node if needed.
281 * The IR node must be a IR_VAR or IR_VAR_DECL node.
282 * \param n the IR node
283 * \param var the variable to associate with the IR node
284 */
285 static void
286 _slang_attach_storage(slang_ir_node *n, slang_variable *var)
287 {
288 assert(n);
289 assert(var);
290 assert(n->Opcode == IR_VAR || n->Opcode == IR_VAR_DECL);
291 assert(!n->Var || n->Var == var);
292
293 n->Var = var;
294
295 if (!n->Store) {
296 /* need to setup storage */
297 if (n->Var && n->Var->store) {
298 /* node storage info = var storage info */
299 n->Store = n->Var->store;
300 }
301 else {
302 /* alloc new storage info */
303 n->Store = _slang_new_ir_storage(PROGRAM_UNDEFINED, -7, -5);
304 #if 0
305 printf("%s var=%s Store=%p Size=%d\n", __FUNCTION__,
306 (char*) var->a_name,
307 (void*) n->Store, n->Store->Size);
308 #endif
309 if (n->Var)
310 n->Var->store = n->Store;
311 assert(n->Var->store);
312 }
313 }
314 }
315
316
317 /**
318 * Return the TEXTURE_*_INDEX value that corresponds to a sampler type,
319 * or -1 if the type is not a sampler.
320 */
321 static GLint
322 sampler_to_texture_index(const slang_type_specifier_type type)
323 {
324 switch (type) {
325 case SLANG_SPEC_SAMPLER1D:
326 return TEXTURE_1D_INDEX;
327 case SLANG_SPEC_SAMPLER2D:
328 return TEXTURE_2D_INDEX;
329 case SLANG_SPEC_SAMPLER3D:
330 return TEXTURE_3D_INDEX;
331 case SLANG_SPEC_SAMPLERCUBE:
332 return TEXTURE_CUBE_INDEX;
333 case SLANG_SPEC_SAMPLER1DSHADOW:
334 return TEXTURE_1D_INDEX; /* XXX fix */
335 case SLANG_SPEC_SAMPLER2DSHADOW:
336 return TEXTURE_2D_INDEX; /* XXX fix */
337 case SLANG_SPEC_SAMPLER2DRECT:
338 return TEXTURE_RECT_INDEX;
339 case SLANG_SPEC_SAMPLER2DRECTSHADOW:
340 return TEXTURE_RECT_INDEX; /* XXX fix */
341 default:
342 return -1;
343 }
344 }
345
346
347 #define SWIZZLE_ZWWW MAKE_SWIZZLE4(SWIZZLE_Z, SWIZZLE_W, SWIZZLE_W, SWIZZLE_W)
348
349 /**
350 * Return the VERT_ATTRIB_* or FRAG_ATTRIB_* value that corresponds to
351 * a vertex or fragment program input variable. Return -1 if the input
352 * name is invalid.
353 * XXX return size too
354 */
355 static GLint
356 _slang_input_index(const char *name, GLenum target, GLuint *swizzleOut)
357 {
358 struct input_info {
359 const char *Name;
360 GLuint Attrib;
361 GLuint Swizzle;
362 };
363 static const struct input_info vertInputs[] = {
364 { "gl_Vertex", VERT_ATTRIB_POS, SWIZZLE_NOOP },
365 { "gl_Normal", VERT_ATTRIB_NORMAL, SWIZZLE_NOOP },
366 { "gl_Color", VERT_ATTRIB_COLOR0, SWIZZLE_NOOP },
367 { "gl_SecondaryColor", VERT_ATTRIB_COLOR1, SWIZZLE_NOOP },
368 { "gl_FogCoord", VERT_ATTRIB_FOG, SWIZZLE_XXXX },
369 { "gl_MultiTexCoord0", VERT_ATTRIB_TEX0, SWIZZLE_NOOP },
370 { "gl_MultiTexCoord1", VERT_ATTRIB_TEX1, SWIZZLE_NOOP },
371 { "gl_MultiTexCoord2", VERT_ATTRIB_TEX2, SWIZZLE_NOOP },
372 { "gl_MultiTexCoord3", VERT_ATTRIB_TEX3, SWIZZLE_NOOP },
373 { "gl_MultiTexCoord4", VERT_ATTRIB_TEX4, SWIZZLE_NOOP },
374 { "gl_MultiTexCoord5", VERT_ATTRIB_TEX5, SWIZZLE_NOOP },
375 { "gl_MultiTexCoord6", VERT_ATTRIB_TEX6, SWIZZLE_NOOP },
376 { "gl_MultiTexCoord7", VERT_ATTRIB_TEX7, SWIZZLE_NOOP },
377 { NULL, 0, SWIZZLE_NOOP }
378 };
379 static const struct input_info fragInputs[] = {
380 { "gl_FragCoord", FRAG_ATTRIB_WPOS, SWIZZLE_NOOP },
381 { "gl_Color", FRAG_ATTRIB_COL0, SWIZZLE_NOOP },
382 { "gl_SecondaryColor", FRAG_ATTRIB_COL1, SWIZZLE_NOOP },
383 { "gl_TexCoord", FRAG_ATTRIB_TEX0, SWIZZLE_NOOP },
384 /* note: we're packing several quantities into the fogcoord vector */
385 { "gl_FogFragCoord", FRAG_ATTRIB_FOGC, SWIZZLE_XXXX },
386 { "gl_FrontFacing", FRAG_ATTRIB_FOGC, SWIZZLE_YYYY }, /*XXX*/
387 { "gl_PointCoord", FRAG_ATTRIB_FOGC, SWIZZLE_ZWWW },
388 { NULL, 0, SWIZZLE_NOOP }
389 };
390 GLuint i;
391 const struct input_info *inputs
392 = (target == GL_VERTEX_PROGRAM_ARB) ? vertInputs : fragInputs;
393
394 ASSERT(MAX_TEXTURE_UNITS == 8); /* if this fails, fix vertInputs above */
395
396 for (i = 0; inputs[i].Name; i++) {
397 if (strcmp(inputs[i].Name, name) == 0) {
398 /* found */
399 *swizzleOut = inputs[i].Swizzle;
400 return inputs[i].Attrib;
401 }
402 }
403 return -1;
404 }
405
406
407 /**
408 * Return the VERT_RESULT_* or FRAG_RESULT_* value that corresponds to
409 * a vertex or fragment program output variable. Return -1 for an invalid
410 * output name.
411 */
412 static GLint
413 _slang_output_index(const char *name, GLenum target)
414 {
415 struct output_info {
416 const char *Name;
417 GLuint Attrib;
418 };
419 static const struct output_info vertOutputs[] = {
420 { "gl_Position", VERT_RESULT_HPOS },
421 { "gl_FrontColor", VERT_RESULT_COL0 },
422 { "gl_BackColor", VERT_RESULT_BFC0 },
423 { "gl_FrontSecondaryColor", VERT_RESULT_COL1 },
424 { "gl_BackSecondaryColor", VERT_RESULT_BFC1 },
425 { "gl_TexCoord", VERT_RESULT_TEX0 },
426 { "gl_FogFragCoord", VERT_RESULT_FOGC },
427 { "gl_PointSize", VERT_RESULT_PSIZ },
428 { NULL, 0 }
429 };
430 static const struct output_info fragOutputs[] = {
431 { "gl_FragColor", FRAG_RESULT_COLR },
432 { "gl_FragDepth", FRAG_RESULT_DEPR },
433 { "gl_FragData", FRAG_RESULT_DATA0 },
434 { NULL, 0 }
435 };
436 GLuint i;
437 const struct output_info *outputs
438 = (target == GL_VERTEX_PROGRAM_ARB) ? vertOutputs : fragOutputs;
439
440 for (i = 0; outputs[i].Name; i++) {
441 if (strcmp(outputs[i].Name, name) == 0) {
442 /* found */
443 return outputs[i].Attrib;
444 }
445 }
446 return -1;
447 }
448
449
450
451 /**********************************************************************/
452
453
454 /**
455 * Map "_asm foo" to IR_FOO, etc.
456 */
457 typedef struct
458 {
459 const char *Name;
460 slang_ir_opcode Opcode;
461 GLuint HaveRetValue, NumParams;
462 } slang_asm_info;
463
464
465 static slang_asm_info AsmInfo[] = {
466 /* vec4 binary op */
467 { "vec4_add", IR_ADD, 1, 2 },
468 { "vec4_subtract", IR_SUB, 1, 2 },
469 { "vec4_multiply", IR_MUL, 1, 2 },
470 { "vec4_dot", IR_DOT4, 1, 2 },
471 { "vec3_dot", IR_DOT3, 1, 2 },
472 { "vec3_cross", IR_CROSS, 1, 2 },
473 { "vec4_lrp", IR_LRP, 1, 3 },
474 { "vec4_min", IR_MIN, 1, 2 },
475 { "vec4_max", IR_MAX, 1, 2 },
476 { "vec4_clamp", IR_CLAMP, 1, 3 },
477 { "vec4_seq", IR_SEQUAL, 1, 2 },
478 { "vec4_sne", IR_SNEQUAL, 1, 2 },
479 { "vec4_sge", IR_SGE, 1, 2 },
480 { "vec4_sgt", IR_SGT, 1, 2 },
481 { "vec4_sle", IR_SLE, 1, 2 },
482 { "vec4_slt", IR_SLT, 1, 2 },
483 /* vec4 unary */
484 { "vec4_move", IR_MOVE, 1, 1 },
485 { "vec4_floor", IR_FLOOR, 1, 1 },
486 { "vec4_frac", IR_FRAC, 1, 1 },
487 { "vec4_abs", IR_ABS, 1, 1 },
488 { "vec4_negate", IR_NEG, 1, 1 },
489 { "vec4_ddx", IR_DDX, 1, 1 },
490 { "vec4_ddy", IR_DDY, 1, 1 },
491 /* float binary op */
492 { "float_power", IR_POW, 1, 2 },
493 /* texture / sampler */
494 { "vec4_tex1d", IR_TEX, 1, 2 },
495 { "vec4_texb1d", IR_TEXB, 1, 2 }, /* 1d w/ bias */
496 { "vec4_texp1d", IR_TEXP, 1, 2 }, /* 1d w/ projection */
497 { "vec4_tex2d", IR_TEX, 1, 2 },
498 { "vec4_texb2d", IR_TEXB, 1, 2 }, /* 2d w/ bias */
499 { "vec4_texp2d", IR_TEXP, 1, 2 }, /* 2d w/ projection */
500 { "vec4_tex3d", IR_TEX, 1, 2 },
501 { "vec4_texb3d", IR_TEXB, 1, 2 }, /* 3d w/ bias */
502 { "vec4_texp3d", IR_TEXP, 1, 2 }, /* 3d w/ projection */
503 { "vec4_texcube", IR_TEX, 1, 2 }, /* cubemap */
504 { "vec4_tex_rect", IR_TEX, 1, 2 }, /* rectangle */
505 { "vec4_texp_rect", IR_TEX, 1, 2 },/* rectangle w/ projection */
506
507 /* unary op */
508 { "ivec4_to_vec4", IR_I_TO_F, 1, 1 }, /* int[4] to float[4] */
509 { "vec4_to_ivec4", IR_F_TO_I, 1, 1 }, /* float[4] to int[4] */
510 { "float_exp", IR_EXP, 1, 1 },
511 { "float_exp2", IR_EXP2, 1, 1 },
512 { "float_log2", IR_LOG2, 1, 1 },
513 { "float_rsq", IR_RSQ, 1, 1 },
514 { "float_rcp", IR_RCP, 1, 1 },
515 { "float_sine", IR_SIN, 1, 1 },
516 { "float_cosine", IR_COS, 1, 1 },
517 { "float_noise1", IR_NOISE1, 1, 1},
518 { "float_noise2", IR_NOISE2, 1, 1},
519 { "float_noise3", IR_NOISE3, 1, 1},
520 { "float_noise4", IR_NOISE4, 1, 1},
521
522 { NULL, IR_NOP, 0, 0 }
523 };
524
525
526 static slang_ir_node *
527 new_node3(slang_ir_opcode op,
528 slang_ir_node *c0, slang_ir_node *c1, slang_ir_node *c2)
529 {
530 slang_ir_node *n = (slang_ir_node *) _slang_alloc(sizeof(slang_ir_node));
531 if (n) {
532 n->Opcode = op;
533 n->Children[0] = c0;
534 n->Children[1] = c1;
535 n->Children[2] = c2;
536 n->InstLocation = -1;
537 }
538 return n;
539 }
540
541 static slang_ir_node *
542 new_node2(slang_ir_opcode op, slang_ir_node *c0, slang_ir_node *c1)
543 {
544 return new_node3(op, c0, c1, NULL);
545 }
546
547 static slang_ir_node *
548 new_node1(slang_ir_opcode op, slang_ir_node *c0)
549 {
550 return new_node3(op, c0, NULL, NULL);
551 }
552
553 static slang_ir_node *
554 new_node0(slang_ir_opcode op)
555 {
556 return new_node3(op, NULL, NULL, NULL);
557 }
558
559
560 /**
561 * Create sequence of two nodes.
562 */
563 static slang_ir_node *
564 new_seq(slang_ir_node *left, slang_ir_node *right)
565 {
566 if (!left)
567 return right;
568 if (!right)
569 return left;
570 return new_node2(IR_SEQ, left, right);
571 }
572
573 static slang_ir_node *
574 new_label(slang_label *label)
575 {
576 slang_ir_node *n = new_node0(IR_LABEL);
577 assert(label);
578 if (n)
579 n->Label = label;
580 return n;
581 }
582
583 static slang_ir_node *
584 new_float_literal(const float v[4], GLuint size)
585 {
586 slang_ir_node *n = new_node0(IR_FLOAT);
587 assert(size <= 4);
588 COPY_4V(n->Value, v);
589 /* allocate a storage object, but compute actual location (Index) later */
590 n->Store = _slang_new_ir_storage(PROGRAM_CONSTANT, -1, size);
591 return n;
592 }
593
594
595 static slang_ir_node *
596 new_not(slang_ir_node *n)
597 {
598 return new_node1(IR_NOT, n);
599 }
600
601
602 /**
603 * Non-inlined function call.
604 */
605 static slang_ir_node *
606 new_function_call(slang_ir_node *code, slang_label *name)
607 {
608 slang_ir_node *n = new_node1(IR_CALL, code);
609 assert(name);
610 if (n)
611 n->Label = name;
612 return n;
613 }
614
615
616 /**
617 * Unconditional jump.
618 */
619 static slang_ir_node *
620 new_return(slang_label *dest)
621 {
622 slang_ir_node *n = new_node0(IR_RETURN);
623 assert(dest);
624 if (n)
625 n->Label = dest;
626 return n;
627 }
628
629
630 static slang_ir_node *
631 new_loop(slang_ir_node *body)
632 {
633 return new_node1(IR_LOOP, body);
634 }
635
636
637 static slang_ir_node *
638 new_break(slang_ir_node *loopNode)
639 {
640 slang_ir_node *n = new_node0(IR_BREAK);
641 assert(loopNode);
642 assert(loopNode->Opcode == IR_LOOP);
643 if (n) {
644 /* insert this node at head of linked list */
645 n->List = loopNode->List;
646 loopNode->List = n;
647 }
648 return n;
649 }
650
651
652 /**
653 * Make new IR_BREAK_IF_TRUE.
654 */
655 static slang_ir_node *
656 new_break_if_true(slang_ir_node *loopNode, slang_ir_node *cond)
657 {
658 slang_ir_node *n;
659 assert(loopNode);
660 assert(loopNode->Opcode == IR_LOOP);
661 n = new_node1(IR_BREAK_IF_TRUE, cond);
662 if (n) {
663 /* insert this node at head of linked list */
664 n->List = loopNode->List;
665 loopNode->List = n;
666 }
667 return n;
668 }
669
670
671 /**
672 * Make new IR_CONT_IF_TRUE node.
673 */
674 static slang_ir_node *
675 new_cont_if_true(slang_ir_node *loopNode, slang_ir_node *cond)
676 {
677 slang_ir_node *n;
678 assert(loopNode);
679 assert(loopNode->Opcode == IR_LOOP);
680 n = new_node1(IR_CONT_IF_TRUE, cond);
681 if (n) {
682 /* insert this node at head of linked list */
683 n->List = loopNode->List;
684 loopNode->List = n;
685 }
686 return n;
687 }
688
689
690 static slang_ir_node *
691 new_cond(slang_ir_node *n)
692 {
693 slang_ir_node *c = new_node1(IR_COND, n);
694 return c;
695 }
696
697
698 static slang_ir_node *
699 new_if(slang_ir_node *cond, slang_ir_node *ifPart, slang_ir_node *elsePart)
700 {
701 return new_node3(IR_IF, cond, ifPart, elsePart);
702 }
703
704
705 /**
706 * New IR_VAR node - a reference to a previously declared variable.
707 */
708 static slang_ir_node *
709 new_var(slang_assemble_ctx *A, slang_variable *var)
710 {
711 slang_ir_node *n = new_node0(IR_VAR);
712 if (n) {
713 _slang_attach_storage(n, var);
714 }
715 return n;
716 }
717
718
719 /**
720 * Check if the given function is really just a wrapper for a
721 * basic assembly instruction.
722 */
723 static GLboolean
724 slang_is_asm_function(const slang_function *fun)
725 {
726 if (fun->body->type == SLANG_OPER_BLOCK_NO_NEW_SCOPE &&
727 fun->body->num_children == 1 &&
728 fun->body->children[0].type == SLANG_OPER_ASM) {
729 return GL_TRUE;
730 }
731 return GL_FALSE;
732 }
733
734
735 static GLboolean
736 _slang_is_noop(const slang_operation *oper)
737 {
738 if (!oper ||
739 oper->type == SLANG_OPER_VOID ||
740 (oper->num_children == 1 && oper->children[0].type == SLANG_OPER_VOID))
741 return GL_TRUE;
742 else
743 return GL_FALSE;
744 }
745
746
747 /**
748 * Recursively search tree for a node of the given type.
749 */
750 static slang_operation *
751 _slang_find_node_type(slang_operation *oper, slang_operation_type type)
752 {
753 GLuint i;
754 if (oper->type == type)
755 return oper;
756 for (i = 0; i < oper->num_children; i++) {
757 slang_operation *p = _slang_find_node_type(&oper->children[i], type);
758 if (p)
759 return p;
760 }
761 return NULL;
762 }
763
764
765 /**
766 * Count the number of operations of the given time rooted at 'oper'.
767 */
768 static GLuint
769 _slang_count_node_type(slang_operation *oper, slang_operation_type type)
770 {
771 GLuint i, count = 0;
772 if (oper->type == type) {
773 return 1;
774 }
775 for (i = 0; i < oper->num_children; i++) {
776 count += _slang_count_node_type(&oper->children[i], type);
777 }
778 return count;
779 }
780
781
782 /**
783 * Check if the 'return' statement found under 'oper' is a "tail return"
784 * that can be no-op'd. For example:
785 *
786 * void func(void)
787 * {
788 * .. do something ..
789 * return; // this is a no-op
790 * }
791 *
792 * This is used when determining if a function can be inlined. If the
793 * 'return' is not the last statement, we can't inline the function since
794 * we still need the semantic behaviour of the 'return' but we don't want
795 * to accidentally return from the _calling_ function. We'd need to use an
796 * unconditional branch, but we don't have such a GPU instruction (not
797 * always, at least).
798 */
799 static GLboolean
800 _slang_is_tail_return(const slang_operation *oper)
801 {
802 GLuint k = oper->num_children;
803
804 while (k > 0) {
805 const slang_operation *last = &oper->children[k - 1];
806 if (last->type == SLANG_OPER_RETURN)
807 return GL_TRUE;
808 else if (last->type == SLANG_OPER_IDENTIFIER ||
809 last->type == SLANG_OPER_LABEL)
810 k--; /* try prev child */
811 else if (last->type == SLANG_OPER_BLOCK_NO_NEW_SCOPE ||
812 last->type == SLANG_OPER_BLOCK_NEW_SCOPE)
813 /* try sub-children */
814 return _slang_is_tail_return(last);
815 else
816 break;
817 }
818
819 return GL_FALSE;
820 }
821
822
823 static void
824 slang_resolve_variable(slang_operation *oper)
825 {
826 if (oper->type == SLANG_OPER_IDENTIFIER && !oper->var) {
827 oper->var = _slang_variable_locate(oper->locals, oper->a_id, GL_TRUE);
828 }
829 }
830
831
832 /**
833 * Replace particular variables (SLANG_OPER_IDENTIFIER) with new expressions.
834 */
835 static void
836 slang_substitute(slang_assemble_ctx *A, slang_operation *oper,
837 GLuint substCount, slang_variable **substOld,
838 slang_operation **substNew, GLboolean isLHS)
839 {
840 switch (oper->type) {
841 case SLANG_OPER_VARIABLE_DECL:
842 {
843 slang_variable *v = _slang_variable_locate(oper->locals,
844 oper->a_id, GL_TRUE);
845 assert(v);
846 if (v->initializer && oper->num_children == 0) {
847 /* set child of oper to copy of initializer */
848 oper->num_children = 1;
849 oper->children = slang_operation_new(1);
850 slang_operation_copy(&oper->children[0], v->initializer);
851 }
852 if (oper->num_children == 1) {
853 /* the initializer */
854 slang_substitute(A, &oper->children[0], substCount,
855 substOld, substNew, GL_FALSE);
856 }
857 }
858 break;
859 case SLANG_OPER_IDENTIFIER:
860 assert(oper->num_children == 0);
861 if (1/**!isLHS XXX FIX */) {
862 slang_atom id = oper->a_id;
863 slang_variable *v;
864 GLuint i;
865 v = _slang_variable_locate(oper->locals, id, GL_TRUE);
866 if (!v) {
867 _mesa_problem(NULL, "var %s not found!\n", (char *) oper->a_id);
868 return;
869 }
870
871 /* look for a substitution */
872 for (i = 0; i < substCount; i++) {
873 if (v == substOld[i]) {
874 /* OK, replace this SLANG_OPER_IDENTIFIER with a new expr */
875 #if 0 /* DEBUG only */
876 if (substNew[i]->type == SLANG_OPER_IDENTIFIER) {
877 assert(substNew[i]->var);
878 assert(substNew[i]->var->a_name);
879 printf("Substitute %s with %s in id node %p\n",
880 (char*)v->a_name, (char*) substNew[i]->var->a_name,
881 (void*) oper);
882 }
883 else {
884 printf("Substitute %s with %f in id node %p\n",
885 (char*)v->a_name, substNew[i]->literal[0],
886 (void*) oper);
887 }
888 #endif
889 slang_operation_copy(oper, substNew[i]);
890 break;
891 }
892 }
893 }
894 break;
895
896 case SLANG_OPER_RETURN:
897 /* do return replacement here too */
898 assert(oper->num_children == 0 || oper->num_children == 1);
899 if (oper->num_children == 1 && !_slang_is_noop(&oper->children[0])) {
900 /* replace:
901 * return expr;
902 * with:
903 * __retVal = expr;
904 * return;
905 * then do substitutions on the assignment.
906 */
907 slang_operation *blockOper, *assignOper, *returnOper;
908
909 /* check if function actually has a return type */
910 assert(A->CurFunction);
911 if (A->CurFunction->header.type.specifier.type == SLANG_SPEC_VOID) {
912 slang_info_log_error(A->log, "illegal return expression");
913 return;
914 }
915
916 blockOper = slang_operation_new(1);
917 blockOper->type = SLANG_OPER_BLOCK_NO_NEW_SCOPE;
918 blockOper->num_children = 2;
919 blockOper->locals->outer_scope = oper->locals->outer_scope;
920 blockOper->children = slang_operation_new(2);
921 assignOper = blockOper->children + 0;
922 returnOper = blockOper->children + 1;
923
924 assignOper->type = SLANG_OPER_ASSIGN;
925 assignOper->num_children = 2;
926 assignOper->locals->outer_scope = blockOper->locals;
927 assignOper->children = slang_operation_new(2);
928 assignOper->children[0].type = SLANG_OPER_IDENTIFIER;
929 assignOper->children[0].a_id = slang_atom_pool_atom(A->atoms, "__retVal");
930 assignOper->children[0].locals->outer_scope = assignOper->locals;
931
932 slang_operation_copy(&assignOper->children[1],
933 &oper->children[0]);
934
935 returnOper->type = SLANG_OPER_RETURN; /* return w/ no value */
936 assert(returnOper->num_children == 0);
937
938 /* do substitutions on the "__retVal = expr" sub-tree */
939 slang_substitute(A, assignOper,
940 substCount, substOld, substNew, GL_FALSE);
941
942 /* install new code */
943 slang_operation_copy(oper, blockOper);
944 slang_operation_destruct(blockOper);
945 }
946 else {
947 /* check if return value was expected */
948 assert(A->CurFunction);
949 if (A->CurFunction->header.type.specifier.type != SLANG_SPEC_VOID) {
950 slang_info_log_error(A->log, "return statement requires an expression");
951 return;
952 }
953 }
954 break;
955
956 case SLANG_OPER_ASSIGN:
957 case SLANG_OPER_SUBSCRIPT:
958 /* special case:
959 * child[0] can't have substitutions but child[1] can.
960 */
961 slang_substitute(A, &oper->children[0],
962 substCount, substOld, substNew, GL_TRUE);
963 slang_substitute(A, &oper->children[1],
964 substCount, substOld, substNew, GL_FALSE);
965 break;
966 case SLANG_OPER_FIELD:
967 /* XXX NEW - test */
968 slang_substitute(A, &oper->children[0],
969 substCount, substOld, substNew, GL_TRUE);
970 break;
971 default:
972 {
973 GLuint i;
974 for (i = 0; i < oper->num_children; i++)
975 slang_substitute(A, &oper->children[i],
976 substCount, substOld, substNew, GL_FALSE);
977 }
978 }
979 }
980
981
982 /**
983 * Produce inline code for a call to an assembly instruction.
984 * This is typically used to compile a call to a built-in function like this:
985 *
986 * vec4 mix(const vec4 x, const vec4 y, const vec4 a)
987 * {
988 * __asm vec4_lrp __retVal, a, y, x;
989 * }
990 *
991 *
992 * A call to
993 * r = mix(p1, p2, p3);
994 *
995 * Becomes:
996 *
997 * mov
998 * / \
999 * r vec4_lrp
1000 * / | \
1001 * p3 p2 p1
1002 *
1003 * We basically translate a SLANG_OPER_CALL into a SLANG_OPER_ASM.
1004 */
1005 static slang_operation *
1006 slang_inline_asm_function(slang_assemble_ctx *A,
1007 slang_function *fun, slang_operation *oper)
1008 {
1009 const GLuint numArgs = oper->num_children;
1010 GLuint i;
1011 slang_operation *inlined;
1012 const GLboolean haveRetValue = _slang_function_has_return_value(fun);
1013 slang_variable **substOld;
1014 slang_operation **substNew;
1015
1016 ASSERT(slang_is_asm_function(fun));
1017 ASSERT(fun->param_count == numArgs + haveRetValue);
1018
1019 /*
1020 printf("Inline %s as %s\n",
1021 (char*) fun->header.a_name,
1022 (char*) fun->body->children[0].a_id);
1023 */
1024
1025 /*
1026 * We'll substitute formal params with actual args in the asm call.
1027 */
1028 substOld = (slang_variable **)
1029 _slang_alloc(numArgs * sizeof(slang_variable *));
1030 substNew = (slang_operation **)
1031 _slang_alloc(numArgs * sizeof(slang_operation *));
1032 for (i = 0; i < numArgs; i++) {
1033 substOld[i] = fun->parameters->variables[i];
1034 substNew[i] = oper->children + i;
1035 }
1036
1037 /* make a copy of the code to inline */
1038 inlined = slang_operation_new(1);
1039 slang_operation_copy(inlined, &fun->body->children[0]);
1040 if (haveRetValue) {
1041 /* get rid of the __retVal child */
1042 inlined->num_children--;
1043 for (i = 0; i < inlined->num_children; i++) {
1044 inlined->children[i] = inlined->children[i + 1];
1045 }
1046 }
1047
1048 /* now do formal->actual substitutions */
1049 slang_substitute(A, inlined, numArgs, substOld, substNew, GL_FALSE);
1050
1051 _slang_free(substOld);
1052 _slang_free(substNew);
1053
1054 #if 0
1055 printf("+++++++++++++ inlined asm function %s +++++++++++++\n",
1056 (char *) fun->header.a_name);
1057 slang_print_tree(inlined, 3);
1058 printf("+++++++++++++++++++++++++++++++++++++++++++++++++++\n");
1059 #endif
1060
1061 return inlined;
1062 }
1063
1064
1065 /**
1066 * Inline the given function call operation.
1067 * Return a new slang_operation that corresponds to the inlined code.
1068 */
1069 static slang_operation *
1070 slang_inline_function_call(slang_assemble_ctx * A, slang_function *fun,
1071 slang_operation *oper, slang_operation *returnOper)
1072 {
1073 typedef enum {
1074 SUBST = 1,
1075 COPY_IN,
1076 COPY_OUT
1077 } ParamMode;
1078 ParamMode *paramMode;
1079 const GLboolean haveRetValue = _slang_function_has_return_value(fun);
1080 const GLuint numArgs = oper->num_children;
1081 const GLuint totalArgs = numArgs + haveRetValue;
1082 slang_operation *args = oper->children;
1083 slang_operation *inlined, *top;
1084 slang_variable **substOld;
1085 slang_operation **substNew;
1086 GLuint substCount, numCopyIn, i;
1087 slang_function *prevFunction;
1088 slang_variable_scope *newScope = NULL;
1089
1090 /* save / push */
1091 prevFunction = A->CurFunction;
1092 A->CurFunction = fun;
1093
1094 /*assert(oper->type == SLANG_OPER_CALL); (or (matrix) multiply, etc) */
1095 assert(fun->param_count == totalArgs);
1096
1097 /* allocate temporary arrays */
1098 paramMode = (ParamMode *)
1099 _slang_alloc(totalArgs * sizeof(ParamMode));
1100 substOld = (slang_variable **)
1101 _slang_alloc(totalArgs * sizeof(slang_variable *));
1102 substNew = (slang_operation **)
1103 _slang_alloc(totalArgs * sizeof(slang_operation *));
1104
1105 #if 0
1106 printf("\nInline call to %s (total vars=%d nparams=%d)\n",
1107 (char *) fun->header.a_name,
1108 fun->parameters->num_variables, numArgs);
1109 #endif
1110
1111 if (haveRetValue && !returnOper) {
1112 /* Create 3-child comma sequence for inlined code:
1113 * child[0]: declare __resultTmp
1114 * child[1]: inlined function body
1115 * child[2]: __resultTmp
1116 */
1117 slang_operation *commaSeq;
1118 slang_operation *declOper = NULL;
1119 slang_variable *resultVar;
1120
1121 commaSeq = slang_operation_new(1);
1122 commaSeq->type = SLANG_OPER_SEQUENCE;
1123 assert(commaSeq->locals);
1124 commaSeq->locals->outer_scope = oper->locals->outer_scope;
1125 commaSeq->num_children = 3;
1126 commaSeq->children = slang_operation_new(3);
1127 /* allocate the return var */
1128 resultVar = slang_variable_scope_grow(commaSeq->locals);
1129 /*
1130 printf("Alloc __resultTmp in scope %p for retval of calling %s\n",
1131 (void*)commaSeq->locals, (char *) fun->header.a_name);
1132 */
1133
1134 resultVar->a_name = slang_atom_pool_atom(A->atoms, "__resultTmp");
1135 resultVar->type = fun->header.type; /* XXX copy? */
1136 resultVar->isTemp = GL_TRUE;
1137
1138 /* child[0] = __resultTmp declaration */
1139 declOper = &commaSeq->children[0];
1140 declOper->type = SLANG_OPER_VARIABLE_DECL;
1141 declOper->a_id = resultVar->a_name;
1142 declOper->locals->outer_scope = commaSeq->locals;
1143
1144 /* child[1] = function body */
1145 inlined = &commaSeq->children[1];
1146 inlined->locals->outer_scope = commaSeq->locals;
1147
1148 /* child[2] = __resultTmp reference */
1149 returnOper = &commaSeq->children[2];
1150 returnOper->type = SLANG_OPER_IDENTIFIER;
1151 returnOper->a_id = resultVar->a_name;
1152 returnOper->locals->outer_scope = commaSeq->locals;
1153
1154 top = commaSeq;
1155 }
1156 else {
1157 top = inlined = slang_operation_new(1);
1158 /* XXXX this may be inappropriate!!!! */
1159 inlined->locals->outer_scope = oper->locals->outer_scope;
1160 }
1161
1162
1163 assert(inlined->locals);
1164
1165 /* Examine the parameters, look for inout/out params, look for possible
1166 * substitutions, etc:
1167 * param type behaviour
1168 * in copy actual to local
1169 * const in substitute param with actual
1170 * out copy out
1171 */
1172 substCount = 0;
1173 for (i = 0; i < totalArgs; i++) {
1174 slang_variable *p = fun->parameters->variables[i];
1175 /*
1176 printf("Param %d: %s %s \n", i,
1177 slang_type_qual_string(p->type.qualifier),
1178 (char *) p->a_name);
1179 */
1180 if (p->type.qualifier == SLANG_QUAL_INOUT ||
1181 p->type.qualifier == SLANG_QUAL_OUT) {
1182 /* an output param */
1183 slang_operation *arg;
1184 if (i < numArgs)
1185 arg = &args[i];
1186 else
1187 arg = returnOper;
1188 paramMode[i] = SUBST;
1189
1190 if (arg->type == SLANG_OPER_IDENTIFIER)
1191 slang_resolve_variable(arg);
1192
1193 /* replace parameter 'p' with argument 'arg' */
1194 substOld[substCount] = p;
1195 substNew[substCount] = arg; /* will get copied */
1196 substCount++;
1197 }
1198 else if (p->type.qualifier == SLANG_QUAL_CONST) {
1199 /* a constant input param */
1200 if (args[i].type == SLANG_OPER_IDENTIFIER ||
1201 args[i].type == SLANG_OPER_LITERAL_FLOAT) {
1202 /* replace all occurances of this parameter variable with the
1203 * actual argument variable or a literal.
1204 */
1205 paramMode[i] = SUBST;
1206 slang_resolve_variable(&args[i]);
1207 substOld[substCount] = p;
1208 substNew[substCount] = &args[i]; /* will get copied */
1209 substCount++;
1210 }
1211 else {
1212 paramMode[i] = COPY_IN;
1213 }
1214 }
1215 else {
1216 paramMode[i] = COPY_IN;
1217 }
1218 assert(paramMode[i]);
1219 }
1220
1221 /* actual code inlining: */
1222 slang_operation_copy(inlined, fun->body);
1223
1224 /*** XXX review this */
1225 assert(inlined->type == SLANG_OPER_BLOCK_NO_NEW_SCOPE ||
1226 inlined->type == SLANG_OPER_BLOCK_NEW_SCOPE);
1227 inlined->type = SLANG_OPER_BLOCK_NEW_SCOPE;
1228
1229 #if 0
1230 printf("======================= orig body code ======================\n");
1231 printf("=== params scope = %p\n", (void*) fun->parameters);
1232 slang_print_tree(fun->body, 8);
1233 printf("======================= copied code =========================\n");
1234 slang_print_tree(inlined, 8);
1235 #endif
1236
1237 /* do parameter substitution in inlined code: */
1238 slang_substitute(A, inlined, substCount, substOld, substNew, GL_FALSE);
1239
1240 #if 0
1241 printf("======================= subst code ==========================\n");
1242 slang_print_tree(inlined, 8);
1243 printf("=============================================================\n");
1244 #endif
1245
1246 /* New prolog statements: (inserted before the inlined code)
1247 * Copy the 'in' arguments.
1248 */
1249 numCopyIn = 0;
1250 for (i = 0; i < numArgs; i++) {
1251 if (paramMode[i] == COPY_IN) {
1252 slang_variable *p = fun->parameters->variables[i];
1253 /* declare parameter 'p' */
1254 slang_operation *decl = slang_operation_insert(&inlined->num_children,
1255 &inlined->children,
1256 numCopyIn);
1257
1258 decl->type = SLANG_OPER_VARIABLE_DECL;
1259 assert(decl->locals);
1260 decl->locals->outer_scope = inlined->locals;
1261 decl->a_id = p->a_name;
1262 decl->num_children = 1;
1263 decl->children = slang_operation_new(1);
1264
1265 /* child[0] is the var's initializer */
1266 slang_operation_copy(&decl->children[0], args + i);
1267
1268 /* add parameter 'p' to the local variable scope here */
1269 {
1270 slang_variable *pCopy = slang_variable_scope_grow(inlined->locals);
1271 pCopy->type = p->type;
1272 pCopy->a_name = p->a_name;
1273 pCopy->array_len = p->array_len;
1274 }
1275
1276 newScope = inlined->locals;
1277 numCopyIn++;
1278 }
1279 }
1280
1281 /* Now add copies of the function's local vars to the new variable scope */
1282 for (i = totalArgs; i < fun->parameters->num_variables; i++) {
1283 slang_variable *p = fun->parameters->variables[i];
1284 slang_variable *pCopy = slang_variable_scope_grow(inlined->locals);
1285 pCopy->type = p->type;
1286 pCopy->a_name = p->a_name;
1287 pCopy->array_len = p->array_len;
1288 }
1289
1290
1291 /* New epilog statements:
1292 * 1. Create end of function label to jump to from return statements.
1293 * 2. Copy the 'out' parameter vars
1294 */
1295 {
1296 slang_operation *lab = slang_operation_insert(&inlined->num_children,
1297 &inlined->children,
1298 inlined->num_children);
1299 lab->type = SLANG_OPER_LABEL;
1300 lab->label = A->curFuncEndLabel;
1301 }
1302
1303 for (i = 0; i < totalArgs; i++) {
1304 if (paramMode[i] == COPY_OUT) {
1305 const slang_variable *p = fun->parameters->variables[i];
1306 /* actualCallVar = outParam */
1307 /*if (i > 0 || !haveRetValue)*/
1308 slang_operation *ass = slang_operation_insert(&inlined->num_children,
1309 &inlined->children,
1310 inlined->num_children);
1311 ass->type = SLANG_OPER_ASSIGN;
1312 ass->num_children = 2;
1313 ass->locals->outer_scope = inlined->locals;
1314 ass->children = slang_operation_new(2);
1315 ass->children[0] = args[i]; /*XXX copy */
1316 ass->children[1].type = SLANG_OPER_IDENTIFIER;
1317 ass->children[1].a_id = p->a_name;
1318 ass->children[1].locals->outer_scope = ass->locals;
1319 }
1320 }
1321
1322 _slang_free(paramMode);
1323 _slang_free(substOld);
1324 _slang_free(substNew);
1325
1326 /* Update scoping to use the new local vars instead of the
1327 * original function's vars. This is especially important
1328 * for nested inlining.
1329 */
1330 if (newScope)
1331 slang_replace_scope(inlined, fun->parameters, newScope);
1332
1333 #if 0
1334 printf("Done Inline call to %s (total vars=%d nparams=%d)\n\n",
1335 (char *) fun->header.a_name,
1336 fun->parameters->num_variables, numArgs);
1337 slang_print_tree(top, 0);
1338 #endif
1339
1340 /* pop */
1341 A->CurFunction = prevFunction;
1342
1343 return top;
1344 }
1345
1346
1347 static slang_ir_node *
1348 _slang_gen_function_call(slang_assemble_ctx *A, slang_function *fun,
1349 slang_operation *oper, slang_operation *dest)
1350 {
1351 slang_ir_node *n;
1352 slang_operation *inlined;
1353 slang_label *prevFuncEndLabel;
1354 char name[200];
1355
1356 prevFuncEndLabel = A->curFuncEndLabel;
1357 sprintf(name, "__endOfFunc_%s_", (char *) fun->header.a_name);
1358 A->curFuncEndLabel = _slang_label_new(name);
1359 assert(A->curFuncEndLabel);
1360
1361 if (slang_is_asm_function(fun) && !dest) {
1362 /* assemble assembly function - tree style */
1363 inlined = slang_inline_asm_function(A, fun, oper);
1364 }
1365 else {
1366 /* non-assembly function */
1367 /* We always generate an "inline-able" block of code here.
1368 * We may either:
1369 * 1. insert the inline code
1370 * 2. Generate a call to the "inline" code as a subroutine
1371 */
1372
1373
1374 slang_operation *ret = NULL;
1375
1376 inlined = slang_inline_function_call(A, fun, oper, dest);
1377 if (!inlined)
1378 return NULL;
1379
1380 ret = _slang_find_node_type(inlined, SLANG_OPER_RETURN);
1381 if (ret) {
1382 /* check if this is a "tail" return */
1383 if (_slang_count_node_type(inlined, SLANG_OPER_RETURN) == 1 &&
1384 _slang_is_tail_return(inlined)) {
1385 /* The only RETURN is the last stmt in the function, no-op it
1386 * and inline the function body.
1387 */
1388 ret->type = SLANG_OPER_NONE;
1389 }
1390 else {
1391 slang_operation *callOper;
1392 /* The function we're calling has one or more 'return' statements.
1393 * So, we can't truly inline this function because we need to
1394 * implement 'return' with RET (and CAL).
1395 * Nevertheless, we performed "inlining" to make a new instance
1396 * of the function body to deal with static register allocation.
1397 *
1398 * XXX check if there's one 'return' and if it's the very last
1399 * statement in the function - we can optimize that case.
1400 */
1401 assert(inlined->type == SLANG_OPER_BLOCK_NEW_SCOPE ||
1402 inlined->type == SLANG_OPER_SEQUENCE);
1403
1404 if (_slang_function_has_return_value(fun) && !dest) {
1405 assert(inlined->children[0].type == SLANG_OPER_VARIABLE_DECL);
1406 assert(inlined->children[2].type == SLANG_OPER_IDENTIFIER);
1407 callOper = &inlined->children[1];
1408 }
1409 else {
1410 callOper = inlined;
1411 }
1412 callOper->type = SLANG_OPER_NON_INLINED_CALL;
1413 callOper->fun = fun;
1414 callOper->label = _slang_label_new_unique((char*) fun->header.a_name);
1415 }
1416 }
1417 }
1418
1419 if (!inlined)
1420 return NULL;
1421
1422 /* Replace the function call with the inlined block (or new CALL stmt) */
1423 slang_operation_destruct(oper);
1424 *oper = *inlined;
1425 _slang_free(inlined);
1426
1427 #if 0
1428 assert(inlined->locals);
1429 printf("*** Inlined code for call to %s:\n",
1430 (char*) fun->header.a_name);
1431 slang_print_tree(oper, 10);
1432 printf("\n");
1433 #endif
1434
1435 n = _slang_gen_operation(A, oper);
1436
1437 /*_slang_label_delete(A->curFuncEndLabel);*/
1438 A->curFuncEndLabel = prevFuncEndLabel;
1439
1440 return n;
1441 }
1442
1443
1444 static slang_asm_info *
1445 slang_find_asm_info(const char *name)
1446 {
1447 GLuint i;
1448 for (i = 0; AsmInfo[i].Name; i++) {
1449 if (_mesa_strcmp(AsmInfo[i].Name, name) == 0) {
1450 return AsmInfo + i;
1451 }
1452 }
1453 return NULL;
1454 }
1455
1456
1457 /**
1458 * Some write-masked assignments are simple, but others are hard.
1459 * Simple example:
1460 * vec3 v;
1461 * v.xy = vec2(a, b);
1462 * Hard example:
1463 * vec3 v;
1464 * v.zy = vec2(a, b);
1465 * this gets transformed/swizzled into:
1466 * v.zy = vec2(a, b).*yx* (* = don't care)
1467 * This function helps to determine simple vs. non-simple.
1468 */
1469 static GLboolean
1470 _slang_simple_writemask(GLuint writemask, GLuint swizzle)
1471 {
1472 switch (writemask) {
1473 case WRITEMASK_X:
1474 return GET_SWZ(swizzle, 0) == SWIZZLE_X;
1475 case WRITEMASK_Y:
1476 return GET_SWZ(swizzle, 1) == SWIZZLE_Y;
1477 case WRITEMASK_Z:
1478 return GET_SWZ(swizzle, 2) == SWIZZLE_Z;
1479 case WRITEMASK_W:
1480 return GET_SWZ(swizzle, 3) == SWIZZLE_W;
1481 case WRITEMASK_XY:
1482 return (GET_SWZ(swizzle, 0) == SWIZZLE_X)
1483 && (GET_SWZ(swizzle, 1) == SWIZZLE_Y);
1484 case WRITEMASK_XYZ:
1485 return (GET_SWZ(swizzle, 0) == SWIZZLE_X)
1486 && (GET_SWZ(swizzle, 1) == SWIZZLE_Y)
1487 && (GET_SWZ(swizzle, 2) == SWIZZLE_Z);
1488 case WRITEMASK_XYZW:
1489 return swizzle == SWIZZLE_NOOP;
1490 default:
1491 return GL_FALSE;
1492 }
1493 }
1494
1495
1496 /**
1497 * Convert the given swizzle into a writemask. In some cases this
1498 * is trivial, in other cases, we'll need to also swizzle the right
1499 * hand side to put components in the right places.
1500 * See comment above for more info.
1501 * XXX this function could be simplified and should probably be renamed.
1502 * \param swizzle the incoming swizzle
1503 * \param writemaskOut returns the writemask
1504 * \param swizzleOut swizzle to apply to the right-hand-side
1505 * \return GL_FALSE for simple writemasks, GL_TRUE for non-simple
1506 */
1507 static GLboolean
1508 swizzle_to_writemask(slang_assemble_ctx *A, GLuint swizzle,
1509 GLuint *writemaskOut, GLuint *swizzleOut)
1510 {
1511 GLuint mask = 0x0, newSwizzle[4];
1512 GLint i, size;
1513
1514 /* make new dst writemask, compute size */
1515 for (i = 0; i < 4; i++) {
1516 const GLuint swz = GET_SWZ(swizzle, i);
1517 if (swz == SWIZZLE_NIL) {
1518 /* end */
1519 break;
1520 }
1521 assert(swz >= 0 && swz <= 3);
1522
1523 if (swizzle != SWIZZLE_XXXX &&
1524 swizzle != SWIZZLE_YYYY &&
1525 swizzle != SWIZZLE_ZZZZ &&
1526 swizzle != SWIZZLE_WWWW &&
1527 (mask & (1 << swz))) {
1528 /* a channel can't be specified twice (ex: ".xyyz") */
1529 slang_info_log_error(A->log, "Invalid writemask '%s'",
1530 _mesa_swizzle_string(swizzle, 0, 0));
1531 return GL_FALSE;
1532 }
1533
1534 mask |= (1 << swz);
1535 }
1536 assert(mask <= 0xf);
1537 size = i; /* number of components in mask/swizzle */
1538
1539 *writemaskOut = mask;
1540
1541 /* make new src swizzle, by inversion */
1542 for (i = 0; i < 4; i++) {
1543 newSwizzle[i] = i; /*identity*/
1544 }
1545 for (i = 0; i < size; i++) {
1546 const GLuint swz = GET_SWZ(swizzle, i);
1547 newSwizzle[swz] = i;
1548 }
1549 *swizzleOut = MAKE_SWIZZLE4(newSwizzle[0],
1550 newSwizzle[1],
1551 newSwizzle[2],
1552 newSwizzle[3]);
1553
1554 if (_slang_simple_writemask(mask, *swizzleOut)) {
1555 if (size >= 1)
1556 assert(GET_SWZ(*swizzleOut, 0) == SWIZZLE_X);
1557 if (size >= 2)
1558 assert(GET_SWZ(*swizzleOut, 1) == SWIZZLE_Y);
1559 if (size >= 3)
1560 assert(GET_SWZ(*swizzleOut, 2) == SWIZZLE_Z);
1561 if (size >= 4)
1562 assert(GET_SWZ(*swizzleOut, 3) == SWIZZLE_W);
1563 return GL_TRUE;
1564 }
1565 else
1566 return GL_FALSE;
1567 }
1568
1569
1570 /**
1571 * Recursively traverse 'oper' to produce a swizzle mask in the event
1572 * of any vector subscripts and swizzle suffixes.
1573 * Ex: for "vec4 v", "v[2].x" resolves to v.z
1574 */
1575 static GLuint
1576 resolve_swizzle(const slang_operation *oper)
1577 {
1578 if (oper->type == SLANG_OPER_FIELD) {
1579 /* writemask from .xyzw suffix */
1580 slang_swizzle swz;
1581 if (_slang_is_swizzle((char*) oper->a_id, 4, &swz)) {
1582 GLuint swizzle = MAKE_SWIZZLE4(swz.swizzle[0],
1583 swz.swizzle[1],
1584 swz.swizzle[2],
1585 swz.swizzle[3]);
1586 GLuint child_swizzle = resolve_swizzle(&oper->children[0]);
1587 GLuint s = _slang_swizzle_swizzle(child_swizzle, swizzle);
1588 return s;
1589 }
1590 else
1591 return SWIZZLE_XYZW;
1592 }
1593 else if (oper->type == SLANG_OPER_SUBSCRIPT &&
1594 oper->children[1].type == SLANG_OPER_LITERAL_INT) {
1595 /* writemask from [index] */
1596 GLuint child_swizzle = resolve_swizzle(&oper->children[0]);
1597 GLuint i = (GLuint) oper->children[1].literal[0];
1598 GLuint swizzle;
1599 GLuint s;
1600 switch (i) {
1601 case 0:
1602 swizzle = SWIZZLE_XXXX;
1603 break;
1604 case 1:
1605 swizzle = SWIZZLE_YYYY;
1606 break;
1607 case 2:
1608 swizzle = SWIZZLE_ZZZZ;
1609 break;
1610 case 3:
1611 swizzle = SWIZZLE_WWWW;
1612 break;
1613 default:
1614 swizzle = SWIZZLE_XYZW;
1615 }
1616 s = _slang_swizzle_swizzle(child_swizzle, swizzle);
1617 return s;
1618 }
1619 else {
1620 return SWIZZLE_XYZW;
1621 }
1622 }
1623
1624
1625 /**
1626 * Recursively descend through swizzle nodes to find the node's storage info.
1627 */
1628 static slang_ir_storage *
1629 get_store(const slang_ir_node *n)
1630 {
1631 if (n->Opcode == IR_SWIZZLE) {
1632 return get_store(n->Children[0]);
1633 }
1634 return n->Store;
1635 }
1636
1637
1638
1639 /**
1640 * Generate IR tree for an asm instruction/operation such as:
1641 * __asm vec4_dot __retVal.x, v1, v2;
1642 */
1643 static slang_ir_node *
1644 _slang_gen_asm(slang_assemble_ctx *A, slang_operation *oper,
1645 slang_operation *dest)
1646 {
1647 const slang_asm_info *info;
1648 slang_ir_node *kids[3], *n;
1649 GLuint j, firstOperand;
1650
1651 assert(oper->type == SLANG_OPER_ASM);
1652
1653 info = slang_find_asm_info((char *) oper->a_id);
1654 if (!info) {
1655 _mesa_problem(NULL, "undefined __asm function %s\n",
1656 (char *) oper->a_id);
1657 assert(info);
1658 }
1659 assert(info->NumParams <= 3);
1660
1661 if (info->NumParams == oper->num_children) {
1662 /* Storage for result is not specified.
1663 * Children[0], [1], [2] are the operands.
1664 */
1665 firstOperand = 0;
1666 }
1667 else {
1668 /* Storage for result (child[0]) is specified.
1669 * Children[1], [2], [3] are the operands.
1670 */
1671 firstOperand = 1;
1672 }
1673
1674 /* assemble child(ren) */
1675 kids[0] = kids[1] = kids[2] = NULL;
1676 for (j = 0; j < info->NumParams; j++) {
1677 kids[j] = _slang_gen_operation(A, &oper->children[firstOperand + j]);
1678 if (!kids[j])
1679 return NULL;
1680 }
1681
1682 n = new_node3(info->Opcode, kids[0], kids[1], kids[2]);
1683
1684 if (firstOperand) {
1685 /* Setup n->Store to be a particular location. Otherwise, storage
1686 * for the result (a temporary) will be allocated later.
1687 */
1688 slang_operation *dest_oper;
1689 slang_ir_node *n0;
1690
1691 dest_oper = &oper->children[0];
1692
1693 n0 = _slang_gen_operation(A, dest_oper);
1694 if (!n0)
1695 return NULL;
1696
1697 assert(!n->Store);
1698 n->Store = n0->Store;
1699
1700 assert(n->Store->File != PROGRAM_UNDEFINED || n->Store->Parent);
1701
1702 _slang_free(n0);
1703 }
1704
1705 return n;
1706 }
1707
1708
1709 static void
1710 print_funcs(struct slang_function_scope_ *scope, const char *name)
1711 {
1712 GLuint i;
1713 for (i = 0; i < scope->num_functions; i++) {
1714 slang_function *f = &scope->functions[i];
1715 if (!name || strcmp(name, (char*) f->header.a_name) == 0)
1716 printf(" %s (%d args)\n", name, f->param_count);
1717
1718 }
1719 if (scope->outer_scope)
1720 print_funcs(scope->outer_scope, name);
1721 }
1722
1723
1724 /**
1725 * Find a function of the given name, taking 'numArgs' arguments.
1726 * This is the function we'll try to call when there is no exact match
1727 * between function parameters and call arguments.
1728 *
1729 * XXX we should really create a list of candidate functions and try
1730 * all of them...
1731 */
1732 static slang_function *
1733 _slang_find_function_by_argc(slang_function_scope *scope,
1734 const char *name, int numArgs)
1735 {
1736 while (scope) {
1737 GLuint i;
1738 for (i = 0; i < scope->num_functions; i++) {
1739 slang_function *f = &scope->functions[i];
1740 if (strcmp(name, (char*) f->header.a_name) == 0) {
1741 int haveRetValue = _slang_function_has_return_value(f);
1742 if (numArgs == f->param_count - haveRetValue)
1743 return f;
1744 }
1745 }
1746 scope = scope->outer_scope;
1747 }
1748
1749 return NULL;
1750 }
1751
1752
1753 static slang_function *
1754 _slang_find_function_by_max_argc(slang_function_scope *scope,
1755 const char *name)
1756 {
1757 slang_function *maxFunc = NULL;
1758 GLuint maxArgs = 0;
1759
1760 while (scope) {
1761 GLuint i;
1762 for (i = 0; i < scope->num_functions; i++) {
1763 slang_function *f = &scope->functions[i];
1764 if (strcmp(name, (char*) f->header.a_name) == 0) {
1765 if (f->param_count > maxArgs) {
1766 maxArgs = f->param_count;
1767 maxFunc = f;
1768 }
1769 }
1770 }
1771 scope = scope->outer_scope;
1772 }
1773
1774 return maxFunc;
1775 }
1776
1777
1778 /**
1779 * Generate a new slang_function which is a constructor for a user-defined
1780 * struct type.
1781 */
1782 static slang_function *
1783 _slang_make_struct_constructor(slang_assemble_ctx *A, slang_struct *str)
1784 {
1785 const GLint numFields = str->fields->num_variables;
1786 slang_function *fun = slang_function_new(SLANG_FUNC_CONSTRUCTOR);
1787
1788 /* function header (name, return type) */
1789 fun->header.a_name = str->a_name;
1790 fun->header.type.qualifier = SLANG_QUAL_NONE;
1791 fun->header.type.specifier.type = SLANG_SPEC_STRUCT;
1792 fun->header.type.specifier._struct = str;
1793
1794 /* function parameters (= struct's fields) */
1795 {
1796 GLint i;
1797 for (i = 0; i < numFields; i++) {
1798 /*
1799 printf("Field %d: %s\n", i, (char*) str->fields->variables[i]->a_name);
1800 */
1801 slang_variable *p = slang_variable_scope_grow(fun->parameters);
1802 *p = *str->fields->variables[i]; /* copy the variable and type */
1803 p->type.qualifier = SLANG_QUAL_CONST;
1804 }
1805 fun->param_count = fun->parameters->num_variables;
1806 }
1807
1808 /* Add __retVal to params */
1809 {
1810 slang_variable *p = slang_variable_scope_grow(fun->parameters);
1811 slang_atom a_retVal = slang_atom_pool_atom(A->atoms, "__retVal");
1812 assert(a_retVal);
1813 p->a_name = a_retVal;
1814 p->type = fun->header.type;
1815 p->type.qualifier = SLANG_QUAL_OUT;
1816 fun->param_count++;
1817 }
1818
1819 /* function body is:
1820 * block:
1821 * declare T;
1822 * T.f1 = p1;
1823 * T.f2 = p2;
1824 * ...
1825 * T.fn = pn;
1826 * return T;
1827 */
1828 {
1829 slang_variable_scope *scope;
1830 slang_variable *var;
1831 GLint i;
1832
1833 fun->body = slang_operation_new(1);
1834 fun->body->type = SLANG_OPER_BLOCK_NEW_SCOPE;
1835 fun->body->num_children = numFields + 2;
1836 fun->body->children = slang_operation_new(numFields + 2);
1837
1838 scope = fun->body->locals;
1839 scope->outer_scope = fun->parameters;
1840
1841 /* create local var 't' */
1842 var = slang_variable_scope_grow(scope);
1843 var->a_name = slang_atom_pool_atom(A->atoms, "t");
1844 var->type = fun->header.type;
1845
1846 /* declare t */
1847 {
1848 slang_operation *decl;
1849
1850 decl = &fun->body->children[0];
1851 decl->type = SLANG_OPER_VARIABLE_DECL;
1852 decl->locals = _slang_variable_scope_new(scope);
1853 decl->a_id = var->a_name;
1854 }
1855
1856 /* assign params to fields of t */
1857 for (i = 0; i < numFields; i++) {
1858 slang_operation *assign = &fun->body->children[1 + i];
1859
1860 assign->type = SLANG_OPER_ASSIGN;
1861 assign->locals = _slang_variable_scope_new(scope);
1862 assign->num_children = 2;
1863 assign->children = slang_operation_new(2);
1864
1865 {
1866 slang_operation *lhs = &assign->children[0];
1867
1868 lhs->type = SLANG_OPER_FIELD;
1869 lhs->locals = _slang_variable_scope_new(scope);
1870 lhs->num_children = 1;
1871 lhs->children = slang_operation_new(1);
1872 lhs->a_id = str->fields->variables[i]->a_name;
1873
1874 lhs->children[0].type = SLANG_OPER_IDENTIFIER;
1875 lhs->children[0].a_id = var->a_name;
1876 lhs->children[0].locals = _slang_variable_scope_new(scope);
1877
1878 #if 0
1879 lhs->children[1].num_children = 1;
1880 lhs->children[1].children = slang_operation_new(1);
1881 lhs->children[1].children[0].type = SLANG_OPER_IDENTIFIER;
1882 lhs->children[1].children[0].a_id = str->fields->variables[i]->a_name;
1883 lhs->children[1].children->locals = _slang_variable_scope_new(scope);
1884 #endif
1885 }
1886
1887 {
1888 slang_operation *rhs = &assign->children[1];
1889
1890 rhs->type = SLANG_OPER_IDENTIFIER;
1891 rhs->locals = _slang_variable_scope_new(scope);
1892 rhs->a_id = str->fields->variables[i]->a_name;
1893 }
1894 }
1895
1896 /* return t; */
1897 {
1898 slang_operation *ret = &fun->body->children[numFields + 1];
1899
1900 ret->type = SLANG_OPER_RETURN;
1901 ret->locals = _slang_variable_scope_new(scope);
1902 ret->num_children = 1;
1903 ret->children = slang_operation_new(1);
1904 ret->children[0].type = SLANG_OPER_IDENTIFIER;
1905 ret->children[0].a_id = var->a_name;
1906 ret->children[0].locals = _slang_variable_scope_new(scope);
1907 }
1908 }
1909 /*
1910 slang_print_function(fun, 1);
1911 */
1912 return fun;
1913 }
1914
1915
1916 /**
1917 * Find/create a function (constructor) for the given structure name.
1918 */
1919 static slang_function *
1920 _slang_locate_struct_constructor(slang_assemble_ctx *A, const char *name)
1921 {
1922 unsigned int i;
1923 for (i = 0; i < A->space.structs->num_structs; i++) {
1924 slang_struct *str = &A->space.structs->structs[i];
1925 if (strcmp(name, (const char *) str->a_name) == 0) {
1926 /* found a structure type that matches the function name */
1927 if (!str->constructor) {
1928 /* create the constructor function now */
1929 str->constructor = _slang_make_struct_constructor(A, str);
1930 }
1931 return str->constructor;
1932 }
1933 }
1934 return NULL;
1935 }
1936
1937
1938 /**
1939 * Generate a new slang_function to satisfy a call to an array constructor.
1940 * Ex: float[3](1., 2., 3.)
1941 */
1942 static slang_function *
1943 _slang_make_array_constructor(slang_assemble_ctx *A, slang_operation *oper)
1944 {
1945 slang_type_specifier_type baseType;
1946 slang_function *fun;
1947 int num_elements;
1948
1949 fun = slang_function_new(SLANG_FUNC_CONSTRUCTOR);
1950 if (!fun)
1951 return NULL;
1952
1953 baseType = slang_type_specifier_type_from_string((char *) oper->a_id);
1954
1955 num_elements = oper->num_children;
1956
1957 /* function header, return type */
1958 {
1959 fun->header.a_name = oper->a_id;
1960 fun->header.type.qualifier = SLANG_QUAL_NONE;
1961 fun->header.type.specifier.type = SLANG_SPEC_ARRAY;
1962 fun->header.type.specifier._array =
1963 slang_type_specifier_new(baseType, NULL, NULL);
1964 fun->header.type.array_len = num_elements;
1965 }
1966
1967 /* function parameters (= number of elements) */
1968 {
1969 GLint i;
1970 for (i = 0; i < num_elements; i++) {
1971 /*
1972 printf("Field %d: %s\n", i, (char*) str->fields->variables[i]->a_name);
1973 */
1974 slang_variable *p = slang_variable_scope_grow(fun->parameters);
1975 char name[10];
1976 snprintf(name, sizeof(name), "p%d", i);
1977 p->a_name = slang_atom_pool_atom(A->atoms, name);
1978 p->type.qualifier = SLANG_QUAL_CONST;
1979 p->type.specifier.type = baseType;
1980 }
1981 fun->param_count = fun->parameters->num_variables;
1982 }
1983
1984 /* Add __retVal to params */
1985 {
1986 slang_variable *p = slang_variable_scope_grow(fun->parameters);
1987 slang_atom a_retVal = slang_atom_pool_atom(A->atoms, "__retVal");
1988 assert(a_retVal);
1989 p->a_name = a_retVal;
1990 p->type = fun->header.type;
1991 p->type.qualifier = SLANG_QUAL_OUT;
1992 p->type.specifier.type = baseType;
1993 fun->param_count++;
1994 }
1995
1996 /* function body is:
1997 * block:
1998 * declare T;
1999 * T[0] = p0;
2000 * T[1] = p1;
2001 * ...
2002 * T[n] = pn;
2003 * return T;
2004 */
2005 {
2006 slang_variable_scope *scope;
2007 slang_variable *var;
2008 GLint i;
2009
2010 fun->body = slang_operation_new(1);
2011 fun->body->type = SLANG_OPER_BLOCK_NEW_SCOPE;
2012 fun->body->num_children = num_elements + 2;
2013 fun->body->children = slang_operation_new(num_elements + 2);
2014
2015 scope = fun->body->locals;
2016 scope->outer_scope = fun->parameters;
2017
2018 /* create local var 't' */
2019 var = slang_variable_scope_grow(scope);
2020 var->a_name = slang_atom_pool_atom(A->atoms, "ttt");
2021 var->type = fun->header.type;/*XXX copy*/
2022
2023 /* declare t */
2024 {
2025 slang_operation *decl;
2026
2027 decl = &fun->body->children[0];
2028 decl->type = SLANG_OPER_VARIABLE_DECL;
2029 decl->locals = _slang_variable_scope_new(scope);
2030 decl->a_id = var->a_name;
2031 }
2032
2033 /* assign params to elements of t */
2034 for (i = 0; i < num_elements; i++) {
2035 slang_operation *assign = &fun->body->children[1 + i];
2036
2037 assign->type = SLANG_OPER_ASSIGN;
2038 assign->locals = _slang_variable_scope_new(scope);
2039 assign->num_children = 2;
2040 assign->children = slang_operation_new(2);
2041
2042 {
2043 slang_operation *lhs = &assign->children[0];
2044
2045 lhs->type = SLANG_OPER_SUBSCRIPT;
2046 lhs->locals = _slang_variable_scope_new(scope);
2047 lhs->num_children = 2;
2048 lhs->children = slang_operation_new(2);
2049
2050 lhs->children[0].type = SLANG_OPER_IDENTIFIER;
2051 lhs->children[0].a_id = var->a_name;
2052 lhs->children[0].locals = _slang_variable_scope_new(scope);
2053
2054 lhs->children[1].type = SLANG_OPER_LITERAL_INT;
2055 lhs->children[1].literal[0] = (GLfloat) i;
2056 }
2057
2058 {
2059 slang_operation *rhs = &assign->children[1];
2060
2061 rhs->type = SLANG_OPER_IDENTIFIER;
2062 rhs->locals = _slang_variable_scope_new(scope);
2063 rhs->a_id = fun->parameters->variables[i]->a_name;
2064 }
2065 }
2066
2067 /* return t; */
2068 {
2069 slang_operation *ret = &fun->body->children[num_elements + 1];
2070
2071 ret->type = SLANG_OPER_RETURN;
2072 ret->locals = _slang_variable_scope_new(scope);
2073 ret->num_children = 1;
2074 ret->children = slang_operation_new(1);
2075 ret->children[0].type = SLANG_OPER_IDENTIFIER;
2076 ret->children[0].a_id = var->a_name;
2077 ret->children[0].locals = _slang_variable_scope_new(scope);
2078 }
2079 }
2080
2081 /*
2082 slang_print_function(fun, 1);
2083 */
2084
2085 return fun;
2086 }
2087
2088
2089 static GLboolean
2090 _slang_is_vec_mat_type(const char *name)
2091 {
2092 static const char *vecmat_types[] = {
2093 "float", "int", "bool",
2094 "vec2", "vec3", "vec4",
2095 "ivec2", "ivec3", "ivec4",
2096 "bvec2", "bvec3", "bvec4",
2097 "mat2", "mat3", "mat4",
2098 "mat2x3", "mat2x4", "mat3x2", "mat3x4", "mat4x2", "mat4x3",
2099 NULL
2100 };
2101 int i;
2102 for (i = 0; vecmat_types[i]; i++)
2103 if (_mesa_strcmp(name, vecmat_types[i]) == 0)
2104 return GL_TRUE;
2105 return GL_FALSE;
2106 }
2107
2108
2109 /**
2110 * Assemble a function call, given a particular function name.
2111 * \param name the function's name (operators like '*' are possible).
2112 */
2113 static slang_ir_node *
2114 _slang_gen_function_call_name(slang_assemble_ctx *A, const char *name,
2115 slang_operation *oper, slang_operation *dest)
2116 {
2117 slang_operation *params = oper->children;
2118 const GLuint param_count = oper->num_children;
2119 slang_atom atom;
2120 slang_function *fun;
2121 slang_ir_node *n;
2122
2123 atom = slang_atom_pool_atom(A->atoms, name);
2124 if (atom == SLANG_ATOM_NULL)
2125 return NULL;
2126
2127 if (oper->array_constructor) {
2128 /* this needs special handling */
2129 fun = _slang_make_array_constructor(A, oper);
2130 }
2131 else {
2132 /* Try to find function by name and exact argument type matching */
2133 GLboolean error = GL_FALSE;
2134 fun = _slang_function_locate(A->space.funcs, atom, params, param_count,
2135 &A->space, A->atoms, A->log, &error);
2136 if (error) {
2137 slang_info_log_error(A->log,
2138 "Function '%s' not found (check argument types)",
2139 name);
2140 return NULL;
2141 }
2142 }
2143
2144 if (!fun) {
2145 /* Next, try locating a constructor function for a user-defined type */
2146 fun = _slang_locate_struct_constructor(A, name);
2147 }
2148
2149 /*
2150 * At this point, some heuristics are used to try to find a function
2151 * that matches the calling signature by means of casting or "unrolling"
2152 * of constructors.
2153 */
2154
2155 if (!fun && _slang_is_vec_mat_type(name)) {
2156 /* Next, if this call looks like a vec() or mat() constructor call,
2157 * try "unwinding" the args to satisfy a constructor.
2158 */
2159 fun = _slang_find_function_by_max_argc(A->space.funcs, name);
2160 if (fun) {
2161 if (!_slang_adapt_call(oper, fun, &A->space, A->atoms, A->log)) {
2162 slang_info_log_error(A->log,
2163 "Function '%s' not found (check argument types)",
2164 name);
2165 return NULL;
2166 }
2167 }
2168 }
2169
2170 if (!fun && _slang_is_vec_mat_type(name)) {
2171 /* Next, try casting args to the types of the formal parameters */
2172 int numArgs = oper->num_children;
2173 fun = _slang_find_function_by_argc(A->space.funcs, name, numArgs);
2174 if (!fun || !_slang_cast_func_params(oper, fun, &A->space, A->atoms, A->log)) {
2175 slang_info_log_error(A->log,
2176 "Function '%s' not found (check argument types)",
2177 name);
2178 return NULL;
2179 }
2180 assert(fun);
2181 }
2182
2183 if (!fun) {
2184 slang_info_log_error(A->log,
2185 "Function '%s' not found (check argument types)",
2186 name);
2187 return NULL;
2188 }
2189 if (!fun->body) {
2190 slang_info_log_error(A->log,
2191 "Function '%s' prototyped but not defined. "
2192 "Separate compilation units not supported.",
2193 name);
2194 return NULL;
2195 }
2196
2197 /* type checking to be sure function's return type matches 'dest' type */
2198 if (dest) {
2199 slang_typeinfo t0;
2200
2201 slang_typeinfo_construct(&t0);
2202 typeof_operation(A, dest, &t0);
2203
2204 if (!slang_type_specifier_equal(&t0.spec, &fun->header.type.specifier)) {
2205 slang_info_log_error(A->log,
2206 "Incompatible type returned by call to '%s'",
2207 name);
2208 return NULL;
2209 }
2210 }
2211
2212 n = _slang_gen_function_call(A, fun, oper, dest);
2213
2214 if (n && !n->Store && !dest
2215 && fun->header.type.specifier.type != SLANG_SPEC_VOID) {
2216 /* setup n->Store for the result of the function call */
2217 GLint size = _slang_sizeof_type_specifier(&fun->header.type.specifier);
2218 n->Store = _slang_new_ir_storage(PROGRAM_TEMPORARY, -1, size);
2219 /*printf("Alloc storage for function result, size %d \n", size);*/
2220 }
2221
2222 if (oper->array_constructor) {
2223 /* free the temporary array constructor function now */
2224 slang_function_destruct(fun);
2225 }
2226
2227 return n;
2228 }
2229
2230
2231 static slang_ir_node *
2232 _slang_gen_method_call(slang_assemble_ctx *A, slang_operation *oper)
2233 {
2234 slang_atom *a_length = slang_atom_pool_atom(A->atoms, "length");
2235 slang_ir_node *n;
2236 slang_variable *var;
2237
2238 /* NOTE: In GLSL 1.20, there's only one kind of method
2239 * call: array.length(). Anything else is an error.
2240 */
2241 if (oper->a_id != a_length) {
2242 slang_info_log_error(A->log,
2243 "Undefined method call '%s'", (char *) oper->a_id);
2244 return NULL;
2245 }
2246
2247 /* length() takes no arguments */
2248 if (oper->num_children > 0) {
2249 slang_info_log_error(A->log, "Invalid arguments to length() method");
2250 return NULL;
2251 }
2252
2253 /* lookup the object/variable */
2254 var = _slang_variable_locate(oper->locals, oper->a_obj, GL_TRUE);
2255 if (!var || var->type.specifier.type != SLANG_SPEC_ARRAY) {
2256 slang_info_log_error(A->log,
2257 "Undefined object '%s'", (char *) oper->a_obj);
2258 return NULL;
2259 }
2260
2261 /* Create a float/literal IR node encoding the array length */
2262 n = new_node0(IR_FLOAT);
2263 if (n) {
2264 n->Value[0] = (float) _slang_array_length(var);
2265 n->Store = _slang_new_ir_storage(PROGRAM_CONSTANT, -1, 1);
2266 }
2267 return n;
2268 }
2269
2270
2271 static GLboolean
2272 _slang_is_constant_cond(const slang_operation *oper, GLboolean *value)
2273 {
2274 if (oper->type == SLANG_OPER_LITERAL_FLOAT ||
2275 oper->type == SLANG_OPER_LITERAL_INT ||
2276 oper->type == SLANG_OPER_LITERAL_BOOL) {
2277 if (oper->literal[0])
2278 *value = GL_TRUE;
2279 else
2280 *value = GL_FALSE;
2281 return GL_TRUE;
2282 }
2283 else if (oper->type == SLANG_OPER_EXPRESSION &&
2284 oper->num_children == 1) {
2285 return _slang_is_constant_cond(&oper->children[0], value);
2286 }
2287 return GL_FALSE;
2288 }
2289
2290
2291 /**
2292 * Test if an operation is a scalar or boolean.
2293 */
2294 static GLboolean
2295 _slang_is_scalar_or_boolean(slang_assemble_ctx *A, slang_operation *oper)
2296 {
2297 slang_typeinfo type;
2298 GLint size;
2299
2300 slang_typeinfo_construct(&type);
2301 typeof_operation(A, oper, &type);
2302 size = _slang_sizeof_type_specifier(&type.spec);
2303 slang_typeinfo_destruct(&type);
2304 return size == 1;
2305 }
2306
2307
2308 /**
2309 * Test if an operation is boolean.
2310 */
2311 static GLboolean
2312 _slang_is_boolean(slang_assemble_ctx *A, slang_operation *oper)
2313 {
2314 slang_typeinfo type;
2315 GLboolean isBool;
2316
2317 slang_typeinfo_construct(&type);
2318 typeof_operation(A, oper, &type);
2319 isBool = (type.spec.type == SLANG_SPEC_BOOL);
2320 slang_typeinfo_destruct(&type);
2321 return isBool;
2322 }
2323
2324
2325 /**
2326 * Generate loop code using high-level IR_LOOP instruction
2327 */
2328 static slang_ir_node *
2329 _slang_gen_while(slang_assemble_ctx * A, const slang_operation *oper)
2330 {
2331 /*
2332 * LOOP:
2333 * BREAK if !expr (child[0])
2334 * body code (child[1])
2335 */
2336 slang_ir_node *prevLoop, *loop, *breakIf, *body;
2337 GLboolean isConst, constTrue;
2338
2339 /* type-check expression */
2340 if (!_slang_is_boolean(A, &oper->children[0])) {
2341 slang_info_log_error(A->log, "scalar/boolean expression expected for 'while'");
2342 return NULL;
2343 }
2344
2345 /* Check if loop condition is a constant */
2346 isConst = _slang_is_constant_cond(&oper->children[0], &constTrue);
2347
2348 if (isConst && !constTrue) {
2349 /* loop is never executed! */
2350 return new_node0(IR_NOP);
2351 }
2352
2353 loop = new_loop(NULL);
2354
2355 /* save old, push new loop */
2356 prevLoop = A->CurLoop;
2357 A->CurLoop = loop;
2358
2359 if (isConst && constTrue) {
2360 /* while(nonzero constant), no conditional break */
2361 breakIf = NULL;
2362 }
2363 else {
2364 slang_ir_node *cond
2365 = new_cond(new_not(_slang_gen_operation(A, &oper->children[0])));
2366 breakIf = new_break_if_true(A->CurLoop, cond);
2367 }
2368 body = _slang_gen_operation(A, &oper->children[1]);
2369 loop->Children[0] = new_seq(breakIf, body);
2370
2371 /* Do infinite loop detection */
2372 /* loop->List is head of linked list of break/continue nodes */
2373 if (!loop->List && isConst && constTrue) {
2374 /* infinite loop detected */
2375 A->CurLoop = prevLoop; /* clean-up */
2376 slang_info_log_error(A->log, "Infinite loop detected!");
2377 return NULL;
2378 }
2379
2380 /* pop loop, restore prev */
2381 A->CurLoop = prevLoop;
2382
2383 return loop;
2384 }
2385
2386
2387 /**
2388 * Generate IR tree for a do-while loop using high-level LOOP, IF instructions.
2389 */
2390 static slang_ir_node *
2391 _slang_gen_do(slang_assemble_ctx * A, const slang_operation *oper)
2392 {
2393 /*
2394 * LOOP:
2395 * body code (child[0])
2396 * tail code:
2397 * BREAK if !expr (child[1])
2398 */
2399 slang_ir_node *prevLoop, *loop;
2400 GLboolean isConst, constTrue;
2401
2402 /* type-check expression */
2403 if (!_slang_is_boolean(A, &oper->children[1])) {
2404 slang_info_log_error(A->log, "scalar/boolean expression expected for 'do/while'");
2405 return NULL;
2406 }
2407
2408 loop = new_loop(NULL);
2409
2410 /* save old, push new loop */
2411 prevLoop = A->CurLoop;
2412 A->CurLoop = loop;
2413
2414 /* loop body: */
2415 loop->Children[0] = _slang_gen_operation(A, &oper->children[0]);
2416
2417 /* Check if loop condition is a constant */
2418 isConst = _slang_is_constant_cond(&oper->children[1], &constTrue);
2419 if (isConst && constTrue) {
2420 /* do { } while(1) ==> no conditional break */
2421 loop->Children[1] = NULL; /* no tail code */
2422 }
2423 else {
2424 slang_ir_node *cond
2425 = new_cond(new_not(_slang_gen_operation(A, &oper->children[1])));
2426 loop->Children[1] = new_break_if_true(A->CurLoop, cond);
2427 }
2428
2429 /* XXX we should do infinite loop detection, as above */
2430
2431 /* pop loop, restore prev */
2432 A->CurLoop = prevLoop;
2433
2434 return loop;
2435 }
2436
2437
2438 /**
2439 * Generate for-loop using high-level IR_LOOP instruction.
2440 */
2441 static slang_ir_node *
2442 _slang_gen_for(slang_assemble_ctx * A, const slang_operation *oper)
2443 {
2444 /*
2445 * init code (child[0])
2446 * LOOP:
2447 * BREAK if !expr (child[1])
2448 * body code (child[3])
2449 * tail code:
2450 * incr code (child[2]) // XXX continue here
2451 */
2452 slang_ir_node *prevLoop, *loop, *cond, *breakIf, *body, *init, *incr;
2453
2454 init = _slang_gen_operation(A, &oper->children[0]);
2455 loop = new_loop(NULL);
2456
2457 /* save old, push new loop */
2458 prevLoop = A->CurLoop;
2459 A->CurLoop = loop;
2460
2461 cond = new_cond(new_not(_slang_gen_operation(A, &oper->children[1])));
2462 breakIf = new_break_if_true(A->CurLoop, cond);
2463 body = _slang_gen_operation(A, &oper->children[3]);
2464 incr = _slang_gen_operation(A, &oper->children[2]);
2465
2466 loop->Children[0] = new_seq(breakIf, body);
2467 loop->Children[1] = incr; /* tail code */
2468
2469 /* pop loop, restore prev */
2470 A->CurLoop = prevLoop;
2471
2472 return new_seq(init, loop);
2473 }
2474
2475
2476 static slang_ir_node *
2477 _slang_gen_continue(slang_assemble_ctx * A, const slang_operation *oper)
2478 {
2479 slang_ir_node *n, *loopNode;
2480 assert(oper->type == SLANG_OPER_CONTINUE);
2481 loopNode = A->CurLoop;
2482 assert(loopNode);
2483 assert(loopNode->Opcode == IR_LOOP);
2484 n = new_node0(IR_CONT);
2485 if (n) {
2486 n->Parent = loopNode;
2487 /* insert this node at head of linked list */
2488 n->List = loopNode->List;
2489 loopNode->List = n;
2490 }
2491 return n;
2492 }
2493
2494
2495 /**
2496 * Determine if the given operation is of a specific type.
2497 */
2498 static GLboolean
2499 is_operation_type(const slang_operation *oper, slang_operation_type type)
2500 {
2501 if (oper->type == type)
2502 return GL_TRUE;
2503 else if ((oper->type == SLANG_OPER_BLOCK_NEW_SCOPE ||
2504 oper->type == SLANG_OPER_BLOCK_NO_NEW_SCOPE) &&
2505 oper->num_children == 1)
2506 return is_operation_type(&oper->children[0], type);
2507 else
2508 return GL_FALSE;
2509 }
2510
2511
2512 /**
2513 * Generate IR tree for an if/then/else conditional using high-level
2514 * IR_IF instruction.
2515 */
2516 static slang_ir_node *
2517 _slang_gen_if(slang_assemble_ctx * A, const slang_operation *oper)
2518 {
2519 /*
2520 * eval expr (child[0])
2521 * IF expr THEN
2522 * if-body code
2523 * ELSE
2524 * else-body code
2525 * ENDIF
2526 */
2527 const GLboolean haveElseClause = !_slang_is_noop(&oper->children[2]);
2528 slang_ir_node *ifNode, *cond, *ifBody, *elseBody;
2529 GLboolean isConst, constTrue;
2530
2531 /* type-check expression */
2532 if (!_slang_is_boolean(A, &oper->children[0])) {
2533 slang_info_log_error(A->log, "boolean expression expected for 'if'");
2534 return NULL;
2535 }
2536
2537 if (!_slang_is_scalar_or_boolean(A, &oper->children[0])) {
2538 slang_info_log_error(A->log, "scalar/boolean expression expected for 'if'");
2539 return NULL;
2540 }
2541
2542 isConst = _slang_is_constant_cond(&oper->children[0], &constTrue);
2543 if (isConst) {
2544 if (constTrue) {
2545 /* if (true) ... */
2546 return _slang_gen_operation(A, &oper->children[1]);
2547 }
2548 else {
2549 /* if (false) ... */
2550 return _slang_gen_operation(A, &oper->children[2]);
2551 }
2552 }
2553
2554 cond = _slang_gen_operation(A, &oper->children[0]);
2555 cond = new_cond(cond);
2556
2557 if (is_operation_type(&oper->children[1], SLANG_OPER_BREAK)
2558 && !haveElseClause) {
2559 /* Special case: generate a conditional break */
2560 ifBody = new_break_if_true(A->CurLoop, cond);
2561 return ifBody;
2562 }
2563 else if (is_operation_type(&oper->children[1], SLANG_OPER_CONTINUE)
2564 && !haveElseClause) {
2565 /* Special case: generate a conditional break */
2566 ifBody = new_cont_if_true(A->CurLoop, cond);
2567 return ifBody;
2568 }
2569 else {
2570 /* general case */
2571 ifBody = _slang_gen_operation(A, &oper->children[1]);
2572 if (haveElseClause)
2573 elseBody = _slang_gen_operation(A, &oper->children[2]);
2574 else
2575 elseBody = NULL;
2576 ifNode = new_if(cond, ifBody, elseBody);
2577 return ifNode;
2578 }
2579 }
2580
2581
2582
2583 static slang_ir_node *
2584 _slang_gen_not(slang_assemble_ctx * A, const slang_operation *oper)
2585 {
2586 slang_ir_node *n;
2587
2588 assert(oper->type == SLANG_OPER_NOT);
2589
2590 /* type-check expression */
2591 if (!_slang_is_scalar_or_boolean(A, &oper->children[0])) {
2592 slang_info_log_error(A->log,
2593 "scalar/boolean expression expected for '!'");
2594 return NULL;
2595 }
2596
2597 n = _slang_gen_operation(A, &oper->children[0]);
2598 if (n)
2599 return new_not(n);
2600 else
2601 return NULL;
2602 }
2603
2604
2605 static slang_ir_node *
2606 _slang_gen_xor(slang_assemble_ctx * A, const slang_operation *oper)
2607 {
2608 slang_ir_node *n1, *n2;
2609
2610 assert(oper->type == SLANG_OPER_LOGICALXOR);
2611
2612 if (!_slang_is_scalar_or_boolean(A, &oper->children[0]) ||
2613 !_slang_is_scalar_or_boolean(A, &oper->children[0])) {
2614 slang_info_log_error(A->log,
2615 "scalar/boolean expressions expected for '^^'");
2616 return NULL;
2617 }
2618
2619 n1 = _slang_gen_operation(A, &oper->children[0]);
2620 if (!n1)
2621 return NULL;
2622 n2 = _slang_gen_operation(A, &oper->children[1]);
2623 if (!n2)
2624 return NULL;
2625 return new_node2(IR_NOTEQUAL, n1, n2);
2626 }
2627
2628
2629 /**
2630 * Generate IR node for storage of a temporary of given size.
2631 */
2632 static slang_ir_node *
2633 _slang_gen_temporary(GLint size)
2634 {
2635 slang_ir_storage *store;
2636 slang_ir_node *n = NULL;
2637
2638 store = _slang_new_ir_storage(PROGRAM_TEMPORARY, -2, size);
2639 if (store) {
2640 n = new_node0(IR_VAR_DECL);
2641 if (n) {
2642 n->Store = store;
2643 }
2644 else {
2645 _slang_free(store);
2646 }
2647 }
2648 return n;
2649 }
2650
2651
2652 /**
2653 * Generate program constants for an array.
2654 * Ex: const vec2[3] v = vec2[3](vec2(1,1), vec2(2,2), vec2(3,3));
2655 * This will allocate and initialize three vector constants, storing
2656 * the array in constant memory, not temporaries like a non-const array.
2657 * This can also be used for uniform array initializers.
2658 * \return GL_TRUE for success, GL_FALSE if failure (semantic error, etc).
2659 */
2660 static GLboolean
2661 make_constant_array(slang_assemble_ctx *A,
2662 slang_variable *var,
2663 slang_operation *initializer)
2664 {
2665 struct gl_program *prog = A->program;
2666 const GLenum datatype = _slang_gltype_from_specifier(&var->type.specifier);
2667 const char *varName = (char *) var->a_name;
2668 const GLuint numElements = initializer->num_children;
2669 GLint size;
2670 GLuint i, j;
2671 GLfloat *values;
2672
2673 if (!var->store) {
2674 var->store = _slang_new_ir_storage(PROGRAM_UNDEFINED, -6, -6);
2675 }
2676 size = var->store->Size;
2677
2678 assert(var->type.qualifier == SLANG_QUAL_CONST ||
2679 var->type.qualifier == SLANG_QUAL_UNIFORM);
2680 assert(initializer->type == SLANG_OPER_CALL);
2681 assert(initializer->array_constructor);
2682
2683 values = (GLfloat *) _mesa_malloc(numElements * 4 * sizeof(GLfloat));
2684
2685 /* convert constructor params into ordinary floats */
2686 for (i = 0; i < numElements; i++) {
2687 const slang_operation *op = &initializer->children[i];
2688 if (op->type != SLANG_OPER_LITERAL_FLOAT) {
2689 /* unsupported type for this optimization */
2690 free(values);
2691 return GL_FALSE;
2692 }
2693 for (j = 0; j < op->literal_size; j++) {
2694 values[i * 4 + j] = op->literal[j];
2695 }
2696 for ( ; j < 4; j++) {
2697 values[i * 4 + j] = 0.0f;
2698 }
2699 }
2700
2701 /* slightly different paths for constants vs. uniforms */
2702 if (var->type.qualifier == SLANG_QUAL_UNIFORM) {
2703 var->store->File = PROGRAM_UNIFORM;
2704 var->store->Index = _mesa_add_uniform(prog->Parameters, varName,
2705 size, datatype, values);
2706 }
2707 else {
2708 var->store->File = PROGRAM_CONSTANT;
2709 var->store->Index = _mesa_add_named_constant(prog->Parameters, varName,
2710 values, size);
2711 }
2712 assert(var->store->Size == size);
2713
2714 _mesa_free(values);
2715
2716 return GL_TRUE;
2717 }
2718
2719
2720
2721 /**
2722 * Generate IR node for allocating/declaring a variable (either a local or
2723 * a global).
2724 * Generally, this involves allocating an slang_ir_storage instance for the
2725 * variable, choosing a register file (temporary, constant, etc).
2726 * For ordinary variables we do not yet allocate storage though. We do that
2727 * when we find the first actual use of the variable to avoid allocating temp
2728 * regs that will never get used.
2729 * At this time, uniforms are always allocated space in this function.
2730 *
2731 * \param initializer Optional initializer expression for the variable.
2732 */
2733 static slang_ir_node *
2734 _slang_gen_var_decl(slang_assemble_ctx *A, slang_variable *var,
2735 slang_operation *initializer)
2736 {
2737 const char *varName = (const char *) var->a_name;
2738 const GLenum datatype = _slang_gltype_from_specifier(&var->type.specifier);
2739 slang_ir_node *varDecl, *n;
2740 slang_ir_storage *store;
2741 GLint arrayLen, size, totalSize; /* if array then totalSize > size */
2742 enum register_file file;
2743
2744 /*assert(!var->declared);*/
2745 var->declared = GL_TRUE;
2746
2747 /* determine GPU register file for simple cases */
2748 if (is_sampler_type(&var->type)) {
2749 file = PROGRAM_SAMPLER;
2750 }
2751 else if (var->type.qualifier == SLANG_QUAL_UNIFORM) {
2752 file = PROGRAM_UNIFORM;
2753 }
2754 else {
2755 file = PROGRAM_TEMPORARY;
2756 }
2757
2758 totalSize = size = _slang_sizeof_type_specifier(&var->type.specifier);
2759 if (size <= 0) {
2760 slang_info_log_error(A->log, "invalid declaration for '%s'", varName);
2761 return NULL;
2762 }
2763
2764 arrayLen = _slang_array_length(var);
2765 totalSize = _slang_array_size(size, arrayLen);
2766
2767 /* Allocate IR node for the declaration */
2768 varDecl = new_node0(IR_VAR_DECL);
2769 if (!varDecl)
2770 return NULL;
2771
2772 _slang_attach_storage(varDecl, var); /* undefined storage at first */
2773 assert(var->store);
2774 assert(varDecl->Store == var->store);
2775 assert(varDecl->Store);
2776 assert(varDecl->Store->Index < 0);
2777 store = var->store;
2778
2779 assert(store == varDecl->Store);
2780
2781
2782 /* Fill in storage fields which we now know. store->Index/Swizzle may be
2783 * set for some cases below. Otherwise, store->Index/Swizzle will be set
2784 * during code emit.
2785 */
2786 store->File = file;
2787 store->Size = totalSize;
2788
2789 /* if there's an initializer, generate IR for the expression */
2790 if (initializer) {
2791 slang_ir_node *varRef, *init;
2792
2793 if (var->type.qualifier == SLANG_QUAL_CONST) {
2794 /* if the variable is const, the initializer must be a const
2795 * expression as well.
2796 */
2797 #if 0
2798 if (!_slang_is_constant_expr(initializer)) {
2799 slang_info_log_error(A->log,
2800 "initializer for %s not constant", varName);
2801 return NULL;
2802 }
2803 #endif
2804 }
2805
2806 /* IR for the variable we're initializing */
2807 varRef = new_var(A, var);
2808 if (!varRef) {
2809 slang_info_log_error(A->log, "out of memory");
2810 return NULL;
2811 }
2812
2813 /* constant-folding, etc here */
2814 _slang_simplify(initializer, &A->space, A->atoms);
2815
2816 /* look for simple constant-valued variables and uniforms */
2817 if (var->type.qualifier == SLANG_QUAL_CONST ||
2818 var->type.qualifier == SLANG_QUAL_UNIFORM) {
2819
2820 if (initializer->type == SLANG_OPER_CALL &&
2821 initializer->array_constructor) {
2822 /* array initializer */
2823 if (make_constant_array(A, var, initializer))
2824 return varRef;
2825 }
2826 else if (initializer->type == SLANG_OPER_LITERAL_FLOAT ||
2827 initializer->type == SLANG_OPER_LITERAL_INT) {
2828 /* simple float/vector initializer */
2829 if (store->File == PROGRAM_UNIFORM) {
2830 store->Index = _mesa_add_uniform(A->program->Parameters,
2831 varName,
2832 totalSize, datatype,
2833 initializer->literal);
2834 store->Swizzle = _slang_var_swizzle(size, 0);
2835 return varRef;
2836 }
2837 #if 0
2838 else {
2839 store->File = PROGRAM_CONSTANT;
2840 store->Index = _mesa_add_named_constant(A->program->Parameters,
2841 varName,
2842 initializer->literal,
2843 totalSize);
2844 store->Swizzle = _slang_var_swizzle(size, 0);
2845 return varRef;
2846 }
2847 #endif
2848 }
2849 }
2850
2851 /* IR for initializer */
2852 init = _slang_gen_operation(A, initializer);
2853 if (!init)
2854 return NULL;
2855
2856 /* XXX remove this when type checking is added above */
2857 if (init->Store && init->Store->Size != totalSize) {
2858 slang_info_log_error(A->log, "invalid assignment (wrong types)");
2859 return NULL;
2860 }
2861
2862 /* assign RHS to LHS */
2863 n = new_node2(IR_COPY, varRef, init);
2864 n = new_seq(varDecl, n);
2865 }
2866 else {
2867 /* no initializer */
2868 n = varDecl;
2869 }
2870
2871 if (store->File == PROGRAM_UNIFORM && store->Index < 0) {
2872 /* always need to allocate storage for uniforms at this point */
2873 store->Index = _mesa_add_uniform(A->program->Parameters, varName,
2874 totalSize, datatype, NULL);
2875 store->Swizzle = _slang_var_swizzle(size, 0);
2876 }
2877
2878 #if 0
2879 printf("%s var %p %s store=%p index=%d size=%d\n",
2880 __FUNCTION__, (void *) var, (char *) varName,
2881 (void *) store, store->Index, store->Size);
2882 #endif
2883
2884 return n;
2885 }
2886
2887
2888 /**
2889 * Generate code for a selection expression: b ? x : y
2890 * XXX In some cases we could implement a selection expression
2891 * with an LRP instruction (use the boolean as the interpolant).
2892 * Otherwise, we use an IF/ELSE/ENDIF construct.
2893 */
2894 static slang_ir_node *
2895 _slang_gen_select(slang_assemble_ctx *A, slang_operation *oper)
2896 {
2897 slang_ir_node *cond, *ifNode, *trueExpr, *falseExpr, *trueNode, *falseNode;
2898 slang_ir_node *tmpDecl, *tmpVar, *tree;
2899 slang_typeinfo type0, type1, type2;
2900 int size, isBool, isEqual;
2901
2902 assert(oper->type == SLANG_OPER_SELECT);
2903 assert(oper->num_children == 3);
2904
2905 /* type of children[0] must be boolean */
2906 slang_typeinfo_construct(&type0);
2907 typeof_operation(A, &oper->children[0], &type0);
2908 isBool = (type0.spec.type == SLANG_SPEC_BOOL);
2909 slang_typeinfo_destruct(&type0);
2910 if (!isBool) {
2911 slang_info_log_error(A->log, "selector type is not boolean");
2912 return NULL;
2913 }
2914
2915 slang_typeinfo_construct(&type1);
2916 slang_typeinfo_construct(&type2);
2917 typeof_operation(A, &oper->children[1], &type1);
2918 typeof_operation(A, &oper->children[2], &type2);
2919 isEqual = slang_type_specifier_equal(&type1.spec, &type2.spec);
2920 slang_typeinfo_destruct(&type1);
2921 slang_typeinfo_destruct(&type2);
2922 if (!isEqual) {
2923 slang_info_log_error(A->log, "incompatible types for ?: operator");
2924 return NULL;
2925 }
2926
2927 /* size of x or y's type */
2928 size = _slang_sizeof_type_specifier(&type1.spec);
2929 assert(size > 0);
2930
2931 /* temporary var */
2932 tmpDecl = _slang_gen_temporary(size);
2933
2934 /* the condition (child 0) */
2935 cond = _slang_gen_operation(A, &oper->children[0]);
2936 cond = new_cond(cond);
2937
2938 /* if-true body (child 1) */
2939 tmpVar = new_node0(IR_VAR);
2940 tmpVar->Store = tmpDecl->Store;
2941 trueExpr = _slang_gen_operation(A, &oper->children[1]);
2942 trueNode = new_node2(IR_COPY, tmpVar, trueExpr);
2943
2944 /* if-false body (child 2) */
2945 tmpVar = new_node0(IR_VAR);
2946 tmpVar->Store = tmpDecl->Store;
2947 falseExpr = _slang_gen_operation(A, &oper->children[2]);
2948 falseNode = new_node2(IR_COPY, tmpVar, falseExpr);
2949
2950 ifNode = new_if(cond, trueNode, falseNode);
2951
2952 /* tmp var value */
2953 tmpVar = new_node0(IR_VAR);
2954 tmpVar->Store = tmpDecl->Store;
2955
2956 tree = new_seq(ifNode, tmpVar);
2957 tree = new_seq(tmpDecl, tree);
2958
2959 /*_slang_print_ir_tree(tree, 10);*/
2960 return tree;
2961 }
2962
2963
2964 /**
2965 * Generate code for &&.
2966 */
2967 static slang_ir_node *
2968 _slang_gen_logical_and(slang_assemble_ctx *A, slang_operation *oper)
2969 {
2970 /* rewrite "a && b" as "a ? b : false" */
2971 slang_operation *select;
2972 slang_ir_node *n;
2973
2974 select = slang_operation_new(1);
2975 select->type = SLANG_OPER_SELECT;
2976 select->num_children = 3;
2977 select->children = slang_operation_new(3);
2978
2979 slang_operation_copy(&select->children[0], &oper->children[0]);
2980 slang_operation_copy(&select->children[1], &oper->children[1]);
2981 select->children[2].type = SLANG_OPER_LITERAL_BOOL;
2982 ASSIGN_4V(select->children[2].literal, 0, 0, 0, 0); /* false */
2983 select->children[2].literal_size = 1;
2984
2985 n = _slang_gen_select(A, select);
2986 return n;
2987 }
2988
2989
2990 /**
2991 * Generate code for ||.
2992 */
2993 static slang_ir_node *
2994 _slang_gen_logical_or(slang_assemble_ctx *A, slang_operation *oper)
2995 {
2996 /* rewrite "a || b" as "a ? true : b" */
2997 slang_operation *select;
2998 slang_ir_node *n;
2999
3000 select = slang_operation_new(1);
3001 select->type = SLANG_OPER_SELECT;
3002 select->num_children = 3;
3003 select->children = slang_operation_new(3);
3004
3005 slang_operation_copy(&select->children[0], &oper->children[0]);
3006 select->children[1].type = SLANG_OPER_LITERAL_BOOL;
3007 ASSIGN_4V(select->children[1].literal, 1, 1, 1, 1); /* true */
3008 select->children[1].literal_size = 1;
3009 slang_operation_copy(&select->children[2], &oper->children[1]);
3010
3011 n = _slang_gen_select(A, select);
3012 return n;
3013 }
3014
3015
3016 /**
3017 * Generate IR tree for a return statement.
3018 */
3019 static slang_ir_node *
3020 _slang_gen_return(slang_assemble_ctx * A, slang_operation *oper)
3021 {
3022 const GLboolean haveReturnValue
3023 = (oper->num_children == 1 && oper->children[0].type != SLANG_OPER_VOID);
3024
3025 /* error checking */
3026 assert(A->CurFunction);
3027 if (haveReturnValue &&
3028 A->CurFunction->header.type.specifier.type == SLANG_SPEC_VOID) {
3029 slang_info_log_error(A->log, "illegal return expression");
3030 return NULL;
3031 }
3032 else if (!haveReturnValue &&
3033 A->CurFunction->header.type.specifier.type != SLANG_SPEC_VOID) {
3034 slang_info_log_error(A->log, "return statement requires an expression");
3035 return NULL;
3036 }
3037
3038 if (!haveReturnValue) {
3039 return new_return(A->curFuncEndLabel);
3040 }
3041 else {
3042 /*
3043 * Convert from:
3044 * return expr;
3045 * To:
3046 * __retVal = expr;
3047 * return; // goto __endOfFunction
3048 */
3049 slang_operation *assign;
3050 slang_atom a_retVal;
3051 slang_ir_node *n;
3052
3053 a_retVal = slang_atom_pool_atom(A->atoms, "__retVal");
3054 assert(a_retVal);
3055
3056 #if 1 /* DEBUG */
3057 {
3058 slang_variable *v =
3059 _slang_variable_locate(oper->locals, a_retVal, GL_TRUE);
3060 if (!v) {
3061 /* trying to return a value in a void-valued function */
3062 return NULL;
3063 }
3064 }
3065 #endif
3066
3067 assign = slang_operation_new(1);
3068 assign->type = SLANG_OPER_ASSIGN;
3069 assign->num_children = 2;
3070 assign->children = slang_operation_new(2);
3071 /* lhs (__retVal) */
3072 assign->children[0].type = SLANG_OPER_IDENTIFIER;
3073 assign->children[0].a_id = a_retVal;
3074 assign->children[0].locals->outer_scope = assign->locals;
3075 /* rhs (expr) */
3076 /* XXX we might be able to avoid this copy someday */
3077 slang_operation_copy(&assign->children[1], &oper->children[0]);
3078
3079 /* assemble the new code */
3080 n = new_seq(_slang_gen_operation(A, assign),
3081 new_return(A->curFuncEndLabel));
3082
3083 slang_operation_delete(assign);
3084 return n;
3085 }
3086 }
3087
3088
3089 /**
3090 * Determine if the given operation/expression is const-valued.
3091 */
3092 static GLboolean
3093 _slang_is_constant_expr(const slang_operation *oper)
3094 {
3095 slang_variable *var;
3096 GLuint i;
3097
3098 switch (oper->type) {
3099 case SLANG_OPER_IDENTIFIER:
3100 var = _slang_variable_locate(oper->locals, oper->a_id, GL_TRUE);
3101 if (var && var->type.qualifier == SLANG_QUAL_CONST)
3102 return GL_TRUE;
3103 return GL_FALSE;
3104 default:
3105 for (i = 0; i < oper->num_children; i++) {
3106 if (!_slang_is_constant_expr(&oper->children[i]))
3107 return GL_FALSE;
3108 }
3109 return GL_TRUE;
3110 }
3111 }
3112
3113
3114 /**
3115 * Check if an assignment of type t1 to t0 is legal.
3116 * XXX more cases needed.
3117 */
3118 static GLboolean
3119 _slang_assignment_compatible(slang_assemble_ctx *A,
3120 slang_operation *op0,
3121 slang_operation *op1)
3122 {
3123 slang_typeinfo t0, t1;
3124 GLuint sz0, sz1;
3125
3126 if (op0->type == SLANG_OPER_POSTINCREMENT ||
3127 op0->type == SLANG_OPER_POSTDECREMENT) {
3128 return GL_FALSE;
3129 }
3130
3131 slang_typeinfo_construct(&t0);
3132 typeof_operation(A, op0, &t0);
3133
3134 slang_typeinfo_construct(&t1);
3135 typeof_operation(A, op1, &t1);
3136
3137 sz0 = _slang_sizeof_type_specifier(&t0.spec);
3138 sz1 = _slang_sizeof_type_specifier(&t1.spec);
3139
3140 #if 1
3141 if (sz0 != sz1) {
3142 /*printf("assignment size mismatch %u vs %u\n", sz0, sz1);*/
3143 return GL_FALSE;
3144 }
3145 #endif
3146
3147 if (t0.spec.type == SLANG_SPEC_STRUCT &&
3148 t1.spec.type == SLANG_SPEC_STRUCT &&
3149 t0.spec._struct->a_name != t1.spec._struct->a_name)
3150 return GL_FALSE;
3151
3152 if (t0.spec.type == SLANG_SPEC_FLOAT &&
3153 t1.spec.type == SLANG_SPEC_BOOL)
3154 return GL_FALSE;
3155
3156 #if 0 /* not used just yet - causes problems elsewhere */
3157 if (t0.spec.type == SLANG_SPEC_INT &&
3158 t1.spec.type == SLANG_SPEC_FLOAT)
3159 return GL_FALSE;
3160 #endif
3161
3162 if (t0.spec.type == SLANG_SPEC_BOOL &&
3163 t1.spec.type == SLANG_SPEC_FLOAT)
3164 return GL_FALSE;
3165
3166 if (t0.spec.type == SLANG_SPEC_BOOL &&
3167 t1.spec.type == SLANG_SPEC_INT)
3168 return GL_FALSE;
3169
3170 return GL_TRUE;
3171 }
3172
3173
3174 /**
3175 * Generate IR tree for a local variable declaration.
3176 * Basically do some error checking and call _slang_gen_var_decl().
3177 */
3178 static slang_ir_node *
3179 _slang_gen_declaration(slang_assemble_ctx *A, slang_operation *oper)
3180 {
3181 const char *varName = (char *) oper->a_id;
3182 slang_variable *var;
3183 slang_ir_node *varDecl;
3184 slang_operation *initializer;
3185
3186 assert(oper->type == SLANG_OPER_VARIABLE_DECL);
3187 assert(oper->num_children <= 1);
3188
3189 /* lookup the variable by name */
3190 var = _slang_variable_locate(oper->locals, oper->a_id, GL_TRUE);
3191 if (!var)
3192 return NULL; /* "shouldn't happen" */
3193
3194 if (var->type.qualifier == SLANG_QUAL_ATTRIBUTE ||
3195 var->type.qualifier == SLANG_QUAL_VARYING ||
3196 var->type.qualifier == SLANG_QUAL_UNIFORM) {
3197 /* can't declare attribute/uniform vars inside functions */
3198 slang_info_log_error(A->log,
3199 "local variable '%s' cannot be an attribute/uniform/varying",
3200 varName);
3201 return NULL;
3202 }
3203
3204 #if 0
3205 if (v->declared) {
3206 slang_info_log_error(A->log, "variable '%s' redeclared", varName);
3207 return NULL;
3208 }
3209 #endif
3210
3211 /* check if the var has an initializer */
3212 if (oper->num_children > 0) {
3213 assert(oper->num_children == 1);
3214 initializer = &oper->children[0];
3215 }
3216 else if (var->initializer) {
3217 initializer = var->initializer;
3218 }
3219 else {
3220 initializer = NULL;
3221 }
3222
3223 if (initializer) {
3224 /* check/compare var type and initializer type */
3225 if (!_slang_assignment_compatible(A, oper, initializer)) {
3226 slang_info_log_error(A->log, "incompatible types in assignment");
3227 return NULL;
3228 }
3229 }
3230 else {
3231 if (var->type.qualifier == SLANG_QUAL_CONST) {
3232 slang_info_log_error(A->log,
3233 "const-qualified variable '%s' requires initializer",
3234 varName);
3235 return NULL;
3236 }
3237 }
3238
3239 /* Generate IR node */
3240 varDecl = _slang_gen_var_decl(A, var, initializer);
3241 if (!varDecl)
3242 return NULL;
3243
3244 return varDecl;
3245 }
3246
3247
3248 /**
3249 * Generate IR tree for a reference to a variable (such as in an expression).
3250 * This is different from a variable declaration.
3251 */
3252 static slang_ir_node *
3253 _slang_gen_variable(slang_assemble_ctx * A, slang_operation *oper)
3254 {
3255 /* If there's a variable associated with this oper (from inlining)
3256 * use it. Otherwise, use the oper's var id.
3257 */
3258 slang_atom name = oper->var ? oper->var->a_name : oper->a_id;
3259 slang_variable *var = _slang_variable_locate(oper->locals, name, GL_TRUE);
3260 slang_ir_node *n;
3261 if (!var) {
3262 slang_info_log_error(A->log, "undefined variable '%s'", (char *) name);
3263 return NULL;
3264 }
3265 assert(var->declared);
3266 n = new_var(A, var);
3267 return n;
3268 }
3269
3270
3271
3272 /**
3273 * Return the number of components actually named by the swizzle.
3274 * Recall that swizzles may have undefined/don't-care values.
3275 */
3276 static GLuint
3277 swizzle_size(GLuint swizzle)
3278 {
3279 GLuint size = 0, i;
3280 for (i = 0; i < 4; i++) {
3281 GLuint swz = GET_SWZ(swizzle, i);
3282 size += (swz >= 0 && swz <= 3);
3283 }
3284 return size;
3285 }
3286
3287
3288 static slang_ir_node *
3289 _slang_gen_swizzle(slang_ir_node *child, GLuint swizzle)
3290 {
3291 slang_ir_node *n = new_node1(IR_SWIZZLE, child);
3292 assert(child);
3293 if (n) {
3294 assert(!n->Store);
3295 n->Store = _slang_new_ir_storage_relative(0,
3296 swizzle_size(swizzle),
3297 child->Store);
3298 n->Store->Swizzle = swizzle;
3299 }
3300 return n;
3301 }
3302
3303
3304 static GLboolean
3305 is_store_writable(const slang_assemble_ctx *A, const slang_ir_storage *store)
3306 {
3307 while (store->Parent)
3308 store = store->Parent;
3309
3310 if (!(store->File == PROGRAM_OUTPUT ||
3311 store->File == PROGRAM_TEMPORARY ||
3312 (store->File == PROGRAM_VARYING &&
3313 A->program->Target == GL_VERTEX_PROGRAM_ARB))) {
3314 return GL_FALSE;
3315 }
3316 else {
3317 return GL_TRUE;
3318 }
3319 }
3320
3321
3322 /**
3323 * Walk up an IR storage path to compute the final swizzle.
3324 * This is used when we find an expression such as "foo.xz.yx".
3325 */
3326 static GLuint
3327 root_swizzle(const slang_ir_storage *st)
3328 {
3329 GLuint swizzle = st->Swizzle;
3330 while (st->Parent) {
3331 st = st->Parent;
3332 swizzle = _slang_swizzle_swizzle(st->Swizzle, swizzle);
3333 }
3334 return swizzle;
3335 }
3336
3337
3338 /**
3339 * Generate IR tree for an assignment (=).
3340 */
3341 static slang_ir_node *
3342 _slang_gen_assignment(slang_assemble_ctx * A, slang_operation *oper)
3343 {
3344 if (oper->children[0].type == SLANG_OPER_IDENTIFIER) {
3345 /* Check that var is writeable */
3346 slang_variable *var
3347 = _slang_variable_locate(oper->children[0].locals,
3348 oper->children[0].a_id, GL_TRUE);
3349 if (!var) {
3350 slang_info_log_error(A->log, "undefined variable '%s'",
3351 (char *) oper->children[0].a_id);
3352 return NULL;
3353 }
3354 if (var->type.qualifier == SLANG_QUAL_CONST ||
3355 var->type.qualifier == SLANG_QUAL_ATTRIBUTE ||
3356 var->type.qualifier == SLANG_QUAL_UNIFORM ||
3357 (var->type.qualifier == SLANG_QUAL_VARYING &&
3358 A->program->Target == GL_FRAGMENT_PROGRAM_ARB)) {
3359 slang_info_log_error(A->log,
3360 "illegal assignment to read-only variable '%s'",
3361 (char *) oper->children[0].a_id);
3362 return NULL;
3363 }
3364 }
3365
3366 if (oper->children[0].type == SLANG_OPER_IDENTIFIER &&
3367 oper->children[1].type == SLANG_OPER_CALL) {
3368 /* Special case of: x = f(a, b)
3369 * Replace with f(a, b, x) (where x == hidden __retVal out param)
3370 *
3371 * XXX this could be even more effective if we could accomodate
3372 * cases such as "v.x = f();" - would help with typical vertex
3373 * transformation.
3374 */
3375 slang_ir_node *n;
3376 n = _slang_gen_function_call_name(A,
3377 (const char *) oper->children[1].a_id,
3378 &oper->children[1], &oper->children[0]);
3379 return n;
3380 }
3381 else {
3382 slang_ir_node *n, *lhs, *rhs;
3383
3384 /* lhs and rhs type checking */
3385 if (!_slang_assignment_compatible(A,
3386 &oper->children[0],
3387 &oper->children[1])) {
3388 slang_info_log_error(A->log, "incompatible types in assignment");
3389 return NULL;
3390 }
3391
3392 lhs = _slang_gen_operation(A, &oper->children[0]);
3393 if (!lhs) {
3394 return NULL;
3395 }
3396
3397 if (!lhs->Store) {
3398 slang_info_log_error(A->log,
3399 "invalid left hand side for assignment");
3400 return NULL;
3401 }
3402
3403 /* check that lhs is writable */
3404 if (!is_store_writable(A, lhs->Store)) {
3405 slang_info_log_error(A->log,
3406 "illegal assignment to read-only l-value");
3407 return NULL;
3408 }
3409
3410 rhs = _slang_gen_operation(A, &oper->children[1]);
3411 if (lhs && rhs) {
3412 /* convert lhs swizzle into writemask */
3413 const GLuint swizzle = root_swizzle(lhs->Store);
3414 GLuint writemask, newSwizzle;
3415 if (!swizzle_to_writemask(A, swizzle, &writemask, &newSwizzle)) {
3416 /* Non-simple writemask, need to swizzle right hand side in
3417 * order to put components into the right place.
3418 */
3419 rhs = _slang_gen_swizzle(rhs, newSwizzle);
3420 }
3421 n = new_node2(IR_COPY, lhs, rhs);
3422 return n;
3423 }
3424 else {
3425 return NULL;
3426 }
3427 }
3428 }
3429
3430
3431 /**
3432 * Generate IR tree for referencing a field in a struct (or basic vector type)
3433 */
3434 static slang_ir_node *
3435 _slang_gen_struct_field(slang_assemble_ctx * A, slang_operation *oper)
3436 {
3437 slang_typeinfo ti;
3438
3439 /* type of struct */
3440 slang_typeinfo_construct(&ti);
3441 typeof_operation(A, &oper->children[0], &ti);
3442
3443 if (_slang_type_is_vector(ti.spec.type)) {
3444 /* the field should be a swizzle */
3445 const GLuint rows = _slang_type_dim(ti.spec.type);
3446 slang_swizzle swz;
3447 slang_ir_node *n;
3448 GLuint swizzle;
3449 if (!_slang_is_swizzle((char *) oper->a_id, rows, &swz)) {
3450 slang_info_log_error(A->log, "Bad swizzle");
3451 return NULL;
3452 }
3453 swizzle = MAKE_SWIZZLE4(swz.swizzle[0],
3454 swz.swizzle[1],
3455 swz.swizzle[2],
3456 swz.swizzle[3]);
3457
3458 n = _slang_gen_operation(A, &oper->children[0]);
3459 /* create new parent node with swizzle */
3460 if (n)
3461 n = _slang_gen_swizzle(n, swizzle);
3462 return n;
3463 }
3464 else if ( ti.spec.type == SLANG_SPEC_FLOAT
3465 || ti.spec.type == SLANG_SPEC_INT
3466 || ti.spec.type == SLANG_SPEC_BOOL) {
3467 const GLuint rows = 1;
3468 slang_swizzle swz;
3469 slang_ir_node *n;
3470 GLuint swizzle;
3471 if (!_slang_is_swizzle((char *) oper->a_id, rows, &swz)) {
3472 slang_info_log_error(A->log, "Bad swizzle");
3473 }
3474 swizzle = MAKE_SWIZZLE4(swz.swizzle[0],
3475 swz.swizzle[1],
3476 swz.swizzle[2],
3477 swz.swizzle[3]);
3478 n = _slang_gen_operation(A, &oper->children[0]);
3479 /* create new parent node with swizzle */
3480 n = _slang_gen_swizzle(n, swizzle);
3481 return n;
3482 }
3483 else {
3484 /* the field is a structure member (base.field) */
3485 /* oper->children[0] is the base */
3486 /* oper->a_id is the field name */
3487 slang_ir_node *base, *n;
3488 slang_typeinfo field_ti;
3489 GLint fieldSize, fieldOffset = -1;
3490
3491 /* type of field */
3492 slang_typeinfo_construct(&field_ti);
3493 typeof_operation(A, oper, &field_ti);
3494
3495 fieldSize = _slang_sizeof_type_specifier(&field_ti.spec);
3496 if (fieldSize > 0)
3497 fieldOffset = _slang_field_offset(&ti.spec, oper->a_id);
3498
3499 if (fieldSize == 0 || fieldOffset < 0) {
3500 const char *structName;
3501 if (ti.spec._struct)
3502 structName = (char *) ti.spec._struct->a_name;
3503 else
3504 structName = "unknown";
3505 slang_info_log_error(A->log,
3506 "\"%s\" is not a member of struct \"%s\"",
3507 (char *) oper->a_id, structName);
3508 return NULL;
3509 }
3510 assert(fieldSize >= 0);
3511
3512 base = _slang_gen_operation(A, &oper->children[0]);
3513 if (!base) {
3514 /* error msg should have already been logged */
3515 return NULL;
3516 }
3517
3518 n = new_node1(IR_FIELD, base);
3519 if (!n)
3520 return NULL;
3521
3522 n->Field = (char *) oper->a_id;
3523
3524 /* Store the field's offset in storage->Index */
3525 n->Store = _slang_new_ir_storage(base->Store->File,
3526 fieldOffset,
3527 fieldSize);
3528
3529 return n;
3530 }
3531 }
3532
3533
3534 /**
3535 * Gen code for array indexing.
3536 */
3537 static slang_ir_node *
3538 _slang_gen_array_element(slang_assemble_ctx * A, slang_operation *oper)
3539 {
3540 slang_typeinfo array_ti;
3541
3542 /* get array's type info */
3543 slang_typeinfo_construct(&array_ti);
3544 typeof_operation(A, &oper->children[0], &array_ti);
3545
3546 if (_slang_type_is_vector(array_ti.spec.type)) {
3547 /* indexing a simple vector type: "vec4 v; v[0]=p;" */
3548 /* translate the index into a swizzle/writemask: "v.x=p" */
3549 const GLuint max = _slang_type_dim(array_ti.spec.type);
3550 GLint index;
3551 slang_ir_node *n;
3552
3553 index = (GLint) oper->children[1].literal[0];
3554 if (oper->children[1].type != SLANG_OPER_LITERAL_INT ||
3555 index >= (GLint) max) {
3556 slang_info_log_error(A->log, "Invalid array index for vector type");
3557 return NULL;
3558 }
3559
3560 n = _slang_gen_operation(A, &oper->children[0]);
3561 if (n) {
3562 /* use swizzle to access the element */
3563 GLuint swizzle = MAKE_SWIZZLE4(SWIZZLE_X + index,
3564 SWIZZLE_NIL,
3565 SWIZZLE_NIL,
3566 SWIZZLE_NIL);
3567 n = _slang_gen_swizzle(n, swizzle);
3568 }
3569 assert(n->Store);
3570 return n;
3571 }
3572 else {
3573 /* conventional array */
3574 slang_typeinfo elem_ti;
3575 slang_ir_node *elem, *array, *index;
3576 GLint elemSize, arrayLen;
3577
3578 /* size of array element */
3579 slang_typeinfo_construct(&elem_ti);
3580 typeof_operation(A, oper, &elem_ti);
3581 elemSize = _slang_sizeof_type_specifier(&elem_ti.spec);
3582
3583 if (_slang_type_is_matrix(array_ti.spec.type))
3584 arrayLen = _slang_type_dim(array_ti.spec.type);
3585 else
3586 arrayLen = array_ti.array_len;
3587
3588 slang_typeinfo_destruct(&array_ti);
3589 slang_typeinfo_destruct(&elem_ti);
3590
3591 if (elemSize <= 0) {
3592 /* unknown var or type */
3593 slang_info_log_error(A->log, "Undefined variable or type");
3594 return NULL;
3595 }
3596
3597 array = _slang_gen_operation(A, &oper->children[0]);
3598 index = _slang_gen_operation(A, &oper->children[1]);
3599 if (array && index) {
3600 /* bounds check */
3601 GLint constIndex = -1;
3602 if (index->Opcode == IR_FLOAT) {
3603 constIndex = (int) index->Value[0];
3604 if (constIndex < 0 || constIndex >= arrayLen) {
3605 slang_info_log_error(A->log,
3606 "Array index out of bounds (index=%d size=%d)",
3607 constIndex, arrayLen);
3608 _slang_free_ir_tree(array);
3609 _slang_free_ir_tree(index);
3610 return NULL;
3611 }
3612 }
3613
3614 if (!array->Store) {
3615 slang_info_log_error(A->log, "Invalid array");
3616 return NULL;
3617 }
3618
3619 elem = new_node2(IR_ELEMENT, array, index);
3620
3621 /* The storage info here will be updated during code emit */
3622 elem->Store = _slang_new_ir_storage(array->Store->File,
3623 array->Store->Index,
3624 elemSize);
3625 elem->Store->Swizzle = _slang_var_swizzle(elemSize, 0);
3626 return elem;
3627 }
3628 else {
3629 _slang_free_ir_tree(array);
3630 _slang_free_ir_tree(index);
3631 return NULL;
3632 }
3633 }
3634 }
3635
3636
3637 static slang_ir_node *
3638 _slang_gen_compare(slang_assemble_ctx *A, slang_operation *oper,
3639 slang_ir_opcode opcode)
3640 {
3641 slang_typeinfo t0, t1;
3642 slang_ir_node *n;
3643
3644 slang_typeinfo_construct(&t0);
3645 typeof_operation(A, &oper->children[0], &t0);
3646
3647 slang_typeinfo_construct(&t1);
3648 typeof_operation(A, &oper->children[0], &t1);
3649
3650 if (t0.spec.type == SLANG_SPEC_ARRAY ||
3651 t1.spec.type == SLANG_SPEC_ARRAY) {
3652 slang_info_log_error(A->log, "Illegal array comparison");
3653 return NULL;
3654 }
3655
3656 if (oper->type != SLANG_OPER_EQUAL &&
3657 oper->type != SLANG_OPER_NOTEQUAL) {
3658 /* <, <=, >, >= can only be used with scalars */
3659 if ((t0.spec.type != SLANG_SPEC_INT &&
3660 t0.spec.type != SLANG_SPEC_FLOAT) ||
3661 (t1.spec.type != SLANG_SPEC_INT &&
3662 t1.spec.type != SLANG_SPEC_FLOAT)) {
3663 slang_info_log_error(A->log, "Incompatible type(s) for inequality operator");
3664 return NULL;
3665 }
3666 }
3667
3668 n = new_node2(opcode,
3669 _slang_gen_operation(A, &oper->children[0]),
3670 _slang_gen_operation(A, &oper->children[1]));
3671
3672 /* result is a bool (size 1) */
3673 n->Store = _slang_new_ir_storage(PROGRAM_TEMPORARY, -1, 1);
3674
3675 return n;
3676 }
3677
3678
3679 #if 0
3680 static void
3681 print_vars(slang_variable_scope *s)
3682 {
3683 int i;
3684 printf("vars: ");
3685 for (i = 0; i < s->num_variables; i++) {
3686 printf("%s %d, \n",
3687 (char*) s->variables[i]->a_name,
3688 s->variables[i]->declared);
3689 }
3690
3691 printf("\n");
3692 }
3693 #endif
3694
3695
3696 #if 0
3697 static void
3698 _slang_undeclare_vars(slang_variable_scope *locals)
3699 {
3700 if (locals->num_variables > 0) {
3701 int i;
3702 for (i = 0; i < locals->num_variables; i++) {
3703 slang_variable *v = locals->variables[i];
3704 printf("undeclare %s at %p\n", (char*) v->a_name, v);
3705 v->declared = GL_FALSE;
3706 }
3707 }
3708 }
3709 #endif
3710
3711
3712 /**
3713 * Generate IR tree for a slang_operation (AST node)
3714 */
3715 static slang_ir_node *
3716 _slang_gen_operation(slang_assemble_ctx * A, slang_operation *oper)
3717 {
3718 switch (oper->type) {
3719 case SLANG_OPER_BLOCK_NEW_SCOPE:
3720 {
3721 slang_ir_node *n;
3722
3723 _slang_push_var_table(A->vartable);
3724
3725 oper->type = SLANG_OPER_BLOCK_NO_NEW_SCOPE; /* temp change */
3726 n = _slang_gen_operation(A, oper);
3727 oper->type = SLANG_OPER_BLOCK_NEW_SCOPE; /* restore */
3728
3729 _slang_pop_var_table(A->vartable);
3730
3731 /*_slang_undeclare_vars(oper->locals);*/
3732 /*print_vars(oper->locals);*/
3733
3734 if (n)
3735 n = new_node1(IR_SCOPE, n);
3736 return n;
3737 }
3738 break;
3739
3740 case SLANG_OPER_BLOCK_NO_NEW_SCOPE:
3741 /* list of operations */
3742 if (oper->num_children > 0)
3743 {
3744 slang_ir_node *n, *tree = NULL;
3745 GLuint i;
3746
3747 for (i = 0; i < oper->num_children; i++) {
3748 n = _slang_gen_operation(A, &oper->children[i]);
3749 if (!n) {
3750 _slang_free_ir_tree(tree);
3751 return NULL; /* error must have occured */
3752 }
3753 tree = new_seq(tree, n);
3754 }
3755
3756 return tree;
3757 }
3758 else {
3759 return new_node0(IR_NOP);
3760 }
3761
3762 case SLANG_OPER_EXPRESSION:
3763 return _slang_gen_operation(A, &oper->children[0]);
3764
3765 case SLANG_OPER_FOR:
3766 return _slang_gen_for(A, oper);
3767 case SLANG_OPER_DO:
3768 return _slang_gen_do(A, oper);
3769 case SLANG_OPER_WHILE:
3770 return _slang_gen_while(A, oper);
3771 case SLANG_OPER_BREAK:
3772 if (!A->CurLoop) {
3773 slang_info_log_error(A->log, "'break' not in loop");
3774 return NULL;
3775 }
3776 return new_break(A->CurLoop);
3777 case SLANG_OPER_CONTINUE:
3778 if (!A->CurLoop) {
3779 slang_info_log_error(A->log, "'continue' not in loop");
3780 return NULL;
3781 }
3782 return _slang_gen_continue(A, oper);
3783 case SLANG_OPER_DISCARD:
3784 return new_node0(IR_KILL);
3785
3786 case SLANG_OPER_EQUAL:
3787 return _slang_gen_compare(A, oper, IR_EQUAL);
3788 case SLANG_OPER_NOTEQUAL:
3789 return _slang_gen_compare(A, oper, IR_NOTEQUAL);
3790 case SLANG_OPER_GREATER:
3791 return _slang_gen_compare(A, oper, IR_SGT);
3792 case SLANG_OPER_LESS:
3793 return _slang_gen_compare(A, oper, IR_SLT);
3794 case SLANG_OPER_GREATEREQUAL:
3795 return _slang_gen_compare(A, oper, IR_SGE);
3796 case SLANG_OPER_LESSEQUAL:
3797 return _slang_gen_compare(A, oper, IR_SLE);
3798 case SLANG_OPER_ADD:
3799 {
3800 slang_ir_node *n;
3801 assert(oper->num_children == 2);
3802 n = _slang_gen_function_call_name(A, "+", oper, NULL);
3803 return n;
3804 }
3805 case SLANG_OPER_SUBTRACT:
3806 {
3807 slang_ir_node *n;
3808 assert(oper->num_children == 2);
3809 n = _slang_gen_function_call_name(A, "-", oper, NULL);
3810 return n;
3811 }
3812 case SLANG_OPER_MULTIPLY:
3813 {
3814 slang_ir_node *n;
3815 assert(oper->num_children == 2);
3816 n = _slang_gen_function_call_name(A, "*", oper, NULL);
3817 return n;
3818 }
3819 case SLANG_OPER_DIVIDE:
3820 {
3821 slang_ir_node *n;
3822 assert(oper->num_children == 2);
3823 n = _slang_gen_function_call_name(A, "/", oper, NULL);
3824 return n;
3825 }
3826 case SLANG_OPER_MINUS:
3827 {
3828 slang_ir_node *n;
3829 assert(oper->num_children == 1);
3830 n = _slang_gen_function_call_name(A, "-", oper, NULL);
3831 return n;
3832 }
3833 case SLANG_OPER_PLUS:
3834 /* +expr --> do nothing */
3835 return _slang_gen_operation(A, &oper->children[0]);
3836 case SLANG_OPER_VARIABLE_DECL:
3837 return _slang_gen_declaration(A, oper);
3838 case SLANG_OPER_ASSIGN:
3839 return _slang_gen_assignment(A, oper);
3840 case SLANG_OPER_ADDASSIGN:
3841 {
3842 slang_ir_node *n;
3843 assert(oper->num_children == 2);
3844 n = _slang_gen_function_call_name(A, "+=", oper, NULL);
3845 return n;
3846 }
3847 case SLANG_OPER_SUBASSIGN:
3848 {
3849 slang_ir_node *n;
3850 assert(oper->num_children == 2);
3851 n = _slang_gen_function_call_name(A, "-=", oper, NULL);
3852 return n;
3853 }
3854 break;
3855 case SLANG_OPER_MULASSIGN:
3856 {
3857 slang_ir_node *n;
3858 assert(oper->num_children == 2);
3859 n = _slang_gen_function_call_name(A, "*=", oper, NULL);
3860 return n;
3861 }
3862 case SLANG_OPER_DIVASSIGN:
3863 {
3864 slang_ir_node *n;
3865 assert(oper->num_children == 2);
3866 n = _slang_gen_function_call_name(A, "/=", oper, NULL);
3867 return n;
3868 }
3869 case SLANG_OPER_LOGICALAND:
3870 {
3871 slang_ir_node *n;
3872 assert(oper->num_children == 2);
3873 n = _slang_gen_logical_and(A, oper);
3874 return n;
3875 }
3876 case SLANG_OPER_LOGICALOR:
3877 {
3878 slang_ir_node *n;
3879 assert(oper->num_children == 2);
3880 n = _slang_gen_logical_or(A, oper);
3881 return n;
3882 }
3883 case SLANG_OPER_LOGICALXOR:
3884 return _slang_gen_xor(A, oper);
3885 case SLANG_OPER_NOT:
3886 return _slang_gen_not(A, oper);
3887 case SLANG_OPER_SELECT: /* b ? x : y */
3888 {
3889 slang_ir_node *n;
3890 assert(oper->num_children == 3);
3891 n = _slang_gen_select(A, oper);
3892 return n;
3893 }
3894
3895 case SLANG_OPER_ASM:
3896 return _slang_gen_asm(A, oper, NULL);
3897 case SLANG_OPER_CALL:
3898 return _slang_gen_function_call_name(A, (const char *) oper->a_id,
3899 oper, NULL);
3900 case SLANG_OPER_METHOD:
3901 return _slang_gen_method_call(A, oper);
3902 case SLANG_OPER_RETURN:
3903 return _slang_gen_return(A, oper);
3904 case SLANG_OPER_LABEL:
3905 return new_label(oper->label);
3906 case SLANG_OPER_IDENTIFIER:
3907 return _slang_gen_variable(A, oper);
3908 case SLANG_OPER_IF:
3909 return _slang_gen_if(A, oper);
3910 case SLANG_OPER_FIELD:
3911 return _slang_gen_struct_field(A, oper);
3912 case SLANG_OPER_SUBSCRIPT:
3913 return _slang_gen_array_element(A, oper);
3914 case SLANG_OPER_LITERAL_FLOAT:
3915 /* fall-through */
3916 case SLANG_OPER_LITERAL_INT:
3917 /* fall-through */
3918 case SLANG_OPER_LITERAL_BOOL:
3919 return new_float_literal(oper->literal, oper->literal_size);
3920
3921 case SLANG_OPER_POSTINCREMENT: /* var++ */
3922 {
3923 slang_ir_node *n;
3924 assert(oper->num_children == 1);
3925 n = _slang_gen_function_call_name(A, "__postIncr", oper, NULL);
3926 return n;
3927 }
3928 case SLANG_OPER_POSTDECREMENT: /* var-- */
3929 {
3930 slang_ir_node *n;
3931 assert(oper->num_children == 1);
3932 n = _slang_gen_function_call_name(A, "__postDecr", oper, NULL);
3933 return n;
3934 }
3935 case SLANG_OPER_PREINCREMENT: /* ++var */
3936 {
3937 slang_ir_node *n;
3938 assert(oper->num_children == 1);
3939 n = _slang_gen_function_call_name(A, "++", oper, NULL);
3940 return n;
3941 }
3942 case SLANG_OPER_PREDECREMENT: /* --var */
3943 {
3944 slang_ir_node *n;
3945 assert(oper->num_children == 1);
3946 n = _slang_gen_function_call_name(A, "--", oper, NULL);
3947 return n;
3948 }
3949
3950 case SLANG_OPER_NON_INLINED_CALL:
3951 case SLANG_OPER_SEQUENCE:
3952 {
3953 slang_ir_node *tree = NULL;
3954 GLuint i;
3955 for (i = 0; i < oper->num_children; i++) {
3956 slang_ir_node *n = _slang_gen_operation(A, &oper->children[i]);
3957 tree = new_seq(tree, n);
3958 if (n)
3959 tree->Store = n->Store;
3960 }
3961 if (oper->type == SLANG_OPER_NON_INLINED_CALL) {
3962 tree = new_function_call(tree, oper->label);
3963 }
3964 return tree;
3965 }
3966
3967 case SLANG_OPER_NONE:
3968 case SLANG_OPER_VOID:
3969 /* returning NULL here would generate an error */
3970 return new_node0(IR_NOP);
3971
3972 default:
3973 _mesa_problem(NULL, "bad node type %d in _slang_gen_operation",
3974 oper->type);
3975 return new_node0(IR_NOP);
3976 }
3977
3978 return NULL;
3979 }
3980
3981
3982 /**
3983 * Called by compiler when a global variable has been parsed/compiled.
3984 * Here we examine the variable's type to determine what kind of register
3985 * storage will be used.
3986 *
3987 * A uniform such as "gl_Position" will become the register specification
3988 * (PROGRAM_OUTPUT, VERT_RESULT_HPOS). Or, uniform "gl_FogFragCoord"
3989 * will be (PROGRAM_INPUT, FRAG_ATTRIB_FOGC).
3990 *
3991 * Samplers are interesting. For "uniform sampler2D tex;" we'll specify
3992 * (PROGRAM_SAMPLER, index) where index is resolved at link-time to an
3993 * actual texture unit (as specified by the user calling glUniform1i()).
3994 */
3995 GLboolean
3996 _slang_codegen_global_variable(slang_assemble_ctx *A, slang_variable *var,
3997 slang_unit_type type)
3998 {
3999 struct gl_program *prog = A->program;
4000 const char *varName = (char *) var->a_name;
4001 GLboolean success = GL_TRUE;
4002 slang_ir_storage *store = NULL;
4003 int dbg = 0;
4004 const GLenum datatype = _slang_gltype_from_specifier(&var->type.specifier);
4005 const GLint texIndex = sampler_to_texture_index(var->type.specifier.type);
4006 const GLint size = _slang_sizeof_type_specifier(&var->type.specifier);
4007 const GLint arrayLen = _slang_array_length(var);
4008 const GLint totalSize = _slang_array_size(size, arrayLen);
4009
4010 if (texIndex != -1) {
4011 /* This is a texture sampler variable...
4012 * store->File = PROGRAM_SAMPLER
4013 * store->Index = sampler number (0..7, typically)
4014 * store->Size = texture type index (1D, 2D, 3D, cube, etc)
4015 */
4016 if (var->initializer) {
4017 slang_info_log_error(A->log, "illegal assignment to '%s'", varName);
4018 return GL_FALSE;
4019 }
4020 #if FEATURE_es2_glsl /* XXX should use FEATURE_texture_rect */
4021 /* disallow rect samplers */
4022 if (var->type.specifier.type == SLANG_SPEC_SAMPLER2DRECT ||
4023 var->type.specifier.type == SLANG_SPEC_SAMPLER2DRECTSHADOW) {
4024 slang_info_log_error(A->log, "invalid sampler type for '%s'", varName);
4025 return GL_FALSE;
4026 }
4027 #endif
4028 {
4029 GLint sampNum = _mesa_add_sampler(prog->Parameters, varName, datatype);
4030 store = _slang_new_ir_storage(PROGRAM_SAMPLER, sampNum, texIndex);
4031 }
4032 if (dbg) printf("SAMPLER ");
4033 }
4034 else if (var->type.qualifier == SLANG_QUAL_UNIFORM) {
4035 /* Uniform variable */
4036 const GLuint swizzle = _slang_var_swizzle(totalSize, 0);
4037
4038 if (prog) {
4039 /* user-defined uniform */
4040 if (datatype == GL_NONE) {
4041 if (var->type.specifier.type == SLANG_SPEC_STRUCT) {
4042 /* temporary work-around */
4043 GLenum datatype = GL_FLOAT;
4044 GLint uniformLoc = _mesa_add_uniform(prog->Parameters, varName,
4045 totalSize, datatype, NULL);
4046 store = _slang_new_ir_storage_swz(PROGRAM_UNIFORM, uniformLoc,
4047 totalSize, swizzle);
4048
4049 /* XXX what we need to do is unroll the struct into its
4050 * basic types, creating a uniform variable for each.
4051 * For example:
4052 * struct foo {
4053 * vec3 a;
4054 * vec4 b;
4055 * };
4056 * uniform foo f;
4057 *
4058 * Should produce uniforms:
4059 * "f.a" (GL_FLOAT_VEC3)
4060 * "f.b" (GL_FLOAT_VEC4)
4061 */
4062
4063 if (var->initializer) {
4064 slang_info_log_error(A->log,
4065 "unsupported initializer for uniform '%s'", varName);
4066 return GL_FALSE;
4067 }
4068 }
4069 else {
4070 slang_info_log_error(A->log,
4071 "invalid datatype for uniform variable %s",
4072 varName);
4073 return GL_FALSE;
4074 }
4075 }
4076 else {
4077 /* non-struct uniform */
4078 if (!_slang_gen_var_decl(A, var, var->initializer))
4079 return GL_FALSE;
4080 store = var->store;
4081 }
4082 }
4083 else {
4084 /* pre-defined uniform, like gl_ModelviewMatrix */
4085 /* We know it's a uniform, but don't allocate storage unless
4086 * it's really used.
4087 */
4088 store = _slang_new_ir_storage_swz(PROGRAM_STATE_VAR, -1,
4089 totalSize, swizzle);
4090 }
4091 if (dbg) printf("UNIFORM (sz %d) ", totalSize);
4092 }
4093 else if (var->type.qualifier == SLANG_QUAL_VARYING) {
4094 /* varyings must be float, vec or mat */
4095 if (!_slang_type_is_float_vec_mat(var->type.specifier.type) &&
4096 var->type.specifier.type != SLANG_SPEC_ARRAY) {
4097 slang_info_log_error(A->log,
4098 "varying '%s' must be float/vector/matrix",
4099 varName);
4100 return GL_FALSE;
4101 }
4102
4103 if (var->initializer) {
4104 slang_info_log_error(A->log, "illegal initializer for varying '%s'",
4105 varName);
4106 return GL_FALSE;
4107 }
4108
4109 if (prog) {
4110 /* user-defined varying */
4111 GLbitfield flags;
4112 GLint varyingLoc;
4113 GLuint swizzle;
4114
4115 flags = 0x0;
4116 if (var->type.centroid == SLANG_CENTROID)
4117 flags |= PROG_PARAM_BIT_CENTROID;
4118 if (var->type.variant == SLANG_INVARIANT)
4119 flags |= PROG_PARAM_BIT_INVARIANT;
4120
4121 varyingLoc = _mesa_add_varying(prog->Varying, varName,
4122 totalSize, flags);
4123 swizzle = _slang_var_swizzle(size, 0);
4124 store = _slang_new_ir_storage_swz(PROGRAM_VARYING, varyingLoc,
4125 totalSize, swizzle);
4126 }
4127 else {
4128 /* pre-defined varying, like gl_Color or gl_TexCoord */
4129 if (type == SLANG_UNIT_FRAGMENT_BUILTIN) {
4130 /* fragment program input */
4131 GLuint swizzle;
4132 GLint index = _slang_input_index(varName, GL_FRAGMENT_PROGRAM_ARB,
4133 &swizzle);
4134 assert(index >= 0);
4135 assert(index < FRAG_ATTRIB_MAX);
4136 store = _slang_new_ir_storage_swz(PROGRAM_INPUT, index,
4137 size, swizzle);
4138 }
4139 else {
4140 /* vertex program output */
4141 GLint index = _slang_output_index(varName, GL_VERTEX_PROGRAM_ARB);
4142 GLuint swizzle = _slang_var_swizzle(size, 0);
4143 assert(index >= 0);
4144 assert(index < VERT_RESULT_MAX);
4145 assert(type == SLANG_UNIT_VERTEX_BUILTIN);
4146 store = _slang_new_ir_storage_swz(PROGRAM_OUTPUT, index,
4147 size, swizzle);
4148 }
4149 if (dbg) printf("V/F ");
4150 }
4151 if (dbg) printf("VARYING ");
4152 }
4153 else if (var->type.qualifier == SLANG_QUAL_ATTRIBUTE) {
4154 GLuint swizzle;
4155 GLint index;
4156 /* attributes must be float, vec or mat */
4157 if (!_slang_type_is_float_vec_mat(var->type.specifier.type)) {
4158 slang_info_log_error(A->log,
4159 "attribute '%s' must be float/vector/matrix",
4160 varName);
4161 return GL_FALSE;
4162 }
4163
4164 if (prog) {
4165 /* user-defined vertex attribute */
4166 const GLint attr = -1; /* unknown */
4167 swizzle = _slang_var_swizzle(size, 0);
4168 index = _mesa_add_attribute(prog->Attributes, varName,
4169 size, datatype, attr);
4170 assert(index >= 0);
4171 index = VERT_ATTRIB_GENERIC0 + index;
4172 }
4173 else {
4174 /* pre-defined vertex attrib */
4175 index = _slang_input_index(varName, GL_VERTEX_PROGRAM_ARB, &swizzle);
4176 assert(index >= 0);
4177 }
4178 store = _slang_new_ir_storage_swz(PROGRAM_INPUT, index, size, swizzle);
4179 if (dbg) printf("ATTRIB ");
4180 }
4181 else if (var->type.qualifier == SLANG_QUAL_FIXEDINPUT) {
4182 GLuint swizzle = SWIZZLE_XYZW; /* silence compiler warning */
4183 GLint index = _slang_input_index(varName, GL_FRAGMENT_PROGRAM_ARB,
4184 &swizzle);
4185 store = _slang_new_ir_storage_swz(PROGRAM_INPUT, index, size, swizzle);
4186 if (dbg) printf("INPUT ");
4187 }
4188 else if (var->type.qualifier == SLANG_QUAL_FIXEDOUTPUT) {
4189 if (type == SLANG_UNIT_VERTEX_BUILTIN) {
4190 GLint index = _slang_output_index(varName, GL_VERTEX_PROGRAM_ARB);
4191 store = _slang_new_ir_storage(PROGRAM_OUTPUT, index, size);
4192 }
4193 else {
4194 GLint index = _slang_output_index(varName, GL_FRAGMENT_PROGRAM_ARB);
4195 GLint specialSize = 4; /* treat all fragment outputs as float[4] */
4196 assert(type == SLANG_UNIT_FRAGMENT_BUILTIN);
4197 store = _slang_new_ir_storage(PROGRAM_OUTPUT, index, specialSize);
4198 }
4199 if (dbg) printf("OUTPUT ");
4200 }
4201 else if (var->type.qualifier == SLANG_QUAL_CONST && !prog) {
4202 /* pre-defined global constant, like gl_MaxLights */
4203 store = _slang_new_ir_storage(PROGRAM_CONSTANT, -1, size);
4204 if (dbg) printf("CONST ");
4205 }
4206 else {
4207 /* ordinary variable (may be const) */
4208 slang_ir_node *n;
4209
4210 /* IR node to declare the variable */
4211 n = _slang_gen_var_decl(A, var, var->initializer);
4212
4213 /* emit GPU instructions */
4214 success = _slang_emit_code(n, A->vartable, A->program, GL_FALSE, A->log);
4215
4216 _slang_free_ir_tree(n);
4217 }
4218
4219 if (dbg) printf("GLOBAL VAR %s idx %d\n", (char*) var->a_name,
4220 store ? store->Index : -2);
4221
4222 if (store)
4223 var->store = store; /* save var's storage info */
4224
4225 var->declared = GL_TRUE;
4226
4227 return success;
4228 }
4229
4230
4231 /**
4232 * Produce an IR tree from a function AST (fun->body).
4233 * Then call the code emitter to convert the IR tree into gl_program
4234 * instructions.
4235 */
4236 GLboolean
4237 _slang_codegen_function(slang_assemble_ctx * A, slang_function * fun)
4238 {
4239 slang_ir_node *n;
4240 GLboolean success = GL_TRUE;
4241
4242 if (_mesa_strcmp((char *) fun->header.a_name, "main") != 0) {
4243 /* we only really generate code for main, all other functions get
4244 * inlined or codegen'd upon an actual call.
4245 */
4246 #if 0
4247 /* do some basic error checking though */
4248 if (fun->header.type.specifier.type != SLANG_SPEC_VOID) {
4249 /* check that non-void functions actually return something */
4250 slang_operation *op
4251 = _slang_find_node_type(fun->body, SLANG_OPER_RETURN);
4252 if (!op) {
4253 slang_info_log_error(A->log,
4254 "function \"%s\" has no return statement",
4255 (char *) fun->header.a_name);
4256 printf(
4257 "function \"%s\" has no return statement\n",
4258 (char *) fun->header.a_name);
4259 return GL_FALSE;
4260 }
4261 }
4262 #endif
4263 return GL_TRUE; /* not an error */
4264 }
4265
4266 #if 0
4267 printf("\n*********** codegen_function %s\n", (char *) fun->header.a_name);
4268 slang_print_function(fun, 1);
4269 #endif
4270
4271 /* should have been allocated earlier: */
4272 assert(A->program->Parameters );
4273 assert(A->program->Varying);
4274 assert(A->vartable);
4275 A->CurLoop = NULL;
4276 A->CurFunction = fun;
4277
4278 /* fold constant expressions, etc. */
4279 _slang_simplify(fun->body, &A->space, A->atoms);
4280
4281 #if 0
4282 printf("\n*********** simplified %s\n", (char *) fun->header.a_name);
4283 slang_print_function(fun, 1);
4284 #endif
4285
4286 /* Create an end-of-function label */
4287 A->curFuncEndLabel = _slang_label_new("__endOfFunc__main");
4288
4289 /* push new vartable scope */
4290 _slang_push_var_table(A->vartable);
4291
4292 /* Generate IR tree for the function body code */
4293 n = _slang_gen_operation(A, fun->body);
4294 if (n)
4295 n = new_node1(IR_SCOPE, n);
4296
4297 /* pop vartable, restore previous */
4298 _slang_pop_var_table(A->vartable);
4299
4300 if (!n) {
4301 /* XXX record error */
4302 return GL_FALSE;
4303 }
4304
4305 /* append an end-of-function-label to IR tree */
4306 n = new_seq(n, new_label(A->curFuncEndLabel));
4307
4308 /*_slang_label_delete(A->curFuncEndLabel);*/
4309 A->curFuncEndLabel = NULL;
4310
4311 #if 0
4312 printf("************* New AST for %s *****\n", (char*)fun->header.a_name);
4313 slang_print_function(fun, 1);
4314 #endif
4315 #if 0
4316 printf("************* IR for %s *******\n", (char*)fun->header.a_name);
4317 _slang_print_ir_tree(n, 0);
4318 #endif
4319 #if 0
4320 printf("************* End codegen function ************\n\n");
4321 #endif
4322
4323 /* Emit program instructions */
4324 success = _slang_emit_code(n, A->vartable, A->program, GL_TRUE, A->log);
4325 _slang_free_ir_tree(n);
4326
4327 /* free codegen context */
4328 /*
4329 _mesa_free(A->codegen);
4330 */
4331
4332 return success;
4333 }
4334