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